repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.split_paths
def split_paths(paths) new_paths = {} paths.each do |p| if p.split('/').length > 1 new_paths[p.split('/').last.to_s] = p else new_paths['home'] = '/' end end new_paths end
ruby
def split_paths(paths) new_paths = {} paths.each do |p| if p.split('/').length > 1 new_paths[p.split('/').last.to_s] = p else new_paths['home'] = '/' end end new_paths end
[ "def", "split_paths", "(", "paths", ")", "new_paths", "=", "{", "}", "paths", ".", "each", "do", "|", "p", "|", "if", "p", ".", "split", "(", "'/'", ")", ".", "length", ">", "1", "new_paths", "[", "p", ".", "split", "(", "'/'", ")", ".", "last", ".", "to_s", "]", "=", "p", "else", "new_paths", "[", "'home'", "]", "=", "'/'", "end", "end", "new_paths", "end" ]
Accounting for space-separated command line arrays @since 0.1.4 @param paths [Array] @return [Hash]
[ "Accounting", "for", "space", "-", "separated", "command", "line", "arrays" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L249-L259
train
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.wraith_setup
def wraith_setup(value, name = 'phantomjs') if @settings.key?(:urls) value['domains'] = @settings[:urls] else value['domains'] = {} # @see #domain value['domains']['main'] = domain end # Set wraith defaults unless they're already defined # Wraith requires this screen_width config to be present value['screen_widths'] ||= [1280, 1024, 767] value['fuzz'] ||= '20%' value['threshold'] ||= 0 value['paths'] = @settings[:paths] temp_it("#{name}.yaml", value.to_yaml) end
ruby
def wraith_setup(value, name = 'phantomjs') if @settings.key?(:urls) value['domains'] = @settings[:urls] else value['domains'] = {} # @see #domain value['domains']['main'] = domain end # Set wraith defaults unless they're already defined # Wraith requires this screen_width config to be present value['screen_widths'] ||= [1280, 1024, 767] value['fuzz'] ||= '20%' value['threshold'] ||= 0 value['paths'] = @settings[:paths] temp_it("#{name}.yaml", value.to_yaml) end
[ "def", "wraith_setup", "(", "value", ",", "name", "=", "'phantomjs'", ")", "if", "@settings", ".", "key?", "(", ":urls", ")", "value", "[", "'domains'", "]", "=", "@settings", "[", ":urls", "]", "else", "value", "[", "'domains'", "]", "=", "{", "}", "value", "[", "'domains'", "]", "[", "'main'", "]", "=", "domain", "end", "value", "[", "'screen_widths'", "]", "||=", "[", "1280", ",", "1024", ",", "767", "]", "value", "[", "'fuzz'", "]", "||=", "'20%'", "value", "[", "'threshold'", "]", "||=", "0", "value", "[", "'paths'", "]", "=", "@settings", "[", ":paths", "]", "temp_it", "(", "\"#{name}.yaml\"", ",", "value", ".", "to_yaml", ")", "end" ]
Wraith is a complicated gem with significant configuration @see yaml_evaluate, temp_it @param value [Hash] modified data from a wraith config or injected data @param name [String] ('wraith') config file name to write and eventually load @return [String] temp file path
[ "Wraith", "is", "a", "complicated", "gem", "with", "significant", "configuration" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L278-L296
train
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.config_exists
def config_exists(file, root) present_location = File.join(root, file) File.exist?(present_location) ? present_location : false end
ruby
def config_exists(file, root) present_location = File.join(root, file) File.exist?(present_location) ? present_location : false end
[ "def", "config_exists", "(", "file", ",", "root", ")", "present_location", "=", "File", ".", "join", "(", "root", ",", "file", ")", "File", ".", "exist?", "(", "present_location", ")", "?", "present_location", ":", "false", "end" ]
See if a config file exists @see load_config_file This is used exclusively for the load_config_file method @param file [String] file name @param root [String] file path to root directory @return [String, FalseClass] if file is found return the absolute path otherwise return false so we can keep checking
[ "See", "if", "a", "config", "file", "exists" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L349-L352
train
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.jshint_ignore
def jshint_ignore(settings_data_key) return unless settings_data_key.is_a?(Hash) && settings_data_key.key?('jshintignore') jshintignore_file = [] settings_data_key['jshintignore'].each { |i| jshintignore_file << "#{i}\n" } @settings[:jshintignore] = temp_it('jshintignore.json', jshintignore_file) end
ruby
def jshint_ignore(settings_data_key) return unless settings_data_key.is_a?(Hash) && settings_data_key.key?('jshintignore') jshintignore_file = [] settings_data_key['jshintignore'].each { |i| jshintignore_file << "#{i}\n" } @settings[:jshintignore] = temp_it('jshintignore.json', jshintignore_file) end
[ "def", "jshint_ignore", "(", "settings_data_key", ")", "return", "unless", "settings_data_key", ".", "is_a?", "(", "Hash", ")", "&&", "settings_data_key", ".", "key?", "(", "'jshintignore'", ")", "jshintignore_file", "=", "[", "]", "settings_data_key", "[", "'jshintignore'", "]", ".", "each", "{", "|", "i", "|", "jshintignore_file", "<<", "\"#{i}\\n\"", "}", "@settings", "[", ":jshintignore", "]", "=", "temp_it", "(", "'jshintignore.json'", ",", "jshintignore_file", ")", "end" ]
Save jshintignore if available @since 0.1.7 @param settings_data_key [Hash] @return updates settings
[ "Save", "jshintignore", "if", "available" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L358-L364
train
ryanbreed/cef
lib/cef/event.rb
CEF.Event.format_prefix
def format_prefix values = CEF::PREFIX_ATTRIBUTES.keys.map { |k| self.send(k) } escaped = values.map do |value| escape_prefix_value(value) end escaped.join('|') end
ruby
def format_prefix values = CEF::PREFIX_ATTRIBUTES.keys.map { |k| self.send(k) } escaped = values.map do |value| escape_prefix_value(value) end escaped.join('|') end
[ "def", "format_prefix", "values", "=", "CEF", "::", "PREFIX_ATTRIBUTES", ".", "keys", ".", "map", "{", "|", "k", "|", "self", ".", "send", "(", "k", ")", "}", "escaped", "=", "values", ".", "map", "do", "|", "value", "|", "escape_prefix_value", "(", "value", ")", "end", "escaped", ".", "join", "(", "'|'", ")", "end" ]
returns a pipe-delimeted list of prefix attributes
[ "returns", "a", "pipe", "-", "delimeted", "list", "of", "prefix", "attributes" ]
99a717b392c796377eaa70be0baa9bfce3e30379
https://github.com/ryanbreed/cef/blob/99a717b392c796377eaa70be0baa9bfce3e30379/lib/cef/event.rb#L109-L115
train
ryanbreed/cef
lib/cef/event.rb
CEF.Event.format_extension
def format_extension extensions = CEF::EXTENSION_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::EXTENSION_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end # make sure time comes out as milliseconds since epoch times = CEF::TIME_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::TIME_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end (extensions + times).compact.join(" ") end
ruby
def format_extension extensions = CEF::EXTENSION_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::EXTENSION_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end # make sure time comes out as milliseconds since epoch times = CEF::TIME_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::TIME_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end (extensions + times).compact.join(" ") end
[ "def", "format_extension", "extensions", "=", "CEF", "::", "EXTENSION_ATTRIBUTES", ".", "keys", ".", "map", "do", "|", "meth", "|", "value", "=", "self", ".", "send", "(", "meth", ")", "next", "if", "value", ".", "nil?", "shortname", "=", "CEF", "::", "EXTENSION_ATTRIBUTES", "[", "meth", "]", "[", "shortname", ",", "escape_extension_value", "(", "value", ")", "]", ".", "join", "(", "\"=\"", ")", "end", "times", "=", "CEF", "::", "TIME_ATTRIBUTES", ".", "keys", ".", "map", "do", "|", "meth", "|", "value", "=", "self", ".", "send", "(", "meth", ")", "next", "if", "value", ".", "nil?", "shortname", "=", "CEF", "::", "TIME_ATTRIBUTES", "[", "meth", "]", "[", "shortname", ",", "escape_extension_value", "(", "value", ")", "]", ".", "join", "(", "\"=\"", ")", "end", "(", "extensions", "+", "times", ")", ".", "compact", ".", "join", "(", "\" \"", ")", "end" ]
returns a space-delimeted list of attribute=value pairs for all optionals
[ "returns", "a", "space", "-", "delimeted", "list", "of", "attribute", "=", "value", "pairs", "for", "all", "optionals" ]
99a717b392c796377eaa70be0baa9bfce3e30379
https://github.com/ryanbreed/cef/blob/99a717b392c796377eaa70be0baa9bfce3e30379/lib/cef/event.rb#L118-L134
train
adonespitogo/unsakini
app/controllers/unsakini/share_board_controller.rb
Unsakini.ShareBoardController.validate_params
def validate_params if params[:encrypted_password].nil? or params[:shared_user_ids].nil? or params[:board].nil? render json: {}, status: 422 return end result = has_board_access(params[:board][:id]) if result[:status] != :ok render json: {}, status: result[:status] return else if !result[:user_board].is_admin render json: {}, status: :forbidden return end @board = result[:board] @user_board = result[:user_board] end if params[:posts] params[:posts].each do |post| s = has_post_access(params[:board][:id], post[:id])[:status] if s != :ok render json: {}, status: s return end if post[:comments] post[:comments].each do |comment| s = has_comment_access(post[:id], comment[:id])[:status] if s != :ok render json: {}, status: s return end end end end end end
ruby
def validate_params if params[:encrypted_password].nil? or params[:shared_user_ids].nil? or params[:board].nil? render json: {}, status: 422 return end result = has_board_access(params[:board][:id]) if result[:status] != :ok render json: {}, status: result[:status] return else if !result[:user_board].is_admin render json: {}, status: :forbidden return end @board = result[:board] @user_board = result[:user_board] end if params[:posts] params[:posts].each do |post| s = has_post_access(params[:board][:id], post[:id])[:status] if s != :ok render json: {}, status: s return end if post[:comments] post[:comments].each do |comment| s = has_comment_access(post[:id], comment[:id])[:status] if s != :ok render json: {}, status: s return end end end end end end
[ "def", "validate_params", "if", "params", "[", ":encrypted_password", "]", ".", "nil?", "or", "params", "[", ":shared_user_ids", "]", ".", "nil?", "or", "params", "[", ":board", "]", ".", "nil?", "render", "json", ":", "{", "}", ",", "status", ":", "422", "return", "end", "result", "=", "has_board_access", "(", "params", "[", ":board", "]", "[", ":id", "]", ")", "if", "result", "[", ":status", "]", "!=", ":ok", "render", "json", ":", "{", "}", ",", "status", ":", "result", "[", ":status", "]", "return", "else", "if", "!", "result", "[", ":user_board", "]", ".", "is_admin", "render", "json", ":", "{", "}", ",", "status", ":", ":forbidden", "return", "end", "@board", "=", "result", "[", ":board", "]", "@user_board", "=", "result", "[", ":user_board", "]", "end", "if", "params", "[", ":posts", "]", "params", "[", ":posts", "]", ".", "each", "do", "|", "post", "|", "s", "=", "has_post_access", "(", "params", "[", ":board", "]", "[", ":id", "]", ",", "post", "[", ":id", "]", ")", "[", ":status", "]", "if", "s", "!=", ":ok", "render", "json", ":", "{", "}", ",", "status", ":", "s", "return", "end", "if", "post", "[", ":comments", "]", "post", "[", ":comments", "]", ".", "each", "do", "|", "comment", "|", "s", "=", "has_comment_access", "(", "post", "[", ":id", "]", ",", "comment", "[", ":id", "]", ")", "[", ":status", "]", "if", "s", "!=", ":ok", "render", "json", ":", "{", "}", ",", "status", ":", "s", "return", "end", "end", "end", "end", "end", "end" ]
Validates the contents of params against the database records.
[ "Validates", "the", "contents", "of", "params", "against", "the", "database", "records", "." ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/share_board_controller.rb#L75-L118
train
adonespitogo/unsakini
app/controllers/unsakini/users_controller.rb
Unsakini.UsersController.create
def create user = User.new(user_params) if user.save UserMailer.confirm_account(user).deliver_now render json: user, status: :created else render json: user.errors, status: 422 end end
ruby
def create user = User.new(user_params) if user.save UserMailer.confirm_account(user).deliver_now render json: user, status: :created else render json: user.errors, status: 422 end end
[ "def", "create", "user", "=", "User", ".", "new", "(", "user_params", ")", "if", "user", ".", "save", "UserMailer", ".", "confirm_account", "(", "user", ")", ".", "deliver_now", "render", "json", ":", "user", ",", "status", ":", ":created", "else", "render", "json", ":", "user", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Creates a new user
[ "Creates", "a", "new", "user" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/users_controller.rb#L11-L20
train
adonespitogo/unsakini
app/controllers/unsakini/users_controller.rb
Unsakini.UsersController.confirm
def confirm token = params[:token].to_s user = User.find_by(confirmation_token: token) if user.present? && user.confirmation_token_valid? if user.mark_as_confirmed! render json: {status: 'Account confirmed successfully.'} else render json: user.errors, status: 422 end else render json: ['Invalid token'], status: :not_found end end
ruby
def confirm token = params[:token].to_s user = User.find_by(confirmation_token: token) if user.present? && user.confirmation_token_valid? if user.mark_as_confirmed! render json: {status: 'Account confirmed successfully.'} else render json: user.errors, status: 422 end else render json: ['Invalid token'], status: :not_found end end
[ "def", "confirm", "token", "=", "params", "[", ":token", "]", ".", "to_s", "user", "=", "User", ".", "find_by", "(", "confirmation_token", ":", "token", ")", "if", "user", ".", "present?", "&&", "user", ".", "confirmation_token_valid?", "if", "user", ".", "mark_as_confirmed!", "render", "json", ":", "{", "status", ":", "'Account confirmed successfully.'", "}", "else", "render", "json", ":", "user", ".", "errors", ",", "status", ":", "422", "end", "else", "render", "json", ":", "[", "'Invalid token'", "]", ",", "status", ":", ":not_found", "end", "end" ]
confirm user account
[ "confirm", "user", "account" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/users_controller.rb#L23-L37
train
adonespitogo/unsakini
app/controllers/unsakini/users_controller.rb
Unsakini.UsersController.search
def search user = User.where("email = ? AND id != ?", params[:email], @user.id).first if user render json: user else render json: {}, status: :not_found end end
ruby
def search user = User.where("email = ? AND id != ?", params[:email], @user.id).first if user render json: user else render json: {}, status: :not_found end end
[ "def", "search", "user", "=", "User", ".", "where", "(", "\"email = ? AND id != ?\"", ",", "params", "[", ":email", "]", ",", "@user", ".", "id", ")", ".", "first", "if", "user", "render", "json", ":", "user", "else", "render", "json", ":", "{", "}", ",", "status", ":", ":not_found", "end", "end" ]
Returns the user with matching email `GET /api/users/search?email=xxx`
[ "Returns", "the", "user", "with", "matching", "email" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/users_controller.rb#L51-L58
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.commit_export
def commit_export(commit_sha = head_sha) commit_sha = commit_sha.to_s ce_commit = @g.gcommit(commit_sha) if first_commit == commit_sha ce_diff = diff_initial(first_commit) else last_commit = @g.gcommit(previous_commit(commit_sha)) ce_diff = diff(last_commit, ce_commit) end { commit_sha: commit_sha, branch: branch, message: ce_commit.message, remote_repo: remote, git_author: ce_commit.author.name, git_author_email: ce_commit.author.email, commit_date: ce_commit.author.date.to_s, diff: ce_diff } end
ruby
def commit_export(commit_sha = head_sha) commit_sha = commit_sha.to_s ce_commit = @g.gcommit(commit_sha) if first_commit == commit_sha ce_diff = diff_initial(first_commit) else last_commit = @g.gcommit(previous_commit(commit_sha)) ce_diff = diff(last_commit, ce_commit) end { commit_sha: commit_sha, branch: branch, message: ce_commit.message, remote_repo: remote, git_author: ce_commit.author.name, git_author_email: ce_commit.author.email, commit_date: ce_commit.author.date.to_s, diff: ce_diff } end
[ "def", "commit_export", "(", "commit_sha", "=", "head_sha", ")", "commit_sha", "=", "commit_sha", ".", "to_s", "ce_commit", "=", "@g", ".", "gcommit", "(", "commit_sha", ")", "if", "first_commit", "==", "commit_sha", "ce_diff", "=", "diff_initial", "(", "first_commit", ")", "else", "last_commit", "=", "@g", ".", "gcommit", "(", "previous_commit", "(", "commit_sha", ")", ")", "ce_diff", "=", "diff", "(", "last_commit", ",", "ce_commit", ")", "end", "{", "commit_sha", ":", "commit_sha", ",", "branch", ":", "branch", ",", "message", ":", "ce_commit", ".", "message", ",", "remote_repo", ":", "remote", ",", "git_author", ":", "ce_commit", ".", "author", ".", "name", ",", "git_author_email", ":", "ce_commit", ".", "author", ".", "email", ",", "commit_date", ":", "ce_commit", ".", "author", ".", "date", ".", "to_s", ",", "diff", ":", "ce_diff", "}", "end" ]
Set up instance variables Inherits settings from {Config#initialize} @param opts [Hash] options passed directly to config @option opts [Config object] :config custom Maximus::Config object @option opts [String] :commit accepts sha, "working", "last", or "master". 30,000 foot view of a commit @param commit_sha [String] (head_sha) the sha of the commit @return [Hash] commit data
[ "Set", "up", "instance", "variables" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L31-L53
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.compare
def compare(sha1 = master_commit_sha, sha2 = head_sha) diff_return = {} sha1 = define_psuedo_commit if @settings[:commit] # Reverse so that we go in chronological order git_spread = commit_range(sha1, sha2).reverse git_spread.each do |git_sha| # Grab all files in that commit and group them by extension # If working copy, just give the diff names of the files changed files = @psuedo_commit ? working_copy_files : files_by_sha(git_sha) diff_return[git_sha] = match_associations(git_sha, files) end diff_return end
ruby
def compare(sha1 = master_commit_sha, sha2 = head_sha) diff_return = {} sha1 = define_psuedo_commit if @settings[:commit] # Reverse so that we go in chronological order git_spread = commit_range(sha1, sha2).reverse git_spread.each do |git_sha| # Grab all files in that commit and group them by extension # If working copy, just give the diff names of the files changed files = @psuedo_commit ? working_copy_files : files_by_sha(git_sha) diff_return[git_sha] = match_associations(git_sha, files) end diff_return end
[ "def", "compare", "(", "sha1", "=", "master_commit_sha", ",", "sha2", "=", "head_sha", ")", "diff_return", "=", "{", "}", "sha1", "=", "define_psuedo_commit", "if", "@settings", "[", ":commit", "]", "git_spread", "=", "commit_range", "(", "sha1", ",", "sha2", ")", ".", "reverse", "git_spread", ".", "each", "do", "|", "git_sha", "|", "files", "=", "@psuedo_commit", "?", "working_copy_files", ":", "files_by_sha", "(", "git_sha", ")", "diff_return", "[", "git_sha", "]", "=", "match_associations", "(", "git_sha", ",", "files", ")", "end", "diff_return", "end" ]
Compare two commits and get line number ranges of changed patches @example output from the method { 'sha': { rb: { filename: 'file.rb', changes: { ['0..4'], ['10..20'] } } } } @param sha1 [String] @param sha2 [String] @return [Hash] diff_return files changed grouped by file extension and line number
[ "Compare", "two", "commits", "and", "get", "line", "number", "ranges", "of", "changed", "patches" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L72-L89
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lints_and_stats
def lints_and_stats(lint_by_path = false, git_shas = compare, nuclear = false) return false if git_shas.blank? base_branch = branch git_ouput = {} git_shas.each do |sha, exts| create_branch(sha) unless @psuedo_commit sha = sha.to_s puts sha.color(:blue) exts.each do |ext, files| # For relevant_lines data lint_opts = { git_files: files, config: @config, file_paths: (lint_file_paths(files, ext) if lint_by_path) } git_ouput[sha] = nuclear ? lints_and_stats_nuclear(lint_opts) : lints_and_stats_switch(ext, lint_opts) end destroy_branch(base_branch, sha) unless @psuedo_commit end git_ouput end
ruby
def lints_and_stats(lint_by_path = false, git_shas = compare, nuclear = false) return false if git_shas.blank? base_branch = branch git_ouput = {} git_shas.each do |sha, exts| create_branch(sha) unless @psuedo_commit sha = sha.to_s puts sha.color(:blue) exts.each do |ext, files| # For relevant_lines data lint_opts = { git_files: files, config: @config, file_paths: (lint_file_paths(files, ext) if lint_by_path) } git_ouput[sha] = nuclear ? lints_and_stats_nuclear(lint_opts) : lints_and_stats_switch(ext, lint_opts) end destroy_branch(base_branch, sha) unless @psuedo_commit end git_ouput end
[ "def", "lints_and_stats", "(", "lint_by_path", "=", "false", ",", "git_shas", "=", "compare", ",", "nuclear", "=", "false", ")", "return", "false", "if", "git_shas", ".", "blank?", "base_branch", "=", "branch", "git_ouput", "=", "{", "}", "git_shas", ".", "each", "do", "|", "sha", ",", "exts", "|", "create_branch", "(", "sha", ")", "unless", "@psuedo_commit", "sha", "=", "sha", ".", "to_s", "puts", "sha", ".", "color", "(", ":blue", ")", "exts", ".", "each", "do", "|", "ext", ",", "files", "|", "lint_opts", "=", "{", "git_files", ":", "files", ",", "config", ":", "@config", ",", "file_paths", ":", "(", "lint_file_paths", "(", "files", ",", "ext", ")", "if", "lint_by_path", ")", "}", "git_ouput", "[", "sha", "]", "=", "nuclear", "?", "lints_and_stats_nuclear", "(", "lint_opts", ")", ":", "lints_and_stats_switch", "(", "ext", ",", "lint_opts", ")", "end", "destroy_branch", "(", "base_branch", ",", "sha", ")", "unless", "@psuedo_commit", "end", "git_ouput", "end" ]
Run appropriate lint for every sha in commit history. For each sha a new branch is created then deleted @example sample output { 'sha': { lints: { scsslint: { files_inspec... }, }, statisti... }, 'sha'... } @see compare @param lint_by_path [Boolean] only lint by files in git commit and not the commit as a whole @param git_shas [Hash] (#compare) a hash of gitcommit shas and relevant file types in the commit @param nuclear [Boolean] do everything regardless of what's in the commit @return [Hash] data all data grouped by task
[ "Run", "appropriate", "lint", "for", "every", "sha", "in", "commit", "history", ".", "For", "each", "sha", "a", "new", "branch", "is", "created", "then", "deleted" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L114-L141
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.associations
def associations { css: ['css'], scss: ['scss', 'sass'], js: ['js'], ruby: ['rb', 'Gemfile', 'lock', 'yml', 'Rakefile', 'ru', 'rdoc', 'rake', 'Capfile', 'jbuilder'], rails: ['slim', 'haml', 'jbuilder', 'erb'], images: ['png', 'jpg', 'jpeg', 'gif'], static: ['pdf', 'txt', 'doc', 'docx', 'csv', 'xls', 'xlsx'], markup: ['html', 'xml', 'xhtml'], markdown: ['md', 'markdown', 'mdown'], php: ['php', 'ini'] } end
ruby
def associations { css: ['css'], scss: ['scss', 'sass'], js: ['js'], ruby: ['rb', 'Gemfile', 'lock', 'yml', 'Rakefile', 'ru', 'rdoc', 'rake', 'Capfile', 'jbuilder'], rails: ['slim', 'haml', 'jbuilder', 'erb'], images: ['png', 'jpg', 'jpeg', 'gif'], static: ['pdf', 'txt', 'doc', 'docx', 'csv', 'xls', 'xlsx'], markup: ['html', 'xml', 'xhtml'], markdown: ['md', 'markdown', 'mdown'], php: ['php', 'ini'] } end
[ "def", "associations", "{", "css", ":", "[", "'css'", "]", ",", "scss", ":", "[", "'scss'", ",", "'sass'", "]", ",", "js", ":", "[", "'js'", "]", ",", "ruby", ":", "[", "'rb'", ",", "'Gemfile'", ",", "'lock'", ",", "'yml'", ",", "'Rakefile'", ",", "'ru'", ",", "'rdoc'", ",", "'rake'", ",", "'Capfile'", ",", "'jbuilder'", "]", ",", "rails", ":", "[", "'slim'", ",", "'haml'", ",", "'jbuilder'", ",", "'erb'", "]", ",", "images", ":", "[", "'png'", ",", "'jpg'", ",", "'jpeg'", ",", "'gif'", "]", ",", "static", ":", "[", "'pdf'", ",", "'txt'", ",", "'doc'", ",", "'docx'", ",", "'csv'", ",", "'xls'", ",", "'xlsx'", "]", ",", "markup", ":", "[", "'html'", ",", "'xml'", ",", "'xhtml'", "]", ",", "markdown", ":", "[", "'md'", ",", "'markdown'", ",", "'mdown'", "]", ",", "php", ":", "[", "'php'", ",", "'ini'", "]", "}", "end" ]
Define associations to linters based on file extension @return [Hash] linters and extension arrays
[ "Define", "associations", "to", "linters", "based", "on", "file", "extension" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L145-L158
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.diff
def diff(old_commit, new_commit) stats = @g.diff(old_commit, new_commit).stats lines = lines_added(new_commit.sha) return if !lines.is_a?(Hash) || stats.blank? lines.each do |filename, filelines| stats[:files][filename][:lines_added] = filelines if stats[:files].key?(filename) end stats end
ruby
def diff(old_commit, new_commit) stats = @g.diff(old_commit, new_commit).stats lines = lines_added(new_commit.sha) return if !lines.is_a?(Hash) || stats.blank? lines.each do |filename, filelines| stats[:files][filename][:lines_added] = filelines if stats[:files].key?(filename) end stats end
[ "def", "diff", "(", "old_commit", ",", "new_commit", ")", "stats", "=", "@g", ".", "diff", "(", "old_commit", ",", "new_commit", ")", ".", "stats", "lines", "=", "lines_added", "(", "new_commit", ".", "sha", ")", "return", "if", "!", "lines", ".", "is_a?", "(", "Hash", ")", "||", "stats", ".", "blank?", "lines", ".", "each", "do", "|", "filename", ",", "filelines", "|", "stats", "[", ":files", "]", "[", "filename", "]", "[", ":lines_added", "]", "=", "filelines", "if", "stats", "[", ":files", "]", ".", "key?", "(", "filename", ")", "end", "stats", "end" ]
Get general stats of commit on HEAD versus last commit on master branch @modified 0.1.4 @param old_commit [Git::Object] @param new_commit [Git::Object] @return [Git::Diff] hash of abbreviated, useful stats with added lines
[ "Get", "general", "stats", "of", "commit", "on", "HEAD", "versus", "last", "commit", "on", "master", "branch" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L227-L237
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.diff_initial
def diff_initial(commit_sha) data = commit_information(commit_sha) value = { total: { insertions: 0, deletions: 0, lines: 0, files: data.length }, files: {} } data.each do |d| item = d.split("\t") insertions = item[0].to_i value[:total][:insertions] += insertions value[:total][:lines] += insertions value[:files][item[2]] = { insertions: insertions, deletions: 0, lines_added: ["0..#{item[0]}"] } end value end
ruby
def diff_initial(commit_sha) data = commit_information(commit_sha) value = { total: { insertions: 0, deletions: 0, lines: 0, files: data.length }, files: {} } data.each do |d| item = d.split("\t") insertions = item[0].to_i value[:total][:insertions] += insertions value[:total][:lines] += insertions value[:files][item[2]] = { insertions: insertions, deletions: 0, lines_added: ["0..#{item[0]}"] } end value end
[ "def", "diff_initial", "(", "commit_sha", ")", "data", "=", "commit_information", "(", "commit_sha", ")", "value", "=", "{", "total", ":", "{", "insertions", ":", "0", ",", "deletions", ":", "0", ",", "lines", ":", "0", ",", "files", ":", "data", ".", "length", "}", ",", "files", ":", "{", "}", "}", "data", ".", "each", "do", "|", "d", "|", "item", "=", "d", ".", "split", "(", "\"\\t\"", ")", "insertions", "=", "item", "[", "0", "]", ".", "to_i", "value", "[", ":total", "]", "[", ":insertions", "]", "+=", "insertions", "value", "[", ":total", "]", "[", ":lines", "]", "+=", "insertions", "value", "[", ":files", "]", "[", "item", "[", "2", "]", "]", "=", "{", "insertions", ":", "insertions", ",", "deletions", ":", "0", ",", "lines_added", ":", "[", "\"0..#{item[0]}\"", "]", "}", "end", "value", "end" ]
Get diff stats on just the initial commit Ruby-git doesn't support this well @see diff @since 0.1.5 @param commit_sha [String] @return [Hash] stat data similar to Ruby-git's Diff.stats return
[ "Get", "diff", "stats", "on", "just", "the", "initial", "commit", "Ruby", "-", "git", "doesn", "t", "support", "this", "well" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L245-L268
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.match_associations
def match_associations(commit_sha, files) new_lines = lines_added(commit_sha) files = files.split("\n").group_by { |f| f.split('.').pop } associations.each do |ext, related| files[ext] ||= [] related.each do |child| next if files[child].blank? files[child].each do |c| # hack to ignore deleted files files[child] = new_lines[c].blank? ? [] : [ filename: File.join(@config.working_dir, c), changes: new_lines[c] ] end files[ext].concat(files[child]) files.delete(child) end end files.delete_if { |k,v| v.blank? || k.nil? } files end
ruby
def match_associations(commit_sha, files) new_lines = lines_added(commit_sha) files = files.split("\n").group_by { |f| f.split('.').pop } associations.each do |ext, related| files[ext] ||= [] related.each do |child| next if files[child].blank? files[child].each do |c| # hack to ignore deleted files files[child] = new_lines[c].blank? ? [] : [ filename: File.join(@config.working_dir, c), changes: new_lines[c] ] end files[ext].concat(files[child]) files.delete(child) end end files.delete_if { |k,v| v.blank? || k.nil? } files end
[ "def", "match_associations", "(", "commit_sha", ",", "files", ")", "new_lines", "=", "lines_added", "(", "commit_sha", ")", "files", "=", "files", ".", "split", "(", "\"\\n\"", ")", ".", "group_by", "{", "|", "f", "|", "f", ".", "split", "(", "'.'", ")", ".", "pop", "}", "associations", ".", "each", "do", "|", "ext", ",", "related", "|", "files", "[", "ext", "]", "||=", "[", "]", "related", ".", "each", "do", "|", "child", "|", "next", "if", "files", "[", "child", "]", ".", "blank?", "files", "[", "child", "]", ".", "each", "do", "|", "c", "|", "files", "[", "child", "]", "=", "new_lines", "[", "c", "]", ".", "blank?", "?", "[", "]", ":", "[", "filename", ":", "File", ".", "join", "(", "@config", ".", "working_dir", ",", "c", ")", ",", "changes", ":", "new_lines", "[", "c", "]", "]", "end", "files", "[", "ext", "]", ".", "concat", "(", "files", "[", "child", "]", ")", "files", ".", "delete", "(", "child", ")", "end", "end", "files", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "blank?", "||", "k", ".", "nil?", "}", "files", "end" ]
Associate files by extension and match their changes @since 0.1.5 @param commit_sha [String] @param files [String] list of files from git @return [Hash] files with matched extensions and changes
[ "Associate", "files", "by", "extension", "and", "match", "their", "changes" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L275-L296
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lints_and_stats_nuclear
def lints_and_stats_nuclear(lint_opts) { lints: { scsslint: Maximus::Scsslint.new(lint_opts).result, jshint: Maximus::Jshint.new(lint_opts).result, rubocop: Maximus::Rubocop.new(lint_opts).result, railsbp: Maximus::Railsbp.new(lint_opts).result, brakeman: Maximus::Brakeman.new(lint_opts).result }, statistics: { stylestat: Maximus::Stylestats.new({config: @config}).result, phantomas: Maximus::Phantomas.new({config: @config}).result, wraith: Maximus::Wraith.new({config: @config}).result } } end
ruby
def lints_and_stats_nuclear(lint_opts) { lints: { scsslint: Maximus::Scsslint.new(lint_opts).result, jshint: Maximus::Jshint.new(lint_opts).result, rubocop: Maximus::Rubocop.new(lint_opts).result, railsbp: Maximus::Railsbp.new(lint_opts).result, brakeman: Maximus::Brakeman.new(lint_opts).result }, statistics: { stylestat: Maximus::Stylestats.new({config: @config}).result, phantomas: Maximus::Phantomas.new({config: @config}).result, wraith: Maximus::Wraith.new({config: @config}).result } } end
[ "def", "lints_and_stats_nuclear", "(", "lint_opts", ")", "{", "lints", ":", "{", "scsslint", ":", "Maximus", "::", "Scsslint", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "jshint", ":", "Maximus", "::", "Jshint", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "rubocop", ":", "Maximus", "::", "Rubocop", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "railsbp", ":", "Maximus", "::", "Railsbp", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "brakeman", ":", "Maximus", "::", "Brakeman", ".", "new", "(", "lint_opts", ")", ".", "result", "}", ",", "statistics", ":", "{", "stylestat", ":", "Maximus", "::", "Stylestats", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", ",", "phantomas", ":", "Maximus", "::", "Phantomas", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", ",", "wraith", ":", "Maximus", "::", "Wraith", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "}", "}", "end" ]
All data retrieved from reports @since 0.1.6 @param lint_opts [Hash] @return [Hash]
[ "All", "data", "retrieved", "from", "reports" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L302-L317
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lints_and_stats_switch
def lints_and_stats_switch(ext, lint_opts) result = { lints: {}, statistics: {} } lints = result[:lints] statistics = result[:statistics] case ext when :scss lints[:scsslint] = Maximus::Scsslint.new(lint_opts).result # @todo stylestat is singular here because model name in Rails is singular. # But adding a .classify when it's converted to a model chops off the end s on 'phantomas', # which breaks the model name. statistics[:stylestat] = Maximus::Stylestats.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :js lints[:jshint] = Maximus::Jshint.new(lint_opts).result statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :ruby lints[:rubocop] = Maximus::Rubocop.new(lint_opts).result lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result lints[:brakeman] = Maximus::Brakeman.new(lint_opts).result when :rails lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result end result end
ruby
def lints_and_stats_switch(ext, lint_opts) result = { lints: {}, statistics: {} } lints = result[:lints] statistics = result[:statistics] case ext when :scss lints[:scsslint] = Maximus::Scsslint.new(lint_opts).result # @todo stylestat is singular here because model name in Rails is singular. # But adding a .classify when it's converted to a model chops off the end s on 'phantomas', # which breaks the model name. statistics[:stylestat] = Maximus::Stylestats.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :js lints[:jshint] = Maximus::Jshint.new(lint_opts).result statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :ruby lints[:rubocop] = Maximus::Rubocop.new(lint_opts).result lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result lints[:brakeman] = Maximus::Brakeman.new(lint_opts).result when :rails lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result end result end
[ "def", "lints_and_stats_switch", "(", "ext", ",", "lint_opts", ")", "result", "=", "{", "lints", ":", "{", "}", ",", "statistics", ":", "{", "}", "}", "lints", "=", "result", "[", ":lints", "]", "statistics", "=", "result", "[", ":statistics", "]", "case", "ext", "when", ":scss", "lints", "[", ":scsslint", "]", "=", "Maximus", "::", "Scsslint", ".", "new", "(", "lint_opts", ")", ".", "result", "statistics", "[", ":stylestat", "]", "=", "Maximus", "::", "Stylestats", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "statistics", "[", ":phantomas", "]", "||=", "Maximus", "::", "Phantomas", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "statistics", "[", ":wraith", "]", "||=", "Maximus", "::", "Wraith", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "when", ":js", "lints", "[", ":jshint", "]", "=", "Maximus", "::", "Jshint", ".", "new", "(", "lint_opts", ")", ".", "result", "statistics", "[", ":phantomas", "]", "||=", "Maximus", "::", "Phantomas", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "statistics", "[", ":wraith", "]", "||=", "Maximus", "::", "Wraith", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "when", ":ruby", "lints", "[", ":rubocop", "]", "=", "Maximus", "::", "Rubocop", ".", "new", "(", "lint_opts", ")", ".", "result", "lints", "[", ":railsbp", "]", "||=", "Maximus", "::", "Railsbp", ".", "new", "(", "lint_opts", ")", ".", "result", "lints", "[", ":brakeman", "]", "=", "Maximus", "::", "Brakeman", ".", "new", "(", "lint_opts", ")", ".", "result", "when", ":rails", "lints", "[", ":railsbp", "]", "||=", "Maximus", "::", "Railsbp", ".", "new", "(", "lint_opts", ")", ".", "result", "end", "result", "end" ]
Specific data retrieved by file extension @since 0.1.6 @param ext [String] @param lint_opts [Hash] @return [Hash]
[ "Specific", "data", "retrieved", "by", "file", "extension" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L324-L361
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.destroy_branch
def destroy_branch(base_branch, sha) if base_branch == "maximus_#{sha}" @g.branch('master').checkout else @g.branch(base_branch).checkout end @g.branch("maximus_#{sha}").delete end
ruby
def destroy_branch(base_branch, sha) if base_branch == "maximus_#{sha}" @g.branch('master').checkout else @g.branch(base_branch).checkout end @g.branch("maximus_#{sha}").delete end
[ "def", "destroy_branch", "(", "base_branch", ",", "sha", ")", "if", "base_branch", "==", "\"maximus_#{sha}\"", "@g", ".", "branch", "(", "'master'", ")", ".", "checkout", "else", "@g", ".", "branch", "(", "base_branch", ")", ".", "checkout", "end", "@g", ".", "branch", "(", "\"maximus_#{sha}\"", ")", ".", "delete", "end" ]
Destroy created branch @since 0.1.5 @param base_branch [String] branch we started on @param sha [String] used to check against created branch name
[ "Destroy", "created", "branch" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L377-L384
train
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lint_file_paths
def lint_file_paths(files, ext) file_list = files.map { |f| f[:filename] }.compact # Lints accept files differently ext == :ruby ? file_list.join(' ') : file_list.join(',') end
ruby
def lint_file_paths(files, ext) file_list = files.map { |f| f[:filename] }.compact # Lints accept files differently ext == :ruby ? file_list.join(' ') : file_list.join(',') end
[ "def", "lint_file_paths", "(", "files", ",", "ext", ")", "file_list", "=", "files", ".", "map", "{", "|", "f", "|", "f", "[", ":filename", "]", "}", ".", "compact", "ext", "==", ":ruby", "?", "file_list", ".", "join", "(", "' '", ")", ":", "file_list", ".", "join", "(", "','", ")", "end" ]
Get list of file paths @param files [Hash] hash of files denoted by key 'filename' @param ext [String] file extension - different extensions are joined different ways @return [String] file paths delimited by comma or space
[ "Get", "list", "of", "file", "paths" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L390-L394
train
ronin-ruby/ronin-support
lib/ronin/path.rb
Ronin.Path.join
def join(*names) joined_path = if root? then '' else self.to_s end names.each do |name| name = name.to_s joined_path << @separator unless name.start_with?(@separator) joined_path << name unless name == @separator end return self.class.new(joined_path,@separator) end
ruby
def join(*names) joined_path = if root? then '' else self.to_s end names.each do |name| name = name.to_s joined_path << @separator unless name.start_with?(@separator) joined_path << name unless name == @separator end return self.class.new(joined_path,@separator) end
[ "def", "join", "(", "*", "names", ")", "joined_path", "=", "if", "root?", "then", "''", "else", "self", ".", "to_s", "end", "names", ".", "each", "do", "|", "name", "|", "name", "=", "name", ".", "to_s", "joined_path", "<<", "@separator", "unless", "name", ".", "start_with?", "(", "@separator", ")", "joined_path", "<<", "name", "unless", "name", "==", "@separator", "end", "return", "self", ".", "class", ".", "new", "(", "joined_path", ",", "@separator", ")", "end" ]
Joins directory names together with the path, but does not resolve the resulting path. @param [Array] names The names to join together. @return [Path] The joined path. @example Path.up(7).join('etc/passwd') # => #<Ronin::Path:../../../../../../../etc/passwd>
[ "Joins", "directory", "names", "together", "with", "the", "path", "but", "does", "not", "resolve", "the", "resulting", "path", "." ]
bc2af0e75098c13133789118245cb185f8c6b4c9
https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/path.rb#L115-L128
train
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_claims
def validate_claims(options = {}) validate_exp(options[:max_clock_skew]) unless options[:ignore_exp] validate_nbf(options[:max_clock_skew]) unless options[:ignore_nbf] validate_iss(options[:valid_iss]) validate_aud(options[:valid_aud]) self end
ruby
def validate_claims(options = {}) validate_exp(options[:max_clock_skew]) unless options[:ignore_exp] validate_nbf(options[:max_clock_skew]) unless options[:ignore_nbf] validate_iss(options[:valid_iss]) validate_aud(options[:valid_aud]) self end
[ "def", "validate_claims", "(", "options", "=", "{", "}", ")", "validate_exp", "(", "options", "[", ":max_clock_skew", "]", ")", "unless", "options", "[", ":ignore_exp", "]", "validate_nbf", "(", "options", "[", ":max_clock_skew", "]", ")", "unless", "options", "[", ":ignore_nbf", "]", "validate_iss", "(", "options", "[", ":valid_iss", "]", ")", "validate_aud", "(", "options", "[", ":valid_aud", "]", ")", "self", "end" ]
Validates the set of claims. @param options [Hash] The claim validation options (see {Sandal::DEFAULT_OPTIONS} for details). @return [Hash] A reference to self. @raise [Sandal::ClaimError] One or more claims is invalid.
[ "Validates", "the", "set", "of", "claims", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L12-L18
train
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_exp
def validate_exp(max_clock_skew = 0) max_clock_skew ||= 0 exp = time_claim("exp") if exp && exp <= (Time.now - max_clock_skew) raise Sandal::ExpiredTokenError, "The token has expired." end end
ruby
def validate_exp(max_clock_skew = 0) max_clock_skew ||= 0 exp = time_claim("exp") if exp && exp <= (Time.now - max_clock_skew) raise Sandal::ExpiredTokenError, "The token has expired." end end
[ "def", "validate_exp", "(", "max_clock_skew", "=", "0", ")", "max_clock_skew", "||=", "0", "exp", "=", "time_claim", "(", "\"exp\"", ")", "if", "exp", "&&", "exp", "<=", "(", "Time", ".", "now", "-", "max_clock_skew", ")", "raise", "Sandal", "::", "ExpiredTokenError", ",", "\"The token has expired.\"", "end", "end" ]
Validates the expires claim. @param max_clock_skew [Numeric] The maximum clock skew, in seconds. @return [void]. @raise [Sandal::ClaimError] The "exp" claim is invalid, or the token has expired.
[ "Validates", "the", "expires", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L26-L33
train
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_nbf
def validate_nbf(max_clock_skew = 0) max_clock_skew ||= 0 nbf = time_claim("nbf") if nbf && nbf > (Time.now + max_clock_skew) raise Sandal::ClaimError, "The token is not valid yet." end end
ruby
def validate_nbf(max_clock_skew = 0) max_clock_skew ||= 0 nbf = time_claim("nbf") if nbf && nbf > (Time.now + max_clock_skew) raise Sandal::ClaimError, "The token is not valid yet." end end
[ "def", "validate_nbf", "(", "max_clock_skew", "=", "0", ")", "max_clock_skew", "||=", "0", "nbf", "=", "time_claim", "(", "\"nbf\"", ")", "if", "nbf", "&&", "nbf", ">", "(", "Time", ".", "now", "+", "max_clock_skew", ")", "raise", "Sandal", "::", "ClaimError", ",", "\"The token is not valid yet.\"", "end", "end" ]
Validates the not-before claim. @param max_clock_skew [Numeric] The maximum clock skew, in seconds. @return [void]. @raise [Sandal::ClaimError] The "nbf" claim is invalid, or the token is not valid yet.
[ "Validates", "the", "not", "-", "before", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L41-L48
train
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_iss
def validate_iss(valid_iss) return unless valid_iss && valid_iss.length > 0 unless valid_iss.include?(self["iss"]) raise Sandal::ClaimError, "The issuer is invalid." end end
ruby
def validate_iss(valid_iss) return unless valid_iss && valid_iss.length > 0 unless valid_iss.include?(self["iss"]) raise Sandal::ClaimError, "The issuer is invalid." end end
[ "def", "validate_iss", "(", "valid_iss", ")", "return", "unless", "valid_iss", "&&", "valid_iss", ".", "length", ">", "0", "unless", "valid_iss", ".", "include?", "(", "self", "[", "\"iss\"", "]", ")", "raise", "Sandal", "::", "ClaimError", ",", "\"The issuer is invalid.\"", "end", "end" ]
Validates the issuer claim. @param valid_iss [Array] The valid issuers. @return [void]. @raise [Sandal::ClaimError] The "iss" claim value is not a valid issuer.
[ "Validates", "the", "issuer", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L55-L61
train
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_aud
def validate_aud(valid_aud) return unless valid_aud && valid_aud.length > 0 aud = self["aud"] aud = [aud] unless aud.is_a?(Array) unless (aud & valid_aud).length > 0 raise Sandal::ClaimError, "The audence is invalid." end end
ruby
def validate_aud(valid_aud) return unless valid_aud && valid_aud.length > 0 aud = self["aud"] aud = [aud] unless aud.is_a?(Array) unless (aud & valid_aud).length > 0 raise Sandal::ClaimError, "The audence is invalid." end end
[ "def", "validate_aud", "(", "valid_aud", ")", "return", "unless", "valid_aud", "&&", "valid_aud", ".", "length", ">", "0", "aud", "=", "self", "[", "\"aud\"", "]", "aud", "=", "[", "aud", "]", "unless", "aud", ".", "is_a?", "(", "Array", ")", "unless", "(", "aud", "&", "valid_aud", ")", ".", "length", ">", "0", "raise", "Sandal", "::", "ClaimError", ",", "\"The audence is invalid.\"", "end", "end" ]
Validates the audience claim. @param valid_aud [Array] The valid audiences. @return [void]. @raise [Sandal::ClaimError] The "aud" claim value does not contain a valid audience.
[ "Validates", "the", "audience", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L69-L77
train
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.time_claim
def time_claim(name) claim = self[name] if claim begin Time.at(claim) rescue raise Sandal::ClaimError, "The \"#{name}\" claim is invalid." end end end
ruby
def time_claim(name) claim = self[name] if claim begin Time.at(claim) rescue raise Sandal::ClaimError, "The \"#{name}\" claim is invalid." end end end
[ "def", "time_claim", "(", "name", ")", "claim", "=", "self", "[", "name", "]", "if", "claim", "begin", "Time", ".", "at", "(", "claim", ")", "rescue", "raise", "Sandal", "::", "ClaimError", ",", "\"The \\\"#{name}\\\" claim is invalid.\"", "end", "end", "end" ]
Gets the value of a claim as a Time.
[ "Gets", "the", "value", "of", "a", "claim", "as", "a", "Time", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L82-L91
train
paulsamuels/xcunique
lib/xcunique/sorter.rb
Xcunique.Sorter.sort
def sort objects.values.each do |object| SORTABLE_ITEMS.select { |key| object.has_key?(key) }.each do |key| object[key].sort_by!(&method(:comparator)) end end project end
ruby
def sort objects.values.each do |object| SORTABLE_ITEMS.select { |key| object.has_key?(key) }.each do |key| object[key].sort_by!(&method(:comparator)) end end project end
[ "def", "sort", "objects", ".", "values", ".", "each", "do", "|", "object", "|", "SORTABLE_ITEMS", ".", "select", "{", "|", "key", "|", "object", ".", "has_key?", "(", "key", ")", "}", ".", "each", "do", "|", "key", "|", "object", "[", "key", "]", ".", "sort_by!", "(", "&", "method", "(", ":comparator", ")", ")", "end", "end", "project", "end" ]
Returns a new instance of Sorter @param project [Hash] the project to sort Traverses the objects in the project clone and sorts in place objects that are held under the `SORTABLE_ITEMS` keys @return [Hash] a sorted project
[ "Returns", "a", "new", "instance", "of", "Sorter" ]
0a95740109dc504734acf01dfbb979d09fb5d9fd
https://github.com/paulsamuels/xcunique/blob/0a95740109dc504734acf01dfbb979d09fb5d9fd/lib/xcunique/sorter.rb#L24-L31
train
paulsamuels/xcunique
lib/xcunique/sorter.rb
Xcunique.Sorter.comparator
def comparator uuid prefix = objects[uuid][Keys::ISA] == Keys::PBXGroup ? ' ' : '' prefix + Helpers.resolve_attributes(uuid, objects) end
ruby
def comparator uuid prefix = objects[uuid][Keys::ISA] == Keys::PBXGroup ? ' ' : '' prefix + Helpers.resolve_attributes(uuid, objects) end
[ "def", "comparator", "uuid", "prefix", "=", "objects", "[", "uuid", "]", "[", "Keys", "::", "ISA", "]", "==", "Keys", "::", "PBXGroup", "?", "' '", ":", "''", "prefix", "+", "Helpers", ".", "resolve_attributes", "(", "uuid", ",", "objects", ")", "end" ]
The comparator used during the sort The comparator resolves the attributes for the node and appends a known prefix to objects where `isa = PBXGroup` to ensure that groups are sorted above files @param uuid [String] the uuid of the object to examine @!visibility public
[ "The", "comparator", "used", "during", "the", "sort" ]
0a95740109dc504734acf01dfbb979d09fb5d9fd
https://github.com/paulsamuels/xcunique/blob/0a95740109dc504734acf01dfbb979d09fb5d9fd/lib/xcunique/sorter.rb#L45-L48
train
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.check
def check(filename, content) node = parse(filename, content) node.file = filename check_node(node) end
ruby
def check(filename, content) node = parse(filename, content) node.file = filename check_node(node) end
[ "def", "check", "(", "filename", ",", "content", ")", "node", "=", "parse", "(", "filename", ",", "content", ")", "node", ".", "file", "=", "filename", "check_node", "(", "node", ")", "end" ]
check the ruby sexp nodes for the ruby file. @param [String] filename is the filename of ruby code. @param [String] content is the content of ruby file.
[ "check", "the", "ruby", "sexp", "nodes", "for", "the", "ruby", "file", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L21-L25
train
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.after_check
def after_check @checkers.each do |checker| after_check_callbacks = checker.class.get_callbacks(:after_check) after_check_callbacks.each do |block| checker.instance_exec &block end end end
ruby
def after_check @checkers.each do |checker| after_check_callbacks = checker.class.get_callbacks(:after_check) after_check_callbacks.each do |block| checker.instance_exec &block end end end
[ "def", "after_check", "@checkers", ".", "each", "do", "|", "checker", "|", "after_check_callbacks", "=", "checker", ".", "class", ".", "get_callbacks", "(", ":after_check", ")", "after_check_callbacks", ".", "each", "do", "|", "block", "|", "checker", ".", "instance_exec", "&", "block", "end", "end", "end" ]
trigger all after_check callbacks defined in all checkers.
[ "trigger", "all", "after_check", "callbacks", "defined", "in", "all", "checkers", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L28-L35
train
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.parse
def parse(filename, content) Sexp.from_array(Ripper::SexpBuilder.new(content).parse) rescue Exception raise AnalyzerException.new("#{filename} looks like it's not a valid Ruby file. Skipping...") end
ruby
def parse(filename, content) Sexp.from_array(Ripper::SexpBuilder.new(content).parse) rescue Exception raise AnalyzerException.new("#{filename} looks like it's not a valid Ruby file. Skipping...") end
[ "def", "parse", "(", "filename", ",", "content", ")", "Sexp", ".", "from_array", "(", "Ripper", "::", "SexpBuilder", ".", "new", "(", "content", ")", ".", "parse", ")", "rescue", "Exception", "raise", "AnalyzerException", ".", "new", "(", "\"#{filename} looks like it's not a valid Ruby file. Skipping...\"", ")", "end" ]
parse ruby code. @param [String] filename is the filename of ruby code. @param [String] content is the content of ruby file.
[ "parse", "ruby", "code", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L41-L45
train
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.check_node
def check_node(node) checkers = @checks[node.sexp_type] if checkers checkers.each { |checker| checker.node_start(node) if checker.parse_file?(node.file) } end node.children.each { |child_node| child_node.file = node.file check_node(child_node) } if checkers checkers.each { |checker| checker.node_end(node) if checker.parse_file?(node.file) } end end
ruby
def check_node(node) checkers = @checks[node.sexp_type] if checkers checkers.each { |checker| checker.node_start(node) if checker.parse_file?(node.file) } end node.children.each { |child_node| child_node.file = node.file check_node(child_node) } if checkers checkers.each { |checker| checker.node_end(node) if checker.parse_file?(node.file) } end end
[ "def", "check_node", "(", "node", ")", "checkers", "=", "@checks", "[", "node", ".", "sexp_type", "]", "if", "checkers", "checkers", ".", "each", "{", "|", "checker", "|", "checker", ".", "node_start", "(", "node", ")", "if", "checker", ".", "parse_file?", "(", "node", ".", "file", ")", "}", "end", "node", ".", "children", ".", "each", "{", "|", "child_node", "|", "child_node", ".", "file", "=", "node", ".", "file", "check_node", "(", "child_node", ")", "}", "if", "checkers", "checkers", ".", "each", "{", "|", "checker", "|", "checker", ".", "node_end", "(", "node", ")", "if", "checker", ".", "parse_file?", "(", "node", ".", "file", ")", "}", "end", "end" ]
recursively check ruby sexp node. 1. it triggers the interesting checkers' start callbacks. 2. recursively check the sexp children. 3. it triggers the interesting checkers' end callbacks.
[ "recursively", "check", "ruby", "sexp", "node", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L52-L64
train
ryanbreed/cef
lib/cef/sender.rb
CEF.UDPSender.emit
def emit(event) self.socksetup if self.sock.nil? # process eventDefaults - we are expecting a hash here. These will # override any values in the events passed to us. i know. brutal. unless self.eventDefaults.nil? self.eventDefaults.each do |k,v| event.send("%s=" % k,v) end end self.sock.send event.to_s, 0 end
ruby
def emit(event) self.socksetup if self.sock.nil? # process eventDefaults - we are expecting a hash here. These will # override any values in the events passed to us. i know. brutal. unless self.eventDefaults.nil? self.eventDefaults.each do |k,v| event.send("%s=" % k,v) end end self.sock.send event.to_s, 0 end
[ "def", "emit", "(", "event", ")", "self", ".", "socksetup", "if", "self", ".", "sock", ".", "nil?", "unless", "self", ".", "eventDefaults", ".", "nil?", "self", ".", "eventDefaults", ".", "each", "do", "|", "k", ",", "v", "|", "event", ".", "send", "(", "\"%s=\"", "%", "k", ",", "v", ")", "end", "end", "self", ".", "sock", ".", "send", "event", ".", "to_s", ",", "0", "end" ]
fire the message off
[ "fire", "the", "message", "off" ]
99a717b392c796377eaa70be0baa9bfce3e30379
https://github.com/ryanbreed/cef/blob/99a717b392c796377eaa70be0baa9bfce3e30379/lib/cef/sender.rb#L22-L32
train
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.bind_meta_app
def bind_meta_app args={}, &block arg_string = args.values_at(:key, :listen_to, :respond_on, :application).join(" ") arg_string += "::#{args[:parameters]}" if args[:parameters] application "bind_meta_app", arg_string, &block end
ruby
def bind_meta_app args={}, &block arg_string = args.values_at(:key, :listen_to, :respond_on, :application).join(" ") arg_string += "::#{args[:parameters]}" if args[:parameters] application "bind_meta_app", arg_string, &block end
[ "def", "bind_meta_app", "args", "=", "{", "}", ",", "&", "block", "arg_string", "=", "args", ".", "values_at", "(", ":key", ",", ":listen_to", ",", ":respond_on", ",", ":application", ")", ".", "join", "(", "\" \"", ")", "arg_string", "+=", "\"::#{args[:parameters]}\"", "if", "args", "[", ":parameters", "]", "application", "\"bind_meta_app\"", ",", "arg_string", ",", "&", "block", "end" ]
Binds an application to the specified call legs. @example bind_meta_app :key => 2, :listen_to => "a", :respond_on => "s", :application => "execute_extension", :parameters => "dx XML features" @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_bind_meta_app
[ "Binds", "an", "application", "to", "the", "specified", "call", "legs", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L32-L38
train
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.bridge
def bridge *args, &block variables = if args.last.is_a? Hash # We need to sort the key/value pairs to facilitate testing. # This can be removed once 1.8-compat is dropped. key_value_pairs = args.pop.sort {|x,y| x.to_s <=> y.to_s} key_value_pairs.map! {|k,v| "#{k}=#{v}"} "{#{key_value_pairs.join(",")}}" else "" end endpoints = if args.first.is_a? Array args.map {|e| e.join(",")}.join("|") else args.join "," end application "bridge", variables + endpoints, &block end
ruby
def bridge *args, &block variables = if args.last.is_a? Hash # We need to sort the key/value pairs to facilitate testing. # This can be removed once 1.8-compat is dropped. key_value_pairs = args.pop.sort {|x,y| x.to_s <=> y.to_s} key_value_pairs.map! {|k,v| "#{k}=#{v}"} "{#{key_value_pairs.join(",")}}" else "" end endpoints = if args.first.is_a? Array args.map {|e| e.join(",")}.join("|") else args.join "," end application "bridge", variables + endpoints, &block end
[ "def", "bridge", "*", "args", ",", "&", "block", "variables", "=", "if", "args", ".", "last", ".", "is_a?", "Hash", "key_value_pairs", "=", "args", ".", "pop", ".", "sort", "{", "|", "x", ",", "y", "|", "x", ".", "to_s", "<=>", "y", ".", "to_s", "}", "key_value_pairs", ".", "map!", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v}\"", "}", "\"{#{key_value_pairs.join(\",\")}}\"", "else", "\"\"", "end", "endpoints", "=", "if", "args", ".", "first", ".", "is_a?", "Array", "args", ".", "map", "{", "|", "e", "|", "e", ".", "join", "(", "\",\"", ")", "}", ".", "join", "(", "\"|\"", ")", "else", "args", ".", "join", "\",\"", "end", "application", "\"bridge\"", ",", "variables", "+", "endpoints", ",", "&", "block", "end" ]
Bridges an incoming call to an endpoint, optionally taking an array of channel variables to set. If given an array of arrays, each contained array of endpoints will be called simultaneously, with the next array of endpoints as failover. See the examples below for different constructs and the callstring it sends to FreeSWITCH. @example bridge "user/coltrane", "user/backup-office" #=> user/coltrane,user/backup-office @example With channel variables bridge "user/coltrane", "user/backup-office", :some_var => "value" #=> {some_var=value}user/coltrane,user/backup-office @example With failover bridge ['user/coltrane', 'user/davis'], ['user/sun-ra', 'user/taylor'] #=> user/coltrane,user/davis|user/sun-ra,user/taylor @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_bridge
[ "Bridges", "an", "incoming", "call", "to", "an", "endpoint", "optionally", "taking", "an", "array", "of", "channel", "variables", "to", "set", ".", "If", "given", "an", "array", "of", "arrays", "each", "contained", "array", "of", "endpoints", "will", "be", "called", "simultaneously", "with", "the", "next", "array", "of", "endpoints", "as", "failover", ".", "See", "the", "examples", "below", "for", "different", "constructs", "and", "the", "callstring", "it", "sends", "to", "FreeSWITCH", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L56-L74
train
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.play_and_get_digits
def play_and_get_digits file, invalid_file, args={}, &block min = args[:min] || 1 max = args[:max] || 2 tries = args[:tries] || 3 terminators = args[:terminators] || "#" timeout = args[:timeout] || 5000 variable = args[:variable] || "read_digits_var" regexp = args[:regexp] || "\\d+" args = [min, max, tries, timeout, terminators, file, invalid_file, variable, regexp].join " " params = {:variable => variable} application "play_and_get_digits", args, params, &block end
ruby
def play_and_get_digits file, invalid_file, args={}, &block min = args[:min] || 1 max = args[:max] || 2 tries = args[:tries] || 3 terminators = args[:terminators] || "#" timeout = args[:timeout] || 5000 variable = args[:variable] || "read_digits_var" regexp = args[:regexp] || "\\d+" args = [min, max, tries, timeout, terminators, file, invalid_file, variable, regexp].join " " params = {:variable => variable} application "play_and_get_digits", args, params, &block end
[ "def", "play_and_get_digits", "file", ",", "invalid_file", ",", "args", "=", "{", "}", ",", "&", "block", "min", "=", "args", "[", ":min", "]", "||", "1", "max", "=", "args", "[", ":max", "]", "||", "2", "tries", "=", "args", "[", ":tries", "]", "||", "3", "terminators", "=", "args", "[", ":terminators", "]", "||", "\"#\"", "timeout", "=", "args", "[", ":timeout", "]", "||", "5000", "variable", "=", "args", "[", ":variable", "]", "||", "\"read_digits_var\"", "regexp", "=", "args", "[", ":regexp", "]", "||", "\"\\\\d+\"", "args", "=", "[", "min", ",", "max", ",", "tries", ",", "timeout", ",", "terminators", ",", "file", ",", "invalid_file", ",", "variable", ",", "regexp", "]", ".", "join", "\" \"", "params", "=", "{", ":variable", "=>", "variable", "}", "application", "\"play_and_get_digits\"", ",", "args", ",", "params", ",", "&", "block", "end" ]
Plays a sound file and reads DTMF presses. @example play_and_get_digits "please-enter.wav", "wrong-choice.wav", :min => 1, :max => 2, :tries => 3, :terminators => "#", :timeout => 5000, :regexp => '\d+' @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_play_and_get_digits
[ "Plays", "a", "sound", "file", "and", "reads", "DTMF", "presses", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L137-L152
train
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.record
def record path, params={}, &block args = [path, params[:limit]].compact.join(" ") application "record", args, &block end
ruby
def record path, params={}, &block args = [path, params[:limit]].compact.join(" ") application "record", args, &block end
[ "def", "record", "path", ",", "params", "=", "{", "}", ",", "&", "block", "args", "=", "[", "path", ",", "params", "[", ":limit", "]", "]", ".", "compact", ".", "join", "(", "\" \"", ")", "application", "\"record\"", ",", "args", ",", "&", "block", "end" ]
Records a message, with an optional limit on the maximum duration of the recording. @example Without limit record "/path/to/new/file.wac" @example With 20 second limit record "/path/to/new/file.wac", :limit => 20 @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_record
[ "Records", "a", "message", "with", "an", "optional", "limit", "on", "the", "maximum", "duration", "of", "the", "recording", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L193-L196
train
matttproud/ruby_quantile_estimation
lib/quantile/estimator.rb
Quantile.Estimator.query
def query(rank) flush current = @head return unless current mid_rank = (rank * @observations).floor max_rank = mid_rank + (invariant(mid_rank, @observations) / 2).floor rank = 0.0 while current.successor rank += current.rank if rank + current.successor.rank + current.successor.delta > max_rank return current.value end current = current.successor end return current.value end
ruby
def query(rank) flush current = @head return unless current mid_rank = (rank * @observations).floor max_rank = mid_rank + (invariant(mid_rank, @observations) / 2).floor rank = 0.0 while current.successor rank += current.rank if rank + current.successor.rank + current.successor.delta > max_rank return current.value end current = current.successor end return current.value end
[ "def", "query", "(", "rank", ")", "flush", "current", "=", "@head", "return", "unless", "current", "mid_rank", "=", "(", "rank", "*", "@observations", ")", ".", "floor", "max_rank", "=", "mid_rank", "+", "(", "invariant", "(", "mid_rank", ",", "@observations", ")", "/", "2", ")", ".", "floor", "rank", "=", "0.0", "while", "current", ".", "successor", "rank", "+=", "current", ".", "rank", "if", "rank", "+", "current", ".", "successor", ".", "rank", "+", "current", ".", "successor", ".", "delta", ">", "max_rank", "return", "current", ".", "value", "end", "current", "=", "current", ".", "successor", "end", "return", "current", ".", "value", "end" ]
Get a quantile value for a given rank. @param rank [Float] The target quantile to retrieve. It *must* be one of the invariants provided in the constructor. @return [Numeric, nil] The quantile value for the rank or nil if no observations are present.
[ "Get", "a", "quantile", "value", "for", "a", "given", "rank", "." ]
49c660bffdc36a8283ecc730a102bae7232a438f
https://github.com/matttproud/ruby_quantile_estimation/blob/49c660bffdc36a8283ecc730a102bae7232a438f/lib/quantile/estimator.rb#L89-L109
train
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.file_list
def file_list(path, ext = 'scss', remover = '') # Necessary so that directories aren't counted collect_path = path.include?("*") ? path : "#{path}/**/*.#{ext}" # Remove first slash from path if present. probably a better way to do this. Dir[collect_path].collect { |file| file.gsub(remover, '').gsub(/^\/app\//, 'app/') if File.file?(file) } end
ruby
def file_list(path, ext = 'scss', remover = '') # Necessary so that directories aren't counted collect_path = path.include?("*") ? path : "#{path}/**/*.#{ext}" # Remove first slash from path if present. probably a better way to do this. Dir[collect_path].collect { |file| file.gsub(remover, '').gsub(/^\/app\//, 'app/') if File.file?(file) } end
[ "def", "file_list", "(", "path", ",", "ext", "=", "'scss'", ",", "remover", "=", "''", ")", "collect_path", "=", "path", ".", "include?", "(", "\"*\"", ")", "?", "path", ":", "\"#{path}/**/*.#{ext}\"", "Dir", "[", "collect_path", "]", ".", "collect", "{", "|", "file", "|", "file", ".", "gsub", "(", "remover", ",", "''", ")", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "'app/'", ")", "if", "File", ".", "file?", "(", "file", ")", "}", "end" ]
Find all files that were linted by extension @param path [String] path to folders @param ext [String] file extension to search for @return [Array<String>] list of file paths
[ "Find", "all", "files", "that", "were", "linted", "by", "extension" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L59-L64
train
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.truthy?
def truthy?(str) return true if str == true || str =~ (/^(true|t|yes|y|1)$/i) return false if str == false || str.blank? || str =~ (/^(false|f|no|n|0)$/i) end
ruby
def truthy?(str) return true if str == true || str =~ (/^(true|t|yes|y|1)$/i) return false if str == false || str.blank? || str =~ (/^(false|f|no|n|0)$/i) end
[ "def", "truthy?", "(", "str", ")", "return", "true", "if", "str", "==", "true", "||", "str", "=~", "(", "/", "/i", ")", "return", "false", "if", "str", "==", "false", "||", "str", ".", "blank?", "||", "str", "=~", "(", "/", "/i", ")", "end" ]
Convert string to boolean @param str [String] the string to evaluate @return [Boolean] whether or not the string is true
[ "Convert", "string", "to", "boolean" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L78-L81
train
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.edit_yaml
def edit_yaml(yaml_location, &block) d = YAML.load_file(yaml_location) block.call(d) File.open(yaml_location, 'w') {|f| f.write d.to_yaml } end
ruby
def edit_yaml(yaml_location, &block) d = YAML.load_file(yaml_location) block.call(d) File.open(yaml_location, 'w') {|f| f.write d.to_yaml } end
[ "def", "edit_yaml", "(", "yaml_location", ",", "&", "block", ")", "d", "=", "YAML", ".", "load_file", "(", "yaml_location", ")", "block", ".", "call", "(", "d", ")", "File", ".", "open", "(", "yaml_location", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "d", ".", "to_yaml", "}", "end" ]
Edit and save a YAML file @param yaml_location [String] YAML absolute file path @return [void]
[ "Edit", "and", "save", "a", "YAML", "file" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L86-L90
train
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.path_exists?
def path_exists?(path = @path) path = path.split(' ') if path.is_a?(String) && path.include?(' ') if path.is_a?(Array) path.each do |p| unless File.exist?(p) puts "#{p} does not exist" return false end end else path = path.gsub('/**', '').gsub('/*', '').gsub(/\/\.*/, '') if path.include?('*') if File.exist?(path) return true else puts "#{path} does not exist" return false end end end
ruby
def path_exists?(path = @path) path = path.split(' ') if path.is_a?(String) && path.include?(' ') if path.is_a?(Array) path.each do |p| unless File.exist?(p) puts "#{p} does not exist" return false end end else path = path.gsub('/**', '').gsub('/*', '').gsub(/\/\.*/, '') if path.include?('*') if File.exist?(path) return true else puts "#{path} does not exist" return false end end end
[ "def", "path_exists?", "(", "path", "=", "@path", ")", "path", "=", "path", ".", "split", "(", "' '", ")", "if", "path", ".", "is_a?", "(", "String", ")", "&&", "path", ".", "include?", "(", "' '", ")", "if", "path", ".", "is_a?", "(", "Array", ")", "path", ".", "each", "do", "|", "p", "|", "unless", "File", ".", "exist?", "(", "p", ")", "puts", "\"#{p} does not exist\"", "return", "false", "end", "end", "else", "path", "=", "path", ".", "gsub", "(", "'/**'", ",", "''", ")", ".", "gsub", "(", "'/*'", ",", "''", ")", ".", "gsub", "(", "/", "\\/", "\\.", "/", ",", "''", ")", "if", "path", ".", "include?", "(", "'*'", ")", "if", "File", ".", "exist?", "(", "path", ")", "return", "true", "else", "puts", "\"#{path} does not exist\"", "return", "false", "end", "end", "end" ]
Ensure path exists @param path [String, Array] path to files can be directory or glob @return [Boolean]
[ "Ensure", "path", "exists" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L103-L121
train
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.discover_path
def discover_path(root = @config.working_dir, folder = '', extension = '') return @path unless @path.blank? if is_middleman? File.join(root, 'source', folder) elsif is_rails? File.join(root, 'app', 'assets', folder) else extension.blank? ? File.join(root) : File.join(root, '/**', "/*.#{extension}") end end
ruby
def discover_path(root = @config.working_dir, folder = '', extension = '') return @path unless @path.blank? if is_middleman? File.join(root, 'source', folder) elsif is_rails? File.join(root, 'app', 'assets', folder) else extension.blank? ? File.join(root) : File.join(root, '/**', "/*.#{extension}") end end
[ "def", "discover_path", "(", "root", "=", "@config", ".", "working_dir", ",", "folder", "=", "''", ",", "extension", "=", "''", ")", "return", "@path", "unless", "@path", ".", "blank?", "if", "is_middleman?", "File", ".", "join", "(", "root", ",", "'source'", ",", "folder", ")", "elsif", "is_rails?", "File", ".", "join", "(", "root", ",", "'app'", ",", "'assets'", ",", "folder", ")", "else", "extension", ".", "blank?", "?", "File", ".", "join", "(", "root", ")", ":", "File", ".", "join", "(", "root", ",", "'/**'", ",", "\"/*.#{extension}\"", ")", "end", "end" ]
Default paths to check for lints and some stats @since 0.1.6.1 Note: is_rails? must be defined second-to-last if more frameworks are added @param root [String] base directory @param folder [String] nested folder to search for for Rails or Middleman @param extension [String] file glob type to search for if neither @return [String] path to desired files
[ "Default", "paths", "to", "check", "for", "lints", "and", "some", "stats" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L130-L139
train
adonespitogo/unsakini
app/controllers/concerns/unsakini/comment_owner_controller_concern.rb
Unsakini.CommentOwnerControllerConcern.ensure_comment
def ensure_comment post_id = params[:post_id] comment_id = params[:comment_id] || params[:id] result = has_comment_access post_id, comment_id @comment = result[:comment] status = result[:status] head status if status != :ok end
ruby
def ensure_comment post_id = params[:post_id] comment_id = params[:comment_id] || params[:id] result = has_comment_access post_id, comment_id @comment = result[:comment] status = result[:status] head status if status != :ok end
[ "def", "ensure_comment", "post_id", "=", "params", "[", ":post_id", "]", "comment_id", "=", "params", "[", ":comment_id", "]", "||", "params", "[", ":id", "]", "result", "=", "has_comment_access", "post_id", ",", "comment_id", "@comment", "=", "result", "[", ":comment", "]", "status", "=", "result", "[", ":status", "]", "head", "status", "if", "status", "!=", ":ok", "end" ]
Ensures user is owner of the comment and sets the `@comment` variable in the controllers
[ "Ensures", "user", "is", "owner", "of", "the", "comment", "and", "sets", "the" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/comment_owner_controller_concern.rb#L7-L14
train
adonespitogo/unsakini
app/controllers/concerns/unsakini/comment_owner_controller_concern.rb
Unsakini.CommentOwnerControllerConcern.has_comment_access
def has_comment_access(post_id, comment_id) comment = Unsakini::Comment.where(id: comment_id, post_id: post_id, user_id: @user.id).first if comment.nil? return {status: :forbidden, comment: comment} else return {status: :ok, comment: comment} end end
ruby
def has_comment_access(post_id, comment_id) comment = Unsakini::Comment.where(id: comment_id, post_id: post_id, user_id: @user.id).first if comment.nil? return {status: :forbidden, comment: comment} else return {status: :ok, comment: comment} end end
[ "def", "has_comment_access", "(", "post_id", ",", "comment_id", ")", "comment", "=", "Unsakini", "::", "Comment", ".", "where", "(", "id", ":", "comment_id", ",", "post_id", ":", "post_id", ",", "user_id", ":", "@user", ".", "id", ")", ".", "first", "if", "comment", ".", "nil?", "return", "{", "status", ":", ":forbidden", ",", "comment", ":", "comment", "}", "else", "return", "{", "status", ":", ":ok", ",", "comment", ":", "comment", "}", "end", "end" ]
Validate if user has access to comment in the post @param post_id [Integer] post id @param comment_id [Integer] comment id
[ "Validate", "if", "user", "has", "access", "to", "comment", "in", "the", "post" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/comment_owner_controller_concern.rb#L20-L27
train
michaeledgar/ripper-plus
lib/ripper-plus/scope_stack.rb
RipperPlus.ScopeStack.with_closed_scope
def with_closed_scope(is_method = false) old_in_method = @in_method @in_method ||= is_method @stack.push(SCOPE_BLOCKER_9000) @stack.push(Set.new) yield ensure @stack.pop # pop closed scope @stack.pop # pop scope blocker @in_method = old_in_method end
ruby
def with_closed_scope(is_method = false) old_in_method = @in_method @in_method ||= is_method @stack.push(SCOPE_BLOCKER_9000) @stack.push(Set.new) yield ensure @stack.pop # pop closed scope @stack.pop # pop scope blocker @in_method = old_in_method end
[ "def", "with_closed_scope", "(", "is_method", "=", "false", ")", "old_in_method", "=", "@in_method", "@in_method", "||=", "is_method", "@stack", ".", "push", "(", "SCOPE_BLOCKER_9000", ")", "@stack", ".", "push", "(", "Set", ".", "new", ")", "yield", "ensure", "@stack", ".", "pop", "@stack", ".", "pop", "@in_method", "=", "old_in_method", "end" ]
An open scope denies reference to local variables in enclosing scopes.
[ "An", "open", "scope", "denies", "reference", "to", "local", "variables", "in", "enclosing", "scopes", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/scope_stack.rb#L44-L54
train
michaeledgar/ripper-plus
lib/ripper-plus/scope_stack.rb
RipperPlus.ScopeStack.has_variable?
def has_variable?(var) @stack.reverse_each do |scope| if SCOPE_BLOCKER_9000 == scope return false elsif scope.include?(var) return true end end end
ruby
def has_variable?(var) @stack.reverse_each do |scope| if SCOPE_BLOCKER_9000 == scope return false elsif scope.include?(var) return true end end end
[ "def", "has_variable?", "(", "var", ")", "@stack", ".", "reverse_each", "do", "|", "scope", "|", "if", "SCOPE_BLOCKER_9000", "==", "scope", "return", "false", "elsif", "scope", ".", "include?", "(", "var", ")", "return", "true", "end", "end", "end" ]
Checks if the given variable is in scope.
[ "Checks", "if", "the", "given", "variable", "is", "in", "scope", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/scope_stack.rb#L57-L65
train
adonespitogo/unsakini
app/controllers/unsakini/comments_controller.rb
Unsakini.CommentsController.create
def create @comment = Comment.new(params.permit(:content)) @comment.user = @user @comment.post = @post if @comment.save render json: @comment else render json: @comment.errors, status: 422 end end
ruby
def create @comment = Comment.new(params.permit(:content)) @comment.user = @user @comment.post = @post if @comment.save render json: @comment else render json: @comment.errors, status: 422 end end
[ "def", "create", "@comment", "=", "Comment", ".", "new", "(", "params", ".", "permit", "(", ":content", ")", ")", "@comment", ".", "user", "=", "@user", "@comment", ".", "post", "=", "@post", "if", "@comment", ".", "save", "render", "json", ":", "@comment", "else", "render", "json", ":", "@comment", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Creates new comment belonging to the post `POST /api/boards/:board_id/posts/:post_id/`
[ "Creates", "new", "comment", "belonging", "to", "the", "post" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/comments_controller.rb#L23-L32
train
adonespitogo/unsakini
app/controllers/unsakini/comments_controller.rb
Unsakini.CommentsController.update
def update if @comment.update(params.permit(:content)) render json: @comment else render json: @comment.errors, status: 422 end end
ruby
def update if @comment.update(params.permit(:content)) render json: @comment else render json: @comment.errors, status: 422 end end
[ "def", "update", "if", "@comment", ".", "update", "(", "params", ".", "permit", "(", ":content", ")", ")", "render", "json", ":", "@comment", "else", "render", "json", ":", "@comment", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Updates a comment `PUT /api/boards/:board_id/posts/:post_id/comments/:id`
[ "Updates", "a", "comment" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/comments_controller.rb#L37-L43
train
adonespitogo/unsakini
app/controllers/concerns/unsakini/board_owner_controller_concern.rb
Unsakini.BoardOwnerControllerConcern.ensure_board
def ensure_board board_id = params[:board_id] || params[:id] result = has_board_access(board_id) @board = result[:board] @user_board = result[:user_board] head result[:status] if result[:status] != :ok end
ruby
def ensure_board board_id = params[:board_id] || params[:id] result = has_board_access(board_id) @board = result[:board] @user_board = result[:user_board] head result[:status] if result[:status] != :ok end
[ "def", "ensure_board", "board_id", "=", "params", "[", ":board_id", "]", "||", "params", "[", ":id", "]", "result", "=", "has_board_access", "(", "board_id", ")", "@board", "=", "result", "[", ":board", "]", "@user_board", "=", "result", "[", ":user_board", "]", "head", "result", "[", ":status", "]", "if", "result", "[", ":status", "]", "!=", ":ok", "end" ]
Ensure user has access to the board and sets the `@board` variable in the controller
[ "Ensure", "user", "has", "access", "to", "the", "board", "and", "sets", "the" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/board_owner_controller_concern.rb#L8-L14
train
adonespitogo/unsakini
app/controllers/concerns/unsakini/board_owner_controller_concern.rb
Unsakini.BoardOwnerControllerConcern.has_board_access
def has_board_access(board_id) board = nil if !board_id.nil? board = Unsakini::Board.find_by_id(board_id) else return {status: :bad_request} end if (board) user_board = Unsakini::UserBoard.where(user_id: @user.id, board_id: board_id).first return {status: :forbidden } if user_board.nil? return {status: :ok, board: board, user_board: user_board} else return {status: :not_found} end end
ruby
def has_board_access(board_id) board = nil if !board_id.nil? board = Unsakini::Board.find_by_id(board_id) else return {status: :bad_request} end if (board) user_board = Unsakini::UserBoard.where(user_id: @user.id, board_id: board_id).first return {status: :forbidden } if user_board.nil? return {status: :ok, board: board, user_board: user_board} else return {status: :not_found} end end
[ "def", "has_board_access", "(", "board_id", ")", "board", "=", "nil", "if", "!", "board_id", ".", "nil?", "board", "=", "Unsakini", "::", "Board", ".", "find_by_id", "(", "board_id", ")", "else", "return", "{", "status", ":", ":bad_request", "}", "end", "if", "(", "board", ")", "user_board", "=", "Unsakini", "::", "UserBoard", ".", "where", "(", "user_id", ":", "@user", ".", "id", ",", "board_id", ":", "board_id", ")", ".", "first", "return", "{", "status", ":", ":forbidden", "}", "if", "user_board", ".", "nil?", "return", "{", "status", ":", ":ok", ",", "board", ":", "board", ",", "user_board", ":", "user_board", "}", "else", "return", "{", "status", ":", ":not_found", "}", "end", "end" ]
Validate if user has access to board @param board_id [Integer] board id
[ "Validate", "if", "user", "has", "access", "to", "board" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/board_owner_controller_concern.rb#L19-L33
train
larrytheliquid/dataflow
dataflow/port.rb
Dataflow.Port.send
def send value LOCK.synchronize do unify @end.head, value unify @end.tail, Stream.new @end = @end.tail end end
ruby
def send value LOCK.synchronize do unify @end.head, value unify @end.tail, Stream.new @end = @end.tail end end
[ "def", "send", "value", "LOCK", ".", "synchronize", "do", "unify", "@end", ".", "head", ",", "value", "unify", "@end", ".", "tail", ",", "Stream", ".", "new", "@end", "=", "@end", ".", "tail", "end", "end" ]
Create a stream object, bind it to the input variable Instance variables are necessary because @end is state This needs to be synchronized because it uses @end as state
[ "Create", "a", "stream", "object", "bind", "it", "to", "the", "input", "variable", "Instance", "variables", "are", "necessary", "because" ]
c856552bbc0fc9e64b2b13a08239cba985874eaf
https://github.com/larrytheliquid/dataflow/blob/c856552bbc0fc9e64b2b13a08239cba985874eaf/dataflow/port.rb#L45-L51
train
ballantyne/weibo
lib/weibo/request.rb
Weibo.Request.make_mash_with_consistent_hash
def make_mash_with_consistent_hash(obj) m = Hashie::Mash.new(obj) def m.hash inspect.hash end return m end
ruby
def make_mash_with_consistent_hash(obj) m = Hashie::Mash.new(obj) def m.hash inspect.hash end return m end
[ "def", "make_mash_with_consistent_hash", "(", "obj", ")", "m", "=", "Hashie", "::", "Mash", ".", "new", "(", "obj", ")", "def", "m", ".", "hash", "inspect", ".", "hash", "end", "return", "m", "end" ]
Lame workaround for the fact that mash doesn't hash correctly
[ "Lame", "workaround", "for", "the", "fact", "that", "mash", "doesn", "t", "hash", "correctly" ]
f3ebbf4d706e158cf81d9ffe4a6ed700db7210bc
https://github.com/ballantyne/weibo/blob/f3ebbf4d706e158cf81d9ffe4a6ed700db7210bc/lib/weibo/request.rb#L109-L115
train
ronin-ruby/ronin-support
lib/ronin/wordlist.rb
Ronin.Wordlist.each_word
def each_word(&block) return enum_for(__method__) unless block if @path File.open(@path) do |file| file.each_line do |line| yield line.chomp end end elsif @words @words.each(&block) end end
ruby
def each_word(&block) return enum_for(__method__) unless block if @path File.open(@path) do |file| file.each_line do |line| yield line.chomp end end elsif @words @words.each(&block) end end
[ "def", "each_word", "(", "&", "block", ")", "return", "enum_for", "(", "__method__", ")", "unless", "block", "if", "@path", "File", ".", "open", "(", "@path", ")", "do", "|", "file", "|", "file", ".", "each_line", "do", "|", "line", "|", "yield", "line", ".", "chomp", "end", "end", "elsif", "@words", "@words", ".", "each", "(", "&", "block", ")", "end", "end" ]
Iterates over each word in the list. @yield [word] The given block will be passed each word. @yieldparam [String] word A word from the list. @return [Enumerator] If no block is given, an Enumerator will be returned. @raise [RuntimeError] {#path} or {#words} must be set. @api public
[ "Iterates", "over", "each", "word", "in", "the", "list", "." ]
bc2af0e75098c13133789118245cb185f8c6b4c9
https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/wordlist.rb#L197-L209
train
ronin-ruby/ronin-support
lib/ronin/wordlist.rb
Ronin.Wordlist.each
def each(&block) return enum_for(__method__) unless block mutator = unless @mutations.empty? Fuzzing::Mutator.new(@mutations) end each_word do |word| yield word if mutator # perform additional mutations mutator.each(word,&block) end end end
ruby
def each(&block) return enum_for(__method__) unless block mutator = unless @mutations.empty? Fuzzing::Mutator.new(@mutations) end each_word do |word| yield word if mutator # perform additional mutations mutator.each(word,&block) end end end
[ "def", "each", "(", "&", "block", ")", "return", "enum_for", "(", "__method__", ")", "unless", "block", "mutator", "=", "unless", "@mutations", ".", "empty?", "Fuzzing", "::", "Mutator", ".", "new", "(", "@mutations", ")", "end", "each_word", "do", "|", "word", "|", "yield", "word", "if", "mutator", "mutator", ".", "each", "(", "word", ",", "&", "block", ")", "end", "end", "end" ]
Iterates over each word, and each mutation, from the list. @yield [word] The given block will be passed each word. @yieldparam [String] word A word from the list. @return [Enumerator] If no block is given, an Enumerator will be returned. @api public
[ "Iterates", "over", "each", "word", "and", "each", "mutation", "from", "the", "list", "." ]
bc2af0e75098c13133789118245cb185f8c6b4c9
https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/wordlist.rb#L225-L240
train
ronin-ruby/ronin-support
lib/ronin/wordlist.rb
Ronin.Wordlist.save
def save(path) File.open(path,'w') do |file| each { |word| file.puts word } end return self end
ruby
def save(path) File.open(path,'w') do |file| each { |word| file.puts word } end return self end
[ "def", "save", "(", "path", ")", "File", ".", "open", "(", "path", ",", "'w'", ")", "do", "|", "file", "|", "each", "{", "|", "word", "|", "file", ".", "puts", "word", "}", "end", "return", "self", "end" ]
Saves the words to a new file. @param [String] path The path to the new wordlist file. @return [Wordlist] The wordlist object. @see #each @since 0.5.0 @api public
[ "Saves", "the", "words", "to", "a", "new", "file", "." ]
bc2af0e75098c13133789118245cb185f8c6b4c9
https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/wordlist.rb#L278-L284
train
integrallis/stripe_saas
app/controllers/stripe_saas/subscriptions_controller.rb
StripeSaas.SubscriptionsController.load_owner
def load_owner unless params[:owner_id].nil? if current_owner.present? # we need to try and look this owner up via the find method so that we're # taking advantage of any override of the find method that would be provided # by older versions of friendly_id. (support for newer versions default behavior # below.) searched_owner = current_owner.class.find(params[:owner_id]) rescue nil # if we couldn't find them that way, check whether there is a new version of # friendly_id in place that we can use to look them up by their slug. # in christoph's words, "why?!" in my words, "warum?!!!" # (we debugged this together on skype.) if searched_owner.nil? && current_owner.class.respond_to?(:friendly) searched_owner = current_owner.class.friendly.find(params[:owner_id]) rescue nil end if current_owner.try(:id) == searched_owner.try(:id) @owner = current_owner else customer = Subscription.find_customer(searched_owner) customer_2 = Subscription.find_customer(current_owner) # susbscription we are looking for belongs to the same user but to a different # subscription owner # e.g. user -> account -> subscription # same user but different accounts for example if customer_2.try(:id) == customer.try(:id) @owner = searched_owner else return unauthorized end end else return unauthorized end end end
ruby
def load_owner unless params[:owner_id].nil? if current_owner.present? # we need to try and look this owner up via the find method so that we're # taking advantage of any override of the find method that would be provided # by older versions of friendly_id. (support for newer versions default behavior # below.) searched_owner = current_owner.class.find(params[:owner_id]) rescue nil # if we couldn't find them that way, check whether there is a new version of # friendly_id in place that we can use to look them up by their slug. # in christoph's words, "why?!" in my words, "warum?!!!" # (we debugged this together on skype.) if searched_owner.nil? && current_owner.class.respond_to?(:friendly) searched_owner = current_owner.class.friendly.find(params[:owner_id]) rescue nil end if current_owner.try(:id) == searched_owner.try(:id) @owner = current_owner else customer = Subscription.find_customer(searched_owner) customer_2 = Subscription.find_customer(current_owner) # susbscription we are looking for belongs to the same user but to a different # subscription owner # e.g. user -> account -> subscription # same user but different accounts for example if customer_2.try(:id) == customer.try(:id) @owner = searched_owner else return unauthorized end end else return unauthorized end end end
[ "def", "load_owner", "unless", "params", "[", ":owner_id", "]", ".", "nil?", "if", "current_owner", ".", "present?", "searched_owner", "=", "current_owner", ".", "class", ".", "find", "(", "params", "[", ":owner_id", "]", ")", "rescue", "nil", "if", "searched_owner", ".", "nil?", "&&", "current_owner", ".", "class", ".", "respond_to?", "(", ":friendly", ")", "searched_owner", "=", "current_owner", ".", "class", ".", "friendly", ".", "find", "(", "params", "[", ":owner_id", "]", ")", "rescue", "nil", "end", "if", "current_owner", ".", "try", "(", ":id", ")", "==", "searched_owner", ".", "try", "(", ":id", ")", "@owner", "=", "current_owner", "else", "customer", "=", "Subscription", ".", "find_customer", "(", "searched_owner", ")", "customer_2", "=", "Subscription", ".", "find_customer", "(", "current_owner", ")", "if", "customer_2", ".", "try", "(", ":id", ")", "==", "customer", ".", "try", "(", ":id", ")", "@owner", "=", "searched_owner", "else", "return", "unauthorized", "end", "end", "else", "return", "unauthorized", "end", "end", "end" ]
subscription.subscription_owner
[ "subscription", ".", "subscription_owner" ]
130acf9ea66e3dd96dedba193327d1e79443e868
https://github.com/integrallis/stripe_saas/blob/130acf9ea66e3dd96dedba193327d1e79443e868/app/controllers/stripe_saas/subscriptions_controller.rb#L18-L56
train
vangberg/librevox
lib/librevox/commands.rb
Librevox.Commands.originate
def originate url, args={}, &block extension = args.delete(:extension) dialplan = args.delete(:dialplan) context = args.delete(:context) vars = args.map {|k,v| "#{k}=#{v}"}.join(",") arg_string = "{#{vars}}" + [url, extension, dialplan, context].compact.join(" ") command "originate", arg_string, &block end
ruby
def originate url, args={}, &block extension = args.delete(:extension) dialplan = args.delete(:dialplan) context = args.delete(:context) vars = args.map {|k,v| "#{k}=#{v}"}.join(",") arg_string = "{#{vars}}" + [url, extension, dialplan, context].compact.join(" ") command "originate", arg_string, &block end
[ "def", "originate", "url", ",", "args", "=", "{", "}", ",", "&", "block", "extension", "=", "args", ".", "delete", "(", ":extension", ")", "dialplan", "=", "args", ".", "delete", "(", ":dialplan", ")", "context", "=", "args", ".", "delete", "(", ":context", ")", "vars", "=", "args", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v}\"", "}", ".", "join", "(", "\",\"", ")", "arg_string", "=", "\"{#{vars}}\"", "+", "[", "url", ",", "extension", ",", "dialplan", ",", "context", "]", ".", "compact", ".", "join", "(", "\" \"", ")", "command", "\"originate\"", ",", "arg_string", ",", "&", "block", "end" ]
Access the hash table that comes with FreeSWITCH. @example socket.hash :insert, :realm, :key, "value" socket.hash :select, :realm, :key socket.hash :delete, :realm, :key Originate a new call. @example Minimum options socket.originate 'sofia/user/coltrane', :extension => "1234" @example With :dialplan and :context @see http://wiki.freeswitch.org/wiki/Mod_commands#originate
[ "Access", "the", "hash", "table", "that", "comes", "with", "FreeSWITCH", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/commands.rb#L37-L47
train
flyerhzm/code_analyzer
lib/code_analyzer/checker.rb
CodeAnalyzer.Checker.add_warning
def add_warning(message, filename = @node.file, line_number = @node.line_number) warnings << Warning.new(filename: filename, line_number: line_number, message: message) end
ruby
def add_warning(message, filename = @node.file, line_number = @node.line_number) warnings << Warning.new(filename: filename, line_number: line_number, message: message) end
[ "def", "add_warning", "(", "message", ",", "filename", "=", "@node", ".", "file", ",", "line_number", "=", "@node", ".", "line_number", ")", "warnings", "<<", "Warning", ".", "new", "(", "filename", ":", "filename", ",", "line_number", ":", "line_number", ",", "message", ":", "message", ")", "end" ]
add an warning. @param [String] message, is the warning message @param [String] filename, is the filename of source code @param [Integer] line_number, is the line number of the source code which is reviewing
[ "add", "an", "warning", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checker.rb#L54-L56
train
mbj/morpher
lib/morpher/type_lookup.rb
Morpher.TypeLookup.call
def call(object) current = target = object.class while current != Object if registry.key?(current) return registry.fetch(current) end current = current.superclass end fail TypeNotFoundError, target end
ruby
def call(object) current = target = object.class while current != Object if registry.key?(current) return registry.fetch(current) end current = current.superclass end fail TypeNotFoundError, target end
[ "def", "call", "(", "object", ")", "current", "=", "target", "=", "object", ".", "class", "while", "current", "!=", "Object", "if", "registry", ".", "key?", "(", "current", ")", "return", "registry", ".", "fetch", "(", "current", ")", "end", "current", "=", "current", ".", "superclass", "end", "fail", "TypeNotFoundError", ",", "target", "end" ]
TypeNotFoundError Perform type lookup @param [Object] object @return [Object] if found @raise [TypeNotFoundError] otherwise @api private
[ "TypeNotFoundError", "Perform", "type", "lookup" ]
c9f9f720933835e09acfe6100bb20e8bd3c01915
https://github.com/mbj/morpher/blob/c9f9f720933835e09acfe6100bb20e8bd3c01915/lib/morpher/type_lookup.rb#L38-L48
train
ballantyne/weibo
lib/weibo.rb
Hashie.Mash.rubyify_keys!
def rubyify_keys! keys.each{|k| v = delete(k) new_key = k.to_s.underscore self[new_key] = v v.rubyify_keys! if v.is_a?(Hash) v.each{|p| p.rubyify_keys! if p.is_a?(Hash)} if v.is_a?(Array) } self end
ruby
def rubyify_keys! keys.each{|k| v = delete(k) new_key = k.to_s.underscore self[new_key] = v v.rubyify_keys! if v.is_a?(Hash) v.each{|p| p.rubyify_keys! if p.is_a?(Hash)} if v.is_a?(Array) } self end
[ "def", "rubyify_keys!", "keys", ".", "each", "{", "|", "k", "|", "v", "=", "delete", "(", "k", ")", "new_key", "=", "k", ".", "to_s", ".", "underscore", "self", "[", "new_key", "]", "=", "v", "v", ".", "rubyify_keys!", "if", "v", ".", "is_a?", "(", "Hash", ")", "v", ".", "each", "{", "|", "p", "|", "p", ".", "rubyify_keys!", "if", "p", ".", "is_a?", "(", "Hash", ")", "}", "if", "v", ".", "is_a?", "(", "Array", ")", "}", "self", "end" ]
Converts all of the keys to strings, optionally formatting key name
[ "Converts", "all", "of", "the", "keys", "to", "strings", "optionally", "formatting", "key", "name" ]
f3ebbf4d706e158cf81d9ffe4a6ed700db7210bc
https://github.com/ballantyne/weibo/blob/f3ebbf4d706e158cf81d9ffe4a6ed700db7210bc/lib/weibo.rb#L44-L53
train
michael-emmi/bam-bam-boogieman
lib/bpl/passes/security/cost_modeling.rb
Bpl.CostModeling.get_annotation_value
def get_annotation_value annotationStmt raise "annotation should have one argument" unless annotationStmt.arguments.length == 1 return annotationStmt.arguments.first.to_s end
ruby
def get_annotation_value annotationStmt raise "annotation should have one argument" unless annotationStmt.arguments.length == 1 return annotationStmt.arguments.first.to_s end
[ "def", "get_annotation_value", "annotationStmt", "raise", "\"annotation should have one argument\"", "unless", "annotationStmt", ".", "arguments", ".", "length", "==", "1", "return", "annotationStmt", ".", "arguments", ".", "first", ".", "to_s", "end" ]
the annotation should have one argument, and we just want whatever it is
[ "the", "annotation", "should", "have", "one", "argument", "and", "we", "just", "want", "whatever", "it", "is" ]
d42037d919e6cc67fcfa7c5ad143f7e2027522d2
https://github.com/michael-emmi/bam-bam-boogieman/blob/d42037d919e6cc67fcfa7c5ad143f7e2027522d2/lib/bpl/passes/security/cost_modeling.rb#L54-L57
train
michael-emmi/bam-bam-boogieman
lib/bpl/passes/security/cost_modeling.rb
Bpl.CostModeling.cost_of
def cost_of block assumes = block.select{ |s| s.is_a?(AssumeStatement)} cost = assumes.inject(0) do |acc, stmt| if values = stmt.get_attribute(:'smack.InstTimingCost.Int64') acc += values.first.show.to_i end acc end return cost end
ruby
def cost_of block assumes = block.select{ |s| s.is_a?(AssumeStatement)} cost = assumes.inject(0) do |acc, stmt| if values = stmt.get_attribute(:'smack.InstTimingCost.Int64') acc += values.first.show.to_i end acc end return cost end
[ "def", "cost_of", "block", "assumes", "=", "block", ".", "select", "{", "|", "s", "|", "s", ".", "is_a?", "(", "AssumeStatement", ")", "}", "cost", "=", "assumes", ".", "inject", "(", "0", ")", "do", "|", "acc", ",", "stmt", "|", "if", "values", "=", "stmt", ".", "get_attribute", "(", ":'", "'", ")", "acc", "+=", "values", ".", "first", ".", "show", ".", "to_i", "end", "acc", "end", "return", "cost", "end" ]
Iterates over timing annotations of a block and sums them up.
[ "Iterates", "over", "timing", "annotations", "of", "a", "block", "and", "sums", "them", "up", "." ]
d42037d919e6cc67fcfa7c5ad143f7e2027522d2
https://github.com/michael-emmi/bam-bam-boogieman/blob/d42037d919e6cc67fcfa7c5ad143f7e2027522d2/lib/bpl/passes/security/cost_modeling.rb#L76-L86
train
michael-emmi/bam-bam-boogieman
lib/bpl/passes/security/cost_modeling.rb
Bpl.CostModeling.extract_branches
def extract_branches blocks branches = [] blocks.each do |block| block.each do |stmt| case stmt when GotoStatement next if stmt.identifiers.length < 2 unless stmt.identifiers.length == 2 fail "Unexpected goto statement: #{stmt}" end if annotation = stmt.previous_sibling fail "Expected :branchcond annotation" unless annotation.has_attribute?(:branchcond) end branches.push(stmt) end end end return branches end
ruby
def extract_branches blocks branches = [] blocks.each do |block| block.each do |stmt| case stmt when GotoStatement next if stmt.identifiers.length < 2 unless stmt.identifiers.length == 2 fail "Unexpected goto statement: #{stmt}" end if annotation = stmt.previous_sibling fail "Expected :branchcond annotation" unless annotation.has_attribute?(:branchcond) end branches.push(stmt) end end end return branches end
[ "def", "extract_branches", "blocks", "branches", "=", "[", "]", "blocks", ".", "each", "do", "|", "block", "|", "block", ".", "each", "do", "|", "stmt", "|", "case", "stmt", "when", "GotoStatement", "next", "if", "stmt", ".", "identifiers", ".", "length", "<", "2", "unless", "stmt", ".", "identifiers", ".", "length", "==", "2", "fail", "\"Unexpected goto statement: #{stmt}\"", "end", "if", "annotation", "=", "stmt", ".", "previous_sibling", "fail", "\"Expected :branchcond annotation\"", "unless", "annotation", ".", "has_attribute?", "(", ":branchcond", ")", "end", "branches", ".", "push", "(", "stmt", ")", "end", "end", "end", "return", "branches", "end" ]
Given a set of blocks, returns 'GotoStatement's of branches
[ "Given", "a", "set", "of", "blocks", "returns", "GotoStatement", "s", "of", "branches" ]
d42037d919e6cc67fcfa7c5ad143f7e2027522d2
https://github.com/michael-emmi/bam-bam-boogieman/blob/d42037d919e6cc67fcfa7c5ad143f7e2027522d2/lib/bpl/passes/security/cost_modeling.rb#L130-L152
train
arbox/wlapi
lib/wlapi/api.rb
WLAPI.API.wordforms
def wordforms(word, limit = 10) check_params(word, limit) # note, it is the only service which requires 'Word', not 'Wort' arg1 = ['Word', word] arg2 = ['Limit', limit] answer = query(@cl_Wordforms, arg1, arg2) get_answer(answer) end
ruby
def wordforms(word, limit = 10) check_params(word, limit) # note, it is the only service which requires 'Word', not 'Wort' arg1 = ['Word', word] arg2 = ['Limit', limit] answer = query(@cl_Wordforms, arg1, arg2) get_answer(answer) end
[ "def", "wordforms", "(", "word", ",", "limit", "=", "10", ")", "check_params", "(", "word", ",", "limit", ")", "arg1", "=", "[", "'Word'", ",", "word", "]", "arg2", "=", "[", "'Limit'", ",", "limit", "]", "answer", "=", "query", "(", "@cl_Wordforms", ",", "arg1", ",", "arg2", ")", "get_answer", "(", "answer", ")", "end" ]
Two parameter methods. Returns all other word forms of the same lemma for a given word form. api.wordforms("Auto") => ["Auto", "Autos"] @return [Array] a list
[ "Two", "parameter", "methods", "." ]
8a5b1b1bbfa58826107daeeae409e4e22b1c5236
https://github.com/arbox/wlapi/blob/8a5b1b1bbfa58826107daeeae409e4e22b1c5236/lib/wlapi/api.rb#L134-L143
train
arbox/wlapi
lib/wlapi/api.rb
WLAPI.API.right_collocation_finder
def right_collocation_finder(word, pos, limit = 10) check_params(word, pos, limit) arg1 = ['Wort', word] arg2 = ['Wortart', pos] arg3 = ['Limit', limit] answer = query(@cl_RightCollocationFinder, arg1, arg2, arg3) get_answer(answer) end
ruby
def right_collocation_finder(word, pos, limit = 10) check_params(word, pos, limit) arg1 = ['Wort', word] arg2 = ['Wortart', pos] arg3 = ['Limit', limit] answer = query(@cl_RightCollocationFinder, arg1, arg2, arg3) get_answer(answer) end
[ "def", "right_collocation_finder", "(", "word", ",", "pos", ",", "limit", "=", "10", ")", "check_params", "(", "word", ",", "pos", ",", "limit", ")", "arg1", "=", "[", "'Wort'", ",", "word", "]", "arg2", "=", "[", "'Wortart'", ",", "pos", "]", "arg3", "=", "[", "'Limit'", ",", "limit", "]", "answer", "=", "query", "(", "@cl_RightCollocationFinder", ",", "arg1", ",", "arg2", ",", "arg3", ")", "get_answer", "(", "answer", ")", "end" ]
Three parameter methods. Attempts to find linguistic collocations that occur to the right of the given input word. The parameter 'Wortart' accepts four values 'A, V, N, S' which stand for adjective, verb, noun and stopword respectively. The parameter restricts the type of words found. It returns an array: api.right_collocation_finder("Auto", "V", 10) => ["Auto", "abfackeln", "V", ...]
[ "Three", "parameter", "methods", "." ]
8a5b1b1bbfa58826107daeeae409e4e22b1c5236
https://github.com/arbox/wlapi/blob/8a5b1b1bbfa58826107daeeae409e4e22b1c5236/lib/wlapi/api.rb#L281-L290
train
arbox/wlapi
lib/wlapi/api.rb
WLAPI.API.cooccurrences
def cooccurrences(word, sign, limit = 10) check_params(word, sign, limit) arg1 = ['Wort', word] arg2 = ['Mindestsignifikanz', sign] arg3 = ['Limit', limit] answer = query(@cl_Cooccurrences, arg1, arg2, arg3) get_answer(answer) end
ruby
def cooccurrences(word, sign, limit = 10) check_params(word, sign, limit) arg1 = ['Wort', word] arg2 = ['Mindestsignifikanz', sign] arg3 = ['Limit', limit] answer = query(@cl_Cooccurrences, arg1, arg2, arg3) get_answer(answer) end
[ "def", "cooccurrences", "(", "word", ",", "sign", ",", "limit", "=", "10", ")", "check_params", "(", "word", ",", "sign", ",", "limit", ")", "arg1", "=", "[", "'Wort'", ",", "word", "]", "arg2", "=", "[", "'Mindestsignifikanz'", ",", "sign", "]", "arg3", "=", "[", "'Limit'", ",", "limit", "]", "answer", "=", "query", "(", "@cl_Cooccurrences", ",", "arg1", ",", "arg2", ",", "arg3", ")", "get_answer", "(", "answer", ")", "end" ]
Returns statistically significant co-occurrences of the input word.
[ "Returns", "statistically", "significant", "co", "-", "occurrences", "of", "the", "input", "word", "." ]
8a5b1b1bbfa58826107daeeae409e4e22b1c5236
https://github.com/arbox/wlapi/blob/8a5b1b1bbfa58826107daeeae409e4e22b1c5236/lib/wlapi/api.rb#L312-L321
train
arbox/wlapi
lib/wlapi/api.rb
WLAPI.API.get_answer
def get_answer(doc, mod='') result = [] # The path seems to be weird, because the namespaces change incrementally # in the output, so I don't want to treat it here. # A modifier needed because synonyms service provides duplicate values. XPath.each(doc, "//result/*/*#{mod}") do |el| warn(el.text) if $DEBUG result << el.text end result.any? ? result : nil end
ruby
def get_answer(doc, mod='') result = [] # The path seems to be weird, because the namespaces change incrementally # in the output, so I don't want to treat it here. # A modifier needed because synonyms service provides duplicate values. XPath.each(doc, "//result/*/*#{mod}") do |el| warn(el.text) if $DEBUG result << el.text end result.any? ? result : nil end
[ "def", "get_answer", "(", "doc", ",", "mod", "=", "''", ")", "result", "=", "[", "]", "XPath", ".", "each", "(", "doc", ",", "\"//result/*/*#{mod}\"", ")", "do", "|", "el", "|", "warn", "(", "el", ".", "text", ")", "if", "$DEBUG", "result", "<<", "el", ".", "text", "end", "result", ".", "any?", "?", "result", ":", "nil", "end" ]
This method extracts valuable data from the XML structure of the soap response. It returns an array with extracted xml text nodes or nil, if the service provided no answer.
[ "This", "method", "extracts", "valuable", "data", "from", "the", "XML", "structure", "of", "the", "soap", "response", ".", "It", "returns", "an", "array", "with", "extracted", "xml", "text", "nodes", "or", "nil", "if", "the", "service", "provided", "no", "answer", "." ]
8a5b1b1bbfa58826107daeeae409e4e22b1c5236
https://github.com/arbox/wlapi/blob/8a5b1b1bbfa58826107daeeae409e4e22b1c5236/lib/wlapi/api.rb#L421-L432
train
souche/aliyun-ons-ruby-sdk
lib/ons/producer.rb
Ons.Producer.send_message
def send_message(topic, tag, body, key = '') @producer.send_message(topic, tag, body, key) end
ruby
def send_message(topic, tag, body, key = '') @producer.send_message(topic, tag, body, key) end
[ "def", "send_message", "(", "topic", ",", "tag", ",", "body", ",", "key", "=", "''", ")", "@producer", ".", "send_message", "(", "topic", ",", "tag", ",", "body", ",", "key", ")", "end" ]
Create a new aliyun ONS Producer instance. @param access_key [String] the access key to aliyun ONS @param secret_key [String] the secret key to aliyun ONS @param producer_id [String] the producer ID @param options [Hash{String, Symbol => String}] @option options [String] :namesrv_addr the nameserver used to fetching ons_addr @option options [String] :ons_addr the ONS server address @option options [String, Fixnum, Bignum] :send_timeout (3000) send message timeout Send a message. @example send 'Hello, World!' message with tag :tagA which is under topic :TopicTestMQ producer.send_message('TopicTestMQ', 'tagA', 'Hello, World!') @see #send_timer_message @param topic [String] the message topic @param tag [String] the message tag @param body [String] the message body @param key [String] the message key @return [String] the message id
[ "Create", "a", "new", "aliyun", "ONS", "Producer", "instance", "." ]
00d16d5fe4dc55929036544a7667c463694f6b1f
https://github.com/souche/aliyun-ons-ruby-sdk/blob/00d16d5fe4dc55929036544a7667c463694f6b1f/lib/ons/producer.rb#L39-L41
train
souche/aliyun-ons-ruby-sdk
lib/ons/producer.rb
Ons.Producer.send_timer_message
def send_timer_message(topic, tag, body, timer, key = '') @producer.send_timer_message(topic, tag, body, timer.to_i * 1000, key) end
ruby
def send_timer_message(topic, tag, body, timer, key = '') @producer.send_timer_message(topic, tag, body, timer.to_i * 1000, key) end
[ "def", "send_timer_message", "(", "topic", ",", "tag", ",", "body", ",", "timer", ",", "key", "=", "''", ")", "@producer", ".", "send_timer_message", "(", "topic", ",", "tag", ",", "body", ",", "timer", ".", "to_i", "*", "1000", ",", "key", ")", "end" ]
Send a timer message. @example send 'Hello, World!' message at 30 seconds later producer.send_timer_message('TopicTestMQ', 'tagA', 'Hello, World!', Time.now + 30) @see #send_message @param topic [String] the message topic @param tag [String] the message tag @param body [String] the message body @param timer [#to_i] when deliver the message @param key [String] the message key @return [String] the message id
[ "Send", "a", "timer", "message", "." ]
00d16d5fe4dc55929036544a7667c463694f6b1f
https://github.com/souche/aliyun-ons-ruby-sdk/blob/00d16d5fe4dc55929036544a7667c463694f6b1f/lib/ons/producer.rb#L56-L58
train
woodruffw/ruby-mpv
lib/mpv/client.rb
MPV.Client.distribute_results!
def distribute_results! response = JSON.parse(@socket.readline) if response["event"] @event_queue << response else @result_queue << response end rescue StandardError @alive = false Thread.exit end
ruby
def distribute_results! response = JSON.parse(@socket.readline) if response["event"] @event_queue << response else @result_queue << response end rescue StandardError @alive = false Thread.exit end
[ "def", "distribute_results!", "response", "=", "JSON", ".", "parse", "(", "@socket", ".", "readline", ")", "if", "response", "[", "\"event\"", "]", "@event_queue", "<<", "response", "else", "@result_queue", "<<", "response", "end", "rescue", "StandardError", "@alive", "=", "false", "Thread", ".", "exit", "end" ]
Distributes results to the event and result queues. @api private
[ "Distributes", "results", "to", "the", "event", "and", "result", "queues", "." ]
af813337aaf64f25b48e562de2176dec1b381aab
https://github.com/woodruffw/ruby-mpv/blob/af813337aaf64f25b48e562de2176dec1b381aab/lib/mpv/client.rb#L120-L131
train
woodruffw/ruby-mpv
lib/mpv/client.rb
MPV.Client.dispatch_events!
def dispatch_events! loop do event = @event_queue.pop callbacks.each do |callback| Thread.new do callback.call event end end end end
ruby
def dispatch_events! loop do event = @event_queue.pop callbacks.each do |callback| Thread.new do callback.call event end end end end
[ "def", "dispatch_events!", "loop", "do", "event", "=", "@event_queue", ".", "pop", "callbacks", ".", "each", "do", "|", "callback", "|", "Thread", ".", "new", "do", "callback", ".", "call", "event", "end", "end", "end", "end" ]
Takes events from the event queue and dispatches them to callbacks. @api private
[ "Takes", "events", "from", "the", "event", "queue", "and", "dispatches", "them", "to", "callbacks", "." ]
af813337aaf64f25b48e562de2176dec1b381aab
https://github.com/woodruffw/ruby-mpv/blob/af813337aaf64f25b48e562de2176dec1b381aab/lib/mpv/client.rb#L135-L145
train
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute.rb
Beaker.GoogleCompute.find_google_ssh_public_key
def find_google_ssh_public_key keyfile = ENV.fetch('BEAKER_gce_ssh_public_key', File.join(ENV['HOME'], '.ssh', 'google_compute_engine.pub')) if @options[:gce_ssh_public_key] && !File.exist?(keyfile) keyfile = @options[:gce_ssh_public_key] end raise("Could not find GCE Public SSH Key at '#{keyfile}'") unless File.exist?(keyfile) return keyfile end
ruby
def find_google_ssh_public_key keyfile = ENV.fetch('BEAKER_gce_ssh_public_key', File.join(ENV['HOME'], '.ssh', 'google_compute_engine.pub')) if @options[:gce_ssh_public_key] && !File.exist?(keyfile) keyfile = @options[:gce_ssh_public_key] end raise("Could not find GCE Public SSH Key at '#{keyfile}'") unless File.exist?(keyfile) return keyfile end
[ "def", "find_google_ssh_public_key", "keyfile", "=", "ENV", ".", "fetch", "(", "'BEAKER_gce_ssh_public_key'", ",", "File", ".", "join", "(", "ENV", "[", "'HOME'", "]", ",", "'.ssh'", ",", "'google_compute_engine.pub'", ")", ")", "if", "@options", "[", ":gce_ssh_public_key", "]", "&&", "!", "File", ".", "exist?", "(", "keyfile", ")", "keyfile", "=", "@options", "[", ":gce_ssh_public_key", "]", "end", "raise", "(", "\"Could not find GCE Public SSH Key at '#{keyfile}'\"", ")", "unless", "File", ".", "exist?", "(", "keyfile", ")", "return", "keyfile", "end" ]
Do some reasonable sleuthing on the SSH public key for GCE
[ "Do", "some", "reasonable", "sleuthing", "on", "the", "SSH", "public", "key", "for", "GCE" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute.rb#L14-L24
train
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute.rb
Beaker.GoogleCompute.provision
def provision attempts = @options[:timeout].to_i / SLEEPWAIT start = Time.now test_group_identifier = "beaker-#{start.to_i}-" # get machineType resource, used by all instances machineType = @gce_helper.get_machineType(start, attempts) # set firewall to open pe ports network = @gce_helper.get_network(start, attempts) @firewall = test_group_identifier + generate_host_name @gce_helper.create_firewall(@firewall, network, start, attempts) @logger.debug("Created Google Compute firewall #{@firewall}") @hosts.each do |host| if host[:image] gplatform = host[:image] elsif host[:platform] gplatform = Platform.new(host[:platform]) else raise('You must specify either :image or :platform, or both as necessary') end img = @gce_helper.get_latest_image(gplatform, start, attempts) unique_host_id = test_group_identifier + generate_host_name host['diskname'] = unique_host_id disk = @gce_helper.create_disk(host['diskname'], img, start, attempts) @logger.debug("Created Google Compute disk for #{host.name}: #{host['diskname']}") # create new host name host['vmhostname'] = unique_host_id #add a new instance of the image instance = @gce_helper.create_instance(host['vmhostname'], img, machineType, disk, start, attempts) @logger.debug("Created Google Compute instance for #{host.name}: #{host['vmhostname']}") # add metadata to instance, if there is any to set mdata = format_metadata unless mdata.empty? @gce_helper.setMetadata_on_instance(host['vmhostname'], instance['metadata']['fingerprint'], mdata, start, attempts) @logger.debug("Added tags to Google Compute instance #{host.name}: #{host['vmhostname']}") end # get ip for this host host['ip'] = instance['networkInterfaces'][0]['accessConfigs'][0]['natIP'] # configure ssh default_user = host['user'] host['user'] = 'google_compute' copy_ssh_to_root(host, @options) enable_root_login(host, @options) host['user'] = default_user # shut down connection, will reconnect on next exec host.close @logger.debug("Instance ready: #{host['vmhostname']} for #{host.name}}") end end
ruby
def provision attempts = @options[:timeout].to_i / SLEEPWAIT start = Time.now test_group_identifier = "beaker-#{start.to_i}-" # get machineType resource, used by all instances machineType = @gce_helper.get_machineType(start, attempts) # set firewall to open pe ports network = @gce_helper.get_network(start, attempts) @firewall = test_group_identifier + generate_host_name @gce_helper.create_firewall(@firewall, network, start, attempts) @logger.debug("Created Google Compute firewall #{@firewall}") @hosts.each do |host| if host[:image] gplatform = host[:image] elsif host[:platform] gplatform = Platform.new(host[:platform]) else raise('You must specify either :image or :platform, or both as necessary') end img = @gce_helper.get_latest_image(gplatform, start, attempts) unique_host_id = test_group_identifier + generate_host_name host['diskname'] = unique_host_id disk = @gce_helper.create_disk(host['diskname'], img, start, attempts) @logger.debug("Created Google Compute disk for #{host.name}: #{host['diskname']}") # create new host name host['vmhostname'] = unique_host_id #add a new instance of the image instance = @gce_helper.create_instance(host['vmhostname'], img, machineType, disk, start, attempts) @logger.debug("Created Google Compute instance for #{host.name}: #{host['vmhostname']}") # add metadata to instance, if there is any to set mdata = format_metadata unless mdata.empty? @gce_helper.setMetadata_on_instance(host['vmhostname'], instance['metadata']['fingerprint'], mdata, start, attempts) @logger.debug("Added tags to Google Compute instance #{host.name}: #{host['vmhostname']}") end # get ip for this host host['ip'] = instance['networkInterfaces'][0]['accessConfigs'][0]['natIP'] # configure ssh default_user = host['user'] host['user'] = 'google_compute' copy_ssh_to_root(host, @options) enable_root_login(host, @options) host['user'] = default_user # shut down connection, will reconnect on next exec host.close @logger.debug("Instance ready: #{host['vmhostname']} for #{host.name}}") end end
[ "def", "provision", "attempts", "=", "@options", "[", ":timeout", "]", ".", "to_i", "/", "SLEEPWAIT", "start", "=", "Time", ".", "now", "test_group_identifier", "=", "\"beaker-#{start.to_i}-\"", "machineType", "=", "@gce_helper", ".", "get_machineType", "(", "start", ",", "attempts", ")", "network", "=", "@gce_helper", ".", "get_network", "(", "start", ",", "attempts", ")", "@firewall", "=", "test_group_identifier", "+", "generate_host_name", "@gce_helper", ".", "create_firewall", "(", "@firewall", ",", "network", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Created Google Compute firewall #{@firewall}\"", ")", "@hosts", ".", "each", "do", "|", "host", "|", "if", "host", "[", ":image", "]", "gplatform", "=", "host", "[", ":image", "]", "elsif", "host", "[", ":platform", "]", "gplatform", "=", "Platform", ".", "new", "(", "host", "[", ":platform", "]", ")", "else", "raise", "(", "'You must specify either :image or :platform, or both as necessary'", ")", "end", "img", "=", "@gce_helper", ".", "get_latest_image", "(", "gplatform", ",", "start", ",", "attempts", ")", "unique_host_id", "=", "test_group_identifier", "+", "generate_host_name", "host", "[", "'diskname'", "]", "=", "unique_host_id", "disk", "=", "@gce_helper", ".", "create_disk", "(", "host", "[", "'diskname'", "]", ",", "img", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Created Google Compute disk for #{host.name}: #{host['diskname']}\"", ")", "host", "[", "'vmhostname'", "]", "=", "unique_host_id", "instance", "=", "@gce_helper", ".", "create_instance", "(", "host", "[", "'vmhostname'", "]", ",", "img", ",", "machineType", ",", "disk", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Created Google Compute instance for #{host.name}: #{host['vmhostname']}\"", ")", "mdata", "=", "format_metadata", "unless", "mdata", ".", "empty?", "@gce_helper", ".", "setMetadata_on_instance", "(", "host", "[", "'vmhostname'", "]", ",", "instance", "[", "'metadata'", "]", "[", "'fingerprint'", "]", ",", "mdata", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Added tags to Google Compute instance #{host.name}: #{host['vmhostname']}\"", ")", "end", "host", "[", "'ip'", "]", "=", "instance", "[", "'networkInterfaces'", "]", "[", "0", "]", "[", "'accessConfigs'", "]", "[", "0", "]", "[", "'natIP'", "]", "default_user", "=", "host", "[", "'user'", "]", "host", "[", "'user'", "]", "=", "'google_compute'", "copy_ssh_to_root", "(", "host", ",", "@options", ")", "enable_root_login", "(", "host", ",", "@options", ")", "host", "[", "'user'", "]", "=", "default_user", "host", ".", "close", "@logger", ".", "debug", "(", "\"Instance ready: #{host['vmhostname']} for #{host.name}}\"", ")", "end", "end" ]
Create a new instance of the Google Compute Engine hypervisor object @param [<Host>] google_hosts The Array of google hosts to provision, may ONLY be of platforms /centos-*/, /debian-*/, /rhel-*/, /suse-*/. Only supports the Google Compute provided templates. @param [Hash{Symbol=>String}] options The options hash containing configuration values @option options [String] :gce_project The Google Compute Project name to connect to @option options [String] :gce_keyfile The location of the Google Compute service account keyfile @option options [String] :gce_password The password for the Google Compute service account key @option options [String] :gce_email The email address for the Google Compute service account @option options [String] :gce_machine_type A Google Compute machine type used to create instances, defaults to n1-highmem-2 @option options [Integer] :timeout The amount of time to attempt execution before quiting and exiting with failure Create and configure virtual machines in the Google Compute Engine, including their associated disks and firewall rules
[ "Create", "a", "new", "instance", "of", "the", "Google", "Compute", "Engine", "hypervisor", "object" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute.rb#L72-L137
train
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute.rb
Beaker.GoogleCompute.cleanup
def cleanup() attempts = @options[:timeout].to_i / SLEEPWAIT start = Time.now @gce_helper.delete_firewall(@firewall, start, attempts) @hosts.each do |host| @gce_helper.delete_instance(host['vmhostname'], start, attempts) @logger.debug("Deleted Google Compute instance #{host['vmhostname']} for #{host.name}") @gce_helper.delete_disk(host['diskname'], start, attempts) @logger.debug("Deleted Google Compute disk #{host['diskname']} for #{host.name}") end end
ruby
def cleanup() attempts = @options[:timeout].to_i / SLEEPWAIT start = Time.now @gce_helper.delete_firewall(@firewall, start, attempts) @hosts.each do |host| @gce_helper.delete_instance(host['vmhostname'], start, attempts) @logger.debug("Deleted Google Compute instance #{host['vmhostname']} for #{host.name}") @gce_helper.delete_disk(host['diskname'], start, attempts) @logger.debug("Deleted Google Compute disk #{host['diskname']} for #{host.name}") end end
[ "def", "cleanup", "(", ")", "attempts", "=", "@options", "[", ":timeout", "]", ".", "to_i", "/", "SLEEPWAIT", "start", "=", "Time", ".", "now", "@gce_helper", ".", "delete_firewall", "(", "@firewall", ",", "start", ",", "attempts", ")", "@hosts", ".", "each", "do", "|", "host", "|", "@gce_helper", ".", "delete_instance", "(", "host", "[", "'vmhostname'", "]", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Deleted Google Compute instance #{host['vmhostname']} for #{host.name}\"", ")", "@gce_helper", ".", "delete_disk", "(", "host", "[", "'diskname'", "]", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Deleted Google Compute disk #{host['diskname']} for #{host.name}\"", ")", "end", "end" ]
Shutdown and destroy virtual machines in the Google Compute Engine, including their associated disks and firewall rules
[ "Shutdown", "and", "destroy", "virtual", "machines", "in", "the", "Google", "Compute", "Engine", "including", "their", "associated", "disks", "and", "firewall", "rules" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute.rb#L141-L154
train
russ/country_code_select
lib/country_code_select/instance_tag.rb
CountryCodeSelect.InstanceTag.country_code_select
def country_code_select(priority_countries, options) selected = object.send(@method_name) countries = "" if priority_countries countries += options_for_select(priority_countries, selected) countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" elsif options[:include_blank] countries += "<option value=\"\">" + options[:include_blank] + "</options>\n" countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" end countries = countries + options_for_select(COUNTRIES, selected) content_tag(:select, countries, options.merge(id: "#{@object_name}_#{@method_name}", :name => "#{@object_name}[#{@method_name}]"), false) end
ruby
def country_code_select(priority_countries, options) selected = object.send(@method_name) countries = "" if priority_countries countries += options_for_select(priority_countries, selected) countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" elsif options[:include_blank] countries += "<option value=\"\">" + options[:include_blank] + "</options>\n" countries += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" end countries = countries + options_for_select(COUNTRIES, selected) content_tag(:select, countries, options.merge(id: "#{@object_name}_#{@method_name}", :name => "#{@object_name}[#{@method_name}]"), false) end
[ "def", "country_code_select", "(", "priority_countries", ",", "options", ")", "selected", "=", "object", ".", "send", "(", "@method_name", ")", "countries", "=", "\"\"", "if", "priority_countries", "countries", "+=", "options_for_select", "(", "priority_countries", ",", "selected", ")", "countries", "+=", "\"<option value=\\\"\\\" disabled=\\\"disabled\\\">-------------</option>\\n\"", "elsif", "options", "[", ":include_blank", "]", "countries", "+=", "\"<option value=\\\"\\\">\"", "+", "options", "[", ":include_blank", "]", "+", "\"</options>\\n\"", "countries", "+=", "\"<option value=\\\"\\\" disabled=\\\"disabled\\\">-------------</option>\\n\"", "end", "countries", "=", "countries", "+", "options_for_select", "(", "COUNTRIES", ",", "selected", ")", "content_tag", "(", ":select", ",", "countries", ",", "options", ".", "merge", "(", "id", ":", "\"#{@object_name}_#{@method_name}\"", ",", ":name", "=>", "\"#{@object_name}[#{@method_name}]\"", ")", ",", "false", ")", "end" ]
Adapted from Rails country_select. Just uses country codes instead of full names.
[ "Adapted", "from", "Rails", "country_select", ".", "Just", "uses", "country", "codes", "instead", "of", "full", "names", "." ]
c1975db2f0b55129bd207ddcd3cb294fa4a5ec5d
https://github.com/russ/country_code_select/blob/c1975db2f0b55129bd207ddcd3cb294fa4a5ec5d/lib/country_code_select/instance_tag.rb#L10-L24
train
adonespitogo/unsakini
app/controllers/unsakini/boards_controller.rb
Unsakini.BoardsController.index
def index admin = true shared = false admin = params[:is_admin] == 'true' if params[:admin] shared = params[:shared] == 'true' if params[:shared] result = @user.user_boards.shared(shared) result = result.admin if admin paginate json: result, per_page: 10 end
ruby
def index admin = true shared = false admin = params[:is_admin] == 'true' if params[:admin] shared = params[:shared] == 'true' if params[:shared] result = @user.user_boards.shared(shared) result = result.admin if admin paginate json: result, per_page: 10 end
[ "def", "index", "admin", "=", "true", "shared", "=", "false", "admin", "=", "params", "[", ":is_admin", "]", "==", "'true'", "if", "params", "[", ":admin", "]", "shared", "=", "params", "[", ":shared", "]", "==", "'true'", "if", "params", "[", ":shared", "]", "result", "=", "@user", ".", "user_boards", ".", "shared", "(", "shared", ")", "result", "=", "result", ".", "admin", "if", "admin", "paginate", "json", ":", "result", ",", "per_page", ":", "10", "end" ]
Returns boards belonging to current user `GET /api/boards`
[ "Returns", "boards", "belonging", "to", "current", "user" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/boards_controller.rb#L17-L25
train
adonespitogo/unsakini
app/controllers/unsakini/boards_controller.rb
Unsakini.BoardsController.create
def create @user_board = UserBoard.new( name: params[:board][:name], user_id: @user.id, encrypted_password: params[:encrypted_password], is_admin: true ) if @user_board.save render json: @user_board, status: :created else render json: @user_board.errors.full_messages, status: 422 end end
ruby
def create @user_board = UserBoard.new( name: params[:board][:name], user_id: @user.id, encrypted_password: params[:encrypted_password], is_admin: true ) if @user_board.save render json: @user_board, status: :created else render json: @user_board.errors.full_messages, status: 422 end end
[ "def", "create", "@user_board", "=", "UserBoard", ".", "new", "(", "name", ":", "params", "[", ":board", "]", "[", ":name", "]", ",", "user_id", ":", "@user", ".", "id", ",", "encrypted_password", ":", "params", "[", ":encrypted_password", "]", ",", "is_admin", ":", "true", ")", "if", "@user_board", ".", "save", "render", "json", ":", "@user_board", ",", "status", ":", ":created", "else", "render", "json", ":", "@user_board", ".", "errors", ".", "full_messages", ",", "status", ":", "422", "end", "end" ]
Creates board belonging to current user. `POST /api/boards`
[ "Creates", "board", "belonging", "to", "current", "user", "." ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/boards_controller.rb#L31-L44
train
adonespitogo/unsakini
app/controllers/unsakini/boards_controller.rb
Unsakini.BoardsController.update
def update if @user_board.update(name: params[:board][:name], encrypted_password: params[:encrypted_password]) render json: @user_board else errors = @board.errors.full_messages.concat @user_board.errors.full_messages render json: errors, status: 422 end end
ruby
def update if @user_board.update(name: params[:board][:name], encrypted_password: params[:encrypted_password]) render json: @user_board else errors = @board.errors.full_messages.concat @user_board.errors.full_messages render json: errors, status: 422 end end
[ "def", "update", "if", "@user_board", ".", "update", "(", "name", ":", "params", "[", ":board", "]", "[", ":name", "]", ",", "encrypted_password", ":", "params", "[", ":encrypted_password", "]", ")", "render", "json", ":", "@user_board", "else", "errors", "=", "@board", ".", "errors", ".", "full_messages", ".", "concat", "@user_board", ".", "errors", ".", "full_messages", "render", "json", ":", "errors", ",", "status", ":", "422", "end", "end" ]
Updates a single board. `PUT /api/boards/:id`
[ "Updates", "a", "single", "board", "." ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/boards_controller.rb#L57-L64
train
tevren/biffbot
lib/biffbot/base.rb
Biffbot.Base.generate_url
def generate_url url, token, type, version case type when 'analyze' url = "http://api.diffbot.com/v3/#{type}?token=#{token}&url=#{url}" when 'custom' url = "http://api.diffbot.com/v3/#{options[:api_name]}?token=#{token}&url=#{url}" when 'article', 'image', 'product' url = "http://api.diffbot.com/v2/#{type}?token=#{token}&url=#{url}" url = "http://api.diffbot.com/#{version}/#{type}?token=#{token}&url=#{url}" if version == 'v2' || version == 'v3' end url end
ruby
def generate_url url, token, type, version case type when 'analyze' url = "http://api.diffbot.com/v3/#{type}?token=#{token}&url=#{url}" when 'custom' url = "http://api.diffbot.com/v3/#{options[:api_name]}?token=#{token}&url=#{url}" when 'article', 'image', 'product' url = "http://api.diffbot.com/v2/#{type}?token=#{token}&url=#{url}" url = "http://api.diffbot.com/#{version}/#{type}?token=#{token}&url=#{url}" if version == 'v2' || version == 'v3' end url end
[ "def", "generate_url", "url", ",", "token", ",", "type", ",", "version", "case", "type", "when", "'analyze'", "url", "=", "\"http://api.diffbot.com/v3/#{type}?token=#{token}&url=#{url}\"", "when", "'custom'", "url", "=", "\"http://api.diffbot.com/v3/#{options[:api_name]}?token=#{token}&url=#{url}\"", "when", "'article'", ",", "'image'", ",", "'product'", "url", "=", "\"http://api.diffbot.com/v2/#{type}?token=#{token}&url=#{url}\"", "url", "=", "\"http://api.diffbot.com/#{version}/#{type}?token=#{token}&url=#{url}\"", "if", "version", "==", "'v2'", "||", "version", "==", "'v3'", "end", "url", "end" ]
generate an url consisting of your api key and the endpoint you'd like to use @param url [String] The url to pass to diffbot @param token [String] Diffbot API token @param type [String] API to use @return [String] a formatted url with your api key, endpoint and input url
[ "generate", "an", "url", "consisting", "of", "your", "api", "key", "and", "the", "endpoint", "you", "d", "like", "to", "use" ]
bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3
https://github.com/tevren/biffbot/blob/bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3/lib/biffbot/base.rb#L28-L39
train
tevren/biffbot
lib/biffbot/base.rb
Biffbot.Base.parse_options
def parse_options options = {}, request = '' options.each do |opt, value| case opt when :timeout, :paging, :mode request += "&#{opt}=#{value}" when :callback, :stats request += "&#{opt}" when :fields request += "&#{opt}=" + value.join(',') if value.is_a?(Array) end end request end
ruby
def parse_options options = {}, request = '' options.each do |opt, value| case opt when :timeout, :paging, :mode request += "&#{opt}=#{value}" when :callback, :stats request += "&#{opt}" when :fields request += "&#{opt}=" + value.join(',') if value.is_a?(Array) end end request end
[ "def", "parse_options", "options", "=", "{", "}", ",", "request", "=", "''", "options", ".", "each", "do", "|", "opt", ",", "value", "|", "case", "opt", "when", ":timeout", ",", ":paging", ",", ":mode", "request", "+=", "\"&#{opt}=#{value}\"", "when", ":callback", ",", ":stats", "request", "+=", "\"&#{opt}\"", "when", ":fields", "request", "+=", "\"&#{opt}=\"", "+", "value", ".", "join", "(", "','", ")", "if", "value", ".", "is_a?", "(", "Array", ")", "end", "end", "request", "end" ]
add the options hash to your input url @param options [Hash] An hash of options @param request [String] The url to append options to @return [String] a formatted url with options merged into the input url
[ "add", "the", "options", "hash", "to", "your", "input", "url" ]
bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3
https://github.com/tevren/biffbot/blob/bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3/lib/biffbot/base.rb#L46-L58
train
melborne/colorable
lib/colorable/color.rb
Colorable.Color.info
def info { name: name, rgb: rgb, hsb: hsb, hex: hex, mode: mode, dark: dark? } end
ruby
def info { name: name, rgb: rgb, hsb: hsb, hex: hex, mode: mode, dark: dark? } end
[ "def", "info", "{", "name", ":", "name", ",", "rgb", ":", "rgb", ",", "hsb", ":", "hsb", ",", "hex", ":", "hex", ",", "mode", ":", "mode", ",", "dark", ":", "dark?", "}", "end" ]
Returns information of the color object
[ "Returns", "information", "of", "the", "color", "object" ]
1787059652aa4b85e7f879c16a7b6a36e6b90e59
https://github.com/melborne/colorable/blob/1787059652aa4b85e7f879c16a7b6a36e6b90e59/lib/colorable/color.rb#L40-L49
train
melborne/colorable
lib/colorable/color.rb
Colorable.Color.next
def next(n=1) @@colorset[mode] ||= Colorable::Colorset.new(order: mode) idx = @@colorset[mode].find_index(self) @@colorset[mode].at(idx+n).tap{|c| c.mode = mode } if idx end
ruby
def next(n=1) @@colorset[mode] ||= Colorable::Colorset.new(order: mode) idx = @@colorset[mode].find_index(self) @@colorset[mode].at(idx+n).tap{|c| c.mode = mode } if idx end
[ "def", "next", "(", "n", "=", "1", ")", "@@colorset", "[", "mode", "]", "||=", "Colorable", "::", "Colorset", ".", "new", "(", "order", ":", "mode", ")", "idx", "=", "@@colorset", "[", "mode", "]", ".", "find_index", "(", "self", ")", "@@colorset", "[", "mode", "]", ".", "at", "(", "idx", "+", "n", ")", ".", "tap", "{", "|", "c", "|", "c", ".", "mode", "=", "mode", "}", "if", "idx", "end" ]
Returns a next color object in X11 colors. The color sequence is determined by its color mode.
[ "Returns", "a", "next", "color", "object", "in", "X11", "colors", ".", "The", "color", "sequence", "is", "determined", "by", "its", "color", "mode", "." ]
1787059652aa4b85e7f879c16a7b6a36e6b90e59
https://github.com/melborne/colorable/blob/1787059652aa4b85e7f879c16a7b6a36e6b90e59/lib/colorable/color.rb#L103-L107
train
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/plain.rb
CodeAnalyzer::CheckingVisitor.Plain.check
def check(filename, content) @checkers.each do |checker| checker.check(filename, content) if checker.parse_file?(filename) end end
ruby
def check(filename, content) @checkers.each do |checker| checker.check(filename, content) if checker.parse_file?(filename) end end
[ "def", "check", "(", "filename", ",", "content", ")", "@checkers", ".", "each", "do", "|", "checker", "|", "checker", ".", "check", "(", "filename", ",", "content", ")", "if", "checker", ".", "parse_file?", "(", "filename", ")", "end", "end" ]
check the ruby plain code. @param [String] filename is the filename of ruby code. @param [String] content is the content of ruby file.
[ "check", "the", "ruby", "plain", "code", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/plain.rb#L9-L13
train
adonespitogo/unsakini
app/controllers/concerns/unsakini/post_owner_controller_concern.rb
Unsakini.PostOwnerControllerConcern.ensure_post
def ensure_post post_id = params[:post_id] || params[:id] board_id = params[:board_id] result = has_post_access(board_id, post_id) status = result[:status] @post = result[:post] head status if status != :ok end
ruby
def ensure_post post_id = params[:post_id] || params[:id] board_id = params[:board_id] result = has_post_access(board_id, post_id) status = result[:status] @post = result[:post] head status if status != :ok end
[ "def", "ensure_post", "post_id", "=", "params", "[", ":post_id", "]", "||", "params", "[", ":id", "]", "board_id", "=", "params", "[", ":board_id", "]", "result", "=", "has_post_access", "(", "board_id", ",", "post_id", ")", "status", "=", "result", "[", ":status", "]", "@post", "=", "result", "[", ":post", "]", "head", "status", "if", "status", "!=", ":ok", "end" ]
Ensures user is owner of the post and sets the `@post` variable in the controllers
[ "Ensures", "user", "is", "owner", "of", "the", "post", "and", "sets", "the" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/post_owner_controller_concern.rb#L7-L14
train
adonespitogo/unsakini
app/controllers/concerns/unsakini/post_owner_controller_concern.rb
Unsakini.PostOwnerControllerConcern.has_post_access
def has_post_access(board_id, post_id) post = Unsakini::Post.where(id: post_id, board_id: board_id) .joins("LEFT JOIN #{UserBoard.table_name} ON #{UserBoard.table_name}.board_id = #{Post.table_name}.board_id") .where("#{UserBoard.table_name}.user_id = ?", @user.id) .first if post.nil? return {status: :forbidden} else return {status: :ok, post: post} end end
ruby
def has_post_access(board_id, post_id) post = Unsakini::Post.where(id: post_id, board_id: board_id) .joins("LEFT JOIN #{UserBoard.table_name} ON #{UserBoard.table_name}.board_id = #{Post.table_name}.board_id") .where("#{UserBoard.table_name}.user_id = ?", @user.id) .first if post.nil? return {status: :forbidden} else return {status: :ok, post: post} end end
[ "def", "has_post_access", "(", "board_id", ",", "post_id", ")", "post", "=", "Unsakini", "::", "Post", ".", "where", "(", "id", ":", "post_id", ",", "board_id", ":", "board_id", ")", ".", "joins", "(", "\"LEFT JOIN #{UserBoard.table_name} ON #{UserBoard.table_name}.board_id = #{Post.table_name}.board_id\"", ")", ".", "where", "(", "\"#{UserBoard.table_name}.user_id = ?\"", ",", "@user", ".", "id", ")", ".", "first", "if", "post", ".", "nil?", "return", "{", "status", ":", ":forbidden", "}", "else", "return", "{", "status", ":", ":ok", ",", "post", ":", "post", "}", "end", "end" ]
Validate if user has access to the post in the board @param board_id [Integer] board id @param post_id [Integer] post id
[ "Validate", "if", "user", "has", "access", "to", "the", "post", "in", "the", "board" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/post_owner_controller_concern.rb#L20-L30
train
wearefine/maximus
lib/maximus/statistics/stylestats.rb
Maximus.Stylestats.compile_scss
def compile_scss puts "\nCompiling assets for stylestats...".color(:blue) if is_rails? # Get rake tasks Rails.application.load_tasks unless @config.is_dev? compile_scss_rails else load_compass compile_scss end end
ruby
def compile_scss puts "\nCompiling assets for stylestats...".color(:blue) if is_rails? # Get rake tasks Rails.application.load_tasks unless @config.is_dev? compile_scss_rails else load_compass compile_scss end end
[ "def", "compile_scss", "puts", "\"\\nCompiling assets for stylestats...\"", ".", "color", "(", ":blue", ")", "if", "is_rails?", "Rails", ".", "application", ".", "load_tasks", "unless", "@config", ".", "is_dev?", "compile_scss_rails", "else", "load_compass", "compile_scss", "end", "end" ]
Find all CSS files or compile. Uses sprockets if Rails; Sass engine otherwise. Compass is supported @return [#compile_scss_rails, #compile_scss, Array] CSS files
[ "Find", "all", "CSS", "files", "or", "compile", "." ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/stylestats.rb#L40-L53
train
wearefine/maximus
lib/maximus/statistics/stylestats.rb
Maximus.Stylestats.load_compass
def load_compass if Gem::Specification::find_all_by_name('compass').any? require 'compass' Compass.sass_engine_options[:load_paths].each do |path| Sass.load_paths << path end end end
ruby
def load_compass if Gem::Specification::find_all_by_name('compass').any? require 'compass' Compass.sass_engine_options[:load_paths].each do |path| Sass.load_paths << path end end end
[ "def", "load_compass", "if", "Gem", "::", "Specification", "::", "find_all_by_name", "(", "'compass'", ")", ".", "any?", "require", "'compass'", "Compass", ".", "sass_engine_options", "[", ":load_paths", "]", ".", "each", "do", "|", "path", "|", "Sass", ".", "load_paths", "<<", "path", "end", "end", "end" ]
Load Compass paths if the gem exists @see find_css_files @since 0.1.5
[ "Load", "Compass", "paths", "if", "the", "gem", "exists" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/stylestats.rb#L58-L65
train
wearefine/maximus
lib/maximus/statistics/stylestats.rb
Maximus.Stylestats.load_scss_load_paths
def load_scss_load_paths Dir.glob(@path).select { |d| File.directory? d}.each do |directory| Sass.load_paths << directory end end
ruby
def load_scss_load_paths Dir.glob(@path).select { |d| File.directory? d}.each do |directory| Sass.load_paths << directory end end
[ "def", "load_scss_load_paths", "Dir", ".", "glob", "(", "@path", ")", ".", "select", "{", "|", "d", "|", "File", ".", "directory?", "d", "}", ".", "each", "do", "|", "directory", "|", "Sass", ".", "load_paths", "<<", "directory", "end", "end" ]
Add directories to load paths @todo This function is here in case older versions of SCSS will need it because there shouldn't be a need to load paths, but there might be a need in older versions of SCSS, which should be tested (although the SCSSLint) dependency may dictate our scss version @since 0.1.5
[ "Add", "directories", "to", "load", "paths" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/stylestats.rb#L73-L77
train
wearefine/maximus
lib/maximus/statistics/stylestats.rb
Maximus.Stylestats.compile_scss_normal
def compile_scss_normal Dir["#{@path}.scss"].select { |f| File.file? f }.each do |file| next if File.basename(file).chr == '_' scss_file = File.open(file, 'rb') { |f| f.read } output_file = File.open( file.split('.').reverse.drop(1).reverse.join('.'), "w" ) output_file << Sass::Engine.new(scss_file, { syntax: :scss, quiet: true, style: :compressed }).render output_file.close end end
ruby
def compile_scss_normal Dir["#{@path}.scss"].select { |f| File.file? f }.each do |file| next if File.basename(file).chr == '_' scss_file = File.open(file, 'rb') { |f| f.read } output_file = File.open( file.split('.').reverse.drop(1).reverse.join('.'), "w" ) output_file << Sass::Engine.new(scss_file, { syntax: :scss, quiet: true, style: :compressed }).render output_file.close end end
[ "def", "compile_scss_normal", "Dir", "[", "\"#{@path}.scss\"", "]", ".", "select", "{", "|", "f", "|", "File", ".", "file?", "f", "}", ".", "each", "do", "|", "file", "|", "next", "if", "File", ".", "basename", "(", "file", ")", ".", "chr", "==", "'_'", "scss_file", "=", "File", ".", "open", "(", "file", ",", "'rb'", ")", "{", "|", "f", "|", "f", ".", "read", "}", "output_file", "=", "File", ".", "open", "(", "file", ".", "split", "(", "'.'", ")", ".", "reverse", ".", "drop", "(", "1", ")", ".", "reverse", ".", "join", "(", "'.'", ")", ",", "\"w\"", ")", "output_file", "<<", "Sass", "::", "Engine", ".", "new", "(", "scss_file", ",", "{", "syntax", ":", ":scss", ",", "quiet", ":", "true", ",", "style", ":", ":compressed", "}", ")", ".", "render", "output_file", ".", "close", "end", "end" ]
Turn scss files into css files Skips if the file starts with an underscore @see find_css_files @since 0.1.5
[ "Turn", "scss", "files", "into", "css", "files", "Skips", "if", "the", "file", "starts", "with", "an", "underscore" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/stylestats.rb#L98-L107
train
wearefine/maximus
lib/maximus/statistics/stylestats.rb
Maximus.Stylestats.find_css
def find_css(path = @path) Dir.glob(path).select { |f| File.file? f }.map { |file| file } end
ruby
def find_css(path = @path) Dir.glob(path).select { |f| File.file? f }.map { |file| file } end
[ "def", "find_css", "(", "path", "=", "@path", ")", "Dir", ".", "glob", "(", "path", ")", ".", "select", "{", "|", "f", "|", "File", ".", "file?", "f", "}", ".", "map", "{", "|", "file", "|", "file", "}", "end" ]
Find all css files @param path [String] globbed file path @return [Array] paths to compiled CSS files
[ "Find", "all", "css", "files" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/statistics/stylestats.rb#L128-L130
train
adonespitogo/unsakini
app/controllers/unsakini/posts_controller.rb
Unsakini.PostsController.create
def create @post = Post.new(params.permit(:title, :content, :board_id)) @post.user = @user if (@post.save) render json: @post, status: :created else render json: @post.errors, status: 422 end end
ruby
def create @post = Post.new(params.permit(:title, :content, :board_id)) @post.user = @user if (@post.save) render json: @post, status: :created else render json: @post.errors, status: 422 end end
[ "def", "create", "@post", "=", "Post", ".", "new", "(", "params", ".", "permit", "(", ":title", ",", ":content", ",", ":board_id", ")", ")", "@post", ".", "user", "=", "@user", "if", "(", "@post", ".", "save", ")", "render", "json", ":", "@post", ",", "status", ":", ":created", "else", "render", "json", ":", "@post", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Creates a single post belonging to the board `POST /api/boards/:board_id/posts/`
[ "Creates", "a", "single", "post", "belonging", "to", "the", "board" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/posts_controller.rb#L30-L38
train
adonespitogo/unsakini
app/models/concerns/unsakini/encryptable_model_concern.rb
Unsakini.EncryptableModelConcern.encrypt
def encrypt(value) return value if is_empty_val(value) c = cipher.encrypt c.key = Digest::SHA256.digest(cipher_key) c.iv = iv = c.random_iv Base64.encode64(iv) + Base64.encode64(c.update(value.to_s) + c.final) end
ruby
def encrypt(value) return value if is_empty_val(value) c = cipher.encrypt c.key = Digest::SHA256.digest(cipher_key) c.iv = iv = c.random_iv Base64.encode64(iv) + Base64.encode64(c.update(value.to_s) + c.final) end
[ "def", "encrypt", "(", "value", ")", "return", "value", "if", "is_empty_val", "(", "value", ")", "c", "=", "cipher", ".", "encrypt", "c", ".", "key", "=", "Digest", "::", "SHA256", ".", "digest", "(", "cipher_key", ")", "c", ".", "iv", "=", "iv", "=", "c", ".", "random_iv", "Base64", ".", "encode64", "(", "iv", ")", "+", "Base64", ".", "encode64", "(", "c", ".", "update", "(", "value", ".", "to_s", ")", "+", "c", ".", "final", ")", "end" ]
Encrypts model attribute value
[ "Encrypts", "model", "attribute", "value" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/models/concerns/unsakini/encryptable_model_concern.rb#L79-L85
train
adonespitogo/unsakini
app/models/concerns/unsakini/encryptable_model_concern.rb
Unsakini.EncryptableModelConcern.decrypt
def decrypt(value) return value if is_empty_val(value) c = cipher.decrypt c.key = Digest::SHA256.digest(cipher_key) c.iv = Base64.decode64 value.slice!(0,25) c.update(Base64.decode64(value.to_s)) + c.final end
ruby
def decrypt(value) return value if is_empty_val(value) c = cipher.decrypt c.key = Digest::SHA256.digest(cipher_key) c.iv = Base64.decode64 value.slice!(0,25) c.update(Base64.decode64(value.to_s)) + c.final end
[ "def", "decrypt", "(", "value", ")", "return", "value", "if", "is_empty_val", "(", "value", ")", "c", "=", "cipher", ".", "decrypt", "c", ".", "key", "=", "Digest", "::", "SHA256", ".", "digest", "(", "cipher_key", ")", "c", ".", "iv", "=", "Base64", ".", "decode64", "value", ".", "slice!", "(", "0", ",", "25", ")", "c", ".", "update", "(", "Base64", ".", "decode64", "(", "value", ".", "to_s", ")", ")", "+", "c", ".", "final", "end" ]
Decrypts model attribute value
[ "Decrypts", "model", "attribute", "value" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/models/concerns/unsakini/encryptable_model_concern.rb#L88-L94
train
michaeledgar/ripper-plus
lib/ripper-plus/transformer.rb
RipperPlus.Transformer.transform
def transform(root, opts={}) new_copy = opts[:in_place] ? root : clone_sexp(root) scope_stack = ScopeStack.new transform_tree(new_copy, scope_stack) new_copy end
ruby
def transform(root, opts={}) new_copy = opts[:in_place] ? root : clone_sexp(root) scope_stack = ScopeStack.new transform_tree(new_copy, scope_stack) new_copy end
[ "def", "transform", "(", "root", ",", "opts", "=", "{", "}", ")", "new_copy", "=", "opts", "[", ":in_place", "]", "?", "root", ":", "clone_sexp", "(", "root", ")", "scope_stack", "=", "ScopeStack", ".", "new", "transform_tree", "(", "new_copy", ",", "scope_stack", ")", "new_copy", "end" ]
Transforms the given AST into a RipperPlus AST.
[ "Transforms", "the", "given", "AST", "into", "a", "RipperPlus", "AST", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/transformer.rb#L52-L57
train
michaeledgar/ripper-plus
lib/ripper-plus/transformer.rb
RipperPlus.Transformer.add_variables_from_node
def add_variables_from_node(lhs, scope_stack, allow_duplicates=true) case lhs[0] when :@ident scope_stack.add_variable(lhs[1], allow_duplicates) when :const_path_field, :@const, :top_const_field if scope_stack.in_method? raise DynamicConstantError.new end when Array add_variable_list(lhs, scope_stack, allow_duplicates) when :mlhs_paren, :var_field, :rest_param, :blockarg add_variables_from_node(lhs[1], scope_stack, allow_duplicates) when :mlhs_add_star pre_star, star, post_star = lhs[1..3] add_variable_list(pre_star, scope_stack, allow_duplicates) if star add_variables_from_node(star, scope_stack, allow_duplicates) end add_variable_list(post_star, scope_stack, allow_duplicates) if post_star when :param_error raise InvalidArgumentError.new when :assign_error raise LHSError.new end end
ruby
def add_variables_from_node(lhs, scope_stack, allow_duplicates=true) case lhs[0] when :@ident scope_stack.add_variable(lhs[1], allow_duplicates) when :const_path_field, :@const, :top_const_field if scope_stack.in_method? raise DynamicConstantError.new end when Array add_variable_list(lhs, scope_stack, allow_duplicates) when :mlhs_paren, :var_field, :rest_param, :blockarg add_variables_from_node(lhs[1], scope_stack, allow_duplicates) when :mlhs_add_star pre_star, star, post_star = lhs[1..3] add_variable_list(pre_star, scope_stack, allow_duplicates) if star add_variables_from_node(star, scope_stack, allow_duplicates) end add_variable_list(post_star, scope_stack, allow_duplicates) if post_star when :param_error raise InvalidArgumentError.new when :assign_error raise LHSError.new end end
[ "def", "add_variables_from_node", "(", "lhs", ",", "scope_stack", ",", "allow_duplicates", "=", "true", ")", "case", "lhs", "[", "0", "]", "when", ":@ident", "scope_stack", ".", "add_variable", "(", "lhs", "[", "1", "]", ",", "allow_duplicates", ")", "when", ":const_path_field", ",", ":@const", ",", ":top_const_field", "if", "scope_stack", ".", "in_method?", "raise", "DynamicConstantError", ".", "new", "end", "when", "Array", "add_variable_list", "(", "lhs", ",", "scope_stack", ",", "allow_duplicates", ")", "when", ":mlhs_paren", ",", ":var_field", ",", ":rest_param", ",", ":blockarg", "add_variables_from_node", "(", "lhs", "[", "1", "]", ",", "scope_stack", ",", "allow_duplicates", ")", "when", ":mlhs_add_star", "pre_star", ",", "star", ",", "post_star", "=", "lhs", "[", "1", "..", "3", "]", "add_variable_list", "(", "pre_star", ",", "scope_stack", ",", "allow_duplicates", ")", "if", "star", "add_variables_from_node", "(", "star", ",", "scope_stack", ",", "allow_duplicates", ")", "end", "add_variable_list", "(", "post_star", ",", "scope_stack", ",", "allow_duplicates", ")", "if", "post_star", "when", ":param_error", "raise", "InvalidArgumentError", ".", "new", "when", ":assign_error", "raise", "LHSError", ".", "new", "end", "end" ]
Adds variables to the given scope stack from the given node. Allows nodes from parameter lists, left-hand-sides, block argument lists, and so on.
[ "Adds", "variables", "to", "the", "given", "scope", "stack", "from", "the", "given", "node", ".", "Allows", "nodes", "from", "parameter", "lists", "left", "-", "hand", "-", "sides", "block", "argument", "lists", "and", "so", "on", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/transformer.rb#L210-L234
train
michaeledgar/ripper-plus
lib/ripper-plus/transformer.rb
RipperPlus.Transformer.transform_in_order
def transform_in_order(tree, scope_stack) # some nodes have no type: include the first element in this case range = Symbol === tree[0] ? 1..-1 : 0..-1 tree[range].each do |subtree| # obviously don't transform literals or token locations if Array === subtree && !(Fixnum === subtree[0]) transform_tree(subtree, scope_stack) end end end
ruby
def transform_in_order(tree, scope_stack) # some nodes have no type: include the first element in this case range = Symbol === tree[0] ? 1..-1 : 0..-1 tree[range].each do |subtree| # obviously don't transform literals or token locations if Array === subtree && !(Fixnum === subtree[0]) transform_tree(subtree, scope_stack) end end end
[ "def", "transform_in_order", "(", "tree", ",", "scope_stack", ")", "range", "=", "Symbol", "===", "tree", "[", "0", "]", "?", "1", "..", "-", "1", ":", "0", "..", "-", "1", "tree", "[", "range", "]", ".", "each", "do", "|", "subtree", "|", "if", "Array", "===", "subtree", "&&", "!", "(", "Fixnum", "===", "subtree", "[", "0", "]", ")", "transform_tree", "(", "subtree", ",", "scope_stack", ")", "end", "end", "end" ]
If this node's subtrees are ordered as they are lexically, as most are, transform each subtree in order.
[ "If", "this", "node", "s", "subtrees", "are", "ordered", "as", "they", "are", "lexically", "as", "most", "are", "transform", "each", "subtree", "in", "order", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/transformer.rb#L238-L247
train
michaeledgar/ripper-plus
lib/ripper-plus/transformer.rb
RipperPlus.Transformer.transform_params
def transform_params(param_node, scope_stack) param_node = param_node[1] if param_node[0] == :paren if param_node positional_1, optional, rest, positional_2, block = param_node[1..5] add_variable_list(positional_1, scope_stack, false) if positional_1 if optional optional.each do |var, value| # MUST walk value first. (def foo(y=y); end) == (def foo(y=y()); end) transform_tree(value, scope_stack) add_variables_from_node(var, scope_stack, false) end end if rest && rest[1] add_variables_from_node(rest, scope_stack, false) end add_variable_list(positional_2, scope_stack, false) if positional_2 add_variables_from_node(block, scope_stack, false) if block end end
ruby
def transform_params(param_node, scope_stack) param_node = param_node[1] if param_node[0] == :paren if param_node positional_1, optional, rest, positional_2, block = param_node[1..5] add_variable_list(positional_1, scope_stack, false) if positional_1 if optional optional.each do |var, value| # MUST walk value first. (def foo(y=y); end) == (def foo(y=y()); end) transform_tree(value, scope_stack) add_variables_from_node(var, scope_stack, false) end end if rest && rest[1] add_variables_from_node(rest, scope_stack, false) end add_variable_list(positional_2, scope_stack, false) if positional_2 add_variables_from_node(block, scope_stack, false) if block end end
[ "def", "transform_params", "(", "param_node", ",", "scope_stack", ")", "param_node", "=", "param_node", "[", "1", "]", "if", "param_node", "[", "0", "]", "==", ":paren", "if", "param_node", "positional_1", ",", "optional", ",", "rest", ",", "positional_2", ",", "block", "=", "param_node", "[", "1", "..", "5", "]", "add_variable_list", "(", "positional_1", ",", "scope_stack", ",", "false", ")", "if", "positional_1", "if", "optional", "optional", ".", "each", "do", "|", "var", ",", "value", "|", "transform_tree", "(", "value", ",", "scope_stack", ")", "add_variables_from_node", "(", "var", ",", "scope_stack", ",", "false", ")", "end", "end", "if", "rest", "&&", "rest", "[", "1", "]", "add_variables_from_node", "(", "rest", ",", "scope_stack", ",", "false", ")", "end", "add_variable_list", "(", "positional_2", ",", "scope_stack", ",", "false", ")", "if", "positional_2", "add_variables_from_node", "(", "block", ",", "scope_stack", ",", "false", ")", "if", "block", "end", "end" ]
Transforms a parameter list, and adds the new variables to current scope. Used by both block args and method args.
[ "Transforms", "a", "parameter", "list", "and", "adds", "the", "new", "variables", "to", "current", "scope", ".", "Used", "by", "both", "block", "args", "and", "method", "args", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/transformer.rb#L251-L269
train