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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
blambeau/yargi | lib/yargi/digraph.rb | Yargi.Digraph.to_edges | def to_edges(*args)
selected = args.collect do |arg|
case arg
when Integer
[@edges[arg]]
when EdgeSet
arg
when Array
arg.collect{|v| to_edges(v)}.flatten.uniq
when Digraph::Edge
[arg]
else
pred = ... | ruby | def to_edges(*args)
selected = args.collect do |arg|
case arg
when Integer
[@edges[arg]]
when EdgeSet
arg
when Array
arg.collect{|v| to_edges(v)}.flatten.uniq
when Digraph::Edge
[arg]
else
pred = ... | [
"def",
"to_edges",
"(",
"*",
"args",
")",
"selected",
"=",
"args",
".",
"collect",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"Integer",
"[",
"@edges",
"[",
"arg",
"]",
"]",
"when",
"EdgeSet",
"arg",
"when",
"Array",
"arg",
".",
"collect",
"{",
... | Applies argument conventions about selection of edges | [
"Applies",
"argument",
"conventions",
"about",
"selection",
"of",
"edges"
] | 100141e96d245a0a8211cd4f7590909be149bc3c | https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L285-L302 | train |
blambeau/yargi | lib/yargi/digraph.rb | Yargi.Digraph.apply_arg_conventions | def apply_arg_conventions(element, args)
args.each do |arg|
case arg
when Module
element.tag(arg)
when Hash
element.add_marks(arg)
else
raise ArgumentError, "Unable to apply argument conventions on #{arg.inspect}", caller
end
... | ruby | def apply_arg_conventions(element, args)
args.each do |arg|
case arg
when Module
element.tag(arg)
when Hash
element.add_marks(arg)
else
raise ArgumentError, "Unable to apply argument conventions on #{arg.inspect}", caller
end
... | [
"def",
"apply_arg_conventions",
"(",
"element",
",",
"args",
")",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"Module",
"element",
".",
"tag",
"(",
"arg",
")",
"when",
"Hash",
"element",
".",
"add_marks",
"(",
"arg",
")",
"else",... | Applies argument conventions on _element_ | [
"Applies",
"argument",
"conventions",
"on",
"_element_"
] | 100141e96d245a0a8211cd4f7590909be149bc3c | https://github.com/blambeau/yargi/blob/100141e96d245a0a8211cd4f7590909be149bc3c/lib/yargi/digraph.rb#L305-L317 | train |
pjb3/curtain | lib/curtain/html_helpers.rb | Curtain.HTMLHelpers.content_tag | def content_tag(name, content=nil, attrs={}, &body)
if content.is_a?(Hash)
attrs = content
content = nil
end
if block_given?
content = capture(&body)
end
tag = tag_opening(name, attrs)
tag << ">".html_safe
tag << content
tag << "</#{name}>".html_... | ruby | def content_tag(name, content=nil, attrs={}, &body)
if content.is_a?(Hash)
attrs = content
content = nil
end
if block_given?
content = capture(&body)
end
tag = tag_opening(name, attrs)
tag << ">".html_safe
tag << content
tag << "</#{name}>".html_... | [
"def",
"content_tag",
"(",
"name",
",",
"content",
"=",
"nil",
",",
"attrs",
"=",
"{",
"}",
",",
"&",
"body",
")",
"if",
"content",
".",
"is_a?",
"(",
"Hash",
")",
"attrs",
"=",
"content",
"content",
"=",
"nil",
"end",
"if",
"block_given?",
"content"... | Generates a with opening and closing tags and potentially content.
@example Tag with no attributes, no content
content_tag(:p) # => "<p></p>"
@example Tag with content
content_tag(:p, "Hello") # => "<p>Hello</p>"
@example Tag with block content
content_tag(:p) { "Hello" } # => "<p>Hello</p>"
@example T... | [
"Generates",
"a",
"with",
"opening",
"and",
"closing",
"tags",
"and",
"potentially",
"content",
"."
] | ab4f3dccea9b887148689084137f1375278f2dcf | https://github.com/pjb3/curtain/blob/ab4f3dccea9b887148689084137f1375278f2dcf/lib/curtain/html_helpers.rb#L50-L64 | train |
barkerest/barkest_core | app/helpers/barkest_core/application_helper.rb | BarkestCore.ApplicationHelper.render_alert | def render_alert(type, message)
if type.to_s.index('safe_')
type = type.to_s[5..-1]
message = message.to_s.html_safe
end
type = type.to_sym
type = :info if type == :notice
type = :danger if type == :alert
return nil unless [:info, :success, :danger, :warning].inclu... | ruby | def render_alert(type, message)
if type.to_s.index('safe_')
type = type.to_s[5..-1]
message = message.to_s.html_safe
end
type = type.to_sym
type = :info if type == :notice
type = :danger if type == :alert
return nil unless [:info, :success, :danger, :warning].inclu... | [
"def",
"render_alert",
"(",
"type",
",",
"message",
")",
"if",
"type",
".",
"to_s",
".",
"index",
"(",
"'safe_'",
")",
"type",
"=",
"type",
".",
"to_s",
"[",
"5",
"..",
"-",
"1",
"]",
"message",
"=",
"message",
".",
"to_s",
".",
"html_safe",
"end",... | Renders an alert message.
* +type+ The type of message [info, success, warn, error, danger, etc]
* +message+ The message to display.
To provide messages including HTML, you need to prefix the type with 'safe_'.
render_alert(safe_info, '<strong>This</strong> is a message containing <code>HTML</code> content.')
... | [
"Renders",
"an",
"alert",
"message",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/application_helper.rb#L74-L88 | train |
Democracy-for-America/ActionKitApi | lib/action_kit_api/event_campaign.rb | ActionKitApi.EventCampaign.create_event | def create_event(*args)
raise "EventCampaign needs to be saved before Event creation" if self.id.nil?
(args[0]).merge!(:campaign_id => self.id)
event = ActionKitApi::Event.new(*args)
end | ruby | def create_event(*args)
raise "EventCampaign needs to be saved before Event creation" if self.id.nil?
(args[0]).merge!(:campaign_id => self.id)
event = ActionKitApi::Event.new(*args)
end | [
"def",
"create_event",
"(",
"*",
"args",
")",
"raise",
"\"EventCampaign needs to be saved before Event creation\"",
"if",
"self",
".",
"id",
".",
"nil?",
"(",
"args",
"[",
"0",
"]",
")",
".",
"merge!",
"(",
":campaign_id",
"=>",
"self",
".",
"id",
")",
"even... | Requires at a minimum the creator_id | [
"Requires",
"at",
"a",
"minimum",
"the",
"creator_id"
] | 81a9e1f84c5e3facbfec0203d453377da7034a26 | https://github.com/Democracy-for-America/ActionKitApi/blob/81a9e1f84c5e3facbfec0203d453377da7034a26/lib/action_kit_api/event_campaign.rb#L30-L36 | train |
Democracy-for-America/ActionKitApi | lib/action_kit_api/event_campaign.rb | ActionKitApi.EventCampaign.public_search | def public_search(*args)
(args[0]).merge!(:campaign_id => self.id)
results = ActionKitApi.connection.call("Event.public_search", *args)
results.map do |r|
Event.new(r)
end
results
end | ruby | def public_search(*args)
(args[0]).merge!(:campaign_id => self.id)
results = ActionKitApi.connection.call("Event.public_search", *args)
results.map do |r|
Event.new(r)
end
results
end | [
"def",
"public_search",
"(",
"*",
"args",
")",
"(",
"args",
"[",
"0",
"]",
")",
".",
"merge!",
"(",
":campaign_id",
"=>",
"self",
".",
"id",
")",
"results",
"=",
"ActionKitApi",
".",
"connection",
".",
"call",
"(",
"\"Event.public_search\"",
",",
"args",... | Will not return private events, events that are full, deleted, or in the past
and doesn't return extra fields | [
"Will",
"not",
"return",
"private",
"events",
"events",
"that",
"are",
"full",
"deleted",
"or",
"in",
"the",
"past",
"and",
"doesn",
"t",
"return",
"extra",
"fields"
] | 81a9e1f84c5e3facbfec0203d453377da7034a26 | https://github.com/Democracy-for-America/ActionKitApi/blob/81a9e1f84c5e3facbfec0203d453377da7034a26/lib/action_kit_api/event_campaign.rb#L45-L54 | train |
roberthoner/encrypted_store | lib/encrypted_store/crypto_hash.rb | EncryptedStore.CryptoHash.encrypt | def encrypt(dek, salt, iter_mag=10)
return nil if empty?
raise Errors::InvalidSaltSize, 'too long' if salt.bytes.length > 255
key, iv = _keyiv_gen(dek, salt, iter_mag)
encryptor = OpenSSL::Cipher::AES256.new(:CBC).encrypt
encryptor.key = key
encryptor.iv = iv
data_packet = _... | ruby | def encrypt(dek, salt, iter_mag=10)
return nil if empty?
raise Errors::InvalidSaltSize, 'too long' if salt.bytes.length > 255
key, iv = _keyiv_gen(dek, salt, iter_mag)
encryptor = OpenSSL::Cipher::AES256.new(:CBC).encrypt
encryptor.key = key
encryptor.iv = iv
data_packet = _... | [
"def",
"encrypt",
"(",
"dek",
",",
"salt",
",",
"iter_mag",
"=",
"10",
")",
"return",
"nil",
"if",
"empty?",
"raise",
"Errors",
"::",
"InvalidSaltSize",
",",
"'too long'",
"if",
"salt",
".",
"bytes",
".",
"length",
">",
"255",
"key",
",",
"iv",
"=",
... | Encrypts the hash using the data encryption key and salt.
Returns a blob:
| Byte 0 | Byte 1 | Byte 2 | Bytes 3...S | Bytes S+1...E | Bytes E+1..E+4 |
------------------------------------------------------------------------------------------------
| Version | Salt Length | Iteration Magnitude ... | [
"Encrypts",
"the",
"hash",
"using",
"the",
"data",
"encryption",
"key",
"and",
"salt",
"."
] | 89e78eb19e0cb710b08b71209e42eda085dcaa8a | https://github.com/roberthoner/encrypted_store/blob/89e78eb19e0cb710b08b71209e42eda085dcaa8a/lib/encrypted_store/crypto_hash.rb#L19-L31 | train |
barkerest/incline | lib/incline/user_manager.rb | Incline.UserManager.authenticate | def authenticate(email, password, client_ip)
return nil unless Incline::EmailValidator.valid?(email)
email = email.downcase
# If an engine is registered for the email domain, then use it.
engine = get_auth_engine(email)
if engine
return engine.authenticate(email, password, client_... | ruby | def authenticate(email, password, client_ip)
return nil unless Incline::EmailValidator.valid?(email)
email = email.downcase
# If an engine is registered for the email domain, then use it.
engine = get_auth_engine(email)
if engine
return engine.authenticate(email, password, client_... | [
"def",
"authenticate",
"(",
"email",
",",
"password",
",",
"client_ip",
")",
"return",
"nil",
"unless",
"Incline",
"::",
"EmailValidator",
".",
"valid?",
"(",
"email",
")",
"email",
"=",
"email",
".",
"downcase",
"# If an engine is registered for the email domain, t... | Creates a new user manager.
The user manager itself takes no options, however options will be passed to
any registered authentication engines when they are instantiated.
The options can be used to pre-register engines and provide configuration for them.
The engines will have specific configurations, but the UserM... | [
"Creates",
"a",
"new",
"user",
"manager",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/user_manager.rb#L81-L109 | train |
barkerest/incline | lib/incline/user_manager.rb | Incline.UserManager.begin_external_authentication | def begin_external_authentication(request)
# We don't have an email domain to work from.
# Instead, we'll call each engine's authenticate_external method.
# If one of them returns a user, then we return that value and skip further processing.
auth_engines.each do |dom,engine|
unless engi... | ruby | def begin_external_authentication(request)
# We don't have an email domain to work from.
# Instead, we'll call each engine's authenticate_external method.
# If one of them returns a user, then we return that value and skip further processing.
auth_engines.each do |dom,engine|
unless engi... | [
"def",
"begin_external_authentication",
"(",
"request",
")",
"# We don't have an email domain to work from.",
"# Instead, we'll call each engine's authenticate_external method.",
"# If one of them returns a user, then we return that value and skip further processing.",
"auth_engines",
".",
"each... | The begin_external_authentication method takes a request object to determine if it should process a login
or return nil. If it decides to process authentication, it should return a URL to redirect to. | [
"The",
"begin_external_authentication",
"method",
"takes",
"a",
"request",
"object",
"to",
"determine",
"if",
"it",
"should",
"process",
"a",
"login",
"or",
"return",
"nil",
".",
"If",
"it",
"decides",
"to",
"process",
"authentication",
"it",
"should",
"return",... | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/user_manager.rb#L114-L125 | train |
barkerest/incline | lib/incline/user_manager.rb | Incline.UserManager.register_auth_engine | def register_auth_engine(engine, *domains)
unless engine.nil?
unless engine.is_a?(::Incline::AuthEngineBase)
raise ArgumentError, "The 'engine' parameter must be an instance of an auth engine or a class defining an auth engine." unless engine.is_a?(::Class)
engine = engine.new(@options... | ruby | def register_auth_engine(engine, *domains)
unless engine.nil?
unless engine.is_a?(::Incline::AuthEngineBase)
raise ArgumentError, "The 'engine' parameter must be an instance of an auth engine or a class defining an auth engine." unless engine.is_a?(::Class)
engine = engine.new(@options... | [
"def",
"register_auth_engine",
"(",
"engine",
",",
"*",
"domains",
")",
"unless",
"engine",
".",
"nil?",
"unless",
"engine",
".",
"is_a?",
"(",
"::",
"Incline",
"::",
"AuthEngineBase",
")",
"raise",
"ArgumentError",
",",
"\"The 'engine' parameter must be an instance... | Registers an authentication engine for one or more domains.
The +engine+ passed in should take an options hash as the only argument to +initialize+
and should provide an +authenticate+ method that takes the +email+, +password+, and
+client_ip+. You can optionally define an +authenticate_external+ method that takes... | [
"Registers",
"an",
"authentication",
"engine",
"for",
"one",
"or",
"more",
"domains",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/user_manager.rb#L189-L204 | train |
jomalley2112/controller_scaffolding | lib/generators/controller_generator_base.rb | Generators.ControllerGeneratorBase.copy_view_files | def copy_view_files #do NOT change the name of this method
# it must be overriding an existing one in a parent class
base_path = File.join("app/views", class_path, file_name)
#binding.pry
empty_directory base_path
@actions = actions.nil? || actions.empty? ? %w(index new ... | ruby | def copy_view_files #do NOT change the name of this method
# it must be overriding an existing one in a parent class
base_path = File.join("app/views", class_path, file_name)
#binding.pry
empty_directory base_path
@actions = actions.nil? || actions.empty? ? %w(index new ... | [
"def",
"copy_view_files",
"#do NOT change the name of this method ",
"# it must be overriding an existing one in a parent class",
"base_path",
"=",
"File",
".",
"join",
"(",
"\"app/views\"",
",",
"class_path",
",",
"file_name",
")",
"#binding.pry",
"empty_directory",
"base_path",... | This method seems to always get run first | [
"This",
"method",
"seems",
"to",
"always",
"get",
"run",
"first"
] | 380d37962fa84d0911e86fe01a8bca158c0b6b10 | https://github.com/jomalley2112/controller_scaffolding/blob/380d37962fa84d0911e86fe01a8bca158c0b6b10/lib/generators/controller_generator_base.rb#L15-L33 | train |
hopsoft/footing | lib/footing/hash.rb | Footing.Hash.to_h | def to_h
copied_object.each_with_object({}) do |pair, memo|
value = pair.last
if value.is_a?(Footing::Hash)
memo[pair.first] = value.to_h
elsif value.is_a?(::Array)
memo[pair.first] = value.map do |val|
if val.is_a?(Footing::Hash)
val.to_h
... | ruby | def to_h
copied_object.each_with_object({}) do |pair, memo|
value = pair.last
if value.is_a?(Footing::Hash)
memo[pair.first] = value.to_h
elsif value.is_a?(::Array)
memo[pair.first] = value.map do |val|
if val.is_a?(Footing::Hash)
val.to_h
... | [
"def",
"to_h",
"copied_object",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"pair",
",",
"memo",
"|",
"value",
"=",
"pair",
".",
"last",
"if",
"value",
".",
"is_a?",
"(",
"Footing",
"::",
"Hash",
")",
"memo",
"[",
"pair",
".",
"first",
... | Returns a standard ruby Hash representation of the wrapped Hash.
@return [Hash] | [
"Returns",
"a",
"standard",
"ruby",
"Hash",
"representation",
"of",
"the",
"wrapped",
"Hash",
"."
] | fa37cbde4a75b774f65c3367245c41a8607fe67a | https://github.com/hopsoft/footing/blob/fa37cbde4a75b774f65c3367245c41a8607fe67a/lib/footing/hash.rb#L18-L35 | train |
eyecuelab/smarteru | lib/smarteru/client.rb | Smarteru.Client.request | def request(operation, data)
opts = {
method: :post,
url: api_url,
payload: { 'Package' => body(operation, data) },
content_type: :xml,
verify_ssl: verify_ssl,
ssl_ca_file: ssl_ca_file }
response = RestClient::Request.execute(opts)
... | ruby | def request(operation, data)
opts = {
method: :post,
url: api_url,
payload: { 'Package' => body(operation, data) },
content_type: :xml,
verify_ssl: verify_ssl,
ssl_ca_file: ssl_ca_file }
response = RestClient::Request.execute(opts)
... | [
"def",
"request",
"(",
"operation",
",",
"data",
")",
"opts",
"=",
"{",
"method",
":",
":post",
",",
"url",
":",
"api_url",
",",
"payload",
":",
"{",
"'Package'",
"=>",
"body",
"(",
"operation",
",",
"data",
")",
"}",
",",
"content_type",
":",
":xml"... | Create an instance of an API client
==== Attributes
* +options+ - Access credentials and options hash, required keys are: account_api_key, user_api_key
==== Example
client = Smarteru::Client.new({account_api_key: 'abc', user_api_key: 'abc'})
Make an API request
==== Attributes
* +operation+ - Operation method... | [
"Create",
"an",
"instance",
"of",
"an",
"API",
"client"
] | a5b1c92f2d938d29b032520dcfdb9eb7be5fa020 | https://github.com/eyecuelab/smarteru/blob/a5b1c92f2d938d29b032520dcfdb9eb7be5fa020/lib/smarteru/client.rb#L33-L49 | train |
eyecuelab/smarteru | lib/smarteru/client.rb | Smarteru.Client.body_parameters | def body_parameters(parameters)
parameters_xml = ''
parameters.each_pair do |k, v|
key = parameter_key(k)
val = case v
when Hash
body_parameters(v)
when Array
v.map { |i| body_parameters(i) }.join('')
when nil
''
else
"... | ruby | def body_parameters(parameters)
parameters_xml = ''
parameters.each_pair do |k, v|
key = parameter_key(k)
val = case v
when Hash
body_parameters(v)
when Array
v.map { |i| body_parameters(i) }.join('')
when nil
''
else
"... | [
"def",
"body_parameters",
"(",
"parameters",
")",
"parameters_xml",
"=",
"''",
"parameters",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"key",
"=",
"parameter_key",
"(",
"k",
")",
"val",
"=",
"case",
"v",
"when",
"Hash",
"body_parameters",
"(",
"v"... | Build body parameteres xml
==== Attributes
* +parameters+ - Parameters hash | [
"Build",
"body",
"parameteres",
"xml"
] | a5b1c92f2d938d29b032520dcfdb9eb7be5fa020 | https://github.com/eyecuelab/smarteru/blob/a5b1c92f2d938d29b032520dcfdb9eb7be5fa020/lib/smarteru/client.rb#L78-L98 | train |
eyecuelab/smarteru | lib/smarteru/client.rb | Smarteru.Client.parameter_key | def parameter_key(term)
string = term.to_s
string = string.sub(/^[a-z\d]*/) { $&.capitalize }
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" }
string
end | ruby | def parameter_key(term)
string = term.to_s
string = string.sub(/^[a-z\d]*/) { $&.capitalize }
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" }
string
end | [
"def",
"parameter_key",
"(",
"term",
")",
"string",
"=",
"term",
".",
"to_s",
"string",
"=",
"string",
".",
"sub",
"(",
"/",
"\\d",
"/",
")",
"{",
"$&",
".",
"capitalize",
"}",
"string",
".",
"gsub!",
"(",
"/",
"\\/",
"\\d",
"/i",
")",
"{",
"\"#{... | Prepare parameter key
==== Attributes
* +parameters+ - Parameters hash | [
"Prepare",
"parameter",
"key"
] | a5b1c92f2d938d29b032520dcfdb9eb7be5fa020 | https://github.com/eyecuelab/smarteru/blob/a5b1c92f2d938d29b032520dcfdb9eb7be5fa020/lib/smarteru/client.rb#L104-L109 | train |
jns/Aims | lib/aims/zinc_blende.rb | Aims.ZincBlende.get_bulk | def get_bulk
b = 0.25*self.lattice_const
a1 = Atom.new(0, 0, 0, self.cation)
a2 = Atom.new(b, b, b, self.anion)
v1 = Vector[0.5, 0.5, 0.0]*self.lattice_const
v2 = Vector[0.5, 0.0, 0.5]*self.lattice_const
v3 = Vector[0.0, 0.5, 0.5]*self.lattice_const
zb = Geometry.new([a1... | ruby | def get_bulk
b = 0.25*self.lattice_const
a1 = Atom.new(0, 0, 0, self.cation)
a2 = Atom.new(b, b, b, self.anion)
v1 = Vector[0.5, 0.5, 0.0]*self.lattice_const
v2 = Vector[0.5, 0.0, 0.5]*self.lattice_const
v3 = Vector[0.0, 0.5, 0.5]*self.lattice_const
zb = Geometry.new([a1... | [
"def",
"get_bulk",
"b",
"=",
"0.25",
"*",
"self",
".",
"lattice_const",
"a1",
"=",
"Atom",
".",
"new",
"(",
"0",
",",
"0",
",",
"0",
",",
"self",
".",
"cation",
")",
"a2",
"=",
"Atom",
".",
"new",
"(",
"b",
",",
"b",
",",
"b",
",",
"self",
... | Initialize the zinc-blende Geometry
cation and anion are the atomic
species occupying the two different sub-lattices.
lattice_const specifies the lattice constant
Return the traditional unit cell of bulk zinc blende | [
"Initialize",
"the",
"zinc",
"-",
"blende",
"Geometry",
"cation",
"and",
"anion",
"are",
"the",
"atomic",
"species",
"occupying",
"the",
"two",
"different",
"sub",
"-",
"lattices",
".",
"lattice_const",
"specifies",
"the",
"lattice",
"constant",
"Return",
"the",... | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/zinc_blende.rb#L29-L46 | train |
jns/Aims | lib/aims/zinc_blende.rb | Aims.ZincBlende.fill_volume | def fill_volume(volume)
# First fill a cube that bounds the volume
max = volume.max_point
min = volume.min_point
dx = max[0] - min[0]
dy = max[1] - min[1]
dz = max[2] - min[2]
bulk = get_bulk
# This inverse matrix gives the number of repetition... | ruby | def fill_volume(volume)
# First fill a cube that bounds the volume
max = volume.max_point
min = volume.min_point
dx = max[0] - min[0]
dy = max[1] - min[1]
dz = max[2] - min[2]
bulk = get_bulk
# This inverse matrix gives the number of repetition... | [
"def",
"fill_volume",
"(",
"volume",
")",
"# First fill a cube that bounds the volume",
"max",
"=",
"volume",
".",
"max_point",
"min",
"=",
"volume",
".",
"min_point",
"dx",
"=",
"max",
"[",
"0",
"]",
"-",
"min",
"[",
"0",
"]",
"dy",
"=",
"max",
"[",
"1"... | Fill the given volume with atoms | [
"Fill",
"the",
"given",
"volume",
"with",
"atoms"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/zinc_blende.rb#L49-L85 | train |
jns/Aims | lib/aims/zinc_blende.rb | Aims.ZincBlende.get_001_surface | def get_001_surface(monolayers, vacuum, constrain_layers = 0)
anion = Atom.new(0,0,0,self.cation)
cation = Atom.new(0.25*self.lattice_const, 0.25*self.lattice_const, 0.25*self.lattice_const, self.anion)
v1 = Vector[0.5, 0.5, 0]*self.lattice_const
v2 = Vector[-0.5,0.5,0]*self.lattice_const
... | ruby | def get_001_surface(monolayers, vacuum, constrain_layers = 0)
anion = Atom.new(0,0,0,self.cation)
cation = Atom.new(0.25*self.lattice_const, 0.25*self.lattice_const, 0.25*self.lattice_const, self.anion)
v1 = Vector[0.5, 0.5, 0]*self.lattice_const
v2 = Vector[-0.5,0.5,0]*self.lattice_const
... | [
"def",
"get_001_surface",
"(",
"monolayers",
",",
"vacuum",
",",
"constrain_layers",
"=",
"0",
")",
"anion",
"=",
"Atom",
".",
"new",
"(",
"0",
",",
"0",
",",
"0",
",",
"self",
".",
"cation",
")",
"cation",
"=",
"Atom",
".",
"new",
"(",
"0.25",
"*"... | Return a unit cell for a slab of 001
Specify the number of atomic monolayers,
the vacuum thickness in angstrom,
and the number of layers to constrain at the base of the slab | [
"Return",
"a",
"unit",
"cell",
"for",
"a",
"slab",
"of",
"001",
"Specify",
"the",
"number",
"of",
"atomic",
"monolayers",
"the",
"vacuum",
"thickness",
"in",
"angstrom",
"and",
"the",
"number",
"of",
"layers",
"to",
"constrain",
"at",
"the",
"base",
"of",
... | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/zinc_blende.rb#L91-L132 | train |
jns/Aims | lib/aims/zinc_blende.rb | Aims.ZincBlende.get_111_surface | def get_111_surface(dir, monolayers, vacuum, constrain_layers = 0)
if dir == "A"
top_atom = self.anion
bot_atom = self.cation
elsif dir == "B"
top_atom = self.cation
bot_atom = self.anion
else
raise "Direction must be either A or B"
end
# The... | ruby | def get_111_surface(dir, monolayers, vacuum, constrain_layers = 0)
if dir == "A"
top_atom = self.anion
bot_atom = self.cation
elsif dir == "B"
top_atom = self.cation
bot_atom = self.anion
else
raise "Direction must be either A or B"
end
# The... | [
"def",
"get_111_surface",
"(",
"dir",
",",
"monolayers",
",",
"vacuum",
",",
"constrain_layers",
"=",
"0",
")",
"if",
"dir",
"==",
"\"A\"",
"top_atom",
"=",
"self",
".",
"anion",
"bot_atom",
"=",
"self",
".",
"cation",
"elsif",
"dir",
"==",
"\"B\"",
"top... | Return a unit cell for a slab of 111
dir is either "A" or "B" for the cation or anion terminated slab
specify the number of atomic monolayers
and the vacuum thickness in angstrom | [
"Return",
"a",
"unit",
"cell",
"for",
"a",
"slab",
"of",
"111",
"dir",
"is",
"either",
"A",
"or",
"B",
"for",
"the",
"cation",
"or",
"anion",
"terminated",
"slab",
"specify",
"the",
"number",
"of",
"atomic",
"monolayers",
"and",
"the",
"vacuum",
"thickne... | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/zinc_blende.rb#L157-L218 | train |
jns/Aims | lib/aims/zinc_blende.rb | Aims.ZincBlende.get_112_surface | def get_112_surface(monolayers, vacuum=0, constrain_layers = 0)
atom1 = Atom.new(0,0,0,self.cation)
atom2 = Atom.new(self.lattice_const*sqrt(3)/2, 0, 0, self.anion)
v1 = Vector[sqrt(3), 0, 0]*self.lattice_const
v2 = Vector[0, sqrt(2)/2, 0]*self.lattice_const
v3 = Vector[1/sqrt(3), 1... | ruby | def get_112_surface(monolayers, vacuum=0, constrain_layers = 0)
atom1 = Atom.new(0,0,0,self.cation)
atom2 = Atom.new(self.lattice_const*sqrt(3)/2, 0, 0, self.anion)
v1 = Vector[sqrt(3), 0, 0]*self.lattice_const
v2 = Vector[0, sqrt(2)/2, 0]*self.lattice_const
v3 = Vector[1/sqrt(3), 1... | [
"def",
"get_112_surface",
"(",
"monolayers",
",",
"vacuum",
"=",
"0",
",",
"constrain_layers",
"=",
"0",
")",
"atom1",
"=",
"Atom",
".",
"new",
"(",
"0",
",",
"0",
",",
"0",
",",
"self",
".",
"cation",
")",
"atom2",
"=",
"Atom",
".",
"new",
"(",
... | return a unit cell for a slab of 112
specify the number of atomic monolayers and the vacuum thickness in angstrom | [
"return",
"a",
"unit",
"cell",
"for",
"a",
"slab",
"of",
"112",
"specify",
"the",
"number",
"of",
"atomic",
"monolayers",
"and",
"the",
"vacuum",
"thickness",
"in",
"angstrom"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/zinc_blende.rb#L222-L260 | train |
jns/Aims | lib/aims/zinc_blende.rb | Aims.ZincBlende.get_110_surface | def get_110_surface(monolayers, vacuum=0, constrain_layers = 0)
# The atoms on a FCC
atom1 = Atom.new(0,0,0,self.cation)
atom2 = Atom.new(self.lattice_const*1/(2*sqrt(2)), self.lattice_const*0.25, 0.0, self.anion)
# The lattice Vectors
v1 = Vector[1/sqrt(2), 0.0, 0.0]*self.lattice_const... | ruby | def get_110_surface(monolayers, vacuum=0, constrain_layers = 0)
# The atoms on a FCC
atom1 = Atom.new(0,0,0,self.cation)
atom2 = Atom.new(self.lattice_const*1/(2*sqrt(2)), self.lattice_const*0.25, 0.0, self.anion)
# The lattice Vectors
v1 = Vector[1/sqrt(2), 0.0, 0.0]*self.lattice_const... | [
"def",
"get_110_surface",
"(",
"monolayers",
",",
"vacuum",
"=",
"0",
",",
"constrain_layers",
"=",
"0",
")",
"# The atoms on a FCC ",
"atom1",
"=",
"Atom",
".",
"new",
"(",
"0",
",",
"0",
",",
"0",
",",
"self",
".",
"cation",
")",
"atom2",
"=",
"Atom"... | Return a unit cell for a slab of 110
specify the number of atomic monolayers
and the vacuum thickness in angstrom | [
"Return",
"a",
"unit",
"cell",
"for",
"a",
"slab",
"of",
"110",
"specify",
"the",
"number",
"of",
"atomic",
"monolayers",
"and",
"the",
"vacuum",
"thickness",
"in",
"angstrom"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/zinc_blende.rb#L266-L308 | train |
jinx/core | lib/jinx/helpers/collection.rb | Jinx.Collection.to_compact_hash_with_index | def to_compact_hash_with_index
hash = {}
self.each_with_index do |item, index|
next if item.nil?
value = yield(item, index)
next if value.nil_or_empty?
hash[item] = value
end
hash
end | ruby | def to_compact_hash_with_index
hash = {}
self.each_with_index do |item, index|
next if item.nil?
value = yield(item, index)
next if value.nil_or_empty?
hash[item] = value
end
hash
end | [
"def",
"to_compact_hash_with_index",
"hash",
"=",
"{",
"}",
"self",
".",
"each_with_index",
"do",
"|",
"item",
",",
"index",
"|",
"next",
"if",
"item",
".",
"nil?",
"value",
"=",
"yield",
"(",
"item",
",",
"index",
")",
"next",
"if",
"value",
".",
"nil... | Returns a new Hash generated from this Collection with a block whose arguments include the enumerated item
and its index. Every value which is nil or empty is excluded.
@example
[1, 2, 3].to_compact_hash_with_index { |item, index| item + index } #=> { 1 => 1, 2 => 3, 3 => 5 }
@yield [item, index] the hash value
... | [
"Returns",
"a",
"new",
"Hash",
"generated",
"from",
"this",
"Collection",
"with",
"a",
"block",
"whose",
"arguments",
"include",
"the",
"enumerated",
"item",
"and",
"its",
"index",
".",
"Every",
"value",
"which",
"is",
"nil",
"or",
"empty",
"is",
"excluded",... | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/collection.rb#L46-L55 | train |
jinx/core | lib/jinx/helpers/collection.rb | Jinx.Collection.partial_sort! | def partial_sort!
unless block_given? then return partial_sort! { |item1, item2| item1 <=> item2 } end
# The comparison hash
h = Hash.new { |h, k| h[k] = Hash.new }
sort! do |a, b|
# * If a and b are comparable, then use the comparison result.
# * Otherwise, if there is a member ... | ruby | def partial_sort!
unless block_given? then return partial_sort! { |item1, item2| item1 <=> item2 } end
# The comparison hash
h = Hash.new { |h, k| h[k] = Hash.new }
sort! do |a, b|
# * If a and b are comparable, then use the comparison result.
# * Otherwise, if there is a member ... | [
"def",
"partial_sort!",
"unless",
"block_given?",
"then",
"return",
"partial_sort!",
"{",
"|",
"item1",
",",
"item2",
"|",
"item1",
"<=>",
"item2",
"}",
"end",
"# The comparison hash",
"h",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",... | Sorts this collection in-place with a partial sort operator block
@see #partial_sort
@yield (see #partial_sort)
@yieldparam (see #partial_sort)
@raise [NoMethodError] if this Collection does not support the +sort!+ sort in-place method | [
"Sorts",
"this",
"collection",
"in",
"-",
"place",
"with",
"a",
"partial",
"sort",
"operator",
"block"
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/collection.rb#L252-L263 | train |
jinx/core | lib/jinx/resource/inversible.rb | Jinx.Inversible.set_inverse | def set_inverse(other, writer, inv_writer)
other.send(inv_writer, self) if other
send(writer, other)
end | ruby | def set_inverse(other, writer, inv_writer)
other.send(inv_writer, self) if other
send(writer, other)
end | [
"def",
"set_inverse",
"(",
"other",
",",
"writer",
",",
"inv_writer",
")",
"other",
".",
"send",
"(",
"inv_writer",
",",
"self",
")",
"if",
"other",
"send",
"(",
"writer",
",",
"other",
")",
"end"
] | Sets an attribute inverse by calling the attribute writer method with the other argument.
If other is non-nil, then the inverse writer method is called on self.
@param other [Resource] the attribute value to set
@param [Symbol] writer the attribute writer method
@param [Symbol] inv_writer the attribute inverse wri... | [
"Sets",
"an",
"attribute",
"inverse",
"by",
"calling",
"the",
"attribute",
"writer",
"method",
"with",
"the",
"other",
"argument",
".",
"If",
"other",
"is",
"non",
"-",
"nil",
"then",
"the",
"inverse",
"writer",
"method",
"is",
"called",
"on",
"self",
"."
... | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/inversible.rb#L12-L15 | train |
jinx/core | lib/jinx/resource/inversible.rb | Jinx.Inversible.set_inversible_noncollection_attribute | def set_inversible_noncollection_attribute(newval, accessors, inverse_writer)
rdr, wtr = accessors
# the previous value
oldval = send(rdr)
# bail if no change
return newval if newval.equal?(oldval)
# clear the previous inverse
logger.debug { "Moving #{qp} from #{oldval.qp} to ... | ruby | def set_inversible_noncollection_attribute(newval, accessors, inverse_writer)
rdr, wtr = accessors
# the previous value
oldval = send(rdr)
# bail if no change
return newval if newval.equal?(oldval)
# clear the previous inverse
logger.debug { "Moving #{qp} from #{oldval.qp} to ... | [
"def",
"set_inversible_noncollection_attribute",
"(",
"newval",
",",
"accessors",
",",
"inverse_writer",
")",
"rdr",
",",
"wtr",
"=",
"accessors",
"# the previous value",
"oldval",
"=",
"send",
"(",
"rdr",
")",
"# bail if no change",
"return",
"newval",
"if",
"newva... | Sets a non-collection attribute value in a way which enforces inverse integrity.
@param [Object] newval the value to set
@param [(Symbol, Symbol)] accessors the reader and writer methods to use in setting the
attribute
@param [Symbol] inverse_writer the inverse attribute writer method
@private | [
"Sets",
"a",
"non",
"-",
"collection",
"attribute",
"value",
"in",
"a",
"way",
"which",
"enforces",
"inverse",
"integrity",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/inversible.rb#L24-L48 | train |
jinx/core | lib/jinx/resource/inversible.rb | Jinx.Inversible.add_to_inverse_collection | def add_to_inverse_collection(newval, accessors, inverse)
rdr, wtr = accessors
# the current inverse
oldval = send(rdr)
# no-op if no change
return newval if newval == oldval
# delete self from the current inverse reference collection
if oldval then
coll = oldval.send(... | ruby | def add_to_inverse_collection(newval, accessors, inverse)
rdr, wtr = accessors
# the current inverse
oldval = send(rdr)
# no-op if no change
return newval if newval == oldval
# delete self from the current inverse reference collection
if oldval then
coll = oldval.send(... | [
"def",
"add_to_inverse_collection",
"(",
"newval",
",",
"accessors",
",",
"inverse",
")",
"rdr",
",",
"wtr",
"=",
"accessors",
"# the current inverse",
"oldval",
"=",
"send",
"(",
"rdr",
")",
"# no-op if no change",
"return",
"newval",
"if",
"newval",
"==",
"old... | Sets a collection attribute value in a way which enforces inverse integrity.
The inverse of the attribute is a collection accessed by calling inverse on newval.
@param [Resource] newval the new attribute reference value
@param [(Symbol, Symbol)] accessors the reader and writer to use in setting
the attribute
@p... | [
"Sets",
"a",
"collection",
"attribute",
"value",
"in",
"a",
"way",
"which",
"enforces",
"inverse",
"integrity",
".",
"The",
"inverse",
"of",
"the",
"attribute",
"is",
"a",
"collection",
"accessed",
"by",
"calling",
"inverse",
"on",
"newval",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/inversible.rb#L60-L92 | train |
riddopic/garcun | lib/garcon/core_ext/pathname.rb | Garcon.Pathref.expand_pathseg | def expand_pathseg(handle)
return handle unless handle.is_a?(Symbol)
pathsegs = ROOT_PATHS[handle] or raise ArgumentError,
"Don't know how to expand path reference '#{handle.inspect}'."
pathsegs.map { |ps| expand_pathseg(ps) }.flatten
end | ruby | def expand_pathseg(handle)
return handle unless handle.is_a?(Symbol)
pathsegs = ROOT_PATHS[handle] or raise ArgumentError,
"Don't know how to expand path reference '#{handle.inspect}'."
pathsegs.map { |ps| expand_pathseg(ps) }.flatten
end | [
"def",
"expand_pathseg",
"(",
"handle",
")",
"return",
"handle",
"unless",
"handle",
".",
"is_a?",
"(",
"Symbol",
")",
"pathsegs",
"=",
"ROOT_PATHS",
"[",
"handle",
"]",
"or",
"raise",
"ArgumentError",
",",
"\"Don't know how to expand path reference '#{handle.inspect}... | A T T E N Z I O N E A R E A P R O T E T T A
Recursively expand a path handle.
@return [Array<String>]
An array of path segments, suitable for .join
@api public | [
"A",
"T",
"T",
"E",
"N",
"Z",
"I",
"O",
"N",
"E",
"A",
"R",
"E",
"A",
"P",
"R",
"O",
"T",
"E",
"T",
"T",
"A",
"Recursively",
"expand",
"a",
"path",
"handle",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/core_ext/pathname.rb#L112-L117 | train |
riddopic/garcun | lib/garcon/task/count_down_latch.rb | Garcon.MutexCountDownLatch.wait | def wait(timeout = nil)
@mutex.synchronize do
remaining = Condition::Result.new(timeout)
while @count > 0 && remaining.can_wait?
remaining = @condition.wait(@mutex, remaining.remaining_time)
end
@count == 0
end
end | ruby | def wait(timeout = nil)
@mutex.synchronize do
remaining = Condition::Result.new(timeout)
while @count > 0 && remaining.can_wait?
remaining = @condition.wait(@mutex, remaining.remaining_time)
end
@count == 0
end
end | [
"def",
"wait",
"(",
"timeout",
"=",
"nil",
")",
"@mutex",
".",
"synchronize",
"do",
"remaining",
"=",
"Condition",
"::",
"Result",
".",
"new",
"(",
"timeout",
")",
"while",
"@count",
">",
"0",
"&&",
"remaining",
".",
"can_wait?",
"remaining",
"=",
"@cond... | Create a new `CountDownLatch` with the initial `count`.
@param [Fixnum] count
The initial count
@raise [ArgumentError]
If `count` is not an integer or is less than zero.
Block on the latch until the counter reaches zero or until `timeout` is
reached.
@param [Fixnum] timeout
The number of seconds to wa... | [
"Create",
"a",
"new",
"CountDownLatch",
"with",
"the",
"initial",
"count",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/count_down_latch.rb#L61-L69 | train |
karthikv/model_schema | lib/model_schema/schema_error.rb | ModelSchema.SchemaError.dump_extra_diffs | def dump_extra_diffs(field)
extra_diffs = diffs_by_field_type(field, TYPE_EXTRA)
if extra_diffs.length > 0
header = "Table #{@table_name} has extra #{field}:\n"
diff_str = extra_diffs.map do |diff|
dump_single(field, diff[:generator], diff[:elem])
end.join("\n\t")
... | ruby | def dump_extra_diffs(field)
extra_diffs = diffs_by_field_type(field, TYPE_EXTRA)
if extra_diffs.length > 0
header = "Table #{@table_name} has extra #{field}:\n"
diff_str = extra_diffs.map do |diff|
dump_single(field, diff[:generator], diff[:elem])
end.join("\n\t")
... | [
"def",
"dump_extra_diffs",
"(",
"field",
")",
"extra_diffs",
"=",
"diffs_by_field_type",
"(",
"field",
",",
"TYPE_EXTRA",
")",
"if",
"extra_diffs",
".",
"length",
">",
"0",
"header",
"=",
"\"Table #{@table_name} has extra #{field}:\\n\"",
"diff_str",
"=",
"extra_diffs... | Dumps all diffs that have the given field and are of TYPE_EXTRA. | [
"Dumps",
"all",
"diffs",
"that",
"have",
"the",
"given",
"field",
"and",
"are",
"of",
"TYPE_EXTRA",
"."
] | d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979 | https://github.com/karthikv/model_schema/blob/d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979/lib/model_schema/schema_error.rb#L54-L65 | train |
karthikv/model_schema | lib/model_schema/schema_error.rb | ModelSchema.SchemaError.dump_missing_diffs | def dump_missing_diffs(field)
missing_diffs = diffs_by_field_type(field, TYPE_MISSING)
if missing_diffs.length > 0
header = "Table #{@table_name} is missing #{field}:\n"
diff_str = missing_diffs.map do |diff|
dump_single(field, diff[:generator], diff[:elem])
end.join("\n\t... | ruby | def dump_missing_diffs(field)
missing_diffs = diffs_by_field_type(field, TYPE_MISSING)
if missing_diffs.length > 0
header = "Table #{@table_name} is missing #{field}:\n"
diff_str = missing_diffs.map do |diff|
dump_single(field, diff[:generator], diff[:elem])
end.join("\n\t... | [
"def",
"dump_missing_diffs",
"(",
"field",
")",
"missing_diffs",
"=",
"diffs_by_field_type",
"(",
"field",
",",
"TYPE_MISSING",
")",
"if",
"missing_diffs",
".",
"length",
">",
"0",
"header",
"=",
"\"Table #{@table_name} is missing #{field}:\\n\"",
"diff_str",
"=",
"mi... | Dumps all diffs that have the given field and are of TYPE_MISSING. | [
"Dumps",
"all",
"diffs",
"that",
"have",
"the",
"given",
"field",
"and",
"are",
"of",
"TYPE_MISSING",
"."
] | d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979 | https://github.com/karthikv/model_schema/blob/d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979/lib/model_schema/schema_error.rb#L68-L79 | train |
karthikv/model_schema | lib/model_schema/schema_error.rb | ModelSchema.SchemaError.dump_mismatch_diffs | def dump_mismatch_diffs(field)
mismatch_diffs = diffs_by_field_type(field, TYPE_MISMATCH)
if mismatch_diffs.length > 0
header = "Table #{@table_name} has mismatched #{field}:\n"
diff_str = mismatch_diffs.map do |diff|
"actual: #{dump_single(field, diff[:db_generator], diff[:db_... | ruby | def dump_mismatch_diffs(field)
mismatch_diffs = diffs_by_field_type(field, TYPE_MISMATCH)
if mismatch_diffs.length > 0
header = "Table #{@table_name} has mismatched #{field}:\n"
diff_str = mismatch_diffs.map do |diff|
"actual: #{dump_single(field, diff[:db_generator], diff[:db_... | [
"def",
"dump_mismatch_diffs",
"(",
"field",
")",
"mismatch_diffs",
"=",
"diffs_by_field_type",
"(",
"field",
",",
"TYPE_MISMATCH",
")",
"if",
"mismatch_diffs",
".",
"length",
">",
"0",
"header",
"=",
"\"Table #{@table_name} has mismatched #{field}:\\n\"",
"diff_str",
"=... | Dumps all diffs that have the given field and are of TYPE_MISMATCH. | [
"Dumps",
"all",
"diffs",
"that",
"have",
"the",
"given",
"field",
"and",
"are",
"of",
"TYPE_MISMATCH",
"."
] | d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979 | https://github.com/karthikv/model_schema/blob/d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979/lib/model_schema/schema_error.rb#L82-L94 | train |
karthikv/model_schema | lib/model_schema/schema_error.rb | ModelSchema.SchemaError.to_s | def to_s
parts = FIELDS.flat_map do |field|
[dump_extra_diffs(field),
dump_missing_diffs(field),
dump_mismatch_diffs(field)]
end
[
"Table #{@table_name} does not match the expected schema.\n\n",
parts.compact.join("\n"),
"\nYou may disable schema chec... | ruby | def to_s
parts = FIELDS.flat_map do |field|
[dump_extra_diffs(field),
dump_missing_diffs(field),
dump_mismatch_diffs(field)]
end
[
"Table #{@table_name} does not match the expected schema.\n\n",
parts.compact.join("\n"),
"\nYou may disable schema chec... | [
"def",
"to_s",
"parts",
"=",
"FIELDS",
".",
"flat_map",
"do",
"|",
"field",
"|",
"[",
"dump_extra_diffs",
"(",
"field",
")",
",",
"dump_missing_diffs",
"(",
"field",
")",
",",
"dump_mismatch_diffs",
"(",
"field",
")",
"]",
"end",
"[",
"\"Table #{@table_name}... | Combines all dumps into one cohesive error message. | [
"Combines",
"all",
"dumps",
"into",
"one",
"cohesive",
"error",
"message",
"."
] | d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979 | https://github.com/karthikv/model_schema/blob/d73f7d9f8b5240ad878a01d1fe7a0e01f66cf979/lib/model_schema/schema_error.rb#L97-L110 | train |
jinx/core | lib/jinx/helpers/visitor.rb | Jinx.Visitor.filter | def filter
raise ArgumentError.new("A filter block is not given to the visitor filter method") unless block_given?
self.class.new(@options) { |node| yield(node, node_children(node)) }
end | ruby | def filter
raise ArgumentError.new("A filter block is not given to the visitor filter method") unless block_given?
self.class.new(@options) { |node| yield(node, node_children(node)) }
end | [
"def",
"filter",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"A filter block is not given to the visitor filter method\"",
")",
"unless",
"block_given?",
"self",
".",
"class",
".",
"new",
"(",
"@options",
")",
"{",
"|",
"node",
"|",
"yield",
"(",
"node",
",",
"... | Returns a new Visitor which determines which nodes to visit by applying the given block
to this visitor. The filter block arguments consist of a parent node and an array of
children nodes for the parent. The block can return nil, a single node to visit or a
collection of nodes to visit.
@example
visitor = Jinx:... | [
"Returns",
"a",
"new",
"Visitor",
"which",
"determines",
"which",
"nodes",
"to",
"visit",
"by",
"applying",
"the",
"given",
"block",
"to",
"this",
"visitor",
".",
"The",
"filter",
"block",
"arguments",
"consist",
"of",
"a",
"parent",
"node",
"and",
"an",
"... | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/visitor.rb#L186-L189 | train |
jinx/core | lib/jinx/helpers/visitor.rb | Jinx.Visitor.node_children | def node_children(node)
children = @navigator.call(node)
return Array::EMPTY_ARRAY if children.nil?
Enumerable === children ? children.to_a.compact : [children]
end | ruby | def node_children(node)
children = @navigator.call(node)
return Array::EMPTY_ARRAY if children.nil?
Enumerable === children ? children.to_a.compact : [children]
end | [
"def",
"node_children",
"(",
"node",
")",
"children",
"=",
"@navigator",
".",
"call",
"(",
"node",
")",
"return",
"Array",
"::",
"EMPTY_ARRAY",
"if",
"children",
".",
"nil?",
"Enumerable",
"===",
"children",
"?",
"children",
".",
"to_a",
".",
"compact",
":... | Returns the children to visit for the given node. | [
"Returns",
"the",
"children",
"to",
"visit",
"for",
"the",
"given",
"node",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/visitor.rb#L202-L206 | train |
jinx/core | lib/jinx/helpers/visitor.rb | Jinx.Visitor.visit_root | def visit_root(node, &operator)
clear
# Exclude cycles if the prune cycles flag is set.
@exclude.merge!(cyclic_nodes(node)) if @prune_cycle_flag
# Visit the root node.
result = visit_recursive(node, &operator)
# Reset the exclusions if the prune cycles flag is set.
@exclude.c... | ruby | def visit_root(node, &operator)
clear
# Exclude cycles if the prune cycles flag is set.
@exclude.merge!(cyclic_nodes(node)) if @prune_cycle_flag
# Visit the root node.
result = visit_recursive(node, &operator)
# Reset the exclusions if the prune cycles flag is set.
@exclude.c... | [
"def",
"visit_root",
"(",
"node",
",",
"&",
"operator",
")",
"clear",
"# Exclude cycles if the prune cycles flag is set. ",
"@exclude",
".",
"merge!",
"(",
"cyclic_nodes",
"(",
"node",
")",
")",
"if",
"@prune_cycle_flag",
"# Visit the root node.",
"result",
"=",
"visi... | Visits the root node and all descendants. | [
"Visits",
"the",
"root",
"node",
"and",
"all",
"descendants",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/visitor.rb#L216-L225 | train |
jinx/core | lib/jinx/helpers/visitor.rb | Jinx.Visitor.cyclic_nodes | def cyclic_nodes(root)
copts = @options.reject { |k, v| k == :prune_cycle }
cyclic = Set.new
cycler = Visitor.new(copts) do |parent|
children = @navigator.call(parent)
# Look for a cycle back to the child.
children.each do |child|
index = cycler.lineage.index(child)
... | ruby | def cyclic_nodes(root)
copts = @options.reject { |k, v| k == :prune_cycle }
cyclic = Set.new
cycler = Visitor.new(copts) do |parent|
children = @navigator.call(parent)
# Look for a cycle back to the child.
children.each do |child|
index = cycler.lineage.index(child)
... | [
"def",
"cyclic_nodes",
"(",
"root",
")",
"copts",
"=",
"@options",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
":prune_cycle",
"}",
"cyclic",
"=",
"Set",
".",
"new",
"cycler",
"=",
"Visitor",
".",
"new",
"(",
"copts",
")",
"do",
"|",
... | Returns the nodes which occur within a cycle, excluding the cycle entry point.
@example
graph.paths #=> a -> b -> a, a -> c -> d -> c
Visitor.new(graph, &navigator).cyclic_nodes(a) #=> [b, d]
@param root the node to visit
@return [Array] the nodes within visit cycles | [
"Returns",
"the",
"nodes",
"which",
"occur",
"within",
"a",
"cycle",
"excluding",
"the",
"cycle",
"entry",
"point",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/visitor.rb#L234-L252 | train |
rubyworks/richunits | work/deprecated/duration.rb | RichUnits.Numeric.duration | def duration(part = nil, klass = Duration)
if [:years, :months, :weeks, :days, :hours, :minutes, :seconds].include? part
klass.new(part => self)
else
klass.new(self)
end
end | ruby | def duration(part = nil, klass = Duration)
if [:years, :months, :weeks, :days, :hours, :minutes, :seconds].include? part
klass.new(part => self)
else
klass.new(self)
end
end | [
"def",
"duration",
"(",
"part",
"=",
"nil",
",",
"klass",
"=",
"Duration",
")",
"if",
"[",
":years",
",",
":months",
",",
":weeks",
",",
":days",
",",
":hours",
",",
":minutes",
",",
":seconds",
"]",
".",
"include?",
"part",
"klass",
".",
"new",
"(",... | Create a Duration object using self where self could represent weeks, days,
hours, minutes, and seconds.
*Example*
10.duration(:weeks)
=> #<Duration: 10 weeks>
10.duration
=> #<Duration: 10 seconds> | [
"Create",
"a",
"Duration",
"object",
"using",
"self",
"where",
"self",
"could",
"represent",
"weeks",
"days",
"hours",
"minutes",
"and",
"seconds",
"."
] | c92bec173fc63798013defdd9a1727b0d1d65d46 | https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/work/deprecated/duration.rb#L466-L472 | train |
rubyworks/richunits | work/deprecated/duration.rb | RichUnits.Duration.seconds | def seconds(part = nil)
# Table mapping
h = {:weeks => WEEK, :days => DAY, :hours => HOUR, :minutes => MINUTE}
if [:weeks, :days, :hours, :minutes].include? part
__send__(part) * h[part]
else
@seconds
end
end | ruby | def seconds(part = nil)
# Table mapping
h = {:weeks => WEEK, :days => DAY, :hours => HOUR, :minutes => MINUTE}
if [:weeks, :days, :hours, :minutes].include? part
__send__(part) * h[part]
else
@seconds
end
end | [
"def",
"seconds",
"(",
"part",
"=",
"nil",
")",
"# Table mapping",
"h",
"=",
"{",
":weeks",
"=>",
"WEEK",
",",
":days",
"=>",
"DAY",
",",
":hours",
"=>",
"HOUR",
",",
":minutes",
"=>",
"MINUTE",
"}",
"if",
"[",
":weeks",
",",
":days",
",",
":hours",
... | Get the number of seconds of a given part, or simply just get the number of
seconds.
*Example*
d = Duration.new(:weeks => 1, :days => 1, :hours => 1, :seconds => 30)
=> #<Duration: 1 week, 1 day, 1 hour and 30 seconds>
d.seconds(:weeks)
=> 604800
d.seconds(:days)
=> 86400
d.second... | [
"Get",
"the",
"number",
"of",
"seconds",
"of",
"a",
"given",
"part",
"or",
"simply",
"just",
"get",
"the",
"number",
"of",
"seconds",
"."
] | c92bec173fc63798013defdd9a1727b0d1d65d46 | https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/work/deprecated/duration.rb#L134-L143 | train |
rubyworks/richunits | work/deprecated/duration.rb | RichUnits.Duration.to_s | def to_s
str = ''
each do |part, time|
# Skip any zero times.
next if time.zero?
# Concatenate the part of the time and the time itself.
str << "#{time} #{time == 1 ? part[0..-2] : part}, "
end
str.chomp(', ').sub(/(.+), ... | ruby | def to_s
str = ''
each do |part, time|
# Skip any zero times.
next if time.zero?
# Concatenate the part of the time and the time itself.
str << "#{time} #{time == 1 ? part[0..-2] : part}, "
end
str.chomp(', ').sub(/(.+), ... | [
"def",
"to_s",
"str",
"=",
"''",
"each",
"do",
"|",
"part",
",",
"time",
"|",
"# Skip any zero times.",
"next",
"if",
"time",
".",
"zero?",
"# Concatenate the part of the time and the time itself.",
"str",
"<<",
"\"#{time} #{time == 1 ? part[0..-2] : part}, \"",
"end",
... | Friendly, human-readable string representation of the duration.
*Example*
d = Duration.new(:seconds => 140)
=> #<Duration: 2 minutes and 20 seconds>
d.to_s
=> "2 minutes and 20 seconds" | [
"Friendly",
"human",
"-",
"readable",
"string",
"representation",
"of",
"the",
"duration",
"."
] | c92bec173fc63798013defdd9a1727b0d1d65d46 | https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/work/deprecated/duration.rb#L258-L270 | train |
syborg/mme_tools | lib/mme_tools/config.rb | MMETools.Config.dump | def dump(filename)
File.open(filename,'w') do |f|
YAML.dump(self.to_hash,f)
end
end | ruby | def dump(filename)
File.open(filename,'w') do |f|
YAML.dump(self.to_hash,f)
end
end | [
"def",
"dump",
"(",
"filename",
")",
"File",
".",
"open",
"(",
"filename",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"YAML",
".",
"dump",
"(",
"self",
".",
"to_hash",
",",
"f",
")",
"end",
"end"
] | saves configuration into a _yaml_ file named +filename+ | [
"saves",
"configuration",
"into",
"a",
"_yaml_",
"file",
"named",
"+",
"filename",
"+"
] | e93919f7fcfb408b941d6144290991a7feabaa7d | https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/config.rb#L101-L105 | train |
OHSU-FM/reindeer-etl | lib/reindeer-etl/sources/multi_source.rb | ReindeerETL::Sources.MultiSource.each | def each
rows = []
all_keys = Set.new
@sources.each_with_index do |source, source_idx|
first_row = false
source.each do |row|
unless row.keys.include? @key
raise ReindeerETL::Errors::RecordInvalid.new("Path#1 missing key: #{@key}")
end
if sour... | ruby | def each
rows = []
all_keys = Set.new
@sources.each_with_index do |source, source_idx|
first_row = false
source.each do |row|
unless row.keys.include? @key
raise ReindeerETL::Errors::RecordInvalid.new("Path#1 missing key: #{@key}")
end
if sour... | [
"def",
"each",
"rows",
"=",
"[",
"]",
"all_keys",
"=",
"Set",
".",
"new",
"@sources",
".",
"each_with_index",
"do",
"|",
"source",
",",
"source_idx",
"|",
"first_row",
"=",
"false",
"source",
".",
"each",
"do",
"|",
"row",
"|",
"unless",
"row",
".",
... | helper methods have h_ prefix
@param key [String] col name (present in all sources) to join on
@param paths [Array[String]] list of file paths. note: order is important
@param klass [String] namespaced class name of ReindeerETL source
@param path_opts [Array[Hash]] list of hashes (count equal to the
number of so... | [
"helper",
"methods",
"have",
"h_",
"prefix"
] | bff48c999b17850681346d500f2a05900252e21f | https://github.com/OHSU-FM/reindeer-etl/blob/bff48c999b17850681346d500f2a05900252e21f/lib/reindeer-etl/sources/multi_source.rb#L36-L81 | train |
akerl/logcabin | lib/logcabin/setcollection.rb | LogCabin.SetCollection.find | def find(name)
cache(name) { @children.find { |x| safe_find(x, name) } || failure }
end | ruby | def find(name)
cache(name) { @children.find { |x| safe_find(x, name) } || failure }
end | [
"def",
"find",
"(",
"name",
")",
"cache",
"(",
"name",
")",
"{",
"@children",
".",
"find",
"{",
"|",
"x",
"|",
"safe_find",
"(",
"x",
",",
"name",
")",
"}",
"||",
"failure",
"}",
"end"
] | Method for finding modules to load | [
"Method",
"for",
"finding",
"modules",
"to",
"load"
] | a0c793f4047f3a80fd232c582ecce55139092b8e | https://github.com/akerl/logcabin/blob/a0c793f4047f3a80fd232c582ecce55139092b8e/lib/logcabin/setcollection.rb#L13-L15 | train |
knuedge/off_the_grid | lib/off_the_grid/user.rb | OffTheGrid.User.add | def add
Tempfile.open do |tmpfile|
tmpfile.puts render(Templates::User::ERB)
tmpfile.flush
system("qconf -Auser #{tmpfile.path}")
sleep 5
end
end | ruby | def add
Tempfile.open do |tmpfile|
tmpfile.puts render(Templates::User::ERB)
tmpfile.flush
system("qconf -Auser #{tmpfile.path}")
sleep 5
end
end | [
"def",
"add",
"Tempfile",
".",
"open",
"do",
"|",
"tmpfile",
"|",
"tmpfile",
".",
"puts",
"render",
"(",
"Templates",
"::",
"User",
"::",
"ERB",
")",
"tmpfile",
".",
"flush",
"system",
"(",
"\"qconf -Auser #{tmpfile.path}\"",
")",
"sleep",
"5",
"end",
"end... | Add an SGE user | [
"Add",
"an",
"SGE",
"user"
] | cf367b6d22de5c73da2e2550e1f45e103a219a51 | https://github.com/knuedge/off_the_grid/blob/cf367b6d22de5c73da2e2550e1f45e103a219a51/lib/off_the_grid/user.rb#L49-L56 | train |
JotaSe/undecided | lib/undecided/decider.rb | Undecided.Decider.decide | def decide(rule, values, strict = true)
rule = rule.clone
values = values.clone
error unless Undecided::Evaluator.valid?(rule, values, strict)
# Sanitize data
# Eval rules and values after process it, with safe data
final_expression = Converter.replacing_variables(rule, values)
... | ruby | def decide(rule, values, strict = true)
rule = rule.clone
values = values.clone
error unless Undecided::Evaluator.valid?(rule, values, strict)
# Sanitize data
# Eval rules and values after process it, with safe data
final_expression = Converter.replacing_variables(rule, values)
... | [
"def",
"decide",
"(",
"rule",
",",
"values",
",",
"strict",
"=",
"true",
")",
"rule",
"=",
"rule",
".",
"clone",
"values",
"=",
"values",
".",
"clone",
"error",
"unless",
"Undecided",
"::",
"Evaluator",
".",
"valid?",
"(",
"rule",
",",
"values",
",",
... | Given a boolean expression and data to replace, return result | [
"Given",
"a",
"boolean",
"expression",
"and",
"data",
"to",
"replace",
"return",
"result"
] | 80255277d0aadb74e98835af01a3427e11c73649 | https://github.com/JotaSe/undecided/blob/80255277d0aadb74e98835af01a3427e11c73649/lib/undecided/decider.rb#L7-L18 | train |
xmatters/sensu-plugins-xmatters | lib/xmatters-sensu.rb | XMSensu.XMClient.get_default_properties | def get_default_properties(event)
client = event['client']
check = event['check']
{
server_name: client['name'],
server_ip: client['address'],
subscriptions: client['subscriptions'].join(';'),
environment: client['environment'],
check_name: check['name'],
... | ruby | def get_default_properties(event)
client = event['client']
check = event['check']
{
server_name: client['name'],
server_ip: client['address'],
subscriptions: client['subscriptions'].join(';'),
environment: client['environment'],
check_name: check['name'],
... | [
"def",
"get_default_properties",
"(",
"event",
")",
"client",
"=",
"event",
"[",
"'client'",
"]",
"check",
"=",
"event",
"[",
"'check'",
"]",
"{",
"server_name",
":",
"client",
"[",
"'name'",
"]",
",",
"server_ip",
":",
"client",
"[",
"'address'",
"]",
"... | Gets a default set of properties from the event | [
"Gets",
"a",
"default",
"set",
"of",
"properties",
"from",
"the",
"event"
] | eb21b1aa6c9c5b31142dd596b01ebeade4f6638f | https://github.com/xmatters/sensu-plugins-xmatters/blob/eb21b1aa6c9c5b31142dd596b01ebeade4f6638f/lib/xmatters-sensu.rb#L46-L59 | train |
riddopic/garcun | lib/garcon/chef/secret_bag.rb | Garcon.SecretBag.data_bag_config_for | def data_bag_config_for(environment, source)
data_bag_item = encrypted_data_bag_for(environment, DATA_BAG)
if data_bag_item.has_key?(source)
data_bag_item[source]
elsif DATA_BAG == source
data_bag_item
else
{}
end
end | ruby | def data_bag_config_for(environment, source)
data_bag_item = encrypted_data_bag_for(environment, DATA_BAG)
if data_bag_item.has_key?(source)
data_bag_item[source]
elsif DATA_BAG == source
data_bag_item
else
{}
end
end | [
"def",
"data_bag_config_for",
"(",
"environment",
",",
"source",
")",
"data_bag_item",
"=",
"encrypted_data_bag_for",
"(",
"environment",
",",
"DATA_BAG",
")",
"if",
"data_bag_item",
".",
"has_key?",
"(",
"source",
")",
"data_bag_item",
"[",
"source",
"]",
"elsif"... | Loads the encrypted data bag item and returns credentials for the
environment or for a default key.
@param [String] environment
The environment
@param [String] source
The deployment source to load configuration for
@return [Chef::DataBagItem]
The data bag item | [
"Loads",
"the",
"encrypted",
"data",
"bag",
"item",
"and",
"returns",
"credentials",
"for",
"the",
"environment",
"or",
"for",
"a",
"default",
"key",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/secret_bag.rb#L129-L139 | train |
riddopic/garcun | lib/garcon/chef/secret_bag.rb | Garcon.SecretBag.encrypted_data_bag_for | def encrypted_data_bag_for(environment, data_bag)
@encrypted_data_bags = {} unless @encrypted_data_bags
if encrypted_data_bags[data_bag]
return get_from_data_bags_cache(data_bag)
else
data_bag_item = encrypted_data_bag_item(data_bag, environment)
data_bag_item ||= encrypted_da... | ruby | def encrypted_data_bag_for(environment, data_bag)
@encrypted_data_bags = {} unless @encrypted_data_bags
if encrypted_data_bags[data_bag]
return get_from_data_bags_cache(data_bag)
else
data_bag_item = encrypted_data_bag_item(data_bag, environment)
data_bag_item ||= encrypted_da... | [
"def",
"encrypted_data_bag_for",
"(",
"environment",
",",
"data_bag",
")",
"@encrypted_data_bags",
"=",
"{",
"}",
"unless",
"@encrypted_data_bags",
"if",
"encrypted_data_bags",
"[",
"data_bag",
"]",
"return",
"get_from_data_bags_cache",
"(",
"data_bag",
")",
"else",
"... | Looks for the given data bag in the cache and if not found, will load a
data bag item named for the chef_environment, or '_wildcard' value.
@param [String] environment
The environment.
@param [String] data_bag
The data bag to load.
@return [Chef::Mash]
The data bag item in Mash form. | [
"Looks",
"for",
"the",
"given",
"data",
"bag",
"in",
"the",
"cache",
"and",
"if",
"not",
"found",
"will",
"load",
"a",
"data",
"bag",
"item",
"named",
"for",
"the",
"chef_environment",
"or",
"_wildcard",
"value",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/secret_bag.rb#L153-L165 | train |
magiclabs/attachment_magic | lib/attachment_magic.rb | AttachmentMagic.ClassMethods.copy_to_temp_file | def copy_to_temp_file(file, temp_base_name)
Tempfile.new(temp_base_name, AttachmentMagic.tempfile_path).tap do |tmp|
tmp.close
FileUtils.cp file, tmp.path
end
end | ruby | def copy_to_temp_file(file, temp_base_name)
Tempfile.new(temp_base_name, AttachmentMagic.tempfile_path).tap do |tmp|
tmp.close
FileUtils.cp file, tmp.path
end
end | [
"def",
"copy_to_temp_file",
"(",
"file",
",",
"temp_base_name",
")",
"Tempfile",
".",
"new",
"(",
"temp_base_name",
",",
"AttachmentMagic",
".",
"tempfile_path",
")",
".",
"tap",
"do",
"|",
"tmp",
"|",
"tmp",
".",
"close",
"FileUtils",
".",
"cp",
"file",
"... | Copies the given file path to a new tempfile, returning the closed tempfile. | [
"Copies",
"the",
"given",
"file",
"path",
"to",
"a",
"new",
"tempfile",
"returning",
"the",
"closed",
"tempfile",
"."
] | 98f2d897f108352e53a7b8d05a475111d1a6f2a1 | https://github.com/magiclabs/attachment_magic/blob/98f2d897f108352e53a7b8d05a475111d1a6f2a1/lib/attachment_magic.rb#L130-L135 | train |
magiclabs/attachment_magic | lib/attachment_magic.rb | AttachmentMagic.ClassMethods.write_to_temp_file | def write_to_temp_file(data, temp_base_name)
Tempfile.new(temp_base_name, AttachmentMagic.tempfile_path).tap do |tmp|
tmp.binmode
tmp.write data
tmp.close
end
end | ruby | def write_to_temp_file(data, temp_base_name)
Tempfile.new(temp_base_name, AttachmentMagic.tempfile_path).tap do |tmp|
tmp.binmode
tmp.write data
tmp.close
end
end | [
"def",
"write_to_temp_file",
"(",
"data",
",",
"temp_base_name",
")",
"Tempfile",
".",
"new",
"(",
"temp_base_name",
",",
"AttachmentMagic",
".",
"tempfile_path",
")",
".",
"tap",
"do",
"|",
"tmp",
"|",
"tmp",
".",
"binmode",
"tmp",
".",
"write",
"data",
"... | Writes the given data to a new tempfile, returning the closed tempfile. | [
"Writes",
"the",
"given",
"data",
"to",
"a",
"new",
"tempfile",
"returning",
"the",
"closed",
"tempfile",
"."
] | 98f2d897f108352e53a7b8d05a475111d1a6f2a1 | https://github.com/magiclabs/attachment_magic/blob/98f2d897f108352e53a7b8d05a475111d1a6f2a1/lib/attachment_magic.rb#L138-L144 | train |
magiclabs/attachment_magic | lib/attachment_magic.rb | AttachmentMagic.InstanceMethods.uploaded_data= | def uploaded_data=(file_data)
if file_data.respond_to?(:content_type)
return nil if file_data.size == 0
self.content_type = detect_mimetype(file_data)
self.filename = file_data.original_filename if respond_to?(:filename)
else
return nil if file_data.blank? || file_data['s... | ruby | def uploaded_data=(file_data)
if file_data.respond_to?(:content_type)
return nil if file_data.size == 0
self.content_type = detect_mimetype(file_data)
self.filename = file_data.original_filename if respond_to?(:filename)
else
return nil if file_data.blank? || file_data['s... | [
"def",
"uploaded_data",
"=",
"(",
"file_data",
")",
"if",
"file_data",
".",
"respond_to?",
"(",
":content_type",
")",
"return",
"nil",
"if",
"file_data",
".",
"size",
"==",
"0",
"self",
".",
"content_type",
"=",
"detect_mimetype",
"(",
"file_data",
")",
"sel... | This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
any special code in your controller.
<% form_for :attachment, :html => { :multipart => true } do |f| -%>
<p><%= f.file_field :uploaded_data %></p>
<p><%= submit_tag :Save %>
<% end -%>
@attach... | [
"This",
"method",
"handles",
"the",
"uploaded",
"file",
"object",
".",
"If",
"you",
"set",
"the",
"field",
"name",
"to",
"uploaded_data",
"you",
"don",
"t",
"need",
"any",
"special",
"code",
"in",
"your",
"controller",
"."
] | 98f2d897f108352e53a7b8d05a475111d1a6f2a1 | https://github.com/magiclabs/attachment_magic/blob/98f2d897f108352e53a7b8d05a475111d1a6f2a1/lib/attachment_magic.rb#L189-L206 | train |
magiclabs/attachment_magic | lib/attachment_magic.rb | AttachmentMagic.InstanceMethods.attachment_attributes_valid? | def attachment_attributes_valid?
[:size, :content_type].each do |attr_name|
enum = attachment_options[attr_name]
errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
end
end | ruby | def attachment_attributes_valid?
[:size, :content_type].each do |attr_name|
enum = attachment_options[attr_name]
errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
end
end | [
"def",
"attachment_attributes_valid?",
"[",
":size",
",",
":content_type",
"]",
".",
"each",
"do",
"|",
"attr_name",
"|",
"enum",
"=",
"attachment_options",
"[",
"attr_name",
"]",
"errors",
".",
"add",
"attr_name",
",",
"I18n",
".",
"translate",
"(",
"\"active... | validates the size and content_type attributes according to the current model's options | [
"validates",
"the",
"size",
"and",
"content_type",
"attributes",
"according",
"to",
"the",
"current",
"model",
"s",
"options"
] | 98f2d897f108352e53a7b8d05a475111d1a6f2a1 | https://github.com/magiclabs/attachment_magic/blob/98f2d897f108352e53a7b8d05a475111d1a6f2a1/lib/attachment_magic.rb#L270-L275 | train |
chrisjones-tripletri/action_command | lib/action_command/pretty_print_log_action.rb | ActionCommand.PrettyPrintLogAction.execute_internal | def execute_internal(_result)
item = LogMessage.new
parser = LogParser.new(@source, @sequence)
sequences = {}
# keep track of sequences, and when you complete one, then print out the
# entire thing at once.
while parser.next(item)
if item.kind?(ActionCommand::LOG_KIND_COMMAN... | ruby | def execute_internal(_result)
item = LogMessage.new
parser = LogParser.new(@source, @sequence)
sequences = {}
# keep track of sequences, and when you complete one, then print out the
# entire thing at once.
while parser.next(item)
if item.kind?(ActionCommand::LOG_KIND_COMMAN... | [
"def",
"execute_internal",
"(",
"_result",
")",
"item",
"=",
"LogMessage",
".",
"new",
"parser",
"=",
"LogParser",
".",
"new",
"(",
"@source",
",",
"@sequence",
")",
"sequences",
"=",
"{",
"}",
"# keep track of sequences, and when you complete one, then print out the ... | Say hello to the specified person. | [
"Say",
"hello",
"to",
"the",
"specified",
"person",
"."
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/pretty_print_log_action.rb#L28-L45 | train |
cloudhead/mutter | lib/mutter/mutterer.rb | Mutter.Mutterer.load | def load styles
styles += '.yml' unless styles =~ /\.ya?ml$/
styles = File.join(File.dirname(__FILE__), "styles", styles) unless File.exist? styles
YAML.load_file(styles).inject({}) do |h, (key, value)|
value = { :match => value['match'], :style => value['style'] }
h.merge key.to_sym =... | ruby | def load styles
styles += '.yml' unless styles =~ /\.ya?ml$/
styles = File.join(File.dirname(__FILE__), "styles", styles) unless File.exist? styles
YAML.load_file(styles).inject({}) do |h, (key, value)|
value = { :match => value['match'], :style => value['style'] }
h.merge key.to_sym =... | [
"def",
"load",
"styles",
"styles",
"+=",
"'.yml'",
"unless",
"styles",
"=~",
"/",
"\\.",
"/",
"styles",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"\"styles\"",
",",
"styles",
")",
"unless",
"File",
".",
"exist?",... | Loads styles from a YAML style-sheet,
and converts the keys to symbols | [
"Loads",
"styles",
"from",
"a",
"YAML",
"style",
"-",
"sheet",
"and",
"converts",
"the",
"keys",
"to",
"symbols"
] | 08a422552027d5a7b30b60206384c11698cf903d | https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L64-L71 | train |
cloudhead/mutter | lib/mutter/mutterer.rb | Mutter.Mutterer.unstyle | def unstyle msg
styles.map do |_,v|
v[:match]
end.flatten.inject(msg) do |m, tag|
m.gsub(tag, '')
end
end | ruby | def unstyle msg
styles.map do |_,v|
v[:match]
end.flatten.inject(msg) do |m, tag|
m.gsub(tag, '')
end
end | [
"def",
"unstyle",
"msg",
"styles",
".",
"map",
"do",
"|",
"_",
",",
"v",
"|",
"v",
"[",
":match",
"]",
"end",
".",
"flatten",
".",
"inject",
"(",
"msg",
")",
"do",
"|",
"m",
",",
"tag",
"|",
"m",
".",
"gsub",
"(",
"tag",
",",
"''",
")",
"en... | Remove all tags from string | [
"Remove",
"all",
"tags",
"from",
"string"
] | 08a422552027d5a7b30b60206384c11698cf903d | https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L88-L94 | train |
cloudhead/mutter | lib/mutter/mutterer.rb | Mutter.Mutterer.write | def write str
self.class.stream.tap do |stream|
stream.write str
stream.flush
end ; nil
end | ruby | def write str
self.class.stream.tap do |stream|
stream.write str
stream.flush
end ; nil
end | [
"def",
"write",
"str",
"self",
".",
"class",
".",
"stream",
".",
"tap",
"do",
"|",
"stream",
"|",
"stream",
".",
"write",
"str",
"stream",
".",
"flush",
"end",
";",
"nil",
"end"
] | Write to the out stream, and flush it | [
"Write",
"to",
"the",
"out",
"stream",
"and",
"flush",
"it"
] | 08a422552027d5a7b30b60206384c11698cf903d | https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L107-L112 | train |
cloudhead/mutter | lib/mutter/mutterer.rb | Mutter.Mutterer.stylize | def stylize string, styles = []
[styles].flatten.inject(string) do |str, style|
style = style.to_sym
if ANSI[:transforms].include? style
esc str, *ANSI[:transforms][style]
elsif ANSI[:colors].include? style
esc str, ANSI[:colors][style], ANSI[:colors][:reset]
el... | ruby | def stylize string, styles = []
[styles].flatten.inject(string) do |str, style|
style = style.to_sym
if ANSI[:transforms].include? style
esc str, *ANSI[:transforms][style]
elsif ANSI[:colors].include? style
esc str, ANSI[:colors][style], ANSI[:colors][:reset]
el... | [
"def",
"stylize",
"string",
",",
"styles",
"=",
"[",
"]",
"[",
"styles",
"]",
".",
"flatten",
".",
"inject",
"(",
"string",
")",
"do",
"|",
"str",
",",
"style",
"|",
"style",
"=",
"style",
".",
"to_sym",
"if",
"ANSI",
"[",
":transforms",
"]",
".",
... | Apply styles to a string
if the style is a default ANSI style, we add the start
and end sequence to the string.
if the style is a custom style, we recurse, sending
the list of ANSI styles contained in the custom style.
TODO: use ';' delimited codes instead of multiple \e sequences | [
"Apply",
"styles",
"to",
"a",
"string"
] | 08a422552027d5a7b30b60206384c11698cf903d | https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L170-L181 | train |
danielpuglisi/seiten | lib/seiten/page.rb | Seiten.Page.parent_of? | def parent_of?(child)
page = self
if child
if page.id == child.parent_id
true
else
child.parent.nil? ? false : page.parent_of?(child.parent)
end
end
end | ruby | def parent_of?(child)
page = self
if child
if page.id == child.parent_id
true
else
child.parent.nil? ? false : page.parent_of?(child.parent)
end
end
end | [
"def",
"parent_of?",
"(",
"child",
")",
"page",
"=",
"self",
"if",
"child",
"if",
"page",
".",
"id",
"==",
"child",
".",
"parent_id",
"true",
"else",
"child",
".",
"parent",
".",
"nil?",
"?",
"false",
":",
"page",
".",
"parent_of?",
"(",
"child",
"."... | true if child is children of page | [
"true",
"if",
"child",
"is",
"children",
"of",
"page"
] | fa23d9ec616a23c615b0bf4b358bb979ab849104 | https://github.com/danielpuglisi/seiten/blob/fa23d9ec616a23c615b0bf4b358bb979ab849104/lib/seiten/page.rb#L83-L92 | train |
danielpuglisi/seiten | lib/seiten/page.rb | Seiten.Page.active? | def active?(current_page)
if current_page
if id == current_page.id
true
elsif parent_of?(current_page)
true
else
false
end
end
end | ruby | def active?(current_page)
if current_page
if id == current_page.id
true
elsif parent_of?(current_page)
true
else
false
end
end
end | [
"def",
"active?",
"(",
"current_page",
")",
"if",
"current_page",
"if",
"id",
"==",
"current_page",
".",
"id",
"true",
"elsif",
"parent_of?",
"(",
"current_page",
")",
"true",
"else",
"false",
"end",
"end",
"end"
] | true if page is equal current_page or parent of current_page | [
"true",
"if",
"page",
"is",
"equal",
"current_page",
"or",
"parent",
"of",
"current_page"
] | fa23d9ec616a23c615b0bf4b358bb979ab849104 | https://github.com/danielpuglisi/seiten/blob/fa23d9ec616a23c615b0bf4b358bb979ab849104/lib/seiten/page.rb#L95-L105 | train |
knaveofdiamonds/sequel_load_data_infile | lib/sequel/load_data_infile.rb | Sequel.LoadDataInfile.load_infile_sql | def load_infile_sql(path, columns, options={})
replacement = opts[:insert_ignore] ? :ignore : :replace
options = {:update => replacement}.merge(options)
LoadDataInfileExpression.new(path,
opts[:from].first,
columns,
... | ruby | def load_infile_sql(path, columns, options={})
replacement = opts[:insert_ignore] ? :ignore : :replace
options = {:update => replacement}.merge(options)
LoadDataInfileExpression.new(path,
opts[:from].first,
columns,
... | [
"def",
"load_infile_sql",
"(",
"path",
",",
"columns",
",",
"options",
"=",
"{",
"}",
")",
"replacement",
"=",
"opts",
"[",
":insert_ignore",
"]",
"?",
":ignore",
":",
":replace",
"options",
"=",
"{",
":update",
"=>",
"replacement",
"}",
".",
"merge",
"(... | Returns the SQL for a LOAD DATA INFILE statement. | [
"Returns",
"the",
"SQL",
"for",
"a",
"LOAD",
"DATA",
"INFILE",
"statement",
"."
] | a9198d727b44289ae99d2eaaf4bd7ec032ef737a | https://github.com/knaveofdiamonds/sequel_load_data_infile/blob/a9198d727b44289ae99d2eaaf4bd7ec032ef737a/lib/sequel/load_data_infile.rb#L136-L144 | train |
dabassett/shibbolite | spec/support/features/session_helpers.rb | Features.SessionHelpers.sign_in_as | def sign_in_as(group)
FactoryGirl.create(:user, umbcusername: 'test_user', group: group)
page.driver.browser.process_and_follow_redirects(:get, '/shibbolite/login', {}, {'umbcusername' => 'test_user'})
end | ruby | def sign_in_as(group)
FactoryGirl.create(:user, umbcusername: 'test_user', group: group)
page.driver.browser.process_and_follow_redirects(:get, '/shibbolite/login', {}, {'umbcusername' => 'test_user'})
end | [
"def",
"sign_in_as",
"(",
"group",
")",
"FactoryGirl",
".",
"create",
"(",
":user",
",",
"umbcusername",
":",
"'test_user'",
",",
"group",
":",
"group",
")",
"page",
".",
"driver",
".",
"browser",
".",
"process_and_follow_redirects",
"(",
":get",
",",
"'/shi... | hacked login, but the alternative is
not having integration tests when
using a Shibboleth based auth | [
"hacked",
"login",
"but",
"the",
"alternative",
"is",
"not",
"having",
"integration",
"tests",
"when",
"using",
"a",
"Shibboleth",
"based",
"auth"
] | cbd679c88de4ab238c40029447715f6ff22f3f50 | https://github.com/dabassett/shibbolite/blob/cbd679c88de4ab238c40029447715f6ff22f3f50/spec/support/features/session_helpers.rb#L7-L10 | train |
arvicco/poster | lib/poster/site.rb | Poster.Site.connect | def connect uri
Faraday.new(:url => "#{uri.scheme}://#{uri.host}") do |faraday|
faraday.request :multipart
faraday.request :url_encoded
# faraday.use FaradayMiddleware::FollowRedirects, limit: 3
faraday.use :cookie_jar
faraday.response :logger # log request... | ruby | def connect uri
Faraday.new(:url => "#{uri.scheme}://#{uri.host}") do |faraday|
faraday.request :multipart
faraday.request :url_encoded
# faraday.use FaradayMiddleware::FollowRedirects, limit: 3
faraday.use :cookie_jar
faraday.response :logger # log request... | [
"def",
"connect",
"uri",
"Faraday",
".",
"new",
"(",
":url",
"=>",
"\"#{uri.scheme}://#{uri.host}\"",
")",
"do",
"|",
"faraday",
"|",
"faraday",
".",
"request",
":multipart",
"faraday",
".",
"request",
":url_encoded",
"# faraday.use FaradayMiddleware::FollowRedirects, l... | Establish Faraday connection | [
"Establish",
"Faraday",
"connection"
] | a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63 | https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/site.rb#L20-L29 | train |
tnorthb/coinstack | lib/coinstack/printer.rb | Coinstack.Printer.pretty_print_user_list | def pretty_print_user_list(list)
total = 0
data = []
# Header row
data.push('Asset', 'Total Value', 'Change % (Week)')
list.user_pairs.each do |user_pair|
data.push(user_pair.symbol)
data.push(user_pair.valuation.format)
data.push(user_pair.perchant_change_week.to_s... | ruby | def pretty_print_user_list(list)
total = 0
data = []
# Header row
data.push('Asset', 'Total Value', 'Change % (Week)')
list.user_pairs.each do |user_pair|
data.push(user_pair.symbol)
data.push(user_pair.valuation.format)
data.push(user_pair.perchant_change_week.to_s... | [
"def",
"pretty_print_user_list",
"(",
"list",
")",
"total",
"=",
"0",
"data",
"=",
"[",
"]",
"# Header row",
"data",
".",
"push",
"(",
"'Asset'",
",",
"'Total Value'",
",",
"'Change % (Week)'",
")",
"list",
".",
"user_pairs",
".",
"each",
"do",
"|",
"user_... | Prints out a summary of the user's hodlings formatted nicely | [
"Prints",
"out",
"a",
"summary",
"of",
"the",
"user",
"s",
"hodlings",
"formatted",
"nicely"
] | 1316fd069f502fa04fe15bc6ab7e63302aa29fd8 | https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/printer.rb#L13-L29 | train |
tnorthb/coinstack | lib/coinstack/printer.rb | Coinstack.Printer.print_arrays | def print_arrays(data, cols)
formatted_list = cli.list(data, :uneven_columns_across, cols)
cli.say(formatted_list)
end | ruby | def print_arrays(data, cols)
formatted_list = cli.list(data, :uneven_columns_across, cols)
cli.say(formatted_list)
end | [
"def",
"print_arrays",
"(",
"data",
",",
"cols",
")",
"formatted_list",
"=",
"cli",
".",
"list",
"(",
"data",
",",
":uneven_columns_across",
",",
"cols",
")",
"cli",
".",
"say",
"(",
"formatted_list",
")",
"end"
] | Data should be an array of arays, cols is the number of columns it has
Prints the data to screen with equal spacing between them | [
"Data",
"should",
"be",
"an",
"array",
"of",
"arays",
"cols",
"is",
"the",
"number",
"of",
"columns",
"it",
"has",
"Prints",
"the",
"data",
"to",
"screen",
"with",
"equal",
"spacing",
"between",
"them"
] | 1316fd069f502fa04fe15bc6ab7e63302aa29fd8 | https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/printer.rb#L33-L36 | train |
tnorthb/coinstack | lib/coinstack/printer.rb | Coinstack.Printer.array_char_length | def array_char_length(input_array)
length = 0
input_array.each do |a|
length += a.to_s.length
end
length
end | ruby | def array_char_length(input_array)
length = 0
input_array.each do |a|
length += a.to_s.length
end
length
end | [
"def",
"array_char_length",
"(",
"input_array",
")",
"length",
"=",
"0",
"input_array",
".",
"each",
"do",
"|",
"a",
"|",
"length",
"+=",
"a",
".",
"to_s",
".",
"length",
"end",
"length",
"end"
] | Returns the combined length of charaters in an array | [
"Returns",
"the",
"combined",
"length",
"of",
"charaters",
"in",
"an",
"array"
] | 1316fd069f502fa04fe15bc6ab7e63302aa29fd8 | https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/printer.rb#L43-L49 | train |
remote-exec/context-filters | lib/context-filters/filters/filters.rb | ContextFilters::Filters.Filters.select_filters | def select_filters(target, options)
found = filters_store.fetch(options, [])
if
Hash === options || options.nil?
then
options ||={}
options.merge!(:target => target)
found +=
# can not @filters.fetch(options, []) to allow filters provide custom ==()
filt... | ruby | def select_filters(target, options)
found = filters_store.fetch(options, [])
if
Hash === options || options.nil?
then
options ||={}
options.merge!(:target => target)
found +=
# can not @filters.fetch(options, []) to allow filters provide custom ==()
filt... | [
"def",
"select_filters",
"(",
"target",
",",
"options",
")",
"found",
"=",
"filters_store",
".",
"fetch",
"(",
"options",
",",
"[",
"]",
")",
"if",
"Hash",
"===",
"options",
"||",
"options",
".",
"nil?",
"then",
"options",
"||=",
"{",
"}",
"options",
"... | Select matching filters and filters including targets when
options is a +Hash+
@param target [Object] an object to run the method on
@param options [Object] a filter for selecting matching blocks | [
"Select",
"matching",
"filters",
"and",
"filters",
"including",
"targets",
"when",
"options",
"is",
"a",
"+",
"Hash",
"+"
] | 66b54fc6c46b224321713b608d70bba3afde9902 | https://github.com/remote-exec/context-filters/blob/66b54fc6c46b224321713b608d70bba3afde9902/lib/context-filters/filters/filters.rb#L54-L68 | train |
modernistik/parse-stack-async | lib/parse/stack/async.rb | Parse.Object.save_eventually | def save_eventually
block = block_given? ? Proc.new : nil
_self = self
Parse::Stack::Async.run do
begin
result = true
_self.save!
rescue => e
result = false
puts "[SaveEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}"
... | ruby | def save_eventually
block = block_given? ? Proc.new : nil
_self = self
Parse::Stack::Async.run do
begin
result = true
_self.save!
rescue => e
result = false
puts "[SaveEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}"
... | [
"def",
"save_eventually",
"block",
"=",
"block_given?",
"?",
"Proc",
".",
"new",
":",
"nil",
"_self",
"=",
"self",
"Parse",
"::",
"Stack",
"::",
"Async",
".",
"run",
"do",
"begin",
"result",
"=",
"true",
"_self",
".",
"save!",
"rescue",
"=>",
"e",
"res... | Adds support for saving a Parse object in the background.
@example
object.save_eventually do |success|
puts "Saved successfully" if success
end
@yield A block to call after the save has completed.
@yieldparam [Boolean] success whether the save was successful.
@return [Boolean] whether the job was enqueued. | [
"Adds",
"support",
"for",
"saving",
"a",
"Parse",
"object",
"in",
"the",
"background",
"."
] | 24f79f0d79c1f2d3f8c561242c4528ac878143a8 | https://github.com/modernistik/parse-stack-async/blob/24f79f0d79c1f2d3f8c561242c4528ac878143a8/lib/parse/stack/async.rb#L66-L82 | train |
modernistik/parse-stack-async | lib/parse/stack/async.rb | Parse.Object.destroy_eventually | def destroy_eventually
block = block_given? ? Proc.new : nil
_self = self
Parse::Stack::Async.run do
begin
result = true
_self.destroy
rescue => e
result = false
puts "[DestroyEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}"
... | ruby | def destroy_eventually
block = block_given? ? Proc.new : nil
_self = self
Parse::Stack::Async.run do
begin
result = true
_self.destroy
rescue => e
result = false
puts "[DestroyEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}"
... | [
"def",
"destroy_eventually",
"block",
"=",
"block_given?",
"?",
"Proc",
".",
"new",
":",
"nil",
"_self",
"=",
"self",
"Parse",
"::",
"Stack",
"::",
"Async",
".",
"run",
"do",
"begin",
"result",
"=",
"true",
"_self",
".",
"destroy",
"rescue",
"=>",
"e",
... | save_eventually
Adds support for deleting a Parse object in the background.
@example
object.destroy_eventually do |success|
puts 'Deleted successfully' if success
end
@yield A block to call after the deletion has completed.
@yieldparam [Boolean] success whether the save was successful.'
@return [Boolean] ... | [
"save_eventually",
"Adds",
"support",
"for",
"deleting",
"a",
"Parse",
"object",
"in",
"the",
"background",
"."
] | 24f79f0d79c1f2d3f8c561242c4528ac878143a8 | https://github.com/modernistik/parse-stack-async/blob/24f79f0d79c1f2d3f8c561242c4528ac878143a8/lib/parse/stack/async.rb#L92-L108 | train |
Raybeam/myreplicator | lib/exporter/mysql_exporter.rb | Myreplicator.MysqlExporter.export_table | def export_table export_obj
@export_obj = export_obj
ExportMetadata.record(:table => @export_obj.table_name,
:database => @export_obj.source_schema,
:export_to => load_to,
:export_id => @export_obj.id,
... | ruby | def export_table export_obj
@export_obj = export_obj
ExportMetadata.record(:table => @export_obj.table_name,
:database => @export_obj.source_schema,
:export_to => load_to,
:export_id => @export_obj.id,
... | [
"def",
"export_table",
"export_obj",
"@export_obj",
"=",
"export_obj",
"ExportMetadata",
".",
"record",
"(",
":table",
"=>",
"@export_obj",
".",
"table_name",
",",
":database",
"=>",
"@export_obj",
".",
"source_schema",
",",
":export_to",
"=>",
"load_to",
",",
":e... | Gets an Export object and dumps the data
Initially using mysqldump
Incrementally using mysql -e afterwards | [
"Gets",
"an",
"Export",
"object",
"and",
"dumps",
"the",
"data",
"Initially",
"using",
"mysqldump",
"Incrementally",
"using",
"mysql",
"-",
"e",
"afterwards"
] | 470938e70f46886b525c65a4a464b4cf8383d00d | https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L13-L37 | train |
Raybeam/myreplicator | lib/exporter/mysql_exporter.rb | Myreplicator.MysqlExporter.initial_export | def initial_export metadata
metadata.export_type = "initial"
max_value = @export_obj.max_value if @export_obj.incremental_export?
cmd = initial_mysqldump_cmd
exporting_state_trans # mark exporting
puts "Exporting..."
result = execute_export(cmd, metadata)
check_result(result, ... | ruby | def initial_export metadata
metadata.export_type = "initial"
max_value = @export_obj.max_value if @export_obj.incremental_export?
cmd = initial_mysqldump_cmd
exporting_state_trans # mark exporting
puts "Exporting..."
result = execute_export(cmd, metadata)
check_result(result, ... | [
"def",
"initial_export",
"metadata",
"metadata",
".",
"export_type",
"=",
"\"initial\"",
"max_value",
"=",
"@export_obj",
".",
"max_value",
"if",
"@export_obj",
".",
"incremental_export?",
"cmd",
"=",
"initial_mysqldump_cmd",
"exporting_state_trans",
"# mark exporting",
"... | Exports Table using mysqldump. This method is invoked only once.
Dumps with create options, no need to create table manaully | [
"Exports",
"Table",
"using",
"mysqldump",
".",
"This",
"method",
"is",
"invoked",
"only",
"once",
".",
"Dumps",
"with",
"create",
"options",
"no",
"need",
"to",
"create",
"table",
"manaully"
] | 470938e70f46886b525c65a4a464b4cf8383d00d | https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L72-L83 | train |
Raybeam/myreplicator | lib/exporter/mysql_exporter.rb | Myreplicator.MysqlExporter.incremental_export_into_outfile | def incremental_export_into_outfile metadata
unless @export_obj.is_running?
if @export_obj.export_type == "incremental"
max_value = @export_obj.max_value
metadata.export_type = "incremental"
@export_obj.update_max_val if @export_obj.max_incremental_value.blan... | ruby | def incremental_export_into_outfile metadata
unless @export_obj.is_running?
if @export_obj.export_type == "incremental"
max_value = @export_obj.max_value
metadata.export_type = "incremental"
@export_obj.update_max_val if @export_obj.max_incremental_value.blan... | [
"def",
"incremental_export_into_outfile",
"metadata",
"unless",
"@export_obj",
".",
"is_running?",
"if",
"@export_obj",
".",
"export_type",
"==",
"\"incremental\"",
"max_value",
"=",
"@export_obj",
".",
"max_value",
"metadata",
".",
"export_type",
"=",
"\"incremental\"",
... | Exports table incrementally, similar to incremental_export method
Dumps file in tmp directory specified in myreplicator.yml
Note that directory needs 777 permissions for mysql to be able to export the file
Uses \\0 as the delimiter and new line for lines | [
"Exports",
"table",
"incrementally",
"similar",
"to",
"incremental_export",
"method",
"Dumps",
"file",
"in",
"tmp",
"directory",
"specified",
"in",
"myreplicator",
".",
"yml",
"Note",
"that",
"directory",
"needs",
"777",
"permissions",
"for",
"mysql",
"to",
"be",
... | 470938e70f46886b525c65a4a464b4cf8383d00d | https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L110-L162 | train |
Raybeam/myreplicator | lib/exporter/mysql_exporter.rb | Myreplicator.MysqlExporter.check_result | def check_result result, size
unless result.nil?
raise Exceptions::ExportError.new("Export Error\n#{result}") if result.length > 0
end
end | ruby | def check_result result, size
unless result.nil?
raise Exceptions::ExportError.new("Export Error\n#{result}") if result.length > 0
end
end | [
"def",
"check_result",
"result",
",",
"size",
"unless",
"result",
".",
"nil?",
"raise",
"Exceptions",
"::",
"ExportError",
".",
"new",
"(",
"\"Export Error\\n#{result}\"",
")",
"if",
"result",
".",
"length",
">",
"0",
"end",
"end"
] | Checks the returned resut from SSH CMD
Size specifies if there should be any returned results or not | [
"Checks",
"the",
"returned",
"resut",
"from",
"SSH",
"CMD",
"Size",
"specifies",
"if",
"there",
"should",
"be",
"any",
"returned",
"results",
"or",
"not"
] | 470938e70f46886b525c65a4a464b4cf8383d00d | https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L239-L243 | train |
Raybeam/myreplicator | lib/exporter/mysql_exporter.rb | Myreplicator.MysqlExporter.zipfile | def zipfile metadata
cmd = "cd #{Myreplicator.configs[@export_obj.source_schema]["ssh_tmp_dir"]}; gzip #{@export_obj.filename}"
puts cmd
zip_result = metadata.ssh.exec!(cmd)
unless zip_result.nil?
raise Exceptions::ExportError.new("Export Error\n#{zip_result}") if zip_result.l... | ruby | def zipfile metadata
cmd = "cd #{Myreplicator.configs[@export_obj.source_schema]["ssh_tmp_dir"]}; gzip #{@export_obj.filename}"
puts cmd
zip_result = metadata.ssh.exec!(cmd)
unless zip_result.nil?
raise Exceptions::ExportError.new("Export Error\n#{zip_result}") if zip_result.l... | [
"def",
"zipfile",
"metadata",
"cmd",
"=",
"\"cd #{Myreplicator.configs[@export_obj.source_schema][\"ssh_tmp_dir\"]}; gzip #{@export_obj.filename}\"",
"puts",
"cmd",
"zip_result",
"=",
"metadata",
".",
"ssh",
".",
"exec!",
"(",
"cmd",
")",
"unless",
"zip_result",
".",
"nil?"... | zips the file on the source DB server | [
"zips",
"the",
"file",
"on",
"the",
"source",
"DB",
"server"
] | 470938e70f46886b525c65a4a464b4cf8383d00d | https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L262-L276 | train |
blotto/thermometer | lib/thermometer/configuration.rb | Thermometer.Configuration.load_time_ranges | def load_time_ranges
@time_ranges = ActiveSupport::HashWithIndifferentAccess.new
time_ranges = @config['time']
time_ranges.each do |t,r|
time_range = ActiveSupport::HashWithIndifferentAccess.new
src_ranges ||= r
src_ranges.map { |k,v| time_range[k.to_sym] = rangify_time_boundar... | ruby | def load_time_ranges
@time_ranges = ActiveSupport::HashWithIndifferentAccess.new
time_ranges = @config['time']
time_ranges.each do |t,r|
time_range = ActiveSupport::HashWithIndifferentAccess.new
src_ranges ||= r
src_ranges.map { |k,v| time_range[k.to_sym] = rangify_time_boundar... | [
"def",
"load_time_ranges",
"@time_ranges",
"=",
"ActiveSupport",
"::",
"HashWithIndifferentAccess",
".",
"new",
"time_ranges",
"=",
"@config",
"[",
"'time'",
"]",
"time_ranges",
".",
"each",
"do",
"|",
"t",
",",
"r",
"|",
"time_range",
"=",
"ActiveSupport",
"::"... | Load ranges from config file | [
"Load",
"ranges",
"from",
"config",
"file"
] | bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa | https://github.com/blotto/thermometer/blob/bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa/lib/thermometer/configuration.rb#L95-L105 | train |
blotto/thermometer | lib/thermometer/configuration.rb | Thermometer.Configuration.rangify_time_boundaries | def rangify_time_boundaries(src)
src.split("..").inject{ |s,e| s.split(".").inject{|n,m| n.to_i.send(m)}..e.split(".").inject{|n,m| n.to_i.send(m) }}
end | ruby | def rangify_time_boundaries(src)
src.split("..").inject{ |s,e| s.split(".").inject{|n,m| n.to_i.send(m)}..e.split(".").inject{|n,m| n.to_i.send(m) }}
end | [
"def",
"rangify_time_boundaries",
"(",
"src",
")",
"src",
".",
"split",
"(",
"\"..\"",
")",
".",
"inject",
"{",
"|",
"s",
",",
"e",
"|",
"s",
".",
"split",
"(",
"\".\"",
")",
".",
"inject",
"{",
"|",
"n",
",",
"m",
"|",
"n",
".",
"to_i",
".",
... | Takes a string like "2.days..3.weeks"
and converts to Range object -> 2.days..3.weeks | [
"Takes",
"a",
"string",
"like",
"2",
".",
"days",
"..",
"3",
".",
"weeks",
"and",
"converts",
"to",
"Range",
"object",
"-",
">",
"2",
".",
"days",
"..",
"3",
".",
"weeks"
] | bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa | https://github.com/blotto/thermometer/blob/bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa/lib/thermometer/configuration.rb#L111-L113 | train |
sanctuarycomputer/appi | app/controllers/concerns/appi/handles_resources.rb | APPI.HandlesResources.klass_for_type | def klass_for_type(type, singular=false)
type = type.singularize unless singular
type.classify.constantize
end | ruby | def klass_for_type(type, singular=false)
type = type.singularize unless singular
type.classify.constantize
end | [
"def",
"klass_for_type",
"(",
"type",
",",
"singular",
"=",
"false",
")",
"type",
"=",
"type",
".",
"singularize",
"unless",
"singular",
"type",
".",
"classify",
".",
"constantize",
"end"
] | Resolves the Class for a type.
Params:
+type+:: +String+ A stringified type.
+singular+:: +Boolean+ Pass true if you don't want to singularize the type. | [
"Resolves",
"the",
"Class",
"for",
"a",
"type",
"."
] | 5a06f7c090e4fcaaba9060685fa6a6c7434e8436 | https://github.com/sanctuarycomputer/appi/blob/5a06f7c090e4fcaaba9060685fa6a6c7434e8436/app/controllers/concerns/appi/handles_resources.rb#L31-L34 | train |
sanctuarycomputer/appi | app/controllers/concerns/appi/handles_resources.rb | APPI.HandlesResources.resource_params | def resource_params
attributes = find_in_params(:attributes).try(:permit, permitted_attributes) || {}
relationships = {}
# Build Relationships Data
relationships_in_payload = find_in_params(:relationships)
if relationships_in_payload
raw_relationships = relationships_in_p... | ruby | def resource_params
attributes = find_in_params(:attributes).try(:permit, permitted_attributes) || {}
relationships = {}
# Build Relationships Data
relationships_in_payload = find_in_params(:relationships)
if relationships_in_payload
raw_relationships = relationships_in_p... | [
"def",
"resource_params",
"attributes",
"=",
"find_in_params",
"(",
":attributes",
")",
".",
"try",
"(",
":permit",
",",
"permitted_attributes",
")",
"||",
"{",
"}",
"relationships",
"=",
"{",
"}",
"# Build Relationships Data",
"relationships_in_payload",
"=",
"find... | Builds a whitelisted resource_params hash from the permitted_attributes &
permitted_relationships arrays. Will automatically attempt to resolve
string IDs to numerical IDs, in the case the model's slug was passed to
the controller as ID. | [
"Builds",
"a",
"whitelisted",
"resource_params",
"hash",
"from",
"the",
"permitted_attributes",
"&",
"permitted_relationships",
"arrays",
".",
"Will",
"automatically",
"attempt",
"to",
"resolve",
"string",
"IDs",
"to",
"numerical",
"IDs",
"in",
"the",
"case",
"the",... | 5a06f7c090e4fcaaba9060685fa6a6c7434e8436 | https://github.com/sanctuarycomputer/appi/blob/5a06f7c090e4fcaaba9060685fa6a6c7434e8436/app/controllers/concerns/appi/handles_resources.rb#L108-L131 | train |
richard-viney/lightstreamer | lib/lightstreamer/stream_connection_header.rb | Lightstreamer.StreamConnectionHeader.process_line | def process_line(line)
@lines << line
return process_success if @lines.first == 'OK'
return process_error if @lines.first == 'ERROR'
return process_end if @lines.first == 'END'
return process_sync_error if @lines.first == 'SYNC ERROR'
process_unrecognized
end | ruby | def process_line(line)
@lines << line
return process_success if @lines.first == 'OK'
return process_error if @lines.first == 'ERROR'
return process_end if @lines.first == 'END'
return process_sync_error if @lines.first == 'SYNC ERROR'
process_unrecognized
end | [
"def",
"process_line",
"(",
"line",
")",
"@lines",
"<<",
"line",
"return",
"process_success",
"if",
"@lines",
".",
"first",
"==",
"'OK'",
"return",
"process_error",
"if",
"@lines",
".",
"first",
"==",
"'ERROR'",
"return",
"process_end",
"if",
"@lines",
".",
... | Processes a single line of header information. The return value indicates whether further data is required in
order to complete the header.
@param [String] line The line of header data to process.
@return [Boolean] Whether the header is still incomplete and requires further data. | [
"Processes",
"a",
"single",
"line",
"of",
"header",
"information",
".",
"The",
"return",
"value",
"indicates",
"whether",
"further",
"data",
"is",
"required",
"in",
"order",
"to",
"complete",
"the",
"header",
"."
] | 7be6350bd861495a52ca35a8640a1e6df34cf9d1 | https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/stream_connection_header.rb#L24-L33 | train |
vpacher/xpay | lib/xpay/transaction_query.rb | Xpay.TransactionQuery.create_request | def create_request
raise AttributeMissing.new "(2500) TransactionReference or OrderReference need to be present." if (transaction_reference.nil? && order_reference.nil?)
raise AttributeMissing.new "(2500) SiteReference must be present." if (site_reference.nil? && (REXML::XPath.first(@request_xml, "//SiteRef... | ruby | def create_request
raise AttributeMissing.new "(2500) TransactionReference or OrderReference need to be present." if (transaction_reference.nil? && order_reference.nil?)
raise AttributeMissing.new "(2500) SiteReference must be present." if (site_reference.nil? && (REXML::XPath.first(@request_xml, "//SiteRef... | [
"def",
"create_request",
"raise",
"AttributeMissing",
".",
"new",
"\"(2500) TransactionReference or OrderReference need to be present.\"",
"if",
"(",
"transaction_reference",
".",
"nil?",
"&&",
"order_reference",
".",
"nil?",
")",
"raise",
"AttributeMissing",
".",
"new",
"\... | Write the xml document needed for processing, fill in elements need and delete unused ones from the root_xml
raises an error if any necessary elements are missing | [
"Write",
"the",
"xml",
"document",
"needed",
"for",
"processing",
"fill",
"in",
"elements",
"need",
"and",
"delete",
"unused",
"ones",
"from",
"the",
"root_xml",
"raises",
"an",
"error",
"if",
"any",
"necessary",
"elements",
"are",
"missing"
] | 58c0b0f2600ed30ff44b84f97b96c74590474f3f | https://github.com/vpacher/xpay/blob/58c0b0f2600ed30ff44b84f97b96c74590474f3f/lib/xpay/transaction_query.rb#L43-L55 | train |
subimage/cashboard-rb | lib/cashboard/time_entry.rb | Cashboard.TimeEntry.toggle_timer | def toggle_timer
options = self.class.merge_options()
options.merge!({:body => self.to_xml})
response = self.class.put(self.links[:toggle_timer], options)
# Raise special errors if not a success
self.class.check_status_code(response)
# Re-initialize ourselves with infor... | ruby | def toggle_timer
options = self.class.merge_options()
options.merge!({:body => self.to_xml})
response = self.class.put(self.links[:toggle_timer], options)
# Raise special errors if not a success
self.class.check_status_code(response)
# Re-initialize ourselves with infor... | [
"def",
"toggle_timer",
"options",
"=",
"self",
".",
"class",
".",
"merge_options",
"(",
")",
"options",
".",
"merge!",
"(",
"{",
":body",
"=>",
"self",
".",
"to_xml",
"}",
")",
"response",
"=",
"self",
".",
"class",
".",
"put",
"(",
"self",
".",
"lin... | readonly
Starts or stops timer depending on its current state.
Will return an object of Cashboard::Struct if another timer was stopped
during this toggle operation.
Will return nil if no timer was stopped. | [
"readonly",
"Starts",
"or",
"stops",
"timer",
"depending",
"on",
"its",
"current",
"state",
"."
] | 320e311ea1549cdd0dada0f8a0a4f9942213b28f | https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/time_entry.rb#L20-L36 | train |
mbj/ducktrap | lib/ducktrap/error.rb | Ducktrap.Error.dump | def dump(output)
output.name(self)
output.attribute(:input, input)
output.nest(:context, context)
end | ruby | def dump(output)
output.name(self)
output.attribute(:input, input)
output.nest(:context, context)
end | [
"def",
"dump",
"(",
"output",
")",
"output",
".",
"name",
"(",
"self",
")",
"output",
".",
"attribute",
"(",
":input",
",",
"input",
")",
"output",
".",
"nest",
"(",
":context",
",",
"context",
")",
"end"
] | Dump state to output
@param [Formatter] formatter
@return [undefined]
@api private | [
"Dump",
"state",
"to",
"output"
] | 482d874d3eb43b2dbb518b8537851d742d785903 | https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/error.rb#L17-L21 | train |
raid5/agilezen | lib/agilezen/stories.rb | AgileZen.Stories.project_story | def project_story(project_id, story_id, options={})
response_body = nil
begin
response = connection.get do |req|
req.url "/api/v1/projects/#{project_id}/story/#{story_id}", options
end
response_body = response.body
rescue MultiJson::DecodeError => e
#p 'Unable... | ruby | def project_story(project_id, story_id, options={})
response_body = nil
begin
response = connection.get do |req|
req.url "/api/v1/projects/#{project_id}/story/#{story_id}", options
end
response_body = response.body
rescue MultiJson::DecodeError => e
#p 'Unable... | [
"def",
"project_story",
"(",
"project_id",
",",
"story_id",
",",
"options",
"=",
"{",
"}",
")",
"response_body",
"=",
"nil",
"begin",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"/api/v1/projects/#{project_id}/story/#... | Retrieve information for an individual story of a given project. | [
"Retrieve",
"information",
"for",
"an",
"individual",
"story",
"of",
"a",
"given",
"project",
"."
] | 36fcef642c82b35c8c8664ee6a2ff22ce52054c0 | https://github.com/raid5/agilezen/blob/36fcef642c82b35c8c8664ee6a2ff22ce52054c0/lib/agilezen/stories.rb#L21-L33 | train |
twohlix/database_cached_attribute | lib/database_cached_attribute.rb | DatabaseCachedAttribute.ClassMethods.database_cached_attribute | def database_cached_attribute(*attrs)
attrs.each do |attr|
define_method("invalidate_#{attr}") do |arg=nil| # default arg to allow before_blah callbacks
invalidate_cache attr.to_sym
end
define_method("only_#{attr}_changed?") do
only_change? attr.to_sym
end
... | ruby | def database_cached_attribute(*attrs)
attrs.each do |attr|
define_method("invalidate_#{attr}") do |arg=nil| # default arg to allow before_blah callbacks
invalidate_cache attr.to_sym
end
define_method("only_#{attr}_changed?") do
only_change? attr.to_sym
end
... | [
"def",
"database_cached_attribute",
"(",
"*",
"attrs",
")",
"attrs",
".",
"each",
"do",
"|",
"attr",
"|",
"define_method",
"(",
"\"invalidate_#{attr}\"",
")",
"do",
"|",
"arg",
"=",
"nil",
"|",
"# default arg to allow before_blah callbacks",
"invalidate_cache",
"att... | Sets up cache invalidation callbacks for the provided attributes | [
"Sets",
"up",
"cache",
"invalidation",
"callbacks",
"for",
"the",
"provided",
"attributes"
] | 9aee710f10062eb0ffa918310183aaabaeaffa04 | https://github.com/twohlix/database_cached_attribute/blob/9aee710f10062eb0ffa918310183aaabaeaffa04/lib/database_cached_attribute.rb#L62-L76 | train |
midas/nameable_record | lib/nameable_record/name.rb | NameableRecord.Name.to_s | def to_s( pattern='%l, %f' )
if pattern.is_a?( Symbol )
return conversational if pattern == :conversational
return sortable if pattern == :sortable
pattern = PREDEFINED_PATTERNS[pattern]
end
PATTERN_MAP.inject( pattern ) do |name, mapping|
name = name.gsub( mapping.fir... | ruby | def to_s( pattern='%l, %f' )
if pattern.is_a?( Symbol )
return conversational if pattern == :conversational
return sortable if pattern == :sortable
pattern = PREDEFINED_PATTERNS[pattern]
end
PATTERN_MAP.inject( pattern ) do |name, mapping|
name = name.gsub( mapping.fir... | [
"def",
"to_s",
"(",
"pattern",
"=",
"'%l, %f'",
")",
"if",
"pattern",
".",
"is_a?",
"(",
"Symbol",
")",
"return",
"conversational",
"if",
"pattern",
"==",
":conversational",
"return",
"sortable",
"if",
"pattern",
"==",
":sortable",
"pattern",
"=",
"PREDEFINED_... | Creates a name based on pattern provided. Defaults to last, first.
Symbols:
%l - last name
%f - first name
%m - middle name
%p - prefix
%s - suffix | [
"Creates",
"a",
"name",
"based",
"on",
"pattern",
"provided",
".",
"Defaults",
"to",
"last",
"first",
"."
] | a8a6689151bff1e7448baeffbd9ee603989a708e | https://github.com/midas/nameable_record/blob/a8a6689151bff1e7448baeffbd9ee603989a708e/lib/nameable_record/name.rb#L38-L49 | train |
midas/nameable_record | lib/nameable_record/name.rb | NameableRecord.Name.sortable | def sortable
[
last,
[
prefix,
first,
middle,
suffix
].reject( &:blank? ).
join( ' ' )
].reject( &:blank? ).
join( ', ' )
end | ruby | def sortable
[
last,
[
prefix,
first,
middle,
suffix
].reject( &:blank? ).
join( ' ' )
].reject( &:blank? ).
join( ', ' )
end | [
"def",
"sortable",
"[",
"last",
",",
"[",
"prefix",
",",
"first",
",",
"middle",
",",
"suffix",
"]",
".",
"reject",
"(",
":blank?",
")",
".",
"join",
"(",
"' '",
")",
"]",
".",
"reject",
"(",
":blank?",
")",
".",
"join",
"(",
"', '",
")",
"end"
] | Returns the name in a sortable format. | [
"Returns",
"the",
"name",
"in",
"a",
"sortable",
"format",
"."
] | a8a6689151bff1e7448baeffbd9ee603989a708e | https://github.com/midas/nameable_record/blob/a8a6689151bff1e7448baeffbd9ee603989a708e/lib/nameable_record/name.rb#L66-L78 | train |
schoefmann/klarlack | lib/varnish/client.rb | Varnish.Client.vcl | def vcl(op, *params)
response = cmd("vcl.#{op}", *params)
case op
when :list
response.split("\n").map do |line|
a = line.split(/\s+/, 3)
[a[0], a[1].to_i, a[2]]
end
else
response
end
end | ruby | def vcl(op, *params)
response = cmd("vcl.#{op}", *params)
case op
when :list
response.split("\n").map do |line|
a = line.split(/\s+/, 3)
[a[0], a[1].to_i, a[2]]
end
else
response
end
end | [
"def",
"vcl",
"(",
"op",
",",
"*",
"params",
")",
"response",
"=",
"cmd",
"(",
"\"vcl.#{op}\"",
",",
"params",
")",
"case",
"op",
"when",
":list",
"response",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"do",
"|",
"line",
"|",
"a",
"=",
"line",
... | Manipulate the VCL configuration
.vcl :load, <configname>, <filename>
.vcl :inline, <configname>, <quoted_VCLstring>
.vcl :use, <configname>
.vcl :discard, <configname>
.vcl :list
.vcl :show, <configname>
Returns an array of VCL configurations for :list, and the servers
response as string otherwise
Ex... | [
"Manipulate",
"the",
"VCL",
"configuration"
] | 7c1b2668da27d663d904c9646ef0d492830fe3de | https://github.com/schoefmann/klarlack/blob/7c1b2668da27d663d904c9646ef0d492830fe3de/lib/varnish/client.rb#L105-L116 | train |
schoefmann/klarlack | lib/varnish/client.rb | Varnish.Client.purge | def purge(*args)
c = 'purge'
c << ".#{args.shift}" if [:url, :hash, :list].include?(args.first)
response = cmd(c, *args)
case c
when 'purge.list'
response.split("\n").map do |line|
a = line.split("\t")
[a[0].to_i, a[1]]
end
else
bool respon... | ruby | def purge(*args)
c = 'purge'
c << ".#{args.shift}" if [:url, :hash, :list].include?(args.first)
response = cmd(c, *args)
case c
when 'purge.list'
response.split("\n").map do |line|
a = line.split("\t")
[a[0].to_i, a[1]]
end
else
bool respon... | [
"def",
"purge",
"(",
"*",
"args",
")",
"c",
"=",
"'purge'",
"c",
"<<",
"\".#{args.shift}\"",
"if",
"[",
":url",
",",
":hash",
",",
":list",
"]",
".",
"include?",
"(",
"args",
".",
"first",
")",
"response",
"=",
"cmd",
"(",
"c",
",",
"args",
")",
... | Purge objects from the cache or show the purge queue.
Takes one or two arguments:
1.
.purge :url, <regexp>
.purge :hash, <regexp>
<regexp> is a string containing a varnish compatible regexp
2.
.purge <costum-purge-conditions>
.purge :list
Returns true for purging, returns an array containing the purge... | [
"Purge",
"objects",
"from",
"the",
"cache",
"or",
"show",
"the",
"purge",
"queue",
"."
] | 7c1b2668da27d663d904c9646ef0d492830fe3de | https://github.com/schoefmann/klarlack/blob/7c1b2668da27d663d904c9646ef0d492830fe3de/lib/varnish/client.rb#L144-L157 | train |
schoefmann/klarlack | lib/varnish/client.rb | Varnish.Client.stats | def stats
result = cmd("stats")
Hash[*result.split("\n").map { |line|
stat = line.strip!.split(/\s+/, 2)
[stat[1], stat[0].to_i]
}.flatten
]
end | ruby | def stats
result = cmd("stats")
Hash[*result.split("\n").map { |line|
stat = line.strip!.split(/\s+/, 2)
[stat[1], stat[0].to_i]
}.flatten
]
end | [
"def",
"stats",
"result",
"=",
"cmd",
"(",
"\"stats\"",
")",
"Hash",
"[",
"result",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"{",
"|",
"line",
"|",
"stat",
"=",
"line",
".",
"strip!",
".",
"split",
"(",
"/",
"\\s",
"/",
",",
"2",
")",
"["... | Returns a hash of status information
Ex.:
v = Varnish::Client.new
v.stats
=> {"Total header bytes"=>0, "Cache misses"=>0 ...} | [
"Returns",
"a",
"hash",
"of",
"status",
"information"
] | 7c1b2668da27d663d904c9646ef0d492830fe3de | https://github.com/schoefmann/klarlack/blob/7c1b2668da27d663d904c9646ef0d492830fe3de/lib/varnish/client.rb#L170-L177 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.last_column | def last_column
max = 0
@data.each do |row|
max = row.length if max < row.length
end
max - 1
end | ruby | def last_column
max = 0
@data.each do |row|
max = row.length if max < row.length
end
max - 1
end | [
"def",
"last_column",
"max",
"=",
"0",
"@data",
".",
"each",
"do",
"|",
"row",
"|",
"max",
"=",
"row",
".",
"length",
"if",
"max",
"<",
"row",
".",
"length",
"end",
"max",
"-",
"1",
"end"
] | Gets the last column in the table. | [
"Gets",
"the",
"last",
"column",
"in",
"the",
"table",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L75-L81 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.build_column | def build_column(start_column = nil)
if block_given?
raise StandardError.new('build_column block called within row block') if @in_row
raise StandardError.new('build_column called without valid argument') unless start_column.is_a?(Numeric)
backup_col_start = @col_start
backup_col_o... | ruby | def build_column(start_column = nil)
if block_given?
raise StandardError.new('build_column block called within row block') if @in_row
raise StandardError.new('build_column called without valid argument') unless start_column.is_a?(Numeric)
backup_col_start = @col_start
backup_col_o... | [
"def",
"build_column",
"(",
"start_column",
"=",
"nil",
")",
"if",
"block_given?",
"raise",
"StandardError",
".",
"new",
"(",
"'build_column block called within row block'",
")",
"if",
"@in_row",
"raise",
"StandardError",
".",
"new",
"(",
"'build_column called without v... | Builds data starting at the specified column.
The +start_column+ is the first column you want to be building.
When you start a new row inside of a build_column block, the new row
starts at this same column. | [
"Builds",
"data",
"starting",
"at",
"the",
"specified",
"column",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L89-L108 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.row | def row(options = {}, &block)
raise StandardError.new('row called within row block') if @in_row
@in_row = true
@col_offset = @col_start
options = change_row(options || {})
@row_cell_options = @base_cell_options.merge(options)
fill_cells(@row_offset, @col_offset)
# skip plac... | ruby | def row(options = {}, &block)
raise StandardError.new('row called within row block') if @in_row
@in_row = true
@col_offset = @col_start
options = change_row(options || {})
@row_cell_options = @base_cell_options.merge(options)
fill_cells(@row_offset, @col_offset)
# skip plac... | [
"def",
"row",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"StandardError",
".",
"new",
"(",
"'row called within row block'",
")",
"if",
"@in_row",
"@in_row",
"=",
"true",
"@col_offset",
"=",
"@col_start",
"options",
"=",
"change_row",
"("... | Builds a row in the table.
Valid options:
row::
Defines the row you want to start on. If not set, then it uses #current_row.
Additional options are merged with the base cell options for this row.
When it completes, the #current_row is set to 1 more than the row we started on. | [
"Builds",
"a",
"row",
"in",
"the",
"table",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L122-L145 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.subtable | def subtable(cell_options = {}, options = {}, &block)
raise StandardError.new('subtable called outside of row block') unless @in_row
cell cell_options || {} do
PdfTableBuilder.new(@doc, options || {}, &block).to_table
end
end | ruby | def subtable(cell_options = {}, options = {}, &block)
raise StandardError.new('subtable called outside of row block') unless @in_row
cell cell_options || {} do
PdfTableBuilder.new(@doc, options || {}, &block).to_table
end
end | [
"def",
"subtable",
"(",
"cell_options",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"StandardError",
".",
"new",
"(",
"'subtable called outside of row block'",
")",
"unless",
"@in_row",
"cell",
"cell_options",
"||",
"{",
"}... | Builds a subtable within the current row.
The +cell_options+ are passed to the current cell.
The +options+ are passed to the new TableBuilder. | [
"Builds",
"a",
"subtable",
"within",
"the",
"current",
"row",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L153-L158 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.cells | def cells(options = {}, &block)
cell_regex = /^cell_([0-9]+)_/
options ||= { }
result = block_given? ? yield : (options[:values] || [''])
cell_options = result.map { {} }
common_options = {}
options.each do |k,v|
# if the option starts with 'cell_#_' then apply it accordi... | ruby | def cells(options = {}, &block)
cell_regex = /^cell_([0-9]+)_/
options ||= { }
result = block_given? ? yield : (options[:values] || [''])
cell_options = result.map { {} }
common_options = {}
options.each do |k,v|
# if the option starts with 'cell_#_' then apply it accordi... | [
"def",
"cells",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"cell_regex",
"=",
"/",
"/",
"options",
"||=",
"{",
"}",
"result",
"=",
"block_given?",
"?",
"yield",
":",
"(",
"options",
"[",
":values",
"]",
"||",
"[",
"''",
"]",
")",
"cel... | Creates multiple cells.
Individual cells can be given options by prefixing the keys with 'cell_#' where # is the cell number (starting at 1).
See #cell for valid options. | [
"Creates",
"multiple",
"cells",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L203-L232 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.cell | def cell(options = {}, &block)
raise StandardError.new('cell called outside of row block') unless @in_row
options = @row_cell_options.merge(options || {})
options = change_col(options)
result = block_given? ? yield : (options[:value] || '')
options.except!(:value)
set_cell(resul... | ruby | def cell(options = {}, &block)
raise StandardError.new('cell called outside of row block') unless @in_row
options = @row_cell_options.merge(options || {})
options = change_col(options)
result = block_given? ? yield : (options[:value] || '')
options.except!(:value)
set_cell(resul... | [
"def",
"cell",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"StandardError",
".",
"new",
"(",
"'cell called outside of row block'",
")",
"unless",
"@in_row",
"options",
"=",
"@row_cell_options",
".",
"merge",
"(",
"options",
"||",
"{",
"}"... | Generates a cell in the current row.
Valid options:
value::
The value to put in the cell, unless a code block is provided, in which case the result of the code block is used.
rowspan::
The number of rows for this cell to cover.
colspan::
The number of columns for this cell to cover.
Additional option... | [
"Generates",
"a",
"cell",
"in",
"the",
"current",
"row",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L275-L287 | train |
barkerest/barkest_core | app/models/barkest_core/pdf_table_builder.rb | BarkestCore.PdfTableBuilder.fix_row_widths | def fix_row_widths
fill_cells(@row_offset - 1, 0)
max = 0
@data.each_with_index do |row|
max = row.length unless max >= row.length
end
@data.each_with_index do |row,idx|
if row.length < max
row = row + [ @base_cell_options.merge({content: ''}) ] * (max - row.l... | ruby | def fix_row_widths
fill_cells(@row_offset - 1, 0)
max = 0
@data.each_with_index do |row|
max = row.length unless max >= row.length
end
@data.each_with_index do |row,idx|
if row.length < max
row = row + [ @base_cell_options.merge({content: ''}) ] * (max - row.l... | [
"def",
"fix_row_widths",
"fill_cells",
"(",
"@row_offset",
"-",
"1",
",",
"0",
")",
"max",
"=",
"0",
"@data",
".",
"each_with_index",
"do",
"|",
"row",
"|",
"max",
"=",
"row",
".",
"length",
"unless",
"max",
">=",
"row",
".",
"length",
"end",
"@data",
... | ensure that all 2nd level arrays are the same size. | [
"ensure",
"that",
"all",
"2nd",
"level",
"arrays",
"are",
"the",
"same",
"size",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L387-L404 | train |
ekosz/Erics-Tic-Tac-Toe | lib/tic_tac_toe/board.rb | TicTacToe.Board.empty_positions | def empty_positions(&block)
positions = []
each_position do |row, column|
next if get_cell(row, column)
yield(row, column) if block_given?
positions << [row, column]
end
positions
end | ruby | def empty_positions(&block)
positions = []
each_position do |row, column|
next if get_cell(row, column)
yield(row, column) if block_given?
positions << [row, column]
end
positions
end | [
"def",
"empty_positions",
"(",
"&",
"block",
")",
"positions",
"=",
"[",
"]",
"each_position",
"do",
"|",
"row",
",",
"column",
"|",
"next",
"if",
"get_cell",
"(",
"row",
",",
"column",
")",
"yield",
"(",
"row",
",",
"column",
")",
"if",
"block_given?"... | Returns the corners of the empty cells | [
"Returns",
"the",
"corners",
"of",
"the",
"empty",
"cells"
] | d0c2580974c12187ec9cf11030b72eda6cae3d97 | https://github.com/ekosz/Erics-Tic-Tac-Toe/blob/d0c2580974c12187ec9cf11030b72eda6cae3d97/lib/tic_tac_toe/board.rb#L21-L29 | train |
ekosz/Erics-Tic-Tac-Toe | lib/tic_tac_toe/board.rb | TicTacToe.Board.solved? | def solved?
letter = won_across?
return letter if letter
letter = won_up_and_down?
return letter if letter
letter = won_diagonally?
return letter if letter
false
end | ruby | def solved?
letter = won_across?
return letter if letter
letter = won_up_and_down?
return letter if letter
letter = won_diagonally?
return letter if letter
false
end | [
"def",
"solved?",
"letter",
"=",
"won_across?",
"return",
"letter",
"if",
"letter",
"letter",
"=",
"won_up_and_down?",
"return",
"letter",
"if",
"letter",
"letter",
"=",
"won_diagonally?",
"return",
"letter",
"if",
"letter",
"false",
"end"
] | Returns true if the board has a wining pattern | [
"Returns",
"true",
"if",
"the",
"board",
"has",
"a",
"wining",
"pattern"
] | d0c2580974c12187ec9cf11030b72eda6cae3d97 | https://github.com/ekosz/Erics-Tic-Tac-Toe/blob/d0c2580974c12187ec9cf11030b72eda6cae3d97/lib/tic_tac_toe/board.rb#L64-L72 | train |
buzzware/buzztools | lib/buzztools/config.rb | Buzztools.Config.read | def read(aSource,&aBlock)
default_values.each do |k,v|
done = false
if block_given? && ((newv = yield(k,v,aSource && aSource[k])) != nil)
self[k] = newv
done = true
end
copy_item(aSource,k) if !done && aSource && !aSource[k].nil?
end
self
end | ruby | def read(aSource,&aBlock)
default_values.each do |k,v|
done = false
if block_given? && ((newv = yield(k,v,aSource && aSource[k])) != nil)
self[k] = newv
done = true
end
copy_item(aSource,k) if !done && aSource && !aSource[k].nil?
end
self
end | [
"def",
"read",
"(",
"aSource",
",",
"&",
"aBlock",
")",
"default_values",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"done",
"=",
"false",
"if",
"block_given?",
"&&",
"(",
"(",
"newv",
"=",
"yield",
"(",
"k",
",",
"v",
",",
"aSource",
"&&",
"aSo... | aBlock allows values to be filtered based on key,default and new values | [
"aBlock",
"allows",
"values",
"to",
"be",
"filtered",
"based",
"on",
"key",
"default",
"and",
"new",
"values"
] | 0823721974d521330ceffe099368ed8cac6209c3 | https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/config.rb#L15-L25 | train |
buzzware/buzztools | lib/buzztools/config.rb | Buzztools.Config.reset | def reset
self.clear
me = self
@default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v}
end | ruby | def reset
self.clear
me = self
@default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v}
end | [
"def",
"reset",
"self",
".",
"clear",
"me",
"=",
"self",
"@default_values",
".",
"each",
"{",
"|",
"n",
",",
"v",
"|",
"me",
"[",
"n",
"]",
"=",
"v",
".",
"is_a?",
"(",
"Class",
")",
"?",
"nil",
":",
"v",
"}",
"end"
] | reset values back to defaults | [
"reset",
"values",
"back",
"to",
"defaults"
] | 0823721974d521330ceffe099368ed8cac6209c3 | https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/config.rb#L28-L32 | train |
cbetta/snapshotify | lib/snapshotify/writer.rb | Snapshotify.Writer.ensure_directory | def ensure_directory
dir = File.dirname(full_filename)
unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end
end | ruby | def ensure_directory
dir = File.dirname(full_filename)
unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end
end | [
"def",
"ensure_directory",
"dir",
"=",
"File",
".",
"dirname",
"(",
"full_filename",
")",
"unless",
"File",
".",
"directory?",
"(",
"dir",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"dir",
")",
"end",
"end"
] | Ensure the directory for the file exists | [
"Ensure",
"the",
"directory",
"for",
"the",
"file",
"exists"
] | 7f5553f4281ffc5bf0e54da1141574bd15af45b6 | https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/writer.rb#L29-L34 | train |
cbetta/snapshotify | lib/snapshotify/writer.rb | Snapshotify.Writer.filename | def filename
# Based on the path of the file
path = resource.url.uri.path
# It's either an index.html file
# if the path ends with a slash
if path.end_with?('/')
return path + 'index.html'
# Or it's also an index.html if it ends
# without a slah yet is not a file with a... | ruby | def filename
# Based on the path of the file
path = resource.url.uri.path
# It's either an index.html file
# if the path ends with a slash
if path.end_with?('/')
return path + 'index.html'
# Or it's also an index.html if it ends
# without a slah yet is not a file with a... | [
"def",
"filename",
"# Based on the path of the file",
"path",
"=",
"resource",
".",
"url",
".",
"uri",
".",
"path",
"# It's either an index.html file",
"# if the path ends with a slash",
"if",
"path",
".",
"end_with?",
"(",
"'/'",
")",
"return",
"path",
"+",
"'index.h... | The actual name of the file | [
"The",
"actual",
"name",
"of",
"the",
"file"
] | 7f5553f4281ffc5bf0e54da1141574bd15af45b6 | https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/writer.rb#L57-L72 | train |
Subsets and Splits
SQL Console for semeru/code-text-ruby
Retrieves 20,000 non-null code samples labeled as Ruby, providing a basic overview of the dataset but without deeper analysis.