repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
godfat/rib
lib/rib/shell.rb
Rib.Shell.loop
def loop before_loop set_trap start in_loop stop self rescue Exception => e Rib.warn("Error while running loop:\n #{format_error(e)}") raise ensure release_trap after_loop end
ruby
def loop before_loop set_trap start in_loop stop self rescue Exception => e Rib.warn("Error while running loop:\n #{format_error(e)}") raise ensure release_trap after_loop end
[ "def", "loop", "before_loop", "set_trap", "start", "in_loop", "stop", "self", "rescue", "Exception", "=>", "e", "Rib", ".", "warn", "(", "\"Error while running loop:\\n #{format_error(e)}\"", ")", "raise", "ensure", "release_trap", "after_loop", "end" ]
Create a new shell. @api public @param config [Hash] The config of the shell. @option config [String] :config ('~/.rib/config.rb') The path to Rib config file. @option config [String] :name ('rib') The name of the shell. Used for Rib application. @option config [String] :result_prompt ('=> ') @option config [String] :prompt ('>> ') @option config [Binding, Object] :binding (new_private_binding) The context of the shell. Could be an Object. @option config [Array<String>] :exit ([nil]) The keywords to exit the shell. `nil` means EOF (ctrl+d). @option config [Fixnum] :line (1) The beginning of line number. @option config [String] :history_file ('~/.rib/config/history.rb') (Only if {Rib::History} plugin is used) The path to history file. @option config [Fixnum] :history_size (500) (Only if {Rib::History} plugin is used) Maximum numbers of history. @option config [Hash<Class, Symbol>] :color (...) (Only if {Rib::Color} plugin is used) Data type colors mapping. @option config [String] :autoindent_spaces (' ') (Only if {Rib::Autoindent} plugin is used) The indented string. Loops shell until user exits
[ "Create", "a", "new", "shell", "." ]
fbbf62ac27751f930b8a606acdd0b12ca9276d33
https://github.com/godfat/rib/blob/fbbf62ac27751f930b8a606acdd0b12ca9276d33/lib/rib/shell.rb#L47-L60
train
godfat/rib
lib/rib/extra/paging.rb
Rib.Paging.one_screen?
def one_screen? str cols, lines = `tput cols`.to_i, `tput lines`.to_i (str.count("\n") + 2) <= lines && # count last line and prompt str.gsub(/\e\[[^m]*m/, '').size <= cols * lines end
ruby
def one_screen? str cols, lines = `tput cols`.to_i, `tput lines`.to_i (str.count("\n") + 2) <= lines && # count last line and prompt str.gsub(/\e\[[^m]*m/, '').size <= cols * lines end
[ "def", "one_screen?", "str", "cols", ",", "lines", "=", "`", "`", ".", "to_i", ",", "`", "`", ".", "to_i", "(", "str", ".", "count", "(", "\"\\n\"", ")", "+", "2", ")", "<=", "lines", "&&", "str", ".", "gsub", "(", "/", "\\e", "\\[", "/", ",", "''", ")", ".", "size", "<=", "cols", "*", "lines", "end" ]
`less -F` can't cat the output, so we need to detect by ourselves. `less -X` would mess up the buffers, so it's not desired, either.
[ "less", "-", "F", "can", "t", "cat", "the", "output", "so", "we", "need", "to", "detect", "by", "ourselves", ".", "less", "-", "X", "would", "mess", "up", "the", "buffers", "so", "it", "s", "not", "desired", "either", "." ]
fbbf62ac27751f930b8a606acdd0b12ca9276d33
https://github.com/godfat/rib/blob/fbbf62ac27751f930b8a606acdd0b12ca9276d33/lib/rib/extra/paging.rb#L22-L26
train
quirkey/vegas
lib/vegas/runner.rb
Vegas.Runner.daemonize!
def daemonize! if JRUBY # It's not a true daemon but when executed with & works like one thread = Thread.new {daemon_execute} thread.join elsif RUBY_VERSION < "1.9" logger.debug "Parent Process: #{Process.pid}" exit!(0) if fork logger.debug "Child Process: #{Process.pid}" daemon_execute else Process.daemon(true, true) daemon_execute end end
ruby
def daemonize! if JRUBY # It's not a true daemon but when executed with & works like one thread = Thread.new {daemon_execute} thread.join elsif RUBY_VERSION < "1.9" logger.debug "Parent Process: #{Process.pid}" exit!(0) if fork logger.debug "Child Process: #{Process.pid}" daemon_execute else Process.daemon(true, true) daemon_execute end end
[ "def", "daemonize!", "if", "JRUBY", "thread", "=", "Thread", ".", "new", "{", "daemon_execute", "}", "thread", ".", "join", "elsif", "RUBY_VERSION", "<", "\"1.9\"", "logger", ".", "debug", "\"Parent Process: #{Process.pid}\"", "exit!", "(", "0", ")", "if", "fork", "logger", ".", "debug", "\"Child Process: #{Process.pid}\"", "daemon_execute", "else", "Process", ".", "daemon", "(", "true", ",", "true", ")", "daemon_execute", "end", "end" ]
Adapted from Rackup
[ "Adapted", "from", "Rackup" ]
2aee90e0be1971115dd2b765540036b39d367dca
https://github.com/quirkey/vegas/blob/2aee90e0be1971115dd2b765540036b39d367dca/lib/vegas/runner.rb#L184-L200
train
quirkey/vegas
lib/vegas/runner.rb
Vegas.Runner.load_config_file
def load_config_file(config_path) abort "Can not find config file at #{config_path}" if !File.readable?(config_path) config = File.read(config_path) # trim off anything after __END__ config.sub!(/^__END__\n.*/, '') @app.module_eval(config) end
ruby
def load_config_file(config_path) abort "Can not find config file at #{config_path}" if !File.readable?(config_path) config = File.read(config_path) # trim off anything after __END__ config.sub!(/^__END__\n.*/, '') @app.module_eval(config) end
[ "def", "load_config_file", "(", "config_path", ")", "abort", "\"Can not find config file at #{config_path}\"", "if", "!", "File", ".", "readable?", "(", "config_path", ")", "config", "=", "File", ".", "read", "(", "config_path", ")", "config", ".", "sub!", "(", "/", "\\n", "/", ",", "''", ")", "@app", ".", "module_eval", "(", "config", ")", "end" ]
Loads a config file at config_path and evals it in the context of the @app.
[ "Loads", "a", "config", "file", "at", "config_path", "and", "evals", "it", "in", "the", "context", "of", "the" ]
2aee90e0be1971115dd2b765540036b39d367dca
https://github.com/quirkey/vegas/blob/2aee90e0be1971115dd2b765540036b39d367dca/lib/vegas/runner.rb#L240-L246
train
evanphx/kpeg
lib/kpeg/code_generator.rb
KPeg.CodeGenerator.output_grammar
def output_grammar(code) code << " # :stopdoc:\n" handle_ast(code) fg = @grammar.foreign_grammars if fg.empty? if @standalone code << " def setup_foreign_grammar; end\n" end else code << " def setup_foreign_grammar\n" @grammar.foreign_grammars.each do |name, gram| code << " @_grammar_#{name} = #{gram}.new(nil)\n" end code << " end\n" end render = GrammarRenderer.new(@grammar) renderings = {} @grammar.rule_order.each do |name| reset_saves rule = @grammar.rules[name] io = StringIO.new render.render_op io, rule.op rend = io.string rend.gsub! "\n", " " renderings[name] = rend code << "\n" code << " # #{name} = #{rend}\n" if rule.arguments code << " def #{method_name name}(#{rule.arguments.join(',')})\n" else code << " def #{method_name name}\n" end if @debug code << " puts \"START #{name} @ \#{show_pos}\\n\"\n" end output_op code, rule.op if @debug code << " if _tmp\n" code << " puts \" OK #{name} @ \#{show_pos}\\n\"\n" code << " else\n" code << " puts \" FAIL #{name} @ \#{show_pos}\\n\"\n" code << " end\n" end code << " set_failed_rule :#{method_name name} unless _tmp\n" code << " return _tmp\n" code << " end\n" end code << "\n Rules = {}\n" @grammar.rule_order.each do |name| rend = GrammarRenderer.escape renderings[name], true code << " Rules[:#{method_name name}] = rule_info(\"#{name}\", \"#{rend}\")\n" end code << " # :startdoc:\n" end
ruby
def output_grammar(code) code << " # :stopdoc:\n" handle_ast(code) fg = @grammar.foreign_grammars if fg.empty? if @standalone code << " def setup_foreign_grammar; end\n" end else code << " def setup_foreign_grammar\n" @grammar.foreign_grammars.each do |name, gram| code << " @_grammar_#{name} = #{gram}.new(nil)\n" end code << " end\n" end render = GrammarRenderer.new(@grammar) renderings = {} @grammar.rule_order.each do |name| reset_saves rule = @grammar.rules[name] io = StringIO.new render.render_op io, rule.op rend = io.string rend.gsub! "\n", " " renderings[name] = rend code << "\n" code << " # #{name} = #{rend}\n" if rule.arguments code << " def #{method_name name}(#{rule.arguments.join(',')})\n" else code << " def #{method_name name}\n" end if @debug code << " puts \"START #{name} @ \#{show_pos}\\n\"\n" end output_op code, rule.op if @debug code << " if _tmp\n" code << " puts \" OK #{name} @ \#{show_pos}\\n\"\n" code << " else\n" code << " puts \" FAIL #{name} @ \#{show_pos}\\n\"\n" code << " end\n" end code << " set_failed_rule :#{method_name name} unless _tmp\n" code << " return _tmp\n" code << " end\n" end code << "\n Rules = {}\n" @grammar.rule_order.each do |name| rend = GrammarRenderer.escape renderings[name], true code << " Rules[:#{method_name name}] = rule_info(\"#{name}\", \"#{rend}\")\n" end code << " # :startdoc:\n" end
[ "def", "output_grammar", "(", "code", ")", "code", "<<", "\" # :stopdoc:\\n\"", "handle_ast", "(", "code", ")", "fg", "=", "@grammar", ".", "foreign_grammars", "if", "fg", ".", "empty?", "if", "@standalone", "code", "<<", "\" def setup_foreign_grammar; end\\n\"", "end", "else", "code", "<<", "\" def setup_foreign_grammar\\n\"", "@grammar", ".", "foreign_grammars", ".", "each", "do", "|", "name", ",", "gram", "|", "code", "<<", "\" @_grammar_#{name} = #{gram}.new(nil)\\n\"", "end", "code", "<<", "\" end\\n\"", "end", "render", "=", "GrammarRenderer", ".", "new", "(", "@grammar", ")", "renderings", "=", "{", "}", "@grammar", ".", "rule_order", ".", "each", "do", "|", "name", "|", "reset_saves", "rule", "=", "@grammar", ".", "rules", "[", "name", "]", "io", "=", "StringIO", ".", "new", "render", ".", "render_op", "io", ",", "rule", ".", "op", "rend", "=", "io", ".", "string", "rend", ".", "gsub!", "\"\\n\"", ",", "\" \"", "renderings", "[", "name", "]", "=", "rend", "code", "<<", "\"\\n\"", "code", "<<", "\" # #{name} = #{rend}\\n\"", "if", "rule", ".", "arguments", "code", "<<", "\" def #{method_name name}(#{rule.arguments.join(',')})\\n\"", "else", "code", "<<", "\" def #{method_name name}\\n\"", "end", "if", "@debug", "code", "<<", "\" puts \\\"START #{name} @ \\#{show_pos}\\\\n\\\"\\n\"", "end", "output_op", "code", ",", "rule", ".", "op", "if", "@debug", "code", "<<", "\" if _tmp\\n\"", "code", "<<", "\" puts \\\" OK #{name} @ \\#{show_pos}\\\\n\\\"\\n\"", "code", "<<", "\" else\\n\"", "code", "<<", "\" puts \\\" FAIL #{name} @ \\#{show_pos}\\\\n\\\"\\n\"", "code", "<<", "\" end\\n\"", "end", "code", "<<", "\" set_failed_rule :#{method_name name} unless _tmp\\n\"", "code", "<<", "\" return _tmp\\n\"", "code", "<<", "\" end\\n\"", "end", "code", "<<", "\"\\n Rules = {}\\n\"", "@grammar", ".", "rule_order", ".", "each", "do", "|", "name", "|", "rend", "=", "GrammarRenderer", ".", "escape", "renderings", "[", "name", "]", ",", "true", "code", "<<", "\" Rules[:#{method_name name}] = rule_info(\\\"#{name}\\\", \\\"#{rend}\\\")\\n\"", "end", "code", "<<", "\" # :startdoc:\\n\"", "end" ]
Output of grammar and rules
[ "Output", "of", "grammar", "and", "rules" ]
7ebf2e58e1248ffcbd0fe2cb552cc3bd12466eb9
https://github.com/evanphx/kpeg/blob/7ebf2e58e1248ffcbd0fe2cb552cc3bd12466eb9/lib/kpeg/code_generator.rb#L361-L429
train
evanphx/kpeg
lib/kpeg/code_generator.rb
KPeg.CodeGenerator.output_header
def output_header(code) if header = @grammar.directives['header'] code << header.action.strip code << "\n" end pre_class = @grammar.directives['pre-class'] if @standalone if pre_class code << pre_class.action.strip code << "\n" end code << "class #{@name}\n" cp = standalone_region("compiled_parser.rb") cpi = standalone_region("compiled_parser.rb", "INITIALIZE") pp = standalone_region("position.rb") cp.gsub!(/^\s*include Position/, pp) code << " # :stopdoc:\n" code << cpi << "\n" unless @grammar.variables['custom_initialize'] code << cp << "\n" code << " # :startdoc:\n" else code << "require 'kpeg/compiled_parser'\n\n" if pre_class code << pre_class.action.strip code << "\n" end code << "class #{@name} < KPeg::CompiledParser\n" end @grammar.setup_actions.each do |act| code << "\n#{act.action}\n\n" end end
ruby
def output_header(code) if header = @grammar.directives['header'] code << header.action.strip code << "\n" end pre_class = @grammar.directives['pre-class'] if @standalone if pre_class code << pre_class.action.strip code << "\n" end code << "class #{@name}\n" cp = standalone_region("compiled_parser.rb") cpi = standalone_region("compiled_parser.rb", "INITIALIZE") pp = standalone_region("position.rb") cp.gsub!(/^\s*include Position/, pp) code << " # :stopdoc:\n" code << cpi << "\n" unless @grammar.variables['custom_initialize'] code << cp << "\n" code << " # :startdoc:\n" else code << "require 'kpeg/compiled_parser'\n\n" if pre_class code << pre_class.action.strip code << "\n" end code << "class #{@name} < KPeg::CompiledParser\n" end @grammar.setup_actions.each do |act| code << "\n#{act.action}\n\n" end end
[ "def", "output_header", "(", "code", ")", "if", "header", "=", "@grammar", ".", "directives", "[", "'header'", "]", "code", "<<", "header", ".", "action", ".", "strip", "code", "<<", "\"\\n\"", "end", "pre_class", "=", "@grammar", ".", "directives", "[", "'pre-class'", "]", "if", "@standalone", "if", "pre_class", "code", "<<", "pre_class", ".", "action", ".", "strip", "code", "<<", "\"\\n\"", "end", "code", "<<", "\"class #{@name}\\n\"", "cp", "=", "standalone_region", "(", "\"compiled_parser.rb\"", ")", "cpi", "=", "standalone_region", "(", "\"compiled_parser.rb\"", ",", "\"INITIALIZE\"", ")", "pp", "=", "standalone_region", "(", "\"position.rb\"", ")", "cp", ".", "gsub!", "(", "/", "\\s", "/", ",", "pp", ")", "code", "<<", "\" # :stopdoc:\\n\"", "code", "<<", "cpi", "<<", "\"\\n\"", "unless", "@grammar", ".", "variables", "[", "'custom_initialize'", "]", "code", "<<", "cp", "<<", "\"\\n\"", "code", "<<", "\" # :startdoc:\\n\"", "else", "code", "<<", "\"require 'kpeg/compiled_parser'\\n\\n\"", "if", "pre_class", "code", "<<", "pre_class", ".", "action", ".", "strip", "code", "<<", "\"\\n\"", "end", "code", "<<", "\"class #{@name} < KPeg::CompiledParser\\n\"", "end", "@grammar", ".", "setup_actions", ".", "each", "do", "|", "act", "|", "code", "<<", "\"\\n#{act.action}\\n\\n\"", "end", "end" ]
Output up to the user-defined setup actions
[ "Output", "up", "to", "the", "user", "-", "defined", "setup", "actions" ]
7ebf2e58e1248ffcbd0fe2cb552cc3bd12466eb9
https://github.com/evanphx/kpeg/blob/7ebf2e58e1248ffcbd0fe2cb552cc3bd12466eb9/lib/kpeg/code_generator.rb#L434-L470
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.create_transaction
def create_transaction(budget_id, data, opts = {}) data, _status_code, _headers = create_transaction_with_http_info(budget_id, data, opts) data end
ruby
def create_transaction(budget_id, data, opts = {}) data, _status_code, _headers = create_transaction_with_http_info(budget_id, data, opts) data end
[ "def", "create_transaction", "(", "budget_id", ",", "data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_transaction_with_http_info", "(", "budget_id", ",", "data", ",", "opts", ")", "data", "end" ]
Create a single transaction or multiple transactions Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' object, a single transaction will be created and if you provide a body containing a 'transactions' array, multiple transactions will be created. @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param data The transaction or transactions to create. To create a single transaction you can specify a value for the &#39;transaction&#39; object and to create multiple transactions you can specify an array of &#39;transactions&#39;. It is expected that you will only provide a value for one of these objects. @param [Hash] opts the optional parameters @return [SaveTransactionsResponse]
[ "Create", "a", "single", "transaction", "or", "multiple", "transactions", "Creates", "a", "single", "transaction", "or", "multiple", "transactions", ".", "If", "you", "provide", "a", "body", "containing", "a", "transaction", "object", "a", "single", "transaction", "will", "be", "created", "and", "if", "you", "provide", "a", "body", "containing", "a", "transactions", "array", "multiple", "transactions", "will", "be", "created", "." ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transaction_by_id
def get_transaction_by_id(budget_id, transaction_id, opts = {}) data, _status_code, _headers = get_transaction_by_id_with_http_info(budget_id, transaction_id, opts) data end
ruby
def get_transaction_by_id(budget_id, transaction_id, opts = {}) data, _status_code, _headers = get_transaction_by_id_with_http_info(budget_id, transaction_id, opts) data end
[ "def", "get_transaction_by_id", "(", "budget_id", ",", "transaction_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_transaction_by_id_with_http_info", "(", "budget_id", ",", "transaction_id", ",", "opts", ")", "data", "end" ]
Single transaction Returns a single transaction @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param transaction_id The id of the transaction @param [Hash] opts the optional parameters @return [TransactionResponse]
[ "Single", "transaction", "Returns", "a", "single", "transaction" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L86-L89
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions
def get_transactions(budget_id, opts = {}) data, _status_code, _headers = get_transactions_with_http_info(budget_id, opts) data end
ruby
def get_transactions(budget_id, opts = {}) data, _status_code, _headers = get_transactions_with_http_info(budget_id, opts) data end
[ "def", "get_transactions", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_transactions_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List transactions Returns budget transactions @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [TransactionsResponse]
[ "List", "transactions", "Returns", "budget", "transactions" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L146-L149
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions_by_account
def get_transactions_by_account(budget_id, account_id, opts = {}) data, _status_code, _headers = get_transactions_by_account_with_http_info(budget_id, account_id, opts) data end
ruby
def get_transactions_by_account(budget_id, account_id, opts = {}) data, _status_code, _headers = get_transactions_by_account_with_http_info(budget_id, account_id, opts) data end
[ "def", "get_transactions_by_account", "(", "budget_id", ",", "account_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_transactions_by_account_with_http_info", "(", "budget_id", ",", "account_id", ",", "opts", ")", "data", "end" ]
List account transactions Returns all transactions for a specified account @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param account_id The id of the account @param [Hash] opts the optional parameters @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [TransactionsResponse]
[ "List", "account", "transactions", "Returns", "all", "transactions", "for", "a", "specified", "account" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L211-L214
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions_by_category
def get_transactions_by_category(budget_id, category_id, opts = {}) data, _status_code, _headers = get_transactions_by_category_with_http_info(budget_id, category_id, opts) data end
ruby
def get_transactions_by_category(budget_id, category_id, opts = {}) data, _status_code, _headers = get_transactions_by_category_with_http_info(budget_id, category_id, opts) data end
[ "def", "get_transactions_by_category", "(", "budget_id", ",", "category_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_transactions_by_category_with_http_info", "(", "budget_id", ",", "category_id", ",", "opts", ")", "data", "end" ]
List category transactions Returns all transactions for a specified category @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param category_id The id of the category @param [Hash] opts the optional parameters @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [HybridTransactionsResponse]
[ "List", "category", "transactions", "Returns", "all", "transactions", "for", "a", "specified", "category" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L281-L284
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions_by_payee
def get_transactions_by_payee(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_transactions_by_payee_with_http_info(budget_id, payee_id, opts) data end
ruby
def get_transactions_by_payee(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_transactions_by_payee_with_http_info(budget_id, payee_id, opts) data end
[ "def", "get_transactions_by_payee", "(", "budget_id", ",", "payee_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_transactions_by_payee_with_http_info", "(", "budget_id", ",", "payee_id", ",", "opts", ")", "data", "end" ]
List payee transactions Returns all transactions for a specified payee @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param payee_id The id of the payee @param [Hash] opts the optional parameters @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date should be ISO formatted (e.g. 2016-12-30). @option opts [String] :type If specified, only transactions of the specified type will be included. &#39;uncategorized&#39; and &#39;unapproved&#39; are currently supported. @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [HybridTransactionsResponse]
[ "List", "payee", "transactions", "Returns", "all", "transactions", "for", "a", "specified", "payee" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L351-L354
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.update_transaction
def update_transaction(budget_id, transaction_id, data, opts = {}) data, _status_code, _headers = update_transaction_with_http_info(budget_id, transaction_id, data, opts) data end
ruby
def update_transaction(budget_id, transaction_id, data, opts = {}) data, _status_code, _headers = update_transaction_with_http_info(budget_id, transaction_id, data, opts) data end
[ "def", "update_transaction", "(", "budget_id", ",", "transaction_id", ",", "data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_transaction_with_http_info", "(", "budget_id", ",", "transaction_id", ",", "data", ",", "opts", ")", "data", "end" ]
Updates an existing transaction Updates a transaction @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param transaction_id The id of the transaction @param data The transaction to update @param [Hash] opts the optional parameters @return [TransactionResponse]
[ "Updates", "an", "existing", "transaction", "Updates", "a", "transaction" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L419-L422
train
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.update_transactions
def update_transactions(budget_id, data, opts = {}) data, _status_code, _headers = update_transactions_with_http_info(budget_id, data, opts) data end
ruby
def update_transactions(budget_id, data, opts = {}) data, _status_code, _headers = update_transactions_with_http_info(budget_id, data, opts) data end
[ "def", "update_transactions", "(", "budget_id", ",", "data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_transactions_with_http_info", "(", "budget_id", ",", "data", ",", "opts", ")", "data", "end" ]
Update multiple transactions Updates multiple transactions, by 'id' or 'import_id'. @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param data The transactions to update. Optionally, transaction &#39;id&#39; value(s) can be specified as null and an &#39;import_id&#39; value can be provided which will allow transaction(s) to updated by their import_id. @param [Hash] opts the optional parameters @return [SaveTransactionsResponse]
[ "Update", "multiple", "transactions", "Updates", "multiple", "transactions", "by", "id", "or", "import_id", "." ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L482-L485
train
ynab/ynab-sdk-ruby
lib/ynab/api/accounts_api.rb
YNAB.AccountsApi.get_account_by_id
def get_account_by_id(budget_id, account_id, opts = {}) data, _status_code, _headers = get_account_by_id_with_http_info(budget_id, account_id, opts) data end
ruby
def get_account_by_id(budget_id, account_id, opts = {}) data, _status_code, _headers = get_account_by_id_with_http_info(budget_id, account_id, opts) data end
[ "def", "get_account_by_id", "(", "budget_id", ",", "account_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_account_by_id_with_http_info", "(", "budget_id", ",", "account_id", ",", "opts", ")", "data", "end" ]
Single account Returns a single account @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param account_id The id of the account @param [Hash] opts the optional parameters @return [AccountResponse]
[ "Single", "account", "Returns", "a", "single", "account" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/accounts_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/accounts_api.rb
YNAB.AccountsApi.get_accounts
def get_accounts(budget_id, opts = {}) data, _status_code, _headers = get_accounts_with_http_info(budget_id, opts) data end
ruby
def get_accounts(budget_id, opts = {}) data, _status_code, _headers = get_accounts_with_http_info(budget_id, opts) data end
[ "def", "get_accounts", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_accounts_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
Account list Returns all accounts @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [AccountsResponse]
[ "Account", "list", "Returns", "all", "accounts" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/accounts_api.rb#L86-L89
train
ynab/ynab-sdk-ruby
lib/ynab/api/months_api.rb
YNAB.MonthsApi.get_budget_month
def get_budget_month(budget_id, month, opts = {}) data, _status_code, _headers = get_budget_month_with_http_info(budget_id, month, opts) data end
ruby
def get_budget_month(budget_id, month, opts = {}) data, _status_code, _headers = get_budget_month_with_http_info(budget_id, month, opts) data end
[ "def", "get_budget_month", "(", "budget_id", ",", "month", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_budget_month_with_http_info", "(", "budget_id", ",", "month", ",", "opts", ")", "data", "end" ]
Single budget month Returns a single budget month @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param month The budget month in ISO format (e.g. 2016-12-01) (\&quot;current\&quot; can also be used to specify the current calendar month (UTC)) @param [Hash] opts the optional parameters @return [MonthDetailResponse]
[ "Single", "budget", "month", "Returns", "a", "single", "budget", "month" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/months_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/months_api.rb
YNAB.MonthsApi.get_budget_months
def get_budget_months(budget_id, opts = {}) data, _status_code, _headers = get_budget_months_with_http_info(budget_id, opts) data end
ruby
def get_budget_months(budget_id, opts = {}) data, _status_code, _headers = get_budget_months_with_http_info(budget_id, opts) data end
[ "def", "get_budget_months", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_budget_months_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List budget months Returns all budget months @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [MonthSummariesResponse]
[ "List", "budget", "months", "Returns", "all", "budget", "months" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/months_api.rb#L86-L89
train
pioz/chess
lib/chess/pgn.rb
Chess.Pgn.to_s
def to_s s = '' TAGS.each do |t| tag = instance_variable_get("@#{t}") s << "[#{t.capitalize} \"#{tag}\"]\n" end s << "\n" m = '' @moves.each_with_index do |move, i| m << "#{i/2+1}. " if i % 2 == 0 m << "#{move} " end m << @result unless @result.nil? s << m.gsub(/(.{1,78})(?: +|$)\n?|(.{78})/, "\\1\\2\n") end
ruby
def to_s s = '' TAGS.each do |t| tag = instance_variable_get("@#{t}") s << "[#{t.capitalize} \"#{tag}\"]\n" end s << "\n" m = '' @moves.each_with_index do |move, i| m << "#{i/2+1}. " if i % 2 == 0 m << "#{move} " end m << @result unless @result.nil? s << m.gsub(/(.{1,78})(?: +|$)\n?|(.{78})/, "\\1\\2\n") end
[ "def", "to_s", "s", "=", "''", "TAGS", ".", "each", "do", "|", "t", "|", "tag", "=", "instance_variable_get", "(", "\"@#{t}\"", ")", "s", "<<", "\"[#{t.capitalize} \\\"#{tag}\\\"]\\n\"", "end", "s", "<<", "\"\\n\"", "m", "=", "''", "@moves", ".", "each_with_index", "do", "|", "move", ",", "i", "|", "m", "<<", "\"#{i/2+1}. \"", "if", "i", "%", "2", "==", "0", "m", "<<", "\"#{move} \"", "end", "m", "<<", "@result", "unless", "@result", ".", "nil?", "s", "<<", "m", ".", "gsub", "(", "/", "\\n", "/", ",", "\"\\\\1\\\\2\\n\"", ")", "end" ]
PGN to string.
[ "PGN", "to", "string", "." ]
80744d1f351d45ecece8058e208c0f381a0569f5
https://github.com/pioz/chess/blob/80744d1f351d45ecece8058e208c0f381a0569f5/lib/chess/pgn.rb#L76-L90
train
pioz/chess
lib/chess/game.rb
Chess.Game.pgn
def pgn pgn = Chess::Pgn.new pgn.moves = self.moves pgn.result = self.result return pgn end
ruby
def pgn pgn = Chess::Pgn.new pgn.moves = self.moves pgn.result = self.result return pgn end
[ "def", "pgn", "pgn", "=", "Chess", "::", "Pgn", ".", "new", "pgn", ".", "moves", "=", "self", ".", "moves", "pgn", ".", "result", "=", "self", ".", "result", "return", "pgn", "end" ]
Returns the PGN rappresenting the game. @return [String]
[ "Returns", "the", "PGN", "rappresenting", "the", "game", "." ]
80744d1f351d45ecece8058e208c0f381a0569f5
https://github.com/pioz/chess/blob/80744d1f351d45ecece8058e208c0f381a0569f5/lib/chess/game.rb#L154-L159
train
ynab/ynab-sdk-ruby
lib/ynab/api/payee_locations_api.rb
YNAB.PayeeLocationsApi.get_payee_location_by_id
def get_payee_location_by_id(budget_id, payee_location_id, opts = {}) data, _status_code, _headers = get_payee_location_by_id_with_http_info(budget_id, payee_location_id, opts) data end
ruby
def get_payee_location_by_id(budget_id, payee_location_id, opts = {}) data, _status_code, _headers = get_payee_location_by_id_with_http_info(budget_id, payee_location_id, opts) data end
[ "def", "get_payee_location_by_id", "(", "budget_id", ",", "payee_location_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payee_location_by_id_with_http_info", "(", "budget_id", ",", "payee_location_id", ",", "opts", ")", "data", "end" ]
Single payee location Returns a single payee location @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param payee_location_id id of payee location @param [Hash] opts the optional parameters @return [PayeeLocationResponse]
[ "Single", "payee", "location", "Returns", "a", "single", "payee", "location" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payee_locations_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/payee_locations_api.rb
YNAB.PayeeLocationsApi.get_payee_locations
def get_payee_locations(budget_id, opts = {}) data, _status_code, _headers = get_payee_locations_with_http_info(budget_id, opts) data end
ruby
def get_payee_locations(budget_id, opts = {}) data, _status_code, _headers = get_payee_locations_with_http_info(budget_id, opts) data end
[ "def", "get_payee_locations", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payee_locations_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List payee locations Returns all payee locations @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @return [PayeeLocationsResponse]
[ "List", "payee", "locations", "Returns", "all", "payee", "locations" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payee_locations_api.rb#L85-L88
train
ynab/ynab-sdk-ruby
lib/ynab/api/payee_locations_api.rb
YNAB.PayeeLocationsApi.get_payee_locations_by_payee
def get_payee_locations_by_payee(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_payee_locations_by_payee_with_http_info(budget_id, payee_id, opts) data end
ruby
def get_payee_locations_by_payee(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_payee_locations_by_payee_with_http_info(budget_id, payee_id, opts) data end
[ "def", "get_payee_locations_by_payee", "(", "budget_id", ",", "payee_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payee_locations_by_payee_with_http_info", "(", "budget_id", ",", "payee_id", ",", "opts", ")", "data", "end" ]
List locations for a payee Returns all payee locations for the specified payee @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param payee_id id of payee @param [Hash] opts the optional parameters @return [PayeeLocationsResponse]
[ "List", "locations", "for", "a", "payee", "Returns", "all", "payee", "locations", "for", "the", "specified", "payee" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payee_locations_api.rb#L138-L141
train
ynab/ynab-sdk-ruby
lib/ynab/api/categories_api.rb
YNAB.CategoriesApi.update_month_category
def update_month_category(budget_id, month, category_id, data, opts = {}) data, _status_code, _headers = update_month_category_with_http_info(budget_id, month, category_id, data, opts) data end
ruby
def update_month_category(budget_id, month, category_id, data, opts = {}) data, _status_code, _headers = update_month_category_with_http_info(budget_id, month, category_id, data, opts) data end
[ "def", "update_month_category", "(", "budget_id", ",", "month", ",", "category_id", ",", "data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_month_category_with_http_info", "(", "budget_id", ",", "month", ",", "category_id", ",", "data", ",", "opts", ")", "data", "end" ]
Update a category for a specific month Update a category for a specific month @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param month The budget month in ISO format (e.g. 2016-12-01) (\&quot;current\&quot; can also be used to specify the current calendar month (UTC)) @param category_id The id of the category @param data The category to update @param [Hash] opts the optional parameters @return [CategoryResponse]
[ "Update", "a", "category", "for", "a", "specific", "month", "Update", "a", "category", "for", "a", "specific", "month" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/categories_api.rb#L207-L210
train
ynab/ynab-sdk-ruby
lib/ynab/api/budgets_api.rb
YNAB.BudgetsApi.get_budget_by_id
def get_budget_by_id(budget_id, opts = {}) data, _status_code, _headers = get_budget_by_id_with_http_info(budget_id, opts) data end
ruby
def get_budget_by_id(budget_id, opts = {}) data, _status_code, _headers = get_budget_by_id_with_http_info(budget_id, opts) data end
[ "def", "get_budget_by_id", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_budget_by_id_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
Single budget Returns a single budget with all related entities. This resource is effectively a full budget export. @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [BudgetDetailResponse]
[ "Single", "budget", "Returns", "a", "single", "budget", "with", "all", "related", "entities", ".", "This", "resource", "is", "effectively", "a", "full", "budget", "export", "." ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/budgets_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/budgets_api.rb
YNAB.BudgetsApi.get_budget_settings_by_id
def get_budget_settings_by_id(budget_id, opts = {}) data, _status_code, _headers = get_budget_settings_by_id_with_http_info(budget_id, opts) data end
ruby
def get_budget_settings_by_id(budget_id, opts = {}) data, _status_code, _headers = get_budget_settings_by_id_with_http_info(budget_id, opts) data end
[ "def", "get_budget_settings_by_id", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_budget_settings_by_id_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
Budget Settings Returns settings for a budget @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @return [BudgetSettingsResponse]
[ "Budget", "Settings", "Returns", "settings", "for", "a", "budget" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/budgets_api.rb#L82-L85
train
ynab/ynab-sdk-ruby
lib/ynab/api/scheduled_transactions_api.rb
YNAB.ScheduledTransactionsApi.get_scheduled_transaction_by_id
def get_scheduled_transaction_by_id(budget_id, scheduled_transaction_id, opts = {}) data, _status_code, _headers = get_scheduled_transaction_by_id_with_http_info(budget_id, scheduled_transaction_id, opts) data end
ruby
def get_scheduled_transaction_by_id(budget_id, scheduled_transaction_id, opts = {}) data, _status_code, _headers = get_scheduled_transaction_by_id_with_http_info(budget_id, scheduled_transaction_id, opts) data end
[ "def", "get_scheduled_transaction_by_id", "(", "budget_id", ",", "scheduled_transaction_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_scheduled_transaction_by_id_with_http_info", "(", "budget_id", ",", "scheduled_transaction_id", ",", "opts", ")", "data", "end" ]
Single scheduled transaction Returns a single scheduled transaction @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param scheduled_transaction_id The id of the scheduled transaction @param [Hash] opts the optional parameters @return [ScheduledTransactionResponse]
[ "Single", "scheduled", "transaction", "Returns", "a", "single", "scheduled", "transaction" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/scheduled_transactions_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/scheduled_transactions_api.rb
YNAB.ScheduledTransactionsApi.get_scheduled_transactions
def get_scheduled_transactions(budget_id, opts = {}) data, _status_code, _headers = get_scheduled_transactions_with_http_info(budget_id, opts) data end
ruby
def get_scheduled_transactions(budget_id, opts = {}) data, _status_code, _headers = get_scheduled_transactions_with_http_info(budget_id, opts) data end
[ "def", "get_scheduled_transactions", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_scheduled_transactions_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List scheduled transactions Returns all scheduled transactions @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @return [ScheduledTransactionsResponse]
[ "List", "scheduled", "transactions", "Returns", "all", "scheduled", "transactions" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/scheduled_transactions_api.rb#L85-L88
train
pioz/chess
lib/chess/gnuchess.rb
Chess.Gnuchess.gnuchess_move
def gnuchess_move pipe = IO.popen('gnuchess -x', 'r+') begin pipe.puts('depth 1') pipe.puts('manual') self.coord_moves.each do |m| pipe.puts(m) end pipe.puts('go') while line = pipe.gets raise IllegalMoveError if line.include?('Invalid move') match = line.match(/My move is : ([a-h][1-8][a-h][1-8][rkbq]?)/) return match[1] if match end ensure pipe.puts('quit') pipe.close end return moves end
ruby
def gnuchess_move pipe = IO.popen('gnuchess -x', 'r+') begin pipe.puts('depth 1') pipe.puts('manual') self.coord_moves.each do |m| pipe.puts(m) end pipe.puts('go') while line = pipe.gets raise IllegalMoveError if line.include?('Invalid move') match = line.match(/My move is : ([a-h][1-8][a-h][1-8][rkbq]?)/) return match[1] if match end ensure pipe.puts('quit') pipe.close end return moves end
[ "def", "gnuchess_move", "pipe", "=", "IO", ".", "popen", "(", "'gnuchess -x'", ",", "'r+'", ")", "begin", "pipe", ".", "puts", "(", "'depth 1'", ")", "pipe", ".", "puts", "(", "'manual'", ")", "self", ".", "coord_moves", ".", "each", "do", "|", "m", "|", "pipe", ".", "puts", "(", "m", ")", "end", "pipe", ".", "puts", "(", "'go'", ")", "while", "line", "=", "pipe", ".", "gets", "raise", "IllegalMoveError", "if", "line", ".", "include?", "(", "'Invalid move'", ")", "match", "=", "line", ".", "match", "(", "/", "/", ")", "return", "match", "[", "1", "]", "if", "match", "end", "ensure", "pipe", ".", "puts", "(", "'quit'", ")", "pipe", ".", "close", "end", "return", "moves", "end" ]
Returns the next move calculated by Gnuchess. @return [String] Returns the short algebraic chess notation of the move.
[ "Returns", "the", "next", "move", "calculated", "by", "Gnuchess", "." ]
80744d1f351d45ecece8058e208c0f381a0569f5
https://github.com/pioz/chess/blob/80744d1f351d45ecece8058e208c0f381a0569f5/lib/chess/gnuchess.rb#L18-L37
train
ynab/ynab-sdk-ruby
lib/ynab/api/payees_api.rb
YNAB.PayeesApi.get_payee_by_id
def get_payee_by_id(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_payee_by_id_with_http_info(budget_id, payee_id, opts) data end
ruby
def get_payee_by_id(budget_id, payee_id, opts = {}) data, _status_code, _headers = get_payee_by_id_with_http_info(budget_id, payee_id, opts) data end
[ "def", "get_payee_by_id", "(", "budget_id", ",", "payee_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payee_by_id_with_http_info", "(", "budget_id", ",", "payee_id", ",", "opts", ")", "data", "end" ]
Single payee Returns single payee @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param payee_id The id of the payee @param [Hash] opts the optional parameters @return [PayeeResponse]
[ "Single", "payee", "Returns", "single", "payee" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payees_api.rb#L28-L31
train
ynab/ynab-sdk-ruby
lib/ynab/api/payees_api.rb
YNAB.PayeesApi.get_payees
def get_payees(budget_id, opts = {}) data, _status_code, _headers = get_payees_with_http_info(budget_id, opts) data end
ruby
def get_payees(budget_id, opts = {}) data, _status_code, _headers = get_payees_with_http_info(budget_id, opts) data end
[ "def", "get_payees", "(", "budget_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_payees_with_http_info", "(", "budget_id", ",", "opts", ")", "data", "end" ]
List payees Returns all payees @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Integer] :last_knowledge_of_server The starting server knowledge. If provided, only entities that have changed since last_knowledge_of_server will be included. @return [PayeesResponse]
[ "List", "payees", "Returns", "all", "payees" ]
389a959e482b6fa9643c7e7bfb55d8640cc952fd
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/payees_api.rb#L86-L89
train
r7kamura/jdoc
lib/jdoc/resource.rb
Jdoc.Resource.links
def links @links ||= @schema.links.map do |link| if link.method && link.href Link.new(link) end end.compact end
ruby
def links @links ||= @schema.links.map do |link| if link.method && link.href Link.new(link) end end.compact end
[ "def", "links", "@links", "||=", "@schema", ".", "links", ".", "map", "do", "|", "link", "|", "if", "link", ".", "method", "&&", "link", ".", "href", "Link", ".", "new", "(", "link", ")", "end", "end", ".", "compact", "end" ]
Defined to change uniqueness in Hash key Defined to change uniqueness in Hash key
[ "Defined", "to", "change", "uniqueness", "in", "Hash", "key", "Defined", "to", "change", "uniqueness", "in", "Hash", "key" ]
42fb0d063313bf6b8eae39ddd8bc1e55381d2890
https://github.com/r7kamura/jdoc/blob/42fb0d063313bf6b8eae39ddd8bc1e55381d2890/lib/jdoc/resource.rb#L59-L65
train
propublica/daybreak
lib/daybreak/db.rb
Daybreak.DB.hash_default
def hash_default(_, key) if @default != nil value = @default.respond_to?(:call) ? @default.call(key) : @default @journal << [key, value] @table[key] = value end end
ruby
def hash_default(_, key) if @default != nil value = @default.respond_to?(:call) ? @default.call(key) : @default @journal << [key, value] @table[key] = value end end
[ "def", "hash_default", "(", "_", ",", "key", ")", "if", "@default", "!=", "nil", "value", "=", "@default", ".", "respond_to?", "(", ":call", ")", "?", "@default", ".", "call", "(", "key", ")", ":", "@default", "@journal", "<<", "[", "key", ",", "value", "]", "@table", "[", "key", "]", "=", "value", "end", "end" ]
The block used in @table for new records
[ "The", "block", "used", "in" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/db.rb#L274-L280
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.clear
def clear flush with_tmpfile do |path, file| file.write(@format.header) file.close # Clear replaces the database file like a compactification does with_flock(File::LOCK_EX) do File.rename(path, @file) end end open end
ruby
def clear flush with_tmpfile do |path, file| file.write(@format.header) file.close # Clear replaces the database file like a compactification does with_flock(File::LOCK_EX) do File.rename(path, @file) end end open end
[ "def", "clear", "flush", "with_tmpfile", "do", "|", "path", ",", "file", "|", "file", ".", "write", "(", "@format", ".", "header", ")", "file", ".", "close", "with_flock", "(", "File", "::", "LOCK_EX", ")", "do", "File", ".", "rename", "(", "path", ",", "@file", ")", "end", "end", "open", "end" ]
Clear the database log and yield
[ "Clear", "the", "database", "log", "and", "yield" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L51-L62
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.compact
def compact load with_tmpfile do |path, file| # Compactified database has the same size -> return return self if @pos == file.write(dump(yield, @format.header)) with_flock(File::LOCK_EX) do # Database was replaced (cleared or compactified) in the meantime if @pos != nil # Append changed journal records if the database changed during compactification file.write(read) file.close File.rename(path, @file) end end end open replay end
ruby
def compact load with_tmpfile do |path, file| # Compactified database has the same size -> return return self if @pos == file.write(dump(yield, @format.header)) with_flock(File::LOCK_EX) do # Database was replaced (cleared or compactified) in the meantime if @pos != nil # Append changed journal records if the database changed during compactification file.write(read) file.close File.rename(path, @file) end end end open replay end
[ "def", "compact", "load", "with_tmpfile", "do", "|", "path", ",", "file", "|", "return", "self", "if", "@pos", "==", "file", ".", "write", "(", "dump", "(", "yield", ",", "@format", ".", "header", ")", ")", "with_flock", "(", "File", "::", "LOCK_EX", ")", "do", "if", "@pos", "!=", "nil", "file", ".", "write", "(", "read", ")", "file", ".", "close", "File", ".", "rename", "(", "path", ",", "@file", ")", "end", "end", "end", "open", "replay", "end" ]
Compact the logfile to represent the in-memory state
[ "Compact", "the", "logfile", "to", "represent", "the", "in", "-", "memory", "state" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L65-L82
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.open
def open @fd.close if @fd @fd = File.open(@file, 'ab+') @fd.advise(:sequential) if @fd.respond_to? :advise stat = @fd.stat @inode = stat.ino write(@format.header) if stat.size == 0 @pos = nil end
ruby
def open @fd.close if @fd @fd = File.open(@file, 'ab+') @fd.advise(:sequential) if @fd.respond_to? :advise stat = @fd.stat @inode = stat.ino write(@format.header) if stat.size == 0 @pos = nil end
[ "def", "open", "@fd", ".", "close", "if", "@fd", "@fd", "=", "File", ".", "open", "(", "@file", ",", "'ab+'", ")", "@fd", ".", "advise", "(", ":sequential", ")", "if", "@fd", ".", "respond_to?", ":advise", "stat", "=", "@fd", ".", "stat", "@inode", "=", "stat", ".", "ino", "write", "(", "@format", ".", "header", ")", "if", "stat", ".", "size", "==", "0", "@pos", "=", "nil", "end" ]
Open or reopen file
[ "Open", "or", "reopen", "file" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L98-L106
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.read
def read with_flock(File::LOCK_SH) do # File was opened unless @pos @fd.pos = 0 @format.read_header(@fd) @size = 0 @emit.call(nil) else @fd.pos = @pos end buf = @fd.read @pos = @fd.pos buf end end
ruby
def read with_flock(File::LOCK_SH) do # File was opened unless @pos @fd.pos = 0 @format.read_header(@fd) @size = 0 @emit.call(nil) else @fd.pos = @pos end buf = @fd.read @pos = @fd.pos buf end end
[ "def", "read", "with_flock", "(", "File", "::", "LOCK_SH", ")", "do", "unless", "@pos", "@fd", ".", "pos", "=", "0", "@format", ".", "read_header", "(", "@fd", ")", "@size", "=", "0", "@emit", ".", "call", "(", "nil", ")", "else", "@fd", ".", "pos", "=", "@pos", "end", "buf", "=", "@fd", ".", "read", "@pos", "=", "@fd", ".", "pos", "buf", "end", "end" ]
Read new file content
[ "Read", "new", "file", "content" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L109-L124
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.dump
def dump(records, dump = '') # each is faster than inject records.each do |record| record[1] = @serializer.dump(record.last) dump << @format.dump(record) end dump end
ruby
def dump(records, dump = '') # each is faster than inject records.each do |record| record[1] = @serializer.dump(record.last) dump << @format.dump(record) end dump end
[ "def", "dump", "(", "records", ",", "dump", "=", "''", ")", "records", ".", "each", "do", "|", "record", "|", "record", "[", "1", "]", "=", "@serializer", ".", "dump", "(", "record", ".", "last", ")", "dump", "<<", "@format", ".", "dump", "(", "record", ")", "end", "dump", "end" ]
Return database dump as string
[ "Return", "database", "dump", "as", "string" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L127-L134
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.write
def write(dump) with_flock(File::LOCK_EX) do @fd.write(dump) # Flush to make sure the file is really updated @fd.flush end @pos = @fd.pos if @pos && @fd.pos == @pos + dump.bytesize end
ruby
def write(dump) with_flock(File::LOCK_EX) do @fd.write(dump) # Flush to make sure the file is really updated @fd.flush end @pos = @fd.pos if @pos && @fd.pos == @pos + dump.bytesize end
[ "def", "write", "(", "dump", ")", "with_flock", "(", "File", "::", "LOCK_EX", ")", "do", "@fd", ".", "write", "(", "dump", ")", "@fd", ".", "flush", "end", "@pos", "=", "@fd", ".", "pos", "if", "@pos", "&&", "@fd", ".", "pos", "==", "@pos", "+", "dump", ".", "bytesize", "end" ]
Write data to output stream and advance @pos
[ "Write", "data", "to", "output", "stream", "and", "advance" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L164-L171
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.with_flock
def with_flock(mode) return yield if @locked begin loop do # HACK: JRuby returns false if the process is already hold by the same process # see https://github.com/jruby/jruby/issues/496 Thread.pass until @fd.flock(mode) # Check if database was replaced (cleared or compactified) in the meantime # break if not stat = @fd.stat break if stat.nlink > 0 && stat.ino == @inode open end @locked = true yield ensure @fd.flock(File::LOCK_UN) @locked = false end end
ruby
def with_flock(mode) return yield if @locked begin loop do # HACK: JRuby returns false if the process is already hold by the same process # see https://github.com/jruby/jruby/issues/496 Thread.pass until @fd.flock(mode) # Check if database was replaced (cleared or compactified) in the meantime # break if not stat = @fd.stat break if stat.nlink > 0 && stat.ino == @inode open end @locked = true yield ensure @fd.flock(File::LOCK_UN) @locked = false end end
[ "def", "with_flock", "(", "mode", ")", "return", "yield", "if", "@locked", "begin", "loop", "do", "Thread", ".", "pass", "until", "@fd", ".", "flock", "(", "mode", ")", "stat", "=", "@fd", ".", "stat", "break", "if", "stat", ".", "nlink", ">", "0", "&&", "stat", ".", "ino", "==", "@inode", "open", "end", "@locked", "=", "true", "yield", "ensure", "@fd", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "@locked", "=", "false", "end", "end" ]
Block with file lock
[ "Block", "with", "file", "lock" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L174-L193
train
propublica/daybreak
lib/daybreak/journal.rb
Daybreak.Journal.with_tmpfile
def with_tmpfile path = [@file, $$.to_s(36), Thread.current.object_id.to_s(36)].join file = File.open(path, 'wb') yield(path, file) ensure file.close unless file.closed? File.unlink(path) if File.exists?(path) end
ruby
def with_tmpfile path = [@file, $$.to_s(36), Thread.current.object_id.to_s(36)].join file = File.open(path, 'wb') yield(path, file) ensure file.close unless file.closed? File.unlink(path) if File.exists?(path) end
[ "def", "with_tmpfile", "path", "=", "[", "@file", ",", "$$", ".", "to_s", "(", "36", ")", ",", "Thread", ".", "current", ".", "object_id", ".", "to_s", "(", "36", ")", "]", ".", "join", "file", "=", "File", ".", "open", "(", "path", ",", "'wb'", ")", "yield", "(", "path", ",", "file", ")", "ensure", "file", ".", "close", "unless", "file", ".", "closed?", "File", ".", "unlink", "(", "path", ")", "if", "File", ".", "exists?", "(", "path", ")", "end" ]
Open temporary file and pass it to the block
[ "Open", "temporary", "file", "and", "pass", "it", "to", "the", "block" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/journal.rb#L196-L203
train
propublica/daybreak
lib/daybreak/format.rb
Daybreak.Format.read_header
def read_header(input) raise 'Not a Daybreak database' if input.read(MAGIC.bytesize) != MAGIC ver = input.read(2).unpack('n').first raise "Expected database version #{VERSION}, got #{ver}" if ver != VERSION end
ruby
def read_header(input) raise 'Not a Daybreak database' if input.read(MAGIC.bytesize) != MAGIC ver = input.read(2).unpack('n').first raise "Expected database version #{VERSION}, got #{ver}" if ver != VERSION end
[ "def", "read_header", "(", "input", ")", "raise", "'Not a Daybreak database'", "if", "input", ".", "read", "(", "MAGIC", ".", "bytesize", ")", "!=", "MAGIC", "ver", "=", "input", ".", "read", "(", "2", ")", ".", "unpack", "(", "'n'", ")", ".", "first", "raise", "\"Expected database version #{VERSION}, got #{ver}\"", "if", "ver", "!=", "VERSION", "end" ]
Read database header from input stream @param [#read] input the input stream @return void
[ "Read", "database", "header", "from", "input", "stream" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/format.rb#L10-L14
train
propublica/daybreak
lib/daybreak/format.rb
Daybreak.Format.dump
def dump(record) data = if record.size == 1 [record[0].bytesize, DELETE].pack('NN') << record[0] else [record[0].bytesize, record[1].bytesize].pack('NN') << record[0] << record[1] end data << crc32(data) end
ruby
def dump(record) data = if record.size == 1 [record[0].bytesize, DELETE].pack('NN') << record[0] else [record[0].bytesize, record[1].bytesize].pack('NN') << record[0] << record[1] end data << crc32(data) end
[ "def", "dump", "(", "record", ")", "data", "=", "if", "record", ".", "size", "==", "1", "[", "record", "[", "0", "]", ".", "bytesize", ",", "DELETE", "]", ".", "pack", "(", "'NN'", ")", "<<", "record", "[", "0", "]", "else", "[", "record", "[", "0", "]", ".", "bytesize", ",", "record", "[", "1", "]", ".", "bytesize", "]", ".", "pack", "(", "'NN'", ")", "<<", "record", "[", "0", "]", "<<", "record", "[", "1", "]", "end", "data", "<<", "crc32", "(", "data", ")", "end" ]
Serialize record and return string @param [Array] record an array with [key, value] or [key] if the record is deleted @return [String] serialized record
[ "Serialize", "record", "and", "return", "string" ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/format.rb#L25-L33
train
propublica/daybreak
lib/daybreak/format.rb
Daybreak.Format.parse
def parse(buf) n, count = 0, 0 while n < buf.size key_size, value_size = buf[n, 8].unpack('NN') data_size = key_size + 8 data_size += value_size if value_size != DELETE data = buf[n, data_size] n += data_size raise 'CRC mismatch: your data might be corrupted!' unless buf[n, 4] == crc32(data) n += 4 yield(value_size == DELETE ? [data[8, key_size]] : [data[8, key_size], data[8 + key_size, value_size]]) count += 1 end count end
ruby
def parse(buf) n, count = 0, 0 while n < buf.size key_size, value_size = buf[n, 8].unpack('NN') data_size = key_size + 8 data_size += value_size if value_size != DELETE data = buf[n, data_size] n += data_size raise 'CRC mismatch: your data might be corrupted!' unless buf[n, 4] == crc32(data) n += 4 yield(value_size == DELETE ? [data[8, key_size]] : [data[8, key_size], data[8 + key_size, value_size]]) count += 1 end count end
[ "def", "parse", "(", "buf", ")", "n", ",", "count", "=", "0", ",", "0", "while", "n", "<", "buf", ".", "size", "key_size", ",", "value_size", "=", "buf", "[", "n", ",", "8", "]", ".", "unpack", "(", "'NN'", ")", "data_size", "=", "key_size", "+", "8", "data_size", "+=", "value_size", "if", "value_size", "!=", "DELETE", "data", "=", "buf", "[", "n", ",", "data_size", "]", "n", "+=", "data_size", "raise", "'CRC mismatch: your data might be corrupted!'", "unless", "buf", "[", "n", ",", "4", "]", "==", "crc32", "(", "data", ")", "n", "+=", "4", "yield", "(", "value_size", "==", "DELETE", "?", "[", "data", "[", "8", ",", "key_size", "]", "]", ":", "[", "data", "[", "8", ",", "key_size", "]", ",", "data", "[", "8", "+", "key_size", ",", "value_size", "]", "]", ")", "count", "+=", "1", "end", "count", "end" ]
Deserialize records from buffer, and yield them. @param [String] buf the buffer to read from @yield [Array] blk deserialized record [key, value] or [key] if the record is deleted @return [Fixnum] number of records
[ "Deserialize", "records", "from", "buffer", "and", "yield", "them", "." ]
b963a911fb68c294f02d0502570915cfb6b8a58d
https://github.com/propublica/daybreak/blob/b963a911fb68c294f02d0502570915cfb6b8a58d/lib/daybreak/format.rb#L39-L53
train
ronin-ruby/ronin
lib/ronin/url.rb
Ronin.URL.query_string
def query_string params = {} self.query_params.each do |param| params[param.name] = param.value end return ::URI::QueryParams.dump(params) end
ruby
def query_string params = {} self.query_params.each do |param| params[param.name] = param.value end return ::URI::QueryParams.dump(params) end
[ "def", "query_string", "params", "=", "{", "}", "self", ".", "query_params", ".", "each", "do", "|", "param", "|", "params", "[", "param", ".", "name", "]", "=", "param", ".", "value", "end", "return", "::", "URI", "::", "QueryParams", ".", "dump", "(", "params", ")", "end" ]
Dumps the URL query params into a URI query string. @return [String] The URI query string. @since 1.0.0 @api public
[ "Dumps", "the", "URL", "query", "params", "into", "a", "URI", "query", "string", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/url.rb#L418-L426
train
ronin-ruby/ronin
lib/ronin/url.rb
Ronin.URL.query_string=
def query_string=(query) self.query_params.clear ::URI::QueryParams.parse(query).each do |name,value| self.query_params.new( :name => URLQueryParamName.first_or_new(:name => name), :value => value ) end return query end
ruby
def query_string=(query) self.query_params.clear ::URI::QueryParams.parse(query).each do |name,value| self.query_params.new( :name => URLQueryParamName.first_or_new(:name => name), :value => value ) end return query end
[ "def", "query_string", "=", "(", "query", ")", "self", ".", "query_params", ".", "clear", "::", "URI", "::", "QueryParams", ".", "parse", "(", "query", ")", ".", "each", "do", "|", "name", ",", "value", "|", "self", ".", "query_params", ".", "new", "(", ":name", "=>", "URLQueryParamName", ".", "first_or_new", "(", ":name", "=>", "name", ")", ",", ":value", "=>", "value", ")", "end", "return", "query", "end" ]
Sets the query params of the URL. @param [String] query The query string to parse. @return [String] The given query string. @since 1.0.0 @api public
[ "Sets", "the", "query", "params", "of", "the", "URL", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/url.rb#L441-L452
train
ronin-ruby/ronin
lib/ronin/url.rb
Ronin.URL.to_uri
def to_uri # map the URL scheme to a URI class url_class = SCHEMES.fetch(self.scheme.name,::URI::Generic) host = if self.host_name self.host_name.address end port = if self.port self.port.number end query = unless self.query_params.empty? self.query_string end # build the URI return url_class.build( :scheme => self.scheme.name, :host => host, :port => port, :path => self.path, :query => query, :fragment => self.fragment ) end
ruby
def to_uri # map the URL scheme to a URI class url_class = SCHEMES.fetch(self.scheme.name,::URI::Generic) host = if self.host_name self.host_name.address end port = if self.port self.port.number end query = unless self.query_params.empty? self.query_string end # build the URI return url_class.build( :scheme => self.scheme.name, :host => host, :port => port, :path => self.path, :query => query, :fragment => self.fragment ) end
[ "def", "to_uri", "url_class", "=", "SCHEMES", ".", "fetch", "(", "self", ".", "scheme", ".", "name", ",", "::", "URI", "::", "Generic", ")", "host", "=", "if", "self", ".", "host_name", "self", ".", "host_name", ".", "address", "end", "port", "=", "if", "self", ".", "port", "self", ".", "port", ".", "number", "end", "query", "=", "unless", "self", ".", "query_params", ".", "empty?", "self", ".", "query_string", "end", "return", "url_class", ".", "build", "(", ":scheme", "=>", "self", ".", "scheme", ".", "name", ",", ":host", "=>", "host", ",", ":port", "=>", "port", ",", ":path", "=>", "self", ".", "path", ",", ":query", "=>", "query", ",", ":fragment", "=>", "self", ".", "fragment", ")", "end" ]
Builds a URI object from the URL. @return [URI::HTTP, URI::HTTPS] The URI object created from the URL attributes. @since 1.0.0 @api public
[ "Builds", "a", "URI", "object", "from", "the", "URL", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/url.rb#L464-L488
train
ronin-ruby/ronin
lib/ronin/host_name.rb
Ronin.HostName.lookup!
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) ips = begin resolver.getaddresses(self.address) rescue [] end ips.map! do |addr| IPAddress.first_or_create( :address => addr, :host_names => [self] ) end return ips end
ruby
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) ips = begin resolver.getaddresses(self.address) rescue [] end ips.map! do |addr| IPAddress.first_or_create( :address => addr, :host_names => [self] ) end return ips end
[ "def", "lookup!", "(", "nameserver", "=", "nil", ")", "resolver", "=", "Resolv", ".", "resolver", "(", "nameserver", ")", "ips", "=", "begin", "resolver", ".", "getaddresses", "(", "self", ".", "address", ")", "rescue", "[", "]", "end", "ips", ".", "map!", "do", "|", "addr", "|", "IPAddress", ".", "first_or_create", "(", ":address", "=>", "addr", ",", ":host_names", "=>", "[", "self", "]", ")", "end", "return", "ips", "end" ]
Looks up all IP Addresses for the host name. @param [String] nameserver The optional nameserver to query. @return [Array<IPAddress>] The IP Addresses for the host name. @since 1.0.0 @api public
[ "Looks", "up", "all", "IP", "Addresses", "for", "the", "host", "name", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/host_name.rb#L218-L234
train
ronin-ruby/ronin
lib/ronin/campaign.rb
Ronin.Campaign.target!
def target!(addr) unless (address = Address.first(:address => addr)) raise("unknown address #{addr.dump}") end return Target.first_or_create(:campaign => self, :address => address) end
ruby
def target!(addr) unless (address = Address.first(:address => addr)) raise("unknown address #{addr.dump}") end return Target.first_or_create(:campaign => self, :address => address) end
[ "def", "target!", "(", "addr", ")", "unless", "(", "address", "=", "Address", ".", "first", "(", ":address", "=>", "addr", ")", ")", "raise", "(", "\"unknown address #{addr.dump}\"", ")", "end", "return", "Target", ".", "first_or_create", "(", ":campaign", "=>", "self", ",", ":address", "=>", "address", ")", "end" ]
Adds an address to the campaign. @param [String] addr The address that will be targeted. @return [Target] The new target of the campaign. @raise [RuntimeError] The given address could not be found. @since 1.0.0 @api public
[ "Adds", "an", "address", "to", "the", "campaign", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/campaign.rb#L120-L126
train
ronin-ruby/ronin
lib/ronin/ip_address.rb
Ronin.IPAddress.lookup!
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) hosts = begin resolver.getnames(self.address.to_s) rescue [] end hosts.map! do |name| HostName.first_or_create( :address => name, :ip_addresses => [self] ) end return hosts end
ruby
def lookup!(nameserver=nil) resolver = Resolv.resolver(nameserver) hosts = begin resolver.getnames(self.address.to_s) rescue [] end hosts.map! do |name| HostName.first_or_create( :address => name, :ip_addresses => [self] ) end return hosts end
[ "def", "lookup!", "(", "nameserver", "=", "nil", ")", "resolver", "=", "Resolv", ".", "resolver", "(", "nameserver", ")", "hosts", "=", "begin", "resolver", ".", "getnames", "(", "self", ".", "address", ".", "to_s", ")", "rescue", "[", "]", "end", "hosts", ".", "map!", "do", "|", "name", "|", "HostName", ".", "first_or_create", "(", ":address", "=>", "name", ",", ":ip_addresses", "=>", "[", "self", "]", ")", "end", "return", "hosts", "end" ]
Performs a reverse lookup on the IP address. @param [String] nameserver Optional nameserver to query. @return [Array<HostName>] The host-names associated with the IP Address. @since 1.0.0 @api public
[ "Performs", "a", "reverse", "lookup", "on", "the", "IP", "address", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/ip_address.rb#L236-L252
train
ronin-ruby/ronin
lib/ronin/repository.rb
Ronin.Repository.find_script
def find_script(sub_path) paths = @script_dirs.map { |dir| File.join(dir,sub_path) } return script_paths.first(:path => paths) end
ruby
def find_script(sub_path) paths = @script_dirs.map { |dir| File.join(dir,sub_path) } return script_paths.first(:path => paths) end
[ "def", "find_script", "(", "sub_path", ")", "paths", "=", "@script_dirs", ".", "map", "{", "|", "dir", "|", "File", ".", "join", "(", "dir", ",", "sub_path", ")", "}", "return", "script_paths", ".", "first", "(", ":path", "=>", "paths", ")", "end" ]
Finds a cached script. @param [String] sub_path The sub-path within the repository to search for. @return [Script::Path, nil] The matching script path. @since 1.1.0 @api private
[ "Finds", "a", "cached", "script", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/repository.rb#L550-L554
train
ronin-ruby/ronin
lib/ronin/repository.rb
Ronin.Repository.update!
def update! local_repo = Pullr::LocalRepository.new( :path => self.path, :scm => self.scm ) # only update if we have a repository local_repo.update(self.uri) # re-initialize the metadata initialize_metadata # save the repository if save # syncs the cached files of the repository sync_scripts! end yield self if block_given? return self end
ruby
def update! local_repo = Pullr::LocalRepository.new( :path => self.path, :scm => self.scm ) # only update if we have a repository local_repo.update(self.uri) # re-initialize the metadata initialize_metadata # save the repository if save # syncs the cached files of the repository sync_scripts! end yield self if block_given? return self end
[ "def", "update!", "local_repo", "=", "Pullr", "::", "LocalRepository", ".", "new", "(", ":path", "=>", "self", ".", "path", ",", ":scm", "=>", "self", ".", "scm", ")", "local_repo", ".", "update", "(", "self", ".", "uri", ")", "initialize_metadata", "if", "save", "sync_scripts!", "end", "yield", "self", "if", "block_given?", "return", "self", "end" ]
Updates the repository, reloads it's metadata and syncs the cached files of the repository. @yield [repo] If a block is given, it will be passed after the repository has been updated. @yieldparam [Repository] repo The updated repository. @return [Repository] The updated repository. @since 1.0.0 @api private
[ "Updates", "the", "repository", "reloads", "it", "s", "metadata", "and", "syncs", "the", "cached", "files", "of", "the", "repository", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/repository.rb#L646-L666
train
ronin-ruby/ronin
lib/ronin/repository.rb
Ronin.Repository.uninstall!
def uninstall! deactivate! FileUtils.rm_rf(self.path) if self.installed? # destroy any cached files first clean_scripts! # remove the repository from the database destroy if saved? yield self if block_given? return self end
ruby
def uninstall! deactivate! FileUtils.rm_rf(self.path) if self.installed? # destroy any cached files first clean_scripts! # remove the repository from the database destroy if saved? yield self if block_given? return self end
[ "def", "uninstall!", "deactivate!", "FileUtils", ".", "rm_rf", "(", "self", ".", "path", ")", "if", "self", ".", "installed?", "clean_scripts!", "destroy", "if", "saved?", "yield", "self", "if", "block_given?", "return", "self", "end" ]
Deletes the contents of the repository. @yield [repo] If a block is given, it will be passed the repository after it's contents have been deleted. @yieldparam [Repository] repo The deleted repository. @return [Repository] The deleted repository. @since 1.0.0 @api private
[ "Deletes", "the", "contents", "of", "the", "repository", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/repository.rb#L685-L698
train
ronin-ruby/ronin
lib/ronin/password.rb
Ronin.Password.digest
def digest(algorithm,options={}) digest_class = begin Digest.const_get(algorithm.to_s.upcase) rescue LoadError raise(ArgumentError,"Unknown Digest algorithm #{algorithm}") end hash = digest_class.new if options[:prepend_salt] hash << options[:prepend_salt].to_s end hash << self.clear_text if options[:append_salt] hash << options[:append_salt].to_s end return hash.hexdigest end
ruby
def digest(algorithm,options={}) digest_class = begin Digest.const_get(algorithm.to_s.upcase) rescue LoadError raise(ArgumentError,"Unknown Digest algorithm #{algorithm}") end hash = digest_class.new if options[:prepend_salt] hash << options[:prepend_salt].to_s end hash << self.clear_text if options[:append_salt] hash << options[:append_salt].to_s end return hash.hexdigest end
[ "def", "digest", "(", "algorithm", ",", "options", "=", "{", "}", ")", "digest_class", "=", "begin", "Digest", ".", "const_get", "(", "algorithm", ".", "to_s", ".", "upcase", ")", "rescue", "LoadError", "raise", "(", "ArgumentError", ",", "\"Unknown Digest algorithm #{algorithm}\"", ")", "end", "hash", "=", "digest_class", ".", "new", "if", "options", "[", ":prepend_salt", "]", "hash", "<<", "options", "[", ":prepend_salt", "]", ".", "to_s", "end", "hash", "<<", "self", ".", "clear_text", "if", "options", "[", ":append_salt", "]", "hash", "<<", "options", "[", ":append_salt", "]", ".", "to_s", "end", "return", "hash", ".", "hexdigest", "end" ]
Hashes the password. @param [Symbol, String] algorithm The digest algorithm to use. @param [Hash] options Additional options. @option options [String] :prepend_salt The salt data to prepend to the password. @option options [String] :append_salt The salt data to append to the password. @return [String] The hex-digest of the hashed password. @raise [ArgumentError] Unknown Digest algorithm. @example pass = Password.new(:clear_text => 'secret') pass.digest(:sha1) # => "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4" pass.digest(:sha1, :prepend_salt => "A\x90\x00") # => "e2817656a48c49f24839ccf9295b389d8f985904" pass.digest(:sha1, :append_salt => "BBBB") # => "aa6ca21e446d425fc044bbb26e950a788444a5b8" @since 1.0.0 @api public
[ "Hashes", "the", "password", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/password.rb#L100-L120
train
ronin-ruby/ronin
lib/ronin/mac_address.rb
Ronin.MACAddress.to_i
def to_i self.address.split(':').inject(0) do |bits,char| bits = ((bits << 8) | char.hex) end end
ruby
def to_i self.address.split(':').inject(0) do |bits,char| bits = ((bits << 8) | char.hex) end end
[ "def", "to_i", "self", ".", "address", ".", "split", "(", "':'", ")", ".", "inject", "(", "0", ")", "do", "|", "bits", ",", "char", "|", "bits", "=", "(", "(", "bits", "<<", "8", ")", "|", "char", ".", "hex", ")", "end", "end" ]
Converts the MAC address to an Integer. @return [Integer] The network representation of the MAC address. @since 1.0.0 @api public
[ "Converts", "the", "MAC", "address", "to", "an", "Integer", "." ]
10474c197f2c130f1e09975716955322a848b20a
https://github.com/ronin-ruby/ronin/blob/10474c197f2c130f1e09975716955322a848b20a/lib/ronin/mac_address.rb#L104-L108
train
SeanNieuwoudt/plugg
lib/plugg.rb
Plugg.Dispatcher.start
def start(paths, params = {}) @registry = [] paths.each do |path| if path[-1] == '/' path.chop! end Dir["#{path}/*.rb"].each do |f| require File.expand_path(f) begin instance = Object.const_get(File.basename(f, '.rb')).new # `before` event callback if instance.respond_to?(:before) instance.send(:before) end # `setup` method if instance.respond_to?(:setup) instance.send(:setup, params) end @registry.push(instance) rescue Exception => e puts "#{f} Plugg Initialization Exception: #{e}" end end end end
ruby
def start(paths, params = {}) @registry = [] paths.each do |path| if path[-1] == '/' path.chop! end Dir["#{path}/*.rb"].each do |f| require File.expand_path(f) begin instance = Object.const_get(File.basename(f, '.rb')).new # `before` event callback if instance.respond_to?(:before) instance.send(:before) end # `setup` method if instance.respond_to?(:setup) instance.send(:setup, params) end @registry.push(instance) rescue Exception => e puts "#{f} Plugg Initialization Exception: #{e}" end end end end
[ "def", "start", "(", "paths", ",", "params", "=", "{", "}", ")", "@registry", "=", "[", "]", "paths", ".", "each", "do", "|", "path", "|", "if", "path", "[", "-", "1", "]", "==", "'/'", "path", ".", "chop!", "end", "Dir", "[", "\"#{path}/*.rb\"", "]", ".", "each", "do", "|", "f", "|", "require", "File", ".", "expand_path", "(", "f", ")", "begin", "instance", "=", "Object", ".", "const_get", "(", "File", ".", "basename", "(", "f", ",", "'.rb'", ")", ")", ".", "new", "if", "instance", ".", "respond_to?", "(", ":before", ")", "instance", ".", "send", "(", ":before", ")", "end", "if", "instance", ".", "respond_to?", "(", ":setup", ")", "instance", ".", "send", "(", ":setup", ",", "params", ")", "end", "@registry", ".", "push", "(", "instance", ")", "rescue", "Exception", "=>", "e", "puts", "\"#{f} Plugg Initialization Exception: #{e}\"", "end", "end", "end", "end" ]
Assign a path where plugins should be loaded from @param mixed path @param hash params @return void
[ "Assign", "a", "path", "where", "plugins", "should", "be", "loaded", "from" ]
f078d76aa17aa651f4c89ba39553a5436e98384b
https://github.com/SeanNieuwoudt/plugg/blob/f078d76aa17aa651f4c89ba39553a5436e98384b/lib/plugg.rb#L126-L158
train
SeanNieuwoudt/plugg
lib/plugg.rb
Plugg.Dispatcher.on
def on(method, *args, &block) if [:initialize, :before, :setup, :after].include? method raise "#{method} should not be called directly" end buffer = [] # Container for the response buffer threads = [] # Container for the execution threads @registry.each do |s| if s.respond_to?(method.to_sym, false) threads << Thread.new do responder = DispatchResponder.new(s) responder.trap(@timeout) do if s.method(method.to_sym).arity == 0 s.send(method, &block) else s.send(method, *args, &block) end end responder.finalize buffer << responder.to_h end end end threads.map(&:join) buffer end
ruby
def on(method, *args, &block) if [:initialize, :before, :setup, :after].include? method raise "#{method} should not be called directly" end buffer = [] # Container for the response buffer threads = [] # Container for the execution threads @registry.each do |s| if s.respond_to?(method.to_sym, false) threads << Thread.new do responder = DispatchResponder.new(s) responder.trap(@timeout) do if s.method(method.to_sym).arity == 0 s.send(method, &block) else s.send(method, *args, &block) end end responder.finalize buffer << responder.to_h end end end threads.map(&:join) buffer end
[ "def", "on", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "[", ":initialize", ",", ":before", ",", ":setup", ",", ":after", "]", ".", "include?", "method", "raise", "\"#{method} should not be called directly\"", "end", "buffer", "=", "[", "]", "threads", "=", "[", "]", "@registry", ".", "each", "do", "|", "s", "|", "if", "s", ".", "respond_to?", "(", "method", ".", "to_sym", ",", "false", ")", "threads", "<<", "Thread", ".", "new", "do", "responder", "=", "DispatchResponder", ".", "new", "(", "s", ")", "responder", ".", "trap", "(", "@timeout", ")", "do", "if", "s", ".", "method", "(", "method", ".", "to_sym", ")", ".", "arity", "==", "0", "s", ".", "send", "(", "method", ",", "&", "block", ")", "else", "s", ".", "send", "(", "method", ",", "*", "args", ",", "&", "block", ")", "end", "end", "responder", ".", "finalize", "buffer", "<<", "responder", ".", "to_h", "end", "end", "end", "threads", ".", "map", "(", "&", ":join", ")", "buffer", "end" ]
Initialize the dispatcher instance with a default timeout of 5s @return void Loop through all services and fire off the supported messages @param string method @return void
[ "Initialize", "the", "dispatcher", "instance", "with", "a", "default", "timeout", "of", "5s" ]
f078d76aa17aa651f4c89ba39553a5436e98384b
https://github.com/SeanNieuwoudt/plugg/blob/f078d76aa17aa651f4c89ba39553a5436e98384b/lib/plugg.rb#L182-L214
train
shunhikita/action_messenger
lib/action_messenger/base.rb
ActionMessenger.Base.message_to_slack
def message_to_slack(channel:, options: {}) @caller_method_name = caller[0][/`([^']*)'/, 1] options = apply_defaults(options) message = nil ActiveSupport::Notifications.instrument('message_to_slack.action_messenger', channel: channel, body: options[:text]) do message = slack_client.message(channel, options) end message ensure self.deliveries << DeliveryLog.new(__method__, channel, message) end
ruby
def message_to_slack(channel:, options: {}) @caller_method_name = caller[0][/`([^']*)'/, 1] options = apply_defaults(options) message = nil ActiveSupport::Notifications.instrument('message_to_slack.action_messenger', channel: channel, body: options[:text]) do message = slack_client.message(channel, options) end message ensure self.deliveries << DeliveryLog.new(__method__, channel, message) end
[ "def", "message_to_slack", "(", "channel", ":", ",", "options", ":", "{", "}", ")", "@caller_method_name", "=", "caller", "[", "0", "]", "[", "/", "/", ",", "1", "]", "options", "=", "apply_defaults", "(", "options", ")", "message", "=", "nil", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'message_to_slack.action_messenger'", ",", "channel", ":", "channel", ",", "body", ":", "options", "[", ":text", "]", ")", "do", "message", "=", "slack_client", ".", "message", "(", "channel", ",", "options", ")", "end", "message", "ensure", "self", ".", "deliveries", "<<", "DeliveryLog", ".", "new", "(", "__method__", ",", "channel", ",", "message", ")", "end" ]
message to slack @param [String] channel slack channel. ex. #general @param [Hash] options Slack API Request Options ex. https://api.slack.com/methods/chat.postMessage ex. message_to_slack(channel: '#general', options: {text: 'sample'})
[ "message", "to", "slack" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/base.rb#L51-L61
train
shunhikita/action_messenger
lib/action_messenger/base.rb
ActionMessenger.Base.upload_file_to_slack
def upload_file_to_slack(channels: ,file: ,options: {}) upload_file = nil ActiveSupport::Notifications.instrument('upload_file_to_slack.action_messenger', channels: channels) do upload_file = slack_client.upload_file(channels, file, options) end upload_file ensure self.deliveries << DeliveryLog.new(__method__, channels, upload_file) end
ruby
def upload_file_to_slack(channels: ,file: ,options: {}) upload_file = nil ActiveSupport::Notifications.instrument('upload_file_to_slack.action_messenger', channels: channels) do upload_file = slack_client.upload_file(channels, file, options) end upload_file ensure self.deliveries << DeliveryLog.new(__method__, channels, upload_file) end
[ "def", "upload_file_to_slack", "(", "channels", ":", ",", "file", ":", ",", "options", ":", "{", "}", ")", "upload_file", "=", "nil", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'upload_file_to_slack.action_messenger'", ",", "channels", ":", "channels", ")", "do", "upload_file", "=", "slack_client", ".", "upload_file", "(", "channels", ",", "file", ",", "options", ")", "end", "upload_file", "ensure", "self", ".", "deliveries", "<<", "DeliveryLog", ".", "new", "(", "__method__", ",", "channels", ",", "upload_file", ")", "end" ]
upload file to slack @param [String] channels slack channel ex. #general, #hoge @param [Faraday::UploadIO] file upload file ex. Faraday::UploadIO.new('/path/to/sample.jpg', 'image/jpg') @param [Hash] options
[ "upload", "file", "to", "slack" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/base.rb#L70-L78
train
tdak/worldcatapi
lib/worldcatapi/sru_search_response.rb
WORLDCATAPI.SruSearchResponse.extract_multiple
def extract_multiple(record, field, tag) a = Array.new record.fields(field).each do |field| a.push field[tag] end return a end
ruby
def extract_multiple(record, field, tag) a = Array.new record.fields(field).each do |field| a.push field[tag] end return a end
[ "def", "extract_multiple", "(", "record", ",", "field", ",", "tag", ")", "a", "=", "Array", ".", "new", "record", ".", "fields", "(", "field", ")", ".", "each", "do", "|", "field", "|", "a", ".", "push", "field", "[", "tag", "]", "end", "return", "a", "end" ]
Extract Multiple fields for record
[ "Extract", "Multiple", "fields", "for", "record" ]
ed6d0cb849e86a032dc84741a5d169da19b8e385
https://github.com/tdak/worldcatapi/blob/ed6d0cb849e86a032dc84741a5d169da19b8e385/lib/worldcatapi/sru_search_response.rb#L60-L66
train
conduit/conduit-braintree
lib/conduit/braintree/actions/base.rb
Conduit::Driver::Braintree.Base.perform
def perform body = perform_action parser = parser_class.new(body) Conduit::ApiResponse.new(raw_response: @raw_response, body: body, parser: parser) rescue Braintree::NotFoundError => error report_braintree_exceptions(error) rescue ArgumentError => error respond_with_error(error.message) rescue Braintree::BraintreeError => error report_braintree_exceptions(error) rescue Net::ReadTimeout, Net::OpenTimeout, Errno::ETIMEDOUT respond_with_error("Braintree timeout") end
ruby
def perform body = perform_action parser = parser_class.new(body) Conduit::ApiResponse.new(raw_response: @raw_response, body: body, parser: parser) rescue Braintree::NotFoundError => error report_braintree_exceptions(error) rescue ArgumentError => error respond_with_error(error.message) rescue Braintree::BraintreeError => error report_braintree_exceptions(error) rescue Net::ReadTimeout, Net::OpenTimeout, Errno::ETIMEDOUT respond_with_error("Braintree timeout") end
[ "def", "perform", "body", "=", "perform_action", "parser", "=", "parser_class", ".", "new", "(", "body", ")", "Conduit", "::", "ApiResponse", ".", "new", "(", "raw_response", ":", "@raw_response", ",", "body", ":", "body", ",", "parser", ":", "parser", ")", "rescue", "Braintree", "::", "NotFoundError", "=>", "error", "report_braintree_exceptions", "(", "error", ")", "rescue", "ArgumentError", "=>", "error", "respond_with_error", "(", "error", ".", "message", ")", "rescue", "Braintree", "::", "BraintreeError", "=>", "error", "report_braintree_exceptions", "(", "error", ")", "rescue", "Net", "::", "ReadTimeout", ",", "Net", "::", "OpenTimeout", ",", "Errno", "::", "ETIMEDOUT", "respond_with_error", "(", "\"Braintree timeout\"", ")", "end" ]
Performs the request, with mocking if requested
[ "Performs", "the", "request", "with", "mocking", "if", "requested" ]
67fd15ac223eb3118da5fe75177e9e6e42430504
https://github.com/conduit/conduit-braintree/blob/67fd15ac223eb3118da5fe75177e9e6e42430504/lib/conduit/braintree/actions/base.rb#L23-L35
train
daanforever/settingson
app/models/concerns/settingson/base.rb
Settingson::Base.ClassMethods.defaults
def defaults @__defaults = Settingson::Store::Default.new( klass: self ) if block_given? Rails.application.config.after_initialize do yield @__defaults end end @__defaults end
ruby
def defaults @__defaults = Settingson::Store::Default.new( klass: self ) if block_given? Rails.application.config.after_initialize do yield @__defaults end end @__defaults end
[ "def", "defaults", "@__defaults", "=", "Settingson", "::", "Store", "::", "Default", ".", "new", "(", "klass", ":", "self", ")", "if", "block_given?", "Rails", ".", "application", ".", "config", ".", "after_initialize", "do", "yield", "@__defaults", "end", "end", "@__defaults", "end" ]
Settings.defaults do |default| default.server.host = 'host' default.server.port = 80 end
[ "Settings", ".", "defaults", "do", "|default|", "default", ".", "server", ".", "host", "=", "host", "default", ".", "server", ".", "port", "=", "80", "end" ]
a3aa6ace98479841b6c9a6f3af7ed01a6cd7269e
https://github.com/daanforever/settingson/blob/a3aa6ace98479841b6c9a6f3af7ed01a6cd7269e/app/models/concerns/settingson/base.rb#L26-L36
train
ianpurvis/police_state
lib/police_state/transition_helpers.rb
PoliceState.TransitionHelpers.attribute_transitioning?
def attribute_transitioning?(attr, options={}) options = _transform_options_for_attribute(attr, options) attribute_changed?(attr, options) end
ruby
def attribute_transitioning?(attr, options={}) options = _transform_options_for_attribute(attr, options) attribute_changed?(attr, options) end
[ "def", "attribute_transitioning?", "(", "attr", ",", "options", "=", "{", "}", ")", "options", "=", "_transform_options_for_attribute", "(", "attr", ",", "options", ")", "attribute_changed?", "(", "attr", ",", "options", ")", "end" ]
Returns +true+ if +attribute+ is currently transitioning but not saved, otherwise +false+. You can specify origin and destination states using the +:from+ and +:to+ options. If +attribute+ is an +ActiveRecord::Enum+, these may be specified as either symbol or their native enum value. model = Model.new(status: :complete) # => #<Model:0x007fa94844d088 @status=:complete> model.status_transitioning? # => true model.status_transitioning?(from: nil) # => true model.status_transitioning?(to: :complete) # => true model.status_transitioning?(to: "complete") # => true model.status_transitioning?(from: nil, to: :complete) # => true
[ "Returns", "+", "true", "+", "if", "+", "attribute", "+", "is", "currently", "transitioning", "but", "not", "saved", "otherwise", "+", "false", "+", "." ]
d827e74a0b2eb2a698a018d5367fb63c49b6b699
https://github.com/ianpurvis/police_state/blob/d827e74a0b2eb2a698a018d5367fb63c49b6b699/lib/police_state/transition_helpers.rb#L54-L57
train
shunhikita/action_messenger
lib/action_messenger/message_delivery.rb
ActionMessenger.MessageDelivery.deliver_now!
def deliver_now! messenger.handle_exceptions do ActiveSupport::Notifications.instrument('deliver_now!.action_messenger', method_name: method_name, args: args) do if args.present? messenger.public_send(method_name, *args) else messenger.public_send(method_name) end end end end
ruby
def deliver_now! messenger.handle_exceptions do ActiveSupport::Notifications.instrument('deliver_now!.action_messenger', method_name: method_name, args: args) do if args.present? messenger.public_send(method_name, *args) else messenger.public_send(method_name) end end end end
[ "def", "deliver_now!", "messenger", ".", "handle_exceptions", "do", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "'deliver_now!.action_messenger'", ",", "method_name", ":", "method_name", ",", "args", ":", "args", ")", "do", "if", "args", ".", "present?", "messenger", ".", "public_send", "(", "method_name", ",", "*", "args", ")", "else", "messenger", ".", "public_send", "(", "method_name", ")", "end", "end", "end", "end" ]
send a message now
[ "send", "a", "message", "now" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/message_delivery.rb#L15-L25
train
shunhikita/action_messenger
lib/action_messenger/message_delivery.rb
ActionMessenger.MessageDelivery.deliver_later!
def deliver_later! ActionMessenger::MessageDeliveryJob.perform_later(self.class.name, 'deliver_now!', messenger_class.to_s, method_name.to_s, *args) end
ruby
def deliver_later! ActionMessenger::MessageDeliveryJob.perform_later(self.class.name, 'deliver_now!', messenger_class.to_s, method_name.to_s, *args) end
[ "def", "deliver_later!", "ActionMessenger", "::", "MessageDeliveryJob", ".", "perform_later", "(", "self", ".", "class", ".", "name", ",", "'deliver_now!'", ",", "messenger_class", ".", "to_s", ",", "method_name", ".", "to_s", ",", "*", "args", ")", "end" ]
send a message asynchronously
[ "send", "a", "message", "asynchronously" ]
0bfed768917de491cf51898bfc0124c423dd6474
https://github.com/shunhikita/action_messenger/blob/0bfed768917de491cf51898bfc0124c423dd6474/lib/action_messenger/message_delivery.rb#L28-L30
train
ateamlunchbox/graphql_grpc
lib/graphql_grpc/proxy.rb
GraphqlGrpc.Proxy.map_functions
def map_functions(stub_services) return @function_map unless @function_map.empty? stub_services.keys.each do |service_name| stub = @services[service_name] = stub_services[service_name] stub.class.to_s.gsub('::Stub', '::Service').constantize.rpc_descs.values.each do |d| next if d.name.to_sym == :Healthcheck grpc_func = ::GraphqlGrpc::Function.new(service_name, stub, d) if @function_map.key?(grpc_func.name) sn = @function_map[grpc_func.name].service_name STDERR.puts "Skipping method #{grpc_func.name}; it was already defined on #{sn}" # raise ConfigurationError, "#{grpc_func.name} was already defined on #{sn}." end @function_map[grpc_func.name] = grpc_func end end @function_map end
ruby
def map_functions(stub_services) return @function_map unless @function_map.empty? stub_services.keys.each do |service_name| stub = @services[service_name] = stub_services[service_name] stub.class.to_s.gsub('::Stub', '::Service').constantize.rpc_descs.values.each do |d| next if d.name.to_sym == :Healthcheck grpc_func = ::GraphqlGrpc::Function.new(service_name, stub, d) if @function_map.key?(grpc_func.name) sn = @function_map[grpc_func.name].service_name STDERR.puts "Skipping method #{grpc_func.name}; it was already defined on #{sn}" # raise ConfigurationError, "#{grpc_func.name} was already defined on #{sn}." end @function_map[grpc_func.name] = grpc_func end end @function_map end
[ "def", "map_functions", "(", "stub_services", ")", "return", "@function_map", "unless", "@function_map", ".", "empty?", "stub_services", ".", "keys", ".", "each", "do", "|", "service_name", "|", "stub", "=", "@services", "[", "service_name", "]", "=", "stub_services", "[", "service_name", "]", "stub", ".", "class", ".", "to_s", ".", "gsub", "(", "'::Stub'", ",", "'::Service'", ")", ".", "constantize", ".", "rpc_descs", ".", "values", ".", "each", "do", "|", "d", "|", "next", "if", "d", ".", "name", ".", "to_sym", "==", ":Healthcheck", "grpc_func", "=", "::", "GraphqlGrpc", "::", "Function", ".", "new", "(", "service_name", ",", "stub", ",", "d", ")", "if", "@function_map", ".", "key?", "(", "grpc_func", ".", "name", ")", "sn", "=", "@function_map", "[", "grpc_func", ".", "name", "]", ".", "service_name", "STDERR", ".", "puts", "\"Skipping method #{grpc_func.name}; it was already defined on #{sn}\"", "end", "@function_map", "[", "grpc_func", ".", "name", "]", "=", "grpc_func", "end", "end", "@function_map", "end" ]
Add to the function_map by inspecting each service for the RPCs it provides.
[ "Add", "to", "the", "function_map", "by", "inspecting", "each", "service", "for", "the", "RPCs", "it", "provides", "." ]
dfb51f32457584007ea03895d12f4e089f3a4946
https://github.com/ateamlunchbox/graphql_grpc/blob/dfb51f32457584007ea03895d12f4e089f3a4946/lib/graphql_grpc/proxy.rb#L85-L103
train
ateamlunchbox/graphql_grpc
lib/graphql_grpc/function.rb
GraphqlGrpc.Function.arg
def arg(params) rpc_desc.input.decode_json(params.reject { |k, _v| k == :selections }.to_json) end
ruby
def arg(params) rpc_desc.input.decode_json(params.reject { |k, _v| k == :selections }.to_json) end
[ "def", "arg", "(", "params", ")", "rpc_desc", ".", "input", ".", "decode_json", "(", "params", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", "==", ":selections", "}", ".", "to_json", ")", "end" ]
Build arguments to a func
[ "Build", "arguments", "to", "a", "func" ]
dfb51f32457584007ea03895d12f4e089f3a4946
https://github.com/ateamlunchbox/graphql_grpc/blob/dfb51f32457584007ea03895d12f4e089f3a4946/lib/graphql_grpc/function.rb#L108-L110
train
conduit/conduit-braintree
lib/conduit/braintree/actions/update_credit_card.rb
Conduit::Driver::Braintree.UpdateCreditCard.whitelist_options
def whitelist_options @options[:options] ||= {}.tap do |h| h[:verify_card] = @options.fetch(:verify_card, true) @options.delete(:verify_card) if @options.key?(:verification_merchant_account_id) h[:verification_merchant_account_id] = @options.delete(:verification_merchant_account_id) end end super end
ruby
def whitelist_options @options[:options] ||= {}.tap do |h| h[:verify_card] = @options.fetch(:verify_card, true) @options.delete(:verify_card) if @options.key?(:verification_merchant_account_id) h[:verification_merchant_account_id] = @options.delete(:verification_merchant_account_id) end end super end
[ "def", "whitelist_options", "@options", "[", ":options", "]", "||=", "{", "}", ".", "tap", "do", "|", "h", "|", "h", "[", ":verify_card", "]", "=", "@options", ".", "fetch", "(", ":verify_card", ",", "true", ")", "@options", ".", "delete", "(", ":verify_card", ")", "if", "@options", ".", "key?", "(", ":verification_merchant_account_id", ")", "h", "[", ":verification_merchant_account_id", "]", "=", "@options", ".", "delete", "(", ":verification_merchant_account_id", ")", "end", "end", "super", "end" ]
Request verification when the card is stored, using the merchant account id if one is provided
[ "Request", "verification", "when", "the", "card", "is", "stored", "using", "the", "merchant", "account", "id", "if", "one", "is", "provided" ]
67fd15ac223eb3118da5fe75177e9e6e42430504
https://github.com/conduit/conduit-braintree/blob/67fd15ac223eb3118da5fe75177e9e6e42430504/lib/conduit/braintree/actions/update_credit_card.rb#L27-L36
train
robmiller/ruby-wpdb
lib/ruby-wpdb/term.rb
WPDB.Termable.add_term
def add_term(term, taxonomy, description, count) if term.respond_to?(:term_id) term_id = term.term_id else term_id = term.to_i end term_taxonomy = WPDB::TermTaxonomy.where(term_id: term_id, taxonomy: taxonomy).first unless term_taxonomy term_taxonomy = WPDB::TermTaxonomy.create( term_id: term_id, taxonomy: taxonomy, description: description, count: count ) else term_taxonomy.count += count end add_termtaxonomy(term_taxonomy) end
ruby
def add_term(term, taxonomy, description, count) if term.respond_to?(:term_id) term_id = term.term_id else term_id = term.to_i end term_taxonomy = WPDB::TermTaxonomy.where(term_id: term_id, taxonomy: taxonomy).first unless term_taxonomy term_taxonomy = WPDB::TermTaxonomy.create( term_id: term_id, taxonomy: taxonomy, description: description, count: count ) else term_taxonomy.count += count end add_termtaxonomy(term_taxonomy) end
[ "def", "add_term", "(", "term", ",", "taxonomy", ",", "description", ",", "count", ")", "if", "term", ".", "respond_to?", "(", ":term_id", ")", "term_id", "=", "term", ".", "term_id", "else", "term_id", "=", "term", ".", "to_i", "end", "term_taxonomy", "=", "WPDB", "::", "TermTaxonomy", ".", "where", "(", "term_id", ":", "term_id", ",", "taxonomy", ":", "taxonomy", ")", ".", "first", "unless", "term_taxonomy", "term_taxonomy", "=", "WPDB", "::", "TermTaxonomy", ".", "create", "(", "term_id", ":", "term_id", ",", "taxonomy", ":", "taxonomy", ",", "description", ":", "description", ",", "count", ":", "count", ")", "else", "term_taxonomy", ".", "count", "+=", "count", "end", "add_termtaxonomy", "(", "term_taxonomy", ")", "end" ]
For objects that have a relationship with termtaxonomies, this module can be mixed in and gives the ability to add a term directly to the model, rather than creating the relationship yourself. Used by Post and Link.
[ "For", "objects", "that", "have", "a", "relationship", "with", "termtaxonomies", "this", "module", "can", "be", "mixed", "in", "and", "gives", "the", "ability", "to", "add", "a", "term", "directly", "to", "the", "model", "rather", "than", "creating", "the", "relationship", "yourself", ".", "Used", "by", "Post", "and", "Link", "." ]
2252be12baa3b9607c26fc8cc5e167ae3b82a94d
https://github.com/robmiller/ruby-wpdb/blob/2252be12baa3b9607c26fc8cc5e167ae3b82a94d/lib/ruby-wpdb/term.rb#L19-L39
train
TailorBrands/noun-project-api
lib/noun-project-api/retriever.rb
NounProjectApi.Retriever.find
def find(id) raise ArgumentError.new("Missing id/slug") unless id result = access_token.get("#{API_BASE}#{self.class::API_PATH}#{id}") raise ServiceError.new(result.code, result.body) unless result.code == "200" self.class::ITEM_CLASS.new(result.body) end
ruby
def find(id) raise ArgumentError.new("Missing id/slug") unless id result = access_token.get("#{API_BASE}#{self.class::API_PATH}#{id}") raise ServiceError.new(result.code, result.body) unless result.code == "200" self.class::ITEM_CLASS.new(result.body) end
[ "def", "find", "(", "id", ")", "raise", "ArgumentError", ".", "new", "(", "\"Missing id/slug\"", ")", "unless", "id", "result", "=", "access_token", ".", "get", "(", "\"#{API_BASE}#{self.class::API_PATH}#{id}\"", ")", "raise", "ServiceError", ".", "new", "(", "result", ".", "code", ",", "result", ".", "body", ")", "unless", "result", ".", "code", "==", "\"200\"", "self", ".", "class", "::", "ITEM_CLASS", ".", "new", "(", "result", ".", "body", ")", "end" ]
Find an item based on it's id.
[ "Find", "an", "item", "based", "on", "it", "s", "id", "." ]
b4fbd0836fd80aee843af03569bdfa2a6ffe79f9
https://github.com/TailorBrands/noun-project-api/blob/b4fbd0836fd80aee843af03569bdfa2a6ffe79f9/lib/noun-project-api/retriever.rb#L7-L14
train
vaharoni/trusted-sandbox
lib/trusted_sandbox/uid_pool.rb
TrustedSandbox.UidPool.lock
def lock retries.times do atomically(timeout) do uid = available_uid if uid lock_uid uid return uid.to_i end end sleep(delay) end raise PoolTimeoutError.new('No available UIDs in the pool. Please try again later.') end
ruby
def lock retries.times do atomically(timeout) do uid = available_uid if uid lock_uid uid return uid.to_i end end sleep(delay) end raise PoolTimeoutError.new('No available UIDs in the pool. Please try again later.') end
[ "def", "lock", "retries", ".", "times", "do", "atomically", "(", "timeout", ")", "do", "uid", "=", "available_uid", "if", "uid", "lock_uid", "uid", "return", "uid", ".", "to_i", "end", "end", "sleep", "(", "delay", ")", "end", "raise", "PoolTimeoutError", ".", "new", "(", "'No available UIDs in the pool. Please try again later.'", ")", "end" ]
Locks one UID from the pool, in a cross-process atomic manner @return [Integer] @raise [PoolTimeoutError] if no ID is available after retries
[ "Locks", "one", "UID", "from", "the", "pool", "in", "a", "cross", "-", "process", "atomic", "manner" ]
e5d5e99bebfeab9e88c2512e30742b392bc09677
https://github.com/vaharoni/trusted-sandbox/blob/e5d5e99bebfeab9e88c2512e30742b392bc09677/lib/trusted_sandbox/uid_pool.rb#L56-L68
train
vaharoni/trusted-sandbox
lib/trusted_sandbox/response.rb
TrustedSandbox.Response.parse!
def parse! unless File.exists? output_file_path @status = 'error' @error = ContainerError.new('User code did not finish properly') @error_to_raise = @error return end begin data = File.binread output_file_path @raw_response = Marshal.load(data) rescue => e @status = 'error' @error = e @error_to_raise = ContainerError.new(e) return end unless ['success', 'error'].include? @raw_response[:status] @status = 'error' @error = InternalError.new('Output file has invalid format') @error_to_raise = @error return end @status = @raw_response[:status] @output = @raw_response[:output] @error = @raw_response[:error] @error_to_raise = UserCodeError.new(@error) if @error nil end
ruby
def parse! unless File.exists? output_file_path @status = 'error' @error = ContainerError.new('User code did not finish properly') @error_to_raise = @error return end begin data = File.binread output_file_path @raw_response = Marshal.load(data) rescue => e @status = 'error' @error = e @error_to_raise = ContainerError.new(e) return end unless ['success', 'error'].include? @raw_response[:status] @status = 'error' @error = InternalError.new('Output file has invalid format') @error_to_raise = @error return end @status = @raw_response[:status] @output = @raw_response[:output] @error = @raw_response[:error] @error_to_raise = UserCodeError.new(@error) if @error nil end
[ "def", "parse!", "unless", "File", ".", "exists?", "output_file_path", "@status", "=", "'error'", "@error", "=", "ContainerError", ".", "new", "(", "'User code did not finish properly'", ")", "@error_to_raise", "=", "@error", "return", "end", "begin", "data", "=", "File", ".", "binread", "output_file_path", "@raw_response", "=", "Marshal", ".", "load", "(", "data", ")", "rescue", "=>", "e", "@status", "=", "'error'", "@error", "=", "e", "@error_to_raise", "=", "ContainerError", ".", "new", "(", "e", ")", "return", "end", "unless", "[", "'success'", ",", "'error'", "]", ".", "include?", "@raw_response", "[", ":status", "]", "@status", "=", "'error'", "@error", "=", "InternalError", ".", "new", "(", "'Output file has invalid format'", ")", "@error_to_raise", "=", "@error", "return", "end", "@status", "=", "@raw_response", "[", ":status", "]", "@output", "=", "@raw_response", "[", ":output", "]", "@error", "=", "@raw_response", "[", ":error", "]", "@error_to_raise", "=", "UserCodeError", ".", "new", "(", "@error", ")", "if", "@error", "nil", "end" ]
Parses the output file and stores the values in the appropriate ivars @return [nil]
[ "Parses", "the", "output", "file", "and", "stores", "the", "values", "in", "the", "appropriate", "ivars" ]
e5d5e99bebfeab9e88c2512e30742b392bc09677
https://github.com/vaharoni/trusted-sandbox/blob/e5d5e99bebfeab9e88c2512e30742b392bc09677/lib/trusted_sandbox/response.rb#L64-L94
train
trishume/pro
lib/pro/commands.rb
Pro.Commands.find_repo
def find_repo(name) return @index.base_dirs.first unless name match = FuzzyMatch.new(@index.to_a, :read => :name).find(name) match[1] unless match.nil? end
ruby
def find_repo(name) return @index.base_dirs.first unless name match = FuzzyMatch.new(@index.to_a, :read => :name).find(name) match[1] unless match.nil? end
[ "def", "find_repo", "(", "name", ")", "return", "@index", ".", "base_dirs", ".", "first", "unless", "name", "match", "=", "FuzzyMatch", ".", "new", "(", "@index", ".", "to_a", ",", ":read", "=>", ":name", ")", ".", "find", "(", "name", ")", "match", "[", "1", "]", "unless", "match", ".", "nil?", "end" ]
Fuzzy search for a git repository by name Returns the full path to the repository. If name is nil return the pro base.
[ "Fuzzy", "search", "for", "a", "git", "repository", "by", "name", "Returns", "the", "full", "path", "to", "the", "repository", "." ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L46-L50
train
trishume/pro
lib/pro/commands.rb
Pro.Commands.status
def status() max_name = @index.map {|repo| repo.name.length}.max + 1 @index.each do |r| next unless Dir.exists?(r.path) status = repo_status(r.path) next if status.empty? name = format("%-#{max_name}s",r.name).bold puts "#{name} > #{status}" end end
ruby
def status() max_name = @index.map {|repo| repo.name.length}.max + 1 @index.each do |r| next unless Dir.exists?(r.path) status = repo_status(r.path) next if status.empty? name = format("%-#{max_name}s",r.name).bold puts "#{name} > #{status}" end end
[ "def", "status", "(", ")", "max_name", "=", "@index", ".", "map", "{", "|", "repo", "|", "repo", ".", "name", ".", "length", "}", ".", "max", "+", "1", "@index", ".", "each", "do", "|", "r", "|", "next", "unless", "Dir", ".", "exists?", "(", "r", ".", "path", ")", "status", "=", "repo_status", "(", "r", ".", "path", ")", "next", "if", "status", ".", "empty?", "name", "=", "format", "(", "\"%-#{max_name}s\"", ",", "r", ".", "name", ")", ".", "bold", "puts", "\"#{name} > #{status}\"", "end", "end" ]
prints a status list showing repos with unpushed commits or uncommitted changes
[ "prints", "a", "status", "list", "showing", "repos", "with", "unpushed", "commits", "or", "uncommitted", "changes" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L88-L97
train
trishume/pro
lib/pro/commands.rb
Pro.Commands.repo_status
def repo_status(path) messages = [] messages << EMPTY_MESSAGE if repo_empty?(path) messages << UNCOMMITTED_MESSAGE if commit_pending?(path) messages << UNTRACKED_MESSAGE if untracked_files?(path) messages << UNPUSHED_MESSAGE if repo_unpushed?(path) messages.join(JOIN_STRING) end
ruby
def repo_status(path) messages = [] messages << EMPTY_MESSAGE if repo_empty?(path) messages << UNCOMMITTED_MESSAGE if commit_pending?(path) messages << UNTRACKED_MESSAGE if untracked_files?(path) messages << UNPUSHED_MESSAGE if repo_unpushed?(path) messages.join(JOIN_STRING) end
[ "def", "repo_status", "(", "path", ")", "messages", "=", "[", "]", "messages", "<<", "EMPTY_MESSAGE", "if", "repo_empty?", "(", "path", ")", "messages", "<<", "UNCOMMITTED_MESSAGE", "if", "commit_pending?", "(", "path", ")", "messages", "<<", "UNTRACKED_MESSAGE", "if", "untracked_files?", "(", "path", ")", "messages", "<<", "UNPUSHED_MESSAGE", "if", "repo_unpushed?", "(", "path", ")", "messages", ".", "join", "(", "JOIN_STRING", ")", "end" ]
returns a short status message for the repo
[ "returns", "a", "short", "status", "message", "for", "the", "repo" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L100-L107
train
trishume/pro
lib/pro/commands.rb
Pro.Commands.install_cd
def install_cd puts CD_INFO print "Continue with installation (yN)? " return unless gets.chomp.downcase == "y" # get name print "Name of pro cd command (default 'pd'): " name = gets.strip name = 'pd' if name.empty? # sub into function func = SHELL_FUNCTION.sub("{{name}}",name) did_any = false ['~/.profile', '~/.bashrc','~/.zshrc','~/.bash_profile'].each do |rel_path| # check if file exists path = File.expand_path(rel_path) next unless File.exists?(path) # ask the user if they want to add it print "Install #{name} function to #{rel_path} [yN]: " next unless gets.chomp.downcase == "y" # add it on to the end of the file File.open(path,'a') do |file| file.puts func end did_any = true end if did_any puts "Done! #{name} will be available in new shells." else STDERR.puts "WARNING: Did not install in any shell dotfiles.".red STDERR.puts "Maybe you should create the shell config file you want.".red end end
ruby
def install_cd puts CD_INFO print "Continue with installation (yN)? " return unless gets.chomp.downcase == "y" # get name print "Name of pro cd command (default 'pd'): " name = gets.strip name = 'pd' if name.empty? # sub into function func = SHELL_FUNCTION.sub("{{name}}",name) did_any = false ['~/.profile', '~/.bashrc','~/.zshrc','~/.bash_profile'].each do |rel_path| # check if file exists path = File.expand_path(rel_path) next unless File.exists?(path) # ask the user if they want to add it print "Install #{name} function to #{rel_path} [yN]: " next unless gets.chomp.downcase == "y" # add it on to the end of the file File.open(path,'a') do |file| file.puts func end did_any = true end if did_any puts "Done! #{name} will be available in new shells." else STDERR.puts "WARNING: Did not install in any shell dotfiles.".red STDERR.puts "Maybe you should create the shell config file you want.".red end end
[ "def", "install_cd", "puts", "CD_INFO", "print", "\"Continue with installation (yN)? \"", "return", "unless", "gets", ".", "chomp", ".", "downcase", "==", "\"y\"", "print", "\"Name of pro cd command (default 'pd'): \"", "name", "=", "gets", ".", "strip", "name", "=", "'pd'", "if", "name", ".", "empty?", "func", "=", "SHELL_FUNCTION", ".", "sub", "(", "\"{{name}}\"", ",", "name", ")", "did_any", "=", "false", "[", "'~/.profile'", ",", "'~/.bashrc'", ",", "'~/.zshrc'", ",", "'~/.bash_profile'", "]", ".", "each", "do", "|", "rel_path", "|", "path", "=", "File", ".", "expand_path", "(", "rel_path", ")", "next", "unless", "File", ".", "exists?", "(", "path", ")", "print", "\"Install #{name} function to #{rel_path} [yN]: \"", "next", "unless", "gets", ".", "chomp", ".", "downcase", "==", "\"y\"", "File", ".", "open", "(", "path", ",", "'a'", ")", "do", "|", "file", "|", "file", ".", "puts", "func", "end", "did_any", "=", "true", "end", "if", "did_any", "puts", "\"Done! #{name} will be available in new shells.\"", "else", "STDERR", ".", "puts", "\"WARNING: Did not install in any shell dotfiles.\"", ".", "red", "STDERR", ".", "puts", "\"Maybe you should create the shell config file you want.\"", ".", "red", "end", "end" ]
Adds a shell function to the shell config files that allows easy directory changing.
[ "Adds", "a", "shell", "function", "to", "the", "shell", "config", "files", "that", "allows", "easy", "directory", "changing", "." ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/commands.rb#L149-L179
train
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.read_cache
def read_cache return nil unless File.readable_real?(CACHE_PATH) index = YAML::load_file(CACHE_PATH) return nil unless index.created_version == Pro::VERSION return nil unless index.base_dirs == @base_dirs index end
ruby
def read_cache return nil unless File.readable_real?(CACHE_PATH) index = YAML::load_file(CACHE_PATH) return nil unless index.created_version == Pro::VERSION return nil unless index.base_dirs == @base_dirs index end
[ "def", "read_cache", "return", "nil", "unless", "File", ".", "readable_real?", "(", "CACHE_PATH", ")", "index", "=", "YAML", "::", "load_file", "(", "CACHE_PATH", ")", "return", "nil", "unless", "index", ".", "created_version", "==", "Pro", "::", "VERSION", "return", "nil", "unless", "index", ".", "base_dirs", "==", "@base_dirs", "index", "end" ]
unserializes the cache file and returns the index object
[ "unserializes", "the", "cache", "file", "and", "returns", "the", "index", "object" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L28-L34
train
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.run_index_process
def run_index_process readme, writeme = IO.pipe p1 = fork { # Stop cd function from blocking on fork STDOUT.reopen(writeme) readme.close index_process unless File.exists?(INDEXER_LOCK_PATH) } Process.detach(p1) end
ruby
def run_index_process readme, writeme = IO.pipe p1 = fork { # Stop cd function from blocking on fork STDOUT.reopen(writeme) readme.close index_process unless File.exists?(INDEXER_LOCK_PATH) } Process.detach(p1) end
[ "def", "run_index_process", "readme", ",", "writeme", "=", "IO", ".", "pipe", "p1", "=", "fork", "{", "STDOUT", ".", "reopen", "(", "writeme", ")", "readme", ".", "close", "index_process", "unless", "File", ".", "exists?", "(", "INDEXER_LOCK_PATH", ")", "}", "Process", ".", "detach", "(", "p1", ")", "end" ]
spins off a background process to update the cache file
[ "spins", "off", "a", "background", "process", "to", "update", "the", "cache", "file" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L37-L47
train
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.cache_index
def cache_index(index) # TODO: atomic rename. Right now we just hope. File.open(CACHE_PATH, 'w' ) do |out| YAML::dump( index, out ) end end
ruby
def cache_index(index) # TODO: atomic rename. Right now we just hope. File.open(CACHE_PATH, 'w' ) do |out| YAML::dump( index, out ) end end
[ "def", "cache_index", "(", "index", ")", "File", ".", "open", "(", "CACHE_PATH", ",", "'w'", ")", "do", "|", "out", "|", "YAML", "::", "dump", "(", "index", ",", "out", ")", "end", "end" ]
serialize the index to a cache file
[ "serialize", "the", "index", "to", "a", "cache", "file" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L70-L75
train
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.index_repos_slow
def index_repos_slow(base) STDERR.puts "WARNING: pro is indexing slowly, please install the 'find' command." repos = [] Find.find(base) do |path| target = path # additionally, index repos symlinked directly from a base root if FileTest.symlink?(path) next if File.dirname(path) != base target = File.readlink(path) end # dir must exist and be a git repo if FileTest.directory?(target) && File.exists?(path+"/.git") base_name = File.basename(path) repos << Repo.new(base_name,path) Find.prune end end repos end
ruby
def index_repos_slow(base) STDERR.puts "WARNING: pro is indexing slowly, please install the 'find' command." repos = [] Find.find(base) do |path| target = path # additionally, index repos symlinked directly from a base root if FileTest.symlink?(path) next if File.dirname(path) != base target = File.readlink(path) end # dir must exist and be a git repo if FileTest.directory?(target) && File.exists?(path+"/.git") base_name = File.basename(path) repos << Repo.new(base_name,path) Find.prune end end repos end
[ "def", "index_repos_slow", "(", "base", ")", "STDERR", ".", "puts", "\"WARNING: pro is indexing slowly, please install the 'find' command.\"", "repos", "=", "[", "]", "Find", ".", "find", "(", "base", ")", "do", "|", "path", "|", "target", "=", "path", "if", "FileTest", ".", "symlink?", "(", "path", ")", "next", "if", "File", ".", "dirname", "(", "path", ")", "!=", "base", "target", "=", "File", ".", "readlink", "(", "path", ")", "end", "if", "FileTest", ".", "directory?", "(", "target", ")", "&&", "File", ".", "exists?", "(", "path", "+", "\"/.git\"", ")", "base_name", "=", "File", ".", "basename", "(", "path", ")", "repos", "<<", "Repo", ".", "new", "(", "base_name", ",", "path", ")", "Find", ".", "prune", "end", "end", "repos", "end" ]
recursive walk in ruby
[ "recursive", "walk", "in", "ruby" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L129-L147
train
trishume/pro
lib/pro/indexer.rb
Pro.Indexer.find_base_dirs
def find_base_dirs() bases = [] # check environment first base = ENV['PRO_BASE'] bases << base if base # next check proBase file path = ENV['HOME'] + "/.proBase" if File.exists?(path) # read lines of the pro base file bases += IO.read(path).split("\n").map {|p| File.expand_path(p.strip)} end # strip bases that do not exist # I know about select! but it doesn't exist in 1.8 bases = bases.select {|b| File.exists?(b)} # if no bases then return home bases << ENV['HOME'] if bases.empty? bases end
ruby
def find_base_dirs() bases = [] # check environment first base = ENV['PRO_BASE'] bases << base if base # next check proBase file path = ENV['HOME'] + "/.proBase" if File.exists?(path) # read lines of the pro base file bases += IO.read(path).split("\n").map {|p| File.expand_path(p.strip)} end # strip bases that do not exist # I know about select! but it doesn't exist in 1.8 bases = bases.select {|b| File.exists?(b)} # if no bases then return home bases << ENV['HOME'] if bases.empty? bases end
[ "def", "find_base_dirs", "(", ")", "bases", "=", "[", "]", "base", "=", "ENV", "[", "'PRO_BASE'", "]", "bases", "<<", "base", "if", "base", "path", "=", "ENV", "[", "'HOME'", "]", "+", "\"/.proBase\"", "if", "File", ".", "exists?", "(", "path", ")", "bases", "+=", "IO", ".", "read", "(", "path", ")", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "p", "|", "File", ".", "expand_path", "(", "p", ".", "strip", ")", "}", "end", "bases", "=", "bases", ".", "select", "{", "|", "b", "|", "File", ".", "exists?", "(", "b", ")", "}", "bases", "<<", "ENV", "[", "'HOME'", "]", "if", "bases", ".", "empty?", "bases", "end" ]
Finds the base directory where repos are kept Checks the environment variable PRO_BASE and the file .proBase
[ "Finds", "the", "base", "directory", "where", "repos", "are", "kept", "Checks", "the", "environment", "variable", "PRO_BASE", "and", "the", "file", ".", "proBase" ]
646098c7514eb5346dd2942f90b888c0de30b6ba
https://github.com/trishume/pro/blob/646098c7514eb5346dd2942f90b888c0de30b6ba/lib/pro/indexer.rb#L152-L169
train
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.artifact_sign
def artifact_sign @signature = 'unsigned' # Clean up the existing signature file signature_cleanup Dir.chdir("#{$config['general']['app_cache']}/artifacts/") do # Generate the signature file and pick up the signature data unless system "gpg --use-agent --detach-sign artifact.#{@checksum}.tar.gz" $logger.error 'Unable to sign the artifact, an unexpected failure occured. No file uploaded.' return false end if File.exist?("artifact.#{@checksum}.tar.gz.sig") $logger.info 'A signature file was successfully generated.' else $logger.error 'A signature file was NOT generated.' return false end # Convert the signature into base64. It's easier to bundle all the # metadata into a single file and extracting it out when needed, than # having to keep track of yet-another-file. Because we encode into # ASCII here, no need to call GPG with --armor either. @signature = Base64.encode64(File.read("artifact.#{@checksum}.tar.gz.sig")) unless @signature $logger.error 'An unexpected issue occured and no signature was generated' return false end end # Make sure the public key has been uploaded if it hasn't already pubkey_upload @signature end
ruby
def artifact_sign @signature = 'unsigned' # Clean up the existing signature file signature_cleanup Dir.chdir("#{$config['general']['app_cache']}/artifacts/") do # Generate the signature file and pick up the signature data unless system "gpg --use-agent --detach-sign artifact.#{@checksum}.tar.gz" $logger.error 'Unable to sign the artifact, an unexpected failure occured. No file uploaded.' return false end if File.exist?("artifact.#{@checksum}.tar.gz.sig") $logger.info 'A signature file was successfully generated.' else $logger.error 'A signature file was NOT generated.' return false end # Convert the signature into base64. It's easier to bundle all the # metadata into a single file and extracting it out when needed, than # having to keep track of yet-another-file. Because we encode into # ASCII here, no need to call GPG with --armor either. @signature = Base64.encode64(File.read("artifact.#{@checksum}.tar.gz.sig")) unless @signature $logger.error 'An unexpected issue occured and no signature was generated' return false end end # Make sure the public key has been uploaded if it hasn't already pubkey_upload @signature end
[ "def", "artifact_sign", "@signature", "=", "'unsigned'", "signature_cleanup", "Dir", ".", "chdir", "(", "\"#{$config['general']['app_cache']}/artifacts/\"", ")", "do", "unless", "system", "\"gpg --use-agent --detach-sign artifact.#{@checksum}.tar.gz\"", "$logger", ".", "error", "'Unable to sign the artifact, an unexpected failure occured. No file uploaded.'", "return", "false", "end", "if", "File", ".", "exist?", "(", "\"artifact.#{@checksum}.tar.gz.sig\"", ")", "$logger", ".", "info", "'A signature file was successfully generated.'", "else", "$logger", ".", "error", "'A signature file was NOT generated.'", "return", "false", "end", "@signature", "=", "Base64", ".", "encode64", "(", "File", ".", "read", "(", "\"artifact.#{@checksum}.tar.gz.sig\"", ")", ")", "unless", "@signature", "$logger", ".", "error", "'An unexpected issue occured and no signature was generated'", "return", "false", "end", "end", "pubkey_upload", "@signature", "end" ]
Sign the artifact and return the signature. Does not validation of the signature. false Failure base64 Encoded signature
[ "Sign", "the", "artifact", "and", "return", "the", "signature", ".", "Does", "not", "validation", "of", "the", "signature", "." ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L37-L74
train
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.signature_extract
def signature_extract manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) if manifest['gpgsig'] # We have the base64 version @signature = manifest['gpgsig'] # Decode the base64 and write the signature file File.write("#{$config['general']['app_cache']}/artifacts/artifact.#{@checksum}.tar.gz.sig", Base64.decode64(@signature)) return @signature else return false end rescue StandardError => e $logger.error 'Something unexpected occured when reading the manifest file' raise e end
ruby
def signature_extract manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) if manifest['gpgsig'] # We have the base64 version @signature = manifest['gpgsig'] # Decode the base64 and write the signature file File.write("#{$config['general']['app_cache']}/artifacts/artifact.#{@checksum}.tar.gz.sig", Base64.decode64(@signature)) return @signature else return false end rescue StandardError => e $logger.error 'Something unexpected occured when reading the manifest file' raise e end
[ "def", "signature_extract", "manifest", "=", "YAML", ".", "load", "(", "File", ".", "open", "(", "$config", "[", "'general'", "]", "[", "'app_cache'", "]", "+", "\"/artifacts/manifest.#{@checksum}.yaml\"", ")", ",", "safe", ":", "true", ",", "raise_on_unknown_tag", ":", "true", ")", "if", "manifest", "[", "'gpgsig'", "]", "@signature", "=", "manifest", "[", "'gpgsig'", "]", "File", ".", "write", "(", "\"#{$config['general']['app_cache']}/artifacts/artifact.#{@checksum}.tar.gz.sig\"", ",", "Base64", ".", "decode64", "(", "@signature", ")", ")", "return", "@signature", "else", "return", "false", "end", "rescue", "StandardError", "=>", "e", "$logger", ".", "error", "'Something unexpected occured when reading the manifest file'", "raise", "e", "end" ]
Extract the signature from the manifest file and write it to file in native binary format. false Unable to extract unsigned Manifest shows that the artifact is not signed base64 Encoded signature
[ "Extract", "the", "signature", "from", "the", "manifest", "file", "and", "write", "it", "to", "file", "in", "native", "binary", "format", "." ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L136-L154
train
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.signature_save
def signature_save manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) manifest['gpgsig'] = @signature File.open("#{$config['general']['app_cache']}/artifacts/manifest.#{@checksum}.yaml", 'w') do |fh| fh.write YAML.dump(manifest) end return true rescue StandardError $logger.error 'Something unexpected occured when updating the manifest file with GPG signature' return false end
ruby
def signature_save manifest = YAML.load(File.open($config['general']['app_cache'] + "/artifacts/manifest.#{@checksum}.yaml"), safe: true, raise_on_unknown_tag: true) manifest['gpgsig'] = @signature File.open("#{$config['general']['app_cache']}/artifacts/manifest.#{@checksum}.yaml", 'w') do |fh| fh.write YAML.dump(manifest) end return true rescue StandardError $logger.error 'Something unexpected occured when updating the manifest file with GPG signature' return false end
[ "def", "signature_save", "manifest", "=", "YAML", ".", "load", "(", "File", ".", "open", "(", "$config", "[", "'general'", "]", "[", "'app_cache'", "]", "+", "\"/artifacts/manifest.#{@checksum}.yaml\"", ")", ",", "safe", ":", "true", ",", "raise_on_unknown_tag", ":", "true", ")", "manifest", "[", "'gpgsig'", "]", "=", "@signature", "File", ".", "open", "(", "\"#{$config['general']['app_cache']}/artifacts/manifest.#{@checksum}.yaml\"", ",", "'w'", ")", "do", "|", "fh", "|", "fh", ".", "write", "YAML", ".", "dump", "(", "manifest", ")", "end", "return", "true", "rescue", "StandardError", "$logger", ".", "error", "'Something unexpected occured when updating the manifest file with GPG signature'", "return", "false", "end" ]
Save the signature into the manifest file
[ "Save", "the", "signature", "into", "the", "manifest", "file" ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L158-L171
train
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.pubkey_upload
def pubkey_upload unless File.exist?("#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey") # GPG key does not exist locally, we therefore assume it's not in the S3 # bucket either, so we should export out and upload. Technically this may # result in a few extra uploads (once for any new machine using Pupistry) # but it doesn't cause any issue and saves me writing more code ;-) $logger.info "Exporting GPG key #{$config['general']['gpg_signing_key']} and uploading to S3 bucket..." # If it doesn't exist on this machine, then we're a bit stuck! unless pubkey_exist? $logger.error "The public key #{$config['general']['gpg_signing_key']} does not exist on this system, so unable to export it out" return false end # Export out key unless system "gpg --export --armour 0x#{$config['general']['gpg_signing_key']} > #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'A fault occured when trying to export the GPG key' return false end # Upload s3 = Pupistry::StorageAWS.new 'build' unless s3.upload "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to upload GPG key to S3 bucket' return false end end end
ruby
def pubkey_upload unless File.exist?("#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey") # GPG key does not exist locally, we therefore assume it's not in the S3 # bucket either, so we should export out and upload. Technically this may # result in a few extra uploads (once for any new machine using Pupistry) # but it doesn't cause any issue and saves me writing more code ;-) $logger.info "Exporting GPG key #{$config['general']['gpg_signing_key']} and uploading to S3 bucket..." # If it doesn't exist on this machine, then we're a bit stuck! unless pubkey_exist? $logger.error "The public key #{$config['general']['gpg_signing_key']} does not exist on this system, so unable to export it out" return false end # Export out key unless system "gpg --export --armour 0x#{$config['general']['gpg_signing_key']} > #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'A fault occured when trying to export the GPG key' return false end # Upload s3 = Pupistry::StorageAWS.new 'build' unless s3.upload "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to upload GPG key to S3 bucket' return false end end end
[ "def", "pubkey_upload", "unless", "File", ".", "exist?", "(", "\"#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", ")", "$logger", ".", "info", "\"Exporting GPG key #{$config['general']['gpg_signing_key']} and uploading to S3 bucket...\"", "unless", "pubkey_exist?", "$logger", ".", "error", "\"The public key #{$config['general']['gpg_signing_key']} does not exist on this system, so unable to export it out\"", "return", "false", "end", "unless", "system", "\"gpg --export --armour 0x#{$config['general']['gpg_signing_key']} > #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", "$logger", ".", "error", "'A fault occured when trying to export the GPG key'", "return", "false", "end", "s3", "=", "Pupistry", "::", "StorageAWS", ".", "new", "'build'", "unless", "s3", ".", "upload", "\"#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", ",", "\"#{$config['general']['gpg_signing_key']}.publickey\"", "$logger", ".", "error", "'Unable to upload GPG key to S3 bucket'", "return", "false", "end", "end", "end" ]
Extract & upload the public key to the s3 bucket for other users
[ "Extract", "&", "upload", "the", "public", "key", "to", "the", "s3", "bucket", "for", "other", "users" ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L188-L219
train
jethrocarr/pupistry
lib/pupistry/gpg.rb
Pupistry.GPG.pubkey_install
def pubkey_install $logger.warn "Installing GPG key #{$config['general']['gpg_signing_key']}..." s3 = Pupistry::StorageAWS.new 'agent' unless s3.download "#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to download GPG key from S3 bucket, this will prevent validation of signature' return false end unless system "gpg --import < #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey > /dev/null 2>&1" $logger.error 'A fault occured when trying to import the GPG key' return false end rescue StandardError $logger.error 'Something unexpected occured when installing the GPG public key' return false end
ruby
def pubkey_install $logger.warn "Installing GPG key #{$config['general']['gpg_signing_key']}..." s3 = Pupistry::StorageAWS.new 'agent' unless s3.download "#{$config['general']['gpg_signing_key']}.publickey", "#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey" $logger.error 'Unable to download GPG key from S3 bucket, this will prevent validation of signature' return false end unless system "gpg --import < #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey > /dev/null 2>&1" $logger.error 'A fault occured when trying to import the GPG key' return false end rescue StandardError $logger.error 'Something unexpected occured when installing the GPG public key' return false end
[ "def", "pubkey_install", "$logger", ".", "warn", "\"Installing GPG key #{$config['general']['gpg_signing_key']}...\"", "s3", "=", "Pupistry", "::", "StorageAWS", ".", "new", "'agent'", "unless", "s3", ".", "download", "\"#{$config['general']['gpg_signing_key']}.publickey\"", ",", "\"#{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey\"", "$logger", ".", "error", "'Unable to download GPG key from S3 bucket, this will prevent validation of signature'", "return", "false", "end", "unless", "system", "\"gpg --import < #{$config['general']['app_cache']}/artifacts/#{$config['general']['gpg_signing_key']}.publickey > /dev/null 2>&1\"", "$logger", ".", "error", "'A fault occured when trying to import the GPG key'", "return", "false", "end", "rescue", "StandardError", "$logger", ".", "error", "'Something unexpected occured when installing the GPG public key'", "return", "false", "end" ]
Install the public key. This is a potential avenue for exploit, if a machine is being built for the first time, it has no existing trust of the GPG key, other than transit encryption to the S3 bucket. To protect against attacks at the bootstrap time, you should pre-load your machine images with the public GPG key. For those users who trade off some security for convienence, we install the GPG public key for them direct from the S3 repo.
[ "Install", "the", "public", "key", ".", "This", "is", "a", "potential", "avenue", "for", "exploit", "if", "a", "machine", "is", "being", "built", "for", "the", "first", "time", "it", "has", "no", "existing", "trust", "of", "the", "GPG", "key", "other", "than", "transit", "encryption", "to", "the", "S3", "bucket", ".", "To", "protect", "against", "attacks", "at", "the", "bootstrap", "time", "you", "should", "pre", "-", "load", "your", "machine", "images", "with", "the", "public", "GPG", "key", "." ]
a80e7a3d01f68ef4544e047719bfe14c5f75235d
https://github.com/jethrocarr/pupistry/blob/a80e7a3d01f68ef4544e047719bfe14c5f75235d/lib/pupistry/gpg.rb#L230-L248
train
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.wip=
def wip=(pr) label_names = [] labels.each do |label| label_names << label.name end puts("exist labels:" + label_names.join(", ")) unless wip? begin add_label("WIP") rescue Octokit::UnprocessableEntity => e puts "WIP label is already exists." puts e end end github.api.add_labels_to_an_issue(repo, pr, [wip_label]) end
ruby
def wip=(pr) label_names = [] labels.each do |label| label_names << label.name end puts("exist labels:" + label_names.join(", ")) unless wip? begin add_label("WIP") rescue Octokit::UnprocessableEntity => e puts "WIP label is already exists." puts e end end github.api.add_labels_to_an_issue(repo, pr, [wip_label]) end
[ "def", "wip", "=", "(", "pr", ")", "label_names", "=", "[", "]", "labels", ".", "each", "do", "|", "label", "|", "label_names", "<<", "label", ".", "name", "end", "puts", "(", "\"exist labels:\"", "+", "label_names", ".", "join", "(", "\", \"", ")", ")", "unless", "wip?", "begin", "add_label", "(", "\"WIP\"", ")", "rescue", "Octokit", "::", "UnprocessableEntity", "=>", "e", "puts", "\"WIP label is already exists.\"", "puts", "e", "end", "end", "github", ".", "api", ".", "add_labels_to_an_issue", "(", "repo", ",", "pr", ",", "[", "wip_label", "]", ")", "end" ]
Set WIP label to PR. @param [Number] pr A number of issue or pull request for set label. @return [void]
[ "Set", "WIP", "label", "to", "PR", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L21-L36
train
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.set
def set(pr, name, color) message = "" if label?(name) message = "Set #{name} label. (Color: #{color})" else message = "Add #{name} new label. (Color: #{color})" add_label(name, color) end github.api.add_labels_to_an_issue(repo, pr, [name]) puts message end
ruby
def set(pr, name, color) message = "" if label?(name) message = "Set #{name} label. (Color: #{color})" else message = "Add #{name} new label. (Color: #{color})" add_label(name, color) end github.api.add_labels_to_an_issue(repo, pr, [name]) puts message end
[ "def", "set", "(", "pr", ",", "name", ",", "color", ")", "message", "=", "\"\"", "if", "label?", "(", "name", ")", "message", "=", "\"Set #{name} label. (Color: #{color})\"", "else", "message", "=", "\"Add #{name} new label. (Color: #{color})\"", "add_label", "(", "name", ",", "color", ")", "end", "github", ".", "api", ".", "add_labels_to_an_issue", "(", "repo", ",", "pr", ",", "[", "name", "]", ")", "puts", "message", "end" ]
Set any labels to PR by this. @param [Number] pr A number of issue or pull request for set label. @param [String] name A new label name. @param [String] color A color, in hex, without the leading #. Default is "fef2c0" @return [void]
[ "Set", "any", "labels", "to", "PR", "by", "this", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L46-L56
train
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.delete
def delete(name) begin github.api.delete_label!(repo, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
ruby
def delete(name) begin github.api.delete_label!(repo, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
[ "def", "delete", "(", "name", ")", "begin", "github", ".", "api", ".", "delete_label!", "(", "repo", ",", "name", ")", "rescue", "Octokit", "::", "Error", "=>", "e", "puts", "\"Error message: \\\"#{name}\\\" label is not existing.\"", "puts", "e", "end", "end" ]
Delete label from repository. @param [String] name Delete label name. @return [void]
[ "Delete", "label", "from", "repository", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L62-L69
train
kaelaela/danger-auto_label
lib/auto_label/plugin.rb
Danger.DangerAutoLabel.remove
def remove(name) begin github.api.remove_label(repo, number, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
ruby
def remove(name) begin github.api.remove_label(repo, number, name) rescue Octokit::Error => e puts "Error message: \"#{name}\" label is not existing." puts e end end
[ "def", "remove", "(", "name", ")", "begin", "github", ".", "api", ".", "remove_label", "(", "repo", ",", "number", ",", "name", ")", "rescue", "Octokit", "::", "Error", "=>", "e", "puts", "\"Error message: \\\"#{name}\\\" label is not existing.\"", "puts", "e", "end", "end" ]
Remove label from PR. @param [String] name Remove label name. @return [void]
[ "Remove", "label", "from", "PR", "." ]
f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4
https://github.com/kaelaela/danger-auto_label/blob/f07eb95ec9933e9fb16040cb5d618a4d7d3e5fc4/lib/auto_label/plugin.rb#L75-L82
train
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.diff
def diff(cov1, cov2) ncov = {} old_format = true cov1.each do |path1, runs1| if cov2[path1] runs2 = cov2[path1] if runs1.is_a?(Array) && runs2.is_a?(Array) && old_format # diff two old-format (ruby 2.4 or before) coverage results ncov[path1] = diff_lines(runs1, runs2) next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if runs2.is_a?(Array) runs2 = { :lines => runs2 } end if old_format old_format = false old2new!(ncov) end # diff two new-format (ruby 2.5 or later) coverage results ncov[path1] = {} [ [:lines, :diff_lines], [:branches, :diff_branches], [:methods, :diff_methods], ].each do |type, diff_func| if runs1[type] if runs2[type] ncov[path1][type] = send(diff_func, runs1[type], runs2[type]) else ncov[path1][type] = runs1[type] end end end else if runs1.is_a?(Array) && old_format ncov[path1] = runs1 next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if old_format old_format = false old2new!(ncov) end ncov[path1] = runs1 end end ncov end
ruby
def diff(cov1, cov2) ncov = {} old_format = true cov1.each do |path1, runs1| if cov2[path1] runs2 = cov2[path1] if runs1.is_a?(Array) && runs2.is_a?(Array) && old_format # diff two old-format (ruby 2.4 or before) coverage results ncov[path1] = diff_lines(runs1, runs2) next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if runs2.is_a?(Array) runs2 = { :lines => runs2 } end if old_format old_format = false old2new!(ncov) end # diff two new-format (ruby 2.5 or later) coverage results ncov[path1] = {} [ [:lines, :diff_lines], [:branches, :diff_branches], [:methods, :diff_methods], ].each do |type, diff_func| if runs1[type] if runs2[type] ncov[path1][type] = send(diff_func, runs1[type], runs2[type]) else ncov[path1][type] = runs1[type] end end end else if runs1.is_a?(Array) && old_format ncov[path1] = runs1 next end # promotes from old format to new one if runs1.is_a?(Array) runs1 = { :lines => runs1 } end if old_format old_format = false old2new!(ncov) end ncov[path1] = runs1 end end ncov end
[ "def", "diff", "(", "cov1", ",", "cov2", ")", "ncov", "=", "{", "}", "old_format", "=", "true", "cov1", ".", "each", "do", "|", "path1", ",", "runs1", "|", "if", "cov2", "[", "path1", "]", "runs2", "=", "cov2", "[", "path1", "]", "if", "runs1", ".", "is_a?", "(", "Array", ")", "&&", "runs2", ".", "is_a?", "(", "Array", ")", "&&", "old_format", "ncov", "[", "path1", "]", "=", "diff_lines", "(", "runs1", ",", "runs2", ")", "next", "end", "if", "runs1", ".", "is_a?", "(", "Array", ")", "runs1", "=", "{", ":lines", "=>", "runs1", "}", "end", "if", "runs2", ".", "is_a?", "(", "Array", ")", "runs2", "=", "{", ":lines", "=>", "runs2", "}", "end", "if", "old_format", "old_format", "=", "false", "old2new!", "(", "ncov", ")", "end", "ncov", "[", "path1", "]", "=", "{", "}", "[", "[", ":lines", ",", ":diff_lines", "]", ",", "[", ":branches", ",", ":diff_branches", "]", ",", "[", ":methods", ",", ":diff_methods", "]", ",", "]", ".", "each", "do", "|", "type", ",", "diff_func", "|", "if", "runs1", "[", "type", "]", "if", "runs2", "[", "type", "]", "ncov", "[", "path1", "]", "[", "type", "]", "=", "send", "(", "diff_func", ",", "runs1", "[", "type", "]", ",", "runs2", "[", "type", "]", ")", "else", "ncov", "[", "path1", "]", "[", "type", "]", "=", "runs1", "[", "type", "]", "end", "end", "end", "else", "if", "runs1", ".", "is_a?", "(", "Array", ")", "&&", "old_format", "ncov", "[", "path1", "]", "=", "runs1", "next", "end", "if", "runs1", ".", "is_a?", "(", "Array", ")", "runs1", "=", "{", ":lines", "=>", "runs1", "}", "end", "if", "old_format", "old_format", "=", "false", "old2new!", "(", "ncov", ")", "end", "ncov", "[", "path1", "]", "=", "runs1", "end", "end", "ncov", "end" ]
Extract the coverage results that is covered by `cov1` but not covered by `cov2`.
[ "Extract", "the", "coverage", "results", "that", "is", "covered", "by", "cov1", "but", "not", "covered", "by", "cov2", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L114-L174
train
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.sanitize
def sanitize(cov) ncov = {} cov.each do |path, runs| if runs.is_a?(Array) ncov[path] = runs next end ncov[path] = {} ncov[path][:lines] = runs[:lines] if runs[:lines] ncov[path][:branches] = runs[:branches] if runs[:branches] if runs[:methods] ncov[path][:methods] = methods = {} runs[:methods].each do |mthd, run| klass = begin Marshal.dump(mthd[0]) mthd[0] rescue mthd[0].to_s end methods[[klass] + mthd.drop(1)] = run end end end ncov end
ruby
def sanitize(cov) ncov = {} cov.each do |path, runs| if runs.is_a?(Array) ncov[path] = runs next end ncov[path] = {} ncov[path][:lines] = runs[:lines] if runs[:lines] ncov[path][:branches] = runs[:branches] if runs[:branches] if runs[:methods] ncov[path][:methods] = methods = {} runs[:methods].each do |mthd, run| klass = begin Marshal.dump(mthd[0]) mthd[0] rescue mthd[0].to_s end methods[[klass] + mthd.drop(1)] = run end end end ncov end
[ "def", "sanitize", "(", "cov", ")", "ncov", "=", "{", "}", "cov", ".", "each", "do", "|", "path", ",", "runs", "|", "if", "runs", ".", "is_a?", "(", "Array", ")", "ncov", "[", "path", "]", "=", "runs", "next", "end", "ncov", "[", "path", "]", "=", "{", "}", "ncov", "[", "path", "]", "[", ":lines", "]", "=", "runs", "[", ":lines", "]", "if", "runs", "[", ":lines", "]", "ncov", "[", "path", "]", "[", ":branches", "]", "=", "runs", "[", ":branches", "]", "if", "runs", "[", ":branches", "]", "if", "runs", "[", ":methods", "]", "ncov", "[", "path", "]", "[", ":methods", "]", "=", "methods", "=", "{", "}", "runs", "[", ":methods", "]", ".", "each", "do", "|", "mthd", ",", "run", "|", "klass", "=", "begin", "Marshal", ".", "dump", "(", "mthd", "[", "0", "]", ")", "mthd", "[", "0", "]", "rescue", "mthd", "[", "0", "]", ".", "to_s", "end", "methods", "[", "[", "klass", "]", "+", "mthd", ".", "drop", "(", "1", ")", "]", "=", "run", "end", "end", "end", "ncov", "end" ]
Make the covearge result able to marshal.
[ "Make", "the", "covearge", "result", "able", "to", "marshal", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L177-L204
train
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.save
def save(path, cov) File.binwrite(path, Marshal.dump(sanitize(cov))) end
ruby
def save(path, cov) File.binwrite(path, Marshal.dump(sanitize(cov))) end
[ "def", "save", "(", "path", ",", "cov", ")", "File", ".", "binwrite", "(", "path", ",", "Marshal", ".", "dump", "(", "sanitize", "(", "cov", ")", ")", ")", "end" ]
Save the coverage result to a file.
[ "Save", "the", "coverage", "result", "to", "a", "file", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L207-L209
train
mame/coverage-helpers
lib/coverage/helpers.rb
Coverage.Helpers.to_lcov_info
def to_lcov_info(cov, out: "", test_name: nil) out << "TN:#{ test_name }\n" cov.each do |path, runs| out << "SF:#{ path }\n" # function coverage if runs.is_a?(Hash) && runs[:methods] total = covered = 0 runs[:methods].each do |(klass, name, lineno), run| out << "FN:#{ lineno },#{ klass }##{ name }\n" total += 1 covered += 1 if run > 0 end out << "FNF:#{ total }\n" out << "FNF:#{ covered }\n" runs[:methods].each do |(klass, name, _), run| out << "FNDA:#{ run },#{ klass }##{ name }\n" end end # line coverage if runs.is_a?(Array) || (runs.is_a?(Hash) && runs[:lines]) total = covered = 0 lines = runs.is_a?(Array) ? runs : runs[:lines] lines.each_with_index do |run, lineno| next unless run out << "DA:#{ lineno + 1 },#{ run }\n" total += 1 covered += 1 if run > 0 end out << "LF:#{ total }\n" out << "LH:#{ covered }\n" end # branch coverage if runs.is_a?(Hash) && runs[:branches] total = covered = 0 id = 0 runs[:branches].each do |(_base_type, _, base_lineno), targets| i = 0 targets.each do |(_target_type, _target_lineno), run| out << "BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\n" total += 1 covered += 1 if run > 0 i += 1 end id += 1 end out << "BRF:#{ total }\n" out << "BRH:#{ covered }\n" end out << "end_of_record\n" end out end
ruby
def to_lcov_info(cov, out: "", test_name: nil) out << "TN:#{ test_name }\n" cov.each do |path, runs| out << "SF:#{ path }\n" # function coverage if runs.is_a?(Hash) && runs[:methods] total = covered = 0 runs[:methods].each do |(klass, name, lineno), run| out << "FN:#{ lineno },#{ klass }##{ name }\n" total += 1 covered += 1 if run > 0 end out << "FNF:#{ total }\n" out << "FNF:#{ covered }\n" runs[:methods].each do |(klass, name, _), run| out << "FNDA:#{ run },#{ klass }##{ name }\n" end end # line coverage if runs.is_a?(Array) || (runs.is_a?(Hash) && runs[:lines]) total = covered = 0 lines = runs.is_a?(Array) ? runs : runs[:lines] lines.each_with_index do |run, lineno| next unless run out << "DA:#{ lineno + 1 },#{ run }\n" total += 1 covered += 1 if run > 0 end out << "LF:#{ total }\n" out << "LH:#{ covered }\n" end # branch coverage if runs.is_a?(Hash) && runs[:branches] total = covered = 0 id = 0 runs[:branches].each do |(_base_type, _, base_lineno), targets| i = 0 targets.each do |(_target_type, _target_lineno), run| out << "BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\n" total += 1 covered += 1 if run > 0 i += 1 end id += 1 end out << "BRF:#{ total }\n" out << "BRH:#{ covered }\n" end out << "end_of_record\n" end out end
[ "def", "to_lcov_info", "(", "cov", ",", "out", ":", "\"\"", ",", "test_name", ":", "nil", ")", "out", "<<", "\"TN:#{ test_name }\\n\"", "cov", ".", "each", "do", "|", "path", ",", "runs", "|", "out", "<<", "\"SF:#{ path }\\n\"", "if", "runs", ".", "is_a?", "(", "Hash", ")", "&&", "runs", "[", ":methods", "]", "total", "=", "covered", "=", "0", "runs", "[", ":methods", "]", ".", "each", "do", "|", "(", "klass", ",", "name", ",", "lineno", ")", ",", "run", "|", "out", "<<", "\"FN:#{ lineno },#{ klass }##{ name }\\n\"", "total", "+=", "1", "covered", "+=", "1", "if", "run", ">", "0", "end", "out", "<<", "\"FNF:#{ total }\\n\"", "out", "<<", "\"FNF:#{ covered }\\n\"", "runs", "[", ":methods", "]", ".", "each", "do", "|", "(", "klass", ",", "name", ",", "_", ")", ",", "run", "|", "out", "<<", "\"FNDA:#{ run },#{ klass }##{ name }\\n\"", "end", "end", "if", "runs", ".", "is_a?", "(", "Array", ")", "||", "(", "runs", ".", "is_a?", "(", "Hash", ")", "&&", "runs", "[", ":lines", "]", ")", "total", "=", "covered", "=", "0", "lines", "=", "runs", ".", "is_a?", "(", "Array", ")", "?", "runs", ":", "runs", "[", ":lines", "]", "lines", ".", "each_with_index", "do", "|", "run", ",", "lineno", "|", "next", "unless", "run", "out", "<<", "\"DA:#{ lineno + 1 },#{ run }\\n\"", "total", "+=", "1", "covered", "+=", "1", "if", "run", ">", "0", "end", "out", "<<", "\"LF:#{ total }\\n\"", "out", "<<", "\"LH:#{ covered }\\n\"", "end", "if", "runs", ".", "is_a?", "(", "Hash", ")", "&&", "runs", "[", ":branches", "]", "total", "=", "covered", "=", "0", "id", "=", "0", "runs", "[", ":branches", "]", ".", "each", "do", "|", "(", "_base_type", ",", "_", ",", "base_lineno", ")", ",", "targets", "|", "i", "=", "0", "targets", ".", "each", "do", "|", "(", "_target_type", ",", "_target_lineno", ")", ",", "run", "|", "out", "<<", "\"BRDA:#{ base_lineno },#{ id },#{ i },#{ run }\\n\"", "total", "+=", "1", "covered", "+=", "1", "if", "run", ">", "0", "i", "+=", "1", "end", "id", "+=", "1", "end", "out", "<<", "\"BRF:#{ total }\\n\"", "out", "<<", "\"BRH:#{ covered }\\n\"", "end", "out", "<<", "\"end_of_record\\n\"", "end", "out", "end" ]
Translate the result into LCOV info format.
[ "Translate", "the", "result", "into", "LCOV", "info", "format", "." ]
4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e
https://github.com/mame/coverage-helpers/blob/4d2a33d3dec8c8bbf51bb21a3cdaf57d2481472e/lib/coverage/helpers.rb#L217-L273
train
kymmt90/hatenablog
lib/hatenablog/entry.rb
Hatenablog.AfterHook.after_hook
def after_hook(hook, *methods) methods.each do |method| origin_method = "#{method}_origin".to_sym if instance_methods.include? origin_method raise NameError, "#{origin_method} isn't a unique name" end alias_method origin_method, method define_method(method) do |*args, &block| result = send(origin_method, *args, &block) send(hook) end end end
ruby
def after_hook(hook, *methods) methods.each do |method| origin_method = "#{method}_origin".to_sym if instance_methods.include? origin_method raise NameError, "#{origin_method} isn't a unique name" end alias_method origin_method, method define_method(method) do |*args, &block| result = send(origin_method, *args, &block) send(hook) end end end
[ "def", "after_hook", "(", "hook", ",", "*", "methods", ")", "methods", ".", "each", "do", "|", "method", "|", "origin_method", "=", "\"#{method}_origin\"", ".", "to_sym", "if", "instance_methods", ".", "include?", "origin_method", "raise", "NameError", ",", "\"#{origin_method} isn't a unique name\"", "end", "alias_method", "origin_method", ",", "method", "define_method", "(", "method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "result", "=", "send", "(", "origin_method", ",", "*", "args", ",", "&", "block", ")", "send", "(", "hook", ")", "end", "end", "end" ]
Register a hooking method for given methods. The hook method is executed after calling given methods. @param [Symbol] hooking method name @param [Array] hooked methods name array
[ "Register", "a", "hooking", "method", "for", "given", "methods", ".", "The", "hook", "method", "is", "executed", "after", "calling", "given", "methods", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/entry.rb#L10-L24
train
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.next_feed
def next_feed(feed = nil) return Feed.load_xml(get_collection(collection_uri).body) if feed.nil? return nil unless feed.has_next? Feed.load_xml(get_collection(feed.next_uri).body) end
ruby
def next_feed(feed = nil) return Feed.load_xml(get_collection(collection_uri).body) if feed.nil? return nil unless feed.has_next? Feed.load_xml(get_collection(feed.next_uri).body) end
[ "def", "next_feed", "(", "feed", "=", "nil", ")", "return", "Feed", ".", "load_xml", "(", "get_collection", "(", "collection_uri", ")", ".", "body", ")", "if", "feed", ".", "nil?", "return", "nil", "unless", "feed", ".", "has_next?", "Feed", ".", "load_xml", "(", "get_collection", "(", "feed", ".", "next_uri", ")", ".", "body", ")", "end" ]
Get the next feed of the given feed. Return the first feed if no argument is passed. @param [Hatenablog::Feed] feed blog feed @return [Hatenablog::Feed] next blog feed
[ "Get", "the", "next", "feed", "of", "the", "given", "feed", ".", "Return", "the", "first", "feed", "if", "no", "argument", "is", "passed", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L69-L73
train
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.get_entry
def get_entry(entry_id) response = get(member_uri(entry_id)) Entry.load_xml(response.body) end
ruby
def get_entry(entry_id) response = get(member_uri(entry_id)) Entry.load_xml(response.body) end
[ "def", "get_entry", "(", "entry_id", ")", "response", "=", "get", "(", "member_uri", "(", "entry_id", ")", ")", "Entry", ".", "load_xml", "(", "response", ".", "body", ")", "end" ]
Get a blog entry specified by its ID. @param [String] entry_id entry ID @return [Hatenablog::BlogEntry] entry
[ "Get", "a", "blog", "entry", "specified", "by", "its", "ID", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L85-L88
train
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.post_entry
def post_entry(title = '', content = '', categories = [], draft = 'no') entry_xml = entry_xml(title, content, categories, draft) response = post(entry_xml) Entry.load_xml(response.body) end
ruby
def post_entry(title = '', content = '', categories = [], draft = 'no') entry_xml = entry_xml(title, content, categories, draft) response = post(entry_xml) Entry.load_xml(response.body) end
[ "def", "post_entry", "(", "title", "=", "''", ",", "content", "=", "''", ",", "categories", "=", "[", "]", ",", "draft", "=", "'no'", ")", "entry_xml", "=", "entry_xml", "(", "title", ",", "content", ",", "categories", ",", "draft", ")", "response", "=", "post", "(", "entry_xml", ")", "Entry", ".", "load_xml", "(", "response", ".", "body", ")", "end" ]
Post a blog entry. @param [String] title entry title @param [String] content entry content @param [Array] categories entry categories @param [String] draft this entry is draft if 'yes', otherwise it is not draft @return [Hatenablog::BlogEntry] posted entry
[ "Post", "a", "blog", "entry", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L96-L100
train
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.update_entry
def update_entry(entry_id, title = '', content = '', categories = [], draft = 'no', updated = '') entry_xml = entry_xml(title, content, categories, draft, updated) response = put(entry_xml, member_uri(entry_id)) Entry.load_xml(response.body) end
ruby
def update_entry(entry_id, title = '', content = '', categories = [], draft = 'no', updated = '') entry_xml = entry_xml(title, content, categories, draft, updated) response = put(entry_xml, member_uri(entry_id)) Entry.load_xml(response.body) end
[ "def", "update_entry", "(", "entry_id", ",", "title", "=", "''", ",", "content", "=", "''", ",", "categories", "=", "[", "]", ",", "draft", "=", "'no'", ",", "updated", "=", "''", ")", "entry_xml", "=", "entry_xml", "(", "title", ",", "content", ",", "categories", ",", "draft", ",", "updated", ")", "response", "=", "put", "(", "entry_xml", ",", "member_uri", "(", "entry_id", ")", ")", "Entry", ".", "load_xml", "(", "response", ".", "body", ")", "end" ]
Update a blog entry specified by its ID. @param [String] entry_id updated entry ID @param [String] title entry title @param [String] content entry content @param [Array] categories entry categories @param [String] draft this entry is draft if 'yes', otherwise it is not draft @param [String] updated entry updated datetime (ISO 8601) @return [Hatenablog::BlogEntry] updated entry
[ "Update", "a", "blog", "entry", "specified", "by", "its", "ID", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L110-L114
train
kymmt90/hatenablog
lib/hatenablog/client.rb
Hatenablog.Client.entry_xml
def entry_xml(title = '', content = '', categories = [], draft = 'no', updated = '', author_name = @user_id) builder = Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml| xml.entry('xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:app' => 'http://www.w3.org/2007/app') do xml.title title xml.author do xml.name author_name end xml.content(content, type: 'text/x-markdown') xml.updated updated unless updated.empty? || updated.nil? categories.each do |category| xml.category(term: category) end xml['app'].control do xml['app'].draft draft end end end builder.to_xml end
ruby
def entry_xml(title = '', content = '', categories = [], draft = 'no', updated = '', author_name = @user_id) builder = Nokogiri::XML::Builder.new(encoding: 'utf-8') do |xml| xml.entry('xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:app' => 'http://www.w3.org/2007/app') do xml.title title xml.author do xml.name author_name end xml.content(content, type: 'text/x-markdown') xml.updated updated unless updated.empty? || updated.nil? categories.each do |category| xml.category(term: category) end xml['app'].control do xml['app'].draft draft end end end builder.to_xml end
[ "def", "entry_xml", "(", "title", "=", "''", ",", "content", "=", "''", ",", "categories", "=", "[", "]", ",", "draft", "=", "'no'", ",", "updated", "=", "''", ",", "author_name", "=", "@user_id", ")", "builder", "=", "Nokogiri", "::", "XML", "::", "Builder", ".", "new", "(", "encoding", ":", "'utf-8'", ")", "do", "|", "xml", "|", "xml", ".", "entry", "(", "'xmlns'", "=>", "'http://www.w3.org/2005/Atom'", ",", "'xmlns:app'", "=>", "'http://www.w3.org/2007/app'", ")", "do", "xml", ".", "title", "title", "xml", ".", "author", "do", "xml", ".", "name", "author_name", "end", "xml", ".", "content", "(", "content", ",", "type", ":", "'text/x-markdown'", ")", "xml", ".", "updated", "updated", "unless", "updated", ".", "empty?", "||", "updated", ".", "nil?", "categories", ".", "each", "do", "|", "category", "|", "xml", ".", "category", "(", "term", ":", "category", ")", "end", "xml", "[", "'app'", "]", ".", "control", "do", "xml", "[", "'app'", "]", ".", "draft", "draft", "end", "end", "end", "builder", ".", "to_xml", "end" ]
Build a entry XML from arguments. @param [String] title entry title @param [String] content entry content @param [Array] categories entry categories @param [String] draft this entry is draft if 'yes', otherwise it is not draft @param [String] updated entry updated datetime (ISO 8601) @param [String] author_name entry author name @return [String] XML string
[ "Build", "a", "entry", "XML", "from", "arguments", "." ]
61b1015073cba9a11dfb4fd35d34922757abd70b
https://github.com/kymmt90/hatenablog/blob/61b1015073cba9a11dfb4fd35d34922757abd70b/lib/hatenablog/client.rb#L155-L175
train