id
int32
0
24.9k
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
15,700
honeybadger-io/honeybadger-ruby
lib/honeybadger/agent.rb
Honeybadger.Agent.notify
def notify(exception_or_opts, opts = {}) if exception_or_opts.is_a?(Exception) opts[:exception] = exception_or_opts elsif exception_or_opts.respond_to?(:to_hash) opts.merge!(exception_or_opts.to_hash) else opts[:error_message] = exception_or_opts.to_s end validate_notify_opts!(opts) opts[:rack_env] ||= context_manager.get_rack_env opts[:global_context] ||= context_manager.get_context notice = Notice.new(config, opts) config.before_notify_hooks.each do |hook| break if notice.halted? with_error_handling { hook.call(notice) } end unless notice.api_key =~ NOT_BLANK error { sprintf('Unable to send error report: API key is missing. id=%s', notice.id) } return false end if !opts[:force] && notice.ignore? debug { sprintf('ignore notice feature=notices id=%s', notice.id) } return false end if notice.halted? debug { 'halted notice feature=notices' } return false end info { sprintf('Reporting error id=%s', notice.id) } if opts[:sync] send_now(notice) else push(notice) end notice.id end
ruby
def notify(exception_or_opts, opts = {}) if exception_or_opts.is_a?(Exception) opts[:exception] = exception_or_opts elsif exception_or_opts.respond_to?(:to_hash) opts.merge!(exception_or_opts.to_hash) else opts[:error_message] = exception_or_opts.to_s end validate_notify_opts!(opts) opts[:rack_env] ||= context_manager.get_rack_env opts[:global_context] ||= context_manager.get_context notice = Notice.new(config, opts) config.before_notify_hooks.each do |hook| break if notice.halted? with_error_handling { hook.call(notice) } end unless notice.api_key =~ NOT_BLANK error { sprintf('Unable to send error report: API key is missing. id=%s', notice.id) } return false end if !opts[:force] && notice.ignore? debug { sprintf('ignore notice feature=notices id=%s', notice.id) } return false end if notice.halted? debug { 'halted notice feature=notices' } return false end info { sprintf('Reporting error id=%s', notice.id) } if opts[:sync] send_now(notice) else push(notice) end notice.id end
[ "def", "notify", "(", "exception_or_opts", ",", "opts", "=", "{", "}", ")", "if", "exception_or_opts", ".", "is_a?", "(", "Exception", ")", "opts", "[", ":exception", "]", "=", "exception_or_opts", "elsif", "exception_or_opts", ".", "respond_to?", "(", ":to_hash", ")", "opts", ".", "merge!", "(", "exception_or_opts", ".", "to_hash", ")", "else", "opts", "[", ":error_message", "]", "=", "exception_or_opts", ".", "to_s", "end", "validate_notify_opts!", "(", "opts", ")", "opts", "[", ":rack_env", "]", "||=", "context_manager", ".", "get_rack_env", "opts", "[", ":global_context", "]", "||=", "context_manager", ".", "get_context", "notice", "=", "Notice", ".", "new", "(", "config", ",", "opts", ")", "config", ".", "before_notify_hooks", ".", "each", "do", "|", "hook", "|", "break", "if", "notice", ".", "halted?", "with_error_handling", "{", "hook", ".", "call", "(", "notice", ")", "}", "end", "unless", "notice", ".", "api_key", "=~", "NOT_BLANK", "error", "{", "sprintf", "(", "'Unable to send error report: API key is missing. id=%s'", ",", "notice", ".", "id", ")", "}", "return", "false", "end", "if", "!", "opts", "[", ":force", "]", "&&", "notice", ".", "ignore?", "debug", "{", "sprintf", "(", "'ignore notice feature=notices id=%s'", ",", "notice", ".", "id", ")", "}", "return", "false", "end", "if", "notice", ".", "halted?", "debug", "{", "'halted notice feature=notices'", "}", "return", "false", "end", "info", "{", "sprintf", "(", "'Reporting error id=%s'", ",", "notice", ".", "id", ")", "}", "if", "opts", "[", ":sync", "]", "send_now", "(", "notice", ")", "else", "push", "(", "notice", ")", "end", "notice", ".", "id", "end" ]
Sends an exception to Honeybadger. Does not report ignored exceptions by default. @example # With an exception: begin fail 'oops' rescue => exception Honeybadger.notify(exception, context: { my_data: 'value' }) # => '-1dfb92ae-9b01-42e9-9c13-31205b70744a' end # Custom notification: Honeybadger.notify('Something went wrong.', { error_class: 'MyClass', context: {my_data: 'value'} }) # => '06220c5a-b471-41e5-baeb-de247da45a56' @param [Exception, Hash, Object] exception_or_opts An Exception object, or a Hash of options which is used to build the notice. All other types of objects will be converted to a String and used as the :error_message. @param [Hash] opts The options Hash when the first argument is an Exception. @option opts [String] :error_message The error message. @option opts [String] :error_class ('Notice') The class name of the error. @option opts [Array] :backtrace The backtrace of the error (optional). @option opts [String] :fingerprint The grouping fingerprint of the exception (optional). @option opts [Boolean] :force (false) Always report the exception when true, even when ignored (optional). @option opts [String] :tags The comma-separated list of tags (optional). @option opts [Hash] :context The context to associate with the exception (optional). @option opts [String] :controller The controller name (such as a Rails controller) (optional). @option opts [String] :action The action name (such as a Rails controller action) (optional). @option opts [Hash] :parameters The HTTP request paramaters (optional). @option opts [Hash] :session The HTTP request session (optional). @option opts [String] :url The HTTP request URL (optional). @option opts [Exception] :cause The cause for this error (optional). @return [String] UUID reference to the notice within Honeybadger. @return [false] when ignored.
[ "Sends", "an", "exception", "to", "Honeybadger", ".", "Does", "not", "report", "ignored", "exceptions", "by", "default", "." ]
dc4af07c347814c2c8a71778c5bcd4d6979b4638
https://github.com/honeybadger-io/honeybadger-ruby/blob/dc4af07c347814c2c8a71778c5bcd4d6979b4638/lib/honeybadger/agent.rb#L112-L157
15,701
honeybadger-io/honeybadger-ruby
lib/honeybadger/agent.rb
Honeybadger.Agent.check_in
def check_in(id) # this is to allow check ins even if a url is passed check_in_id = id.to_s.strip.gsub(/\/$/, '').split('/').last response = backend.check_in(check_in_id) response.success? end
ruby
def check_in(id) # this is to allow check ins even if a url is passed check_in_id = id.to_s.strip.gsub(/\/$/, '').split('/').last response = backend.check_in(check_in_id) response.success? end
[ "def", "check_in", "(", "id", ")", "# this is to allow check ins even if a url is passed", "check_in_id", "=", "id", ".", "to_s", ".", "strip", ".", "gsub", "(", "/", "\\/", "/", ",", "''", ")", ".", "split", "(", "'/'", ")", ".", "last", "response", "=", "backend", ".", "check_in", "(", "check_in_id", ")", "response", ".", "success?", "end" ]
Perform a synchronous check_in. @example Honeybadger.check_in('1MqIo1') @param [String] id The unique check in id (e.g. '1MqIo1') or the check in url. @return [Boolean] true if the check in was successful and false otherwise.
[ "Perform", "a", "synchronous", "check_in", "." ]
dc4af07c347814c2c8a71778c5bcd4d6979b4638
https://github.com/honeybadger-io/honeybadger-ruby/blob/dc4af07c347814c2c8a71778c5bcd4d6979b4638/lib/honeybadger/agent.rb#L168-L173
15,702
honeybadger-io/honeybadger-ruby
lib/honeybadger/backtrace.rb
Honeybadger.Backtrace.to_ary
def to_ary lines.take(1000).map { |l| { :number => l.filtered_number, :file => l.filtered_file, :method => l.filtered_method, :source => l.source } } end
ruby
def to_ary lines.take(1000).map { |l| { :number => l.filtered_number, :file => l.filtered_file, :method => l.filtered_method, :source => l.source } } end
[ "def", "to_ary", "lines", ".", "take", "(", "1000", ")", ".", "map", "{", "|", "l", "|", "{", ":number", "=>", "l", ".", "filtered_number", ",", ":file", "=>", "l", ".", "filtered_file", ",", ":method", "=>", "l", ".", "filtered_method", ",", ":source", "=>", "l", ".", "source", "}", "}", "end" ]
Convert Backtrace to arry. Returns array containing backtrace lines.
[ "Convert", "Backtrace", "to", "arry", "." ]
dc4af07c347814c2c8a71778c5bcd4d6979b4638
https://github.com/honeybadger-io/honeybadger-ruby/blob/dc4af07c347814c2c8a71778c5bcd4d6979b4638/lib/honeybadger/backtrace.rb#L134-L136
15,703
looker-open-source/gzr
lib/gzr/command.rb
Gzr.Command.keys_to_keep
def keys_to_keep(operation) o = @sdk.operations[operation] begin say_error "Operation #{operation} not found" return [] end unless o parameters = o[:info][:parameters].select { |p| p[:in] == "body" && p[:schema] } say_warning "Expecting exactly one body parameter with a schema for operation #{operation}" unless parameters.length == 1 schema_ref = parameters[0][:schema][:$ref].split(/\//) return @sdk.swagger[schema_ref[1].to_sym][schema_ref[2].to_sym][:properties].reject { |k,v| v[:readOnly] }.keys end
ruby
def keys_to_keep(operation) o = @sdk.operations[operation] begin say_error "Operation #{operation} not found" return [] end unless o parameters = o[:info][:parameters].select { |p| p[:in] == "body" && p[:schema] } say_warning "Expecting exactly one body parameter with a schema for operation #{operation}" unless parameters.length == 1 schema_ref = parameters[0][:schema][:$ref].split(/\//) return @sdk.swagger[schema_ref[1].to_sym][schema_ref[2].to_sym][:properties].reject { |k,v| v[:readOnly] }.keys end
[ "def", "keys_to_keep", "(", "operation", ")", "o", "=", "@sdk", ".", "operations", "[", "operation", "]", "begin", "say_error", "\"Operation #{operation} not found\"", "return", "[", "]", "end", "unless", "o", "parameters", "=", "o", "[", ":info", "]", "[", ":parameters", "]", ".", "select", "{", "|", "p", "|", "p", "[", ":in", "]", "==", "\"body\"", "&&", "p", "[", ":schema", "]", "}", "say_warning", "\"Expecting exactly one body parameter with a schema for operation #{operation}\"", "unless", "parameters", ".", "length", "==", "1", "schema_ref", "=", "parameters", "[", "0", "]", "[", ":schema", "]", "[", ":$ref", "]", ".", "split", "(", "/", "\\/", "/", ")", "return", "@sdk", ".", "swagger", "[", "schema_ref", "[", "1", "]", ".", "to_sym", "]", "[", "schema_ref", "[", "2", "]", ".", "to_sym", "]", "[", ":properties", "]", ".", "reject", "{", "|", "k", ",", "v", "|", "v", "[", ":readOnly", "]", "}", ".", "keys", "end" ]
This method accepts the name of an sdk operation, then finds the parameter for that operation in the data structures from the swagger.json file. The parameter is a json object. Some of the attributes of the json object are read-only, and some are read-write. A few are write-only. The list of read-write and write-only attribute names are returned as an array. That array can be used to take the json document that describes an object and strip out the read-only values, creating a document that can be used to create or update an object. The pattern typically looks like this... new_obj_hash = existing_obj_hash.select do |k,v| keys_to_keep('create_new_obj').include? k end
[ "This", "method", "accepts", "the", "name", "of", "an", "sdk", "operation", "then", "finds", "the", "parameter", "for", "that", "operation", "in", "the", "data", "structures", "from", "the", "swagger", ".", "json", "file", ".", "The", "parameter", "is", "a", "json", "object", ".", "Some", "of", "the", "attributes", "of", "the", "json", "object", "are", "read", "-", "only", "and", "some", "are", "read", "-", "write", ".", "A", "few", "are", "write", "-", "only", ".", "The", "list", "of", "read", "-", "write", "and", "write", "-", "only", "attribute", "names", "are", "returned", "as", "an", "array", ".", "That", "array", "can", "be", "used", "to", "take", "the", "json", "document", "that", "describes", "an", "object", "and", "strip", "out", "the", "read", "-", "only", "values", "creating", "a", "document", "that", "can", "be", "used", "to", "create", "or", "update", "an", "object", "." ]
96dd5edc9cdc6f8d053f517805b9637ff8417378
https://github.com/looker-open-source/gzr/blob/96dd5edc9cdc6f8d053f517805b9637ff8417378/lib/gzr/command.rb#L132-L144
15,704
looker-open-source/gzr
lib/gzr/command.rb
Gzr.Command.render_csv
def render_csv(t) io = StringIO.new io.puts ( t.header.collect do |v| v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : "" end.join(',') ) unless @options[:plain] t.each do |row| next if row === t.header io.puts ( row.collect do |v| v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : "" end.join(',') ) end io.rewind io.gets(nil).encode(crlf_newline: true) end
ruby
def render_csv(t) io = StringIO.new io.puts ( t.header.collect do |v| v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : "" end.join(',') ) unless @options[:plain] t.each do |row| next if row === t.header io.puts ( row.collect do |v| v ? "\"#{v.to_s.gsub(/"/, '""')}\"" : "" end.join(',') ) end io.rewind io.gets(nil).encode(crlf_newline: true) end
[ "def", "render_csv", "(", "t", ")", "io", "=", "StringIO", ".", "new", "io", ".", "puts", "(", "t", ".", "header", ".", "collect", "do", "|", "v", "|", "v", "?", "\"\\\"#{v.to_s.gsub(/\"/, '\"\"')}\\\"\"", ":", "\"\"", "end", ".", "join", "(", "','", ")", ")", "unless", "@options", "[", ":plain", "]", "t", ".", "each", "do", "|", "row", "|", "next", "if", "row", "===", "t", ".", "header", "io", ".", "puts", "(", "row", ".", "collect", "do", "|", "v", "|", "v", "?", "\"\\\"#{v.to_s.gsub(/\"/, '\"\"')}\\\"\"", ":", "\"\"", "end", ".", "join", "(", "','", ")", ")", "end", "io", ".", "rewind", "io", ".", "gets", "(", "nil", ")", ".", "encode", "(", "crlf_newline", ":", "true", ")", "end" ]
The tty-table gem is normally used to output tabular data. This method accepts a Table object as used by the tty-table gem, and generates CSV output. It returns a string with crlf encoding
[ "The", "tty", "-", "table", "gem", "is", "normally", "used", "to", "output", "tabular", "data", ".", "This", "method", "accepts", "a", "Table", "object", "as", "used", "by", "the", "tty", "-", "table", "gem", "and", "generates", "CSV", "output", ".", "It", "returns", "a", "string", "with", "crlf", "encoding" ]
96dd5edc9cdc6f8d053f517805b9637ff8417378
https://github.com/looker-open-source/gzr/blob/96dd5edc9cdc6f8d053f517805b9637ff8417378/lib/gzr/command.rb#L151-L168
15,705
looker-open-source/gzr
lib/gzr/command.rb
Gzr.Command.field_names
def field_names(opt_fields) fields = [] token_stack = [] last_token = false tokens = opt_fields.split /(\(|,|\))/ tokens << nil tokens.each do |t| if t.nil? then fields << (token_stack + [last_token]).join('.') if last_token elsif t.empty? then next elsif t == ',' then fields << (token_stack + [last_token]).join('.') if last_token elsif t == '(' then token_stack.push(last_token) elsif t == ')' then fields << (token_stack + [last_token]).join('.') if last_token token_stack.pop last_token = false else last_token = t end end fields end
ruby
def field_names(opt_fields) fields = [] token_stack = [] last_token = false tokens = opt_fields.split /(\(|,|\))/ tokens << nil tokens.each do |t| if t.nil? then fields << (token_stack + [last_token]).join('.') if last_token elsif t.empty? then next elsif t == ',' then fields << (token_stack + [last_token]).join('.') if last_token elsif t == '(' then token_stack.push(last_token) elsif t == ')' then fields << (token_stack + [last_token]).join('.') if last_token token_stack.pop last_token = false else last_token = t end end fields end
[ "def", "field_names", "(", "opt_fields", ")", "fields", "=", "[", "]", "token_stack", "=", "[", "]", "last_token", "=", "false", "tokens", "=", "opt_fields", ".", "split", "/", "\\(", "\\)", "/", "tokens", "<<", "nil", "tokens", ".", "each", "do", "|", "t", "|", "if", "t", ".", "nil?", "then", "fields", "<<", "(", "token_stack", "+", "[", "last_token", "]", ")", ".", "join", "(", "'.'", ")", "if", "last_token", "elsif", "t", ".", "empty?", "then", "next", "elsif", "t", "==", "','", "then", "fields", "<<", "(", "token_stack", "+", "[", "last_token", "]", ")", ".", "join", "(", "'.'", ")", "if", "last_token", "elsif", "t", "==", "'('", "then", "token_stack", ".", "push", "(", "last_token", ")", "elsif", "t", "==", "')'", "then", "fields", "<<", "(", "token_stack", "+", "[", "last_token", "]", ")", ".", "join", "(", "'.'", ")", "if", "last_token", "token_stack", ".", "pop", "last_token", "=", "false", "else", "last_token", "=", "t", "end", "end", "fields", "end" ]
This method accepts a string containing a list of fields. The fields can be nested in a format like... 'a,b,c(d,e(f,g)),h' representing a structure like { a: "val", b: "val", c: { d: "val", e: { f: "val", g: "val" } }, h: "val" } That string will get parsed and yield an array like [ a, b, c.d, c.e.f, c.e.g, h ]
[ "This", "method", "accepts", "a", "string", "containing", "a", "list", "of", "fields", ".", "The", "fields", "can", "be", "nested", "in", "a", "format", "like", "..." ]
96dd5edc9cdc6f8d053f517805b9637ff8417378
https://github.com/looker-open-source/gzr/blob/96dd5edc9cdc6f8d053f517805b9637ff8417378/lib/gzr/command.rb#L195-L219
15,706
traject/traject
lib/traject/macros/marc21_semantics.rb
Traject::Macros.Marc21Semantics.oclcnum
def oclcnum(extract_fields = "035a") extractor = MarcExtractor.new(extract_fields, :separator => nil) lambda do |record, accumulator| list = extractor.extract(record).collect! do |o| Marc21Semantics.oclcnum_extract(o) end.compact accumulator.concat list.uniq if list end end
ruby
def oclcnum(extract_fields = "035a") extractor = MarcExtractor.new(extract_fields, :separator => nil) lambda do |record, accumulator| list = extractor.extract(record).collect! do |o| Marc21Semantics.oclcnum_extract(o) end.compact accumulator.concat list.uniq if list end end
[ "def", "oclcnum", "(", "extract_fields", "=", "\"035a\"", ")", "extractor", "=", "MarcExtractor", ".", "new", "(", "extract_fields", ",", ":separator", "=>", "nil", ")", "lambda", "do", "|", "record", ",", "accumulator", "|", "list", "=", "extractor", ".", "extract", "(", "record", ")", ".", "collect!", "do", "|", "o", "|", "Marc21Semantics", ".", "oclcnum_extract", "(", "o", ")", "end", ".", "compact", "accumulator", ".", "concat", "list", ".", "uniq", "if", "list", "end", "end" ]
Extract OCLC numbers from, by default 035a's by known prefixes, then stripped just the num, and de-dup.
[ "Extract", "OCLC", "numbers", "from", "by", "default", "035a", "s", "by", "known", "prefixes", "then", "stripped", "just", "the", "num", "and", "de", "-", "dup", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/macros/marc21_semantics.rb#L18-L28
15,707
traject/traject
lib/traject/macros/marc21_semantics.rb
Traject::Macros.Marc21Semantics.marc_sortable_title
def marc_sortable_title lambda do |record, accumulator| st = Marc21Semantics.get_sortable_title(record) accumulator << st if st end end
ruby
def marc_sortable_title lambda do |record, accumulator| st = Marc21Semantics.get_sortable_title(record) accumulator << st if st end end
[ "def", "marc_sortable_title", "lambda", "do", "|", "record", ",", "accumulator", "|", "st", "=", "Marc21Semantics", ".", "get_sortable_title", "(", "record", ")", "accumulator", "<<", "st", "if", "st", "end", "end" ]
245 a and b, with non-filing characters stripped off
[ "245", "a", "and", "b", "with", "non", "-", "filing", "characters", "stripped", "off" ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/macros/marc21_semantics.rb#L92-L97
15,708
traject/traject
lib/traject/macros/marc21_semantics.rb
Traject::Macros.Marc21Semantics.marc_publication_date
def marc_publication_date(options = {}) estimate_tolerance = options[:estimate_tolerance] || 15 min_year = options[:min_year] || 500 max_year = options[:max_year] || (Time.new.year + 6) lambda do |record, accumulator| date = Marc21Semantics.publication_date(record, estimate_tolerance, min_year, max_year) accumulator << date if date end end
ruby
def marc_publication_date(options = {}) estimate_tolerance = options[:estimate_tolerance] || 15 min_year = options[:min_year] || 500 max_year = options[:max_year] || (Time.new.year + 6) lambda do |record, accumulator| date = Marc21Semantics.publication_date(record, estimate_tolerance, min_year, max_year) accumulator << date if date end end
[ "def", "marc_publication_date", "(", "options", "=", "{", "}", ")", "estimate_tolerance", "=", "options", "[", ":estimate_tolerance", "]", "||", "15", "min_year", "=", "options", "[", ":min_year", "]", "||", "500", "max_year", "=", "options", "[", ":max_year", "]", "||", "(", "Time", ".", "new", ".", "year", "+", "6", ")", "lambda", "do", "|", "record", ",", "accumulator", "|", "date", "=", "Marc21Semantics", ".", "publication_date", "(", "record", ",", "estimate_tolerance", ",", "min_year", ",", "max_year", ")", "accumulator", "<<", "date", "if", "date", "end", "end" ]
An opinionated algorithm for getting a SINGLE publication date out of marc * Prefers using 008, but will resort to 260c * If 008 represents a date range, will take the midpoint of the range, only if range is smaller than estimate_tolerance, default 15 years. * Ignores dates below min_year (default 500) or above max_year (this year plus 6 years), because experience shows too many of these were in error. Yeah, this code ends up ridiculous.
[ "An", "opinionated", "algorithm", "for", "getting", "a", "SINGLE", "publication", "date", "out", "of", "marc" ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/macros/marc21_semantics.rb#L310-L319
15,709
traject/traject
lib/traject/macros/marc21_semantics.rb
Traject::Macros.Marc21Semantics.marc_geo_facet
def marc_geo_facet(options = {}) marc_geo_map = Traject::TranslationMap.new("marc_geographic") a_fields_spec = options[:geo_a_fields] || "651a:691a" z_fields_spec = options[:geo_z_fields] || "600:610:611:630:648:650:654:655:656:690:651:691" extractor_043a = MarcExtractor.new("043a", :separator => nil) extractor_a_fields = MarcExtractor.new(a_fields_spec, :separator => nil) extractor_z_fields = MarcExtractor.new(z_fields_spec) lambda do |record, accumulator| accumulator.concat( extractor_043a.extract(record).collect do |code| # remove any trailing hyphens, then map marc_geo_map[code.gsub(/\-+\Z/, '')] end.compact ) #LCSH 651a and 691a go in more or less normally. accumulator.concat( extractor_a_fields.extract(record).collect do |s| # remove trailing periods, which they sometimes have if they were # at end of LCSH. s.sub(/\. */, '') end ) # fields we take z's from have a bit more normalization extractor_z_fields.each_matching_line(record) do |field, spec, extractor| z_fields = field.subfields.find_all {|sf| sf.code == "z"}.collect {|sf| sf.value } # depending on position in total field, may be a period on the end # we want to remove. z_fields.collect! {|s| s.gsub(/\. *\Z/, '')} if z_fields.length == 2 # normalize subdivision as parenthetical accumulator << "#{z_fields[1]} (#{z_fields[0]})" # and 'post up' accumulator << z_fields[0] else # just add all the z's if there's 1 or more than 2. accumulator.concat z_fields end end accumulator.uniq! end end
ruby
def marc_geo_facet(options = {}) marc_geo_map = Traject::TranslationMap.new("marc_geographic") a_fields_spec = options[:geo_a_fields] || "651a:691a" z_fields_spec = options[:geo_z_fields] || "600:610:611:630:648:650:654:655:656:690:651:691" extractor_043a = MarcExtractor.new("043a", :separator => nil) extractor_a_fields = MarcExtractor.new(a_fields_spec, :separator => nil) extractor_z_fields = MarcExtractor.new(z_fields_spec) lambda do |record, accumulator| accumulator.concat( extractor_043a.extract(record).collect do |code| # remove any trailing hyphens, then map marc_geo_map[code.gsub(/\-+\Z/, '')] end.compact ) #LCSH 651a and 691a go in more or less normally. accumulator.concat( extractor_a_fields.extract(record).collect do |s| # remove trailing periods, which they sometimes have if they were # at end of LCSH. s.sub(/\. */, '') end ) # fields we take z's from have a bit more normalization extractor_z_fields.each_matching_line(record) do |field, spec, extractor| z_fields = field.subfields.find_all {|sf| sf.code == "z"}.collect {|sf| sf.value } # depending on position in total field, may be a period on the end # we want to remove. z_fields.collect! {|s| s.gsub(/\. *\Z/, '')} if z_fields.length == 2 # normalize subdivision as parenthetical accumulator << "#{z_fields[1]} (#{z_fields[0]})" # and 'post up' accumulator << z_fields[0] else # just add all the z's if there's 1 or more than 2. accumulator.concat z_fields end end accumulator.uniq! end end
[ "def", "marc_geo_facet", "(", "options", "=", "{", "}", ")", "marc_geo_map", "=", "Traject", "::", "TranslationMap", ".", "new", "(", "\"marc_geographic\"", ")", "a_fields_spec", "=", "options", "[", ":geo_a_fields", "]", "||", "\"651a:691a\"", "z_fields_spec", "=", "options", "[", ":geo_z_fields", "]", "||", "\"600:610:611:630:648:650:654:655:656:690:651:691\"", "extractor_043a", "=", "MarcExtractor", ".", "new", "(", "\"043a\"", ",", ":separator", "=>", "nil", ")", "extractor_a_fields", "=", "MarcExtractor", ".", "new", "(", "a_fields_spec", ",", ":separator", "=>", "nil", ")", "extractor_z_fields", "=", "MarcExtractor", ".", "new", "(", "z_fields_spec", ")", "lambda", "do", "|", "record", ",", "accumulator", "|", "accumulator", ".", "concat", "(", "extractor_043a", ".", "extract", "(", "record", ")", ".", "collect", "do", "|", "code", "|", "# remove any trailing hyphens, then map", "marc_geo_map", "[", "code", ".", "gsub", "(", "/", "\\-", "\\Z", "/", ",", "''", ")", "]", "end", ".", "compact", ")", "#LCSH 651a and 691a go in more or less normally.", "accumulator", ".", "concat", "(", "extractor_a_fields", ".", "extract", "(", "record", ")", ".", "collect", "do", "|", "s", "|", "# remove trailing periods, which they sometimes have if they were", "# at end of LCSH.", "s", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "end", ")", "# fields we take z's from have a bit more normalization", "extractor_z_fields", ".", "each_matching_line", "(", "record", ")", "do", "|", "field", ",", "spec", ",", "extractor", "|", "z_fields", "=", "field", ".", "subfields", ".", "find_all", "{", "|", "sf", "|", "sf", ".", "code", "==", "\"z\"", "}", ".", "collect", "{", "|", "sf", "|", "sf", ".", "value", "}", "# depending on position in total field, may be a period on the end", "# we want to remove.", "z_fields", ".", "collect!", "{", "|", "s", "|", "s", ".", "gsub", "(", "/", "\\.", "\\Z", "/", ",", "''", ")", "}", "if", "z_fields", ".", "length", "==", "2", "# normalize subdivision as parenthetical", "accumulator", "<<", "\"#{z_fields[1]} (#{z_fields[0]})\"", "# and 'post up'", "accumulator", "<<", "z_fields", "[", "0", "]", "else", "# just add all the z's if there's 1 or more than 2.", "accumulator", ".", "concat", "z_fields", "end", "end", "accumulator", ".", "uniq!", "end", "end" ]
An opinionated method of making a geographic facet out of BOTH 048 marc codes, AND geo subdivisions in 6xx LCSH subjects. The LCSH geo subdivisions are further normalized: * geo qualifiers in $z fields into parens, so "Germany -- Berlin" becomes "Berlin (Germany)" (to be consistent with how same areas are written in $a fields -- doesn't get everything, but gets lots of em) * qualified regions like that are additionally 'posted up', so "Germany -- Berlin" gets recorded additionally as "Germany"
[ "An", "opinionated", "method", "of", "making", "a", "geographic", "facet", "out", "of", "BOTH", "048", "marc", "codes", "AND", "geo", "subdivisions", "in", "6xx", "LCSH", "subjects", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/macros/marc21_semantics.rb#L431-L478
15,710
traject/traject
lib/traject/macros/marc21_semantics.rb
Traject::Macros.Marc21Semantics.marc_lcsh_formatted
def marc_lcsh_formatted(options = {}) spec = options[:spec] || "600:610:611:630:648:650:651:654:662" subd_separator = options[:subdivison_separator] || " — " other_separator = options[:other_separator] || " " extractor = MarcExtractor.new(spec) return lambda do |record, accumulator| accumulator.concat( extractor.collect_matching_lines(record) do |field, spec| Marc21Semantics.assemble_lcsh(field, subd_separator, other_separator) end) end end
ruby
def marc_lcsh_formatted(options = {}) spec = options[:spec] || "600:610:611:630:648:650:651:654:662" subd_separator = options[:subdivison_separator] || " — " other_separator = options[:other_separator] || " " extractor = MarcExtractor.new(spec) return lambda do |record, accumulator| accumulator.concat( extractor.collect_matching_lines(record) do |field, spec| Marc21Semantics.assemble_lcsh(field, subd_separator, other_separator) end) end end
[ "def", "marc_lcsh_formatted", "(", "options", "=", "{", "}", ")", "spec", "=", "options", "[", ":spec", "]", "||", "\"600:610:611:630:648:650:651:654:662\"", "subd_separator", "=", "options", "[", ":subdivison_separator", "]", "||", "\" — \"", "other_separator", "=", "options", "[", ":other_separator", "]", "||", "\" \"", "extractor", "=", "MarcExtractor", ".", "new", "(", "spec", ")", "return", "lambda", "do", "|", "record", ",", "accumulator", "|", "accumulator", ".", "concat", "(", "extractor", ".", "collect_matching_lines", "(", "record", ")", "do", "|", "field", ",", "spec", "|", "Marc21Semantics", ".", "assemble_lcsh", "(", "field", ",", "subd_separator", ",", "other_separator", ")", "end", ")", "end", "end" ]
Extracts LCSH-carrying fields, and formatting them as a pre-coordinated LCSH string, for instance suitable for including in a facet. You can supply your own list of fields as a spec, but for significant customization you probably just want to write your own method in terms of the Marc21Semantics.assemble_lcsh method.
[ "Extracts", "LCSH", "-", "carrying", "fields", "and", "formatting", "them", "as", "a", "pre", "-", "coordinated", "LCSH", "string", "for", "instance", "suitable", "for", "including", "in", "a", "facet", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/macros/marc21_semantics.rb#L527-L540
15,711
traject/traject
lib/traject/translation_map.rb
Traject.TranslationMap.translate_array
def translate_array(array) array.each_with_object([]) do |input_element, output_array| output_element = self.map(input_element) if output_element.kind_of? Array output_array.concat output_element elsif ! output_element.nil? output_array << output_element end end end
ruby
def translate_array(array) array.each_with_object([]) do |input_element, output_array| output_element = self.map(input_element) if output_element.kind_of? Array output_array.concat output_element elsif ! output_element.nil? output_array << output_element end end end
[ "def", "translate_array", "(", "array", ")", "array", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "input_element", ",", "output_array", "|", "output_element", "=", "self", ".", "map", "(", "input_element", ")", "if", "output_element", ".", "kind_of?", "Array", "output_array", ".", "concat", "output_element", "elsif", "!", "output_element", ".", "nil?", "output_array", "<<", "output_element", "end", "end", "end" ]
Run every element of an array through this translation map, return the resulting array. If translation map returns nil, original element will be missing from output. If an input maps to an array, each element of the array will be flattened into the output. If an input maps to nil, it will cause the input element to be removed entirely.
[ "Run", "every", "element", "of", "an", "array", "through", "this", "translation", "map", "return", "the", "resulting", "array", ".", "If", "translation", "map", "returns", "nil", "original", "element", "will", "be", "missing", "from", "output", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/translation_map.rb#L217-L226
15,712
traject/traject
lib/traject/translation_map.rb
Traject.TranslationMap.merge
def merge(other_map) default = other_map.default || self.default TranslationMap.new(self.to_hash.merge(other_map.to_hash), :default => default) end
ruby
def merge(other_map) default = other_map.default || self.default TranslationMap.new(self.to_hash.merge(other_map.to_hash), :default => default) end
[ "def", "merge", "(", "other_map", ")", "default", "=", "other_map", ".", "default", "||", "self", ".", "default", "TranslationMap", ".", "new", "(", "self", ".", "to_hash", ".", "merge", "(", "other_map", ".", "to_hash", ")", ",", ":default", "=>", "default", ")", "end" ]
Return a new TranslationMap that results from merging argument on top of self. Can be useful for taking an existing translation map, but merging a few overrides on top. merged_map = TranslationMap.new(something).merge TranslationMap.new(else) #... merged_map.translate_array(something) # etc If a default is set in the second map, it will merge over the first too. You can also pass in a plain hash as an arg, instead of an existing TranslationMap: TranslationMap.new(something).merge("overridden_key" => "value", "a" => "")
[ "Return", "a", "new", "TranslationMap", "that", "results", "from", "merging", "argument", "on", "top", "of", "self", ".", "Can", "be", "useful", "for", "taking", "an", "existing", "translation", "map", "but", "merging", "a", "few", "overrides", "on", "top", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/translation_map.rb#L245-L248
15,713
traject/traject
lib/traject/macros/marc21.rb
Traject::Macros.Marc21.extract_all_marc_values
def extract_all_marc_values(options = {}) unless (options.keys - EXTRACT_ALL_MARC_VALID_OPTIONS).empty? raise RuntimeError.new("Illegal/Unknown argument '#{(options.keys - EXTRACT_ALL_MARC_VALID_OPTIONS).join(', ')}' in extract_all_marc at #{Traject::Util.extract_caller_location(caller.first)}") end options = {:from => "100", :to => "899", :separator => ' '}.merge(options) if [options[:from], options[:to]].map{|x| x.is_a? String}.any?{|x| x == false} raise ArgumentError.new("from/to options to extract_all_marc_values must be strings") end lambda do |record, accumulator, context| record.each do |field| next unless field.tag >= options[:from] && field.tag <= options[:to] subfield_values = field.subfields.collect {|sf| sf.value} next unless subfield_values.length > 0 if options[:separator] accumulator << subfield_values.join( options[:separator]) else accumulator.concat subfield_values end end end end
ruby
def extract_all_marc_values(options = {}) unless (options.keys - EXTRACT_ALL_MARC_VALID_OPTIONS).empty? raise RuntimeError.new("Illegal/Unknown argument '#{(options.keys - EXTRACT_ALL_MARC_VALID_OPTIONS).join(', ')}' in extract_all_marc at #{Traject::Util.extract_caller_location(caller.first)}") end options = {:from => "100", :to => "899", :separator => ' '}.merge(options) if [options[:from], options[:to]].map{|x| x.is_a? String}.any?{|x| x == false} raise ArgumentError.new("from/to options to extract_all_marc_values must be strings") end lambda do |record, accumulator, context| record.each do |field| next unless field.tag >= options[:from] && field.tag <= options[:to] subfield_values = field.subfields.collect {|sf| sf.value} next unless subfield_values.length > 0 if options[:separator] accumulator << subfield_values.join( options[:separator]) else accumulator.concat subfield_values end end end end
[ "def", "extract_all_marc_values", "(", "options", "=", "{", "}", ")", "unless", "(", "options", ".", "keys", "-", "EXTRACT_ALL_MARC_VALID_OPTIONS", ")", ".", "empty?", "raise", "RuntimeError", ".", "new", "(", "\"Illegal/Unknown argument '#{(options.keys - EXTRACT_ALL_MARC_VALID_OPTIONS).join(', ')}' in extract_all_marc at #{Traject::Util.extract_caller_location(caller.first)}\"", ")", "end", "options", "=", "{", ":from", "=>", "\"100\"", ",", ":to", "=>", "\"899\"", ",", ":separator", "=>", "' '", "}", ".", "merge", "(", "options", ")", "if", "[", "options", "[", ":from", "]", ",", "options", "[", ":to", "]", "]", ".", "map", "{", "|", "x", "|", "x", ".", "is_a?", "String", "}", ".", "any?", "{", "|", "x", "|", "x", "==", "false", "}", "raise", "ArgumentError", ".", "new", "(", "\"from/to options to extract_all_marc_values must be strings\"", ")", "end", "lambda", "do", "|", "record", ",", "accumulator", ",", "context", "|", "record", ".", "each", "do", "|", "field", "|", "next", "unless", "field", ".", "tag", ">=", "options", "[", ":from", "]", "&&", "field", ".", "tag", "<=", "options", "[", ":to", "]", "subfield_values", "=", "field", ".", "subfields", ".", "collect", "{", "|", "sf", "|", "sf", ".", "value", "}", "next", "unless", "subfield_values", ".", "length", ">", "0", "if", "options", "[", ":separator", "]", "accumulator", "<<", "subfield_values", ".", "join", "(", "options", "[", ":separator", "]", ")", "else", "accumulator", ".", "concat", "subfield_values", "end", "end", "end", "end" ]
Takes the whole record, by default from tags 100 to 899 inclusive, all subfields, and adds them to output. Subfields in a record are all joined by space by default. options [:from] default '100', only tags >= lexicographically [:to] default '899', only tags <= lexicographically [:separator] how to join subfields, default space, nil means don't join All fields in from-to must be marc DATA (not control fields), or weirdness Can always run this thing multiple times on the same field if you need non-contiguous ranges of fields.
[ "Takes", "the", "whole", "record", "by", "default", "from", "tags", "100", "to", "899", "inclusive", "all", "subfields", "and", "adds", "them", "to", "output", ".", "Subfields", "in", "a", "record", "are", "all", "joined", "by", "space", "by", "default", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/macros/marc21.rb#L213-L237
15,714
traject/traject
lib/traject/oai_pmh_nokogiri_reader.rb
Traject.OaiPmhNokogiriReader.http_client
def http_client @http_client ||= begin # timeout setting on http.rb seems to be a mess. # https://github.com/httprb/http/issues/488 client = HTTP.timeout(:global, write: timeout / 3, connect: timeout / 3, read: timeout / 3) if settings["oai_pmh.try_gzip"] client = client.use(:auto_inflate).headers("accept-encoding" => "gzip;q=1.0, identity;q=0.5") end if settings["oai_pmh.http_persistent"] parsed_uri = URI.parse(start_url) client = client.persistent("#{parsed_uri.scheme}://#{parsed_uri.host}") end client end end
ruby
def http_client @http_client ||= begin # timeout setting on http.rb seems to be a mess. # https://github.com/httprb/http/issues/488 client = HTTP.timeout(:global, write: timeout / 3, connect: timeout / 3, read: timeout / 3) if settings["oai_pmh.try_gzip"] client = client.use(:auto_inflate).headers("accept-encoding" => "gzip;q=1.0, identity;q=0.5") end if settings["oai_pmh.http_persistent"] parsed_uri = URI.parse(start_url) client = client.persistent("#{parsed_uri.scheme}://#{parsed_uri.host}") end client end end
[ "def", "http_client", "@http_client", "||=", "begin", "# timeout setting on http.rb seems to be a mess.", "# https://github.com/httprb/http/issues/488", "client", "=", "HTTP", ".", "timeout", "(", ":global", ",", "write", ":", "timeout", "/", "3", ",", "connect", ":", "timeout", "/", "3", ",", "read", ":", "timeout", "/", "3", ")", "if", "settings", "[", "\"oai_pmh.try_gzip\"", "]", "client", "=", "client", ".", "use", "(", ":auto_inflate", ")", ".", "headers", "(", "\"accept-encoding\"", "=>", "\"gzip;q=1.0, identity;q=0.5\"", ")", "end", "if", "settings", "[", "\"oai_pmh.http_persistent\"", "]", "parsed_uri", "=", "URI", ".", "parse", "(", "start_url", ")", "client", "=", "client", ".", "persistent", "(", "\"#{parsed_uri.scheme}://#{parsed_uri.host}\"", ")", "end", "client", "end", "end" ]
re-use an http-client for subsequent requests, to get http.rb's persistent connection re-use Note this means this is NOT thread safe, which is fine for now, but we'd have to do something different if we tried to multi-thread reading multiple files or something. @returns [HTTP::Client] from http.rb gem
[ "re", "-", "use", "an", "http", "-", "client", "for", "subsequent", "requests", "to", "get", "http", ".", "rb", "s", "persistent", "connection", "re", "-", "use", "Note", "this", "means", "this", "is", "NOT", "thread", "safe", "which", "is", "fine", "for", "now", "but", "we", "d", "have", "to", "do", "something", "different", "if", "we", "tried", "to", "multi", "-", "thread", "reading", "multiple", "files", "or", "something", "." ]
fcb17711fe7a0590e72ecbd39fd3c61d77689f24
https://github.com/traject/traject/blob/fcb17711fe7a0590e72ecbd39fd3c61d77689f24/lib/traject/oai_pmh_nokogiri_reader.rb#L116-L133
15,715
zurb/inky-rb
lib/inky/component_factory.rb
Inky.ComponentFactory._transform_columns
def _transform_columns(component, inner) col_count = component.parent.elements.size small_val = component.attr('small') large_val = component.attr('large') small_size = small_val || column_count large_size = large_val || small_val || (column_count / col_count).to_i classes = _combine_classes(component, "small-#{small_size} large-#{large_size} columns") classes << ' first' unless component.previous_element classes << ' last' unless component.next_element subrows = component.elements.css(".row").to_a.concat(component.elements.css("row").to_a) expander = %{<th class="expander"></th>} if large_size.to_i == column_count && subrows.empty? %{<#{INTERIM_TH_TAG} class="#{classes}" #{_pass_through_attributes(component)}><table><tr><th>#{inner}</th>#{expander}</tr></table></#{INTERIM_TH_TAG}>} end
ruby
def _transform_columns(component, inner) col_count = component.parent.elements.size small_val = component.attr('small') large_val = component.attr('large') small_size = small_val || column_count large_size = large_val || small_val || (column_count / col_count).to_i classes = _combine_classes(component, "small-#{small_size} large-#{large_size} columns") classes << ' first' unless component.previous_element classes << ' last' unless component.next_element subrows = component.elements.css(".row").to_a.concat(component.elements.css("row").to_a) expander = %{<th class="expander"></th>} if large_size.to_i == column_count && subrows.empty? %{<#{INTERIM_TH_TAG} class="#{classes}" #{_pass_through_attributes(component)}><table><tr><th>#{inner}</th>#{expander}</tr></table></#{INTERIM_TH_TAG}>} end
[ "def", "_transform_columns", "(", "component", ",", "inner", ")", "col_count", "=", "component", ".", "parent", ".", "elements", ".", "size", "small_val", "=", "component", ".", "attr", "(", "'small'", ")", "large_val", "=", "component", ".", "attr", "(", "'large'", ")", "small_size", "=", "small_val", "||", "column_count", "large_size", "=", "large_val", "||", "small_val", "||", "(", "column_count", "/", "col_count", ")", ".", "to_i", "classes", "=", "_combine_classes", "(", "component", ",", "\"small-#{small_size} large-#{large_size} columns\"", ")", "classes", "<<", "' first'", "unless", "component", ".", "previous_element", "classes", "<<", "' last'", "unless", "component", ".", "next_element", "subrows", "=", "component", ".", "elements", ".", "css", "(", "\".row\"", ")", ".", "to_a", ".", "concat", "(", "component", ".", "elements", ".", "css", "(", "\"row\"", ")", ".", "to_a", ")", "expander", "=", "%{<th class=\"expander\"></th>}", "if", "large_size", ".", "to_i", "==", "column_count", "&&", "subrows", ".", "empty?", "%{<#{INTERIM_TH_TAG} class=\"#{classes}\" #{_pass_through_attributes(component)}><table><tr><th>#{inner}</th>#{expander}</tr></table></#{INTERIM_TH_TAG}>}", "end" ]
in inky.js this is factored out into makeClumn. TBD if we need that here.
[ "in", "inky", ".", "js", "this", "is", "factored", "out", "into", "makeClumn", ".", "TBD", "if", "we", "need", "that", "here", "." ]
208ade8b9fa95afae0e81b8cd0bb23ab96371e5b
https://github.com/zurb/inky-rb/blob/208ade8b9fa95afae0e81b8cd0bb23ab96371e5b/lib/inky/component_factory.rb#L82-L100
15,716
gollum/gollum-lib
lib/gollum-lib/committer.rb
Gollum.Committer.index
def index @index ||= begin idx = @wiki.repo.index if (tree = options[:tree]) idx.read_tree(tree) elsif (parent = parents.first) idx.read_tree(parent.tree.id) end idx end end
ruby
def index @index ||= begin idx = @wiki.repo.index if (tree = options[:tree]) idx.read_tree(tree) elsif (parent = parents.first) idx.read_tree(parent.tree.id) end idx end end
[ "def", "index", "@index", "||=", "begin", "idx", "=", "@wiki", ".", "repo", ".", "index", "if", "(", "tree", "=", "options", "[", ":tree", "]", ")", "idx", ".", "read_tree", "(", "tree", ")", "elsif", "(", "parent", "=", "parents", ".", "first", ")", "idx", ".", "read_tree", "(", "parent", ".", "tree", ".", "id", ")", "end", "idx", "end", "end" ]
Initializes the Committer. wiki - The Gollum::Wiki instance that is being updated. options - The commit Hash details: :message - The String commit message. :name - The String author full name. :email - The String email address. :parent - Optional Gollum::Git::Commit parent to this update. :tree - Optional String SHA of the tree to create the index from. :committer - Optional Gollum::Committer instance. If provided, assume that this operation is part of batch of updates and the commit happens later. Returns the Committer instance. Public: References the Git index for this commit. Returns a Gollum::Git::Index.
[ "Initializes", "the", "Committer", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/committer.rb#L39-L49
15,717
gollum/gollum-lib
lib/gollum-lib/committer.rb
Gollum.Committer.add_to_index
def add_to_index(dir, name, format, data, allow_same_ext = false) # spaces must be dashes dir.gsub!(' ', '-') name.gsub!(' ', '-') path = @wiki.page_file_name(name, format) dir = '/' if dir.strip.empty? fullpath = ::File.join(*[dir, path]) fullpath = fullpath[1..-1] if fullpath =~ /^\// if index.current_tree && (tree = index.current_tree / (@wiki.page_file_dir || '/')) tree = tree / dir unless tree.nil? end if tree downpath = path.downcase.sub(/\.\w+$/, '') tree.blobs.each do |blob| next if page_path_scheduled_for_deletion?(index.tree, fullpath) existing_file = blob.name.downcase.sub(/\.\w+$/, '') existing_file_ext = ::File.extname(blob.name).sub(/^\./, '') new_file_ext = ::File.extname(path).sub(/^\./, '') if downpath == existing_file && !(allow_same_ext && new_file_ext == existing_file_ext) raise DuplicatePageError.new(dir, blob.name, path) end end end fullpath = fullpath.force_encoding('ascii-8bit') if fullpath.respond_to?(:force_encoding) begin data = @wiki.normalize(data) rescue ArgumentError => err # Swallow errors that arise from data being binary raise err unless err.message.include?('invalid byte sequence') end index.add(fullpath, data) end
ruby
def add_to_index(dir, name, format, data, allow_same_ext = false) # spaces must be dashes dir.gsub!(' ', '-') name.gsub!(' ', '-') path = @wiki.page_file_name(name, format) dir = '/' if dir.strip.empty? fullpath = ::File.join(*[dir, path]) fullpath = fullpath[1..-1] if fullpath =~ /^\// if index.current_tree && (tree = index.current_tree / (@wiki.page_file_dir || '/')) tree = tree / dir unless tree.nil? end if tree downpath = path.downcase.sub(/\.\w+$/, '') tree.blobs.each do |blob| next if page_path_scheduled_for_deletion?(index.tree, fullpath) existing_file = blob.name.downcase.sub(/\.\w+$/, '') existing_file_ext = ::File.extname(blob.name).sub(/^\./, '') new_file_ext = ::File.extname(path).sub(/^\./, '') if downpath == existing_file && !(allow_same_ext && new_file_ext == existing_file_ext) raise DuplicatePageError.new(dir, blob.name, path) end end end fullpath = fullpath.force_encoding('ascii-8bit') if fullpath.respond_to?(:force_encoding) begin data = @wiki.normalize(data) rescue ArgumentError => err # Swallow errors that arise from data being binary raise err unless err.message.include?('invalid byte sequence') end index.add(fullpath, data) end
[ "def", "add_to_index", "(", "dir", ",", "name", ",", "format", ",", "data", ",", "allow_same_ext", "=", "false", ")", "# spaces must be dashes", "dir", ".", "gsub!", "(", "' '", ",", "'-'", ")", "name", ".", "gsub!", "(", "' '", ",", "'-'", ")", "path", "=", "@wiki", ".", "page_file_name", "(", "name", ",", "format", ")", "dir", "=", "'/'", "if", "dir", ".", "strip", ".", "empty?", "fullpath", "=", "::", "File", ".", "join", "(", "[", "dir", ",", "path", "]", ")", "fullpath", "=", "fullpath", "[", "1", "..", "-", "1", "]", "if", "fullpath", "=~", "/", "\\/", "/", "if", "index", ".", "current_tree", "&&", "(", "tree", "=", "index", ".", "current_tree", "/", "(", "@wiki", ".", "page_file_dir", "||", "'/'", ")", ")", "tree", "=", "tree", "/", "dir", "unless", "tree", ".", "nil?", "end", "if", "tree", "downpath", "=", "path", ".", "downcase", ".", "sub", "(", "/", "\\.", "\\w", "/", ",", "''", ")", "tree", ".", "blobs", ".", "each", "do", "|", "blob", "|", "next", "if", "page_path_scheduled_for_deletion?", "(", "index", ".", "tree", ",", "fullpath", ")", "existing_file", "=", "blob", ".", "name", ".", "downcase", ".", "sub", "(", "/", "\\.", "\\w", "/", ",", "''", ")", "existing_file_ext", "=", "::", "File", ".", "extname", "(", "blob", ".", "name", ")", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "new_file_ext", "=", "::", "File", ".", "extname", "(", "path", ")", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "if", "downpath", "==", "existing_file", "&&", "!", "(", "allow_same_ext", "&&", "new_file_ext", "==", "existing_file_ext", ")", "raise", "DuplicatePageError", ".", "new", "(", "dir", ",", "blob", ".", "name", ",", "path", ")", "end", "end", "end", "fullpath", "=", "fullpath", ".", "force_encoding", "(", "'ascii-8bit'", ")", "if", "fullpath", ".", "respond_to?", "(", ":force_encoding", ")", "begin", "data", "=", "@wiki", ".", "normalize", "(", "data", ")", "rescue", "ArgumentError", "=>", "err", "# Swallow errors that arise from data being binary", "raise", "err", "unless", "err", ".", "message", ".", "include?", "(", "'invalid byte sequence'", ")", "end", "index", ".", "add", "(", "fullpath", ",", "data", ")", "end" ]
Adds a page to the given Index. dir - The String subdirectory of the Gollum::Page without any prefix or suffix slashes (e.g. "foo/bar"). name - The String Gollum::Page filename_stripped. format - The Symbol Gollum::Page format. data - The String wiki data to store in the tree map. allow_same_ext - A Boolean determining if the tree map allows the same filename with the same extension. Raises Gollum::DuplicatePageError if a matching filename already exists. This way, pages are not inadvertently overwritten. Returns nothing (modifies the Index in place).
[ "Adds", "a", "page", "to", "the", "given", "Index", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/committer.rb#L88-L130
15,718
gollum/gollum-lib
lib/gollum-lib/committer.rb
Gollum.Committer.commit
def commit sha1 = index.commit(@options[:message], parents, actor, nil, @wiki.ref) @callbacks.each do |cb| cb.call(self, sha1) end sha1 end
ruby
def commit sha1 = index.commit(@options[:message], parents, actor, nil, @wiki.ref) @callbacks.each do |cb| cb.call(self, sha1) end sha1 end
[ "def", "commit", "sha1", "=", "index", ".", "commit", "(", "@options", "[", ":message", "]", ",", "parents", ",", "actor", ",", "nil", ",", "@wiki", ".", "ref", ")", "@callbacks", ".", "each", "do", "|", "cb", "|", "cb", ".", "call", "(", "self", ",", "sha1", ")", "end", "sha1", "end" ]
Writes the commit to Git and runs the after_commit callbacks. Returns the String SHA1 of the new commit.
[ "Writes", "the", "commit", "to", "Git", "and", "runs", "the", "after_commit", "callbacks", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/committer.rb#L169-L175
15,719
gollum/gollum-lib
lib/gollum-lib/committer.rb
Gollum.Committer.file_path_scheduled_for_deletion?
def file_path_scheduled_for_deletion?(map, path) parts = path.split('/') if parts.size == 1 deletions = map.keys.select { |k| !map[k] } deletions.any? { |d| d == parts.first } else part = parts.shift if (rest = map[part]) file_path_scheduled_for_deletion?(rest, parts.join('/')) else false end end end
ruby
def file_path_scheduled_for_deletion?(map, path) parts = path.split('/') if parts.size == 1 deletions = map.keys.select { |k| !map[k] } deletions.any? { |d| d == parts.first } else part = parts.shift if (rest = map[part]) file_path_scheduled_for_deletion?(rest, parts.join('/')) else false end end end
[ "def", "file_path_scheduled_for_deletion?", "(", "map", ",", "path", ")", "parts", "=", "path", ".", "split", "(", "'/'", ")", "if", "parts", ".", "size", "==", "1", "deletions", "=", "map", ".", "keys", ".", "select", "{", "|", "k", "|", "!", "map", "[", "k", "]", "}", "deletions", ".", "any?", "{", "|", "d", "|", "d", "==", "parts", ".", "first", "}", "else", "part", "=", "parts", ".", "shift", "if", "(", "rest", "=", "map", "[", "part", "]", ")", "file_path_scheduled_for_deletion?", "(", "rest", ",", "parts", ".", "join", "(", "'/'", ")", ")", "else", "false", "end", "end", "end" ]
Determine if a given file is scheduled to be deleted in the next commit for the given Index. map - The Hash map: key - The String directory or filename. val - The Hash submap or the String contents of the file. path - The String path of the file including extension. Returns the Boolean response.
[ "Determine", "if", "a", "given", "file", "is", "scheduled", "to", "be", "deleted", "in", "the", "next", "commit", "for", "the", "given", "Index", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/committer.rb#L222-L235
15,720
gollum/gollum-lib
lib/gollum-lib/committer.rb
Gollum.Committer.method_missing
def method_missing(name, *args) args.map! { |item| item.respond_to?(:force_encoding) ? item.force_encoding('ascii-8bit') : item } index.send(name, *args) end
ruby
def method_missing(name, *args) args.map! { |item| item.respond_to?(:force_encoding) ? item.force_encoding('ascii-8bit') : item } index.send(name, *args) end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "args", ".", "map!", "{", "|", "item", "|", "item", ".", "respond_to?", "(", ":force_encoding", ")", "?", "item", ".", "force_encoding", "(", "'ascii-8bit'", ")", ":", "item", "}", "index", ".", "send", "(", "name", ",", "args", ")", "end" ]
Proxies methods t
[ "Proxies", "methods", "t" ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/committer.rb#L238-L241
15,721
gollum/gollum-lib
lib/gollum-lib/file.rb
Gollum.File.find
def find(name, version, try_on_disk = false) checked = name.downcase map = @wiki.tree_map_for(version) commit = version.is_a?(Gollum::Git::Commit) ? version : @wiki.commit_for(version) if (result = map.detect { |entry| entry.path.downcase == checked }) @path = name @version = commit if try_on_disk && get_disk_reference(name, commit) @on_disk = true else @blob = result.blob(@wiki.repo) end self end end
ruby
def find(name, version, try_on_disk = false) checked = name.downcase map = @wiki.tree_map_for(version) commit = version.is_a?(Gollum::Git::Commit) ? version : @wiki.commit_for(version) if (result = map.detect { |entry| entry.path.downcase == checked }) @path = name @version = commit if try_on_disk && get_disk_reference(name, commit) @on_disk = true else @blob = result.blob(@wiki.repo) end self end end
[ "def", "find", "(", "name", ",", "version", ",", "try_on_disk", "=", "false", ")", "checked", "=", "name", ".", "downcase", "map", "=", "@wiki", ".", "tree_map_for", "(", "version", ")", "commit", "=", "version", ".", "is_a?", "(", "Gollum", "::", "Git", "::", "Commit", ")", "?", "version", ":", "@wiki", ".", "commit_for", "(", "version", ")", "if", "(", "result", "=", "map", ".", "detect", "{", "|", "entry", "|", "entry", ".", "path", ".", "downcase", "==", "checked", "}", ")", "@path", "=", "name", "@version", "=", "commit", "if", "try_on_disk", "&&", "get_disk_reference", "(", "name", ",", "commit", ")", "@on_disk", "=", "true", "else", "@blob", "=", "result", ".", "blob", "(", "@wiki", ".", "repo", ")", "end", "self", "end", "end" ]
Find a file in the given Gollum repo. name - The full String path. version - The String version ID to find. try_on_disk - If true, try to return just a reference to a file that exists on the disk. Returns a Gollum::File or nil if the file could not be found. Note that if you specify try_on_disk=true, you may or may not get a file for which on_disk? is actually true.
[ "Find", "a", "file", "in", "the", "given", "Gollum", "repo", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/file.rb#L138-L155
15,722
gollum/gollum-lib
lib/gollum-lib/blob_entry.rb
Gollum.BlobEntry.page
def page(wiki, commit) blob = self.blob(wiki.repo) page = wiki.page_class.new(wiki).populate(blob, self.dir) page.version = commit page end
ruby
def page(wiki, commit) blob = self.blob(wiki.repo) page = wiki.page_class.new(wiki).populate(blob, self.dir) page.version = commit page end
[ "def", "page", "(", "wiki", ",", "commit", ")", "blob", "=", "self", ".", "blob", "(", "wiki", ".", "repo", ")", "page", "=", "wiki", ".", "page_class", ".", "new", "(", "wiki", ")", ".", "populate", "(", "blob", ",", "self", ".", "dir", ")", "page", ".", "version", "=", "commit", "page", "end" ]
Gets a Page instance for this blob. wiki - Gollum::Wiki instance for the Gollum::Page Returns a Gollum::Page instance.
[ "Gets", "a", "Page", "instance", "for", "this", "blob", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/blob_entry.rb#L49-L54
15,723
gollum/gollum-lib
lib/gollum-lib/blob_entry.rb
Gollum.BlobEntry.file
def file(wiki, commit) blob = self.blob(wiki.repo) file = wiki.file_class.new(wiki).populate(blob, self.dir) file.version = commit file end
ruby
def file(wiki, commit) blob = self.blob(wiki.repo) file = wiki.file_class.new(wiki).populate(blob, self.dir) file.version = commit file end
[ "def", "file", "(", "wiki", ",", "commit", ")", "blob", "=", "self", ".", "blob", "(", "wiki", ".", "repo", ")", "file", "=", "wiki", ".", "file_class", ".", "new", "(", "wiki", ")", ".", "populate", "(", "blob", ",", "self", ".", "dir", ")", "file", ".", "version", "=", "commit", "file", "end" ]
Gets a File instance for this blob. wiki - Gollum::Wiki instance for the Gollum::File Returns a Gollum::File instance.
[ "Gets", "a", "File", "instance", "for", "this", "blob", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/blob_entry.rb#L61-L66
15,724
gollum/gollum-lib
lib/gollum-lib/markup.rb
Gollum.Markup.render_default
def render_default(data, format=:markdown, name='render_default.md') # set instance vars so we're able to render data without a wiki or page. @format = format @name = name chain = [:Metadata, :PlainText, :Emoji, :TOC, :RemoteCode, :Code, :Sanitize, :WSD, :Tags, :Render] filter_chain = chain.map do |r| Gollum::Filter.const_get(r).new(self) end process_chain data, filter_chain end
ruby
def render_default(data, format=:markdown, name='render_default.md') # set instance vars so we're able to render data without a wiki or page. @format = format @name = name chain = [:Metadata, :PlainText, :Emoji, :TOC, :RemoteCode, :Code, :Sanitize, :WSD, :Tags, :Render] filter_chain = chain.map do |r| Gollum::Filter.const_get(r).new(self) end process_chain data, filter_chain end
[ "def", "render_default", "(", "data", ",", "format", "=", ":markdown", ",", "name", "=", "'render_default.md'", ")", "# set instance vars so we're able to render data without a wiki or page.", "@format", "=", "format", "@name", "=", "name", "chain", "=", "[", ":Metadata", ",", ":PlainText", ",", ":Emoji", ",", ":TOC", ",", ":RemoteCode", ",", ":Code", ",", ":Sanitize", ",", ":WSD", ",", ":Tags", ",", ":Render", "]", "filter_chain", "=", "chain", ".", "map", "do", "|", "r", "|", "Gollum", "::", "Filter", ".", "const_get", "(", "r", ")", ".", "new", "(", "self", ")", "end", "process_chain", "data", ",", "filter_chain", "end" ]
Render data using default chain in the target format. data - the data to render format - format to use as a symbol name - name using the extension of the format Returns the processed data
[ "Render", "data", "using", "default", "chain", "in", "the", "target", "format", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/markup.rb#L97-L109
15,725
gollum/gollum-lib
lib/gollum-lib/markup.rb
Gollum.Markup.process_chain
def process_chain(data, filter_chain) # First we extract the data through the chain... filter_chain.each do |filter| data = filter.extract(data) end # Then we process the data through the chain *backwards* filter_chain.reverse.each do |filter| data = filter.process(data) end # Finally, a little bit of cleanup, just because data.gsub!(/<p><\/p>/) do '' end data end
ruby
def process_chain(data, filter_chain) # First we extract the data through the chain... filter_chain.each do |filter| data = filter.extract(data) end # Then we process the data through the chain *backwards* filter_chain.reverse.each do |filter| data = filter.process(data) end # Finally, a little bit of cleanup, just because data.gsub!(/<p><\/p>/) do '' end data end
[ "def", "process_chain", "(", "data", ",", "filter_chain", ")", "# First we extract the data through the chain...", "filter_chain", ".", "each", "do", "|", "filter", "|", "data", "=", "filter", ".", "extract", "(", "data", ")", "end", "# Then we process the data through the chain *backwards*", "filter_chain", ".", "reverse", ".", "each", "do", "|", "filter", "|", "data", "=", "filter", ".", "process", "(", "data", ")", "end", "# Finally, a little bit of cleanup, just because", "data", ".", "gsub!", "(", "/", "\\/", "/", ")", "do", "''", "end", "data", "end" ]
Process the filter chain data - the data to send through the chain filter_chain - the chain to process Returns the formatted data
[ "Process", "the", "filter", "chain" ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/markup.rb#L117-L134
15,726
gollum/gollum-lib
lib/gollum-lib/markup.rb
Gollum.Markup.render
def render(no_follow = false, encoding = nil, include_levels = 10) @sanitize = no_follow ? @wiki.history_sanitizer : @wiki.sanitizer @encoding = encoding @include_levels = include_levels data = @data.dup filter_chain = @wiki.filter_chain.map do |r| Gollum::Filter.const_get(r).new(self) end # Since the last 'extract' action in our chain *should* be the markup # to HTML converter, we now have HTML which we can parse and yield, for # anyone who wants it if block_given? yield Nokogiri::HTML::DocumentFragment.parse(data) end process_chain data, filter_chain end
ruby
def render(no_follow = false, encoding = nil, include_levels = 10) @sanitize = no_follow ? @wiki.history_sanitizer : @wiki.sanitizer @encoding = encoding @include_levels = include_levels data = @data.dup filter_chain = @wiki.filter_chain.map do |r| Gollum::Filter.const_get(r).new(self) end # Since the last 'extract' action in our chain *should* be the markup # to HTML converter, we now have HTML which we can parse and yield, for # anyone who wants it if block_given? yield Nokogiri::HTML::DocumentFragment.parse(data) end process_chain data, filter_chain end
[ "def", "render", "(", "no_follow", "=", "false", ",", "encoding", "=", "nil", ",", "include_levels", "=", "10", ")", "@sanitize", "=", "no_follow", "?", "@wiki", ".", "history_sanitizer", ":", "@wiki", ".", "sanitizer", "@encoding", "=", "encoding", "@include_levels", "=", "include_levels", "data", "=", "@data", ".", "dup", "filter_chain", "=", "@wiki", ".", "filter_chain", ".", "map", "do", "|", "r", "|", "Gollum", "::", "Filter", ".", "const_get", "(", "r", ")", ".", "new", "(", "self", ")", "end", "# Since the last 'extract' action in our chain *should* be the markup", "# to HTML converter, we now have HTML which we can parse and yield, for", "# anyone who wants it", "if", "block_given?", "yield", "Nokogiri", "::", "HTML", "::", "DocumentFragment", ".", "parse", "(", "data", ")", "end", "process_chain", "data", ",", "filter_chain", "end" ]
Render the content with Gollum wiki syntax on top of the file's own markup language. no_follow - Boolean that determines if rel="nofollow" is added to all <a> tags. encoding - Encoding Constant or String. Returns the formatted String content.
[ "Render", "the", "content", "with", "Gollum", "wiki", "syntax", "on", "top", "of", "the", "file", "s", "own", "markup", "language", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/markup.rb#L144-L165
15,727
gollum/gollum-lib
lib/gollum-lib/markup.rb
Gollum.Markup.find_file
def find_file(name, version=@version) if name =~ /^\// @wiki.file(name[1..-1], version) else path = @dir == '.' ? name : ::File.join(@dir, name) @wiki.file(path, version) end end
ruby
def find_file(name, version=@version) if name =~ /^\// @wiki.file(name[1..-1], version) else path = @dir == '.' ? name : ::File.join(@dir, name) @wiki.file(path, version) end end
[ "def", "find_file", "(", "name", ",", "version", "=", "@version", ")", "if", "name", "=~", "/", "\\/", "/", "@wiki", ".", "file", "(", "name", "[", "1", "..", "-", "1", "]", ",", "version", ")", "else", "path", "=", "@dir", "==", "'.'", "?", "name", ":", "::", "File", ".", "join", "(", "@dir", ",", "name", ")", "@wiki", ".", "file", "(", "path", ",", "version", ")", "end", "end" ]
Find the given file in the repo. name - The String absolute or relative path of the file. Returns the Gollum::File or nil if none was found.
[ "Find", "the", "given", "file", "in", "the", "repo", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/markup.rb#L172-L179
15,728
gollum/gollum-lib
lib/gollum-lib/wiki.rb
Gollum.Wiki.remove_filter
def remove_filter(name) unless name.is_a? Symbol raise ArgumentError, "Invalid filter name #{name.inspect} (must be a symbol)" end unless @filter_chain.delete(name) raise ArgumentError, "#{name.inspect} not found in filter chain" end end
ruby
def remove_filter(name) unless name.is_a? Symbol raise ArgumentError, "Invalid filter name #{name.inspect} (must be a symbol)" end unless @filter_chain.delete(name) raise ArgumentError, "#{name.inspect} not found in filter chain" end end
[ "def", "remove_filter", "(", "name", ")", "unless", "name", ".", "is_a?", "Symbol", "raise", "ArgumentError", ",", "\"Invalid filter name #{name.inspect} (must be a symbol)\"", "end", "unless", "@filter_chain", ".", "delete", "(", "name", ")", "raise", "ArgumentError", ",", "\"#{name.inspect} not found in filter chain\"", "end", "end" ]
Remove the named filter from the filter chain. Returns nothing. Raises `ArgumentError` if the named filter doesn't exist in the chain.
[ "Remove", "the", "named", "filter", "from", "the", "filter", "chain", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/wiki.rb#L775-L785
15,729
gollum/gollum-lib
lib/gollum-lib/wiki.rb
Gollum.Wiki.tree_list
def tree_list(ref) if (sha = @access.ref_to_sha(ref)) commit = @access.commit(sha) tree_map_for(sha).inject([]) do |list, entry| next list unless @page_class.valid_page_name?(entry.name) list << entry.page(self, commit) end else [] end end
ruby
def tree_list(ref) if (sha = @access.ref_to_sha(ref)) commit = @access.commit(sha) tree_map_for(sha).inject([]) do |list, entry| next list unless @page_class.valid_page_name?(entry.name) list << entry.page(self, commit) end else [] end end
[ "def", "tree_list", "(", "ref", ")", "if", "(", "sha", "=", "@access", ".", "ref_to_sha", "(", "ref", ")", ")", "commit", "=", "@access", ".", "commit", "(", "sha", ")", "tree_map_for", "(", "sha", ")", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "entry", "|", "next", "list", "unless", "@page_class", ".", "valid_page_name?", "(", "entry", ".", "name", ")", "list", "<<", "entry", ".", "page", "(", "self", ",", "commit", ")", "end", "else", "[", "]", "end", "end" ]
Fill an array with a list of pages. ref - A String ref that is either a commit SHA or references one. Returns a flat Array of Gollum::Page instances.
[ "Fill", "an", "array", "with", "a", "list", "of", "pages", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/wiki.rb#L859-L869
15,730
gollum/gollum-lib
lib/gollum-lib/wiki.rb
Gollum.Wiki.file_list
def file_list(ref) if (sha = @access.ref_to_sha(ref)) commit = @access.commit(sha) tree_map_for(sha).inject([]) do |list, entry| next list if entry.name.start_with?('_') next list if @page_class.valid_page_name?(entry.name) list << entry.file(self, commit) end else [] end end
ruby
def file_list(ref) if (sha = @access.ref_to_sha(ref)) commit = @access.commit(sha) tree_map_for(sha).inject([]) do |list, entry| next list if entry.name.start_with?('_') next list if @page_class.valid_page_name?(entry.name) list << entry.file(self, commit) end else [] end end
[ "def", "file_list", "(", "ref", ")", "if", "(", "sha", "=", "@access", ".", "ref_to_sha", "(", "ref", ")", ")", "commit", "=", "@access", ".", "commit", "(", "sha", ")", "tree_map_for", "(", "sha", ")", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "entry", "|", "next", "list", "if", "entry", ".", "name", ".", "start_with?", "(", "'_'", ")", "next", "list", "if", "@page_class", ".", "valid_page_name?", "(", "entry", ".", "name", ")", "list", "<<", "entry", ".", "file", "(", "self", ",", "commit", ")", "end", "else", "[", "]", "end", "end" ]
Fill an array with a list of files. ref - A String ref that is either a commit SHA or references one. Returns a flat Array of Gollum::File instances.
[ "Fill", "an", "array", "with", "a", "list", "of", "files", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/wiki.rb#L876-L887
15,731
gollum/gollum-lib
lib/gollum-lib/wiki.rb
Gollum.Wiki.tree_map_for
def tree_map_for(ref, ignore_page_file_dir=false) if ignore_page_file_dir && !@page_file_dir.nil? @root_access ||= GitAccess.new(path, nil, @repo_is_bare) @root_access.tree(ref) else @access.tree(ref) end rescue Gollum::Git::NoSuchShaFound [] end
ruby
def tree_map_for(ref, ignore_page_file_dir=false) if ignore_page_file_dir && !@page_file_dir.nil? @root_access ||= GitAccess.new(path, nil, @repo_is_bare) @root_access.tree(ref) else @access.tree(ref) end rescue Gollum::Git::NoSuchShaFound [] end
[ "def", "tree_map_for", "(", "ref", ",", "ignore_page_file_dir", "=", "false", ")", "if", "ignore_page_file_dir", "&&", "!", "@page_file_dir", ".", "nil?", "@root_access", "||=", "GitAccess", ".", "new", "(", "path", ",", "nil", ",", "@repo_is_bare", ")", "@root_access", ".", "tree", "(", "ref", ")", "else", "@access", ".", "tree", "(", "ref", ")", "end", "rescue", "Gollum", "::", "Git", "::", "NoSuchShaFound", "[", "]", "end" ]
Finds a full listing of files and their blob SHA for a given ref. Each listing is cached based on its actual commit SHA. ref - A String ref that is either a commit SHA or references one. ignore_page_file_dir - Boolean, if true, searches all files within the git repo, regardless of dir/subdir Returns an Array of BlobEntry instances.
[ "Finds", "a", "full", "listing", "of", "files", "and", "their", "blob", "SHA", "for", "a", "given", "ref", ".", "Each", "listing", "is", "cached", "based", "on", "its", "actual", "commit", "SHA", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/wiki.rb#L951-L960
15,732
gollum/gollum-lib
lib/gollum-lib/git_access.rb
Gollum.GitAccess.get_cache
def get_cache(name, key) cache = instance_variable_get("@#{name}_map") value = cache[key] if value.nil? && block_given? set_cache(name, key, value = yield) end value == :_nil ? nil : value end
ruby
def get_cache(name, key) cache = instance_variable_get("@#{name}_map") value = cache[key] if value.nil? && block_given? set_cache(name, key, value = yield) end value == :_nil ? nil : value end
[ "def", "get_cache", "(", "name", ",", "key", ")", "cache", "=", "instance_variable_get", "(", "\"@#{name}_map\"", ")", "value", "=", "cache", "[", "key", "]", "if", "value", ".", "nil?", "&&", "block_given?", "set_cache", "(", "name", ",", "key", ",", "value", "=", "yield", ")", "end", "value", "==", ":_nil", "?", "nil", ":", "value", "end" ]
Attempts to get the given data from a cache. If it doesn't exist, it'll pass the results of the yielded block to the cache for future accesses. name - The cache prefix used in building the full cache key. key - The unique cache key suffix, usually a String Git SHA. Yields a block to pass to the cache. Returns the cached result.
[ "Attempts", "to", "get", "the", "given", "data", "from", "a", "cache", ".", "If", "it", "doesn", "t", "exist", "it", "ll", "pass", "the", "results", "of", "the", "yielded", "block", "to", "the", "cache", "for", "future", "accesses", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/git_access.rb#L201-L208
15,733
gollum/gollum-lib
lib/gollum-lib/git_access.rb
Gollum.GitAccess.parse_tree_line
def parse_tree_line(line) mode, _type, sha, size, *name = line.split(/\s+/) BlobEntry.new(sha, name.join(' '), size.to_i, mode.to_i(8)) end
ruby
def parse_tree_line(line) mode, _type, sha, size, *name = line.split(/\s+/) BlobEntry.new(sha, name.join(' '), size.to_i, mode.to_i(8)) end
[ "def", "parse_tree_line", "(", "line", ")", "mode", ",", "_type", ",", "sha", ",", "size", ",", "*", "name", "=", "line", ".", "split", "(", "/", "\\s", "/", ")", "BlobEntry", ".", "new", "(", "sha", ",", "name", ".", "join", "(", "' '", ")", ",", "size", ".", "to_i", ",", "mode", ".", "to_i", "(", "8", ")", ")", "end" ]
Parses a line of output from the `ls-tree` command. line - A String line of output: "100644 blob 839c2291b30495b9a882c17d08254d3c90d8fb53 Home.md" Returns an Array of BlobEntry instances.
[ "Parses", "a", "line", "of", "output", "from", "the", "ls", "-", "tree", "command", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/git_access.rb#L228-L231
15,734
gollum/gollum-lib
lib/gollum-lib/page.rb
Gollum.Page.find
def find(name, version, dir = nil, exact = false) map = @wiki.tree_map_for(version.to_s) if (page = find_page_in_tree(map, name, dir, exact)) page.version = version.is_a?(Gollum::Git::Commit) ? version : @wiki.commit_for(version) page.historical = page.version.to_s == version.to_s page end rescue Gollum::Git::NoSuchShaFound end
ruby
def find(name, version, dir = nil, exact = false) map = @wiki.tree_map_for(version.to_s) if (page = find_page_in_tree(map, name, dir, exact)) page.version = version.is_a?(Gollum::Git::Commit) ? version : @wiki.commit_for(version) page.historical = page.version.to_s == version.to_s page end rescue Gollum::Git::NoSuchShaFound end
[ "def", "find", "(", "name", ",", "version", ",", "dir", "=", "nil", ",", "exact", "=", "false", ")", "map", "=", "@wiki", ".", "tree_map_for", "(", "version", ".", "to_s", ")", "if", "(", "page", "=", "find_page_in_tree", "(", "map", ",", "name", ",", "dir", ",", "exact", ")", ")", "page", ".", "version", "=", "version", ".", "is_a?", "(", "Gollum", "::", "Git", "::", "Commit", ")", "?", "version", ":", "@wiki", ".", "commit_for", "(", "version", ")", "page", ".", "historical", "=", "page", ".", "version", ".", "to_s", "==", "version", ".", "to_s", "page", "end", "rescue", "Gollum", "::", "Git", "::", "NoSuchShaFound", "end" ]
Find a page in the given Gollum repo. name - The human or canonical String page name to find. version - The String version ID to find. Returns a Gollum::Page or nil if the page could not be found.
[ "Find", "a", "page", "in", "the", "given", "Gollum", "repo", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/page.rb#L392-L401
15,735
gollum/gollum-lib
lib/gollum-lib/page.rb
Gollum.Page.find_page_in_tree
def find_page_in_tree(map, name, checked_dir = nil, exact = false) return nil if !map || name.to_s.empty? checked_dir = BlobEntry.normalize_dir(checked_dir) checked_dir = '' if exact && checked_dir.nil? name = ::File.join(checked_dir, name) if checked_dir map.each do |entry| next if entry.name.to_s.empty? path = checked_dir ? ::File.join(entry.dir, entry.name) : entry.name next unless page_match(name, path) return entry.page(@wiki, @version) end return nil # nothing was found end
ruby
def find_page_in_tree(map, name, checked_dir = nil, exact = false) return nil if !map || name.to_s.empty? checked_dir = BlobEntry.normalize_dir(checked_dir) checked_dir = '' if exact && checked_dir.nil? name = ::File.join(checked_dir, name) if checked_dir map.each do |entry| next if entry.name.to_s.empty? path = checked_dir ? ::File.join(entry.dir, entry.name) : entry.name next unless page_match(name, path) return entry.page(@wiki, @version) end return nil # nothing was found end
[ "def", "find_page_in_tree", "(", "map", ",", "name", ",", "checked_dir", "=", "nil", ",", "exact", "=", "false", ")", "return", "nil", "if", "!", "map", "||", "name", ".", "to_s", ".", "empty?", "checked_dir", "=", "BlobEntry", ".", "normalize_dir", "(", "checked_dir", ")", "checked_dir", "=", "''", "if", "exact", "&&", "checked_dir", ".", "nil?", "name", "=", "::", "File", ".", "join", "(", "checked_dir", ",", "name", ")", "if", "checked_dir", "map", ".", "each", "do", "|", "entry", "|", "next", "if", "entry", ".", "name", ".", "to_s", ".", "empty?", "path", "=", "checked_dir", "?", "::", "File", ".", "join", "(", "entry", ".", "dir", ",", "entry", ".", "name", ")", ":", "entry", ".", "name", "next", "unless", "page_match", "(", "name", ",", "path", ")", "return", "entry", ".", "page", "(", "@wiki", ",", "@version", ")", "end", "return", "nil", "# nothing was found", "end" ]
Find a page in a given tree. map - The Array tree map from Wiki#tree_map. name - The canonical String page name. checked_dir - Optional String of the directory a matching page needs to be in. The string should Returns a Gollum::Page or nil if the page could not be found.
[ "Find", "a", "page", "in", "a", "given", "tree", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/page.rb#L411-L426
15,736
gollum/gollum-lib
lib/gollum-lib/page.rb
Gollum.Page.tree_path
def tree_path(treemap, tree) if (ptree = treemap[tree]) tree_path(treemap, ptree) + '/' + tree.name else '' end end
ruby
def tree_path(treemap, tree) if (ptree = treemap[tree]) tree_path(treemap, ptree) + '/' + tree.name else '' end end
[ "def", "tree_path", "(", "treemap", ",", "tree", ")", "if", "(", "ptree", "=", "treemap", "[", "tree", "]", ")", "tree_path", "(", "treemap", ",", "ptree", ")", "+", "'/'", "+", "tree", ".", "name", "else", "''", "end", "end" ]
The full directory path for the given tree. treemap - The Hash treemap containing parentage information. tree - The Gollum::Git::Tree for which to compute the path. Returns the String path.
[ "The", "full", "directory", "path", "for", "the", "given", "tree", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/page.rb#L446-L452
15,737
gollum/gollum-lib
lib/gollum-lib/page.rb
Gollum.Page.page_match
def page_match(name, path) if (match = self.class.valid_filename?(path)) @wiki.ws_subs.each do |sub| return true if Page.cname(name).downcase == Page.cname(match, sub).downcase end end false end
ruby
def page_match(name, path) if (match = self.class.valid_filename?(path)) @wiki.ws_subs.each do |sub| return true if Page.cname(name).downcase == Page.cname(match, sub).downcase end end false end
[ "def", "page_match", "(", "name", ",", "path", ")", "if", "(", "match", "=", "self", ".", "class", ".", "valid_filename?", "(", "path", ")", ")", "@wiki", ".", "ws_subs", ".", "each", "do", "|", "sub", "|", "return", "true", "if", "Page", ".", "cname", "(", "name", ")", ".", "downcase", "==", "Page", ".", "cname", "(", "match", ",", "sub", ")", ".", "downcase", "end", "end", "false", "end" ]
Compare the canonicalized versions of the two names. name - The human or canonical String page name. path - the String path on disk (including file extension). Returns a Boolean.
[ "Compare", "the", "canonicalized", "versions", "of", "the", "two", "names", "." ]
e811f79cb569f1bf0711947d49105db60421e2c1
https://github.com/gollum/gollum-lib/blob/e811f79cb569f1bf0711947d49105db60421e2c1/lib/gollum-lib/page.rb#L460-L467
15,738
lessonly/scim_rails
app/controllers/concerns/scim_rails/response.rb
ScimRails.Response.find_value
def find_value(user, object) case object when Hash object.each.with_object({}) do |(key, value), hash| hash[key] = find_value(user, value) end when Array object.map do |value| find_value(user, value) end when Symbol user.public_send(object) else object end end
ruby
def find_value(user, object) case object when Hash object.each.with_object({}) do |(key, value), hash| hash[key] = find_value(user, value) end when Array object.map do |value| find_value(user, value) end when Symbol user.public_send(object) else object end end
[ "def", "find_value", "(", "user", ",", "object", ")", "case", "object", "when", "Hash", "object", ".", "each", ".", "with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "hash", "|", "hash", "[", "key", "]", "=", "find_value", "(", "user", ",", "value", ")", "end", "when", "Array", "object", ".", "map", "do", "|", "value", "|", "find_value", "(", "user", ",", "value", ")", "end", "when", "Symbol", "user", ".", "public_send", "(", "object", ")", "else", "object", "end", "end" ]
`find_value` is a recursive method that takes a "user" and a "user schema" and replaces any symbols in the schema with the corresponding value from the user. Given a schema with symbols, `find_value` will search through the object for the symbols, send those symbols to the model, and replace the symbol with the return value.
[ "find_value", "is", "a", "recursive", "method", "that", "takes", "a", "user", "and", "a", "user", "schema", "and", "replaces", "any", "symbols", "in", "the", "schema", "with", "the", "corresponding", "value", "from", "the", "user", ".", "Given", "a", "schema", "with", "symbols", "find_value", "will", "search", "through", "the", "object", "for", "the", "symbols", "send", "those", "symbols", "to", "the", "model", "and", "replace", "the", "symbol", "with", "the", "return", "value", "." ]
085e0aae5da72d719f8d42b6785710bd97b0a8a4
https://github.com/lessonly/scim_rails/blob/085e0aae5da72d719f8d42b6785710bd97b0a8a4/app/controllers/concerns/scim_rails/response.rb#L64-L79
15,739
lessonly/scim_rails
app/controllers/scim_rails/scim_users_controller.rb
ScimRails.ScimUsersController.path_for
def path_for(attribute, object = ScimRails.config.mutable_user_attributes_schema, path = []) at_path = path.empty? ? object : object.dig(*path) return path if at_path == attribute case at_path when Hash at_path.each do |key, value| found_path = path_for(attribute, object, [*path, key]) return found_path if found_path end nil when Array at_path.each_with_index do |value, index| found_path = path_for(attribute, object, [*path, index]) return found_path if found_path end nil end end
ruby
def path_for(attribute, object = ScimRails.config.mutable_user_attributes_schema, path = []) at_path = path.empty? ? object : object.dig(*path) return path if at_path == attribute case at_path when Hash at_path.each do |key, value| found_path = path_for(attribute, object, [*path, key]) return found_path if found_path end nil when Array at_path.each_with_index do |value, index| found_path = path_for(attribute, object, [*path, index]) return found_path if found_path end nil end end
[ "def", "path_for", "(", "attribute", ",", "object", "=", "ScimRails", ".", "config", ".", "mutable_user_attributes_schema", ",", "path", "=", "[", "]", ")", "at_path", "=", "path", ".", "empty?", "?", "object", ":", "object", ".", "dig", "(", "path", ")", "return", "path", "if", "at_path", "==", "attribute", "case", "at_path", "when", "Hash", "at_path", ".", "each", "do", "|", "key", ",", "value", "|", "found_path", "=", "path_for", "(", "attribute", ",", "object", ",", "[", "path", ",", "key", "]", ")", "return", "found_path", "if", "found_path", "end", "nil", "when", "Array", "at_path", ".", "each_with_index", "do", "|", "value", ",", "index", "|", "found_path", "=", "path_for", "(", "attribute", ",", "object", ",", "[", "path", ",", "index", "]", ")", "return", "found_path", "if", "found_path", "end", "nil", "end", "end" ]
`path_for` is a recursive method used to find the "path" for `.dig` to take when looking for a given attribute in the params. Example: `path_for(:name)` should return an array that looks like [:names, 0, :givenName]. `.dig` can then use that path against the params to translate the :name attribute to "John".
[ "path_for", "is", "a", "recursive", "method", "used", "to", "find", "the", "path", "for", ".", "dig", "to", "take", "when", "looking", "for", "a", "given", "attribute", "in", "the", "params", "." ]
085e0aae5da72d719f8d42b6785710bd97b0a8a4
https://github.com/lessonly/scim_rails/blob/085e0aae5da72d719f8d42b6785710bd97b0a8a4/app/controllers/scim_rails/scim_users_controller.rb#L81-L99
15,740
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.send_envelope
def send_envelope(envelope_id) content_type = { 'Content-Type' => 'application/json' } post_body = { status: 'sent' }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Put.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end
ruby
def send_envelope(envelope_id) content_type = { 'Content-Type' => 'application/json' } post_body = { status: 'sent' }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Put.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end
[ "def", "send_envelope", "(", "envelope_id", ")", "content_type", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "post_body", "=", "{", "status", ":", "'sent'", "}", ".", "to_json", "uri", "=", "build_uri", "(", "\"/accounts/#{acct_id}/envelopes/#{envelope_id}\"", ")", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", "(", "content_type", ")", ")", "request", ".", "body", "=", "post_body", "response", "=", "http", ".", "request", "(", "request", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Public marks an envelope as sent envelope_id - ID of the envelope which you want to send Returns the response (success or failure).
[ "Public", "marks", "an", "envelope", "as", "sent" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1009-L1024
15,741
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.get_recipient_view
def get_recipient_view(options={}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] post_body = { authenticationMethod: 'email', clientUserId: options[:client_id] || options[:email], email: options[:email], returnUrl: options[:return_url], userName: options[:name] }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) generate_log(request, response, uri) JSON.parse(response.body) end
ruby
def get_recipient_view(options={}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] post_body = { authenticationMethod: 'email', clientUserId: options[:client_id] || options[:email], email: options[:email], returnUrl: options[:return_url], userName: options[:name] }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) generate_log(request, response, uri) JSON.parse(response.body) end
[ "def", "get_recipient_view", "(", "options", "=", "{", "}", ")", "content_type", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "content_type", ".", "merge", "(", "options", "[", ":headers", "]", ")", "if", "options", "[", ":headers", "]", "post_body", "=", "{", "authenticationMethod", ":", "'email'", ",", "clientUserId", ":", "options", "[", ":client_id", "]", "||", "options", "[", ":email", "]", ",", "email", ":", "options", "[", ":email", "]", ",", "returnUrl", ":", "options", "[", ":return_url", "]", ",", "userName", ":", "options", "[", ":name", "]", "}", ".", "to_json", "uri", "=", "build_uri", "(", "\"/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient\"", ")", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", "(", "content_type", ")", ")", "request", ".", "body", "=", "post_body", "response", "=", "http", ".", "request", "(", "request", ")", "generate_log", "(", "request", ",", "response", ",", "uri", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Public returns the URL for embedded signing envelope_id - the ID of the envelope you wish to use for embedded signing name - the name of the signer email - the email of the recipient return_url - the URL you want the user to be directed to after he or she completes the document signing headers - optional hash of headers to merge into the existing required headers for a multipart request. Returns the URL string for embedded signing (can be put in an iFrame)
[ "Public", "returns", "the", "URL", "for", "embedded", "signing" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1091-L1113
15,742
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.get_envelope_recipients
def get_envelope_recipients(options={}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] include_tabs = options[:include_tabs] || false include_extended = options[:include_extended] || false uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) generate_log(request, response, uri) JSON.parse(response.body) end
ruby
def get_envelope_recipients(options={}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] include_tabs = options[:include_tabs] || false include_extended = options[:include_extended] || false uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) generate_log(request, response, uri) JSON.parse(response.body) end
[ "def", "get_envelope_recipients", "(", "options", "=", "{", "}", ")", "content_type", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "content_type", ".", "merge", "(", "options", "[", ":headers", "]", ")", "if", "options", "[", ":headers", "]", "include_tabs", "=", "options", "[", ":include_tabs", "]", "||", "false", "include_extended", "=", "options", "[", ":include_extended", "]", "||", "false", "uri", "=", "build_uri", "(", "\"/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}\"", ")", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", "(", "content_type", ")", ")", "response", "=", "http", ".", "request", "(", "request", ")", "generate_log", "(", "request", ",", "response", ",", "uri", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Public returns the envelope recipients for a given envelope include_tabs - boolean, determines if the tabs for each signer will be returned in the response, defaults to false. envelope_id - ID of the envelope for which you want to retrieve the signer info headers - optional hash of headers to merge into the existing required headers for a multipart request. Returns a hash of detailed info about the envelope including the signer hash and status of each signer
[ "Public", "returns", "the", "envelope", "recipients", "for", "a", "given", "envelope" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1180-L1193
15,743
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.get_page_image
def get_page_image(options={}) envelope_id = options[:envelope_id] document_id = options[:document_id] page_number = options[:page_number] uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}/documents/#{document_id}/pages/#{page_number}/page_image") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers) response = http.request(request) generate_log(request, response, uri) response.body end
ruby
def get_page_image(options={}) envelope_id = options[:envelope_id] document_id = options[:document_id] page_number = options[:page_number] uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}/documents/#{document_id}/pages/#{page_number}/page_image") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers) response = http.request(request) generate_log(request, response, uri) response.body end
[ "def", "get_page_image", "(", "options", "=", "{", "}", ")", "envelope_id", "=", "options", "[", ":envelope_id", "]", "document_id", "=", "options", "[", ":document_id", "]", "page_number", "=", "options", "[", ":page_number", "]", "uri", "=", "build_uri", "(", "\"/accounts/#{acct_id}/envelopes/#{envelope_id}/documents/#{document_id}/pages/#{page_number}/page_image\"", ")", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", ")", "response", "=", "http", ".", "request", "(", "request", ")", "generate_log", "(", "request", ",", "response", ",", "uri", ")", "response", ".", "body", "end" ]
Public retrieves a png of a page of a document in an envelope envelope_id - ID of the envelope from which the doc will be retrieved document_id - ID of the document to retrieve page_number - page number to retrieve Returns the png as a bytestream
[ "Public", "retrieves", "a", "png", "of", "a", "page", "of", "a", "document", "in", "an", "envelope" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1250-L1262
15,744
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.get_document_from_envelope
def get_document_from_envelope(options={}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) generate_log(request, response, uri) return response.body if options[:return_stream] split_path = options[:local_save_path].split('/') split_path.pop #removes the document name and extension from the array path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file FileUtils.mkdir_p(path) File.open(options[:local_save_path], 'wb') do |output| output << response.body end end
ruby
def get_document_from_envelope(options={}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) generate_log(request, response, uri) return response.body if options[:return_stream] split_path = options[:local_save_path].split('/') split_path.pop #removes the document name and extension from the array path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file FileUtils.mkdir_p(path) File.open(options[:local_save_path], 'wb') do |output| output << response.body end end
[ "def", "get_document_from_envelope", "(", "options", "=", "{", "}", ")", "content_type", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "content_type", ".", "merge", "(", "options", "[", ":headers", "]", ")", "if", "options", "[", ":headers", "]", "uri", "=", "build_uri", "(", "\"/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}\"", ")", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", "(", "content_type", ")", ")", "response", "=", "http", ".", "request", "(", "request", ")", "generate_log", "(", "request", ",", "response", ",", "uri", ")", "return", "response", ".", "body", "if", "options", "[", ":return_stream", "]", "split_path", "=", "options", "[", ":local_save_path", "]", ".", "split", "(", "'/'", ")", "split_path", ".", "pop", "#removes the document name and extension from the array", "path", "=", "split_path", ".", "join", "(", "\"/\"", ")", "#rejoins the array to form path to the folder that will contain the file", "FileUtils", ".", "mkdir_p", "(", "path", ")", "File", ".", "open", "(", "options", "[", ":local_save_path", "]", ",", "'wb'", ")", "do", "|", "output", "|", "output", "<<", "response", ".", "body", "end", "end" ]
Public retrieves the attached file from a given envelope envelope_id - ID of the envelope from which the doc will be retrieved document_id - ID of the document to retrieve local_save_path - Local absolute path to save the doc to including the filename itself headers - Optional hash of headers to merge into the existing required headers for a multipart request. Example client.get_document_from_envelope( envelope_id: @envelope_response['envelopeId'], document_id: 1, local_save_path: 'docusign_docs/file_name.pdf', return_stream: true/false # will return the bytestream instead of saving doc to file system. ) Returns the PDF document as a byte stream.
[ "Public", "retrieves", "the", "attached", "file", "from", "a", "given", "envelope" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1283-L1303
15,745
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.delete_envelope_recipient
def delete_envelope_recipient(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients") post_body = "{ \"signers\" : [{\"recipientId\" : \"#{options[:recipient_id]}\"}] }" http = initialize_net_http_ssl(uri) request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) generate_log(request, response, uri) JSON.parse(response.body) end
ruby
def delete_envelope_recipient(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients") post_body = "{ \"signers\" : [{\"recipientId\" : \"#{options[:recipient_id]}\"}] }" http = initialize_net_http_ssl(uri) request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) generate_log(request, response, uri) JSON.parse(response.body) end
[ "def", "delete_envelope_recipient", "(", "options", "=", "{", "}", ")", "content_type", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "content_type", ".", "merge", "(", "options", "[", ":headers", "]", ")", "if", "options", "[", ":headers", "]", "uri", "=", "build_uri", "(", "\"/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients\"", ")", "post_body", "=", "\"{\n \\\"signers\\\" : [{\\\"recipientId\\\" : \\\"#{options[:recipient_id]}\\\"}]\n }\"", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", "(", "content_type", ")", ")", "request", ".", "body", "=", "post_body", "response", "=", "http", ".", "request", "(", "request", ")", "generate_log", "(", "request", ",", "response", ",", "uri", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Public deletes a recipient for a given envelope envelope_id - ID of the envelope for which you want to retrieve the signer info recipient_id - ID of the recipient to delete Returns a hash of recipients with an error code for any recipients that were not successfully deleted.
[ "Public", "deletes", "a", "recipient", "for", "a", "given", "envelope" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1596-L1612
15,746
jondkinney/docusign_rest
lib/docusign_rest/client.rb
DocusignRest.Client.void_envelope
def void_envelope(options = {}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] post_body = { "status" =>"voided", "voidedReason" => options[:voided_reason] || "No reason provided." }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Put.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) generate_log(request, response, uri) response end
ruby
def void_envelope(options = {}) content_type = { 'Content-Type' => 'application/json' } content_type.merge(options[:headers]) if options[:headers] post_body = { "status" =>"voided", "voidedReason" => options[:voided_reason] || "No reason provided." }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Put.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) generate_log(request, response, uri) response end
[ "def", "void_envelope", "(", "options", "=", "{", "}", ")", "content_type", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "content_type", ".", "merge", "(", "options", "[", ":headers", "]", ")", "if", "options", "[", ":headers", "]", "post_body", "=", "{", "\"status\"", "=>", "\"voided\"", ",", "\"voidedReason\"", "=>", "options", "[", ":voided_reason", "]", "||", "\"No reason provided.\"", "}", ".", "to_json", "uri", "=", "build_uri", "(", "\"/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}\"", ")", "http", "=", "initialize_net_http_ssl", "(", "uri", ")", "request", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "uri", ".", "request_uri", ",", "headers", "(", "content_type", ")", ")", "request", ".", "body", "=", "post_body", "response", "=", "http", ".", "request", "(", "request", ")", "generate_log", "(", "request", ",", "response", ",", "uri", ")", "response", "end" ]
Public voids an in-process envelope envelope_id - ID of the envelope to be voided voided_reason - Optional reason for the envelope being voided Returns the response (success or failure).
[ "Public", "voids", "an", "in", "-", "process", "envelope" ]
f93eaff7b649336ef54fe5310c4c00d74531e5e1
https://github.com/jondkinney/docusign_rest/blob/f93eaff7b649336ef54fe5310c4c00d74531e5e1/lib/docusign_rest/client.rb#L1621-L1638
15,747
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.validate_uncles
def validate_uncles return false if Utils.keccak256_rlp(uncles) != uncles_hash return false if uncles.size > config[:max_uncles] uncles.each do |uncle| raise InvalidUncles, "Cannot find uncle prevhash in db" unless db.include?(uncle.prevhash) if uncle.number == number logger.error "uncle at same block height", block: self return false end end max_uncle_depth = config[:max_uncle_depth] ancestor_chain = [self] + get_ancestor_list(max_uncle_depth+1) raise ValueError, "invalid ancestor chain" unless ancestor_chain.size == [number+1, max_uncle_depth+2].min # Uncles of this block cannot be direct ancestors and cannot also be # uncles included 1-6 blocks ago. ineligible = [] ancestor_chain.safe_slice(1..-1).each {|a| ineligible.concat a.uncles } ineligible.concat(ancestor_chain.map {|a| a.header }) eligible_ancestor_hashes = ancestor_chain.safe_slice(2..-1).map(&:full_hash) uncles.each do |uncle| parent = Block.find env, uncle.prevhash return false if uncle.difficulty != Block.calc_difficulty(parent, uncle.timestamp) return false if uncle.number != parent.number + 1 return false if uncle.timestamp < parent.timestamp return false unless uncle.check_pow unless eligible_ancestor_hashes.include?(uncle.prevhash) eligible = eligible_ancestor_hashes.map {|h| Utils.encode_hex(h) } logger.error "Uncle does not have a valid ancestor", block: self, eligible: eligible, uncle_prevhash: Utils.encode_hex(uncle.prevhash) return false end if ineligible.include?(uncle) logger.error "Duplicate uncle", block: self, uncle: Utils.encode_hex(Utils.keccak256_rlp(uncle)) return false end # FIXME: what if uncles include previously rewarded uncle? ineligible.push uncle end true end
ruby
def validate_uncles return false if Utils.keccak256_rlp(uncles) != uncles_hash return false if uncles.size > config[:max_uncles] uncles.each do |uncle| raise InvalidUncles, "Cannot find uncle prevhash in db" unless db.include?(uncle.prevhash) if uncle.number == number logger.error "uncle at same block height", block: self return false end end max_uncle_depth = config[:max_uncle_depth] ancestor_chain = [self] + get_ancestor_list(max_uncle_depth+1) raise ValueError, "invalid ancestor chain" unless ancestor_chain.size == [number+1, max_uncle_depth+2].min # Uncles of this block cannot be direct ancestors and cannot also be # uncles included 1-6 blocks ago. ineligible = [] ancestor_chain.safe_slice(1..-1).each {|a| ineligible.concat a.uncles } ineligible.concat(ancestor_chain.map {|a| a.header }) eligible_ancestor_hashes = ancestor_chain.safe_slice(2..-1).map(&:full_hash) uncles.each do |uncle| parent = Block.find env, uncle.prevhash return false if uncle.difficulty != Block.calc_difficulty(parent, uncle.timestamp) return false if uncle.number != parent.number + 1 return false if uncle.timestamp < parent.timestamp return false unless uncle.check_pow unless eligible_ancestor_hashes.include?(uncle.prevhash) eligible = eligible_ancestor_hashes.map {|h| Utils.encode_hex(h) } logger.error "Uncle does not have a valid ancestor", block: self, eligible: eligible, uncle_prevhash: Utils.encode_hex(uncle.prevhash) return false end if ineligible.include?(uncle) logger.error "Duplicate uncle", block: self, uncle: Utils.encode_hex(Utils.keccak256_rlp(uncle)) return false end # FIXME: what if uncles include previously rewarded uncle? ineligible.push uncle end true end
[ "def", "validate_uncles", "return", "false", "if", "Utils", ".", "keccak256_rlp", "(", "uncles", ")", "!=", "uncles_hash", "return", "false", "if", "uncles", ".", "size", ">", "config", "[", ":max_uncles", "]", "uncles", ".", "each", "do", "|", "uncle", "|", "raise", "InvalidUncles", ",", "\"Cannot find uncle prevhash in db\"", "unless", "db", ".", "include?", "(", "uncle", ".", "prevhash", ")", "if", "uncle", ".", "number", "==", "number", "logger", ".", "error", "\"uncle at same block height\"", ",", "block", ":", "self", "return", "false", "end", "end", "max_uncle_depth", "=", "config", "[", ":max_uncle_depth", "]", "ancestor_chain", "=", "[", "self", "]", "+", "get_ancestor_list", "(", "max_uncle_depth", "+", "1", ")", "raise", "ValueError", ",", "\"invalid ancestor chain\"", "unless", "ancestor_chain", ".", "size", "==", "[", "number", "+", "1", ",", "max_uncle_depth", "+", "2", "]", ".", "min", "# Uncles of this block cannot be direct ancestors and cannot also be", "# uncles included 1-6 blocks ago.", "ineligible", "=", "[", "]", "ancestor_chain", ".", "safe_slice", "(", "1", "..", "-", "1", ")", ".", "each", "{", "|", "a", "|", "ineligible", ".", "concat", "a", ".", "uncles", "}", "ineligible", ".", "concat", "(", "ancestor_chain", ".", "map", "{", "|", "a", "|", "a", ".", "header", "}", ")", "eligible_ancestor_hashes", "=", "ancestor_chain", ".", "safe_slice", "(", "2", "..", "-", "1", ")", ".", "map", "(", ":full_hash", ")", "uncles", ".", "each", "do", "|", "uncle", "|", "parent", "=", "Block", ".", "find", "env", ",", "uncle", ".", "prevhash", "return", "false", "if", "uncle", ".", "difficulty", "!=", "Block", ".", "calc_difficulty", "(", "parent", ",", "uncle", ".", "timestamp", ")", "return", "false", "if", "uncle", ".", "number", "!=", "parent", ".", "number", "+", "1", "return", "false", "if", "uncle", ".", "timestamp", "<", "parent", ".", "timestamp", "return", "false", "unless", "uncle", ".", "check_pow", "unless", "eligible_ancestor_hashes", ".", "include?", "(", "uncle", ".", "prevhash", ")", "eligible", "=", "eligible_ancestor_hashes", ".", "map", "{", "|", "h", "|", "Utils", ".", "encode_hex", "(", "h", ")", "}", "logger", ".", "error", "\"Uncle does not have a valid ancestor\"", ",", "block", ":", "self", ",", "eligible", ":", "eligible", ",", "uncle_prevhash", ":", "Utils", ".", "encode_hex", "(", "uncle", ".", "prevhash", ")", "return", "false", "end", "if", "ineligible", ".", "include?", "(", "uncle", ")", "logger", ".", "error", "\"Duplicate uncle\"", ",", "block", ":", "self", ",", "uncle", ":", "Utils", ".", "encode_hex", "(", "Utils", ".", "keccak256_rlp", "(", "uncle", ")", ")", "return", "false", "end", "# FIXME: what if uncles include previously rewarded uncle?", "ineligible", ".", "push", "uncle", "end", "true", "end" ]
Validate the uncles of this block.
[ "Validate", "the", "uncles", "of", "this", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L351-L398
15,748
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.add_transaction_to_list
def add_transaction_to_list(tx) k = RLP.encode @transaction_count @transactions[k] = RLP.encode(tx) r = mk_transaction_receipt tx @receipts[k] = RLP.encode(r) self.bloom |= r.bloom @transaction_count += 1 end
ruby
def add_transaction_to_list(tx) k = RLP.encode @transaction_count @transactions[k] = RLP.encode(tx) r = mk_transaction_receipt tx @receipts[k] = RLP.encode(r) self.bloom |= r.bloom @transaction_count += 1 end
[ "def", "add_transaction_to_list", "(", "tx", ")", "k", "=", "RLP", ".", "encode", "@transaction_count", "@transactions", "[", "k", "]", "=", "RLP", ".", "encode", "(", "tx", ")", "r", "=", "mk_transaction_receipt", "tx", "@receipts", "[", "k", "]", "=", "RLP", ".", "encode", "(", "r", ")", "self", ".", "bloom", "|=", "r", ".", "bloom", "@transaction_count", "+=", "1", "end" ]
Add a transaction to the transaction trie. Note that this does not execute anything, i.e. the state is not updated.
[ "Add", "a", "transaction", "to", "the", "transaction", "trie", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L418-L427
15,749
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_transaction
def get_transaction(num) index = RLP.encode num tx = @transactions.get index raise IndexError, "Transaction does not exist" if tx == Trie::BLANK_NODE RLP.decode tx, sedes: Transaction end
ruby
def get_transaction(num) index = RLP.encode num tx = @transactions.get index raise IndexError, "Transaction does not exist" if tx == Trie::BLANK_NODE RLP.decode tx, sedes: Transaction end
[ "def", "get_transaction", "(", "num", ")", "index", "=", "RLP", ".", "encode", "num", "tx", "=", "@transactions", ".", "get", "index", "raise", "IndexError", ",", "\"Transaction does not exist\"", "if", "tx", "==", "Trie", "::", "BLANK_NODE", "RLP", ".", "decode", "tx", ",", "sedes", ":", "Transaction", "end" ]
Get the `num`th transaction in this block. @raise [IndexError] if the transaction does not exist
[ "Get", "the", "num", "th", "transaction", "in", "this", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L537-L543
15,750
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.finalize
def finalize delta = @config[:block_reward] + @config[:nephew_reward] * uncles.size delta_balance coinbase, delta self.ether_delta += delta uncles.each do |uncle| r = @config[:block_reward] * (@config[:uncle_depth_penalty_factor] + uncle.number - number) / @config[:uncle_depth_penalty_factor] delta_balance uncle.coinbase, r self.ether_delta += r end commit_state end
ruby
def finalize delta = @config[:block_reward] + @config[:nephew_reward] * uncles.size delta_balance coinbase, delta self.ether_delta += delta uncles.each do |uncle| r = @config[:block_reward] * (@config[:uncle_depth_penalty_factor] + uncle.number - number) / @config[:uncle_depth_penalty_factor] delta_balance uncle.coinbase, r self.ether_delta += r end commit_state end
[ "def", "finalize", "delta", "=", "@config", "[", ":block_reward", "]", "+", "@config", "[", ":nephew_reward", "]", "*", "uncles", ".", "size", "delta_balance", "coinbase", ",", "delta", "self", ".", "ether_delta", "+=", "delta", "uncles", ".", "each", "do", "|", "uncle", "|", "r", "=", "@config", "[", ":block_reward", "]", "*", "(", "@config", "[", ":uncle_depth_penalty_factor", "]", "+", "uncle", ".", "number", "-", "number", ")", "/", "@config", "[", ":uncle_depth_penalty_factor", "]", "delta_balance", "uncle", ".", "coinbase", ",", "r", "self", ".", "ether_delta", "+=", "r", "end", "commit_state", "end" ]
Apply rewards and commit.
[ "Apply", "rewards", "and", "commit", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L579-L593
15,751
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.to_h
def to_h(with_state: false, full_transactions: false, with_storage_roots: false, with_uncles: false) b = { header: header.to_h } txlist = [] get_transactions.each_with_index do |tx, i| receipt_rlp = @receipts[RLP.encode(i)] receipt = RLP.decode receipt_rlp, sedes: Receipt txjson = full_transactions ? tx.to_h : tx.full_hash logs = receipt.logs.map {|l| Log.serialize(l) } txlist.push( tx: txjson, medstate: Utils.encode_hex(receipt.state_root), gas: receipt.gas_used.to_s, logs: logs, bloom: Sedes.int256.serialize(receipt.bloom) ) end b[:transactions] = txlist if with_state state_dump = {} @state.each do |address, v| state_dump[Utils.encode_hex(address)] = account_to_dict(address, with_storage_root: with_storage_roots) end b[:state] = state_dump end if with_uncles b[:uncles] = uncles.map {|u| RLP.decode(u, sedes: BlockHeader) } end b end
ruby
def to_h(with_state: false, full_transactions: false, with_storage_roots: false, with_uncles: false) b = { header: header.to_h } txlist = [] get_transactions.each_with_index do |tx, i| receipt_rlp = @receipts[RLP.encode(i)] receipt = RLP.decode receipt_rlp, sedes: Receipt txjson = full_transactions ? tx.to_h : tx.full_hash logs = receipt.logs.map {|l| Log.serialize(l) } txlist.push( tx: txjson, medstate: Utils.encode_hex(receipt.state_root), gas: receipt.gas_used.to_s, logs: logs, bloom: Sedes.int256.serialize(receipt.bloom) ) end b[:transactions] = txlist if with_state state_dump = {} @state.each do |address, v| state_dump[Utils.encode_hex(address)] = account_to_dict(address, with_storage_root: with_storage_roots) end b[:state] = state_dump end if with_uncles b[:uncles] = uncles.map {|u| RLP.decode(u, sedes: BlockHeader) } end b end
[ "def", "to_h", "(", "with_state", ":", "false", ",", "full_transactions", ":", "false", ",", "with_storage_roots", ":", "false", ",", "with_uncles", ":", "false", ")", "b", "=", "{", "header", ":", "header", ".", "to_h", "}", "txlist", "=", "[", "]", "get_transactions", ".", "each_with_index", "do", "|", "tx", ",", "i", "|", "receipt_rlp", "=", "@receipts", "[", "RLP", ".", "encode", "(", "i", ")", "]", "receipt", "=", "RLP", ".", "decode", "receipt_rlp", ",", "sedes", ":", "Receipt", "txjson", "=", "full_transactions", "?", "tx", ".", "to_h", ":", "tx", ".", "full_hash", "logs", "=", "receipt", ".", "logs", ".", "map", "{", "|", "l", "|", "Log", ".", "serialize", "(", "l", ")", "}", "txlist", ".", "push", "(", "tx", ":", "txjson", ",", "medstate", ":", "Utils", ".", "encode_hex", "(", "receipt", ".", "state_root", ")", ",", "gas", ":", "receipt", ".", "gas_used", ".", "to_s", ",", "logs", ":", "logs", ",", "bloom", ":", "Sedes", ".", "int256", ".", "serialize", "(", "receipt", ".", "bloom", ")", ")", "end", "b", "[", ":transactions", "]", "=", "txlist", "if", "with_state", "state_dump", "=", "{", "}", "@state", ".", "each", "do", "|", "address", ",", "v", "|", "state_dump", "[", "Utils", ".", "encode_hex", "(", "address", ")", "]", "=", "account_to_dict", "(", "address", ",", "with_storage_root", ":", "with_storage_roots", ")", "end", "b", "[", ":state", "]", "=", "state_dump", "end", "if", "with_uncles", "b", "[", ":uncles", "]", "=", "uncles", ".", "map", "{", "|", "u", "|", "RLP", ".", "decode", "(", "u", ",", "sedes", ":", "BlockHeader", ")", "}", "end", "b", "end" ]
Serialize the block to a readable hash. @param with_state [Bool] include state for all accounts @param full_transactions [Bool] include serialized transactions (hashes otherwise) @param with_storage_roots [Bool] if account states are included also include their storage roots @param with_uncles [Bool] include uncle hashes @return [Hash] a hash represents the block
[ "Serialize", "the", "block", "to", "a", "readable", "hash", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L607-L641
15,752
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_parent
def get_parent raise UnknownParentError, "Genesis block has no parent" if number == 0 Block.find env, prevhash rescue KeyError raise UnknownParentError, Utils.encode_hex(prevhash) end
ruby
def get_parent raise UnknownParentError, "Genesis block has no parent" if number == 0 Block.find env, prevhash rescue KeyError raise UnknownParentError, Utils.encode_hex(prevhash) end
[ "def", "get_parent", "raise", "UnknownParentError", ",", "\"Genesis block has no parent\"", "if", "number", "==", "0", "Block", ".", "find", "env", ",", "prevhash", "rescue", "KeyError", "raise", "UnknownParentError", ",", "Utils", ".", "encode_hex", "(", "prevhash", ")", "end" ]
Get the parent of this block.
[ "Get", "the", "parent", "of", "this", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L667-L672
15,753
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.chain_difficulty
def chain_difficulty return difficulty if genesis? k = "difficulty:#{Utils.encode_hex(full_hash)}" return Utils.decode_int(db.get(k)) if db.has_key?(k) o = difficulty + get_parent.chain_difficulty @state.db.put_temporarily k, Utils.encode_int(o) o end
ruby
def chain_difficulty return difficulty if genesis? k = "difficulty:#{Utils.encode_hex(full_hash)}" return Utils.decode_int(db.get(k)) if db.has_key?(k) o = difficulty + get_parent.chain_difficulty @state.db.put_temporarily k, Utils.encode_int(o) o end
[ "def", "chain_difficulty", "return", "difficulty", "if", "genesis?", "k", "=", "\"difficulty:#{Utils.encode_hex(full_hash)}\"", "return", "Utils", ".", "decode_int", "(", "db", ".", "get", "(", "k", ")", ")", "if", "db", ".", "has_key?", "(", "k", ")", "o", "=", "difficulty", "+", "get_parent", ".", "chain_difficulty", "@state", ".", "db", ".", "put_temporarily", "k", ",", "Utils", ".", "encode_int", "(", "o", ")", "o", "end" ]
Get the summarized difficulty. If the summarized difficulty is not stored in the database, it will be calculated recursively and put int the database.
[ "Get", "the", "summarized", "difficulty", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L680-L689
15,754
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.account_is_empty
def account_is_empty(address) get_balance(address) == 0 && get_code(address) == Constant::BYTE_EMPTY && get_nonce(address) == 0 end
ruby
def account_is_empty(address) get_balance(address) == 0 && get_code(address) == Constant::BYTE_EMPTY && get_nonce(address) == 0 end
[ "def", "account_is_empty", "(", "address", ")", "get_balance", "(", "address", ")", "==", "0", "&&", "get_code", "(", "address", ")", "==", "Constant", "::", "BYTE_EMPTY", "&&", "get_nonce", "(", "address", ")", "==", "0", "end" ]
Returns true when the account is either empty or non-exist.
[ "Returns", "true", "when", "the", "account", "is", "either", "empty", "or", "non", "-", "exist", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L741-L743
15,755
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.snapshot
def snapshot { state: @state.root_hash, gas: gas_used, txs: @transactions, txcount: @transaction_count, refunds: refunds, suicides: suicides, suicides_size: suicides.size, logs: logs, logs_size: logs.size, journal: @journal, # pointer to reference, so is not static journal_size: @journal.size, ether_delta: ether_delta } end
ruby
def snapshot { state: @state.root_hash, gas: gas_used, txs: @transactions, txcount: @transaction_count, refunds: refunds, suicides: suicides, suicides_size: suicides.size, logs: logs, logs_size: logs.size, journal: @journal, # pointer to reference, so is not static journal_size: @journal.size, ether_delta: ether_delta } end
[ "def", "snapshot", "{", "state", ":", "@state", ".", "root_hash", ",", "gas", ":", "gas_used", ",", "txs", ":", "@transactions", ",", "txcount", ":", "@transaction_count", ",", "refunds", ":", "refunds", ",", "suicides", ":", "suicides", ",", "suicides_size", ":", "suicides", ".", "size", ",", "logs", ":", "logs", ",", "logs_size", ":", "logs", ".", "size", ",", "journal", ":", "@journal", ",", "# pointer to reference, so is not static", "journal_size", ":", "@journal", ".", "size", ",", "ether_delta", ":", "ether_delta", "}", "end" ]
Make a snapshot of the current state to enable later reverting.
[ "Make", "a", "snapshot", "of", "the", "current", "state", "to", "enable", "later", "reverting", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L779-L793
15,756
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.revert
def revert(mysnapshot) logger.debug "REVERTING" @journal = mysnapshot[:journal] # if @journal changed after snapshot while @journal.size > mysnapshot[:journal_size] cache, index, prev, post = @journal.pop logger.debug "revert journal", cache: cache, index: index, prev: prev, post: post if prev @caches[cache][index] = prev else @caches[cache].delete index end end self.suicides = mysnapshot[:suicides] suicides.pop while suicides.size > mysnapshot[:suicides_size] self.logs = mysnapshot[:logs] logs.pop while logs.size > mysnapshot[:logs_size] self.refunds = mysnapshot[:refunds] self.gas_used = mysnapshot[:gas] self.ether_delta = mysnapshot[:ether_delta] @transactions = mysnapshot[:txs] @transaction_count = mysnapshot[:txcount] @state.set_root_hash mysnapshot[:state] @get_transactions_cache = [] end
ruby
def revert(mysnapshot) logger.debug "REVERTING" @journal = mysnapshot[:journal] # if @journal changed after snapshot while @journal.size > mysnapshot[:journal_size] cache, index, prev, post = @journal.pop logger.debug "revert journal", cache: cache, index: index, prev: prev, post: post if prev @caches[cache][index] = prev else @caches[cache].delete index end end self.suicides = mysnapshot[:suicides] suicides.pop while suicides.size > mysnapshot[:suicides_size] self.logs = mysnapshot[:logs] logs.pop while logs.size > mysnapshot[:logs_size] self.refunds = mysnapshot[:refunds] self.gas_used = mysnapshot[:gas] self.ether_delta = mysnapshot[:ether_delta] @transactions = mysnapshot[:txs] @transaction_count = mysnapshot[:txcount] @state.set_root_hash mysnapshot[:state] @get_transactions_cache = [] end
[ "def", "revert", "(", "mysnapshot", ")", "logger", ".", "debug", "\"REVERTING\"", "@journal", "=", "mysnapshot", "[", ":journal", "]", "# if @journal changed after snapshot", "while", "@journal", ".", "size", ">", "mysnapshot", "[", ":journal_size", "]", "cache", ",", "index", ",", "prev", ",", "post", "=", "@journal", ".", "pop", "logger", ".", "debug", "\"revert journal\"", ",", "cache", ":", "cache", ",", "index", ":", "index", ",", "prev", ":", "prev", ",", "post", ":", "post", "if", "prev", "@caches", "[", "cache", "]", "[", "index", "]", "=", "prev", "else", "@caches", "[", "cache", "]", ".", "delete", "index", "end", "end", "self", ".", "suicides", "=", "mysnapshot", "[", ":suicides", "]", "suicides", ".", "pop", "while", "suicides", ".", "size", ">", "mysnapshot", "[", ":suicides_size", "]", "self", ".", "logs", "=", "mysnapshot", "[", ":logs", "]", "logs", ".", "pop", "while", "logs", ".", "size", ">", "mysnapshot", "[", ":logs_size", "]", "self", ".", "refunds", "=", "mysnapshot", "[", ":refunds", "]", "self", ".", "gas_used", "=", "mysnapshot", "[", ":gas", "]", "self", ".", "ether_delta", "=", "mysnapshot", "[", ":ether_delta", "]", "@transactions", "=", "mysnapshot", "[", ":txs", "]", "@transaction_count", "=", "mysnapshot", "[", ":txcount", "]", "@state", ".", "set_root_hash", "mysnapshot", "[", ":state", "]", "@get_transactions_cache", "=", "[", "]", "end" ]
Revert to a previously made snapshot. Reverting is for example neccessary when a contract runs out of gas during execution.
[ "Revert", "to", "a", "previously", "made", "snapshot", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L801-L832
15,757
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_receipt
def get_receipt(num) index = RLP.encode num receipt = @receipts[index] if receipt == Trie::BLANK_NODE raise IndexError, "Receipt does not exist" else RLP.decode receipt, sedes: Receipt end end
ruby
def get_receipt(num) index = RLP.encode num receipt = @receipts[index] if receipt == Trie::BLANK_NODE raise IndexError, "Receipt does not exist" else RLP.decode receipt, sedes: Receipt end end
[ "def", "get_receipt", "(", "num", ")", "index", "=", "RLP", ".", "encode", "num", "receipt", "=", "@receipts", "[", "index", "]", "if", "receipt", "==", "Trie", "::", "BLANK_NODE", "raise", "IndexError", ",", "\"Receipt does not exist\"", "else", "RLP", ".", "decode", "receipt", ",", "sedes", ":", "Receipt", "end", "end" ]
Get the receipt of the `num`th transaction. @raise [IndexError] if receipt at index is not found @return [Receipt]
[ "Get", "the", "receipt", "of", "the", "num", "th", "transaction", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L841-L850
15,758
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_receipts
def get_receipts receipts = [] i = 0 loop do begin receipts.push get_receipt(i) i += 1 rescue IndexError return receipts end end end
ruby
def get_receipts receipts = [] i = 0 loop do begin receipts.push get_receipt(i) i += 1 rescue IndexError return receipts end end end
[ "def", "get_receipts", "receipts", "=", "[", "]", "i", "=", "0", "loop", "do", "begin", "receipts", ".", "push", "get_receipt", "(", "i", ")", "i", "+=", "1", "rescue", "IndexError", "return", "receipts", "end", "end", "end" ]
Build a list of all receipts in this block.
[ "Build", "a", "list", "of", "all", "receipts", "in", "this", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L855-L866
15,759
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.transfer_value
def transfer_value(from, to, value) raise ArgumentError, "value must be greater or equal than zero" unless value >= 0 delta_balance(from, -value) && delta_balance(to, value) end
ruby
def transfer_value(from, to, value) raise ArgumentError, "value must be greater or equal than zero" unless value >= 0 delta_balance(from, -value) && delta_balance(to, value) end
[ "def", "transfer_value", "(", "from", ",", "to", ",", "value", ")", "raise", "ArgumentError", ",", "\"value must be greater or equal than zero\"", "unless", "value", ">=", "0", "delta_balance", "(", "from", ",", "-", "value", ")", "&&", "delta_balance", "(", "to", ",", "value", ")", "end" ]
Transfer a value between two account balance. @param from [String] the address of the sending account (binary or hex string) @param to [String] the address of the receiving account (binary or hex string) @param value [Integer] the (positive) value to send @return [Bool] `true` if successful, otherwise `false`
[ "Transfer", "a", "value", "between", "two", "account", "balance", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L952-L955
15,760
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_storage
def get_storage(address) storage_root = get_account_item address, :storage SecureTrie.new PruningTrie.new(db, storage_root) end
ruby
def get_storage(address) storage_root = get_account_item address, :storage SecureTrie.new PruningTrie.new(db, storage_root) end
[ "def", "get_storage", "(", "address", ")", "storage_root", "=", "get_account_item", "address", ",", ":storage", "SecureTrie", ".", "new", "PruningTrie", ".", "new", "(", "db", ",", "storage_root", ")", "end" ]
Get the trie holding an account's storage. @param address [String] the address of the account (binary or hex string) @return [Trie] the storage trie of account
[ "Get", "the", "trie", "holding", "an", "account", "s", "storage", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L987-L990
15,761
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_storage_data
def get_storage_data(address, index) address = Utils.normalize_address address cache = @caches["storage:#{address}"] return cache[index] if cache && cache.has_key?(index) key = Utils.zpad Utils.coerce_to_bytes(index), 32 value = get_storage(address)[key] value.true? ? RLP.decode(value, sedes: Sedes.big_endian_int) : 0 end
ruby
def get_storage_data(address, index) address = Utils.normalize_address address cache = @caches["storage:#{address}"] return cache[index] if cache && cache.has_key?(index) key = Utils.zpad Utils.coerce_to_bytes(index), 32 value = get_storage(address)[key] value.true? ? RLP.decode(value, sedes: Sedes.big_endian_int) : 0 end
[ "def", "get_storage_data", "(", "address", ",", "index", ")", "address", "=", "Utils", ".", "normalize_address", "address", "cache", "=", "@caches", "[", "\"storage:#{address}\"", "]", "return", "cache", "[", "index", "]", "if", "cache", "&&", "cache", ".", "has_key?", "(", "index", ")", "key", "=", "Utils", ".", "zpad", "Utils", ".", "coerce_to_bytes", "(", "index", ")", ",", "32", "value", "=", "get_storage", "(", "address", ")", "[", "key", "]", "value", ".", "true?", "?", "RLP", ".", "decode", "(", "value", ",", "sedes", ":", "Sedes", ".", "big_endian_int", ")", ":", "0", "end" ]
Get a specific item in the storage of an account. @param address [String] the address of the account (binary or hex string) @param index [Integer] the index of the requested item in the storage @return [Integer] the value at storage index
[ "Get", "a", "specific", "item", "in", "the", "storage", "of", "an", "account", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1009-L1019
15,762
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.set_storage_data
def set_storage_data(address, index, value) address = Utils.normalize_address address cache_key = "storage:#{address}" unless @caches.has_key?(cache_key) @caches[cache_key] = {} set_and_journal :all, address, true end set_and_journal cache_key, index, value end
ruby
def set_storage_data(address, index, value) address = Utils.normalize_address address cache_key = "storage:#{address}" unless @caches.has_key?(cache_key) @caches[cache_key] = {} set_and_journal :all, address, true end set_and_journal cache_key, index, value end
[ "def", "set_storage_data", "(", "address", ",", "index", ",", "value", ")", "address", "=", "Utils", ".", "normalize_address", "address", "cache_key", "=", "\"storage:#{address}\"", "unless", "@caches", ".", "has_key?", "(", "cache_key", ")", "@caches", "[", "cache_key", "]", "=", "{", "}", "set_and_journal", ":all", ",", "address", ",", "true", "end", "set_and_journal", "cache_key", ",", "index", ",", "value", "end" ]
Set a specific item in the storage of an account. @param address [String] the address of the account (binary or hex string) @param index [Integer] the index of the requested item in the storage @param value [Integer] the new value of the item
[ "Set", "a", "specific", "item", "in", "the", "storage", "of", "an", "account", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1028-L1038
15,763
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.account_to_dict
def account_to_dict(address, with_storage_root: false, with_storage: true) address = Utils.normalize_address address # if there are uncommited account changes the current storage root is # meaningless raise ArgumentError, "cannot include storage root with uncommited account changes" if with_storage_root && !@journal.empty? h = {} account = get_account address h[:nonce] = (@caches[:nonce][address] || account.nonce).to_s h[:balance] = (@caches[:balance][address] || account.balance).to_s code = @caches[:code][address] || account.code h[:code] = "0x#{Utils.encode_hex code}" storage_trie = SecureTrie.new PruningTrie.new(db, account.storage) h[:storage_root] = Utils.encode_hex storage_trie.root_hash if with_storage_root if with_storage h[:storage] = {} sh = storage_trie.to_h cache = @caches["storage:#{address}"] || {} keys = cache.keys.map {|k| Utils.zpad Utils.coerce_to_bytes(k), 32 } (sh.keys + keys).each do |k| hexkey = "0x#{Utils.encode_hex Utils.zunpad(k)}" v = cache[Utils.big_endian_to_int(k)] if v.true? h[:storage][hexkey] = "0x#{Utils.encode_hex Utils.int_to_big_endian(v)}" else v = sh[k] h[:storage][hexkey] = "0x#{Utils.encode_hex RLP.decode(v)}" if v end end end h end
ruby
def account_to_dict(address, with_storage_root: false, with_storage: true) address = Utils.normalize_address address # if there are uncommited account changes the current storage root is # meaningless raise ArgumentError, "cannot include storage root with uncommited account changes" if with_storage_root && !@journal.empty? h = {} account = get_account address h[:nonce] = (@caches[:nonce][address] || account.nonce).to_s h[:balance] = (@caches[:balance][address] || account.balance).to_s code = @caches[:code][address] || account.code h[:code] = "0x#{Utils.encode_hex code}" storage_trie = SecureTrie.new PruningTrie.new(db, account.storage) h[:storage_root] = Utils.encode_hex storage_trie.root_hash if with_storage_root if with_storage h[:storage] = {} sh = storage_trie.to_h cache = @caches["storage:#{address}"] || {} keys = cache.keys.map {|k| Utils.zpad Utils.coerce_to_bytes(k), 32 } (sh.keys + keys).each do |k| hexkey = "0x#{Utils.encode_hex Utils.zunpad(k)}" v = cache[Utils.big_endian_to_int(k)] if v.true? h[:storage][hexkey] = "0x#{Utils.encode_hex Utils.int_to_big_endian(v)}" else v = sh[k] h[:storage][hexkey] = "0x#{Utils.encode_hex RLP.decode(v)}" if v end end end h end
[ "def", "account_to_dict", "(", "address", ",", "with_storage_root", ":", "false", ",", "with_storage", ":", "true", ")", "address", "=", "Utils", ".", "normalize_address", "address", "# if there are uncommited account changes the current storage root is", "# meaningless", "raise", "ArgumentError", ",", "\"cannot include storage root with uncommited account changes\"", "if", "with_storage_root", "&&", "!", "@journal", ".", "empty?", "h", "=", "{", "}", "account", "=", "get_account", "address", "h", "[", ":nonce", "]", "=", "(", "@caches", "[", ":nonce", "]", "[", "address", "]", "||", "account", ".", "nonce", ")", ".", "to_s", "h", "[", ":balance", "]", "=", "(", "@caches", "[", ":balance", "]", "[", "address", "]", "||", "account", ".", "balance", ")", ".", "to_s", "code", "=", "@caches", "[", ":code", "]", "[", "address", "]", "||", "account", ".", "code", "h", "[", ":code", "]", "=", "\"0x#{Utils.encode_hex code}\"", "storage_trie", "=", "SecureTrie", ".", "new", "PruningTrie", ".", "new", "(", "db", ",", "account", ".", "storage", ")", "h", "[", ":storage_root", "]", "=", "Utils", ".", "encode_hex", "storage_trie", ".", "root_hash", "if", "with_storage_root", "if", "with_storage", "h", "[", ":storage", "]", "=", "{", "}", "sh", "=", "storage_trie", ".", "to_h", "cache", "=", "@caches", "[", "\"storage:#{address}\"", "]", "||", "{", "}", "keys", "=", "cache", ".", "keys", ".", "map", "{", "|", "k", "|", "Utils", ".", "zpad", "Utils", ".", "coerce_to_bytes", "(", "k", ")", ",", "32", "}", "(", "sh", ".", "keys", "+", "keys", ")", ".", "each", "do", "|", "k", "|", "hexkey", "=", "\"0x#{Utils.encode_hex Utils.zunpad(k)}\"", "v", "=", "cache", "[", "Utils", ".", "big_endian_to_int", "(", "k", ")", "]", "if", "v", ".", "true?", "h", "[", ":storage", "]", "[", "hexkey", "]", "=", "\"0x#{Utils.encode_hex Utils.int_to_big_endian(v)}\"", "else", "v", "=", "sh", "[", "k", "]", "h", "[", ":storage", "]", "[", "hexkey", "]", "=", "\"0x#{Utils.encode_hex RLP.decode(v)}\"", "if", "v", "end", "end", "end", "h", "end" ]
Serialize an account to a hash with human readable entries. @param address [String] the account address @param with_storage_root [Bool] include the account's storage root @param with_storage [Bool] include the whole account's storage @return [Hash] hash represent the account
[ "Serialize", "an", "account", "to", "a", "hash", "with", "human", "readable", "entries", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1060-L1099
15,764
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_ancestor_list
def get_ancestor_list(n) raise ArgumentError, "n must be greater or equal than zero" unless n >= 0 return [] if n == 0 || number == 0 parent = get_parent [parent] + parent.get_ancestor_list(n-1) end
ruby
def get_ancestor_list(n) raise ArgumentError, "n must be greater or equal than zero" unless n >= 0 return [] if n == 0 || number == 0 parent = get_parent [parent] + parent.get_ancestor_list(n-1) end
[ "def", "get_ancestor_list", "(", "n", ")", "raise", "ArgumentError", ",", "\"n must be greater or equal than zero\"", "unless", "n", ">=", "0", "return", "[", "]", "if", "n", "==", "0", "||", "number", "==", "0", "parent", "=", "get_parent", "[", "parent", "]", "+", "parent", ".", "get_ancestor_list", "(", "n", "-", "1", ")", "end" ]
Return `n` ancestors of this block. @return [Array] array of ancestors in format of `[parent, parent.parent, ...]
[ "Return", "n", "ancestors", "of", "this", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1106-L1112
15,765
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.validate_fields
def validate_fields l = Block.serialize self RLP.decode(RLP.encode(l)) == l end
ruby
def validate_fields l = Block.serialize self RLP.decode(RLP.encode(l)) == l end
[ "def", "validate_fields", "l", "=", "Block", ".", "serialize", "self", "RLP", ".", "decode", "(", "RLP", ".", "encode", "(", "l", ")", ")", "==", "l", "end" ]
Check that the values of all fields are well formed. Serialize and deserialize and check that the values didn't change.
[ "Check", "that", "the", "values", "of", "all", "fields", "are", "well", "formed", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1289-L1292
15,766
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.delta_account_item
def delta_account_item(address, param, value) new_value = get_account_item(address, param) + value return false if new_value < 0 set_account_item(address, param, new_value % 2**256) true end
ruby
def delta_account_item(address, param, value) new_value = get_account_item(address, param) + value return false if new_value < 0 set_account_item(address, param, new_value % 2**256) true end
[ "def", "delta_account_item", "(", "address", ",", "param", ",", "value", ")", "new_value", "=", "get_account_item", "(", "address", ",", "param", ")", "+", "value", "return", "false", "if", "new_value", "<", "0", "set_account_item", "(", "address", ",", "param", ",", "new_value", "%", "2", "**", "256", ")", "true", "end" ]
Add a value to an account item. If the resulting value would be negative, it is left unchanged and `false` is returned. @param address [String] the address of the account (binary or hex string) @param param [Symbol] the parameter to increase or decrease (`:nonce`, `:balance`, `:storage`, or `:code`) @param value [Integer] can be positive or negative @return [Bool] `true` if the operation was successful, `false` if not
[ "Add", "a", "value", "to", "an", "account", "item", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1307-L1313
15,767
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_account_item
def get_account_item(address, param) address = Utils.normalize_address address, allow_blank: true return @caches[param][address] if @caches[param].has_key?(address) account = get_account address v = account.send param @caches[param][address] = v v end
ruby
def get_account_item(address, param) address = Utils.normalize_address address, allow_blank: true return @caches[param][address] if @caches[param].has_key?(address) account = get_account address v = account.send param @caches[param][address] = v v end
[ "def", "get_account_item", "(", "address", ",", "param", ")", "address", "=", "Utils", ".", "normalize_address", "address", ",", "allow_blank", ":", "true", "return", "@caches", "[", "param", "]", "[", "address", "]", "if", "@caches", "[", "param", "]", ".", "has_key?", "(", "address", ")", "account", "=", "get_account", "address", "v", "=", "account", ".", "send", "param", "@caches", "[", "param", "]", "[", "address", "]", "=", "v", "v", "end" ]
Get a specific parameter of a specific account. @param address [String] the address of the account (binary or hex string) @param param [Symbol] the requested parameter (`:nonce`, `:balance`, `:storage` or `:code`) @return [Object] the value
[ "Get", "a", "specific", "parameter", "of", "a", "specific", "account", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1324-L1332
15,768
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.set_account_item
def set_account_item(address, param, value) raise ArgumentError, "invalid address: #{address}" unless address.size == 20 || address.size == 40 address = Utils.decode_hex(address) if address.size == 40 set_and_journal(param, address, value) set_and_journal(:all, address, true) end
ruby
def set_account_item(address, param, value) raise ArgumentError, "invalid address: #{address}" unless address.size == 20 || address.size == 40 address = Utils.decode_hex(address) if address.size == 40 set_and_journal(param, address, value) set_and_journal(:all, address, true) end
[ "def", "set_account_item", "(", "address", ",", "param", ",", "value", ")", "raise", "ArgumentError", ",", "\"invalid address: #{address}\"", "unless", "address", ".", "size", "==", "20", "||", "address", ".", "size", "==", "40", "address", "=", "Utils", ".", "decode_hex", "(", "address", ")", "if", "address", ".", "size", "==", "40", "set_and_journal", "(", "param", ",", "address", ",", "value", ")", "set_and_journal", "(", ":all", ",", "address", ",", "true", ")", "end" ]
Set a specific parameter of a specific account. @param address [String] the address of the account (binary or hex string) @param param [Symbol] the requested parameter (`:nonce`, `:balance`, `:storage` or `:code`) @param value [Object] the new value
[ "Set", "a", "specific", "parameter", "of", "a", "specific", "account", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1342-L1348
15,769
cryptape/ruby-ethereum
lib/ethereum/block.rb
Ethereum.Block.get_account
def get_account(address) address = Utils.normalize_address address, allow_blank: true rlpdata = @state[address] if rlpdata == Trie::BLANK_NODE Account.build_blank db, config[:account_initial_nonce] else RLP.decode(rlpdata, sedes: Account, db: db).tap do |acct| acct.make_mutable! acct._cached_rlp = nil end end end
ruby
def get_account(address) address = Utils.normalize_address address, allow_blank: true rlpdata = @state[address] if rlpdata == Trie::BLANK_NODE Account.build_blank db, config[:account_initial_nonce] else RLP.decode(rlpdata, sedes: Account, db: db).tap do |acct| acct.make_mutable! acct._cached_rlp = nil end end end
[ "def", "get_account", "(", "address", ")", "address", "=", "Utils", ".", "normalize_address", "address", ",", "allow_blank", ":", "true", "rlpdata", "=", "@state", "[", "address", "]", "if", "rlpdata", "==", "Trie", "::", "BLANK_NODE", "Account", ".", "build_blank", "db", ",", "config", "[", ":account_initial_nonce", "]", "else", "RLP", ".", "decode", "(", "rlpdata", ",", "sedes", ":", "Account", ",", "db", ":", "db", ")", ".", "tap", "do", "|", "acct", "|", "acct", ".", "make_mutable!", "acct", ".", "_cached_rlp", "=", "nil", "end", "end", "end" ]
Get the account with the given address. Note that this method ignores cached account items.
[ "Get", "the", "account", "with", "the", "given", "address", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block.rb#L1355-L1367
15,770
cryptape/ruby-ethereum
lib/ethereum/transaction.rb
Ethereum.Transaction.sign
def sign(key) raise InvalidTransaction, "Zero privkey cannot sign" if [0, '', Constant::PRIVKEY_ZERO, Constant::PRIVKEY_ZERO_HEX].include?(key) rawhash = Utils.keccak256 signing_data(:sign) key = PrivateKey.new(key).encode(:bin) vrs = Secp256k1.recoverable_sign rawhash, key self.v = encode_v(vrs[0]) self.r = vrs[1] self.s = vrs[2] self.sender = PrivateKey.new(key).to_address self end
ruby
def sign(key) raise InvalidTransaction, "Zero privkey cannot sign" if [0, '', Constant::PRIVKEY_ZERO, Constant::PRIVKEY_ZERO_HEX].include?(key) rawhash = Utils.keccak256 signing_data(:sign) key = PrivateKey.new(key).encode(:bin) vrs = Secp256k1.recoverable_sign rawhash, key self.v = encode_v(vrs[0]) self.r = vrs[1] self.s = vrs[2] self.sender = PrivateKey.new(key).to_address self end
[ "def", "sign", "(", "key", ")", "raise", "InvalidTransaction", ",", "\"Zero privkey cannot sign\"", "if", "[", "0", ",", "''", ",", "Constant", "::", "PRIVKEY_ZERO", ",", "Constant", "::", "PRIVKEY_ZERO_HEX", "]", ".", "include?", "(", "key", ")", "rawhash", "=", "Utils", ".", "keccak256", "signing_data", "(", ":sign", ")", "key", "=", "PrivateKey", ".", "new", "(", "key", ")", ".", "encode", "(", ":bin", ")", "vrs", "=", "Secp256k1", ".", "recoverable_sign", "rawhash", ",", "key", "self", ".", "v", "=", "encode_v", "(", "vrs", "[", "0", "]", ")", "self", ".", "r", "=", "vrs", "[", "1", "]", "self", ".", "s", "=", "vrs", "[", "2", "]", "self", ".", "sender", "=", "PrivateKey", ".", "new", "(", "key", ")", ".", "to_address", "self", "end" ]
Sign this transaction with a private key. A potentially already existing signature would be override.
[ "Sign", "this", "transaction", "with", "a", "private", "key", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/transaction.rb#L105-L119
15,771
cryptape/ruby-ethereum
lib/ethereum/transaction.rb
Ethereum.Transaction.creates
def creates Utils.mk_contract_address(sender, nonce) if [Address::BLANK, Address::ZERO].include?(to) end
ruby
def creates Utils.mk_contract_address(sender, nonce) if [Address::BLANK, Address::ZERO].include?(to) end
[ "def", "creates", "Utils", ".", "mk_contract_address", "(", "sender", ",", "nonce", ")", "if", "[", "Address", "::", "BLANK", ",", "Address", "::", "ZERO", "]", ".", "include?", "(", "to", ")", "end" ]
returns the address of a contract created by this tx
[ "returns", "the", "address", "of", "a", "contract", "created", "by", "this", "tx" ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/transaction.rb#L174-L176
15,772
cryptape/ruby-ethereum
lib/ethereum/miner.rb
Ethereum.Miner.mine
def mine(rounds=1000, start_nonce=0) blk = @block bin_nonce, mixhash = _mine(blk.number, blk.difficulty, blk.mining_hash, start_nonce, rounds) if bin_nonce.true? blk.mixhash = mixhash blk.nonce = bin_nonce return blk end end
ruby
def mine(rounds=1000, start_nonce=0) blk = @block bin_nonce, mixhash = _mine(blk.number, blk.difficulty, blk.mining_hash, start_nonce, rounds) if bin_nonce.true? blk.mixhash = mixhash blk.nonce = bin_nonce return blk end end
[ "def", "mine", "(", "rounds", "=", "1000", ",", "start_nonce", "=", "0", ")", "blk", "=", "@block", "bin_nonce", ",", "mixhash", "=", "_mine", "(", "blk", ".", "number", ",", "blk", ".", "difficulty", ",", "blk", ".", "mining_hash", ",", "start_nonce", ",", "rounds", ")", "if", "bin_nonce", ".", "true?", "blk", ".", "mixhash", "=", "mixhash", "blk", ".", "nonce", "=", "bin_nonce", "return", "blk", "end", "end" ]
Mines on the current head. Stores received transactions. The process of finalising a block involves four stages: 1. validate (or, if mining, determine) uncles; 2. validate (or, if mining, determine) transactions; 3. apply rewards; 4. verify (or, if mining, compute a valid) state and nonce.
[ "Mines", "on", "the", "current", "head", ".", "Stores", "received", "transactions", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/miner.rb#L43-L52
15,773
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.root_hash
def root_hash # TODO: can I memoize computation below? return BLANK_ROOT if @root_node == BLANK_NODE raise InvalidNode, "invalid root node" unless @root_node.instance_of?(Array) val = FastRLP.encode @root_node key = Utils.keccak256 val @db.put key, val SPV.grabbing @root_node key end
ruby
def root_hash # TODO: can I memoize computation below? return BLANK_ROOT if @root_node == BLANK_NODE raise InvalidNode, "invalid root node" unless @root_node.instance_of?(Array) val = FastRLP.encode @root_node key = Utils.keccak256 val @db.put key, val SPV.grabbing @root_node key end
[ "def", "root_hash", "# TODO: can I memoize computation below?", "return", "BLANK_ROOT", "if", "@root_node", "==", "BLANK_NODE", "raise", "InvalidNode", ",", "\"invalid root node\"", "unless", "@root_node", ".", "instance_of?", "(", "Array", ")", "val", "=", "FastRLP", ".", "encode", "@root_node", "key", "=", "Utils", ".", "keccak256", "val", "@db", ".", "put", "key", ",", "val", "SPV", ".", "grabbing", "@root_node", "key", "end" ]
It presents a hash like interface. @param db [Object] key value database @param root_hash [String] blank or trie node in form of [key, value] or [v0, v1, .. v15, v] @return empty or 32 bytes string
[ "It", "presents", "a", "hash", "like", "interface", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L45-L58
15,774
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.[]=
def []=(key, value) raise ArgumentError, "key must be string" unless key.instance_of?(String) raise ArgumentError, "value must be string" unless value.instance_of?(String) @root_node = update_and_delete_storage( @root_node, NibbleKey.from_string(key), value ) update_root_hash end
ruby
def []=(key, value) raise ArgumentError, "key must be string" unless key.instance_of?(String) raise ArgumentError, "value must be string" unless value.instance_of?(String) @root_node = update_and_delete_storage( @root_node, NibbleKey.from_string(key), value ) update_root_hash end
[ "def", "[]=", "(", "key", ",", "value", ")", "raise", "ArgumentError", ",", "\"key must be string\"", "unless", "key", ".", "instance_of?", "(", "String", ")", "raise", "ArgumentError", ",", "\"value must be string\"", "unless", "value", ".", "instance_of?", "(", "String", ")", "@root_node", "=", "update_and_delete_storage", "(", "@root_node", ",", "NibbleKey", ".", "from_string", "(", "key", ")", ",", "value", ")", "update_root_hash", "end" ]
Set value of key. @param key [String] @param value [String]
[ "Set", "value", "of", "key", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L96-L107
15,775
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.delete
def delete(key) raise ArgumentError, "key must be string" unless key.instance_of?(String) raise ArgumentError, "max key size is 32" if key.size > 32 @root_node = delete_and_delete_storage( @root_node, NibbleKey.from_string(key) ) update_root_hash end
ruby
def delete(key) raise ArgumentError, "key must be string" unless key.instance_of?(String) raise ArgumentError, "max key size is 32" if key.size > 32 @root_node = delete_and_delete_storage( @root_node, NibbleKey.from_string(key) ) update_root_hash end
[ "def", "delete", "(", "key", ")", "raise", "ArgumentError", ",", "\"key must be string\"", "unless", "key", ".", "instance_of?", "(", "String", ")", "raise", "ArgumentError", ",", "\"max key size is 32\"", "if", "key", ".", "size", ">", "32", "@root_node", "=", "delete_and_delete_storage", "(", "@root_node", ",", "NibbleKey", ".", "from_string", "(", "key", ")", ")", "update_root_hash", "end" ]
Delete value at key. @param key [String] a string with length of [0,32]
[ "Delete", "value", "at", "key", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L115-L125
15,776
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.to_h
def to_h h = {} to_hash(@root_node).each do |k, v| key = k.terminate(false).to_string h[key] = v end h end
ruby
def to_h h = {} to_hash(@root_node).each do |k, v| key = k.terminate(false).to_string h[key] = v end h end
[ "def", "to_h", "h", "=", "{", "}", "to_hash", "(", "@root_node", ")", ".", "each", "do", "|", "k", ",", "v", "|", "key", "=", "k", ".", "terminate", "(", "false", ")", ".", "to_string", "h", "[", "key", "]", "=", "v", "end", "h", "end" ]
Convert to hash.
[ "Convert", "to", "hash", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L130-L137
15,777
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.find
def find(node, nbk) node_type = get_node_type node case node_type when :blank BLANK_NODE when :branch return node.last if nbk.empty? sub_node = decode_to_node node[nbk[0]] find sub_node, nbk[1..-1] when :leaf node_key = NibbleKey.decode(node[0]).terminate(false) nbk == node_key ? node[1] : BLANK_NODE when :extension node_key = NibbleKey.decode(node[0]).terminate(false) if node_key.prefix?(nbk) sub_node = decode_to_node node[1] find sub_node, nbk[node_key.size..-1] else BLANK_NODE end else raise InvalidNodeType, "node type must be in #{NODE_TYPES}, given: #{node_type}" end end
ruby
def find(node, nbk) node_type = get_node_type node case node_type when :blank BLANK_NODE when :branch return node.last if nbk.empty? sub_node = decode_to_node node[nbk[0]] find sub_node, nbk[1..-1] when :leaf node_key = NibbleKey.decode(node[0]).terminate(false) nbk == node_key ? node[1] : BLANK_NODE when :extension node_key = NibbleKey.decode(node[0]).terminate(false) if node_key.prefix?(nbk) sub_node = decode_to_node node[1] find sub_node, nbk[node_key.size..-1] else BLANK_NODE end else raise InvalidNodeType, "node type must be in #{NODE_TYPES}, given: #{node_type}" end end
[ "def", "find", "(", "node", ",", "nbk", ")", "node_type", "=", "get_node_type", "node", "case", "node_type", "when", ":blank", "BLANK_NODE", "when", ":branch", "return", "node", ".", "last", "if", "nbk", ".", "empty?", "sub_node", "=", "decode_to_node", "node", "[", "nbk", "[", "0", "]", "]", "find", "sub_node", ",", "nbk", "[", "1", "..", "-", "1", "]", "when", ":leaf", "node_key", "=", "NibbleKey", ".", "decode", "(", "node", "[", "0", "]", ")", ".", "terminate", "(", "false", ")", "nbk", "==", "node_key", "?", "node", "[", "1", "]", ":", "BLANK_NODE", "when", ":extension", "node_key", "=", "NibbleKey", ".", "decode", "(", "node", "[", "0", "]", ")", ".", "terminate", "(", "false", ")", "if", "node_key", ".", "prefix?", "(", "nbk", ")", "sub_node", "=", "decode_to_node", "node", "[", "1", "]", "find", "sub_node", ",", "nbk", "[", "node_key", ".", "size", "..", "-", "1", "]", "else", "BLANK_NODE", "end", "else", "raise", "InvalidNodeType", ",", "\"node type must be in #{NODE_TYPES}, given: #{node_type}\"", "end", "end" ]
Get value inside a node. @param node [Array, BLANK_NODE] node in form of array, or BLANK_NODE @param nbk [Array] nibble array without terminator @return [String] BLANK_NODE if does not exist, otherwise node value
[ "Get", "value", "inside", "a", "node", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L172-L197
15,778
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.update_node
def update_node(node, key, value) node_type = get_node_type node case node_type when :blank [key.terminate(true).encode, value] when :branch if key.empty? node.last = value else new_node = update_and_delete_storage( decode_to_node(node[key[0]]), key[1..-1], value ) node[key[0]] = encode_node new_node end node when :leaf update_leaf_node(node, key, value) else update_extension_node(node, key, value) end end
ruby
def update_node(node, key, value) node_type = get_node_type node case node_type when :blank [key.terminate(true).encode, value] when :branch if key.empty? node.last = value else new_node = update_and_delete_storage( decode_to_node(node[key[0]]), key[1..-1], value ) node[key[0]] = encode_node new_node end node when :leaf update_leaf_node(node, key, value) else update_extension_node(node, key, value) end end
[ "def", "update_node", "(", "node", ",", "key", ",", "value", ")", "node_type", "=", "get_node_type", "node", "case", "node_type", "when", ":blank", "[", "key", ".", "terminate", "(", "true", ")", ".", "encode", ",", "value", "]", "when", ":branch", "if", "key", ".", "empty?", "node", ".", "last", "=", "value", "else", "new_node", "=", "update_and_delete_storage", "(", "decode_to_node", "(", "node", "[", "key", "[", "0", "]", "]", ")", ",", "key", "[", "1", "..", "-", "1", "]", ",", "value", ")", "node", "[", "key", "[", "0", "]", "]", "=", "encode_node", "new_node", "end", "node", "when", ":leaf", "update_leaf_node", "(", "node", ",", "key", ",", "value", ")", "else", "update_extension_node", "(", "node", ",", "key", ",", "value", ")", "end", "end" ]
Update item inside a node. If this node is changed to a new node, it's parent will take the responsibility to **store** the new node storage, and delete the old node storage. @param node [Array, BLANK_NODE] node in form of array, or BLANK_NODE @param key [Array] nibble key without terminator @param value [String] value string @return [Array, BLANK_NODE] new node
[ "Update", "item", "inside", "a", "node", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L275-L299
15,779
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.delete_node
def delete_node(node, key) case get_node_type(node) when :blank BLANK_NODE when :branch delete_branch_node(node, key) else # kv type delete_kv_node(node, key) end end
ruby
def delete_node(node, key) case get_node_type(node) when :blank BLANK_NODE when :branch delete_branch_node(node, key) else # kv type delete_kv_node(node, key) end end
[ "def", "delete_node", "(", "node", ",", "key", ")", "case", "get_node_type", "(", "node", ")", "when", ":blank", "BLANK_NODE", "when", ":branch", "delete_branch_node", "(", "node", ",", "key", ")", "else", "# kv type", "delete_kv_node", "(", "node", ",", "key", ")", "end", "end" ]
Delete item inside node. If this node is changed to a new node, it's parent will take the responsibility to **store** the new node storage, and delete the old node storage. @param node [Array, BLANK_NODE] node in form of array, or BLANK_NODE @param key [Array] nibble key without terminator. key maybe empty @return new node
[ "Delete", "item", "inside", "node", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L403-L412
15,780
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.delete_node_storage
def delete_node_storage(node) return if node == BLANK_NODE raise ArgumentError, "node must be Array or BLANK_NODE" unless node.instance_of?(Array) encoded = encode_node node return if encoded.size < 32 # FIXME: in current trie implementation two nodes can share identical # subtree thus we can not safely delete nodes for now # # \@db.delete encoded end
ruby
def delete_node_storage(node) return if node == BLANK_NODE raise ArgumentError, "node must be Array or BLANK_NODE" unless node.instance_of?(Array) encoded = encode_node node return if encoded.size < 32 # FIXME: in current trie implementation two nodes can share identical # subtree thus we can not safely delete nodes for now # # \@db.delete encoded end
[ "def", "delete_node_storage", "(", "node", ")", "return", "if", "node", "==", "BLANK_NODE", "raise", "ArgumentError", ",", "\"node must be Array or BLANK_NODE\"", "unless", "node", ".", "instance_of?", "(", "Array", ")", "encoded", "=", "encode_node", "node", "return", "if", "encoded", ".", "size", "<", "32", "# FIXME: in current trie implementation two nodes can share identical", "# subtree thus we can not safely delete nodes for now", "#", "# \\@db.delete encoded", "end" ]
Delete node storage. @param node [Array, BLANK_NODE] node in form of array, or BLANK_NODE
[ "Delete", "node", "storage", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L494-L505
15,781
cryptape/ruby-ethereum
lib/ethereum/trie.rb
Ethereum.Trie.get_node_type
def get_node_type(node) return :blank if node == BLANK_NODE case node.size when KV_WIDTH # [k,v] NibbleKey.decode(node[0]).terminate? ? :leaf : :extension when BRANCH_WIDTH # [k0, ... k15, v] :branch else raise InvalidNode, "node size must be #{KV_WIDTH} or #{BRANCH_WIDTH}" end end
ruby
def get_node_type(node) return :blank if node == BLANK_NODE case node.size when KV_WIDTH # [k,v] NibbleKey.decode(node[0]).terminate? ? :leaf : :extension when BRANCH_WIDTH # [k0, ... k15, v] :branch else raise InvalidNode, "node size must be #{KV_WIDTH} or #{BRANCH_WIDTH}" end end
[ "def", "get_node_type", "(", "node", ")", "return", ":blank", "if", "node", "==", "BLANK_NODE", "case", "node", ".", "size", "when", "KV_WIDTH", "# [k,v]", "NibbleKey", ".", "decode", "(", "node", "[", "0", "]", ")", ".", "terminate?", "?", ":leaf", ":", ":extension", "when", "BRANCH_WIDTH", "# [k0, ... k15, v]", ":branch", "else", "raise", "InvalidNode", ",", "\"node size must be #{KV_WIDTH} or #{BRANCH_WIDTH}\"", "end", "end" ]
get node type and content @param node [Array, BLANK_NODE] node in form of array, or BLANK_NODE @return [Symbol] node type
[ "get", "node", "type", "and", "content" ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/trie.rb#L526-L537
15,782
cryptape/ruby-ethereum
lib/ethereum/vm.rb
Ethereum.VM.preprocess_code
def preprocess_code(code) code = Utils.bytes_to_int_array code ops = [] i = 0 while i < code.size o = Opcodes::TABLE.fetch(code[i], [:INVALID, 0, 0, 0]) + [code[i], 0] ops.push o if o[0][0,Opcodes::PREFIX_PUSH.size] == Opcodes::PREFIX_PUSH n = o[0][Opcodes::PREFIX_PUSH.size..-1].to_i n.times do |j| i += 1 byte = i < code.size ? code[i] : 0 o[-1] = (o[-1] << 8) + byte # polyfill, these INVALID ops will be skipped in execution ops.push [:INVALID, 0, 0, 0, byte, 0] if i < code.size end end i += 1 end ops end
ruby
def preprocess_code(code) code = Utils.bytes_to_int_array code ops = [] i = 0 while i < code.size o = Opcodes::TABLE.fetch(code[i], [:INVALID, 0, 0, 0]) + [code[i], 0] ops.push o if o[0][0,Opcodes::PREFIX_PUSH.size] == Opcodes::PREFIX_PUSH n = o[0][Opcodes::PREFIX_PUSH.size..-1].to_i n.times do |j| i += 1 byte = i < code.size ? code[i] : 0 o[-1] = (o[-1] << 8) + byte # polyfill, these INVALID ops will be skipped in execution ops.push [:INVALID, 0, 0, 0, byte, 0] if i < code.size end end i += 1 end ops end
[ "def", "preprocess_code", "(", "code", ")", "code", "=", "Utils", ".", "bytes_to_int_array", "code", "ops", "=", "[", "]", "i", "=", "0", "while", "i", "<", "code", ".", "size", "o", "=", "Opcodes", "::", "TABLE", ".", "fetch", "(", "code", "[", "i", "]", ",", "[", ":INVALID", ",", "0", ",", "0", ",", "0", "]", ")", "+", "[", "code", "[", "i", "]", ",", "0", "]", "ops", ".", "push", "o", "if", "o", "[", "0", "]", "[", "0", ",", "Opcodes", "::", "PREFIX_PUSH", ".", "size", "]", "==", "Opcodes", "::", "PREFIX_PUSH", "n", "=", "o", "[", "0", "]", "[", "Opcodes", "::", "PREFIX_PUSH", ".", "size", "..", "-", "1", "]", ".", "to_i", "n", ".", "times", "do", "|", "j", "|", "i", "+=", "1", "byte", "=", "i", "<", "code", ".", "size", "?", "code", "[", "i", "]", ":", "0", "o", "[", "-", "1", "]", "=", "(", "o", "[", "-", "1", "]", "<<", "8", ")", "+", "byte", "# polyfill, these INVALID ops will be skipped in execution", "ops", ".", "push", "[", ":INVALID", ",", "0", ",", "0", ",", "0", ",", "byte", ",", "0", "]", "if", "i", "<", "code", ".", "size", "end", "end", "i", "+=", "1", "end", "ops", "end" ]
Preprocesses code, and determines which locations are in the middle of pushdata and thus invalid
[ "Preprocesses", "code", "and", "determines", "which", "locations", "are", "in", "the", "middle", "of", "pushdata", "and", "thus", "invalid" ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/vm.rb#L574-L599
15,783
cryptape/ruby-ethereum
lib/ethereum/block_header.rb
Ethereum.BlockHeader.check_pow
def check_pow(nonce=nil) logger.debug "checking pow", block: full_hash_hex[0,8] Miner.check_pow(number, mining_hash, mixhash, nonce || self.nonce, difficulty) end
ruby
def check_pow(nonce=nil) logger.debug "checking pow", block: full_hash_hex[0,8] Miner.check_pow(number, mining_hash, mixhash, nonce || self.nonce, difficulty) end
[ "def", "check_pow", "(", "nonce", "=", "nil", ")", "logger", ".", "debug", "\"checking pow\"", ",", "block", ":", "full_hash_hex", "[", "0", ",", "8", "]", "Miner", ".", "check_pow", "(", "number", ",", "mining_hash", ",", "mixhash", ",", "nonce", "||", "self", ".", "nonce", ",", "difficulty", ")", "end" ]
Check if the proof-of-work of the block is valid. @param nonce [String] if given the proof of work function will be evaluated with this nonce instead of the one already present in the header @return [Bool]
[ "Check", "if", "the", "proof", "-", "of", "-", "work", "of", "the", "block", "is", "valid", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block_header.rb#L147-L150
15,784
cryptape/ruby-ethereum
lib/ethereum/block_header.rb
Ethereum.BlockHeader.to_h
def to_h h = {} %i(prevhash uncles_hash extra_data nonce mixhash).each do |field| h[field] = "0x#{Utils.encode_hex(send field)}" end %i(state_root tx_list_root receipts_root coinbase).each do |field| h[field] = Utils.encode_hex send(field) end %i(number difficulty gas_limit gas_used timestamp).each do |field| h[field] = send(field).to_s end h[:bloom] = Utils.encode_hex Sedes.int256.serialize(bloom) h end
ruby
def to_h h = {} %i(prevhash uncles_hash extra_data nonce mixhash).each do |field| h[field] = "0x#{Utils.encode_hex(send field)}" end %i(state_root tx_list_root receipts_root coinbase).each do |field| h[field] = Utils.encode_hex send(field) end %i(number difficulty gas_limit gas_used timestamp).each do |field| h[field] = send(field).to_s end h[:bloom] = Utils.encode_hex Sedes.int256.serialize(bloom) h end
[ "def", "to_h", "h", "=", "{", "}", "%i(", "prevhash", "uncles_hash", "extra_data", "nonce", "mixhash", ")", ".", "each", "do", "|", "field", "|", "h", "[", "field", "]", "=", "\"0x#{Utils.encode_hex(send field)}\"", "end", "%i(", "state_root", "tx_list_root", "receipts_root", "coinbase", ")", ".", "each", "do", "|", "field", "|", "h", "[", "field", "]", "=", "Utils", ".", "encode_hex", "send", "(", "field", ")", "end", "%i(", "number", "difficulty", "gas_limit", "gas_used", "timestamp", ")", ".", "each", "do", "|", "field", "|", "h", "[", "field", "]", "=", "send", "(", "field", ")", ".", "to_s", "end", "h", "[", ":bloom", "]", "=", "Utils", ".", "encode_hex", "Sedes", ".", "int256", ".", "serialize", "(", "bloom", ")", "h", "end" ]
Serialize the header to a readable hash.
[ "Serialize", "the", "header", "to", "a", "readable", "hash", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/block_header.rb#L155-L173
15,785
cryptape/ruby-ethereum
lib/ethereum/chain.rb
Ethereum.Chain.get_brothers
def get_brothers(block) o = [] i = 0 while block.has_parent? && i < @env.config[:max_uncle_depth] parent = block.get_parent children = get_children(parent).select {|c| c != block } o.concat children block = parent i += 1 end o end
ruby
def get_brothers(block) o = [] i = 0 while block.has_parent? && i < @env.config[:max_uncle_depth] parent = block.get_parent children = get_children(parent).select {|c| c != block } o.concat children block = parent i += 1 end o end
[ "def", "get_brothers", "(", "block", ")", "o", "=", "[", "]", "i", "=", "0", "while", "block", ".", "has_parent?", "&&", "i", "<", "@env", ".", "config", "[", ":max_uncle_depth", "]", "parent", "=", "block", ".", "get_parent", "children", "=", "get_children", "(", "parent", ")", ".", "select", "{", "|", "c", "|", "c", "!=", "block", "}", "o", ".", "concat", "children", "block", "=", "parent", "i", "+=", "1", "end", "o", "end" ]
Return the uncles of the hypothetical child of `block`.
[ "Return", "the", "uncles", "of", "the", "hypothetical", "child", "of", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/chain.rb#L68-L81
15,786
cryptape/ruby-ethereum
lib/ethereum/chain.rb
Ethereum.Chain.add_block
def add_block(block, forward_pending_transaction=true) unless block.has_parent? || block.genesis? logger.debug "missing parent", block_hash: block return false end unless block.validate_uncles logger.debug "invalid uncles", block_hash: block return false end unless block.header.check_pow || block.genesis? logger.debug "invalid nonce", block_hash: block return false end if block.has_parent? begin Block.verify(block, block.get_parent) rescue InvalidBlock => e log.fatal "VERIFICATION FAILED", block_hash: block, error: e f = File.join Utils.data_dir, 'badblock.log' File.write(f, Utils.encode_hex(RLP.encode(block))) return false end end if block.number < head.number logger.debug "older than head", block_hash: block, head_hash: head end @index.add_block block store_block block # set to head if this makes the longest chain w/ most work for that number if block.chain_difficulty > head.chain_difficulty logger.debug "new head", block_hash: block, num_tx: block.transaction_count update_head block, forward_pending_transaction elsif block.number > head.number logger.warn "has higher blk number than head but lower chain_difficulty", block_has: block, head_hash: head, block_difficulty: block.chain_difficulty, head_difficulty: head.chain_difficulty end # Refactor the long calling chain block.transactions.clear_all block.receipts.clear_all block.state.db.commit_refcount_changes block.number block.state.db.cleanup block.number commit # batch commits all changes that came with the new block true end
ruby
def add_block(block, forward_pending_transaction=true) unless block.has_parent? || block.genesis? logger.debug "missing parent", block_hash: block return false end unless block.validate_uncles logger.debug "invalid uncles", block_hash: block return false end unless block.header.check_pow || block.genesis? logger.debug "invalid nonce", block_hash: block return false end if block.has_parent? begin Block.verify(block, block.get_parent) rescue InvalidBlock => e log.fatal "VERIFICATION FAILED", block_hash: block, error: e f = File.join Utils.data_dir, 'badblock.log' File.write(f, Utils.encode_hex(RLP.encode(block))) return false end end if block.number < head.number logger.debug "older than head", block_hash: block, head_hash: head end @index.add_block block store_block block # set to head if this makes the longest chain w/ most work for that number if block.chain_difficulty > head.chain_difficulty logger.debug "new head", block_hash: block, num_tx: block.transaction_count update_head block, forward_pending_transaction elsif block.number > head.number logger.warn "has higher blk number than head but lower chain_difficulty", block_has: block, head_hash: head, block_difficulty: block.chain_difficulty, head_difficulty: head.chain_difficulty end # Refactor the long calling chain block.transactions.clear_all block.receipts.clear_all block.state.db.commit_refcount_changes block.number block.state.db.cleanup block.number commit # batch commits all changes that came with the new block true end
[ "def", "add_block", "(", "block", ",", "forward_pending_transaction", "=", "true", ")", "unless", "block", ".", "has_parent?", "||", "block", ".", "genesis?", "logger", ".", "debug", "\"missing parent\"", ",", "block_hash", ":", "block", "return", "false", "end", "unless", "block", ".", "validate_uncles", "logger", ".", "debug", "\"invalid uncles\"", ",", "block_hash", ":", "block", "return", "false", "end", "unless", "block", ".", "header", ".", "check_pow", "||", "block", ".", "genesis?", "logger", ".", "debug", "\"invalid nonce\"", ",", "block_hash", ":", "block", "return", "false", "end", "if", "block", ".", "has_parent?", "begin", "Block", ".", "verify", "(", "block", ",", "block", ".", "get_parent", ")", "rescue", "InvalidBlock", "=>", "e", "log", ".", "fatal", "\"VERIFICATION FAILED\"", ",", "block_hash", ":", "block", ",", "error", ":", "e", "f", "=", "File", ".", "join", "Utils", ".", "data_dir", ",", "'badblock.log'", "File", ".", "write", "(", "f", ",", "Utils", ".", "encode_hex", "(", "RLP", ".", "encode", "(", "block", ")", ")", ")", "return", "false", "end", "end", "if", "block", ".", "number", "<", "head", ".", "number", "logger", ".", "debug", "\"older than head\"", ",", "block_hash", ":", "block", ",", "head_hash", ":", "head", "end", "@index", ".", "add_block", "block", "store_block", "block", "# set to head if this makes the longest chain w/ most work for that number", "if", "block", ".", "chain_difficulty", ">", "head", ".", "chain_difficulty", "logger", ".", "debug", "\"new head\"", ",", "block_hash", ":", "block", ",", "num_tx", ":", "block", ".", "transaction_count", "update_head", "block", ",", "forward_pending_transaction", "elsif", "block", ".", "number", ">", "head", ".", "number", "logger", ".", "warn", "\"has higher blk number than head but lower chain_difficulty\"", ",", "block_has", ":", "block", ",", "head_hash", ":", "head", ",", "block_difficulty", ":", "block", ".", "chain_difficulty", ",", "head_difficulty", ":", "head", ".", "chain_difficulty", "end", "# Refactor the long calling chain", "block", ".", "transactions", ".", "clear_all", "block", ".", "receipts", ".", "clear_all", "block", ".", "state", ".", "db", ".", "commit_refcount_changes", "block", ".", "number", "block", ".", "state", ".", "db", ".", "cleanup", "block", ".", "number", "commit", "# batch commits all changes that came with the new block", "true", "end" ]
Returns `true` if block was added successfully.
[ "Returns", "true", "if", "block", "was", "added", "successfully", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/chain.rb#L109-L160
15,787
cryptape/ruby-ethereum
lib/ethereum/chain.rb
Ethereum.Chain.add_transaction
def add_transaction(transaction) raise AssertError, "head candiate cannot be nil" unless @head_candidate hc = @head_candidate logger.debug "add tx", num_txs: transaction_count, tx: transaction, on: hc if @head_candidate.include_transaction?(transaction.full_hash) logger.debug "known tx" return end old_state_root = hc.state_root # revert finalization hc.state_root = @pre_finalize_state_root begin success, output = hc.apply_transaction(transaction) rescue InvalidTransaction => e # if unsuccessful the prerequisites were not fullfilled and the tx is # invalid, state must not have changed logger.debug "invalid tx", error: e hc.state_root = old_state_root return false end logger.debug "valid tx" # we might have a new head_candidate (due to ctx switches in up layer) if @head_candidate != hc logger.debug "head_candidate changed during validation, trying again" return add_transaction(transaction) end @pre_finalize_state_root = hc.state_root hc.finalize logger.debug "tx applied", result: output raise AssertError, "state root unchanged!" unless old_state_root != hc.state_root true end
ruby
def add_transaction(transaction) raise AssertError, "head candiate cannot be nil" unless @head_candidate hc = @head_candidate logger.debug "add tx", num_txs: transaction_count, tx: transaction, on: hc if @head_candidate.include_transaction?(transaction.full_hash) logger.debug "known tx" return end old_state_root = hc.state_root # revert finalization hc.state_root = @pre_finalize_state_root begin success, output = hc.apply_transaction(transaction) rescue InvalidTransaction => e # if unsuccessful the prerequisites were not fullfilled and the tx is # invalid, state must not have changed logger.debug "invalid tx", error: e hc.state_root = old_state_root return false end logger.debug "valid tx" # we might have a new head_candidate (due to ctx switches in up layer) if @head_candidate != hc logger.debug "head_candidate changed during validation, trying again" return add_transaction(transaction) end @pre_finalize_state_root = hc.state_root hc.finalize logger.debug "tx applied", result: output raise AssertError, "state root unchanged!" unless old_state_root != hc.state_root true end
[ "def", "add_transaction", "(", "transaction", ")", "raise", "AssertError", ",", "\"head candiate cannot be nil\"", "unless", "@head_candidate", "hc", "=", "@head_candidate", "logger", ".", "debug", "\"add tx\"", ",", "num_txs", ":", "transaction_count", ",", "tx", ":", "transaction", ",", "on", ":", "hc", "if", "@head_candidate", ".", "include_transaction?", "(", "transaction", ".", "full_hash", ")", "logger", ".", "debug", "\"known tx\"", "return", "end", "old_state_root", "=", "hc", ".", "state_root", "# revert finalization", "hc", ".", "state_root", "=", "@pre_finalize_state_root", "begin", "success", ",", "output", "=", "hc", ".", "apply_transaction", "(", "transaction", ")", "rescue", "InvalidTransaction", "=>", "e", "# if unsuccessful the prerequisites were not fullfilled and the tx is", "# invalid, state must not have changed", "logger", ".", "debug", "\"invalid tx\"", ",", "error", ":", "e", "hc", ".", "state_root", "=", "old_state_root", "return", "false", "end", "logger", ".", "debug", "\"valid tx\"", "# we might have a new head_candidate (due to ctx switches in up layer)", "if", "@head_candidate", "!=", "hc", "logger", ".", "debug", "\"head_candidate changed during validation, trying again\"", "return", "add_transaction", "(", "transaction", ")", "end", "@pre_finalize_state_root", "=", "hc", ".", "state_root", "hc", ".", "finalize", "logger", ".", "debug", "\"tx applied\"", ",", "result", ":", "output", "raise", "AssertError", ",", "\"state root unchanged!\"", "unless", "old_state_root", "!=", "hc", ".", "state_root", "true", "end" ]
Add a transaction to the `head_candidate` block. If the transaction is invalid, the block will not be changed. @return [Bool,NilClass] `true` is the transaction was successfully added or `false` if the transaction was invalid, `nil` if it's already included
[ "Add", "a", "transaction", "to", "the", "head_candidate", "block", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/chain.rb#L174-L211
15,788
cryptape/ruby-ethereum
lib/ethereum/chain.rb
Ethereum.Chain.get_chain
def get_chain(start: '', count: 10) logger.debug "get_chain", start: Utils.encode_hex(start), count: count if start.true? return [] unless @index.db.include?(start) block = get start return [] unless in_main_branch?(block) else block = head end blocks = [] count.times do |i| blocks.push block break if block.genesis? block = block.get_parent end blocks end
ruby
def get_chain(start: '', count: 10) logger.debug "get_chain", start: Utils.encode_hex(start), count: count if start.true? return [] unless @index.db.include?(start) block = get start return [] unless in_main_branch?(block) else block = head end blocks = [] count.times do |i| blocks.push block break if block.genesis? block = block.get_parent end blocks end
[ "def", "get_chain", "(", "start", ":", "''", ",", "count", ":", "10", ")", "logger", ".", "debug", "\"get_chain\"", ",", "start", ":", "Utils", ".", "encode_hex", "(", "start", ")", ",", "count", ":", "count", "if", "start", ".", "true?", "return", "[", "]", "unless", "@index", ".", "db", ".", "include?", "(", "start", ")", "block", "=", "get", "start", "return", "[", "]", "unless", "in_main_branch?", "(", "block", ")", "else", "block", "=", "head", "end", "blocks", "=", "[", "]", "count", ".", "times", "do", "|", "i", "|", "blocks", ".", "push", "block", "break", "if", "block", ".", "genesis?", "block", "=", "block", ".", "get_parent", "end", "blocks", "end" ]
Return `count` of blocks starting from head or `start`.
[ "Return", "count", "of", "blocks", "starting", "from", "head", "or", "start", "." ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/chain.rb#L233-L253
15,789
cryptape/ruby-ethereum
lib/ethereum/chain.rb
Ethereum.Chain.update_head_candidate
def update_head_candidate(forward_pending_transaction=true) logger.debug "updating head candidate", head: head # collect uncles blk = head # parent of the block we are collecting uncles for uncles = get_brothers(blk).map(&:header).uniq (@env.config[:max_uncle_depth]+2).times do |i| blk.uncles.each {|u| uncles.delete u } blk = blk.get_parent if blk.has_parent? end raise "strange uncle found!" unless uncles.empty? || uncles.map(&:number).max <= head.number uncles = uncles[0, @env.config[:max_uncles]] # create block ts = [Time.now.to_i, head.timestamp+1].max _env = Env.new DB::OverlayDB.new(head.db), config: @env.config, global_config: @env.global_config hc = Block.build_from_parent head, @coinbase, timestamp: ts, uncles: uncles, env: _env raise ValidationError, "invalid uncles" unless hc.validate_uncles @pre_finalize_state_root = hc.state_root hc.finalize # add transactions from previous head candidate old_hc = @head_candidate @head_candidate = hc if old_hc tx_hashes = head.get_transaction_hashes pending = old_hc.get_transactions.select {|tx| !tx_hashes.include?(tx.full_hash) } if pending.true? if forward_pending_transaction logger.debug "forwarding pending transaction", num: pending.size pending.each {|tx| add_transaction tx } else logger.debug "discarding pending transaction", num: pending.size end end end end
ruby
def update_head_candidate(forward_pending_transaction=true) logger.debug "updating head candidate", head: head # collect uncles blk = head # parent of the block we are collecting uncles for uncles = get_brothers(blk).map(&:header).uniq (@env.config[:max_uncle_depth]+2).times do |i| blk.uncles.each {|u| uncles.delete u } blk = blk.get_parent if blk.has_parent? end raise "strange uncle found!" unless uncles.empty? || uncles.map(&:number).max <= head.number uncles = uncles[0, @env.config[:max_uncles]] # create block ts = [Time.now.to_i, head.timestamp+1].max _env = Env.new DB::OverlayDB.new(head.db), config: @env.config, global_config: @env.global_config hc = Block.build_from_parent head, @coinbase, timestamp: ts, uncles: uncles, env: _env raise ValidationError, "invalid uncles" unless hc.validate_uncles @pre_finalize_state_root = hc.state_root hc.finalize # add transactions from previous head candidate old_hc = @head_candidate @head_candidate = hc if old_hc tx_hashes = head.get_transaction_hashes pending = old_hc.get_transactions.select {|tx| !tx_hashes.include?(tx.full_hash) } if pending.true? if forward_pending_transaction logger.debug "forwarding pending transaction", num: pending.size pending.each {|tx| add_transaction tx } else logger.debug "discarding pending transaction", num: pending.size end end end end
[ "def", "update_head_candidate", "(", "forward_pending_transaction", "=", "true", ")", "logger", ".", "debug", "\"updating head candidate\"", ",", "head", ":", "head", "# collect uncles", "blk", "=", "head", "# parent of the block we are collecting uncles for", "uncles", "=", "get_brothers", "(", "blk", ")", ".", "map", "(", ":header", ")", ".", "uniq", "(", "@env", ".", "config", "[", ":max_uncle_depth", "]", "+", "2", ")", ".", "times", "do", "|", "i", "|", "blk", ".", "uncles", ".", "each", "{", "|", "u", "|", "uncles", ".", "delete", "u", "}", "blk", "=", "blk", ".", "get_parent", "if", "blk", ".", "has_parent?", "end", "raise", "\"strange uncle found!\"", "unless", "uncles", ".", "empty?", "||", "uncles", ".", "map", "(", ":number", ")", ".", "max", "<=", "head", ".", "number", "uncles", "=", "uncles", "[", "0", ",", "@env", ".", "config", "[", ":max_uncles", "]", "]", "# create block", "ts", "=", "[", "Time", ".", "now", ".", "to_i", ",", "head", ".", "timestamp", "+", "1", "]", ".", "max", "_env", "=", "Env", ".", "new", "DB", "::", "OverlayDB", ".", "new", "(", "head", ".", "db", ")", ",", "config", ":", "@env", ".", "config", ",", "global_config", ":", "@env", ".", "global_config", "hc", "=", "Block", ".", "build_from_parent", "head", ",", "@coinbase", ",", "timestamp", ":", "ts", ",", "uncles", ":", "uncles", ",", "env", ":", "_env", "raise", "ValidationError", ",", "\"invalid uncles\"", "unless", "hc", ".", "validate_uncles", "@pre_finalize_state_root", "=", "hc", ".", "state_root", "hc", ".", "finalize", "# add transactions from previous head candidate", "old_hc", "=", "@head_candidate", "@head_candidate", "=", "hc", "if", "old_hc", "tx_hashes", "=", "head", ".", "get_transaction_hashes", "pending", "=", "old_hc", ".", "get_transactions", ".", "select", "{", "|", "tx", "|", "!", "tx_hashes", ".", "include?", "(", "tx", ".", "full_hash", ")", "}", "if", "pending", ".", "true?", "if", "forward_pending_transaction", "logger", ".", "debug", "\"forwarding pending transaction\"", ",", "num", ":", "pending", ".", "size", "pending", ".", "each", "{", "|", "tx", "|", "add_transaction", "tx", "}", "else", "logger", ".", "debug", "\"discarding pending transaction\"", ",", "num", ":", "pending", ".", "size", "end", "end", "end", "end" ]
after new head is set
[ "after", "new", "head", "is", "set" ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/chain.rb#L355-L397
15,790
cryptape/ruby-ethereum
lib/ethereum/index.rb
Ethereum.Index.update_blocknumbers
def update_blocknumbers(blk) loop do if blk.number > 0 @db.put_temporarily block_by_number_key(blk.number), blk.full_hash else @db.put block_by_number_key(blk.number), blk.full_hash end @db.commit_refcount_changes blk.number break if blk.number == 0 blk = blk.get_parent() break if has_block_by_number(blk.number) && get_block_by_number(blk.number) == blk.full_hash end end
ruby
def update_blocknumbers(blk) loop do if blk.number > 0 @db.put_temporarily block_by_number_key(blk.number), blk.full_hash else @db.put block_by_number_key(blk.number), blk.full_hash end @db.commit_refcount_changes blk.number break if blk.number == 0 blk = blk.get_parent() break if has_block_by_number(blk.number) && get_block_by_number(blk.number) == blk.full_hash end end
[ "def", "update_blocknumbers", "(", "blk", ")", "loop", "do", "if", "blk", ".", "number", ">", "0", "@db", ".", "put_temporarily", "block_by_number_key", "(", "blk", ".", "number", ")", ",", "blk", ".", "full_hash", "else", "@db", ".", "put", "block_by_number_key", "(", "blk", ".", "number", ")", ",", "blk", ".", "full_hash", "end", "@db", ".", "commit_refcount_changes", "blk", ".", "number", "break", "if", "blk", ".", "number", "==", "0", "blk", "=", "blk", ".", "get_parent", "(", ")", "break", "if", "has_block_by_number", "(", "blk", ".", "number", ")", "&&", "get_block_by_number", "(", "blk", ".", "number", ")", "==", "blk", ".", "full_hash", "end", "end" ]
start from head and update until the existing indices match the block
[ "start", "from", "head", "and", "update", "until", "the", "existing", "indices", "match", "the", "block" ]
763f8651085ba145355a290da716884c7625a941
https://github.com/cryptape/ruby-ethereum/blob/763f8651085ba145355a290da716884c7625a941/lib/ethereum/index.rb#L33-L47
15,791
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.install_if_reported_available=
def install_if_reported_available=(new_val) return nil if new_val == @install_if_reported_available new_val = false if new_val.to_s.empty? raise JSS::InvalidDataError, 'install_if_reported_available must be boolean true or false' unless JSS::TRUE_FALSE.include? new_val @install_if_reported_available = new_val @need_to_update = true end
ruby
def install_if_reported_available=(new_val) return nil if new_val == @install_if_reported_available new_val = false if new_val.to_s.empty? raise JSS::InvalidDataError, 'install_if_reported_available must be boolean true or false' unless JSS::TRUE_FALSE.include? new_val @install_if_reported_available = new_val @need_to_update = true end
[ "def", "install_if_reported_available", "=", "(", "new_val", ")", "return", "nil", "if", "new_val", "==", "@install_if_reported_available", "new_val", "=", "false", "if", "new_val", ".", "to_s", ".", "empty?", "raise", "JSS", "::", "InvalidDataError", ",", "'install_if_reported_available must be boolean true or false'", "unless", "JSS", "::", "TRUE_FALSE", ".", "include?", "new_val", "@install_if_reported_available", "=", "new_val", "@need_to_update", "=", "true", "end" ]
Change the if_in_swupdate field in the JSS @param new_val[Boolean] @return [void]
[ "Change", "the", "if_in_swupdate", "field", "in", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L383-L389
15,792
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.priority=
def priority=(new_val) return nil if new_val == @priority new_val = DEFAULT_PRIORITY if new_val.to_s.empty? raise JSS::InvalidDataError, ':priority must be an integer from 1-20' unless PRIORITIES.include? new_val @priority = new_val @need_to_update = true end
ruby
def priority=(new_val) return nil if new_val == @priority new_val = DEFAULT_PRIORITY if new_val.to_s.empty? raise JSS::InvalidDataError, ':priority must be an integer from 1-20' unless PRIORITIES.include? new_val @priority = new_val @need_to_update = true end
[ "def", "priority", "=", "(", "new_val", ")", "return", "nil", "if", "new_val", "==", "@priority", "new_val", "=", "DEFAULT_PRIORITY", "if", "new_val", ".", "to_s", ".", "empty?", "raise", "JSS", "::", "InvalidDataError", ",", "':priority must be an integer from 1-20'", "unless", "PRIORITIES", ".", "include?", "new_val", "@priority", "=", "new_val", "@need_to_update", "=", "true", "end" ]
Change the priority field in the JSS @param new_val[Integer] one of PRIORITIES @return [void]
[ "Change", "the", "priority", "field", "in", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L485-L491
15,793
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.required_processor=
def required_processor=(new_val) return nil if new_val == @required_processor new_val = DEFAULT_PROCESSOR if new_val.to_s.empty? raise JSS::InvalidDataError, "Required_processor must be one of: #{CPU_TYPES.join ', '}" unless CPU_TYPES.include? new_val @required_processor = new_val @need_to_update = true end
ruby
def required_processor=(new_val) return nil if new_val == @required_processor new_val = DEFAULT_PROCESSOR if new_val.to_s.empty? raise JSS::InvalidDataError, "Required_processor must be one of: #{CPU_TYPES.join ', '}" unless CPU_TYPES.include? new_val @required_processor = new_val @need_to_update = true end
[ "def", "required_processor", "=", "(", "new_val", ")", "return", "nil", "if", "new_val", "==", "@required_processor", "new_val", "=", "DEFAULT_PROCESSOR", "if", "new_val", ".", "to_s", ".", "empty?", "raise", "JSS", "::", "InvalidDataError", ",", "\"Required_processor must be one of: #{CPU_TYPES.join ', '}\"", "unless", "CPU_TYPES", ".", "include?", "new_val", "@required_processor", "=", "new_val", "@need_to_update", "=", "true", "end" ]
Change the required processor field in the JSS @param new_val[String] one of {CPU_TYPES} @return [void]
[ "Change", "the", "required", "processor", "field", "in", "the", "JSS" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L513-L521
15,794
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.calculate_checksum
def calculate_checksum(type: nil, local_file: nil, rw_pw: nil, ro_pw: nil, unmount: true ) type ||= DEFAULT_CHECKSUM_HASH_TYPE mdp = JSS::DistributionPoint.master_distribution_point api: @api if local_file file_to_calc = local_file else if rw_pw dppw = rw_pw mnt = :rw elsif ro_pw dppw = ro_pw mnt = :ro else raise ArgumentError, 'Either rw_pw: or ro_pw: must be provided' end file_to_calc = mdp.mount(dppw, mnt) + "#{DIST_POINT_PKGS_FOLDER}/#{@filename}" end new_checksum = self.class.calculate_checksum(file_to_calc, type) mdp.unmount if unmount && mdp.mounted? new_checksum end
ruby
def calculate_checksum(type: nil, local_file: nil, rw_pw: nil, ro_pw: nil, unmount: true ) type ||= DEFAULT_CHECKSUM_HASH_TYPE mdp = JSS::DistributionPoint.master_distribution_point api: @api if local_file file_to_calc = local_file else if rw_pw dppw = rw_pw mnt = :rw elsif ro_pw dppw = ro_pw mnt = :ro else raise ArgumentError, 'Either rw_pw: or ro_pw: must be provided' end file_to_calc = mdp.mount(dppw, mnt) + "#{DIST_POINT_PKGS_FOLDER}/#{@filename}" end new_checksum = self.class.calculate_checksum(file_to_calc, type) mdp.unmount if unmount && mdp.mounted? new_checksum end
[ "def", "calculate_checksum", "(", "type", ":", "nil", ",", "local_file", ":", "nil", ",", "rw_pw", ":", "nil", ",", "ro_pw", ":", "nil", ",", "unmount", ":", "true", ")", "type", "||=", "DEFAULT_CHECKSUM_HASH_TYPE", "mdp", "=", "JSS", "::", "DistributionPoint", ".", "master_distribution_point", "api", ":", "@api", "if", "local_file", "file_to_calc", "=", "local_file", "else", "if", "rw_pw", "dppw", "=", "rw_pw", "mnt", "=", ":rw", "elsif", "ro_pw", "dppw", "=", "ro_pw", "mnt", "=", ":ro", "else", "raise", "ArgumentError", ",", "'Either rw_pw: or ro_pw: must be provided'", "end", "file_to_calc", "=", "mdp", ".", "mount", "(", "dppw", ",", "mnt", ")", "+", "\"#{DIST_POINT_PKGS_FOLDER}/#{@filename}\"", "end", "new_checksum", "=", "self", ".", "class", ".", "calculate_checksum", "(", "file_to_calc", ",", "type", ")", "mdp", ".", "unmount", "if", "unmount", "&&", "mdp", ".", "mounted?", "new_checksum", "end" ]
Caclulate and return the checksum hash for a given local file, or the file on the master dist point if no local file is given. @param type [String] The checksum hash type, one of the keys of CHECKSUM_HASH_TYPES @param local_file [String, Pathname] A local copy of the pkg file. BE SURE it's identical to the one on the server. If omitted, the master dist. point will be mounted and the file read from there. @param rw_pw [String] The read-write password for mounting the master dist point. Either this or the ro_pw must be provided if no local_file @param ro_pw [String] The read-onlypassword for mounting the master dist point. Either this or the rw_pw must be provided if no local_file @param unmount [Boolean] Unmount the master dist point after using it. Only used if the dist point is mounted. default: true @return [String] The calculated checksum
[ "Caclulate", "and", "return", "the", "checksum", "hash", "for", "a", "given", "local", "file", "or", "the", "file", "on", "the", "master", "dist", "point", "if", "no", "local", "file", "is", "given", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L702-L723
15,795
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.checksum_valid?
def checksum_valid?(local_file: nil, rw_pw: nil, ro_pw: nil, unmount: true) return false unless @checksum new_checksum = calculate_checksum( type: @checksum_type, local_file: local_file, rw_pw: rw_pw, ro_pw: ro_pw, unmount: unmount ) new_checksum == @checksum end
ruby
def checksum_valid?(local_file: nil, rw_pw: nil, ro_pw: nil, unmount: true) return false unless @checksum new_checksum = calculate_checksum( type: @checksum_type, local_file: local_file, rw_pw: rw_pw, ro_pw: ro_pw, unmount: unmount ) new_checksum == @checksum end
[ "def", "checksum_valid?", "(", "local_file", ":", "nil", ",", "rw_pw", ":", "nil", ",", "ro_pw", ":", "nil", ",", "unmount", ":", "true", ")", "return", "false", "unless", "@checksum", "new_checksum", "=", "calculate_checksum", "(", "type", ":", "@checksum_type", ",", "local_file", ":", "local_file", ",", "rw_pw", ":", "rw_pw", ",", "ro_pw", ":", "ro_pw", ",", "unmount", ":", "unmount", ")", "new_checksum", "==", "@checksum", "end" ]
Is the checksum for this pkg is valid? @param local_file [String, Pathname] A local copy of the pkg file. BE SURE it's identical to the one on the server. If omitted, the master dist. point will be mounted and the file read from there. @param rw_pw [String] The read-write password for mounting the master dist point. Either this or the ro_pw must be provided if no local_file @param ro_pw [String] The read-onlypassword for mounting the master dist point. Either this or the rw_pw must be provided if no local_file @param unmount [Boolean] Unmount the master dist point after using it. Only used if the dist point is mounted. default: true @return [Boolean] false if there is no checksum for this pkg, otherwise, does the calculated checksum match the one stored for the pkg?
[ "Is", "the", "checksum", "for", "this", "pkg", "is", "valid?" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L743-L753
15,796
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.update_master_filename
def update_master_filename(old_file_name, new_file_name, rw_pw, unmount = true) raise JSS::NoSuchItemError, "#{old_file_name} does not exist in the jss." unless @in_jss mdp = JSS::DistributionPoint.master_distribution_point api: @api pkgs_dir = mdp.mount(rw_pw, :rw) + DIST_POINT_PKGS_FOLDER.to_s old_file = pkgs_dir + old_file_name raise JSS::NoSuchItemError, "File not found on the master distribution point at #{DIST_POINT_PKGS_FOLDER}/#{old_file_name}." unless \ old_file.exist? new_file = pkgs_dir + new_file_name # use the extension of the original file. new_file = pkgs_dir + (new_file_name + old_file.extname) if new_file.extname.empty? old_file.rename new_file mdp.unmount if unmount nil end
ruby
def update_master_filename(old_file_name, new_file_name, rw_pw, unmount = true) raise JSS::NoSuchItemError, "#{old_file_name} does not exist in the jss." unless @in_jss mdp = JSS::DistributionPoint.master_distribution_point api: @api pkgs_dir = mdp.mount(rw_pw, :rw) + DIST_POINT_PKGS_FOLDER.to_s old_file = pkgs_dir + old_file_name raise JSS::NoSuchItemError, "File not found on the master distribution point at #{DIST_POINT_PKGS_FOLDER}/#{old_file_name}." unless \ old_file.exist? new_file = pkgs_dir + new_file_name # use the extension of the original file. new_file = pkgs_dir + (new_file_name + old_file.extname) if new_file.extname.empty? old_file.rename new_file mdp.unmount if unmount nil end
[ "def", "update_master_filename", "(", "old_file_name", ",", "new_file_name", ",", "rw_pw", ",", "unmount", "=", "true", ")", "raise", "JSS", "::", "NoSuchItemError", ",", "\"#{old_file_name} does not exist in the jss.\"", "unless", "@in_jss", "mdp", "=", "JSS", "::", "DistributionPoint", ".", "master_distribution_point", "api", ":", "@api", "pkgs_dir", "=", "mdp", ".", "mount", "(", "rw_pw", ",", ":rw", ")", "+", "DIST_POINT_PKGS_FOLDER", ".", "to_s", "old_file", "=", "pkgs_dir", "+", "old_file_name", "raise", "JSS", "::", "NoSuchItemError", ",", "\"File not found on the master distribution point at #{DIST_POINT_PKGS_FOLDER}/#{old_file_name}.\"", "unless", "old_file", ".", "exist?", "new_file", "=", "pkgs_dir", "+", "new_file_name", "# use the extension of the original file.", "new_file", "=", "pkgs_dir", "+", "(", "new_file_name", "+", "old_file", ".", "extname", ")", "if", "new_file", ".", "extname", ".", "empty?", "old_file", ".", "rename", "new_file", "mdp", ".", "unmount", "if", "unmount", "nil", "end" ]
Change the name of a package file on the master distribution point. @param new_file_name[String] @param old_file_name[default: @filename, String] @param unmount[Boolean] whether or not ot unount the distribution point when finished. @param rw_pw[String,Symbol] the password for the read/write account on the master Distribution Point, or :prompt, or :stdin# where # is the line of stdin containing the password See {JSS::DistributionPoint#mount} @return [nil]
[ "Change", "the", "name", "of", "a", "package", "file", "on", "the", "master", "distribution", "point", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L768-L783
15,797
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.delete
def delete(delete_file: false, rw_pw: nil, unmount: true) super() delete_master_file(rw_pw, unmount) if delete_file end
ruby
def delete(delete_file: false, rw_pw: nil, unmount: true) super() delete_master_file(rw_pw, unmount) if delete_file end
[ "def", "delete", "(", "delete_file", ":", "false", ",", "rw_pw", ":", "nil", ",", "unmount", ":", "true", ")", "super", "(", ")", "delete_master_file", "(", "rw_pw", ",", "unmount", ")", "if", "delete_file", "end" ]
delete master file Delete this package from the JSS, optionally deleting the master dist point file also. @param delete_file[Boolean] should the master dist point file be deleted? @param rw_pw[String] the password for the read/write account on the master Distribution Point or :prompt, or :stdin# where # is the line of stdin containing the password. See {JSS::DistributionPoint#mount} @param unmount[Boolean] whether or not ot unount the distribution point when finished.
[ "delete", "master", "file", "Delete", "this", "package", "from", "the", "JSS", "optionally", "deleting", "the", "master", "dist", "point", "file", "also", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L822-L825
15,798
PixarAnimationStudios/ruby-jss
lib/jss/api_object/package.rb
JSS.Package.uninstall
def uninstall(args = {}) unless removable? raise JSS::UnsupportedError, \ 'This package cannot be uninstalled. Please use CasperAdmin to index it and allow uninstalls' end raise JSS::UnsupportedError, 'You must have root privileges to uninstall packages' unless JSS.superuser? args[:target] ||= '/' # are we doing "fill existing users" or "fill user template"? do_feu = args[:feu] ? '-feu' : '' do_fut = args[:fut] ? '-fut' : '' # use jamf binary to uninstall the pkg jamf_opts = "-target '#{args[:target]}' -id '#{@id}' #{do_feu} #{do_fut}" # run it via a client JSS::Client.run_jamf 'uninstall', jamf_opts, args[:verbose] $CHILD_STATUS end
ruby
def uninstall(args = {}) unless removable? raise JSS::UnsupportedError, \ 'This package cannot be uninstalled. Please use CasperAdmin to index it and allow uninstalls' end raise JSS::UnsupportedError, 'You must have root privileges to uninstall packages' unless JSS.superuser? args[:target] ||= '/' # are we doing "fill existing users" or "fill user template"? do_feu = args[:feu] ? '-feu' : '' do_fut = args[:fut] ? '-fut' : '' # use jamf binary to uninstall the pkg jamf_opts = "-target '#{args[:target]}' -id '#{@id}' #{do_feu} #{do_fut}" # run it via a client JSS::Client.run_jamf 'uninstall', jamf_opts, args[:verbose] $CHILD_STATUS end
[ "def", "uninstall", "(", "args", "=", "{", "}", ")", "unless", "removable?", "raise", "JSS", "::", "UnsupportedError", ",", "'This package cannot be uninstalled. Please use CasperAdmin to index it and allow uninstalls'", "end", "raise", "JSS", "::", "UnsupportedError", ",", "'You must have root privileges to uninstall packages'", "unless", "JSS", ".", "superuser?", "args", "[", ":target", "]", "||=", "'/'", "# are we doing \"fill existing users\" or \"fill user template\"?", "do_feu", "=", "args", "[", ":feu", "]", "?", "'-feu'", ":", "''", "do_fut", "=", "args", "[", ":fut", "]", "?", "'-fut'", ":", "''", "# use jamf binary to uninstall the pkg", "jamf_opts", "=", "\"-target '#{args[:target]}' -id '#{@id}' #{do_feu} #{do_fut}\"", "# run it via a client", "JSS", "::", "Client", ".", "run_jamf", "'uninstall'", ",", "jamf_opts", ",", "args", "[", ":verbose", "]", "$CHILD_STATUS", "end" ]
Uninstall this pkg via the jamf command. @param args[Hash] the arguments for installation @option args :target[String,Pathname] The drive from which to uninstall the package, defaults to '/' @option args :verbose[Boolean] be verbose to stdout, defaults to false @option args :feu[Boolean] fill existing users, defaults to false @option args :fut[Boolean] fill user template, defaults to false @return [Process::Status] the result of the 'jamf uninstall' command @note This code must be run as root to uninstall packages
[ "Uninstall", "this", "pkg", "via", "the", "jamf", "command", "." ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/package.rb#L959-L978
15,799
PixarAnimationStudios/ruby-jss
lib/jss/api_object/distribution_point.rb
JSS.DistributionPoint.rest_xml
def rest_xml doc = REXML::Document.new dp = doc.add_element "distribution_point" dp.add_element(:name.to_s).text = @name dp.add_element(:ip_address.to_s).text = @ip_address dp.add_element(:local_path.to_s).text = @local_path dp.add_element(:enable_load_balancing.to_s).text = @enable_load_balancing dp.add_element(:failover_point.to_s).text = @failover_point dp.add_element(:is_master.to_s).text = @is_master dp.add_element(:connection_type.to_s).text = @connection_type dp.add_element(:share_port.to_s).text = @share_port dp.add_element(:share_name.to_s).text = @share_name dp.add_element(:read_write_username.to_s).text = @read_write_username dp.add_element(:read_write_password.to_s).text = @read_write_password dp.add_element(:read_only_username.to_s).text = @read_only_username dp.add_element(:read_only_password.to_s).text = @read_only_password dp.add_element(:workgroup_or_domain.to_s).text = @workgroup_or_domain dp.add_element(:http_downloads_enabled.to_s).text = @http_downloads_enabled dp.add_element(:protocol.to_s).text = @protocol dp.add_element(:port.to_s).text = @port dp.add_element(:context.to_s).text = @context dp.add_element(:no_authentication_required.to_s).text = @no_authentication_required dp.add_element(:certificate_required.to_s).text = @certificate_required dp.add_element(:username_password_required.to_s).text = @username_password_required dp.add_element(:http_username.to_s).text = @http_username dp.add_element(:certificate.to_s).text = @certificate dp.add_element(:http_url.to_s).text = @http_url dp.add_element(:failover_point_url.to_s).text = @failover_point_url dp.add_element(:ssh_username.to_s).text = @ssh_username dp.add_element(:ssh_password.to_s).text = @ssh_password if @ssh_password return doc.to_s end
ruby
def rest_xml doc = REXML::Document.new dp = doc.add_element "distribution_point" dp.add_element(:name.to_s).text = @name dp.add_element(:ip_address.to_s).text = @ip_address dp.add_element(:local_path.to_s).text = @local_path dp.add_element(:enable_load_balancing.to_s).text = @enable_load_balancing dp.add_element(:failover_point.to_s).text = @failover_point dp.add_element(:is_master.to_s).text = @is_master dp.add_element(:connection_type.to_s).text = @connection_type dp.add_element(:share_port.to_s).text = @share_port dp.add_element(:share_name.to_s).text = @share_name dp.add_element(:read_write_username.to_s).text = @read_write_username dp.add_element(:read_write_password.to_s).text = @read_write_password dp.add_element(:read_only_username.to_s).text = @read_only_username dp.add_element(:read_only_password.to_s).text = @read_only_password dp.add_element(:workgroup_or_domain.to_s).text = @workgroup_or_domain dp.add_element(:http_downloads_enabled.to_s).text = @http_downloads_enabled dp.add_element(:protocol.to_s).text = @protocol dp.add_element(:port.to_s).text = @port dp.add_element(:context.to_s).text = @context dp.add_element(:no_authentication_required.to_s).text = @no_authentication_required dp.add_element(:certificate_required.to_s).text = @certificate_required dp.add_element(:username_password_required.to_s).text = @username_password_required dp.add_element(:http_username.to_s).text = @http_username dp.add_element(:certificate.to_s).text = @certificate dp.add_element(:http_url.to_s).text = @http_url dp.add_element(:failover_point_url.to_s).text = @failover_point_url dp.add_element(:ssh_username.to_s).text = @ssh_username dp.add_element(:ssh_password.to_s).text = @ssh_password if @ssh_password return doc.to_s end
[ "def", "rest_xml", "doc", "=", "REXML", "::", "Document", ".", "new", "dp", "=", "doc", ".", "add_element", "\"distribution_point\"", "dp", ".", "add_element", "(", ":name", ".", "to_s", ")", ".", "text", "=", "@name", "dp", ".", "add_element", "(", ":ip_address", ".", "to_s", ")", ".", "text", "=", "@ip_address", "dp", ".", "add_element", "(", ":local_path", ".", "to_s", ")", ".", "text", "=", "@local_path", "dp", ".", "add_element", "(", ":enable_load_balancing", ".", "to_s", ")", ".", "text", "=", "@enable_load_balancing", "dp", ".", "add_element", "(", ":failover_point", ".", "to_s", ")", ".", "text", "=", "@failover_point", "dp", ".", "add_element", "(", ":is_master", ".", "to_s", ")", ".", "text", "=", "@is_master", "dp", ".", "add_element", "(", ":connection_type", ".", "to_s", ")", ".", "text", "=", "@connection_type", "dp", ".", "add_element", "(", ":share_port", ".", "to_s", ")", ".", "text", "=", "@share_port", "dp", ".", "add_element", "(", ":share_name", ".", "to_s", ")", ".", "text", "=", "@share_name", "dp", ".", "add_element", "(", ":read_write_username", ".", "to_s", ")", ".", "text", "=", "@read_write_username", "dp", ".", "add_element", "(", ":read_write_password", ".", "to_s", ")", ".", "text", "=", "@read_write_password", "dp", ".", "add_element", "(", ":read_only_username", ".", "to_s", ")", ".", "text", "=", "@read_only_username", "dp", ".", "add_element", "(", ":read_only_password", ".", "to_s", ")", ".", "text", "=", "@read_only_password", "dp", ".", "add_element", "(", ":workgroup_or_domain", ".", "to_s", ")", ".", "text", "=", "@workgroup_or_domain", "dp", ".", "add_element", "(", ":http_downloads_enabled", ".", "to_s", ")", ".", "text", "=", "@http_downloads_enabled", "dp", ".", "add_element", "(", ":protocol", ".", "to_s", ")", ".", "text", "=", "@protocol", "dp", ".", "add_element", "(", ":port", ".", "to_s", ")", ".", "text", "=", "@port", "dp", ".", "add_element", "(", ":context", ".", "to_s", ")", ".", "text", "=", "@context", "dp", ".", "add_element", "(", ":no_authentication_required", ".", "to_s", ")", ".", "text", "=", "@no_authentication_required", "dp", ".", "add_element", "(", ":certificate_required", ".", "to_s", ")", ".", "text", "=", "@certificate_required", "dp", ".", "add_element", "(", ":username_password_required", ".", "to_s", ")", ".", "text", "=", "@username_password_required", "dp", ".", "add_element", "(", ":http_username", ".", "to_s", ")", ".", "text", "=", "@http_username", "dp", ".", "add_element", "(", ":certificate", ".", "to_s", ")", ".", "text", "=", "@certificate", "dp", ".", "add_element", "(", ":http_url", ".", "to_s", ")", ".", "text", "=", "@http_url", "dp", ".", "add_element", "(", ":failover_point_url", ".", "to_s", ")", ".", "text", "=", "@failover_point_url", "dp", ".", "add_element", "(", ":ssh_username", ".", "to_s", ")", ".", "text", "=", "@ssh_username", "dp", ".", "add_element", "(", ":ssh_password", ".", "to_s", ")", ".", "text", "=", "@ssh_password", "if", "@ssh_password", "return", "doc", ".", "to_s", "end" ]
Unused - until I get around to making DP's updatable the XML representation of the current state of this object, for POSTing or PUTting back to the JSS via the API Will be supported for Dist Points some day, I'm sure.
[ "Unused", "-", "until", "I", "get", "around", "to", "making", "DP", "s", "updatable" ]
4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9
https://github.com/PixarAnimationStudios/ruby-jss/blob/4ab645bfaec8b2edb1ea146bfc2b10f0d62edee9/lib/jss/api_object/distribution_point.rb#L503-L538