repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
chetan/bixby-common
lib/bixby-common/command_spec.rb
Bixby.CommandSpec.manifest
def manifest if File.exists?(manifest_file) && File.readable?(manifest_file) then MultiJson.load(File.read(manifest_file)) else {} end end
ruby
def manifest if File.exists?(manifest_file) && File.readable?(manifest_file) then MultiJson.load(File.read(manifest_file)) else {} end end
[ "def", "manifest", "if", "File", ".", "exists?", "(", "manifest_file", ")", "&&", "File", ".", "readable?", "(", "manifest_file", ")", "then", "MultiJson", ".", "load", "(", "File", ".", "read", "(", "manifest_file", ")", ")", "else", "{", "}", "end", ...
Retrieve the command's Manifest, loading it from disk if necessary If no Manifest is available, returns an empty hash @return [Hash]
[ "Retrieve", "the", "command", "s", "Manifest", "loading", "it", "from", "disk", "if", "necessary", "If", "no", "Manifest", "is", "available", "returns", "an", "empty", "hash" ]
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/command_spec.rb#L100-L106
train
chetan/bixby-common
lib/bixby-common/command_spec.rb
Bixby.CommandSpec.to_s
def to_s # :nocov: s = [] s << "CommandSpec:#{self.object_id}" s << " digest: #{self.digest}" s << " repo: #{self.repo}" s << " bundle: #{self.bundle}" s << " command: #{self.command}" s << " args: #{self.args}" s << " user: #{self.user}" s << " group: #{self.group}" s << " env: " + (self.env.nil?() ? "" : MultiJson.dump(self.env)) s << " stdin: " + Debug.pretty_str(stdin) s.join("\n") end
ruby
def to_s # :nocov: s = [] s << "CommandSpec:#{self.object_id}" s << " digest: #{self.digest}" s << " repo: #{self.repo}" s << " bundle: #{self.bundle}" s << " command: #{self.command}" s << " args: #{self.args}" s << " user: #{self.user}" s << " group: #{self.group}" s << " env: " + (self.env.nil?() ? "" : MultiJson.dump(self.env)) s << " stdin: " + Debug.pretty_str(stdin) s.join("\n") end
[ "def", "to_s", "s", "=", "[", "]", "s", "<<", "\"CommandSpec:#{self.object_id}\"", "s", "<<", "\" digest: #{self.digest}\"", "s", "<<", "\" repo: #{self.repo}\"", "s", "<<", "\" bundle: #{self.bundle}\"", "s", "<<", "\" command: #{self.command}\"", "s", "<<",...
Convert object to String, useful for debugging @return [String]
[ "Convert", "object", "to", "String", "useful", "for", "debugging" ]
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/command_spec.rb#L173-L186
train
ideonetwork/lato-blog
app/models/lato_blog/category.rb
LatoBlog.Category.check_category_father_circular_dependency
def check_category_father_circular_dependency return unless self.lato_blog_category_id all_children = self.get_all_category_children same_children = all_children.select { |child| child.id === self.lato_blog_category_id } if same_children.length > 0 errors.add('Category father', 'can not be a children of the category') throw :abort end end
ruby
def check_category_father_circular_dependency return unless self.lato_blog_category_id all_children = self.get_all_category_children same_children = all_children.select { |child| child.id === self.lato_blog_category_id } if same_children.length > 0 errors.add('Category father', 'can not be a children of the category') throw :abort end end
[ "def", "check_category_father_circular_dependency", "return", "unless", "self", ".", "lato_blog_category_id", "all_children", "=", "self", ".", "get_all_category_children", "same_children", "=", "all_children", ".", "select", "{", "|", "child", "|", "child", ".", "id", ...
This function check the category parent of the category do not create a circular dependency.
[ "This", "function", "check", "the", "category", "parent", "of", "the", "category", "do", "not", "create", "a", "circular", "dependency", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category.rb#L80-L90
train
ideonetwork/lato-blog
app/models/lato_blog/category.rb
LatoBlog.Category.check_lato_blog_category_parent
def check_lato_blog_category_parent category_parent = LatoBlog::CategoryParent.find_by(id: lato_blog_category_parent_id) if !category_parent errors.add('Category parent', 'not exist for the category') throw :abort return end same_language_category = category_parent.categories.find_by(meta_language: meta_language) if same_language_category && same_language_category.id != id errors.add('Category parent', 'has another category for the same language') throw :abort return end end
ruby
def check_lato_blog_category_parent category_parent = LatoBlog::CategoryParent.find_by(id: lato_blog_category_parent_id) if !category_parent errors.add('Category parent', 'not exist for the category') throw :abort return end same_language_category = category_parent.categories.find_by(meta_language: meta_language) if same_language_category && same_language_category.id != id errors.add('Category parent', 'has another category for the same language') throw :abort return end end
[ "def", "check_lato_blog_category_parent", "category_parent", "=", "LatoBlog", "::", "CategoryParent", ".", "find_by", "(", "id", ":", "lato_blog_category_parent_id", ")", "if", "!", "category_parent", "errors", ".", "add", "(", "'Category parent'", ",", "'not exist for ...
This function check that the category parent exist and has not others categories for the same language.
[ "This", "function", "check", "that", "the", "category", "parent", "exist", "and", "has", "not", "others", "categories", "for", "the", "same", "language", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category.rb#L102-L116
train
nsi-iff/nsivideogranulate-ruby
lib/nsivideogranulate/fake_server.rb
NSIVideoGranulate.FakeServerManager.start_server
def start_server(port=9886) @thread = Thread.new do Server.prepare Server.run! :port => port end sleep(1) self end
ruby
def start_server(port=9886) @thread = Thread.new do Server.prepare Server.run! :port => port end sleep(1) self end
[ "def", "start_server", "(", "port", "=", "9886", ")", "@thread", "=", "Thread", ".", "new", "do", "Server", ".", "prepare", "Server", ".", "run!", ":port", "=>", "port", "end", "sleep", "(", "1", ")", "self", "end" ]
Start the nsi.videogranulate fake server @param [Fixnum] port the port where the fake server will listen * make sure there's not anything else listenning on this port
[ "Start", "the", "nsi", ".", "videogranulate", "fake", "server" ]
794f44630ba6cac019a320288229ccccee00864d
https://github.com/nsi-iff/nsivideogranulate-ruby/blob/794f44630ba6cac019a320288229ccccee00864d/lib/nsivideogranulate/fake_server.rb#L56-L63
train
sugaryourcoffee/syclink
lib/syclink/importer.rb
SycLink.Importer.links
def links rows.map do |row| attributes = Link::ATTRS.dup - [:url] Link.new(row.shift, Hash[row.map { |v| [attributes.shift, v] }]) end end
ruby
def links rows.map do |row| attributes = Link::ATTRS.dup - [:url] Link.new(row.shift, Hash[row.map { |v| [attributes.shift, v] }]) end end
[ "def", "links", "rows", ".", "map", "do", "|", "row", "|", "attributes", "=", "Link", "::", "ATTRS", ".", "dup", "-", "[", ":url", "]", "Link", ".", "new", "(", "row", ".", "shift", ",", "Hash", "[", "row", ".", "map", "{", "|", "v", "|", "["...
Links returned as Link objects
[ "Links", "returned", "as", "Link", "objects" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/importer.rb#L38-L43
train
petebrowne/machined
lib/machined/server.rb
Machined.Server.to_app
def to_app # :nodoc: Rack::Builder.new.tap do |app| app.use Middleware::Static, machined.output_path app.use Middleware::RootIndex app.run Rack::URLMap.new(sprockets_map) end end
ruby
def to_app # :nodoc: Rack::Builder.new.tap do |app| app.use Middleware::Static, machined.output_path app.use Middleware::RootIndex app.run Rack::URLMap.new(sprockets_map) end end
[ "def", "to_app", "Rack", "::", "Builder", ".", "new", ".", "tap", "do", "|", "app", "|", "app", ".", "use", "Middleware", "::", "Static", ",", "machined", ".", "output_path", "app", ".", "use", "Middleware", "::", "RootIndex", "app", ".", "run", "Rack"...
Creates a Rack app with the current Machined environment configuration.
[ "Creates", "a", "Rack", "app", "with", "the", "current", "Machined", "environment", "configuration", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/server.rb#L52-L58
train
checkdin/checkdin-ruby
lib/checkdin/twitter_hashtag_streams.rb
Checkdin.TwitterHashtagStreams.twitter_hashtag_streams
def twitter_hashtag_streams(campaign_id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams", options end return_error_or_body(response) end
ruby
def twitter_hashtag_streams(campaign_id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams", options end return_error_or_body(response) end
[ "def", "twitter_hashtag_streams", "(", "campaign_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"campaigns/#{campaign_id}/twitter_hashtag_streams\"", ",", "options", "end", "return_er...
Retrieve Twitter Hashtag Streams for a campaign param [Integer] campaign_id The ID of the campaign to fetch the twitter hashtag stream for. @param [Hash] options
[ "Retrieve", "Twitter", "Hashtag", "Streams", "for", "a", "campaign" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/twitter_hashtag_streams.rb#L9-L14
train
checkdin/checkdin-ruby
lib/checkdin/twitter_hashtag_streams.rb
Checkdin.TwitterHashtagStreams.twitter_hashtag_stream
def twitter_hashtag_stream(campaign_id, id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}", options end return_error_or_body(response) end
ruby
def twitter_hashtag_stream(campaign_id, id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}", options end return_error_or_body(response) end
[ "def", "twitter_hashtag_stream", "(", "campaign_id", ",", "id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}\"", ",", "options", ...
Retrieve Single Twitter Hashtag Stream for a campaign param [Integer] campaign_id The ID of the campaign to fetch the twitter hashtag stream for. param [Integer] id The ID of the twitter_hashtag_stream to fetch. @param [Hash] options
[ "Retrieve", "Single", "Twitter", "Hashtag", "Stream", "for", "a", "campaign" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/twitter_hashtag_streams.rb#L22-L27
train
pixeltrix/rails_legacy_mapper
lib/rails_legacy_mapper/mapper.rb
RailsLegacyMapper.Mapper.root
def root(options = {}) if options.is_a?(Symbol) if source_route = @set.named_routes.routes[options] options = source_route.defaults.merge({ :conditions => source_route.conditions }) end end named_route("root", '', options) end
ruby
def root(options = {}) if options.is_a?(Symbol) if source_route = @set.named_routes.routes[options] options = source_route.defaults.merge({ :conditions => source_route.conditions }) end end named_route("root", '', options) end
[ "def", "root", "(", "options", "=", "{", "}", ")", "if", "options", ".", "is_a?", "(", "Symbol", ")", "if", "source_route", "=", "@set", ".", "named_routes", ".", "routes", "[", "options", "]", "options", "=", "source_route", ".", "defaults", ".", "mer...
Creates a named route called "root" for matching the root level request.
[ "Creates", "a", "named", "route", "called", "root", "for", "matching", "the", "root", "level", "request", "." ]
d841d25b76fed96595f5dff19d4772c7017b3b71
https://github.com/pixeltrix/rails_legacy_mapper/blob/d841d25b76fed96595f5dff19d4772c7017b3b71/lib/rails_legacy_mapper/mapper.rb#L157-L164
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.index
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories to show @categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC') @widget_index_categories = core__widgets_index(@categories, search: 'title', pagination: 10) end
ruby
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories to show @categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC') @widget_index_categories = core__widgets_index(@categories, search: 'title', pagination: 10) end
[ "def", "index", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":categories", "]", ")", "@categories", "=", "LatoBlog", "::", "Category", ".", "where", "(", "meta_language", ":", "cookies", "[", ":lato_bl...
This function shows the list of possible categories.
[ "This", "function", "shows", "the", "list", "of", "possible", "categories", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L9-L14
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.new
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_new]) @category = LatoBlog::Category.new if params[:language] set_current_language params[:language] end if params[:parent] @category_parent = LatoBlog::CategoryParent.find_by(id: params[:parent]) end fetch_external_objects end
ruby
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_new]) @category = LatoBlog::Category.new if params[:language] set_current_language params[:language] end if params[:parent] @category_parent = LatoBlog::CategoryParent.find_by(id: params[:parent]) end fetch_external_objects end
[ "def", "new", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":categories_new", "]", ")", "@category", "=", "LatoBlog", "::", "Category", ".", "new", "if", "params", "[", ":language", "]", "set_current_la...
This function shows the view to create a new category.
[ "This", "function", "shows", "the", "view", "to", "create", "a", "new", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L23-L36
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.create
def create @category = LatoBlog::Category.new(new_category_params) if !@category.save flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.new_category_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_create_success] redirect_to lato_blog.category_path(@category.id) end
ruby
def create @category = LatoBlog::Category.new(new_category_params) if !@category.save flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.new_category_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_create_success] redirect_to lato_blog.category_path(@category.id) end
[ "def", "create", "@category", "=", "LatoBlog", "::", "Category", ".", "new", "(", "new_category_params", ")", "if", "!", "@category", ".", "save", "flash", "[", ":danger", "]", "=", "@category", ".", "errors", ".", "full_messages", ".", "to_sentence", "redir...
This function creates a new category.
[ "This", "function", "creates", "a", "new", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L39-L50
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.edit
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_edit]) @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if @category.meta_language != cookies[:lato_blog__current_language] set_current_language @category.meta_language end fetch_external_objects end
ruby
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_edit]) @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if @category.meta_language != cookies[:lato_blog__current_language] set_current_language @category.meta_language end fetch_external_objects end
[ "def", "edit", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":categories_edit", "]", ")", "@category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", "...
This function show the view to edit a category.
[ "This", "function", "show", "the", "view", "to", "edit", "a", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L53-L63
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.update
def update @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.update(edit_category_params) flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_update_success] redirect_to lato_blog.category_path(@category.id) end
ruby
def update @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.update(edit_category_params) flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_update_success] redirect_to lato_blog.category_path(@category.id) end
[ "def", "update", "@category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_category_presence", "if", "!", "@category", ".", "update", "(", "edit_category_params", ")", "flash", ...
This function updates a category.
[ "This", "function", "updates", "a", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L66-L78
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.destroy
def destroy @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.destroy flash[:danger] = @category.category_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
ruby
def destroy @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.destroy flash[:danger] = @category.category_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
[ "def", "destroy", "@category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_category_presence", "if", "!", "@category", ".", "destroy", "flash", "[", ":danger", "]", "=", "@ca...
This function destroyes a category.
[ "This", "function", "destroyes", "a", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L81-L93
train
yolk/pump
lib/pump/encoder.rb
Pump.Encoder.encode
def encode(object, options={}) object = object.to_a if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation) fields_to_hash(options) if object.is_a?(Array) if options[:fields] encode_partial_array(object, options) else encode_array(object, options) end elsif options[:fields] encode_partial_single(object, options) else encode_single(object, options) end end
ruby
def encode(object, options={}) object = object.to_a if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation) fields_to_hash(options) if object.is_a?(Array) if options[:fields] encode_partial_array(object, options) else encode_array(object, options) end elsif options[:fields] encode_partial_single(object, options) else encode_single(object, options) end end
[ "def", "encode", "(", "object", ",", "options", "=", "{", "}", ")", "object", "=", "object", ".", "to_a", "if", "defined?", "(", "ActiveRecord", "::", "Relation", ")", "&&", "object", ".", "is_a?", "(", "ActiveRecord", "::", "Relation", ")", "fields_to_h...
Creates a new XML-encoder with a root tag named after +root_name+. @example Create a simple encoder for a person with a name attribute: Pump::Xml.new :person do tag :name end @example Create the same without usage of the DSL: Pump::Xml.new :person, [{:name => :name}] @example Create the same but without the xml instruct Pump::Xml.new :person, :instruct => false do tag :name end @example The same again without DSL: Pump::Xml.new :person, [{:name => :name}], :instruct => false @param [String, Symbol] root_name the name of the used root tag @param [Array<Hash>] encoder_config optional config for all tags @param [Hash] encoder_options optional encoder_options for the whole encoder @yield an optional block to create the encoder with the Pump::Dsl @return [self] Encode a object or an array of objects to an formatted string. @param [Object, Array<Object>] object object or an array of objects to encode to XML or JSON. The only requirement: The given objects must respond to all methods configured during initalization of the Pump::Xml or Pump::JSON instance. @return [String]
[ "Creates", "a", "new", "XML", "-", "encoder", "with", "a", "root", "tag", "named", "after", "+", "root_name", "+", "." ]
164281df30363302ff43ad2a250d9407b3aa3af4
https://github.com/yolk/pump/blob/164281df30363302ff43ad2a250d9407b3aa3af4/lib/pump/encoder.rb#L55-L69
train
dlindahl/network_executive
lib/network_executive/channel_schedule.rb
NetworkExecutive.ChannelSchedule.extend_off_air
def extend_off_air( programs, program, stop ) prev = programs.pop + program program = prev.program occurrence = prev.occurrence remainder = time_left( occurrence.start_time, occurrence.end_time, stop ) [ program, occurrence, remainder ] end
ruby
def extend_off_air( programs, program, stop ) prev = programs.pop + program program = prev.program occurrence = prev.occurrence remainder = time_left( occurrence.start_time, occurrence.end_time, stop ) [ program, occurrence, remainder ] end
[ "def", "extend_off_air", "(", "programs", ",", "program", ",", "stop", ")", "prev", "=", "programs", ".", "pop", "+", "program", "program", "=", "prev", ".", "program", "occurrence", "=", "prev", ".", "occurrence", "remainder", "=", "time_left", "(", "occu...
Extends the previous Off Air schedule
[ "Extends", "the", "previous", "Off", "Air", "schedule" ]
4802e8b20225d7058c82f5ded05bfa6c84918e3d
https://github.com/dlindahl/network_executive/blob/4802e8b20225d7058c82f5ded05bfa6c84918e3d/lib/network_executive/channel_schedule.rb#L55-L62
train
jimjh/reaction
lib/reaction/client/signer.rb
Reaction.Client::Signer.outgoing
def outgoing(message, callback) # Allow non-data messages to pass through. return callback.call(message) if %r{^/meta/} =~ message['channel'] message['ext'] ||= {} signature = OpenSSL::HMAC.digest('sha256', @key, message['data']) message['ext']['signature'] = Base64.encode64(signature) return callback.call(message) end
ruby
def outgoing(message, callback) # Allow non-data messages to pass through. return callback.call(message) if %r{^/meta/} =~ message['channel'] message['ext'] ||= {} signature = OpenSSL::HMAC.digest('sha256', @key, message['data']) message['ext']['signature'] = Base64.encode64(signature) return callback.call(message) end
[ "def", "outgoing", "(", "message", ",", "callback", ")", "return", "callback", ".", "call", "(", "message", ")", "if", "%r{", "}", "=~", "message", "[", "'channel'", "]", "message", "[", "'ext'", "]", "||=", "{", "}", "signature", "=", "OpenSSL", "::",...
Initializes the signer with a secret key. @param [String] key secret key, used to sign messages Adds a signature to every outgoing publish message.
[ "Initializes", "the", "signer", "with", "a", "secret", "key", "." ]
8aff9633dbd177ea536b79f59115a2825b5adf0a
https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/client/signer.rb#L14-L25
train
mntnorv/puttext
lib/puttext/extractor.rb
PutText.Extractor.extract
def extract(path) files = files_in_path(path) supported_files = filter_files(files) parse_files(supported_files) end
ruby
def extract(path) files = files_in_path(path) supported_files = filter_files(files) parse_files(supported_files) end
[ "def", "extract", "(", "path", ")", "files", "=", "files_in_path", "(", "path", ")", "supported_files", "=", "filter_files", "(", "files", ")", "parse_files", "(", "supported_files", ")", "end" ]
Extract strings from files in the given path. @param [String] path the path of a directory or file to extract strings from. @return [POFile] a POFile object, representing the strings extracted from the files or file in the specified path.
[ "Extract", "strings", "from", "files", "in", "the", "given", "path", "." ]
c5c210dff4e11f714418b6b426dc9e2739fe9876
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/extractor.rb#L45-L50
train
TuftsUniversity/whowas
lib/whowas/validatable.rb
Whowas.Validatable.validate
def validate(input) (check_exists(required_inputs, input) && check_format(input_formats, input)) || (raise Errors::InvalidInput, "Invalid input for #{self.class.name}") end
ruby
def validate(input) (check_exists(required_inputs, input) && check_format(input_formats, input)) || (raise Errors::InvalidInput, "Invalid input for #{self.class.name}") end
[ "def", "validate", "(", "input", ")", "(", "check_exists", "(", "required_inputs", ",", "input", ")", "&&", "check_format", "(", "input_formats", ",", "input", ")", ")", "||", "(", "raise", "Errors", "::", "InvalidInput", ",", "\"Invalid input for #{self.class.n...
Checks for required inputs and input formats that the adapter will need to process the search. It does *not* matter if there are other, non-required parameters in the input hash; they will be ignored later.
[ "Checks", "for", "required", "inputs", "and", "input", "formats", "that", "the", "adapter", "will", "need", "to", "process", "the", "search", "." ]
65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c
https://github.com/TuftsUniversity/whowas/blob/65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c/lib/whowas/validatable.rb#L8-L12
train
TuftsUniversity/whowas
lib/whowas/validatable.rb
Whowas.Validatable.check_exists
def check_exists(required, input) required.inject(true) do |result, key| input[key] && result end end
ruby
def check_exists(required, input) required.inject(true) do |result, key| input[key] && result end end
[ "def", "check_exists", "(", "required", ",", "input", ")", "required", ".", "inject", "(", "true", ")", "do", "|", "result", ",", "key", "|", "input", "[", "key", "]", "&&", "result", "end", "end" ]
Required keys must exist in the input hash and must have a non-nil, non-empty value.
[ "Required", "keys", "must", "exist", "in", "the", "input", "hash", "and", "must", "have", "a", "non", "-", "nil", "non", "-", "empty", "value", "." ]
65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c
https://github.com/TuftsUniversity/whowas/blob/65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c/lib/whowas/validatable.rb#L29-L33
train
Noah2610/MachineConfigure
lib/machine_configure/exporter.rb
MachineConfigure.Exporter.get_files
def get_files return @dir.values.map do |dir| next get_files_recursively_from dir end .reject { |x| !x } .flatten end
ruby
def get_files return @dir.values.map do |dir| next get_files_recursively_from dir end .reject { |x| !x } .flatten end
[ "def", "get_files", "return", "@dir", ".", "values", ".", "map", "do", "|", "dir", "|", "next", "get_files_recursively_from", "dir", "end", ".", "reject", "{", "|", "x", "|", "!", "x", "}", ".", "flatten", "end" ]
Returns all necessary filepaths.
[ "Returns", "all", "necessary", "filepaths", "." ]
8dc94112a1da91a72fa32b84dc53ac41ec0ec00a
https://github.com/Noah2610/MachineConfigure/blob/8dc94112a1da91a72fa32b84dc53ac41ec0ec00a/lib/machine_configure/exporter.rb#L42-L46
train
mufid/kanade
lib/kanade/engine.rb
Kanade.Engine.deserialize_object
def deserialize_object(definition, hash) return nil if hash.nil? result = definition.new result.__fields.each do |field| name = field.key_json || name_to_json(field.sym) if field.options[:as] == :list value = deserialize_list(hash[name], field) elsif field.options[:as] == :dto value = deserialize_object(field.options[:of], hash[name]) else value = hash[name] end next if value.nil? result.send("#{field.key_ruby}=", value) end result end
ruby
def deserialize_object(definition, hash) return nil if hash.nil? result = definition.new result.__fields.each do |field| name = field.key_json || name_to_json(field.sym) if field.options[:as] == :list value = deserialize_list(hash[name], field) elsif field.options[:as] == :dto value = deserialize_object(field.options[:of], hash[name]) else value = hash[name] end next if value.nil? result.send("#{field.key_ruby}=", value) end result end
[ "def", "deserialize_object", "(", "definition", ",", "hash", ")", "return", "nil", "if", "hash", ".", "nil?", "result", "=", "definition", ".", "new", "result", ".", "__fields", ".", "each", "do", "|", "field", "|", "name", "=", "field", ".", "key_json",...
IF engine contains deserialization logic, we can no more unit test the converters. Seems like, the conversion logic must be outsourced to its respective converter
[ "IF", "engine", "contains", "deserialization", "logic", "we", "can", "no", "more", "unit", "test", "the", "converters", ".", "Seems", "like", "the", "conversion", "logic", "must", "be", "outsourced", "to", "its", "respective", "converter" ]
b0666e306df89d19fed87e956d82ca869a647006
https://github.com/mufid/kanade/blob/b0666e306df89d19fed87e956d82ca869a647006/lib/kanade/engine.rb#L70-L89
train
seamusabshere/cohort_scope
lib/cohort_scope/big_cohort.rb
CohortScope.BigCohort.reduce!
def reduce! @reduced_characteristics = if @reduced_characteristics.keys.length < 2 {} else most_restrictive_characteristic = @reduced_characteristics.keys.max_by do |key| conditions = CohortScope.conditions_for @reduced_characteristics.except(key) @active_record_relation.where(conditions).count end @reduced_characteristics.except most_restrictive_characteristic end end
ruby
def reduce! @reduced_characteristics = if @reduced_characteristics.keys.length < 2 {} else most_restrictive_characteristic = @reduced_characteristics.keys.max_by do |key| conditions = CohortScope.conditions_for @reduced_characteristics.except(key) @active_record_relation.where(conditions).count end @reduced_characteristics.except most_restrictive_characteristic end end
[ "def", "reduce!", "@reduced_characteristics", "=", "if", "@reduced_characteristics", ".", "keys", ".", "length", "<", "2", "{", "}", "else", "most_restrictive_characteristic", "=", "@reduced_characteristics", ".", "keys", ".", "max_by", "do", "|", "key", "|", "con...
Reduce characteristics by removing them one by one and counting the results. The characteristic whose removal leads to the highest record count is removed from the overall characteristic set.
[ "Reduce", "characteristics", "by", "removing", "them", "one", "by", "one", "and", "counting", "the", "results", "." ]
62e2f67a4bfeaae9c8befce318bf0a9bb40e4350
https://github.com/seamusabshere/cohort_scope/blob/62e2f67a4bfeaae9c8befce318bf0a9bb40e4350/lib/cohort_scope/big_cohort.rb#L6-L16
train
ryanuber/ruby-aptly
lib/aptly/snapshot.rb
Aptly.Snapshot.pull
def pull name, source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true if packages.length == 0 raise AptlyError.new "1 or more package names are required" end cmd = 'aptly snapshot pull' cmd += ' -no-deps' if !deps cmd += ' -no-remove' if !remove cmd += " #{name.quote} #{source.quote} #{dest.quote}" if !packages.empty? packages.each {|p| cmd += " #{p.quote}"} end Aptly::runcmd cmd Aptly::Snapshot.new dest end
ruby
def pull name, source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true if packages.length == 0 raise AptlyError.new "1 or more package names are required" end cmd = 'aptly snapshot pull' cmd += ' -no-deps' if !deps cmd += ' -no-remove' if !remove cmd += " #{name.quote} #{source.quote} #{dest.quote}" if !packages.empty? packages.each {|p| cmd += " #{p.quote}"} end Aptly::runcmd cmd Aptly::Snapshot.new dest end
[ "def", "pull", "name", ",", "source", ",", "dest", ",", "kwargs", "=", "{", "}", "packages", "=", "kwargs", ".", "arg", ":packages", ",", "[", "]", "deps", "=", "kwargs", ".", "arg", ":deps", ",", "true", "remove", "=", "kwargs", ".", "arg", ":remo...
Pull packages from a snapshot into another, creating a new snapshot. == Parameters: name:: The name of the snapshot to pull to source:: The repository containing the packages to pull in dest:: The name for the new snapshot which will be created packages:: An array of package names to search deps:: When true, process dependencies remove:: When true, removes package versions not found in source
[ "Pull", "packages", "from", "a", "snapshot", "into", "another", "creating", "a", "new", "snapshot", "." ]
9581c38da30119d6a61b7ddac6334ab17fc67164
https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/snapshot.rb#L200-L219
train
ryanuber/ruby-aptly
lib/aptly/snapshot.rb
Aptly.Snapshot.pull_from
def pull_from source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true pull @name, source, dest, :packages => packages, :deps => deps, :remove => remove end
ruby
def pull_from source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true pull @name, source, dest, :packages => packages, :deps => deps, :remove => remove end
[ "def", "pull_from", "source", ",", "dest", ",", "kwargs", "=", "{", "}", "packages", "=", "kwargs", ".", "arg", ":packages", ",", "[", "]", "deps", "=", "kwargs", ".", "arg", ":deps", ",", "true", "remove", "=", "kwargs", ".", "arg", ":remove", ",", ...
Shortcut method to pull packages to the current snapshot
[ "Shortcut", "method", "to", "pull", "packages", "to", "the", "current", "snapshot" ]
9581c38da30119d6a61b7ddac6334ab17fc67164
https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/snapshot.rb#L223-L229
train
bradfeehan/derelict
lib/derelict/parser/status.rb
Derelict.Parser::Status.exists?
def exists?(vm_name = nil) return (vm_names.count > 0) if vm_name.nil? vm_names.include? vm_name.to_sym end
ruby
def exists?(vm_name = nil) return (vm_names.count > 0) if vm_name.nil? vm_names.include? vm_name.to_sym end
[ "def", "exists?", "(", "vm_name", "=", "nil", ")", "return", "(", "vm_names", ".", "count", ">", "0", ")", "if", "vm_name", ".", "nil?", "vm_names", ".", "include?", "vm_name", ".", "to_sym", "end" ]
Determines if a particular virtual machine exists in the output * vm_name: The name of the virtual machine to look for
[ "Determines", "if", "a", "particular", "virtual", "machine", "exists", "in", "the", "output" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/status.rb#L32-L35
train
bradfeehan/derelict
lib/derelict/parser/status.rb
Derelict.Parser::Status.state
def state(vm_name) unless states.include? vm_name.to_sym raise Derelict::VirtualMachine::NotFound.new vm_name end states[vm_name.to_sym] end
ruby
def state(vm_name) unless states.include? vm_name.to_sym raise Derelict::VirtualMachine::NotFound.new vm_name end states[vm_name.to_sym] end
[ "def", "state", "(", "vm_name", ")", "unless", "states", ".", "include?", "vm_name", ".", "to_sym", "raise", "Derelict", "::", "VirtualMachine", "::", "NotFound", ".", "new", "vm_name", "end", "states", "[", "vm_name", ".", "to_sym", "]", "end" ]
Determines the state of a particular virtual machine The state is returned as a symbol, e.g. :running. * vm_name: The name of the virtual machine to retrieve state
[ "Determines", "the", "state", "of", "a", "particular", "virtual", "machine" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/status.rb#L42-L48
train
bradfeehan/derelict
lib/derelict/parser/status.rb
Derelict.Parser::Status.vm_lines
def vm_lines output.match(PARSE_LIST_FROM_OUTPUT).tap {|list| logger.debug "Parsing VM list from output using #{description}" raise InvalidFormat.new "Couldn't find VM list" if list.nil? }.captures[0].lines end
ruby
def vm_lines output.match(PARSE_LIST_FROM_OUTPUT).tap {|list| logger.debug "Parsing VM list from output using #{description}" raise InvalidFormat.new "Couldn't find VM list" if list.nil? }.captures[0].lines end
[ "def", "vm_lines", "output", ".", "match", "(", "PARSE_LIST_FROM_OUTPUT", ")", ".", "tap", "{", "|", "list", "|", "logger", ".", "debug", "\"Parsing VM list from output using #{description}\"", "raise", "InvalidFormat", ".", "new", "\"Couldn't find VM list\"", "if", "...
Retrieves the virtual machine list section of the output
[ "Retrieves", "the", "virtual", "machine", "list", "section", "of", "the", "output" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/status.rb#L59-L64
train
marcboeker/mongolicious
lib/mongolicious/db.rb
Mongolicious.DB.get_opts
def get_opts(db_uri) uri = URI.parse(db_uri) { :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password, :db => uri.path.gsub('/', '') } end
ruby
def get_opts(db_uri) uri = URI.parse(db_uri) { :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password, :db => uri.path.gsub('/', '') } end
[ "def", "get_opts", "(", "db_uri", ")", "uri", "=", "URI", ".", "parse", "(", "db_uri", ")", "{", ":host", "=>", "uri", ".", "host", ",", ":port", "=>", "uri", ".", "port", ",", ":user", "=>", "uri", ".", "user", ",", ":password", "=>", "uri", "."...
Initialize a ne DB object. @return [DB] Parse the MongoDB URI. @param [String] db_uri the DB URI. @return [Hash]
[ "Initialize", "a", "ne", "DB", "object", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/db.rb#L16-L26
train
marcboeker/mongolicious
lib/mongolicious/db.rb
Mongolicious.DB.dump
def dump(db, path) Mongolicious.logger.info("Dumping database #{db[:db]}") cmd = "mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}" cmd << " -u '#{db[:user]}' -p '#{db[:password]}'" unless (db[:user].nil? || db[:user].empty?) cmd << " > /dev/null" system(cmd) raise "Error while backuing up #{db[:db]}" if $?.to_i != 0 end
ruby
def dump(db, path) Mongolicious.logger.info("Dumping database #{db[:db]}") cmd = "mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}" cmd << " -u '#{db[:user]}' -p '#{db[:password]}'" unless (db[:user].nil? || db[:user].empty?) cmd << " > /dev/null" system(cmd) raise "Error while backuing up #{db[:db]}" if $?.to_i != 0 end
[ "def", "dump", "(", "db", ",", "path", ")", "Mongolicious", ".", "logger", ".", "info", "(", "\"Dumping database #{db[:db]}\"", ")", "cmd", "=", "\"mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}\"", "cmd", "<<", "\" -u '#{db[:user]}' -p '#{db[:password]}'\"",...
Dump database using mongodump. @param [Hash] db the DB connection opts. @param [String] path the path, where the dump should be stored. @return [nil]
[ "Dump", "database", "using", "mongodump", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/db.rb#L34-L43
train
postmodern/wsoc
lib/wsoc/runner.rb
WSOC.Runner.run
def run(*args) optparse(*args) options = { :env => :production, :host => @host, :port => @port } options.merge!(:server => @handler) if @handler App.run!(options) end
ruby
def run(*args) optparse(*args) options = { :env => :production, :host => @host, :port => @port } options.merge!(:server => @handler) if @handler App.run!(options) end
[ "def", "run", "(", "*", "args", ")", "optparse", "(", "*", "args", ")", "options", "=", "{", ":env", "=>", ":production", ",", ":host", "=>", "@host", ",", ":port", "=>", "@port", "}", "options", ".", "merge!", "(", ":server", "=>", "@handler", ")", ...
Runs the runner. @param [Array<String>] args The arguments to run the runner with. @since 0.1.0
[ "Runs", "the", "runner", "." ]
b8b82f0cef0fd8594c48c45d3b213bc65412b455
https://github.com/postmodern/wsoc/blob/b8b82f0cef0fd8594c48c45d3b213bc65412b455/lib/wsoc/runner.rb#L67-L79
train
rodrigopinto/biju
lib/biju/modem.rb
Biju.Modem.messages
def messages(which = "ALL") # read message from all storage in the mobile phone (sim+mem) cmd('AT+CPMS="MT"') # get message list sms = cmd('AT+CMGL="%s"' % which ) # collect messages msgs = sms.scan(/\+CMGL\:\s*?(\d+)\,.*?\,\"(.+?)\"\,.*?\,\"(.+?)\".*?\n(.*)/) return nil unless msgs msgs.collect!{ |msg| Biju::Sms.new(:id => msg[0], :phone_number => msg[1], :datetime => msg[2], :message => msg[3].chomp) } end
ruby
def messages(which = "ALL") # read message from all storage in the mobile phone (sim+mem) cmd('AT+CPMS="MT"') # get message list sms = cmd('AT+CMGL="%s"' % which ) # collect messages msgs = sms.scan(/\+CMGL\:\s*?(\d+)\,.*?\,\"(.+?)\"\,.*?\,\"(.+?)\".*?\n(.*)/) return nil unless msgs msgs.collect!{ |msg| Biju::Sms.new(:id => msg[0], :phone_number => msg[1], :datetime => msg[2], :message => msg[3].chomp) } end
[ "def", "messages", "(", "which", "=", "\"ALL\"", ")", "cmd", "(", "'AT+CPMS=\"MT\"'", ")", "sms", "=", "cmd", "(", "'AT+CMGL=\"%s\"'", "%", "which", ")", "msgs", "=", "sms", ".", "scan", "(", "/", "\\+", "\\:", "\\s", "\\d", "\\,", "\\,", "\\\"", "\\...
Return an Array of Sms if there is messages nad return nil if not.
[ "Return", "an", "Array", "of", "Sms", "if", "there", "is", "messages", "nad", "return", "nil", "if", "not", "." ]
898d8d73a9cac0f6bca68731927c37343b9e0ff6
https://github.com/rodrigopinto/biju/blob/898d8d73a9cac0f6bca68731927c37343b9e0ff6/lib/biju/modem.rb#L34-L43
train
djhworld/gmail-mailer
lib/gmail-mailer.rb
GmailMailer.Mailer.send_smtp
def send_smtp(mail) smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT) smtp.enable_starttls_auto secret = { :consumer_key => SMTP_CONSUMER_KEY, :consumer_secret => SMTP_CONSUMER_SECRET, :token => @email_credentials[:smtp_oauth_token], :token_secret => @email_credentials[:smtp_oauth_token_secret] } smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session| print "Sending message..." session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations) puts ".sent!" end end
ruby
def send_smtp(mail) smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT) smtp.enable_starttls_auto secret = { :consumer_key => SMTP_CONSUMER_KEY, :consumer_secret => SMTP_CONSUMER_SECRET, :token => @email_credentials[:smtp_oauth_token], :token_secret => @email_credentials[:smtp_oauth_token_secret] } smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session| print "Sending message..." session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations) puts ".sent!" end end
[ "def", "send_smtp", "(", "mail", ")", "smtp", "=", "Net", "::", "SMTP", ".", "new", "(", "SMTP_SERVER", ",", "SMTP_PORT", ")", "smtp", ".", "enable_starttls_auto", "secret", "=", "{", ":consumer_key", "=>", "SMTP_CONSUMER_KEY", ",", ":consumer_secret", "=>", ...
Use gmail_xoauth to send email
[ "Use", "gmail_xoauth", "to", "send", "email" ]
b63c259d124950b612d20bcad1e82d260984f0e9
https://github.com/djhworld/gmail-mailer/blob/b63c259d124950b612d20bcad1e82d260984f0e9/lib/gmail-mailer.rb#L49-L63
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_404_public_file!
def render_404_public_file!(file_name) four_oh_four_path = File.expand_path("#{file_name}.html", settings.public_dir) return unless File.file?(four_oh_four_path) send_file four_oh_four_path, status: 404 end
ruby
def render_404_public_file!(file_name) four_oh_four_path = File.expand_path("#{file_name}.html", settings.public_dir) return unless File.file?(four_oh_four_path) send_file four_oh_four_path, status: 404 end
[ "def", "render_404_public_file!", "(", "file_name", ")", "four_oh_four_path", "=", "File", ".", "expand_path", "(", "\"#{file_name}.html\"", ",", "settings", ".", "public_dir", ")", "return", "unless", "File", ".", "file?", "(", "four_oh_four_path", ")", "send_file"...
Given a file name, attempts to send an public 404 file, if it exists, and halt @param [String] file_name
[ "Given", "a", "file", "name", "attempts", "to", "send", "an", "public", "404", "file", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L275-L279
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_404_template!
def render_404_template!(template_name) VIEW_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.views, template_name, engine) do |file| next unless File.file?(file) halt send(extension, template_name.to_sym, layout: false) end end end
ruby
def render_404_template!(template_name) VIEW_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.views, template_name, engine) do |file| next unless File.file?(file) halt send(extension, template_name.to_sym, layout: false) end end end
[ "def", "render_404_template!", "(", "template_name", ")", "VIEW_TEMPLATE_ENGINES", ".", "each", "do", "|", "engine", ",", "extension", "|", "@preferred_extension", "=", "extension", ".", "to_s", "find_template", "(", "settings", ".", "views", ",", "template_name", ...
Given a template name, and with a prioritized list of template engines, attempts to render a 404 template, if one exists, and halt. @param [String] template_name @see VIEW_TEMPLATE_ENGINES
[ "Given", "a", "template", "name", "and", "with", "a", "prioritized", "list", "of", "template", "engines", "attempts", "to", "render", "a", "404", "template", "if", "one", "exists", "and", "halt", "." ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L287-L295
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_javascript_template!
def render_javascript_template!(uri_path) javascript_match = File.join(settings.javascripts, "*") javascript_path = File.expand_path(uri_path, settings.javascripts) return unless File.fnmatch(javascript_match, javascript_path) JAVASCRIPT_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.javascripts, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.javascripts) end end end
ruby
def render_javascript_template!(uri_path) javascript_match = File.join(settings.javascripts, "*") javascript_path = File.expand_path(uri_path, settings.javascripts) return unless File.fnmatch(javascript_match, javascript_path) JAVASCRIPT_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.javascripts, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.javascripts) end end end
[ "def", "render_javascript_template!", "(", "uri_path", ")", "javascript_match", "=", "File", ".", "join", "(", "settings", ".", "javascripts", ",", "\"*\"", ")", "javascript_path", "=", "File", ".", "expand_path", "(", "uri_path", ",", "settings", ".", "javascri...
Given a URI path, attempts to render a JavaScript template, if it exists, and halt @param [String] uri_path @see JAVASCRIPT_TEMPLATE_ENGINES
[ "Given", "a", "URI", "path", "attempts", "to", "render", "a", "JavaScript", "template", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L355-L368
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_stylesheet_template!
def render_stylesheet_template!(uri_path) stylesheet_match = File.join(settings.stylesheets, "*") stylesheet_path = File.expand_path(uri_path, settings.stylesheets) return unless File.fnmatch(stylesheet_match, stylesheet_path) STYLESHEET_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.stylesheets, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.stylesheets) end end end
ruby
def render_stylesheet_template!(uri_path) stylesheet_match = File.join(settings.stylesheets, "*") stylesheet_path = File.expand_path(uri_path, settings.stylesheets) return unless File.fnmatch(stylesheet_match, stylesheet_path) STYLESHEET_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.stylesheets, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.stylesheets) end end end
[ "def", "render_stylesheet_template!", "(", "uri_path", ")", "stylesheet_match", "=", "File", ".", "join", "(", "settings", ".", "stylesheets", ",", "\"*\"", ")", "stylesheet_path", "=", "File", ".", "expand_path", "(", "uri_path", ",", "settings", ".", "styleshe...
Given a URI path, attempts to render a stylesheet template, if it exists, and halt @param [String] uri_path @see STYLESHEET_TEMPLATE_ENGINES
[ "Given", "a", "URI", "path", "attempts", "to", "render", "a", "stylesheet", "template", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L425-L438
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_index_file!
def render_index_file!(uri_path) return unless URI.directory?(uri_path) index_match = File.join(settings.public_dir, "*") index_file_path = File.expand_path(uri_path + "index.html", settings.public_dir) return unless File.fnmatch(index_match, index_file_path) return unless File.file?(index_file_path) send_file index_file_path end
ruby
def render_index_file!(uri_path) return unless URI.directory?(uri_path) index_match = File.join(settings.public_dir, "*") index_file_path = File.expand_path(uri_path + "index.html", settings.public_dir) return unless File.fnmatch(index_match, index_file_path) return unless File.file?(index_file_path) send_file index_file_path end
[ "def", "render_index_file!", "(", "uri_path", ")", "return", "unless", "URI", ".", "directory?", "(", "uri_path", ")", "index_match", "=", "File", ".", "join", "(", "settings", ".", "public_dir", ",", "\"*\"", ")", "index_file_path", "=", "File", ".", "expan...
Given a URI path, attempts to send an index.html file, if it exists, and halt @param [String] uri_path
[ "Given", "a", "URI", "path", "attempts", "to", "send", "an", "index", ".", "html", "file", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L504-L514
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_content_page!
def render_content_page!(uri_path) uri_path += "index" if URI.directory?(uri_path) content_match = File.join(settings.content, "*") content_page_path = File.expand_path(uri_path, settings.content) return unless File.fnmatch(content_match, content_page_path) begin content_page = find_content_page(uri_path) rescue ContentPageNotFound return end view_template_path = File.expand_path(content_page.view, settings.views) begin engine = VIEW_TEMPLATE_ENGINES.fetch(Tilt[content_page.view]) rescue KeyError message = "Cannot find registered engine for view template file -- #{view_template_path}" raise RegisteredEngineNotFound, message end begin halt send(engine, content_page.view.to_s.templatize, locals: { page: content_page }) rescue Errno::ENOENT message = "Cannot find view template file -- #{view_template_path}" raise ViewTemplateNotFound, message end end
ruby
def render_content_page!(uri_path) uri_path += "index" if URI.directory?(uri_path) content_match = File.join(settings.content, "*") content_page_path = File.expand_path(uri_path, settings.content) return unless File.fnmatch(content_match, content_page_path) begin content_page = find_content_page(uri_path) rescue ContentPageNotFound return end view_template_path = File.expand_path(content_page.view, settings.views) begin engine = VIEW_TEMPLATE_ENGINES.fetch(Tilt[content_page.view]) rescue KeyError message = "Cannot find registered engine for view template file -- #{view_template_path}" raise RegisteredEngineNotFound, message end begin halt send(engine, content_page.view.to_s.templatize, locals: { page: content_page }) rescue Errno::ENOENT message = "Cannot find view template file -- #{view_template_path}" raise ViewTemplateNotFound, message end end
[ "def", "render_content_page!", "(", "uri_path", ")", "uri_path", "+=", "\"index\"", "if", "URI", ".", "directory?", "(", "uri_path", ")", "content_match", "=", "File", ".", "join", "(", "settings", ".", "content", ",", "\"*\"", ")", "content_page_path", "=", ...
Given a URI path, attempts to render a content page, if it exists, and halt @param [String] uri_path @raise [RegisteredEngineNotFound] Raised when a registered engine for the content page's view template cannot be found @raise [ViewTemplateNotFound] Raised when the content page's view template cannot be found
[ "Given", "a", "URI", "path", "attempts", "to", "render", "a", "content", "page", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L533-L561
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.find_content_page
def find_content_page(uri_path) ContentPage::TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.content, uri_path, engine) do |file| next unless File.file?(file) return ContentPage.new(data: File.read(file), engine: engine) end end raise ContentPageNotFound, "Cannot find content page for path -- #{uri_path}" end
ruby
def find_content_page(uri_path) ContentPage::TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.content, uri_path, engine) do |file| next unless File.file?(file) return ContentPage.new(data: File.read(file), engine: engine) end end raise ContentPageNotFound, "Cannot find content page for path -- #{uri_path}" end
[ "def", "find_content_page", "(", "uri_path", ")", "ContentPage", "::", "TEMPLATE_ENGINES", ".", "each", "do", "|", "engine", ",", "extension", "|", "@preferred_extension", "=", "extension", ".", "to_s", "find_template", "(", "settings", ".", "content", ",", "uri...
Given a URI path, creates a new `ContentPage` instance by searching for and reading a content file from disk. Content files are searched consecutively until a page with a supported content page template engine is found. @param [String] uri_path @raise [ContentPageNotFound] Raised when a content page cannot be found for the uri path @return [ContentPage] A new instance is created and returned when found @see ContentPage::TEMPLATE_ENGINES
[ "Given", "a", "URI", "path", "creates", "a", "new", "ContentPage", "instance", "by", "searching", "for", "and", "reading", "a", "content", "file", "from", "disk", ".", "Content", "files", "are", "searched", "consecutively", "until", "a", "page", "with", "a",...
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L572-L582
train
skift/estore_conventions
lib/estore_conventions.rb
EstoreConventions.ClassMethods.factory_build_for_store
def factory_build_for_store(atts_hash, identifier_conditions = {}, full_data_object={}, &blk) if identifier_conditions.empty? record = self.new else record = self.where(identifier_conditions).first_or_initialize end record.assign_attributes(atts_hash, :without_protection => true) if block_given? yield record, full_data_object end return record end
ruby
def factory_build_for_store(atts_hash, identifier_conditions = {}, full_data_object={}, &blk) if identifier_conditions.empty? record = self.new else record = self.where(identifier_conditions).first_or_initialize end record.assign_attributes(atts_hash, :without_protection => true) if block_given? yield record, full_data_object end return record end
[ "def", "factory_build_for_store", "(", "atts_hash", ",", "identifier_conditions", "=", "{", "}", ",", "full_data_object", "=", "{", "}", ",", "&", "blk", ")", "if", "identifier_conditions", ".", "empty?", "record", "=", "self", ".", "new", "else", "record", ...
atts_hash are the attributes to assign to the Record identifier_conditions is what the scope for first_or_initialize is called upon so that an existing object is updated full_data_object is passed in to be saved as a blob
[ "atts_hash", "are", "the", "attributes", "to", "assign", "to", "the", "Record", "identifier_conditions", "is", "what", "the", "scope", "for", "first_or_initialize", "is", "called", "upon", "so", "that", "an", "existing", "object", "is", "updated", "full_data_objec...
b9f1dfa45d476ecbadaa0a50729aeef064961183
https://github.com/skift/estore_conventions/blob/b9f1dfa45d476ecbadaa0a50729aeef064961183/lib/estore_conventions.rb#L40-L53
train
wwidea/rexport
lib/rexport/tree_node.rb
Rexport.TreeNode.add_child
def add_child(*names) names.flatten! return unless name = names.shift node = children.find { |c| c.name == name } node ? node.add_child(names) : (children << TreeNode.new(name, names)) end
ruby
def add_child(*names) names.flatten! return unless name = names.shift node = children.find { |c| c.name == name } node ? node.add_child(names) : (children << TreeNode.new(name, names)) end
[ "def", "add_child", "(", "*", "names", ")", "names", ".", "flatten!", "return", "unless", "name", "=", "names", ".", "shift", "node", "=", "children", ".", "find", "{", "|", "c", "|", "c", ".", "name", "==", "name", "}", "node", "?", "node", ".", ...
Initialize a tree node setting name and adding a child if one was passed Add one or more children to the tree
[ "Initialize", "a", "tree", "node", "setting", "name", "and", "adding", "a", "child", "if", "one", "was", "passed", "Add", "one", "or", "more", "children", "to", "the", "tree" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/tree_node.rb#L14-L19
train
lkdjiin/bookmarks
lib/bookmarks/document.rb
Bookmarks.Document.parse_a_bookmark
def parse_a_bookmark line line = line.strip if line =~ /^<DT><H3/ @h3_tags << h3_tags(line) elsif line =~ /^<\/DL>/ @h3_tags.pop elsif line =~ /<DT><A HREF="http/ @bookmarks << NetscapeBookmark.from_string(line) if (not @h3_tags.empty?) && (not @bookmarks.last.nil?) @bookmarks.last.add_tags @h3_tags end elsif line =~ /^<DD>/ @bookmarks.last.description = line[4..-1].chomp end end
ruby
def parse_a_bookmark line line = line.strip if line =~ /^<DT><H3/ @h3_tags << h3_tags(line) elsif line =~ /^<\/DL>/ @h3_tags.pop elsif line =~ /<DT><A HREF="http/ @bookmarks << NetscapeBookmark.from_string(line) if (not @h3_tags.empty?) && (not @bookmarks.last.nil?) @bookmarks.last.add_tags @h3_tags end elsif line =~ /^<DD>/ @bookmarks.last.description = line[4..-1].chomp end end
[ "def", "parse_a_bookmark", "line", "line", "=", "line", ".", "strip", "if", "line", "=~", "/", "/", "@h3_tags", "<<", "h3_tags", "(", "line", ")", "elsif", "line", "=~", "/", "\\/", "/", "@h3_tags", ".", "pop", "elsif", "line", "=~", "/", "/", "@book...
Parse a single line from a bookmarks file. line - String. Returns nothing. TODO This should have its own parser class.
[ "Parse", "a", "single", "line", "from", "a", "bookmarks", "file", "." ]
6f6bdf94f2de5347a9db19d01ad0721033cf0123
https://github.com/lkdjiin/bookmarks/blob/6f6bdf94f2de5347a9db19d01ad0721033cf0123/lib/bookmarks/document.rb#L78-L92
train
nickcharlton/atlas-ruby
lib/atlas/box_version.rb
Atlas.BoxVersion.save
def save # rubocop:disable Metrics/AbcSize body = { version: to_hash } # providers are saved seperately body[:version].delete(:providers) begin response = Atlas.client.put(url_builder.box_version_url, body: body) rescue Atlas::Errors::NotFoundError response = Atlas.client.post("#{url_builder.box_url}/versions", body: body) end # trigger the same on the providers providers.each(&:save) if providers update_with_response(response, [:providers]) end
ruby
def save # rubocop:disable Metrics/AbcSize body = { version: to_hash } # providers are saved seperately body[:version].delete(:providers) begin response = Atlas.client.put(url_builder.box_version_url, body: body) rescue Atlas::Errors::NotFoundError response = Atlas.client.post("#{url_builder.box_url}/versions", body: body) end # trigger the same on the providers providers.each(&:save) if providers update_with_response(response, [:providers]) end
[ "def", "save", "body", "=", "{", "version", ":", "to_hash", "}", "body", "[", ":version", "]", ".", "delete", "(", ":providers", ")", "begin", "response", "=", "Atlas", ".", "client", ".", "put", "(", "url_builder", ".", "box_version_url", ",", "body", ...
Save the version. @return [Hash] Atlas response object.
[ "Save", "the", "version", "." ]
2170c04496682e0d8e7c959bd9f267f62fa84c1d
https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box_version.rb#L80-L97
train
sight-labs/enchanted_quill
lib/enchanted_quill/label.rb
EnchantedQuill.Label.textRectForBounds
def textRectForBounds(bounds, limitedToNumberOfLines: num_of_lines) required_rect = rect_fitting_text_for_container_size(bounds.size, for_number_of_line: num_of_lines) text_container.size = required_rect.size required_rect end
ruby
def textRectForBounds(bounds, limitedToNumberOfLines: num_of_lines) required_rect = rect_fitting_text_for_container_size(bounds.size, for_number_of_line: num_of_lines) text_container.size = required_rect.size required_rect end
[ "def", "textRectForBounds", "(", "bounds", ",", "limitedToNumberOfLines", ":", "num_of_lines", ")", "required_rect", "=", "rect_fitting_text_for_container_size", "(", "bounds", ".", "size", ",", "for_number_of_line", ":", "num_of_lines", ")", "text_container", ".", "siz...
Override UILabel Methods
[ "Override", "UILabel", "Methods" ]
d8c70f50fea320878249fec7ed3ea134a4975f32
https://github.com/sight-labs/enchanted_quill/blob/d8c70f50fea320878249fec7ed3ea134a4975f32/lib/enchanted_quill/label.rb#L66-L70
train
sight-labs/enchanted_quill
lib/enchanted_quill/label.rb
EnchantedQuill.Label.add_link_attribute
def add_link_attribute(mut_attr_string) range_pointer = Pointer.new(NSRange.type) attributes = mut_attr_string.attributesAtIndex(0, effectiveRange: range_pointer).dup attributes[NSFontAttributeName] = self.font attributes[NSForegroundColorAttributeName] = self.textColor mut_attr_string.addAttributes(attributes, range: range_pointer[0]) active_elements.each do |type, elements| case type when :mention then attributes[NSForegroundColorAttributeName] = mention_color when :hashtag then attributes[NSForegroundColorAttributeName] = hashtag_color when :url then attributes[NSForegroundColorAttributeName] = url_color when :category then attributes[NSForegroundColorAttributeName] = category_color end elements.each do |element| mut_attr_string.setAttributes(attributes, range: element.range) end end end
ruby
def add_link_attribute(mut_attr_string) range_pointer = Pointer.new(NSRange.type) attributes = mut_attr_string.attributesAtIndex(0, effectiveRange: range_pointer).dup attributes[NSFontAttributeName] = self.font attributes[NSForegroundColorAttributeName] = self.textColor mut_attr_string.addAttributes(attributes, range: range_pointer[0]) active_elements.each do |type, elements| case type when :mention then attributes[NSForegroundColorAttributeName] = mention_color when :hashtag then attributes[NSForegroundColorAttributeName] = hashtag_color when :url then attributes[NSForegroundColorAttributeName] = url_color when :category then attributes[NSForegroundColorAttributeName] = category_color end elements.each do |element| mut_attr_string.setAttributes(attributes, range: element.range) end end end
[ "def", "add_link_attribute", "(", "mut_attr_string", ")", "range_pointer", "=", "Pointer", ".", "new", "(", "NSRange", ".", "type", ")", "attributes", "=", "mut_attr_string", ".", "attributesAtIndex", "(", "0", ",", "effectiveRange", ":", "range_pointer", ")", "...
add link attribute
[ "add", "link", "attribute" ]
d8c70f50fea320878249fec7ed3ea134a4975f32
https://github.com/sight-labs/enchanted_quill/blob/d8c70f50fea320878249fec7ed3ea134a4975f32/lib/enchanted_quill/label.rb#L384-L404
train
bradleyd/shelltastic
lib/shelltastic/utils.rb
ShellTastic.Utils.empty_nil_blank?
def empty_nil_blank?(str, raize=false) result = (str !~ /[^[:space:]]/ || str.nil? || str.empty?) raise ShellTastic::CommandException.new("Command is emtpy or nil") if result and raize result end
ruby
def empty_nil_blank?(str, raize=false) result = (str !~ /[^[:space:]]/ || str.nil? || str.empty?) raise ShellTastic::CommandException.new("Command is emtpy or nil") if result and raize result end
[ "def", "empty_nil_blank?", "(", "str", ",", "raize", "=", "false", ")", "result", "=", "(", "str", "!~", "/", "/", "||", "str", ".", "nil?", "||", "str", ".", "empty?", ")", "raise", "ShellTastic", "::", "CommandException", ".", "new", "(", "\"Command ...
like the other methods but allow to set an exception flag @param [String] str the string the needs to be checked @param [Boolean] to raise an exception or not. DEFAULT is false @return [Boolean] @return [ShellTastic::CommandException]
[ "like", "the", "other", "methods", "but", "allow", "to", "set", "an", "exception", "flag" ]
4004c2b98efb8882d5b702b9c5d69e15cc38cc38
https://github.com/bradleyd/shelltastic/blob/4004c2b98efb8882d5b702b9c5d69e15cc38cc38/lib/shelltastic/utils.rb#L25-L29
train
hamidp/nadb
lib/nadb.rb
Nadb.Tool.load_config
def load_config path = ENV['HOME'] + '/.nadb.config' if !File.exists?(path) return end @config = JSON.parse(File.read(path)) end
ruby
def load_config path = ENV['HOME'] + '/.nadb.config' if !File.exists?(path) return end @config = JSON.parse(File.read(path)) end
[ "def", "load_config", "path", "=", "ENV", "[", "'HOME'", "]", "+", "'/.nadb.config'", "if", "!", "File", ".", "exists?", "(", "path", ")", "return", "end", "@config", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "path", ")", ")", "end" ]
Load config from the file if any exists
[ "Load", "config", "from", "the", "file", "if", "any", "exists" ]
8d97f00045af988d551a1e9dc5aa076615628035
https://github.com/hamidp/nadb/blob/8d97f00045af988d551a1e9dc5aa076615628035/lib/nadb.rb#L41-L48
train
hamidp/nadb
lib/nadb.rb
Nadb.Tool.run_adb_command
def run_adb_command(command, device = nil) full_command = construct_adb_command command, device puts full_command pio = IO.popen(full_command, 'w') Process.wait(pio.pid) end
ruby
def run_adb_command(command, device = nil) full_command = construct_adb_command command, device puts full_command pio = IO.popen(full_command, 'w') Process.wait(pio.pid) end
[ "def", "run_adb_command", "(", "command", ",", "device", "=", "nil", ")", "full_command", "=", "construct_adb_command", "command", ",", "device", "puts", "full_command", "pio", "=", "IO", ".", "popen", "(", "full_command", ",", "'w'", ")", "Process", ".", "w...
Run an adb commd on specified device, optionally printing the output
[ "Run", "an", "adb", "commd", "on", "specified", "device", "optionally", "printing", "the", "output" ]
8d97f00045af988d551a1e9dc5aa076615628035
https://github.com/hamidp/nadb/blob/8d97f00045af988d551a1e9dc5aa076615628035/lib/nadb.rb#L66-L72
train
hamidp/nadb
lib/nadb.rb
Nadb.Tool.get_connected_devices
def get_connected_devices get_adb_command_output('devices') .drop(1) .map { |line| line.split[0] } .reject { |d| d.nil? || d.empty? } end
ruby
def get_connected_devices get_adb_command_output('devices') .drop(1) .map { |line| line.split[0] } .reject { |d| d.nil? || d.empty? } end
[ "def", "get_connected_devices", "get_adb_command_output", "(", "'devices'", ")", ".", "drop", "(", "1", ")", ".", "map", "{", "|", "line", "|", "line", ".", "split", "[", "0", "]", "}", ".", "reject", "{", "|", "d", "|", "d", ".", "nil?", "||", "d"...
Get all currently connected android devices
[ "Get", "all", "currently", "connected", "android", "devices" ]
8d97f00045af988d551a1e9dc5aa076615628035
https://github.com/hamidp/nadb/blob/8d97f00045af988d551a1e9dc5aa076615628035/lib/nadb.rb#L75-L80
train
fridge-cms/jekyll-fridge
lib/jekyll-fridge/fridge_filters.rb
Jekyll.FridgeFilters.fridge_asset
def fridge_asset(input) return input unless input if input.respond_to?('first') input = input.first['name'] end site = @context.registers[:site] asset_dir = site.config['fridge'].config['asset_dir'] dest_path = File.join(site.dest, asset_dir, input) path = File.join(asset_dir, input) # Check if file already exists if site.keep_files.index(path) != nil return "/#{path}" end asset = site.config['fridge'].client.get("content/upload/#{input}") return input unless asset # play for keeps # this is so jekyll won't clean up the file site.keep_files << path # write file to destination FileUtils.mkdir_p(File.dirname(dest_path)) File.write(dest_path, asset) "/#{path}" end
ruby
def fridge_asset(input) return input unless input if input.respond_to?('first') input = input.first['name'] end site = @context.registers[:site] asset_dir = site.config['fridge'].config['asset_dir'] dest_path = File.join(site.dest, asset_dir, input) path = File.join(asset_dir, input) # Check if file already exists if site.keep_files.index(path) != nil return "/#{path}" end asset = site.config['fridge'].client.get("content/upload/#{input}") return input unless asset # play for keeps # this is so jekyll won't clean up the file site.keep_files << path # write file to destination FileUtils.mkdir_p(File.dirname(dest_path)) File.write(dest_path, asset) "/#{path}" end
[ "def", "fridge_asset", "(", "input", ")", "return", "input", "unless", "input", "if", "input", ".", "respond_to?", "(", "'first'", ")", "input", "=", "input", ".", "first", "[", "'name'", "]", "end", "site", "=", "@context", ".", "registers", "[", ":site...
Filter for fetching assets Writes static file to asset_dir and returns absolute file path
[ "Filter", "for", "fetching", "assets", "Writes", "static", "file", "to", "asset_dir", "and", "returns", "absolute", "file", "path" ]
ac5fa7bd861ba6544ca14cf47eafcf0d15601e4c
https://github.com/fridge-cms/jekyll-fridge/blob/ac5fa7bd861ba6544ca14cf47eafcf0d15601e4c/lib/jekyll-fridge/fridge_filters.rb#L5-L31
train
lacravate/git-trifle
lib/git/trifle.rb
Git.Trifle.cover
def cover(path, options={}) reset = options.delete :reset cook_layer do @dressing << Proc.new { self.reset if commits.any? } if reset Git::Base.open path if can_cover? path end end
ruby
def cover(path, options={}) reset = options.delete :reset cook_layer do @dressing << Proc.new { self.reset if commits.any? } if reset Git::Base.open path if can_cover? path end end
[ "def", "cover", "(", "path", ",", "options", "=", "{", "}", ")", "reset", "=", "options", ".", "delete", ":reset", "cook_layer", "do", "@dressing", "<<", "Proc", ".", "new", "{", "self", ".", "reset", "if", "commits", ".", "any?", "}", "if", "reset",...
hands on the handler
[ "hands", "on", "the", "handler" ]
43d18284c5b772bb5a2ecd412e8d11d4e8444531
https://github.com/lacravate/git-trifle/blob/43d18284c5b772bb5a2ecd412e8d11d4e8444531/lib/git/trifle.rb#L54-L61
train
tubbo/active_copy
lib/active_copy/finders.rb
ActiveCopy.Finders.matches?
def matches? query query.reduce(true) do |matches, (key, value)| matches = if key == 'tag' return false unless tags.present? tags.include? value else attributes[key] == value end end end
ruby
def matches? query query.reduce(true) do |matches, (key, value)| matches = if key == 'tag' return false unless tags.present? tags.include? value else attributes[key] == value end end end
[ "def", "matches?", "query", "query", ".", "reduce", "(", "true", ")", "do", "|", "matches", ",", "(", "key", ",", "value", ")", "|", "matches", "=", "if", "key", "==", "'tag'", "return", "false", "unless", "tags", ".", "present?", "tags", ".", "inclu...
Test if the query matches this particular model.
[ "Test", "if", "the", "query", "matches", "this", "particular", "model", "." ]
63716fdd9283231e9ed0d8ac6af97633d3e97210
https://github.com/tubbo/active_copy/blob/63716fdd9283231e9ed0d8ac6af97633d3e97210/lib/active_copy/finders.rb#L9-L18
train
alfa-jpn/rails-kvs-driver
lib/rails_kvs_driver/validation_driver_config.rb
RailsKvsDriver.ValidationDriverConfig.validate_driver_config!
def validate_driver_config!(driver_config) raise_argument_error!(:host) unless driver_config.has_key? :host raise_argument_error!(:port) unless driver_config.has_key? :port raise_argument_error!(:namespace) unless driver_config.has_key? :namespace raise_argument_error!(:timeout_sec) unless driver_config.has_key? :timeout_sec raise_argument_error!(:pool_size) unless driver_config.has_key? :pool_size driver_config[:config_key] = :none unless driver_config.has_key? :config_key return driver_config end
ruby
def validate_driver_config!(driver_config) raise_argument_error!(:host) unless driver_config.has_key? :host raise_argument_error!(:port) unless driver_config.has_key? :port raise_argument_error!(:namespace) unless driver_config.has_key? :namespace raise_argument_error!(:timeout_sec) unless driver_config.has_key? :timeout_sec raise_argument_error!(:pool_size) unless driver_config.has_key? :pool_size driver_config[:config_key] = :none unless driver_config.has_key? :config_key return driver_config end
[ "def", "validate_driver_config!", "(", "driver_config", ")", "raise_argument_error!", "(", ":host", ")", "unless", "driver_config", ".", "has_key?", ":host", "raise_argument_error!", "(", ":port", ")", "unless", "driver_config", ".", "has_key?", ":port", "raise_argument...
Validate driver_config. This method raise ArgumentError, if missing driver_config. @param driver_config [Hash] driver config. @return [Hash] driver_config
[ "Validate", "driver_config", ".", "This", "method", "raise", "ArgumentError", "if", "missing", "driver_config", "." ]
0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982
https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/validation_driver_config.rb#L8-L18
train
jasonrclark/hometown
lib/hometown/creation_tracer.rb
Hometown.CreationTracer.update_on_instance_created
def update_on_instance_created(clazz, on_instance_created) return unless on_instance_created clazz.instance_eval do def instance_hooks hooks = (self.ancestors + [self]).map do |target| target.instance_variable_get(:@instance_hooks) end hooks.flatten! hooks.compact! hooks.uniq! hooks end @instance_hooks ||= [] @instance_hooks << on_instance_created end end
ruby
def update_on_instance_created(clazz, on_instance_created) return unless on_instance_created clazz.instance_eval do def instance_hooks hooks = (self.ancestors + [self]).map do |target| target.instance_variable_get(:@instance_hooks) end hooks.flatten! hooks.compact! hooks.uniq! hooks end @instance_hooks ||= [] @instance_hooks << on_instance_created end end
[ "def", "update_on_instance_created", "(", "clazz", ",", "on_instance_created", ")", "return", "unless", "on_instance_created", "clazz", ".", "instance_eval", "do", "def", "instance_hooks", "hooks", "=", "(", "self", ".", "ancestors", "+", "[", "self", "]", ")", ...
This hook allows other tracing in Hometown to get a whack at an object after it's been created without forcing them to patch new themselves
[ "This", "hook", "allows", "other", "tracing", "in", "Hometown", "to", "get", "a", "whack", "at", "an", "object", "after", "it", "s", "been", "created", "without", "forcing", "them", "to", "patch", "new", "themselves" ]
1d955bd684d5f9a81134332ae0b474252b793687
https://github.com/jasonrclark/hometown/blob/1d955bd684d5f9a81134332ae0b474252b793687/lib/hometown/creation_tracer.rb#L64-L81
train
mnipper/serket
lib/serket/field_encrypter.rb
Serket.FieldEncrypter.encrypt
def encrypt(field) return if field !~ /\S/ aes = OpenSSL::Cipher.new(symmetric_algorithm) aes_key = aes.random_key iv = aes.random_iv encrypt_data(iv, aes_key, field.force_encoding(encoding)) end
ruby
def encrypt(field) return if field !~ /\S/ aes = OpenSSL::Cipher.new(symmetric_algorithm) aes_key = aes.random_key iv = aes.random_iv encrypt_data(iv, aes_key, field.force_encoding(encoding)) end
[ "def", "encrypt", "(", "field", ")", "return", "if", "field", "!~", "/", "\\S", "/", "aes", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "symmetric_algorithm", ")", "aes_key", "=", "aes", ".", "random_key", "iv", "=", "aes", ".", "random_iv", "encr...
Return encrypted string according to specified format. Return nil if field is whitespace.
[ "Return", "encrypted", "string", "according", "to", "specified", "format", ".", "Return", "nil", "if", "field", "is", "whitespace", "." ]
a4606071fde8982d794ff1f8fc09c399ac92ba17
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_encrypter.rb#L22-L28
train
mnipper/serket
lib/serket/field_encrypter.rb
Serket.FieldEncrypter.parse
def parse(iv, encrypted_key, encrypted_text) case @format when :delimited [iv, field_delimiter, encrypted_key, field_delimiter, encrypted_text].join('') when :json hash = {} hash['iv'] = iv hash['key'] = encrypted_key hash['message'] = encrypted_text hash.to_json end end
ruby
def parse(iv, encrypted_key, encrypted_text) case @format when :delimited [iv, field_delimiter, encrypted_key, field_delimiter, encrypted_text].join('') when :json hash = {} hash['iv'] = iv hash['key'] = encrypted_key hash['message'] = encrypted_text hash.to_json end end
[ "def", "parse", "(", "iv", ",", "encrypted_key", ",", "encrypted_text", ")", "case", "@format", "when", ":delimited", "[", "iv", ",", "field_delimiter", ",", "encrypted_key", ",", "field_delimiter", ",", "encrypted_text", "]", ".", "join", "(", "''", ")", "w...
Format the final encrypted string to be returned depending on specified format.
[ "Format", "the", "final", "encrypted", "string", "to", "be", "returned", "depending", "on", "specified", "format", "." ]
a4606071fde8982d794ff1f8fc09c399ac92ba17
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_encrypter.rb#L55-L66
train
sunchess/cfror
lib/cfror.rb
Cfror.Data.save_cfror_fields
def save_cfror_fields(fields) fields.each do |field, value| field = Cfror::Field.find(field) field.save_value!(self, value) end end
ruby
def save_cfror_fields(fields) fields.each do |field, value| field = Cfror::Field.find(field) field.save_value!(self, value) end end
[ "def", "save_cfror_fields", "(", "fields", ")", "fields", ".", "each", "do", "|", "field", ",", "value", "|", "field", "=", "Cfror", "::", "Field", ".", "find", "(", "field", ")", "field", ".", "save_value!", "(", "self", ",", "value", ")", "end", "e...
save fields value
[ "save", "fields", "value" ]
0e5771f7eb50bfab84992c6187572080a63e7a58
https://github.com/sunchess/cfror/blob/0e5771f7eb50bfab84992c6187572080a63e7a58/lib/cfror.rb#L45-L50
train
sunchess/cfror
lib/cfror.rb
Cfror.Data.value_fields_for
def value_fields_for(source, order=nil) fields = self.send(source).fields fields = fields.order(order) if order fields.each do |i| i.set_value_for(self) end fields end
ruby
def value_fields_for(source, order=nil) fields = self.send(source).fields fields = fields.order(order) if order fields.each do |i| i.set_value_for(self) end fields end
[ "def", "value_fields_for", "(", "source", ",", "order", "=", "nil", ")", "fields", "=", "self", ".", "send", "(", "source", ")", ".", "fields", "fields", "=", "fields", ".", "order", "(", "order", ")", "if", "order", "fields", ".", "each", "do", "|",...
set values for fields @param source is symbol of relation method contains include Cfror::Fields
[ "set", "values", "for", "fields" ]
0e5771f7eb50bfab84992c6187572080a63e7a58
https://github.com/sunchess/cfror/blob/0e5771f7eb50bfab84992c6187572080a63e7a58/lib/cfror.rb#L54-L64
train
bilus/kawaii
lib/kawaii/formats.rb
Kawaii.FormatHandler.method_missing
def method_missing(meth, *_args, &block) format = FormatRegistry.formats[meth] return unless format && format.match?(@route_handler.request) @candidates << format @blocks[meth] = block end
ruby
def method_missing(meth, *_args, &block) format = FormatRegistry.formats[meth] return unless format && format.match?(@route_handler.request) @candidates << format @blocks[meth] = block end
[ "def", "method_missing", "(", "meth", ",", "*", "_args", ",", "&", "block", ")", "format", "=", "FormatRegistry", ".", "formats", "[", "meth", "]", "return", "unless", "format", "&&", "format", ".", "match?", "(", "@route_handler", ".", "request", ")", "...
Creates a format handler for a route handler @param [Kawaii::RouteHandler] current route handler @return {FormatHandler} Matches method invoked in end-user code with {FormatBase#key}. If format matches the current request, it saves it for negotiation in {FormatHandler#response}.
[ "Creates", "a", "format", "handler", "for", "a", "route", "handler" ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/formats.rb#L31-L36
train
bilus/kawaii
lib/kawaii/formats.rb
Kawaii.JsonFormat.parse_params
def parse_params(request) json = request.body.read JSON.parse(json).symbolize_keys if json.is_a?(String) && !json.empty? end
ruby
def parse_params(request) json = request.body.read JSON.parse(json).symbolize_keys if json.is_a?(String) && !json.empty? end
[ "def", "parse_params", "(", "request", ")", "json", "=", "request", ".", "body", ".", "read", "JSON", ".", "parse", "(", "json", ")", ".", "symbolize_keys", "if", "json", ".", "is_a?", "(", "String", ")", "&&", "!", "json", ".", "empty?", "end" ]
Parses JSON string in request body if present and converts it to a hash. @param request [Rack::Request] contains information about the current HTTP request @return {Hash} including parsed params or nil
[ "Parses", "JSON", "string", "in", "request", "body", "if", "present", "and", "converts", "it", "to", "a", "hash", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/formats.rb#L126-L129
train
bilus/kawaii
lib/kawaii/formats.rb
Kawaii.JsonFormat.encode
def encode(response) json = response.to_json [200, { Rack::CONTENT_TYPE => 'application/json', Rack::CONTENT_LENGTH => json.length.to_s }, [json]] end
ruby
def encode(response) json = response.to_json [200, { Rack::CONTENT_TYPE => 'application/json', Rack::CONTENT_LENGTH => json.length.to_s }, [json]] end
[ "def", "encode", "(", "response", ")", "json", "=", "response", ".", "to_json", "[", "200", ",", "{", "Rack", "::", "CONTENT_TYPE", "=>", "'application/json'", ",", "Rack", "::", "CONTENT_LENGTH", "=>", "json", ".", "length", ".", "to_s", "}", ",", "[", ...
Encodes response appropriately by converting it to a JSON string. @param response [String, Hash, Array] response from format handler block. @return Rack response {Array}
[ "Encodes", "response", "appropriately", "by", "converting", "it", "to", "a", "JSON", "string", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/formats.rb#L134-L140
train
wenzowski/closync
lib/closync/sync.rb
Closync.Sync.upload!
def upload!(local_file) @remote.directory.files.create( key: local_file.key, body: local_file.body, cache_control: "public, max-age=#{max_age(local_file)}", public: true ) end
ruby
def upload!(local_file) @remote.directory.files.create( key: local_file.key, body: local_file.body, cache_control: "public, max-age=#{max_age(local_file)}", public: true ) end
[ "def", "upload!", "(", "local_file", ")", "@remote", ".", "directory", ".", "files", ".", "create", "(", "key", ":", "local_file", ".", "key", ",", "body", ":", "local_file", ".", "body", ",", "cache_control", ":", "\"public, max-age=#{max_age(local_file)}\"", ...
If file already exists on remote it will be overwritten.
[ "If", "file", "already", "exists", "on", "remote", "it", "will", "be", "overwritten", "." ]
67730c160bcbd25420fb03d749ac086be429284c
https://github.com/wenzowski/closync/blob/67730c160bcbd25420fb03d749ac086be429284c/lib/closync/sync.rb#L46-L53
train
seblindberg/ruby-adam6050
lib/adam6050/password.rb
ADAM6050.Password.obfuscate
def obfuscate(plain) codepoints = plain.codepoints raise FormatError if codepoints.length > 8 password = Array.new(8, 0x0E) codepoints.each_with_index do |c, i| password[i] = (c & 0x40) | (~c & 0x3F) end password.pack 'c*' end
ruby
def obfuscate(plain) codepoints = plain.codepoints raise FormatError if codepoints.length > 8 password = Array.new(8, 0x0E) codepoints.each_with_index do |c, i| password[i] = (c & 0x40) | (~c & 0x3F) end password.pack 'c*' end
[ "def", "obfuscate", "(", "plain", ")", "codepoints", "=", "plain", ".", "codepoints", "raise", "FormatError", "if", "codepoints", ".", "length", ">", "8", "password", "=", "Array", ".", "new", "(", "8", ",", "0x0E", ")", "codepoints", ".", "each_with_index...
Transforms a plain text password into an 8 character string recognised by the ADAM-6050. The algorithm, if you can even call it that, used to perform the transformation was found by trial and error. @raise [FormatError] if the plain text password is longer than 8 characters. @param plain [String] the plain text version of the password. @return [String] the obfuscated, 8 character password.
[ "Transforms", "a", "plain", "text", "password", "into", "an", "8", "character", "string", "recognised", "by", "the", "ADAM", "-", "6050", ".", "The", "algorithm", "if", "you", "can", "even", "call", "it", "that", "used", "to", "perform", "the", "transforma...
7a8e8c344cc770b25d18ddf43f105d0f19e14d50
https://github.com/seblindberg/ruby-adam6050/blob/7a8e8c344cc770b25d18ddf43f105d0f19e14d50/lib/adam6050/password.rb#L54-L64
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/base.rb
ActiveRecord.Base.to_yaml
def to_yaml(opts = {}) #:nodoc: if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? super else coder = {} encode_with(coder) YAML.quick_emit(self, opts) do |out| out.map(taguri, to_yaml_style) do |map| coder.each { |k, v| map.add(k, v) } end end end end
ruby
def to_yaml(opts = {}) #:nodoc: if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? super else coder = {} encode_with(coder) YAML.quick_emit(self, opts) do |out| out.map(taguri, to_yaml_style) do |map| coder.each { |k, v| map.add(k, v) } end end end end
[ "def", "to_yaml", "(", "opts", "=", "{", "}", ")", "if", "YAML", ".", "const_defined?", "(", ":ENGINE", ")", "&&", "!", "YAML", "::", "ENGINE", ".", "syck?", "super", "else", "coder", "=", "{", "}", "encode_with", "(", "coder", ")", "YAML", ".", "q...
Hackery to accomodate Syck. Remove for 4.0.
[ "Hackery", "to", "accomodate", "Syck", ".", "Remove", "for", "4", ".", "0", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/base.rb#L652-L664
train
ktonon/code_node
lib/code_node/sexp_walker.rb
CodeNode.SexpWalker.walk
def walk(s = nil) s ||= @root if [:module, :class].member?(s[0]) add_node s elsif find_relations? && s[0] == :call && s.length >= 4 && [:extend, :include].member?(s[2]) && !@graph.scope.empty? add_relation s else walk_siblings s.slice(1..-1) end end
ruby
def walk(s = nil) s ||= @root if [:module, :class].member?(s[0]) add_node s elsif find_relations? && s[0] == :call && s.length >= 4 && [:extend, :include].member?(s[2]) && !@graph.scope.empty? add_relation s else walk_siblings s.slice(1..-1) end end
[ "def", "walk", "(", "s", "=", "nil", ")", "s", "||=", "@root", "if", "[", ":module", ",", ":class", "]", ".", "member?", "(", "s", "[", "0", "]", ")", "add_node", "s", "elsif", "find_relations?", "&&", "s", "[", "0", "]", "==", ":call", "&&", "...
Initialize a walker with a graph and sexp All files in a code base should be walked once in <tt>:find_nodes</tt> mode, and then walked again in <tt>:find_relations</tt> mode. @param graph [IR::Graph] a graph to which nodes and relations will be added @param sexp [Sexp] the root sexp of a ruby file @option opt [Symbol] :mode (:find_nodes) one of <tt>:find_nodes</tt> or <tt>:find_relations</tt> Walk the tree rooted at the given sexp @param s [Sexp] if +nil+ will be the root sexp @return [nil]
[ "Initialize", "a", "walker", "with", "a", "graph", "and", "sexp" ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/lib/code_node/sexp_walker.rb#L23-L32
train
mbj/aql
lib/aql/buffer.rb
AQL.Buffer.delimited
def delimited(nodes, delimiter = ', ') max = nodes.length - 1 nodes.each_with_index do |element, index| element.visit(self) append(delimiter) if index < max end self end
ruby
def delimited(nodes, delimiter = ', ') max = nodes.length - 1 nodes.each_with_index do |element, index| element.visit(self) append(delimiter) if index < max end self end
[ "def", "delimited", "(", "nodes", ",", "delimiter", "=", "', '", ")", "max", "=", "nodes", ".", "length", "-", "1", "nodes", ".", "each_with_index", "do", "|", "element", ",", "index", "|", "element", ".", "visit", "(", "self", ")", "append", "(", "d...
Emit delimited nodes @param [Enumerable<Node>] nodes @return [self] @api private
[ "Emit", "delimited", "nodes" ]
b271162935d8351d99be50dab5025d56c972fa25
https://github.com/mbj/aql/blob/b271162935d8351d99be50dab5025d56c972fa25/lib/aql/buffer.rb#L52-L59
train
FronteraConsulting/oanda_ruby_client
lib/oanda_ruby_client/exchange_rates_client.rb
OandaRubyClient.ExchangeRatesClient.rates
def rates(rates_request) rates_uri = "#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}" rates_response = HTTParty.get(rates_uri, headers: oanda_headers) handle_response(rates_response.response) OpenStruct.new(rates_response.parsed_response) end
ruby
def rates(rates_request) rates_uri = "#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}" rates_response = HTTParty.get(rates_uri, headers: oanda_headers) handle_response(rates_response.response) OpenStruct.new(rates_response.parsed_response) end
[ "def", "rates", "(", "rates_request", ")", "rates_uri", "=", "\"#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}\"", "rates_response", "=", "HTTParty", ".", "get", "(", "rates_uri", ",", "headers", ":", "oanda_headers", ")", ...
Returns the exchanges rates based on the specified request @param rates_request [OandaRubyClient::RatesRequest] Request criteria @return [OpenStruct] An object structured similarly to the response from the Exchange Rate API
[ "Returns", "the", "exchanges", "rates", "based", "on", "the", "specified", "request" ]
1230e6a011ea4448597349ea7f46548bcbff2e86
https://github.com/FronteraConsulting/oanda_ruby_client/blob/1230e6a011ea4448597349ea7f46548bcbff2e86/lib/oanda_ruby_client/exchange_rates_client.rb#L30-L35
train
FronteraConsulting/oanda_ruby_client
lib/oanda_ruby_client/exchange_rates_client.rb
OandaRubyClient.ExchangeRatesClient.remaining_quotes
def remaining_quotes remaining_quotes_response = HTTParty.get("#{oanda_endpoint}#{REMAINING_QUOTES_PATH}", headers: oanda_headers) handle_response(remaining_quotes_response.response) remaining_quotes_response.parsed_response['remaining_quotes'] end
ruby
def remaining_quotes remaining_quotes_response = HTTParty.get("#{oanda_endpoint}#{REMAINING_QUOTES_PATH}", headers: oanda_headers) handle_response(remaining_quotes_response.response) remaining_quotes_response.parsed_response['remaining_quotes'] end
[ "def", "remaining_quotes", "remaining_quotes_response", "=", "HTTParty", ".", "get", "(", "\"#{oanda_endpoint}#{REMAINING_QUOTES_PATH}\"", ",", "headers", ":", "oanda_headers", ")", "handle_response", "(", "remaining_quotes_response", ".", "response", ")", "remaining_quotes_r...
Returns the number of remaining quote requests @return [Fixnum, 'unlimited'] Number of remaining quote requests
[ "Returns", "the", "number", "of", "remaining", "quote", "requests" ]
1230e6a011ea4448597349ea7f46548bcbff2e86
https://github.com/FronteraConsulting/oanda_ruby_client/blob/1230e6a011ea4448597349ea7f46548bcbff2e86/lib/oanda_ruby_client/exchange_rates_client.rb#L40-L44
train
docwhat/lego_nxt
lib/lego_nxt/low_level/brick.rb
LegoNXT::LowLevel.Brick.reset_motor_position
def reset_motor_position port, set_relative transmit( DirectOps::NO_RESPONSE, DirectOps::RESETMOTORPOSITION, normalize_motor_port(port), normalize_boolean(set_relative) ) end
ruby
def reset_motor_position port, set_relative transmit( DirectOps::NO_RESPONSE, DirectOps::RESETMOTORPOSITION, normalize_motor_port(port), normalize_boolean(set_relative) ) end
[ "def", "reset_motor_position", "port", ",", "set_relative", "transmit", "(", "DirectOps", "::", "NO_RESPONSE", ",", "DirectOps", "::", "RESETMOTORPOSITION", ",", "normalize_motor_port", "(", "port", ")", ",", "normalize_boolean", "(", "set_relative", ")", ")", "end"...
Resets the tracking for the motor position. @param [Symbol] port The port the motor is attached to. Should be `:a`, `:b`, or `:c` @param [Boolean] set_relative Sets the position tracking to relative if true, otherwise absolute if false. @return [nil]
[ "Resets", "the", "tracking", "for", "the", "motor", "position", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/brick.rb#L104-L111
train
docwhat/lego_nxt
lib/lego_nxt/low_level/brick.rb
LegoNXT::LowLevel.Brick.run_motor
def run_motor port, power=100 raise ArgumentError.new("Power must be -100 through 100") if power < -100 || power > 100 transmit( DirectOps::NO_RESPONSE, DirectOps::SETOUTPUTSTATE, normalize_motor_port(port, true), sbyte(power), # power set point byte(1), # mode byte(0), # regulation mode sbyte(0), # turn ratio byte(0x20), # run state long(0), # tacho limit ) end
ruby
def run_motor port, power=100 raise ArgumentError.new("Power must be -100 through 100") if power < -100 || power > 100 transmit( DirectOps::NO_RESPONSE, DirectOps::SETOUTPUTSTATE, normalize_motor_port(port, true), sbyte(power), # power set point byte(1), # mode byte(0), # regulation mode sbyte(0), # turn ratio byte(0x20), # run state long(0), # tacho limit ) end
[ "def", "run_motor", "port", ",", "power", "=", "100", "raise", "ArgumentError", ".", "new", "(", "\"Power must be -100 through 100\"", ")", "if", "power", "<", "-", "100", "||", "power", ">", "100", "transmit", "(", "DirectOps", "::", "NO_RESPONSE", ",", "Di...
Runs the motor @param [Symbol] port The port the motor is attached to. Should be `:a`, `:b`, `:c`, `:all` @param [Integer] power A number between -100 through 100 inclusive. Defaults to 100. @return [nil]
[ "Runs", "the", "motor" ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/brick.rb#L118-L131
train
docwhat/lego_nxt
lib/lego_nxt/low_level/brick.rb
LegoNXT::LowLevel.Brick.transceive
def transceive *bits bitstring = bits.map(&:byte_string).join("") retval = connection.transceive bitstring # Check that it's a response bit. raise ::LegoNXT::BadResponseError unless retval[0] == "\x02" # Check that it's for this command. raise ::LegoNXT::BadResponseError unless retval[1] == bitstring[1] # Check that there is no error. # TODO: This should raise a specific error based on the status bit. raise ::LegoNXT::StatusError unless retval[2] == "\x00" return retval[3..-1] end
ruby
def transceive *bits bitstring = bits.map(&:byte_string).join("") retval = connection.transceive bitstring # Check that it's a response bit. raise ::LegoNXT::BadResponseError unless retval[0] == "\x02" # Check that it's for this command. raise ::LegoNXT::BadResponseError unless retval[1] == bitstring[1] # Check that there is no error. # TODO: This should raise a specific error based on the status bit. raise ::LegoNXT::StatusError unless retval[2] == "\x00" return retval[3..-1] end
[ "def", "transceive", "*", "bits", "bitstring", "=", "bits", ".", "map", "(", "&", ":byte_string", ")", ".", "join", "(", "\"\"", ")", "retval", "=", "connection", ".", "transceive", "bitstring", "raise", "::", "LegoNXT", "::", "BadResponseError", "unless", ...
A wrapper around the transceive function for the connection. The first three bytes of the return value are stripped off. Errors are raised if they show a problem. @param [LegoNXT::Type] bits A list of bytes. @return [String] The bytes returned; bytes 0 through 2 are stripped.
[ "A", "wrapper", "around", "the", "transceive", "function", "for", "the", "connection", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/brick.rb#L157-L168
train
travis-ci/travis.rb
lib/travis/cli.rb
Travis.CLI.preparse
def preparse(unparsed, args = [], opts = {}) case unparsed when Hash then opts.merge! unparsed when Array then unparsed.each { |e| preparse(e, args, opts) } else args << unparsed.to_s end [args, opts] end
ruby
def preparse(unparsed, args = [], opts = {}) case unparsed when Hash then opts.merge! unparsed when Array then unparsed.each { |e| preparse(e, args, opts) } else args << unparsed.to_s end [args, opts] end
[ "def", "preparse", "(", "unparsed", ",", "args", "=", "[", "]", ",", "opts", "=", "{", "}", ")", "case", "unparsed", "when", "Hash", "then", "opts", ".", "merge!", "unparsed", "when", "Array", "then", "unparsed", ".", "each", "{", "|", "e", "|", "p...
can't use flatten as it will flatten hashes
[ "can", "t", "use", "flatten", "as", "it", "will", "flatten", "hashes" ]
6547e3ad1393f508c679236a4b0e5403d2732043
https://github.com/travis-ci/travis.rb/blob/6547e3ad1393f508c679236a4b0e5403d2732043/lib/travis/cli.rb#L117-L124
valid
github/scientist
lib/scientist/experiment.rb
Scientist::Experiment.MismatchError.to_s
def to_s super + ":\n" + format_observation(result.control) + "\n" + result.candidates.map { |candidate| format_observation(candidate) }.join("\n") + "\n" end
ruby
def to_s super + ":\n" + format_observation(result.control) + "\n" + result.candidates.map { |candidate| format_observation(candidate) }.join("\n") + "\n" end
[ "def", "to_s", "super", "+", "\":\\n\"", "+", "format_observation", "(", "result", ".", "control", ")", "+", "\"\\n\"", "+", "result", ".", "candidates", ".", "map", "{", "|", "candidate", "|", "format_observation", "(", "candidate", ")", "}", ".", "join",...
The default formatting is nearly unreadable, so make it useful. The assumption here is that errors raised in a test environment are printed out as strings, rather than using #inspect.
[ "The", "default", "formatting", "is", "nearly", "unreadable", "so", "make", "it", "useful", "." ]
25a22f733d4be523404b22ad818e520d20b57619
https://github.com/github/scientist/blob/25a22f733d4be523404b22ad818e520d20b57619/lib/scientist/experiment.rb#L34-L39
valid
rest-client/rest-client
lib/restclient/request.rb
RestClient.Request.process_url_params
def process_url_params(url, headers) url_params = nil # find and extract/remove "params" key if the value is a Hash/ParamsArray headers.delete_if do |key, value| if key.to_s.downcase == 'params' && (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray)) if url_params raise ArgumentError.new("Multiple 'params' options passed") end url_params = value true else false end end # build resulting URL with query string if url_params && !url_params.empty? query_string = RestClient::Utils.encode_query_string(url_params) if url.include?('?') url + '&' + query_string else url + '?' + query_string end else url end end
ruby
def process_url_params(url, headers) url_params = nil # find and extract/remove "params" key if the value is a Hash/ParamsArray headers.delete_if do |key, value| if key.to_s.downcase == 'params' && (value.is_a?(Hash) || value.is_a?(RestClient::ParamsArray)) if url_params raise ArgumentError.new("Multiple 'params' options passed") end url_params = value true else false end end # build resulting URL with query string if url_params && !url_params.empty? query_string = RestClient::Utils.encode_query_string(url_params) if url.include?('?') url + '&' + query_string else url + '?' + query_string end else url end end
[ "def", "process_url_params", "(", "url", ",", "headers", ")", "url_params", "=", "nil", "headers", ".", "delete_if", "do", "|", "key", ",", "value", "|", "if", "key", ".", "to_s", ".", "downcase", "==", "'params'", "&&", "(", "value", ".", "is_a?", "("...
Extract the query parameters and append them to the url Look through the headers hash for a :params option (case-insensitive, may be string or symbol). If present and the value is a Hash or RestClient::ParamsArray, *delete* the key/value pair from the headers hash and encode the value into a query string. Append this query string to the URL and return the resulting URL. @param [String] url @param [Hash] headers An options/headers hash to process. Mutation warning: the params key may be removed if present! @return [String] resulting url with query string
[ "Extract", "the", "query", "parameters", "and", "append", "them", "to", "the", "url" ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L195-L224
valid
rest-client/rest-client
lib/restclient/request.rb
RestClient.Request.stringify_headers
def stringify_headers headers headers.inject({}) do |result, (key, value)| if key.is_a? Symbol key = key.to_s.split(/_/).map(&:capitalize).join('-') end if 'CONTENT-TYPE' == key.upcase result[key] = maybe_convert_extension(value.to_s) elsif 'ACCEPT' == key.upcase # Accept can be composed of several comma-separated values if value.is_a? Array target_values = value else target_values = value.to_s.split ',' end result[key] = target_values.map { |ext| maybe_convert_extension(ext.to_s.strip) }.join(', ') else result[key] = value.to_s end result end end
ruby
def stringify_headers headers headers.inject({}) do |result, (key, value)| if key.is_a? Symbol key = key.to_s.split(/_/).map(&:capitalize).join('-') end if 'CONTENT-TYPE' == key.upcase result[key] = maybe_convert_extension(value.to_s) elsif 'ACCEPT' == key.upcase # Accept can be composed of several comma-separated values if value.is_a? Array target_values = value else target_values = value.to_s.split ',' end result[key] = target_values.map { |ext| maybe_convert_extension(ext.to_s.strip) }.join(', ') else result[key] = value.to_s end result end end
[ "def", "stringify_headers", "headers", "headers", ".", "inject", "(", "{", "}", ")", "do", "|", "result", ",", "(", "key", ",", "value", ")", "|", "if", "key", ".", "is_a?", "Symbol", "key", "=", "key", ".", "to_s", ".", "split", "(", "/", "/", "...
Return a hash of headers whose keys are capitalized strings BUG: stringify_headers does not fix the capitalization of headers that are already Strings. Leaving this behavior as is for now for backwards compatibility. https://github.com/rest-client/rest-client/issues/599
[ "Return", "a", "hash", "of", "headers", "whose", "keys", "are", "capitalized", "strings" ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L553-L575
valid
rest-client/rest-client
lib/restclient/request.rb
RestClient.Request.maybe_convert_extension
def maybe_convert_extension(ext) unless ext =~ /\A[a-zA-Z0-9_@-]+\z/ # Don't look up strings unless they look like they could be a file # extension known to mime-types. # # There currently isn't any API public way to look up extensions # directly out of MIME::Types, but the type_for() method only strips # off after a period anyway. return ext end types = MIME::Types.type_for(ext) if types.empty? ext else types.first.content_type end end
ruby
def maybe_convert_extension(ext) unless ext =~ /\A[a-zA-Z0-9_@-]+\z/ # Don't look up strings unless they look like they could be a file # extension known to mime-types. # # There currently isn't any API public way to look up extensions # directly out of MIME::Types, but the type_for() method only strips # off after a period anyway. return ext end types = MIME::Types.type_for(ext) if types.empty? ext else types.first.content_type end end
[ "def", "maybe_convert_extension", "(", "ext", ")", "unless", "ext", "=~", "/", "\\A", "\\z", "/", "return", "ext", "end", "types", "=", "MIME", "::", "Types", ".", "type_for", "(", "ext", ")", "if", "types", ".", "empty?", "ext", "else", "types", ".", ...
Given a MIME type or file extension, return either a MIME type or, if none is found, the input unchanged. >> maybe_convert_extension('json') => 'application/json' >> maybe_convert_extension('unknown') => 'unknown' >> maybe_convert_extension('application/xml') => 'application/xml' @param ext [String] @return [String]
[ "Given", "a", "MIME", "type", "or", "file", "extension", "return", "either", "a", "MIME", "type", "or", "if", "none", "is", "found", "the", "input", "unchanged", "." ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/request.rb#L856-L873
valid
rest-client/rest-client
lib/restclient/resource.rb
RestClient.Resource.[]
def [](suburl, &new_block) case when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block) when block then self.class.new(concat_urls(url, suburl), options, &block) else self.class.new(concat_urls(url, suburl), options) end end
ruby
def [](suburl, &new_block) case when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block) when block then self.class.new(concat_urls(url, suburl), options, &block) else self.class.new(concat_urls(url, suburl), options) end end
[ "def", "[]", "(", "suburl", ",", "&", "new_block", ")", "case", "when", "block_given?", "then", "self", ".", "class", ".", "new", "(", "concat_urls", "(", "url", ",", "suburl", ")", ",", "options", ",", "&", "new_block", ")", "when", "block", "then", ...
Construct a subresource, preserving authentication. Example: site = RestClient::Resource.new('http://example.com', 'adam', 'mypasswd') site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain' This is especially useful if you wish to define your site in one place and call it in multiple locations: def orders RestClient::Resource.new('http://example.com/orders', 'admin', 'mypasswd') end orders.get # GET http://example.com/orders orders['1'].get # GET http://example.com/orders/1 orders['1/items'].delete # DELETE http://example.com/orders/1/items Nest resources as far as you want: site = RestClient::Resource.new('http://example.com') posts = site['posts'] first_post = posts['1'] comments = first_post['comments'] comments.post 'Hello', :content_type => 'text/plain'
[ "Construct", "a", "subresource", "preserving", "authentication", "." ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/resource.rb#L160-L166
valid
rest-client/rest-client
lib/restclient/abstract_response.rb
RestClient.AbstractResponse.cookies
def cookies hash = {} cookie_jar.cookies(@request.uri).each do |cookie| hash[cookie.name] = cookie.value end hash end
ruby
def cookies hash = {} cookie_jar.cookies(@request.uri).each do |cookie| hash[cookie.name] = cookie.value end hash end
[ "def", "cookies", "hash", "=", "{", "}", "cookie_jar", ".", "cookies", "(", "@request", ".", "uri", ")", ".", "each", "do", "|", "cookie", "|", "hash", "[", "cookie", ".", "name", "]", "=", "cookie", ".", "value", "end", "hash", "end" ]
Hash of cookies extracted from response headers. NB: This will return only cookies whose domain matches this request, and may not even return all of those cookies if there are duplicate names. Use the full cookie_jar for more nuanced access. @see #cookie_jar @return [Hash]
[ "Hash", "of", "cookies", "extracted", "from", "response", "headers", "." ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L78-L86
valid
rest-client/rest-client
lib/restclient/abstract_response.rb
RestClient.AbstractResponse.cookie_jar
def cookie_jar return @cookie_jar if defined?(@cookie_jar) && @cookie_jar jar = @request.cookie_jar.dup headers.fetch(:set_cookie, []).each do |cookie| jar.parse(cookie, @request.uri) end @cookie_jar = jar end
ruby
def cookie_jar return @cookie_jar if defined?(@cookie_jar) && @cookie_jar jar = @request.cookie_jar.dup headers.fetch(:set_cookie, []).each do |cookie| jar.parse(cookie, @request.uri) end @cookie_jar = jar end
[ "def", "cookie_jar", "return", "@cookie_jar", "if", "defined?", "(", "@cookie_jar", ")", "&&", "@cookie_jar", "jar", "=", "@request", ".", "cookie_jar", ".", "dup", "headers", ".", "fetch", "(", ":set_cookie", ",", "[", "]", ")", ".", "each", "do", "|", ...
Cookie jar extracted from response headers. @return [HTTP::CookieJar]
[ "Cookie", "jar", "extracted", "from", "response", "headers", "." ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L92-L101
valid
rest-client/rest-client
lib/restclient/abstract_response.rb
RestClient.AbstractResponse.follow_get_redirection
def follow_get_redirection(&block) new_args = request.args.dup new_args[:method] = :get new_args.delete(:payload) _follow_redirection(new_args, &block) end
ruby
def follow_get_redirection(&block) new_args = request.args.dup new_args[:method] = :get new_args.delete(:payload) _follow_redirection(new_args, &block) end
[ "def", "follow_get_redirection", "(", "&", "block", ")", "new_args", "=", "request", ".", "args", ".", "dup", "new_args", "[", ":method", "]", "=", ":get", "new_args", ".", "delete", "(", ":payload", ")", "_follow_redirection", "(", "new_args", ",", "&", "...
Follow a redirection response, but change the HTTP method to GET and drop the payload from the original request.
[ "Follow", "a", "redirection", "response", "but", "change", "the", "HTTP", "method", "to", "GET", "and", "drop", "the", "payload", "from", "the", "original", "request", "." ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L150-L156
valid
rest-client/rest-client
lib/restclient/abstract_response.rb
RestClient.AbstractResponse._follow_redirection
def _follow_redirection(new_args, &block) # parse location header and merge into existing URL url = headers[:location] # cannot follow redirection if there is no location header unless url raise exception_with_response end # handle relative redirects unless url.start_with?('http') url = URI.parse(request.url).merge(url).to_s end new_args[:url] = url new_args[:password] = request.password new_args[:user] = request.user new_args[:headers] = request.headers new_args[:max_redirects] = request.max_redirects - 1 # pass through our new cookie jar new_args[:cookies] = cookie_jar # prepare new request new_req = Request.new(new_args) # append self to redirection history new_req.redirection_history = history + [self] # execute redirected request new_req.execute(&block) end
ruby
def _follow_redirection(new_args, &block) # parse location header and merge into existing URL url = headers[:location] # cannot follow redirection if there is no location header unless url raise exception_with_response end # handle relative redirects unless url.start_with?('http') url = URI.parse(request.url).merge(url).to_s end new_args[:url] = url new_args[:password] = request.password new_args[:user] = request.user new_args[:headers] = request.headers new_args[:max_redirects] = request.max_redirects - 1 # pass through our new cookie jar new_args[:cookies] = cookie_jar # prepare new request new_req = Request.new(new_args) # append self to redirection history new_req.redirection_history = history + [self] # execute redirected request new_req.execute(&block) end
[ "def", "_follow_redirection", "(", "new_args", ",", "&", "block", ")", "url", "=", "headers", "[", ":location", "]", "unless", "url", "raise", "exception_with_response", "end", "unless", "url", ".", "start_with?", "(", "'http'", ")", "url", "=", "URI", ".", ...
Follow a redirection @param new_args [Hash] Start with this hash of arguments for the redirection request. The hash will be mutated, so be sure to dup any existing hash that should not be modified.
[ "Follow", "a", "redirection" ]
f450a0f086f1cd1049abbef2a2c66166a1a9ba71
https://github.com/rest-client/rest-client/blob/f450a0f086f1cd1049abbef2a2c66166a1a9ba71/lib/restclient/abstract_response.rb#L202-L234
valid
omniauth/omniauth
lib/omniauth/strategy.rb
OmniAuth.Strategy.call!
def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity unless env['rack.session'] error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.') raise(error) end @env = env @env['omniauth.strategy'] = self if on_auth_path? return mock_call!(env) if OmniAuth.config.test_mode return options_call if on_auth_path? && options_request? return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym) return callback_call if on_callback_path? return other_phase if respond_to?(:other_phase) @app.call(env) end
ruby
def call!(env) # rubocop:disable CyclomaticComplexity, PerceivedComplexity unless env['rack.session'] error = OmniAuth::NoSessionError.new('You must provide a session to use OmniAuth.') raise(error) end @env = env @env['omniauth.strategy'] = self if on_auth_path? return mock_call!(env) if OmniAuth.config.test_mode return options_call if on_auth_path? && options_request? return request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym) return callback_call if on_callback_path? return other_phase if respond_to?(:other_phase) @app.call(env) end
[ "def", "call!", "(", "env", ")", "unless", "env", "[", "'rack.session'", "]", "error", "=", "OmniAuth", "::", "NoSessionError", ".", "new", "(", "'You must provide a session to use OmniAuth.'", ")", "raise", "(", "error", ")", "end", "@env", "=", "env", "@env"...
The logic for dispatching any additional actions that need to be taken. For instance, calling the request phase if the request path is recognized. @param env [Hash] The Rack environment.
[ "The", "logic", "for", "dispatching", "any", "additional", "actions", "that", "need", "to", "be", "taken", ".", "For", "instance", "calling", "the", "request", "phase", "if", "the", "request", "path", "is", "recognized", "." ]
cc0f5522621b4a372f4dff0aa608822aa082cb60
https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L177-L193
valid
omniauth/omniauth
lib/omniauth/strategy.rb
OmniAuth.Strategy.options_call
def options_call OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ') [200, {'Allow' => verbs}, []] end
ruby
def options_call OmniAuth.config.before_options_phase.call(env) if OmniAuth.config.before_options_phase verbs = OmniAuth.config.allowed_request_methods.collect(&:to_s).collect(&:upcase).join(', ') [200, {'Allow' => verbs}, []] end
[ "def", "options_call", "OmniAuth", ".", "config", ".", "before_options_phase", ".", "call", "(", "env", ")", "if", "OmniAuth", ".", "config", ".", "before_options_phase", "verbs", "=", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "collect", "(...
Responds to an OPTIONS request.
[ "Responds", "to", "an", "OPTIONS", "request", "." ]
cc0f5522621b4a372f4dff0aa608822aa082cb60
https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L196-L200
valid
omniauth/omniauth
lib/omniauth/strategy.rb
OmniAuth.Strategy.callback_call
def callback_call setup_phase log :info, 'Callback phase initiated.' @env['omniauth.origin'] = session.delete('omniauth.origin') @env['omniauth.origin'] = nil if env['omniauth.origin'] == '' @env['omniauth.params'] = session.delete('omniauth.params') || {} OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase callback_phase end
ruby
def callback_call setup_phase log :info, 'Callback phase initiated.' @env['omniauth.origin'] = session.delete('omniauth.origin') @env['omniauth.origin'] = nil if env['omniauth.origin'] == '' @env['omniauth.params'] = session.delete('omniauth.params') || {} OmniAuth.config.before_callback_phase.call(@env) if OmniAuth.config.before_callback_phase callback_phase end
[ "def", "callback_call", "setup_phase", "log", ":info", ",", "'Callback phase initiated.'", "@env", "[", "'omniauth.origin'", "]", "=", "session", ".", "delete", "(", "'omniauth.origin'", ")", "@env", "[", "'omniauth.origin'", "]", "=", "nil", "if", "env", "[", "...
Performs the steps necessary to run the callback phase of a strategy.
[ "Performs", "the", "steps", "necessary", "to", "run", "the", "callback", "phase", "of", "a", "strategy", "." ]
cc0f5522621b4a372f4dff0aa608822aa082cb60
https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L231-L239
valid
omniauth/omniauth
lib/omniauth/strategy.rb
OmniAuth.Strategy.mock_call!
def mock_call!(*) return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym) return mock_callback_call if on_callback_path? call_app! end
ruby
def mock_call!(*) return mock_request_call if on_request_path? && OmniAuth.config.allowed_request_methods.include?(request.request_method.downcase.to_sym) return mock_callback_call if on_callback_path? call_app! end
[ "def", "mock_call!", "(", "*", ")", "return", "mock_request_call", "if", "on_request_path?", "&&", "OmniAuth", ".", "config", ".", "allowed_request_methods", ".", "include?", "(", "request", ".", "request_method", ".", "downcase", ".", "to_sym", ")", "return", "...
This is called in lieu of the normal request process in the event that OmniAuth has been configured to be in test mode.
[ "This", "is", "called", "in", "lieu", "of", "the", "normal", "request", "process", "in", "the", "event", "that", "OmniAuth", "has", "been", "configured", "to", "be", "in", "test", "mode", "." ]
cc0f5522621b4a372f4dff0aa608822aa082cb60
https://github.com/omniauth/omniauth/blob/cc0f5522621b4a372f4dff0aa608822aa082cb60/lib/omniauth/strategy.rb#L270-L275
valid
googleads/google-api-ads-ruby
ads_savon/lib/ads_savon/model.rb
GoogleAdsSavon.Model.instance_action_module
def instance_action_module @instance_action_module ||= Module.new do # Returns the <tt>GoogleAdsSavon::Client</tt> from the class instance. def client(&block) self.class.client(&block) end end.tap { |mod| include(mod) } end
ruby
def instance_action_module @instance_action_module ||= Module.new do # Returns the <tt>GoogleAdsSavon::Client</tt> from the class instance. def client(&block) self.class.client(&block) end end.tap { |mod| include(mod) } end
[ "def", "instance_action_module", "@instance_action_module", "||=", "Module", ".", "new", "do", "def", "client", "(", "&", "block", ")", "self", ".", "class", ".", "client", "(", "&", "block", ")", "end", "end", ".", "tap", "{", "|", "mod", "|", "include"...
Instance methods.
[ "Instance", "methods", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_savon/lib/ads_savon/model.rb#L90-L99
valid
googleads/google-api-ads-ruby
adwords_api/lib/adwords_api.rb
AdwordsApi.Api.soap_header_handler
def soap_header_handler(auth_handler, version, header_ns, default_ns) auth_method = @config.read('authentication.method', :OAUTH2) handler_class = case auth_method when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT AdsCommon::SavonHeaders::OAuthHeaderHandler else raise AdsCommon::Errors::AuthError, "Unknown auth method: %s" % auth_method end return handler_class.new(@credential_handler, auth_handler, header_ns, default_ns, version) end
ruby
def soap_header_handler(auth_handler, version, header_ns, default_ns) auth_method = @config.read('authentication.method', :OAUTH2) handler_class = case auth_method when :OAUTH2, :OAUTH2_SERVICE_ACCOUNT AdsCommon::SavonHeaders::OAuthHeaderHandler else raise AdsCommon::Errors::AuthError, "Unknown auth method: %s" % auth_method end return handler_class.new(@credential_handler, auth_handler, header_ns, default_ns, version) end
[ "def", "soap_header_handler", "(", "auth_handler", ",", "version", ",", "header_ns", ",", "default_ns", ")", "auth_method", "=", "@config", ".", "read", "(", "'authentication.method'", ",", ":OAUTH2", ")", "handler_class", "=", "case", "auth_method", "when", ":OAU...
Retrieve correct soap_header_handler. Args: - auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to handle authentication - version: intended API version - header_ns: header namespace - default_ns: default namespace Returns: - SOAP header handler
[ "Retrieve", "correct", "soap_header_handler", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L66-L77
valid
googleads/google-api-ads-ruby
adwords_api/lib/adwords_api.rb
AdwordsApi.Api.report_utils
def report_utils(version = nil) version = api_config.default_version if version.nil? # Check if version exists. if !api_config.versions.include?(version) raise AdsCommon::Errors::Error, "Unknown version '%s'" % version end return AdwordsApi::ReportUtils.new(self, version) end
ruby
def report_utils(version = nil) version = api_config.default_version if version.nil? # Check if version exists. if !api_config.versions.include?(version) raise AdsCommon::Errors::Error, "Unknown version '%s'" % version end return AdwordsApi::ReportUtils.new(self, version) end
[ "def", "report_utils", "(", "version", "=", "nil", ")", "version", "=", "api_config", ".", "default_version", "if", "version", ".", "nil?", "if", "!", "api_config", ".", "versions", ".", "include?", "(", "version", ")", "raise", "AdsCommon", "::", "Errors", ...
Returns an instance of ReportUtils object with all utilities relevant to the reporting. Args: - version: version of the API to use (optional).
[ "Returns", "an", "instance", "of", "ReportUtils", "object", "with", "all", "utilities", "relevant", "to", "the", "reporting", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L187-L194
valid
googleads/google-api-ads-ruby
adwords_api/lib/adwords_api.rb
AdwordsApi.Api.batch_job_utils
def batch_job_utils(version = nil) version = api_config.default_version if version.nil? # Check if version exists. if !api_config.versions.include?(version) raise AdsCommon::Errors::Error, "Unknown version '%s'" % version end return AdwordsApi::BatchJobUtils.new(self, version) end
ruby
def batch_job_utils(version = nil) version = api_config.default_version if version.nil? # Check if version exists. if !api_config.versions.include?(version) raise AdsCommon::Errors::Error, "Unknown version '%s'" % version end return AdwordsApi::BatchJobUtils.new(self, version) end
[ "def", "batch_job_utils", "(", "version", "=", "nil", ")", "version", "=", "api_config", ".", "default_version", "if", "version", ".", "nil?", "if", "!", "api_config", ".", "versions", ".", "include?", "(", "version", ")", "raise", "AdsCommon", "::", "Errors...
Returns an instance of BatchJobUtils object with all utilities relevant to running batch jobs. Args: - version: version of the API to use (optional).
[ "Returns", "an", "instance", "of", "BatchJobUtils", "object", "with", "all", "utilities", "relevant", "to", "running", "batch", "jobs", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L202-L209
valid
googleads/google-api-ads-ruby
adwords_api/lib/adwords_api.rb
AdwordsApi.Api.run_with_temporary_flag
def run_with_temporary_flag(flag_name, flag_value, block) previous = @credential_handler.instance_variable_get(flag_name) @credential_handler.instance_variable_set(flag_name, flag_value) begin return block.call ensure @credential_handler.instance_variable_set(flag_name, previous) end end
ruby
def run_with_temporary_flag(flag_name, flag_value, block) previous = @credential_handler.instance_variable_get(flag_name) @credential_handler.instance_variable_set(flag_name, flag_value) begin return block.call ensure @credential_handler.instance_variable_set(flag_name, previous) end end
[ "def", "run_with_temporary_flag", "(", "flag_name", ",", "flag_value", ",", "block", ")", "previous", "=", "@credential_handler", ".", "instance_variable_get", "(", "flag_name", ")", "@credential_handler", ".", "instance_variable_set", "(", "flag_name", ",", "flag_value...
Executes block with a temporary flag set to a given value. Returns block result.
[ "Executes", "block", "with", "a", "temporary", "flag", "set", "to", "a", "given", "value", ".", "Returns", "block", "result", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/adwords_api/lib/adwords_api.rb#L227-L235
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.validate_arguments
def validate_arguments(args_hash, fields_list, type_ns = nil) check_extra_fields(args_hash, array_from_named_list(fields_list)) add_order_key(args_hash, fields_list) fields_list.each do |field| key = field[:name] item = args_hash[key] check_required_argument_present(item, field) unless item.nil? original_name = field[:original_name] if original_name key = handle_name_override(args_hash, key, original_name) end item_type = get_full_type_signature(field[:type]) item_ns = field[:ns] || type_ns key = handle_namespace_override(args_hash, key, item_ns) if item_ns # Separate validation for choice types as we need to inject nodes into # the tree. Validate as usual if not a choice type. unless validate_choice_argument(item, args_hash, key, item_type) validate_arg(item, args_hash, key, item_type) end end end return args_hash end
ruby
def validate_arguments(args_hash, fields_list, type_ns = nil) check_extra_fields(args_hash, array_from_named_list(fields_list)) add_order_key(args_hash, fields_list) fields_list.each do |field| key = field[:name] item = args_hash[key] check_required_argument_present(item, field) unless item.nil? original_name = field[:original_name] if original_name key = handle_name_override(args_hash, key, original_name) end item_type = get_full_type_signature(field[:type]) item_ns = field[:ns] || type_ns key = handle_namespace_override(args_hash, key, item_ns) if item_ns # Separate validation for choice types as we need to inject nodes into # the tree. Validate as usual if not a choice type. unless validate_choice_argument(item, args_hash, key, item_type) validate_arg(item, args_hash, key, item_type) end end end return args_hash end
[ "def", "validate_arguments", "(", "args_hash", ",", "fields_list", ",", "type_ns", "=", "nil", ")", "check_extra_fields", "(", "args_hash", ",", "array_from_named_list", "(", "fields_list", ")", ")", "add_order_key", "(", "args_hash", ",", "fields_list", ")", "fie...
Validates given arguments based on provided fields list.
[ "Validates", "given", "arguments", "based", "on", "provided", "fields", "list", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L58-L83
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.validate_choice_argument
def validate_choice_argument(item, parent, key, item_type) result = false if item_type.kind_of?(Hash) && item_type.include?(:choices) # If we have an array of choices, we need to go over them individually. # We drop original array and replace it with the generated one that's # nested one level more. if item.kind_of?(Array) parent[key] = [] item.each do |sub_item| unless validate_choice_argument(sub_item, parent, key, item_type) validate_arg(sub_item, parent, key, item_type) end end return true end # New root needed for extra nesting we have (choice field). new_root = {} choice_items = arrayize(item) choice_items.each do |choice_item| choice_type = choice_item.delete(:xsi_type) choice_item_type = find_choice_by_xsi_type(choice_type, item_type[:choices]) if choice_type.nil? || choice_item_type.nil? raise AdsCommon::Errors::TypeMismatchError.new( 'choice subtype', choice_type, choice_item.to_s()) end choice_item[:xsi_type] = choice_type # Note we use original name that produces a string like # "BasicUserList". That's needed as the name is generated out of # standard naming ("basicUserList") which would otherwise be produced. choice_key = choice_item_type[:original_name] new_root[choice_key] = choice_item type_signature = get_full_type_signature(choice_type) validate_arg(choice_item, new_root, choice_key, type_signature) end if parent[key].kind_of?(Array) parent[key] << new_root else parent[key] = new_root end result = true end return result end
ruby
def validate_choice_argument(item, parent, key, item_type) result = false if item_type.kind_of?(Hash) && item_type.include?(:choices) # If we have an array of choices, we need to go over them individually. # We drop original array and replace it with the generated one that's # nested one level more. if item.kind_of?(Array) parent[key] = [] item.each do |sub_item| unless validate_choice_argument(sub_item, parent, key, item_type) validate_arg(sub_item, parent, key, item_type) end end return true end # New root needed for extra nesting we have (choice field). new_root = {} choice_items = arrayize(item) choice_items.each do |choice_item| choice_type = choice_item.delete(:xsi_type) choice_item_type = find_choice_by_xsi_type(choice_type, item_type[:choices]) if choice_type.nil? || choice_item_type.nil? raise AdsCommon::Errors::TypeMismatchError.new( 'choice subtype', choice_type, choice_item.to_s()) end choice_item[:xsi_type] = choice_type # Note we use original name that produces a string like # "BasicUserList". That's needed as the name is generated out of # standard naming ("basicUserList") which would otherwise be produced. choice_key = choice_item_type[:original_name] new_root[choice_key] = choice_item type_signature = get_full_type_signature(choice_type) validate_arg(choice_item, new_root, choice_key, type_signature) end if parent[key].kind_of?(Array) parent[key] << new_root else parent[key] = new_root end result = true end return result end
[ "def", "validate_choice_argument", "(", "item", ",", "parent", ",", "key", ",", "item_type", ")", "result", "=", "false", "if", "item_type", ".", "kind_of?", "(", "Hash", ")", "&&", "item_type", ".", "include?", "(", ":choices", ")", "if", "item", ".", "...
Special handling for choice types. Goes over each item, checks xsi_type is set and correct and injects new node for it into the tree. After that, recurces with the correct item type.
[ "Special", "handling", "for", "choice", "types", ".", "Goes", "over", "each", "item", "checks", "xsi_type", "is", "set", "and", "correct", "and", "injects", "new", "node", "for", "it", "into", "the", "tree", ".", "After", "that", "recurces", "with", "the",...
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L88-L131
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.check_extra_fields
def check_extra_fields(args_hash, known_fields) extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS unless extra_fields.empty? raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields) end end
ruby
def check_extra_fields(args_hash, known_fields) extra_fields = args_hash.keys - known_fields - IGNORED_HASH_KEYS unless extra_fields.empty? raise AdsCommon::Errors::UnexpectedParametersError.new(extra_fields) end end
[ "def", "check_extra_fields", "(", "args_hash", ",", "known_fields", ")", "extra_fields", "=", "args_hash", ".", "keys", "-", "known_fields", "-", "IGNORED_HASH_KEYS", "unless", "extra_fields", ".", "empty?", "raise", "AdsCommon", "::", "Errors", "::", "UnexpectedPar...
Checks if no extra fields provided outside of known ones.
[ "Checks", "if", "no", "extra", "fields", "provided", "outside", "of", "known", "ones", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L153-L158
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.check_required_argument_present
def check_required_argument_present(arg, field) # At least one item required, none passed. if field[:min_occurs] > 0 and arg.nil? raise AdsCommon::Errors::MissingPropertyError.new( field[:name], field[:type]) end # An object passed when an array is expected. if (field[:max_occurs] == :unbounded) and !(arg.nil? or arg.kind_of?(Array)) raise AdsCommon::Errors::TypeMismatchError.new( Array, arg.class, field[:name]) end # An array passed when an object is expected. if (field[:max_occurs] == 1) and arg.kind_of?(Array) raise AdsCommon::Errors::TypeMismatchError.new( field[:type], Array, field[:name]) end end
ruby
def check_required_argument_present(arg, field) # At least one item required, none passed. if field[:min_occurs] > 0 and arg.nil? raise AdsCommon::Errors::MissingPropertyError.new( field[:name], field[:type]) end # An object passed when an array is expected. if (field[:max_occurs] == :unbounded) and !(arg.nil? or arg.kind_of?(Array)) raise AdsCommon::Errors::TypeMismatchError.new( Array, arg.class, field[:name]) end # An array passed when an object is expected. if (field[:max_occurs] == 1) and arg.kind_of?(Array) raise AdsCommon::Errors::TypeMismatchError.new( field[:type], Array, field[:name]) end end
[ "def", "check_required_argument_present", "(", "arg", ",", "field", ")", "if", "field", "[", ":min_occurs", "]", ">", "0", "and", "arg", ".", "nil?", "raise", "AdsCommon", "::", "Errors", "::", "MissingPropertyError", ".", "new", "(", "field", "[", ":name", ...
Checks the provided data structure matches wsdl definition.
[ "Checks", "the", "provided", "data", "structure", "matches", "wsdl", "definition", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L169-L186
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.handle_name_override
def handle_name_override(args, key, original_name) rename_hash_key(args, key, original_name) replace_array_item(args[:order!], key, original_name) return original_name end
ruby
def handle_name_override(args, key, original_name) rename_hash_key(args, key, original_name) replace_array_item(args[:order!], key, original_name) return original_name end
[ "def", "handle_name_override", "(", "args", ",", "key", ",", "original_name", ")", "rename_hash_key", "(", "args", ",", "key", ",", "original_name", ")", "replace_array_item", "(", "args", "[", ":order!", "]", ",", "key", ",", "original_name", ")", "return", ...
Overrides non-standard name conversion.
[ "Overrides", "non", "-", "standard", "name", "conversion", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L189-L193
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.handle_namespace_override
def handle_namespace_override(args, key, ns) add_extra_namespace(ns) new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns) rename_hash_key(args, key, new_key) replace_array_item(args[:order!], key, new_key) return new_key end
ruby
def handle_namespace_override(args, key, ns) add_extra_namespace(ns) new_key = prefix_key_with_namespace(key.to_s.lower_camelcase, ns) rename_hash_key(args, key, new_key) replace_array_item(args[:order!], key, new_key) return new_key end
[ "def", "handle_namespace_override", "(", "args", ",", "key", ",", "ns", ")", "add_extra_namespace", "(", "ns", ")", "new_key", "=", "prefix_key_with_namespace", "(", "key", ".", "to_s", ".", "lower_camelcase", ",", "ns", ")", "rename_hash_key", "(", "args", ",...
Overrides non-default namespace if requested.
[ "Overrides", "non", "-", "default", "namespace", "if", "requested", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L196-L202
valid
googleads/google-api-ads-ruby
ads_common/lib/ads_common/parameters_validator.rb
AdsCommon.ParametersValidator.validate_arg
def validate_arg(arg, parent, key, arg_type) result = case arg when Array validate_array_arg(arg, parent, key, arg_type) when Hash validate_hash_arg(arg, parent, key, arg_type) when Time arg = validate_time_arg(arg, parent, key) validate_hash_arg(arg, parent, key, arg_type) else arg end return result end
ruby
def validate_arg(arg, parent, key, arg_type) result = case arg when Array validate_array_arg(arg, parent, key, arg_type) when Hash validate_hash_arg(arg, parent, key, arg_type) when Time arg = validate_time_arg(arg, parent, key) validate_hash_arg(arg, parent, key, arg_type) else arg end return result end
[ "def", "validate_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "result", "=", "case", "arg", "when", "Array", "validate_array_arg", "(", "arg", ",", "parent", ",", "key", ",", "arg_type", ")", "when", "Hash", "validate_hash_arg", "(", ...
Validates single argument.
[ "Validates", "single", "argument", "." ]
bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b
https://github.com/googleads/google-api-ads-ruby/blob/bf8ede5dda838bbd6161f4eb7d66b4654ae6e46b/ads_common/lib/ads_common/parameters_validator.rb#L205-L218
valid