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
4,000
hallison/sinatra-mapping
lib/sinatra/mapping.rb
Sinatra.Mapping.locations_get_from
def locations_get_from(*args) args.flatten.reject do |path| path == :root end.collect do |path| @locations[path] || path end end
ruby
def locations_get_from(*args) args.flatten.reject do |path| path == :root end.collect do |path| @locations[path] || path end end
[ "def", "locations_get_from", "(", "*", "args", ")", "args", ".", "flatten", ".", "reject", "do", "|", "path", "|", "path", "==", ":root", "end", ".", "collect", "do", "|", "path", "|", "@locations", "[", "path", "]", "||", "path", "end", "end" ]
Get paths from location maps.
[ "Get", "paths", "from", "location", "maps", "." ]
693ce820304f5aea8e9af879d89c96b8b3fa02ed
https://github.com/hallison/sinatra-mapping/blob/693ce820304f5aea8e9af879d89c96b8b3fa02ed/lib/sinatra/mapping.rb#L148-L154
4,001
rhenium/plum
lib/plum/server/connection.rb
Plum.ServerConnection.reserve_stream
def reserve_stream(**args) next_id = @max_stream_ids[0] + 2 stream = stream(next_id) stream.set_state(:reserved_local) stream.update_dependency(**args) stream end
ruby
def reserve_stream(**args) next_id = @max_stream_ids[0] + 2 stream = stream(next_id) stream.set_state(:reserved_local) stream.update_dependency(**args) stream end
[ "def", "reserve_stream", "(", "**", "args", ")", "next_id", "=", "@max_stream_ids", "[", "0", "]", "+", "2", "stream", "=", "stream", "(", "next_id", ")", "stream", ".", "set_state", "(", ":reserved_local", ")", "stream", ".", "update_dependency", "(", "**", "args", ")", "stream", "end" ]
Reserves a new stream to server push. @param args [Hash] The argument to pass to Stram.new.
[ "Reserves", "a", "new", "stream", "to", "server", "push", "." ]
9190801a092d46c7079ccee201b212b2d7985952
https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/server/connection.rb#L14-L20
4,002
GomaaK/sshez
lib/sshez/runner.rb
Sshez.Runner.process
def process(args) parser = Parser.new(Exec.new(self)) parser.parse(args) PRINTER.output end
ruby
def process(args) parser = Parser.new(Exec.new(self)) parser.parse(args) PRINTER.output end
[ "def", "process", "(", "args", ")", "parser", "=", "Parser", ".", "new", "(", "Exec", ".", "new", "(", "self", ")", ")", "parser", ".", "parse", "(", "args", ")", "PRINTER", ".", "output", "end" ]
Main method of the application takes un processed ARGS and pass it to our parser to start our processing
[ "Main", "method", "of", "the", "application", "takes", "un", "processed", "ARGS", "and", "pass", "it", "to", "our", "parser", "to", "start", "our", "processing" ]
6771012c2b29c2f28fdaf42372f93f70dbcbb291
https://github.com/GomaaK/sshez/blob/6771012c2b29c2f28fdaf42372f93f70dbcbb291/lib/sshez/runner.rb#L23-L27
4,003
twg/bootstrap_builder
lib/bootstrap_builder/builder.rb
BootstrapBuilder.Builder.element
def element(label = '&nbsp;', value = '', type = 'text_field', &block) value += @template.capture(&block) if block_given? %{ <div class='control-group'> <label class='control-label'>#{label}</label> <div class='controls'> #{value} </div> </div> }.html_safe end
ruby
def element(label = '&nbsp;', value = '', type = 'text_field', &block) value += @template.capture(&block) if block_given? %{ <div class='control-group'> <label class='control-label'>#{label}</label> <div class='controls'> #{value} </div> </div> }.html_safe end
[ "def", "element", "(", "label", "=", "'&nbsp;'", ",", "value", "=", "''", ",", "type", "=", "'text_field'", ",", "&", "block", ")", "value", "+=", "@template", ".", "capture", "(", "block", ")", "if", "block_given?", "%{\n <div class='control-group'>\n <label class='control-label'>#{label}</label>\n <div class='controls'>\n #{value}\n </div>\n </div>\n }", ".", "html_safe", "end" ]
generic container for all things form
[ "generic", "container", "for", "all", "things", "form" ]
6af08e205f4581705673e225868c831f26b64573
https://github.com/twg/bootstrap_builder/blob/6af08e205f4581705673e225868c831f26b64573/lib/bootstrap_builder/builder.rb#L134-L144
4,004
twg/bootstrap_builder
lib/bootstrap_builder/builder.rb
BootstrapBuilder.Builder.render_field
def render_field(field_name, method, options={}, html_options={}, &block) case field_name when 'check_box' template = field_name else template = 'default_field' end @template.render(:partial => "#{BootstrapBuilder.config.template_folder}/#{template}", :locals => { :builder => self, :method => method, :field => @template.capture(&block), :label_text => label_text(method, html_options[:label]), :required => html_options[:required], :prepend => html_options[:prepend], :append => html_options[:append], :help_block => html_options[:help_block], :error_messages => error_messages_for(method) }) end
ruby
def render_field(field_name, method, options={}, html_options={}, &block) case field_name when 'check_box' template = field_name else template = 'default_field' end @template.render(:partial => "#{BootstrapBuilder.config.template_folder}/#{template}", :locals => { :builder => self, :method => method, :field => @template.capture(&block), :label_text => label_text(method, html_options[:label]), :required => html_options[:required], :prepend => html_options[:prepend], :append => html_options[:append], :help_block => html_options[:help_block], :error_messages => error_messages_for(method) }) end
[ "def", "render_field", "(", "field_name", ",", "method", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ",", "&", "block", ")", "case", "field_name", "when", "'check_box'", "template", "=", "field_name", "else", "template", "=", "'default_field'", "end", "@template", ".", "render", "(", ":partial", "=>", "\"#{BootstrapBuilder.config.template_folder}/#{template}\"", ",", ":locals", "=>", "{", ":builder", "=>", "self", ",", ":method", "=>", "method", ",", ":field", "=>", "@template", ".", "capture", "(", "block", ")", ",", ":label_text", "=>", "label_text", "(", "method", ",", "html_options", "[", ":label", "]", ")", ",", ":required", "=>", "html_options", "[", ":required", "]", ",", ":prepend", "=>", "html_options", "[", ":prepend", "]", ",", ":append", "=>", "html_options", "[", ":append", "]", ",", ":help_block", "=>", "html_options", "[", ":help_block", "]", ",", ":error_messages", "=>", "error_messages_for", "(", "method", ")", "}", ")", "end" ]
Main rendering method
[ "Main", "rendering", "method" ]
6af08e205f4581705673e225868c831f26b64573
https://github.com/twg/bootstrap_builder/blob/6af08e205f4581705673e225868c831f26b64573/lib/bootstrap_builder/builder.rb#L171-L189
4,005
christinedraper/knife-topo
lib/chef/knife/topo/command_helper.rb
KnifeTopo.CommandHelper.initialize_cmd_args
def initialize_cmd_args(args, name_args, new_name_args) args = args.dup args.shift(2 + name_args.length) new_name_args + args end
ruby
def initialize_cmd_args(args, name_args, new_name_args) args = args.dup args.shift(2 + name_args.length) new_name_args + args end
[ "def", "initialize_cmd_args", "(", "args", ",", "name_args", ",", "new_name_args", ")", "args", "=", "args", ".", "dup", "args", ".", "shift", "(", "2", "+", "name_args", ".", "length", ")", "new_name_args", "+", "args", "end" ]
initialize args for another knife command
[ "initialize", "args", "for", "another", "knife", "command" ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/command_helper.rb#L25-L29
4,006
christinedraper/knife-topo
lib/chef/knife/topo/command_helper.rb
KnifeTopo.CommandHelper.run_cmd
def run_cmd(command_class, args) command = command_class.new(args) command.config[:config_file] = config[:config_file] command.configure_chef command_class.load_deps command.run command end
ruby
def run_cmd(command_class, args) command = command_class.new(args) command.config[:config_file] = config[:config_file] command.configure_chef command_class.load_deps command.run command end
[ "def", "run_cmd", "(", "command_class", ",", "args", ")", "command", "=", "command_class", ".", "new", "(", "args", ")", "command", ".", "config", "[", ":config_file", "]", "=", "config", "[", ":config_file", "]", "command", ".", "configure_chef", "command_class", ".", "load_deps", "command", ".", "run", "command", "end" ]
run another knife command
[ "run", "another", "knife", "command" ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/command_helper.rb#L32-L40
4,007
christinedraper/knife-topo
lib/chef/knife/topo/command_helper.rb
KnifeTopo.CommandHelper.resource_exists?
def resource_exists?(relative_path) rest.get_rest(relative_path) true rescue Net::HTTPServerException => e raise unless e.response.code == '404' false end
ruby
def resource_exists?(relative_path) rest.get_rest(relative_path) true rescue Net::HTTPServerException => e raise unless e.response.code == '404' false end
[ "def", "resource_exists?", "(", "relative_path", ")", "rest", ".", "get_rest", "(", "relative_path", ")", "true", "rescue", "Net", "::", "HTTPServerException", "=>", "e", "raise", "unless", "e", ".", "response", ".", "code", "==", "'404'", "false", "end" ]
check if resource exists
[ "check", "if", "resource", "exists" ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/command_helper.rb#L43-L49
4,008
christinedraper/knife-topo
lib/chef/knife/topo/command_helper.rb
KnifeTopo.CommandHelper.check_chef_env
def check_chef_env(chef_env_name) return unless chef_env_name Chef::Environment.load(chef_env_name) if chef_env_name rescue Net::HTTPServerException => e raise unless e.to_s =~ /^404/ ui.info 'Creating chef environment ' + chef_env_name chef_env = Chef::Environment.new chef_env.name(chef_env_name) chef_env.create chef_env end
ruby
def check_chef_env(chef_env_name) return unless chef_env_name Chef::Environment.load(chef_env_name) if chef_env_name rescue Net::HTTPServerException => e raise unless e.to_s =~ /^404/ ui.info 'Creating chef environment ' + chef_env_name chef_env = Chef::Environment.new chef_env.name(chef_env_name) chef_env.create chef_env end
[ "def", "check_chef_env", "(", "chef_env_name", ")", "return", "unless", "chef_env_name", "Chef", "::", "Environment", ".", "load", "(", "chef_env_name", ")", "if", "chef_env_name", "rescue", "Net", "::", "HTTPServerException", "=>", "e", "raise", "unless", "e", ".", "to_s", "=~", "/", "/", "ui", ".", "info", "'Creating chef environment '", "+", "chef_env_name", "chef_env", "=", "Chef", "::", "Environment", ".", "new", "chef_env", ".", "name", "(", "chef_env_name", ")", "chef_env", ".", "create", "chef_env", "end" ]
make sure the chef environment exists
[ "make", "sure", "the", "chef", "environment", "exists" ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/command_helper.rb#L52-L62
4,009
flippa/ralexa
lib/ralexa/abstract_service.rb
Ralexa.AbstractService.result
def result(*params, &parser) Result.new( @client, host, path, merged_params(*params), &parser ).result end
ruby
def result(*params, &parser) Result.new( @client, host, path, merged_params(*params), &parser ).result end
[ "def", "result", "(", "*", "params", ",", "&", "parser", ")", "Result", ".", "new", "(", "@client", ",", "host", ",", "path", ",", "merged_params", "(", "params", ")", ",", "parser", ")", ".", "result", "end" ]
a single result value
[ "a", "single", "result", "value" ]
fd5bdff102fe52f5c2898b1f917a12a1f17f25de
https://github.com/flippa/ralexa/blob/fd5bdff102fe52f5c2898b1f917a12a1f17f25de/lib/ralexa/abstract_service.rb#L11-L19
4,010
flippa/ralexa
lib/ralexa/abstract_service.rb
Ralexa.AbstractService.collection
def collection(*params, &parser) LazyCollection.new( @client, host, path, merged_params(*params), &parser ) end
ruby
def collection(*params, &parser) LazyCollection.new( @client, host, path, merged_params(*params), &parser ) end
[ "def", "collection", "(", "*", "params", ",", "&", "parser", ")", "LazyCollection", ".", "new", "(", "@client", ",", "host", ",", "path", ",", "merged_params", "(", "params", ")", ",", "parser", ")", "end" ]
A lazy collection which fetches records on demand.
[ "A", "lazy", "collection", "which", "fetches", "records", "on", "demand", "." ]
fd5bdff102fe52f5c2898b1f917a12a1f17f25de
https://github.com/flippa/ralexa/blob/fd5bdff102fe52f5c2898b1f917a12a1f17f25de/lib/ralexa/abstract_service.rb#L22-L30
4,011
flippa/ralexa
lib/ralexa/abstract_service.rb
Ralexa.AbstractService.merged_params
def merged_params(*params) params.reduce(default_params) do |merged, params| merged.merge(params) end end
ruby
def merged_params(*params) params.reduce(default_params) do |merged, params| merged.merge(params) end end
[ "def", "merged_params", "(", "*", "params", ")", "params", ".", "reduce", "(", "default_params", ")", "do", "|", "merged", ",", "params", "|", "merged", ".", "merge", "(", "params", ")", "end", "end" ]
A hash of the provided params hashes merged into the default_params.
[ "A", "hash", "of", "the", "provided", "params", "hashes", "merged", "into", "the", "default_params", "." ]
fd5bdff102fe52f5c2898b1f917a12a1f17f25de
https://github.com/flippa/ralexa/blob/fd5bdff102fe52f5c2898b1f917a12a1f17f25de/lib/ralexa/abstract_service.rb#L45-L49
4,012
romainberger/shop
lib/shop/template.rb
Shop.Template.custom_template_path
def custom_template_path(name) config = ShopConfig.new custom_path = config.get('template', 'path') if File.exists?("#{custom_path}/#{name}") "#{custom_path}/#{name}" else false end end
ruby
def custom_template_path(name) config = ShopConfig.new custom_path = config.get('template', 'path') if File.exists?("#{custom_path}/#{name}") "#{custom_path}/#{name}" else false end end
[ "def", "custom_template_path", "(", "name", ")", "config", "=", "ShopConfig", ".", "new", "custom_path", "=", "config", ".", "get", "(", "'template'", ",", "'path'", ")", "if", "File", ".", "exists?", "(", "\"#{custom_path}/#{name}\"", ")", "\"#{custom_path}/#{name}\"", "else", "false", "end", "end" ]
Returns the path to the custom template if it exists
[ "Returns", "the", "path", "to", "the", "custom", "template", "if", "it", "exists" ]
0cbfdf098027c7d5bb049f5181c5bbb3854cb543
https://github.com/romainberger/shop/blob/0cbfdf098027c7d5bb049f5181c5bbb3854cb543/lib/shop/template.rb#L5-L13
4,013
romainberger/shop
lib/shop/template.rb
Shop.Template.template_path
def template_path(name=false) custom_path = custom_template_path(name) if custom_path custom_path else path = File.expand_path File.dirname(__FILE__) return "#{path}/../../templates/#{name}" if name "#{path}/../../templates" end end
ruby
def template_path(name=false) custom_path = custom_template_path(name) if custom_path custom_path else path = File.expand_path File.dirname(__FILE__) return "#{path}/../../templates/#{name}" if name "#{path}/../../templates" end end
[ "def", "template_path", "(", "name", "=", "false", ")", "custom_path", "=", "custom_template_path", "(", "name", ")", "if", "custom_path", "custom_path", "else", "path", "=", "File", ".", "expand_path", "File", ".", "dirname", "(", "__FILE__", ")", "return", "\"#{path}/../../templates/#{name}\"", "if", "name", "\"#{path}/../../templates\"", "end", "end" ]
Returns the path to the templates directory Returns string
[ "Returns", "the", "path", "to", "the", "templates", "directory" ]
0cbfdf098027c7d5bb049f5181c5bbb3854cb543
https://github.com/romainberger/shop/blob/0cbfdf098027c7d5bb049f5181c5bbb3854cb543/lib/shop/template.rb#L18-L29
4,014
romainberger/shop
lib/shop/template.rb
Shop.Template.template
def template(name, datas) file = template_path(name) content = File.read(file) datas.each do |k, v| k = "<%= #{k} %>" content = content.gsub(k, v) end return content end
ruby
def template(name, datas) file = template_path(name) content = File.read(file) datas.each do |k, v| k = "<%= #{k} %>" content = content.gsub(k, v) end return content end
[ "def", "template", "(", "name", ",", "datas", ")", "file", "=", "template_path", "(", "name", ")", "content", "=", "File", ".", "read", "(", "file", ")", "datas", ".", "each", "do", "|", "k", ",", "v", "|", "k", "=", "\"<%= #{k} %>\"", "content", "=", "content", ".", "gsub", "(", "k", ",", "v", ")", "end", "return", "content", "end" ]
Replace the placeholders by the variables name: template name datas: hash containing the values Returns string
[ "Replace", "the", "placeholders", "by", "the", "variables" ]
0cbfdf098027c7d5bb049f5181c5bbb3854cb543
https://github.com/romainberger/shop/blob/0cbfdf098027c7d5bb049f5181c5bbb3854cb543/lib/shop/template.rb#L37-L46
4,015
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.binary=
def binary=(path) raise(ArgumentError, "binary doesn't exist") if !File.exists?(path) raise(ArgumentError, "binary isn't called \'barman\'") if File.basename(path) != 'barman' @binary = path end
ruby
def binary=(path) raise(ArgumentError, "binary doesn't exist") if !File.exists?(path) raise(ArgumentError, "binary isn't called \'barman\'") if File.basename(path) != 'barman' @binary = path end
[ "def", "binary", "=", "(", "path", ")", "raise", "(", "ArgumentError", ",", "\"binary doesn't exist\"", ")", "if", "!", "File", ".", "exists?", "(", "path", ")", "raise", "(", "ArgumentError", ",", "\"binary isn't called \\'barman\\'\"", ")", "if", "File", ".", "basename", "(", "path", ")", "!=", "'barman'", "@binary", "=", "path", "end" ]
Creates a new instance of CliCommand @param [String] path_to_binary see {#binary}. If nil, it will be initialized from {Configuration} @param [String] path_to_barman_home see {#barman_home}. If nil, it will be initialized from {Configuration}
[ "Creates", "a", "new", "instance", "of", "CliCommand" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L33-L37
4,016
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.backup
def backup(server, backup_id, opts = {}) raise(ArgumentError, "backup id must not be nil!") if backup_id.nil? opts[:backup_id] = backup_id return backups(server, opts)[0] end
ruby
def backup(server, backup_id, opts = {}) raise(ArgumentError, "backup id must not be nil!") if backup_id.nil? opts[:backup_id] = backup_id return backups(server, opts)[0] end
[ "def", "backup", "(", "server", ",", "backup_id", ",", "opts", "=", "{", "}", ")", "raise", "(", "ArgumentError", ",", "\"backup id must not be nil!\"", ")", "if", "backup_id", ".", "nil?", "opts", "[", ":backup_id", "]", "=", "backup_id", "return", "backups", "(", "server", ",", "opts", ")", "[", "0", "]", "end" ]
Instructs barman to get information about a specific backup @param [String] server server name @param [String] backup_id id of the backup @param [Hash] opts options for creating a {Backup} @option opts [Boolean] :with_wal_files whether to include {WalFiles} in each {Backup} @return [Backup] a new {Backup} object @raise [ArgumentError] if backup_id is nil
[ "Instructs", "barman", "to", "get", "information", "about", "a", "specific", "backup" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L51-L55
4,017
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.server
def server(name, opts = {}) lines = run_barman_command("show-server #{name}") server = parse_show_server_lines(name, lines) lines = run_barman_command("check #{name}", { :abort_on_error => false }) parse_check_lines(server, lines) server.backups = backups(server.name, opts) if opts[:with_backups] return server end
ruby
def server(name, opts = {}) lines = run_barman_command("show-server #{name}") server = parse_show_server_lines(name, lines) lines = run_barman_command("check #{name}", { :abort_on_error => false }) parse_check_lines(server, lines) server.backups = backups(server.name, opts) if opts[:with_backups] return server end
[ "def", "server", "(", "name", ",", "opts", "=", "{", "}", ")", "lines", "=", "run_barman_command", "(", "\"show-server #{name}\"", ")", "server", "=", "parse_show_server_lines", "(", "name", ",", "lines", ")", "lines", "=", "run_barman_command", "(", "\"check #{name}\"", ",", "{", ":abort_on_error", "=>", "false", "}", ")", "parse_check_lines", "(", "server", ",", "lines", ")", "server", ".", "backups", "=", "backups", "(", "server", ".", "name", ",", "opts", ")", "if", "opts", "[", ":with_backups", "]", "return", "server", "end" ]
Instructs barman to get information about a server @param [String] name name of the server @param [Hash] opts options for creating {Server} @option opts [Boolean] :with_backups whether to include {Backups} in {Server} @option opts [Boolean] :with_wal_files whether to include {WalFiles} in each {Backup} @return [Server] a new {Server}
[ "Instructs", "barman", "to", "get", "information", "about", "a", "server" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L87-L94
4,018
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.servers
def servers(opts = {}) result = Servers.new lines = run_barman_command("list-server") server_names = parse_list_server_lines(lines) server_names.each do |name| result << server(name, opts) end return result end
ruby
def servers(opts = {}) result = Servers.new lines = run_barman_command("list-server") server_names = parse_list_server_lines(lines) server_names.each do |name| result << server(name, opts) end return result end
[ "def", "servers", "(", "opts", "=", "{", "}", ")", "result", "=", "Servers", ".", "new", "lines", "=", "run_barman_command", "(", "\"list-server\"", ")", "server_names", "=", "parse_list_server_lines", "(", "lines", ")", "server_names", ".", "each", "do", "|", "name", "|", "result", "<<", "server", "(", "name", ",", "opts", ")", "end", "return", "result", "end" ]
Instructs barman to get information about all servers @param [Hash] opts options for creating {Servers} @option opts [Boolean] :with_backups whether to include {Backups} @option opts [Boolean] :with_wal_files whether to include {WalFiles} @return [Servers] an array of {Server}
[ "Instructs", "barman", "to", "get", "information", "about", "all", "servers" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L101-L109
4,019
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.wal_files
def wal_files(server, backup_id) lines = run_barman_command("list-files --target wal #{server} #{backup_id}") wal_files = parse_wal_files_list(lines) xlog_db = read_xlog_db(server) wal_files.each do |w| wal = "#{w.timeline}#{w.xlog}#{w.segment}" entry = xlog_db[wal] w.size = entry[:size] w.compression = entry[:compression] w.created = entry[:created].to_i end return wal_files end
ruby
def wal_files(server, backup_id) lines = run_barman_command("list-files --target wal #{server} #{backup_id}") wal_files = parse_wal_files_list(lines) xlog_db = read_xlog_db(server) wal_files.each do |w| wal = "#{w.timeline}#{w.xlog}#{w.segment}" entry = xlog_db[wal] w.size = entry[:size] w.compression = entry[:compression] w.created = entry[:created].to_i end return wal_files end
[ "def", "wal_files", "(", "server", ",", "backup_id", ")", "lines", "=", "run_barman_command", "(", "\"list-files --target wal #{server} #{backup_id}\"", ")", "wal_files", "=", "parse_wal_files_list", "(", "lines", ")", "xlog_db", "=", "read_xlog_db", "(", "server", ")", "wal_files", ".", "each", "do", "|", "w", "|", "wal", "=", "\"#{w.timeline}#{w.xlog}#{w.segment}\"", "entry", "=", "xlog_db", "[", "wal", "]", "w", ".", "size", "=", "entry", "[", ":size", "]", "w", ".", "compression", "=", "entry", "[", ":compression", "]", "w", ".", "created", "=", "entry", "[", ":created", "]", ".", "to_i", "end", "return", "wal_files", "end" ]
Instructs barman to list all wal files for a specific backup id @param [String] server server name @param [String] backup_id id of the backup @return [WalFiles] an array of {WalFile} @raise [RuntimeError] if wal file duplicates are found in xlog.db @raise [RuntimeError] if barman lists a wal file but no information could be found in xlog.db
[ "Instructs", "barman", "to", "list", "all", "wal", "files", "for", "a", "specific", "backup", "id" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L117-L129
4,020
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.parse_list_server_lines
def parse_list_server_lines(lines) result = Array.new lines.each do |l| result << l.split("-")[0].strip end return result end
ruby
def parse_list_server_lines(lines) result = Array.new lines.each do |l| result << l.split("-")[0].strip end return result end
[ "def", "parse_list_server_lines", "(", "lines", ")", "result", "=", "Array", ".", "new", "lines", ".", "each", "do", "|", "l", "|", "result", "<<", "l", ".", "split", "(", "\"-\"", ")", "[", "0", "]", ".", "strip", "end", "return", "result", "end" ]
Parses lines reported by barman's `list-server` @param [Array<String>] lines an array of lines from output of barman's `list-server` cmd @return [Array<String>] an array of server names
[ "Parses", "lines", "reported", "by", "barman", "s", "list", "-", "server" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L135-L141
4,021
sauspiel/rbarman
lib/rbarman/cli_command.rb
RBarman.CliCommand.create_recovery_cmd_args
def create_recovery_cmd_args(opts={}) args = Array.new args << "--remote-ssh-command='#{opts[:remote_ssh_cmd]}'" if opts[:remote_ssh_cmd] args << "--target-time '#{opts[:target_time].to_s}'" if opts[:target_time] args << "--target-xid #{opts[:target_xid]}" if opts[:target_xid] args << "--exclusive" if opts[:exclusive] return args.join(" ") end
ruby
def create_recovery_cmd_args(opts={}) args = Array.new args << "--remote-ssh-command='#{opts[:remote_ssh_cmd]}'" if opts[:remote_ssh_cmd] args << "--target-time '#{opts[:target_time].to_s}'" if opts[:target_time] args << "--target-xid #{opts[:target_xid]}" if opts[:target_xid] args << "--exclusive" if opts[:exclusive] return args.join(" ") end
[ "def", "create_recovery_cmd_args", "(", "opts", "=", "{", "}", ")", "args", "=", "Array", ".", "new", "args", "<<", "\"--remote-ssh-command='#{opts[:remote_ssh_cmd]}'\"", "if", "opts", "[", ":remote_ssh_cmd", "]", "args", "<<", "\"--target-time '#{opts[:target_time].to_s}'\"", "if", "opts", "[", ":target_time", "]", "args", "<<", "\"--target-xid #{opts[:target_xid]}\"", "if", "opts", "[", ":target_xid", "]", "args", "<<", "\"--exclusive\"", "if", "opts", "[", ":exclusive", "]", "return", "args", ".", "join", "(", "\" \"", ")", "end" ]
Creates an argument string for barman recovery command based on opts Hash @param [Hash] opts options for creating the arguments @option opts [String] :remote_ssh_cmd the ssh command to be used for remote recovery @option opts [String, Time] :target_time the timestamp as recovery target @option opts [String] :target_xid the transaction ID as recovery target @option opts [Boolean] :exclusive whether to stop immediately before or immediately after the recovery target @return [String] the arguments @since 0.0.3
[ "Creates", "an", "argument", "string", "for", "barman", "recovery", "command", "based", "on", "opts", "Hash" ]
89723b5e051bafb1c30848e4f431b9d058871e3f
https://github.com/sauspiel/rbarman/blob/89723b5e051bafb1c30848e4f431b9d058871e3f/lib/rbarman/cli_command.rb#L335-L342
4,022
christinedraper/knife-topo
lib/chef/knife/topo/node_update_helper.rb
KnifeTopo.NodeUpdateHelper.update_node
def update_node(node_updates, merge = false) config[:disable_editing] = true begin # load then update and save the node node = Chef::Node.load(node_updates['name']) env = node_updates['chef_environment'] check_chef_env(env) unless env == node['chef_environment'] do_node_updates(node, node_updates, merge) rescue Net::HTTPServerException => e raise unless e.to_s =~ /^404/ # Node has not been created end node end
ruby
def update_node(node_updates, merge = false) config[:disable_editing] = true begin # load then update and save the node node = Chef::Node.load(node_updates['name']) env = node_updates['chef_environment'] check_chef_env(env) unless env == node['chef_environment'] do_node_updates(node, node_updates, merge) rescue Net::HTTPServerException => e raise unless e.to_s =~ /^404/ # Node has not been created end node end
[ "def", "update_node", "(", "node_updates", ",", "merge", "=", "false", ")", "config", "[", ":disable_editing", "]", "=", "true", "begin", "# load then update and save the node", "node", "=", "Chef", "::", "Node", ".", "load", "(", "node_updates", "[", "'name'", "]", ")", "env", "=", "node_updates", "[", "'chef_environment'", "]", "check_chef_env", "(", "env", ")", "unless", "env", "==", "node", "[", "'chef_environment'", "]", "do_node_updates", "(", "node", ",", "node_updates", ",", "merge", ")", "rescue", "Net", "::", "HTTPServerException", "=>", "e", "raise", "unless", "e", ".", "to_s", "=~", "/", "/", "# Node has not been created", "end", "node", "end" ]
Update an existing node
[ "Update", "an", "existing", "node" ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/node_update_helper.rb#L28-L45
4,023
christinedraper/knife-topo
lib/chef/knife/topo/node_update_helper.rb
KnifeTopo.NodeUpdateHelper.update_node_with_values
def update_node_with_values(node, updates, merge = false) updated = [] # merge the normal attributes (but not tags) updated << 'normal' if update_attrs(node, updates['normal'], merge) # update runlist updated << 'run_list' if update_runlist(node, updates['run_list']) # update chef env if update_chef_env(node, updates['chef_environment']) updated << 'chef_environment' end # merge tags updated << 'tags' if update_tags(node, updates['tags']) # return false if no updates, else return array of property names !updated.empty? && updated end
ruby
def update_node_with_values(node, updates, merge = false) updated = [] # merge the normal attributes (but not tags) updated << 'normal' if update_attrs(node, updates['normal'], merge) # update runlist updated << 'run_list' if update_runlist(node, updates['run_list']) # update chef env if update_chef_env(node, updates['chef_environment']) updated << 'chef_environment' end # merge tags updated << 'tags' if update_tags(node, updates['tags']) # return false if no updates, else return array of property names !updated.empty? && updated end
[ "def", "update_node_with_values", "(", "node", ",", "updates", ",", "merge", "=", "false", ")", "updated", "=", "[", "]", "# merge the normal attributes (but not tags)", "updated", "<<", "'normal'", "if", "update_attrs", "(", "node", ",", "updates", "[", "'normal'", "]", ",", "merge", ")", "# update runlist", "updated", "<<", "'run_list'", "if", "update_runlist", "(", "node", ",", "updates", "[", "'run_list'", "]", ")", "# update chef env", "if", "update_chef_env", "(", "node", ",", "updates", "[", "'chef_environment'", "]", ")", "updated", "<<", "'chef_environment'", "end", "# merge tags", "updated", "<<", "'tags'", "if", "update_tags", "(", "node", ",", "updates", "[", "'tags'", "]", ")", "# return false if no updates, else return array of property names", "!", "updated", ".", "empty?", "&&", "updated", "end" ]
Update original node, return list of updated properties.
[ "Update", "original", "node", "return", "list", "of", "updated", "properties", "." ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/node_update_helper.rb#L59-L78
4,024
christinedraper/knife-topo
lib/chef/knife/topo/node_update_helper.rb
KnifeTopo.NodeUpdateHelper.update_attrs
def update_attrs(node, attrs, merge = false) return false unless attrs # keep the current tags attrs['tags'] = node.normal.tags || [] original = Marshal.load(Marshal.dump(node.normal)) node.normal = if merge Chef::Mixin::DeepMerge.merge(node.normal, attrs) else attrs end original != node.normal end
ruby
def update_attrs(node, attrs, merge = false) return false unless attrs # keep the current tags attrs['tags'] = node.normal.tags || [] original = Marshal.load(Marshal.dump(node.normal)) node.normal = if merge Chef::Mixin::DeepMerge.merge(node.normal, attrs) else attrs end original != node.normal end
[ "def", "update_attrs", "(", "node", ",", "attrs", ",", "merge", "=", "false", ")", "return", "false", "unless", "attrs", "# keep the current tags", "attrs", "[", "'tags'", "]", "=", "node", ".", "normal", ".", "tags", "||", "[", "]", "original", "=", "Marshal", ".", "load", "(", "Marshal", ".", "dump", "(", "node", ".", "normal", ")", ")", "node", ".", "normal", "=", "if", "merge", "Chef", "::", "Mixin", "::", "DeepMerge", ".", "merge", "(", "node", ".", "normal", ",", "attrs", ")", "else", "attrs", "end", "original", "!=", "node", ".", "normal", "end" ]
Update methods all return true if an actual update is made
[ "Update", "methods", "all", "return", "true", "if", "an", "actual", "update", "is", "made" ]
323f5767a6ed98212629888323c4e694fec820ca
https://github.com/christinedraper/knife-topo/blob/323f5767a6ed98212629888323c4e694fec820ca/lib/chef/knife/topo/node_update_helper.rb#L81-L92
4,025
marks/truevault.rb
lib/truevault/user.rb
TrueVault.User.create
def create(options = {}) query = { query: { username: options[:username], password: options[:password], attributes: hash_to_base64_json(options[:attributes]) } } new_options = default_options_to_merge_with.merge(query) self.class.post("/#{@api_ver}/users", new_options) end
ruby
def create(options = {}) query = { query: { username: options[:username], password: options[:password], attributes: hash_to_base64_json(options[:attributes]) } } new_options = default_options_to_merge_with.merge(query) self.class.post("/#{@api_ver}/users", new_options) end
[ "def", "create", "(", "options", "=", "{", "}", ")", "query", "=", "{", "query", ":", "{", "username", ":", "options", "[", ":username", "]", ",", "password", ":", "options", "[", ":password", "]", ",", "attributes", ":", "hash_to_base64_json", "(", "options", "[", ":attributes", "]", ")", "}", "}", "new_options", "=", "default_options_to_merge_with", ".", "merge", "(", "query", ")", "self", ".", "class", ".", "post", "(", "\"/#{@api_ver}/users\"", ",", "new_options", ")", "end" ]
USER API Methods creates a user TVUser.create_user( username: "bar", password: "foo", attributes: { "id": "000", "name": "John", "type": "patient" } } )
[ "USER", "API", "Methods" ]
d0d22fc0945de324e45e7d300a37542949ee67b9
https://github.com/marks/truevault.rb/blob/d0d22fc0945de324e45e7d300a37542949ee67b9/lib/truevault/user.rb#L21-L31
4,026
marks/truevault.rb
lib/truevault/user.rb
TrueVault.User.all
def all(read_attributes="01") options = default_options_to_merge_with.merge({ query: { full: read_attributes} }) self.class.get("/#{@api_ver}/users", options) end
ruby
def all(read_attributes="01") options = default_options_to_merge_with.merge({ query: { full: read_attributes} }) self.class.get("/#{@api_ver}/users", options) end
[ "def", "all", "(", "read_attributes", "=", "\"01\"", ")", "options", "=", "default_options_to_merge_with", ".", "merge", "(", "{", "query", ":", "{", "full", ":", "read_attributes", "}", "}", ")", "self", ".", "class", ".", "get", "(", "\"/#{@api_ver}/users\"", ",", "options", ")", "end" ]
list all users TVUser.list_users
[ "list", "all", "users", "TVUser", ".", "list_users" ]
d0d22fc0945de324e45e7d300a37542949ee67b9
https://github.com/marks/truevault.rb/blob/d0d22fc0945de324e45e7d300a37542949ee67b9/lib/truevault/user.rb#L44-L47
4,027
paradox460/le_meme
lib/le_meme/meme_lib.rb
LeMeme.MemeLib.load_directory!
def load_directory!(dir) paths = Dir.glob(dir).grep LeMeme::IMAGE_EXTENSIONS @memes.merge!(paths.reduce({}) do |images, path| path = File.expand_path(path) name = path.split.last.sub(LeMeme::IMAGE_EXTENSIONS, '').to_s images.merge(name => path) end) end
ruby
def load_directory!(dir) paths = Dir.glob(dir).grep LeMeme::IMAGE_EXTENSIONS @memes.merge!(paths.reduce({}) do |images, path| path = File.expand_path(path) name = path.split.last.sub(LeMeme::IMAGE_EXTENSIONS, '').to_s images.merge(name => path) end) end
[ "def", "load_directory!", "(", "dir", ")", "paths", "=", "Dir", ".", "glob", "(", "dir", ")", ".", "grep", "LeMeme", "::", "IMAGE_EXTENSIONS", "@memes", ".", "merge!", "(", "paths", ".", "reduce", "(", "{", "}", ")", "do", "|", "images", ",", "path", "|", "path", "=", "File", ".", "expand_path", "(", "path", ")", "name", "=", "path", ".", "split", ".", "last", ".", "sub", "(", "LeMeme", "::", "IMAGE_EXTENSIONS", ",", "''", ")", ".", "to_s", "images", ".", "merge", "(", "name", "=>", "path", ")", "end", ")", "end" ]
Loads a directory into the MemeLib, for template consumption Clobbers any existing templates @param [String] dir Directory glob pattern to meme templates @return [Hash] Hash of all templates and their filepaths
[ "Loads", "a", "directory", "into", "the", "MemeLib", "for", "template", "consumption", "Clobbers", "any", "existing", "templates" ]
cd625df2e29c2c619511dedd5ef0014c2b731696
https://github.com/paradox460/le_meme/blob/cd625df2e29c2c619511dedd5ef0014c2b731696/lib/le_meme/meme_lib.rb#L27-L34
4,028
paradox460/le_meme
lib/le_meme/meme_lib.rb
LeMeme.MemeLib.meme
def meme(template: nil, top: nil, bottom: nil, watermark: nil) path = template.nil? ? @memes.values.sample : @memes[template] Meme.new(path, top: top, bottom: bottom, watermark: watermark) end
ruby
def meme(template: nil, top: nil, bottom: nil, watermark: nil) path = template.nil? ? @memes.values.sample : @memes[template] Meme.new(path, top: top, bottom: bottom, watermark: watermark) end
[ "def", "meme", "(", "template", ":", "nil", ",", "top", ":", "nil", ",", "bottom", ":", "nil", ",", "watermark", ":", "nil", ")", "path", "=", "template", ".", "nil?", "?", "@memes", ".", "values", ".", "sample", ":", "@memes", "[", "template", "]", "Meme", ".", "new", "(", "path", ",", "top", ":", "top", ",", "bottom", ":", "bottom", ",", "watermark", ":", "watermark", ")", "end" ]
Create a meme from a template @param [String] template: nil The template to use. Omit for random template @param [String] top: nil @param [String] bottom: nil @param [String] watermark: nil @return [LeMeme::Meme]
[ "Create", "a", "meme", "from", "a", "template" ]
cd625df2e29c2c619511dedd5ef0014c2b731696
https://github.com/paradox460/le_meme/blob/cd625df2e29c2c619511dedd5ef0014c2b731696/lib/le_meme/meme_lib.rb#L43-L47
4,029
kristianmandrup/cancan-permits
lib/cancan-permits/permits/ability.rb
Permits.Ability.role_groups
def role_groups groups = [] user_account_class.role_groups.map{|k,v| groups << k if user_account.has_any_role?(v)} groups end
ruby
def role_groups groups = [] user_account_class.role_groups.map{|k,v| groups << k if user_account.has_any_role?(v)} groups end
[ "def", "role_groups", "groups", "=", "[", "]", "user_account_class", ".", "role_groups", ".", "map", "{", "|", "k", ",", "v", "|", "groups", "<<", "k", "if", "user_account", ".", "has_any_role?", "(", "v", ")", "}", "groups", "end" ]
return list of symbols for role groups the user belongs to
[ "return", "list", "of", "symbols", "for", "role", "groups", "the", "user", "belongs", "to" ]
cbc56d299751118b5b6629af0f77917b3d762d61
https://github.com/kristianmandrup/cancan-permits/blob/cbc56d299751118b5b6629af0f77917b3d762d61/lib/cancan-permits/permits/ability.rb#L55-L59
4,030
rhenium/plum
lib/plum/flow_control.rb
Plum.FlowControl.send
def send(frame) if Frame::Data === frame @send_buffer << frame if @send_remaining_window < frame.length if Stream === self connection.callback(:send_deferred, self, frame) else callback(:send_deferred, self, frame) end else consume_send_buffer end else send_immediately frame end end
ruby
def send(frame) if Frame::Data === frame @send_buffer << frame if @send_remaining_window < frame.length if Stream === self connection.callback(:send_deferred, self, frame) else callback(:send_deferred, self, frame) end else consume_send_buffer end else send_immediately frame end end
[ "def", "send", "(", "frame", ")", "if", "Frame", "::", "Data", "===", "frame", "@send_buffer", "<<", "frame", "if", "@send_remaining_window", "<", "frame", ".", "length", "if", "Stream", "===", "self", "connection", ".", "callback", "(", ":send_deferred", ",", "self", ",", "frame", ")", "else", "callback", "(", ":send_deferred", ",", "self", ",", "frame", ")", "end", "else", "consume_send_buffer", "end", "else", "send_immediately", "frame", "end", "end" ]
Sends frame respecting inner-stream flow control. @param frame [Frame] The frame to be sent.
[ "Sends", "frame", "respecting", "inner", "-", "stream", "flow", "control", "." ]
9190801a092d46c7079ccee201b212b2d7985952
https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/flow_control.rb#L11-L26
4,031
rhenium/plum
lib/plum/flow_control.rb
Plum.FlowControl.window_update
def window_update(wsi) @recv_remaining_window += wsi sid = (Stream === self) ? self.id : 0 send_immediately Frame::WindowUpdate.new(sid, wsi) end
ruby
def window_update(wsi) @recv_remaining_window += wsi sid = (Stream === self) ? self.id : 0 send_immediately Frame::WindowUpdate.new(sid, wsi) end
[ "def", "window_update", "(", "wsi", ")", "@recv_remaining_window", "+=", "wsi", "sid", "=", "(", "Stream", "===", "self", ")", "?", "self", ".", "id", ":", "0", "send_immediately", "Frame", "::", "WindowUpdate", ".", "new", "(", "sid", ",", "wsi", ")", "end" ]
Increases receiving window size. Sends WINDOW_UPDATE frame to the peer. @param wsi [Integer] The amount to increase receiving window size. The legal range is 1 to 2^32-1.
[ "Increases", "receiving", "window", "size", ".", "Sends", "WINDOW_UPDATE", "frame", "to", "the", "peer", "." ]
9190801a092d46c7079ccee201b212b2d7985952
https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/flow_control.rb#L30-L34
4,032
dmacvicar/bicho
lib/bicho/bug.rb
Bicho.Bug.add_attachment
def add_attachment(summary, file, **kwargs) @client.add_attachment(summary, file, id, **kwargs).first end
ruby
def add_attachment(summary, file, **kwargs) @client.add_attachment(summary, file, id, **kwargs).first end
[ "def", "add_attachment", "(", "summary", ",", "file", ",", "**", "kwargs", ")", "@client", ".", "add_attachment", "(", "summary", ",", "file", ",", "id", ",", "**", "kwargs", ")", ".", "first", "end" ]
Add an attachment to the bug For the params description, see the Client.add_attachment method. @return [ID] of the new attachment
[ "Add", "an", "attachment", "to", "the", "bug", "For", "the", "params", "description", "see", "the", "Client", ".", "add_attachment", "method", "." ]
fff403fcc5b1e1b6c81defd7c6434e9499aa1a63
https://github.com/dmacvicar/bicho/blob/fff403fcc5b1e1b6c81defd7c6434e9499aa1a63/lib/bicho/bug.rb#L108-L110
4,033
TwP/pixel_pi
lib/pixel_pi/fake_leds.rb
PixelPi.Leds.show
def show closed! if @debug ary = @leds.map { |value| Rainbow(@debug).color(*to_rgb(value)) } $stdout.print "\r#{ary.join}" end self end
ruby
def show closed! if @debug ary = @leds.map { |value| Rainbow(@debug).color(*to_rgb(value)) } $stdout.print "\r#{ary.join}" end self end
[ "def", "show", "closed!", "if", "@debug", "ary", "=", "@leds", ".", "map", "{", "|", "value", "|", "Rainbow", "(", "@debug", ")", ".", "color", "(", "to_rgb", "(", "value", ")", ")", "}", "$stdout", ".", "print", "\"\\r#{ary.join}\"", "end", "self", "end" ]
Update the display with the data from the LED buffer. This is a noop method for the fake LEDs.
[ "Update", "the", "display", "with", "the", "data", "from", "the", "LED", "buffer", ".", "This", "is", "a", "noop", "method", "for", "the", "fake", "LEDs", "." ]
e0a63e337f378f48ecf4df20b2e55d87d84a2a5c
https://github.com/TwP/pixel_pi/blob/e0a63e337f378f48ecf4df20b2e55d87d84a2a5c/lib/pixel_pi/fake_leds.rb#L65-L72
4,034
TwP/pixel_pi
lib/pixel_pi/fake_leds.rb
PixelPi.Leds.[]=
def []=( num, value ) closed! if (num < 0 || num >= @leds.length) raise IndexError, "index #{num} is outside of LED range: 0...#{@leds.length-1}" end @leds[num] = to_color(value) end
ruby
def []=( num, value ) closed! if (num < 0 || num >= @leds.length) raise IndexError, "index #{num} is outside of LED range: 0...#{@leds.length-1}" end @leds[num] = to_color(value) end
[ "def", "[]=", "(", "num", ",", "value", ")", "closed!", "if", "(", "num", "<", "0", "||", "num", ">=", "@leds", ".", "length", ")", "raise", "IndexError", ",", "\"index #{num} is outside of LED range: 0...#{@leds.length-1}\"", "end", "@leds", "[", "num", "]", "=", "to_color", "(", "value", ")", "end" ]
Set the LED at position `num` to the provided 24-bit RGB color value. Returns the 24-bit RGB color value.
[ "Set", "the", "LED", "at", "position", "num", "to", "the", "provided", "24", "-", "bit", "RGB", "color", "value", "." ]
e0a63e337f378f48ecf4df20b2e55d87d84a2a5c
https://github.com/TwP/pixel_pi/blob/e0a63e337f378f48ecf4df20b2e55d87d84a2a5c/lib/pixel_pi/fake_leds.rb#L97-L103
4,035
TwP/pixel_pi
lib/pixel_pi/fake_leds.rb
PixelPi.Leds.replace
def replace( ary ) closed! @leds.length.times do |ii| @leds[ii] = Integer(ary[ii]) end self end
ruby
def replace( ary ) closed! @leds.length.times do |ii| @leds[ii] = Integer(ary[ii]) end self end
[ "def", "replace", "(", "ary", ")", "closed!", "@leds", ".", "length", ".", "times", "do", "|", "ii", "|", "@leds", "[", "ii", "]", "=", "Integer", "(", "ary", "[", "ii", "]", ")", "end", "self", "end" ]
Replace the LED colors with the 24-bit RGB color values found in the `ary`. If the `ary` is longer than the LED string then the extra color values will be ignored. If the `ary` is shorter than the LED string then only the LEDS up to `ary.length` will be changed. You must call `show` for the new colors to be displayed. Returns this PixelPi::Leds instance.
[ "Replace", "the", "LED", "colors", "with", "the", "24", "-", "bit", "RGB", "color", "values", "found", "in", "the", "ary", ".", "If", "the", "ary", "is", "longer", "than", "the", "LED", "string", "then", "the", "extra", "color", "values", "will", "be", "ignored", ".", "If", "the", "ary", "is", "shorter", "than", "the", "LED", "string", "then", "only", "the", "LEDS", "up", "to", "ary", ".", "length", "will", "be", "changed", "." ]
e0a63e337f378f48ecf4df20b2e55d87d84a2a5c
https://github.com/TwP/pixel_pi/blob/e0a63e337f378f48ecf4df20b2e55d87d84a2a5c/lib/pixel_pi/fake_leds.rb#L133-L139
4,036
TwP/pixel_pi
lib/pixel_pi/fake_leds.rb
PixelPi.Leds.fill
def fill( *args ) closed! if block_given? @leds.fill do |ii| value = yield(ii) to_color(value) end else value = to_color(args.shift) @leds.fill(value, *args) end self end
ruby
def fill( *args ) closed! if block_given? @leds.fill do |ii| value = yield(ii) to_color(value) end else value = to_color(args.shift) @leds.fill(value, *args) end self end
[ "def", "fill", "(", "*", "args", ")", "closed!", "if", "block_given?", "@leds", ".", "fill", "do", "|", "ii", "|", "value", "=", "yield", "(", "ii", ")", "to_color", "(", "value", ")", "end", "else", "value", "=", "to_color", "(", "args", ".", "shift", ")", "@leds", ".", "fill", "(", "value", ",", "args", ")", "end", "self", "end" ]
Set the selected LEDs to the given `color`. The `color` msut be given as a 24-bit RGB value. You can also supply a block that receives an LED index and returns a 24-bit RGB color. Examples: leds.fill( 0x00FF00 ) leds.fill( 0xFF0000, 2, 2 ) leds.fill( 0x0000FF, (4...8) ) leds.fill { |i| 256 << i } Returns this PixelPi::Leds instance.
[ "Set", "the", "selected", "LEDs", "to", "the", "given", "color", ".", "The", "color", "msut", "be", "given", "as", "a", "24", "-", "bit", "RGB", "value", ".", "You", "can", "also", "supply", "a", "block", "that", "receives", "an", "LED", "index", "and", "returns", "a", "24", "-", "bit", "RGB", "color", "." ]
e0a63e337f378f48ecf4df20b2e55d87d84a2a5c
https://github.com/TwP/pixel_pi/blob/e0a63e337f378f48ecf4df20b2e55d87d84a2a5c/lib/pixel_pi/fake_leds.rb#L172-L184
4,037
dmacvicar/bicho
lib/bicho/query.rb
Bicho.Query.each
def each ret = Bicho.client.search_bugs(self) return ret.each unless block_given? ret.each { |bug| yield bug } end
ruby
def each ret = Bicho.client.search_bugs(self) return ret.each unless block_given? ret.each { |bug| yield bug } end
[ "def", "each", "ret", "=", "Bicho", ".", "client", ".", "search_bugs", "(", "self", ")", "return", "ret", ".", "each", "unless", "block_given?", "ret", ".", "each", "{", "|", "bug", "|", "yield", "bug", "}", "end" ]
Iterates through the result of the current query. @note Requires Bicho.client to be set @yield [Bicho::Bug]
[ "Iterates", "through", "the", "result", "of", "the", "current", "query", "." ]
fff403fcc5b1e1b6c81defd7c6434e9499aa1a63
https://github.com/dmacvicar/bicho/blob/fff403fcc5b1e1b6c81defd7c6434e9499aa1a63/lib/bicho/query.rb#L40-L44
4,038
dmacvicar/bicho
lib/bicho/query.rb
Bicho.Query.method_missing
def method_missing(method_name, *args) return super unless Bicho::SEARCH_FIELDS .map(&:first) .include?(method_name) args.each do |arg| append_query(method_name.to_s, arg) end self end
ruby
def method_missing(method_name, *args) return super unless Bicho::SEARCH_FIELDS .map(&:first) .include?(method_name) args.each do |arg| append_query(method_name.to_s, arg) end self end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ")", "return", "super", "unless", "Bicho", "::", "SEARCH_FIELDS", ".", "map", "(", ":first", ")", ".", "include?", "(", "method_name", ")", "args", ".", "each", "do", "|", "arg", "|", "append_query", "(", "method_name", ".", "to_s", ",", "arg", ")", "end", "self", "end" ]
Create a query. @example query from a hash containing the attributes: q = Query.new({:summary => "substring", :assigned_to => "[email protected]"}) @example using chainable methods: q = Query.new.assigned_to("[email protected]@).summary("some text") Query responds to all the bug search attributes. @see {Bug.where Allowed attributes}
[ "Create", "a", "query", "." ]
fff403fcc5b1e1b6c81defd7c6434e9499aa1a63
https://github.com/dmacvicar/bicho/blob/fff403fcc5b1e1b6c81defd7c6434e9499aa1a63/lib/bicho/query.rb#L65-L73
4,039
dmacvicar/bicho
lib/bicho/query.rb
Bicho.Query.append_query
def append_query(param, value) @query_map[param] = [] unless @query_map.key?(param) @query_map[param] = [@query_map[param], value].flatten end
ruby
def append_query(param, value) @query_map[param] = [] unless @query_map.key?(param) @query_map[param] = [@query_map[param], value].flatten end
[ "def", "append_query", "(", "param", ",", "value", ")", "@query_map", "[", "param", "]", "=", "[", "]", "unless", "@query_map", ".", "key?", "(", "param", ")", "@query_map", "[", "param", "]", "=", "[", "@query_map", "[", "param", "]", ",", "value", "]", ".", "flatten", "end" ]
Appends a parameter to the query map Only used internally. If the parameter already exists that parameter is converted to an array of values @private
[ "Appends", "a", "parameter", "to", "the", "query", "map" ]
fff403fcc5b1e1b6c81defd7c6434e9499aa1a63
https://github.com/dmacvicar/bicho/blob/fff403fcc5b1e1b6c81defd7c6434e9499aa1a63/lib/bicho/query.rb#L101-L104
4,040
davetron5000/moocow
lib/moocow/moocow.rb
RTM.RTMMethodSpace.method_missing
def method_missing(symbol,*args) if (@name == 'tasks' && symbol.to_s == 'notes') return RTMMethodSpace.new("tasks.notes",@endpoint) else rtm_method = "rtm.#{@name}.#{symbol.to_s.rtmize}" @endpoint.call_method(rtm_method,*args) end end
ruby
def method_missing(symbol,*args) if (@name == 'tasks' && symbol.to_s == 'notes') return RTMMethodSpace.new("tasks.notes",@endpoint) else rtm_method = "rtm.#{@name}.#{symbol.to_s.rtmize}" @endpoint.call_method(rtm_method,*args) end end
[ "def", "method_missing", "(", "symbol", ",", "*", "args", ")", "if", "(", "@name", "==", "'tasks'", "&&", "symbol", ".", "to_s", "==", "'notes'", ")", "return", "RTMMethodSpace", ".", "new", "(", "\"tasks.notes\"", ",", "@endpoint", ")", "else", "rtm_method", "=", "\"rtm.#{@name}.#{symbol.to_s.rtmize}\"", "@endpoint", ".", "call_method", "(", "rtm_method", ",", "args", ")", "end", "end" ]
Create an RTMMethodSpace [name] the name of this method space, e.g. 'tasks' [endpoint] an endpoing to RTM Calls the method on RTM in most cases. The only exception is if this RTMMethodSpace is 'tasks' and you call the 'notes' method on it: a new RTMMethodSpace is returned for the 'rtm.tasks.notes' method-space. This returns a response object as from HTTParty, dereferenced into <rsp>. So, for example, if you called the 'tasks.getList' method, you would get a hash that could be accessed via response['tasks']. This object is a Hash and Array structure that mimcs the XML returned by RTM. One quirk is that for methods that could return 1 or more of the same item (tasks.getList is a good example; it will return multilple <list> elements unless you restrict by list, in which case it returns only one <list> element). Because HTTParty doesn't understand this, you may find it convienient to convert such results to arrays. the to_array extension on Hash and Array accomplish this: response = rtm.tasks.getList(:filter => 'list:Work') response['tasks']['list'].as_array.each do |list| list['taskseries'].as_array.each do |task| puts task['name'] end end So, call to_array on anything you expect to be a list. This method raises either a BadResponseException if you got a bad or garbled response from RTM or a VerificationException if you got a non-OK response.
[ "Create", "an", "RTMMethodSpace" ]
92377d31d76728097fe505a5d0bf5dd7f034c9d5
https://github.com/davetron5000/moocow/blob/92377d31d76728097fe505a5d0bf5dd7f034c9d5/lib/moocow/moocow.rb#L124-L131
4,041
kojnapp/bitstamp
lib/bitstamp/model.rb
Bitstamp.Model.attributes=
def attributes=(attributes = {}) attributes.each do |name, value| begin send("#{name}=", value) rescue NoMethodError => e puts "Unable to assign #{name}. No such method." end end end
ruby
def attributes=(attributes = {}) attributes.each do |name, value| begin send("#{name}=", value) rescue NoMethodError => e puts "Unable to assign #{name}. No such method." end end end
[ "def", "attributes", "=", "(", "attributes", "=", "{", "}", ")", "attributes", ".", "each", "do", "|", "name", ",", "value", "|", "begin", "send", "(", "\"#{name}=\"", ",", "value", ")", "rescue", "NoMethodError", "=>", "e", "puts", "\"Unable to assign #{name}. No such method.\"", "end", "end", "end" ]
Set the attributes based on the given hash
[ "Set", "the", "attributes", "based", "on", "the", "given", "hash" ]
aa7460beb4fa7c412f2906c6ad7b0ad78026f579
https://github.com/kojnapp/bitstamp/blob/aa7460beb4fa7c412f2906c6ad7b0ad78026f579/lib/bitstamp/model.rb#L14-L22
4,042
rhenium/plum
lib/plum/client.rb
Plum.Client.start
def start(&block) raise IOError, "Session already started" if @started _start if block_given? begin ret = yield(self) resume return ret ensure close end end self end
ruby
def start(&block) raise IOError, "Session already started" if @started _start if block_given? begin ret = yield(self) resume return ret ensure close end end self end
[ "def", "start", "(", "&", "block", ")", "raise", "IOError", ",", "\"Session already started\"", "if", "@started", "_start", "if", "block_given?", "begin", "ret", "=", "yield", "(", "self", ")", "resume", "return", "ret", "ensure", "close", "end", "end", "self", "end" ]
Creates a new HTTP client. @param host [String | IO] the host to connect, or IO object. @param port [Integer] the port number to connect @param config [Hash<Symbol, Object>] the client configuration Starts communication. If block passed, waits for asynchronous requests and closes the connection after calling the block.
[ "Creates", "a", "new", "HTTP", "client", "." ]
9190801a092d46c7079ccee201b212b2d7985952
https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/client.rb#L43-L56
4,043
rhenium/plum
lib/plum/client.rb
Plum.Client.request
def request(headers, body, options = {}, &block) raise ArgumentError, ":method and :path headers are required" unless headers[":method"] && headers[":path"] @session.request(headers, body, @config.merge(options), &block) end
ruby
def request(headers, body, options = {}, &block) raise ArgumentError, ":method and :path headers are required" unless headers[":method"] && headers[":path"] @session.request(headers, body, @config.merge(options), &block) end
[ "def", "request", "(", "headers", ",", "body", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "ArgumentError", ",", "\":method and :path headers are required\"", "unless", "headers", "[", "\":method\"", "]", "&&", "headers", "[", "\":path\"", "]", "@session", ".", "request", "(", "headers", ",", "body", ",", "@config", ".", "merge", "(", "options", ")", ",", "block", ")", "end" ]
Creates a new HTTP request. @param headers [Hash<String, String>] the request headers @param body [String] the request body @param options [Hash<Symbol, Object>] request options @param block [Proc] if passed, it will be called when received response headers.
[ "Creates", "a", "new", "HTTP", "request", "." ]
9190801a092d46c7079ccee201b212b2d7985952
https://github.com/rhenium/plum/blob/9190801a092d46c7079ccee201b212b2d7985952/lib/plum/client.rb#L75-L78
4,044
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.open
def open file_name = File.join(@db_dir, 'database.blobs') new_db_created = false begin if File.exist?(file_name) @f = File.open(file_name, 'rb+') else PEROBS.log.info "New FlatFile database '#{file_name}' created" @f = File.open(file_name, 'wb+') new_db_created = true end rescue IOError => e PEROBS.log.fatal "Cannot open FlatFile database #{file_name}: " + e.message end unless @f.flock(File::LOCK_NB | File::LOCK_EX) PEROBS.log.fatal "FlatFile database '#{file_name}' is locked by " + "another process" end @f.sync = true open_index_files(!new_db_created) end
ruby
def open file_name = File.join(@db_dir, 'database.blobs') new_db_created = false begin if File.exist?(file_name) @f = File.open(file_name, 'rb+') else PEROBS.log.info "New FlatFile database '#{file_name}' created" @f = File.open(file_name, 'wb+') new_db_created = true end rescue IOError => e PEROBS.log.fatal "Cannot open FlatFile database #{file_name}: " + e.message end unless @f.flock(File::LOCK_NB | File::LOCK_EX) PEROBS.log.fatal "FlatFile database '#{file_name}' is locked by " + "another process" end @f.sync = true open_index_files(!new_db_created) end
[ "def", "open", "file_name", "=", "File", ".", "join", "(", "@db_dir", ",", "'database.blobs'", ")", "new_db_created", "=", "false", "begin", "if", "File", ".", "exist?", "(", "file_name", ")", "@f", "=", "File", ".", "open", "(", "file_name", ",", "'rb+'", ")", "else", "PEROBS", ".", "log", ".", "info", "\"New FlatFile database '#{file_name}' created\"", "@f", "=", "File", ".", "open", "(", "file_name", ",", "'wb+'", ")", "new_db_created", "=", "true", "end", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot open FlatFile database #{file_name}: \"", "+", "e", ".", "message", "end", "unless", "@f", ".", "flock", "(", "File", "::", "LOCK_NB", "|", "File", "::", "LOCK_EX", ")", "PEROBS", ".", "log", ".", "fatal", "\"FlatFile database '#{file_name}' is locked by \"", "+", "\"another process\"", "end", "@f", ".", "sync", "=", "true", "open_index_files", "(", "!", "new_db_created", ")", "end" ]
Create a new FlatFile object for a database in the given path. @param dir [String] Directory path for the data base file Open the flat file for reading and writing.
[ "Create", "a", "new", "FlatFile", "object", "for", "a", "database", "in", "the", "given", "path", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L58-L80
4,045
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.close
def close @space_list.close if @space_list.is_open? @index.close if @index.is_open? if @marks @marks.erase @marks = nil end if @f @f.flush @f.flock(File::LOCK_UN) @f.fsync @f.close @f = nil end end
ruby
def close @space_list.close if @space_list.is_open? @index.close if @index.is_open? if @marks @marks.erase @marks = nil end if @f @f.flush @f.flock(File::LOCK_UN) @f.fsync @f.close @f = nil end end
[ "def", "close", "@space_list", ".", "close", "if", "@space_list", ".", "is_open?", "@index", ".", "close", "if", "@index", ".", "is_open?", "if", "@marks", "@marks", ".", "erase", "@marks", "=", "nil", "end", "if", "@f", "@f", ".", "flush", "@f", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "@f", ".", "fsync", "@f", ".", "close", "@f", "=", "nil", "end", "end" ]
Close the flat file. This method must be called to ensure that all data is really written into the filesystem.
[ "Close", "the", "flat", "file", ".", "This", "method", "must", "be", "called", "to", "ensure", "that", "all", "data", "is", "really", "written", "into", "the", "filesystem", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L84-L100
4,046
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.sync
def sync begin @f.flush @f.fsync rescue IOError => e PEROBS.log.fatal "Cannot sync flat file database: #{e.message}" end @index.sync @space_list.sync end
ruby
def sync begin @f.flush @f.fsync rescue IOError => e PEROBS.log.fatal "Cannot sync flat file database: #{e.message}" end @index.sync @space_list.sync end
[ "def", "sync", "begin", "@f", ".", "flush", "@f", ".", "fsync", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot sync flat file database: #{e.message}\"", "end", "@index", ".", "sync", "@space_list", ".", "sync", "end" ]
Force outstanding data to be written to the filesystem.
[ "Force", "outstanding", "data", "to", "be", "written", "to", "the", "filesystem", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L103-L112
4,047
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.delete_obj_by_id
def delete_obj_by_id(id) if (pos = find_obj_addr_by_id(id)) delete_obj_by_address(pos, id) return true end return false end
ruby
def delete_obj_by_id(id) if (pos = find_obj_addr_by_id(id)) delete_obj_by_address(pos, id) return true end return false end
[ "def", "delete_obj_by_id", "(", "id", ")", "if", "(", "pos", "=", "find_obj_addr_by_id", "(", "id", ")", ")", "delete_obj_by_address", "(", "pos", ",", "id", ")", "return", "true", "end", "return", "false", "end" ]
Delete the blob for the specified ID. @param id [Integer] ID of the object to be deleted @return [Boolean] True if object was deleted, false otherwise
[ "Delete", "the", "blob", "for", "the", "specified", "ID", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L117-L124
4,048
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.delete_obj_by_address
def delete_obj_by_address(addr, id) @index.remove(id) if @index.is_open? header = FlatFileBlobHeader.read(@f, addr, id) header.clear_flags @space_list.add_space(addr, header.length) if @space_list.is_open? end
ruby
def delete_obj_by_address(addr, id) @index.remove(id) if @index.is_open? header = FlatFileBlobHeader.read(@f, addr, id) header.clear_flags @space_list.add_space(addr, header.length) if @space_list.is_open? end
[ "def", "delete_obj_by_address", "(", "addr", ",", "id", ")", "@index", ".", "remove", "(", "id", ")", "if", "@index", ".", "is_open?", "header", "=", "FlatFileBlobHeader", ".", "read", "(", "@f", ",", "addr", ",", "id", ")", "header", ".", "clear_flags", "@space_list", ".", "add_space", "(", "addr", ",", "header", ".", "length", ")", "if", "@space_list", ".", "is_open?", "end" ]
Delete the blob that is stored at the specified address. @param addr [Integer] Address of the blob to delete @param id [Integer] ID of the blob to delete
[ "Delete", "the", "blob", "that", "is", "stored", "at", "the", "specified", "address", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L129-L134
4,049
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.delete_unmarked_objects
def delete_unmarked_objects # We don't update the index and the space list during this operation as # we defragmentize the blob file at the end. We'll end the operation # with an empty space list. clear_index_files deleted_objects_count = 0 @progressmeter.start('Sweeping unmarked objects', @f.size) do |pm| each_blob_header do |header| if header.is_valid? && [email protected]?(header.id) delete_obj_by_address(header.addr, header.id) deleted_objects_count += 1 end pm.update(header.addr) end end defragmentize # Update the index file and create a new, empty space list. regenerate_index_and_spaces deleted_objects_count end
ruby
def delete_unmarked_objects # We don't update the index and the space list during this operation as # we defragmentize the blob file at the end. We'll end the operation # with an empty space list. clear_index_files deleted_objects_count = 0 @progressmeter.start('Sweeping unmarked objects', @f.size) do |pm| each_blob_header do |header| if header.is_valid? && [email protected]?(header.id) delete_obj_by_address(header.addr, header.id) deleted_objects_count += 1 end pm.update(header.addr) end end defragmentize # Update the index file and create a new, empty space list. regenerate_index_and_spaces deleted_objects_count end
[ "def", "delete_unmarked_objects", "# We don't update the index and the space list during this operation as", "# we defragmentize the blob file at the end. We'll end the operation", "# with an empty space list.", "clear_index_files", "deleted_objects_count", "=", "0", "@progressmeter", ".", "start", "(", "'Sweeping unmarked objects'", ",", "@f", ".", "size", ")", "do", "|", "pm", "|", "each_blob_header", "do", "|", "header", "|", "if", "header", ".", "is_valid?", "&&", "!", "@marks", ".", "include?", "(", "header", ".", "id", ")", "delete_obj_by_address", "(", "header", ".", "addr", ",", "header", ".", "id", ")", "deleted_objects_count", "+=", "1", "end", "pm", ".", "update", "(", "header", ".", "addr", ")", "end", "end", "defragmentize", "# Update the index file and create a new, empty space list.", "regenerate_index_and_spaces", "deleted_objects_count", "end" ]
Delete all unmarked objects.
[ "Delete", "all", "unmarked", "objects", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L137-L160
4,050
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.write_obj_by_id
def write_obj_by_id(id, raw_obj) # Check if we have already an object with the given ID. We'll mark it as # outdated and save the header for later deletion. In case this # operation is aborted or interrupted we ensure that we either have the # old or the new version available. if (old_addr = find_obj_addr_by_id(id)) old_header = FlatFileBlobHeader.read(@f, old_addr) old_header.set_outdated_flag end crc = checksum(raw_obj) # If the raw_obj is larger then 256 characters we will compress it to # safe some space in the database file. For smaller strings the # performance impact of compression is not compensated by writing # less data to the storage. compressed = false if raw_obj.bytesize > 256 raw_obj = Zlib.deflate(raw_obj) compressed = true end addr, length = find_free_blob(raw_obj.bytesize) begin if length != -1 # Just a safeguard so we don't overwrite current data. header = FlatFileBlobHeader.read(@f, addr) if header.length != length PEROBS.log.fatal "Length in free list (#{length}) and header " + "(#{header.length}) for address #{addr} don't match." end if raw_obj.bytesize > header.length PEROBS.log.fatal "Object (#{raw_obj.bytesize}) is longer than " + "blob space (#{header.length})." end if header.is_valid? PEROBS.log.fatal "Entry at address #{addr} with flags: " + "#{header.flags} is already used for ID #{header.id}." end end flags = 1 << FlatFileBlobHeader::VALID_FLAG_BIT flags |= (1 << FlatFileBlobHeader::COMPRESSED_FLAG_BIT) if compressed FlatFileBlobHeader.new(@f, addr, flags, raw_obj.bytesize, id, crc).write @f.write(raw_obj) if length != -1 && raw_obj.bytesize < length # The new object was not appended and it did not completely fill the # free space. So we have to write a new header to mark the remaining # empty space. unless length - raw_obj.bytesize >= FlatFileBlobHeader::LENGTH PEROBS.log.fatal "Not enough space to append the empty space " + "header (space: #{length} bytes, object: #{raw_obj.bytesize} " + "bytes)." end space_address = @f.pos space_length = length - FlatFileBlobHeader::LENGTH - raw_obj.bytesize FlatFileBlobHeader.new(@f, space_address, 0, space_length, 0, 0).write # Register the new space with the space list. if @space_list.is_open? && space_length > 0 @space_list.add_space(space_address, space_length) end end # Once the blob has been written we can update the index as well. @index.insert(id, addr) if @index.is_open? if old_addr # If we had an existing object stored for the ID we have to mark # this entry as deleted now. old_header.clear_flags # And register the newly freed space with the space list. if @space_list.is_open? @space_list.add_space(old_addr, old_header.length) end else @f.flush end rescue IOError => e PEROBS.log.fatal "Cannot write blob for ID #{id} to FlatFileDB: " + e.message end addr end
ruby
def write_obj_by_id(id, raw_obj) # Check if we have already an object with the given ID. We'll mark it as # outdated and save the header for later deletion. In case this # operation is aborted or interrupted we ensure that we either have the # old or the new version available. if (old_addr = find_obj_addr_by_id(id)) old_header = FlatFileBlobHeader.read(@f, old_addr) old_header.set_outdated_flag end crc = checksum(raw_obj) # If the raw_obj is larger then 256 characters we will compress it to # safe some space in the database file. For smaller strings the # performance impact of compression is not compensated by writing # less data to the storage. compressed = false if raw_obj.bytesize > 256 raw_obj = Zlib.deflate(raw_obj) compressed = true end addr, length = find_free_blob(raw_obj.bytesize) begin if length != -1 # Just a safeguard so we don't overwrite current data. header = FlatFileBlobHeader.read(@f, addr) if header.length != length PEROBS.log.fatal "Length in free list (#{length}) and header " + "(#{header.length}) for address #{addr} don't match." end if raw_obj.bytesize > header.length PEROBS.log.fatal "Object (#{raw_obj.bytesize}) is longer than " + "blob space (#{header.length})." end if header.is_valid? PEROBS.log.fatal "Entry at address #{addr} with flags: " + "#{header.flags} is already used for ID #{header.id}." end end flags = 1 << FlatFileBlobHeader::VALID_FLAG_BIT flags |= (1 << FlatFileBlobHeader::COMPRESSED_FLAG_BIT) if compressed FlatFileBlobHeader.new(@f, addr, flags, raw_obj.bytesize, id, crc).write @f.write(raw_obj) if length != -1 && raw_obj.bytesize < length # The new object was not appended and it did not completely fill the # free space. So we have to write a new header to mark the remaining # empty space. unless length - raw_obj.bytesize >= FlatFileBlobHeader::LENGTH PEROBS.log.fatal "Not enough space to append the empty space " + "header (space: #{length} bytes, object: #{raw_obj.bytesize} " + "bytes)." end space_address = @f.pos space_length = length - FlatFileBlobHeader::LENGTH - raw_obj.bytesize FlatFileBlobHeader.new(@f, space_address, 0, space_length, 0, 0).write # Register the new space with the space list. if @space_list.is_open? && space_length > 0 @space_list.add_space(space_address, space_length) end end # Once the blob has been written we can update the index as well. @index.insert(id, addr) if @index.is_open? if old_addr # If we had an existing object stored for the ID we have to mark # this entry as deleted now. old_header.clear_flags # And register the newly freed space with the space list. if @space_list.is_open? @space_list.add_space(old_addr, old_header.length) end else @f.flush end rescue IOError => e PEROBS.log.fatal "Cannot write blob for ID #{id} to FlatFileDB: " + e.message end addr end
[ "def", "write_obj_by_id", "(", "id", ",", "raw_obj", ")", "# Check if we have already an object with the given ID. We'll mark it as", "# outdated and save the header for later deletion. In case this", "# operation is aborted or interrupted we ensure that we either have the", "# old or the new version available.", "if", "(", "old_addr", "=", "find_obj_addr_by_id", "(", "id", ")", ")", "old_header", "=", "FlatFileBlobHeader", ".", "read", "(", "@f", ",", "old_addr", ")", "old_header", ".", "set_outdated_flag", "end", "crc", "=", "checksum", "(", "raw_obj", ")", "# If the raw_obj is larger then 256 characters we will compress it to", "# safe some space in the database file. For smaller strings the", "# performance impact of compression is not compensated by writing", "# less data to the storage.", "compressed", "=", "false", "if", "raw_obj", ".", "bytesize", ">", "256", "raw_obj", "=", "Zlib", ".", "deflate", "(", "raw_obj", ")", "compressed", "=", "true", "end", "addr", ",", "length", "=", "find_free_blob", "(", "raw_obj", ".", "bytesize", ")", "begin", "if", "length", "!=", "-", "1", "# Just a safeguard so we don't overwrite current data.", "header", "=", "FlatFileBlobHeader", ".", "read", "(", "@f", ",", "addr", ")", "if", "header", ".", "length", "!=", "length", "PEROBS", ".", "log", ".", "fatal", "\"Length in free list (#{length}) and header \"", "+", "\"(#{header.length}) for address #{addr} don't match.\"", "end", "if", "raw_obj", ".", "bytesize", ">", "header", ".", "length", "PEROBS", ".", "log", ".", "fatal", "\"Object (#{raw_obj.bytesize}) is longer than \"", "+", "\"blob space (#{header.length}).\"", "end", "if", "header", ".", "is_valid?", "PEROBS", ".", "log", ".", "fatal", "\"Entry at address #{addr} with flags: \"", "+", "\"#{header.flags} is already used for ID #{header.id}.\"", "end", "end", "flags", "=", "1", "<<", "FlatFileBlobHeader", "::", "VALID_FLAG_BIT", "flags", "|=", "(", "1", "<<", "FlatFileBlobHeader", "::", "COMPRESSED_FLAG_BIT", ")", "if", "compressed", "FlatFileBlobHeader", ".", "new", "(", "@f", ",", "addr", ",", "flags", ",", "raw_obj", ".", "bytesize", ",", "id", ",", "crc", ")", ".", "write", "@f", ".", "write", "(", "raw_obj", ")", "if", "length", "!=", "-", "1", "&&", "raw_obj", ".", "bytesize", "<", "length", "# The new object was not appended and it did not completely fill the", "# free space. So we have to write a new header to mark the remaining", "# empty space.", "unless", "length", "-", "raw_obj", ".", "bytesize", ">=", "FlatFileBlobHeader", "::", "LENGTH", "PEROBS", ".", "log", ".", "fatal", "\"Not enough space to append the empty space \"", "+", "\"header (space: #{length} bytes, object: #{raw_obj.bytesize} \"", "+", "\"bytes).\"", "end", "space_address", "=", "@f", ".", "pos", "space_length", "=", "length", "-", "FlatFileBlobHeader", "::", "LENGTH", "-", "raw_obj", ".", "bytesize", "FlatFileBlobHeader", ".", "new", "(", "@f", ",", "space_address", ",", "0", ",", "space_length", ",", "0", ",", "0", ")", ".", "write", "# Register the new space with the space list.", "if", "@space_list", ".", "is_open?", "&&", "space_length", ">", "0", "@space_list", ".", "add_space", "(", "space_address", ",", "space_length", ")", "end", "end", "# Once the blob has been written we can update the index as well.", "@index", ".", "insert", "(", "id", ",", "addr", ")", "if", "@index", ".", "is_open?", "if", "old_addr", "# If we had an existing object stored for the ID we have to mark", "# this entry as deleted now.", "old_header", ".", "clear_flags", "# And register the newly freed space with the space list.", "if", "@space_list", ".", "is_open?", "@space_list", ".", "add_space", "(", "old_addr", ",", "old_header", ".", "length", ")", "end", "else", "@f", ".", "flush", "end", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot write blob for ID #{id} to FlatFileDB: \"", "+", "e", ".", "message", "end", "addr", "end" ]
Write the given object into the file. This method never uses in-place updates for existing objects. A new copy is inserted first and only when the insert was successful, the old copy is deleted and the index updated. @param id [Integer] ID of the object @param raw_obj [String] Raw object as String @return [Integer] position of the written blob in the blob file
[ "Write", "the", "given", "object", "into", "the", "file", ".", "This", "method", "never", "uses", "in", "-", "place", "updates", "for", "existing", "objects", ".", "A", "new", "copy", "is", "inserted", "first", "and", "only", "when", "the", "insert", "was", "successful", "the", "old", "copy", "is", "deleted", "and", "the", "index", "updated", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L169-L252
4,051
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.read_obj_by_address
def read_obj_by_address(addr, id) header = FlatFileBlobHeader.read(@f, addr, id) if header.id != id PEROBS.log.fatal "Database index corrupted: Index for object " + "#{id} points to object with ID #{header.id}" end buf = nil begin @f.seek(addr + FlatFileBlobHeader::LENGTH) buf = @f.read(header.length) rescue IOError => e PEROBS.log.fatal "Cannot read blob for ID #{id}: #{e.message}" end # Uncompress the data if the compression bit is set in the flags byte. if header.is_compressed? begin buf = Zlib.inflate(buf) rescue Zlib::BufError, Zlib::DataError PEROBS.log.fatal "Corrupted compressed block with ID " + "#{header.id} found." end end if checksum(buf) != header.crc PEROBS.log.fatal "Checksum failure while reading blob ID #{id}" end buf end
ruby
def read_obj_by_address(addr, id) header = FlatFileBlobHeader.read(@f, addr, id) if header.id != id PEROBS.log.fatal "Database index corrupted: Index for object " + "#{id} points to object with ID #{header.id}" end buf = nil begin @f.seek(addr + FlatFileBlobHeader::LENGTH) buf = @f.read(header.length) rescue IOError => e PEROBS.log.fatal "Cannot read blob for ID #{id}: #{e.message}" end # Uncompress the data if the compression bit is set in the flags byte. if header.is_compressed? begin buf = Zlib.inflate(buf) rescue Zlib::BufError, Zlib::DataError PEROBS.log.fatal "Corrupted compressed block with ID " + "#{header.id} found." end end if checksum(buf) != header.crc PEROBS.log.fatal "Checksum failure while reading blob ID #{id}" end buf end
[ "def", "read_obj_by_address", "(", "addr", ",", "id", ")", "header", "=", "FlatFileBlobHeader", ".", "read", "(", "@f", ",", "addr", ",", "id", ")", "if", "header", ".", "id", "!=", "id", "PEROBS", ".", "log", ".", "fatal", "\"Database index corrupted: Index for object \"", "+", "\"#{id} points to object with ID #{header.id}\"", "end", "buf", "=", "nil", "begin", "@f", ".", "seek", "(", "addr", "+", "FlatFileBlobHeader", "::", "LENGTH", ")", "buf", "=", "@f", ".", "read", "(", "header", ".", "length", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot read blob for ID #{id}: #{e.message}\"", "end", "# Uncompress the data if the compression bit is set in the flags byte.", "if", "header", ".", "is_compressed?", "begin", "buf", "=", "Zlib", ".", "inflate", "(", "buf", ")", "rescue", "Zlib", "::", "BufError", ",", "Zlib", "::", "DataError", "PEROBS", ".", "log", ".", "fatal", "\"Corrupted compressed block with ID \"", "+", "\"#{header.id} found.\"", "end", "end", "if", "checksum", "(", "buf", ")", "!=", "header", ".", "crc", "PEROBS", ".", "log", ".", "fatal", "\"Checksum failure while reading blob ID #{id}\"", "end", "buf", "end" ]
Read the object at the specified address. @param addr [Integer] Offset in the flat file @param id [Integer] ID of the data blob @return [String] Raw object data
[ "Read", "the", "object", "at", "the", "specified", "address", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L281-L312
4,052
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.defragmentize
def defragmentize distance = 0 new_file_size = 0 deleted_blobs = 0 corrupted_blobs = 0 valid_blobs = 0 # Iterate over all entries. @progressmeter.start('Defragmentizing blobs file', @f.size) do |pm| each_blob_header do |header| # If we have stumbled over a corrupted blob we treat it similar to a # deleted blob and reuse the space. if header.corruption_start distance += header.addr - header.corruption_start corrupted_blobs += 1 end # Total size of the current entry entry_bytes = FlatFileBlobHeader::LENGTH + header.length if header.is_valid? # We have found a valid entry. valid_blobs += 1 if distance > 0 begin # Read current entry into a buffer @f.seek(header.addr) buf = @f.read(entry_bytes) # Write the buffer right after the end of the previous entry. @f.seek(header.addr - distance) @f.write(buf) # Mark the space between the relocated current entry and the # next valid entry as deleted space. FlatFileBlobHeader.new(@f, @f.pos, 0, distance - FlatFileBlobHeader::LENGTH, 0, 0).write @f.flush rescue IOError => e PEROBS.log.fatal "Error while moving blob for ID " + "#{header.id}: #{e.message}" end end new_file_size = header.addr - distance + FlatFileBlobHeader::LENGTH + header.length else deleted_blobs += 1 distance += entry_bytes end pm.update(header.addr) end end PEROBS.log.info "#{distance / 1000} KiB/#{deleted_blobs} blobs of " + "#{@f.size / 1000} KiB/#{valid_blobs} blobs or " + "#{'%.1f' % (distance.to_f / @f.size * 100.0)}% reclaimed" if corrupted_blobs > 0 PEROBS.log.info "#{corrupted_blobs} corrupted blob(s) found. Space " + "was recycled." end @f.flush @f.truncate(new_file_size) @f.flush sync end
ruby
def defragmentize distance = 0 new_file_size = 0 deleted_blobs = 0 corrupted_blobs = 0 valid_blobs = 0 # Iterate over all entries. @progressmeter.start('Defragmentizing blobs file', @f.size) do |pm| each_blob_header do |header| # If we have stumbled over a corrupted blob we treat it similar to a # deleted blob and reuse the space. if header.corruption_start distance += header.addr - header.corruption_start corrupted_blobs += 1 end # Total size of the current entry entry_bytes = FlatFileBlobHeader::LENGTH + header.length if header.is_valid? # We have found a valid entry. valid_blobs += 1 if distance > 0 begin # Read current entry into a buffer @f.seek(header.addr) buf = @f.read(entry_bytes) # Write the buffer right after the end of the previous entry. @f.seek(header.addr - distance) @f.write(buf) # Mark the space between the relocated current entry and the # next valid entry as deleted space. FlatFileBlobHeader.new(@f, @f.pos, 0, distance - FlatFileBlobHeader::LENGTH, 0, 0).write @f.flush rescue IOError => e PEROBS.log.fatal "Error while moving blob for ID " + "#{header.id}: #{e.message}" end end new_file_size = header.addr - distance + FlatFileBlobHeader::LENGTH + header.length else deleted_blobs += 1 distance += entry_bytes end pm.update(header.addr) end end PEROBS.log.info "#{distance / 1000} KiB/#{deleted_blobs} blobs of " + "#{@f.size / 1000} KiB/#{valid_blobs} blobs or " + "#{'%.1f' % (distance.to_f / @f.size * 100.0)}% reclaimed" if corrupted_blobs > 0 PEROBS.log.info "#{corrupted_blobs} corrupted blob(s) found. Space " + "was recycled." end @f.flush @f.truncate(new_file_size) @f.flush sync end
[ "def", "defragmentize", "distance", "=", "0", "new_file_size", "=", "0", "deleted_blobs", "=", "0", "corrupted_blobs", "=", "0", "valid_blobs", "=", "0", "# Iterate over all entries.", "@progressmeter", ".", "start", "(", "'Defragmentizing blobs file'", ",", "@f", ".", "size", ")", "do", "|", "pm", "|", "each_blob_header", "do", "|", "header", "|", "# If we have stumbled over a corrupted blob we treat it similar to a", "# deleted blob and reuse the space.", "if", "header", ".", "corruption_start", "distance", "+=", "header", ".", "addr", "-", "header", ".", "corruption_start", "corrupted_blobs", "+=", "1", "end", "# Total size of the current entry", "entry_bytes", "=", "FlatFileBlobHeader", "::", "LENGTH", "+", "header", ".", "length", "if", "header", ".", "is_valid?", "# We have found a valid entry.", "valid_blobs", "+=", "1", "if", "distance", ">", "0", "begin", "# Read current entry into a buffer", "@f", ".", "seek", "(", "header", ".", "addr", ")", "buf", "=", "@f", ".", "read", "(", "entry_bytes", ")", "# Write the buffer right after the end of the previous entry.", "@f", ".", "seek", "(", "header", ".", "addr", "-", "distance", ")", "@f", ".", "write", "(", "buf", ")", "# Mark the space between the relocated current entry and the", "# next valid entry as deleted space.", "FlatFileBlobHeader", ".", "new", "(", "@f", ",", "@f", ".", "pos", ",", "0", ",", "distance", "-", "FlatFileBlobHeader", "::", "LENGTH", ",", "0", ",", "0", ")", ".", "write", "@f", ".", "flush", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Error while moving blob for ID \"", "+", "\"#{header.id}: #{e.message}\"", "end", "end", "new_file_size", "=", "header", ".", "addr", "-", "distance", "+", "FlatFileBlobHeader", "::", "LENGTH", "+", "header", ".", "length", "else", "deleted_blobs", "+=", "1", "distance", "+=", "entry_bytes", "end", "pm", ".", "update", "(", "header", ".", "addr", ")", "end", "end", "PEROBS", ".", "log", ".", "info", "\"#{distance / 1000} KiB/#{deleted_blobs} blobs of \"", "+", "\"#{@f.size / 1000} KiB/#{valid_blobs} blobs or \"", "+", "\"#{'%.1f' % (distance.to_f / @f.size * 100.0)}% reclaimed\"", "if", "corrupted_blobs", ">", "0", "PEROBS", ".", "log", ".", "info", "\"#{corrupted_blobs} corrupted blob(s) found. Space \"", "+", "\"was recycled.\"", "end", "@f", ".", "flush", "@f", ".", "truncate", "(", "new_file_size", ")", "@f", ".", "flush", "sync", "end" ]
Eliminate all the holes in the file. This is an in-place implementation. No additional space will be needed on the file system.
[ "Eliminate", "all", "the", "holes", "in", "the", "file", ".", "This", "is", "an", "in", "-", "place", "implementation", ".", "No", "additional", "space", "will", "be", "needed", "on", "the", "file", "system", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L337-L402
4,053
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.refresh
def refresh # This iteration might look scary as we iterate over the entries while # while we are rearranging them. Re-inserted items may be inserted # before or at the current entry and this is fine. They also may be # inserted after the current entry and will be re-read again unless they # are inserted after the original file end. file_size = @f.size # We don't update the index and the space list during this operation as # we defragmentize the blob file at the end. We'll end the operation # with an empty space list. clear_index_files @progressmeter.start('Converting objects to new storage format', @f.size) do |pm| each_blob_header do |header| if header.is_valid? buf = read_obj_by_address(header.addr, header.id) delete_obj_by_address(header.addr, header.id) write_obj_by_id(header.id, buf) end # Some re-inserted blobs may be inserted after the original file end. # No need to process those blobs again. break if header.addr >= file_size pm.update(header.addr) end end # Reclaim the space saved by compressing entries. defragmentize # Recreate the index file and create an empty space list. regenerate_index_and_spaces end
ruby
def refresh # This iteration might look scary as we iterate over the entries while # while we are rearranging them. Re-inserted items may be inserted # before or at the current entry and this is fine. They also may be # inserted after the current entry and will be re-read again unless they # are inserted after the original file end. file_size = @f.size # We don't update the index and the space list during this operation as # we defragmentize the blob file at the end. We'll end the operation # with an empty space list. clear_index_files @progressmeter.start('Converting objects to new storage format', @f.size) do |pm| each_blob_header do |header| if header.is_valid? buf = read_obj_by_address(header.addr, header.id) delete_obj_by_address(header.addr, header.id) write_obj_by_id(header.id, buf) end # Some re-inserted blobs may be inserted after the original file end. # No need to process those blobs again. break if header.addr >= file_size pm.update(header.addr) end end # Reclaim the space saved by compressing entries. defragmentize # Recreate the index file and create an empty space list. regenerate_index_and_spaces end
[ "def", "refresh", "# This iteration might look scary as we iterate over the entries while", "# while we are rearranging them. Re-inserted items may be inserted", "# before or at the current entry and this is fine. They also may be", "# inserted after the current entry and will be re-read again unless they", "# are inserted after the original file end.", "file_size", "=", "@f", ".", "size", "# We don't update the index and the space list during this operation as", "# we defragmentize the blob file at the end. We'll end the operation", "# with an empty space list.", "clear_index_files", "@progressmeter", ".", "start", "(", "'Converting objects to new storage format'", ",", "@f", ".", "size", ")", "do", "|", "pm", "|", "each_blob_header", "do", "|", "header", "|", "if", "header", ".", "is_valid?", "buf", "=", "read_obj_by_address", "(", "header", ".", "addr", ",", "header", ".", "id", ")", "delete_obj_by_address", "(", "header", ".", "addr", ",", "header", ".", "id", ")", "write_obj_by_id", "(", "header", ".", "id", ",", "buf", ")", "end", "# Some re-inserted blobs may be inserted after the original file end.", "# No need to process those blobs again.", "break", "if", "header", ".", "addr", ">=", "file_size", "pm", ".", "update", "(", "header", ".", "addr", ")", "end", "end", "# Reclaim the space saved by compressing entries.", "defragmentize", "# Recreate the index file and create an empty space list.", "regenerate_index_and_spaces", "end" ]
This method iterates over all entries in the FlatFile and removes the entry and inserts it again. This is useful to update all entries in case the storage format has changed.
[ "This", "method", "iterates", "over", "all", "entries", "in", "the", "FlatFile", "and", "removes", "the", "entry", "and", "inserts", "it", "again", ".", "This", "is", "useful", "to", "update", "all", "entries", "in", "case", "the", "storage", "format", "has", "changed", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L407-L442
4,054
scrapper/perobs
lib/perobs/FlatFile.rb
PEROBS.FlatFile.regenerate_index_and_spaces
def regenerate_index_and_spaces PEROBS.log.warn "Re-generating FlatFileDB index and space files" @index.open unless @index.is_open? @index.clear @space_list.open unless @space_list.is_open? @space_list.clear @progressmeter.start('Re-generating database index', @f.size) do |pm| each_blob_header do |header| if header.is_valid? if (duplicate_pos = @index.get(header.id)) PEROBS.log.error "FlatFile contains multiple blobs for ID " + "#{header.id}. First blob is at address #{duplicate_pos}. " + "Other blob found at address #{header.addr}." if header.length > 0 @space_list.add_space(header.addr, header.length) end discard_damaged_blob(header) else @index.insert(header.id, header.addr) end else if header.length > 0 @space_list.add_space(header.addr, header.length) end end pm.update(header.addr) end end sync end
ruby
def regenerate_index_and_spaces PEROBS.log.warn "Re-generating FlatFileDB index and space files" @index.open unless @index.is_open? @index.clear @space_list.open unless @space_list.is_open? @space_list.clear @progressmeter.start('Re-generating database index', @f.size) do |pm| each_blob_header do |header| if header.is_valid? if (duplicate_pos = @index.get(header.id)) PEROBS.log.error "FlatFile contains multiple blobs for ID " + "#{header.id}. First blob is at address #{duplicate_pos}. " + "Other blob found at address #{header.addr}." if header.length > 0 @space_list.add_space(header.addr, header.length) end discard_damaged_blob(header) else @index.insert(header.id, header.addr) end else if header.length > 0 @space_list.add_space(header.addr, header.length) end end pm.update(header.addr) end end sync end
[ "def", "regenerate_index_and_spaces", "PEROBS", ".", "log", ".", "warn", "\"Re-generating FlatFileDB index and space files\"", "@index", ".", "open", "unless", "@index", ".", "is_open?", "@index", ".", "clear", "@space_list", ".", "open", "unless", "@space_list", ".", "is_open?", "@space_list", ".", "clear", "@progressmeter", ".", "start", "(", "'Re-generating database index'", ",", "@f", ".", "size", ")", "do", "|", "pm", "|", "each_blob_header", "do", "|", "header", "|", "if", "header", ".", "is_valid?", "if", "(", "duplicate_pos", "=", "@index", ".", "get", "(", "header", ".", "id", ")", ")", "PEROBS", ".", "log", ".", "error", "\"FlatFile contains multiple blobs for ID \"", "+", "\"#{header.id}. First blob is at address #{duplicate_pos}. \"", "+", "\"Other blob found at address #{header.addr}.\"", "if", "header", ".", "length", ">", "0", "@space_list", ".", "add_space", "(", "header", ".", "addr", ",", "header", ".", "length", ")", "end", "discard_damaged_blob", "(", "header", ")", "else", "@index", ".", "insert", "(", "header", ".", "id", ",", "header", ".", "addr", ")", "end", "else", "if", "header", ".", "length", ">", "0", "@space_list", ".", "add_space", "(", "header", ".", "addr", ",", "header", ".", "length", ")", "end", "end", "pm", ".", "update", "(", "header", ".", "addr", ")", "end", "end", "sync", "end" ]
This method clears the index tree and the free space list and regenerates them from the FlatFile.
[ "This", "method", "clears", "the", "index", "tree", "and", "the", "free", "space", "list", "and", "regenerates", "them", "from", "the", "FlatFile", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFile.rb#L580-L612
4,055
notonthehighstreet/chicago
lib/chicago/rake_tasks.rb
Chicago.RakeTasks.define
def define namespace :db do desc "Write Null dimension records" task :create_null_records do # TODO: replace this with proper logging. warn "Loading NULL records." @schema.dimensions.each do |dimension| dimension.create_null_records(@staging_db) end end desc "Writes a migration file to change the database based on defined Facts & Dimensions" task :write_migrations do writer = Database::MigrationFileWriter.new writer.write_migration_file(@staging_db, @schema, staging_directory) if @presentation_db writer.write_migration_file(@presentation_db, @schema, presentation_directory, false) end end end end
ruby
def define namespace :db do desc "Write Null dimension records" task :create_null_records do # TODO: replace this with proper logging. warn "Loading NULL records." @schema.dimensions.each do |dimension| dimension.create_null_records(@staging_db) end end desc "Writes a migration file to change the database based on defined Facts & Dimensions" task :write_migrations do writer = Database::MigrationFileWriter.new writer.write_migration_file(@staging_db, @schema, staging_directory) if @presentation_db writer.write_migration_file(@presentation_db, @schema, presentation_directory, false) end end end end
[ "def", "define", "namespace", ":db", "do", "desc", "\"Write Null dimension records\"", "task", ":create_null_records", "do", "# TODO: replace this with proper logging.", "warn", "\"Loading NULL records.\"", "@schema", ".", "dimensions", ".", "each", "do", "|", "dimension", "|", "dimension", ".", "create_null_records", "(", "@staging_db", ")", "end", "end", "desc", "\"Writes a migration file to change the database based on defined Facts & Dimensions\"", "task", ":write_migrations", "do", "writer", "=", "Database", "::", "MigrationFileWriter", ".", "new", "writer", ".", "write_migration_file", "(", "@staging_db", ",", "@schema", ",", "staging_directory", ")", "if", "@presentation_db", "writer", ".", "write_migration_file", "(", "@presentation_db", ",", "@schema", ",", "presentation_directory", ",", "false", ")", "end", "end", "end", "end" ]
Defines the rake tasks. @api private
[ "Defines", "the", "rake", "tasks", "." ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/rake_tasks.rb#L35-L58
4,056
scrapper/perobs
lib/perobs/LockFile.rb
PEROBS.LockFile.lock
def lock retries = @max_retries while retries > 0 begin @file = File.open(@file_name, File::RDWR | File::CREAT, 0644) @file.sync = true if @file.flock(File::LOCK_EX | File::LOCK_NB) # We have taken the lock. Write the PID into the file and leave it # open. @file.write($$) @file.flush @file.fsync @file.truncate(@file.pos) PEROBS.log.debug "Lock file #{@file_name} has been taken for " + "process #{$$}" return true else # We did not manage to take the lock file. if @file.mtime <= Time.now - @timeout_secs pid = @file.read.to_i PEROBS.log.info "Old lock file found for PID #{pid}. " + "Removing lock." if is_running?(pid) send_signal('TERM', pid) # Give the process 3 seconds to terminate gracefully. sleep 3 # Then send a SIGKILL to ensure it's gone. send_signal('KILL', pid) if is_running?(pid) end @file.close File.delete(@file_name) if File.exist?(@file_name) else PEROBS.log.debug "Lock file #{@file_name} is taken. Trying " + "to get it #{retries} more times." end end rescue => e PEROBS.log.error "Cannot take lock file #{@file_name}: #{e.message}" return false end retries -= 1 sleep(@pause_secs) end PEROBS.log.info "Failed to get lock file #{@file_name} due to timeout" false end
ruby
def lock retries = @max_retries while retries > 0 begin @file = File.open(@file_name, File::RDWR | File::CREAT, 0644) @file.sync = true if @file.flock(File::LOCK_EX | File::LOCK_NB) # We have taken the lock. Write the PID into the file and leave it # open. @file.write($$) @file.flush @file.fsync @file.truncate(@file.pos) PEROBS.log.debug "Lock file #{@file_name} has been taken for " + "process #{$$}" return true else # We did not manage to take the lock file. if @file.mtime <= Time.now - @timeout_secs pid = @file.read.to_i PEROBS.log.info "Old lock file found for PID #{pid}. " + "Removing lock." if is_running?(pid) send_signal('TERM', pid) # Give the process 3 seconds to terminate gracefully. sleep 3 # Then send a SIGKILL to ensure it's gone. send_signal('KILL', pid) if is_running?(pid) end @file.close File.delete(@file_name) if File.exist?(@file_name) else PEROBS.log.debug "Lock file #{@file_name} is taken. Trying " + "to get it #{retries} more times." end end rescue => e PEROBS.log.error "Cannot take lock file #{@file_name}: #{e.message}" return false end retries -= 1 sleep(@pause_secs) end PEROBS.log.info "Failed to get lock file #{@file_name} due to timeout" false end
[ "def", "lock", "retries", "=", "@max_retries", "while", "retries", ">", "0", "begin", "@file", "=", "File", ".", "open", "(", "@file_name", ",", "File", "::", "RDWR", "|", "File", "::", "CREAT", ",", "0644", ")", "@file", ".", "sync", "=", "true", "if", "@file", ".", "flock", "(", "File", "::", "LOCK_EX", "|", "File", "::", "LOCK_NB", ")", "# We have taken the lock. Write the PID into the file and leave it", "# open.", "@file", ".", "write", "(", "$$", ")", "@file", ".", "flush", "@file", ".", "fsync", "@file", ".", "truncate", "(", "@file", ".", "pos", ")", "PEROBS", ".", "log", ".", "debug", "\"Lock file #{@file_name} has been taken for \"", "+", "\"process #{$$}\"", "return", "true", "else", "# We did not manage to take the lock file.", "if", "@file", ".", "mtime", "<=", "Time", ".", "now", "-", "@timeout_secs", "pid", "=", "@file", ".", "read", ".", "to_i", "PEROBS", ".", "log", ".", "info", "\"Old lock file found for PID #{pid}. \"", "+", "\"Removing lock.\"", "if", "is_running?", "(", "pid", ")", "send_signal", "(", "'TERM'", ",", "pid", ")", "# Give the process 3 seconds to terminate gracefully.", "sleep", "3", "# Then send a SIGKILL to ensure it's gone.", "send_signal", "(", "'KILL'", ",", "pid", ")", "if", "is_running?", "(", "pid", ")", "end", "@file", ".", "close", "File", ".", "delete", "(", "@file_name", ")", "if", "File", ".", "exist?", "(", "@file_name", ")", "else", "PEROBS", ".", "log", ".", "debug", "\"Lock file #{@file_name} is taken. Trying \"", "+", "\"to get it #{retries} more times.\"", "end", "end", "rescue", "=>", "e", "PEROBS", ".", "log", ".", "error", "\"Cannot take lock file #{@file_name}: #{e.message}\"", "return", "false", "end", "retries", "-=", "1", "sleep", "(", "@pause_secs", ")", "end", "PEROBS", ".", "log", ".", "info", "\"Failed to get lock file #{@file_name} due to timeout\"", "false", "end" ]
Create a new lock for the given file. @param file_name [String] file name of the lock file @param options [Hash] See case statement Attempt to take the lock. @return [Boolean] true if lock was taken, false otherwise
[ "Create", "a", "new", "lock", "for", "the", "given", "file", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/LockFile.rb#L68-L117
4,057
scrapper/perobs
lib/perobs/LockFile.rb
PEROBS.LockFile.unlock
def unlock unless @file PEROBS.log.error "There is no current lock to release" return false end begin @file.flock(File::LOCK_UN) @file.fsync @file.close forced_unlock PEROBS.log.debug "Lock file #{@file_name} for PID #{$$} has been " + "released" rescue => e PEROBS.log.error "Releasing of lock file #{@file_name} failed: " + e.message return false end true end
ruby
def unlock unless @file PEROBS.log.error "There is no current lock to release" return false end begin @file.flock(File::LOCK_UN) @file.fsync @file.close forced_unlock PEROBS.log.debug "Lock file #{@file_name} for PID #{$$} has been " + "released" rescue => e PEROBS.log.error "Releasing of lock file #{@file_name} failed: " + e.message return false end true end
[ "def", "unlock", "unless", "@file", "PEROBS", ".", "log", ".", "error", "\"There is no current lock to release\"", "return", "false", "end", "begin", "@file", ".", "flock", "(", "File", "::", "LOCK_UN", ")", "@file", ".", "fsync", "@file", ".", "close", "forced_unlock", "PEROBS", ".", "log", ".", "debug", "\"Lock file #{@file_name} for PID #{$$} has been \"", "+", "\"released\"", "rescue", "=>", "e", "PEROBS", ".", "log", ".", "error", "\"Releasing of lock file #{@file_name} failed: \"", "+", "e", ".", "message", "return", "false", "end", "true", "end" ]
Release the lock again.
[ "Release", "the", "lock", "again", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/LockFile.rb#L126-L146
4,058
scrapper/perobs
lib/perobs/LockFile.rb
PEROBS.LockFile.forced_unlock
def forced_unlock @file = nil if File.exist?(@file_name) begin File.delete(@file_name) PEROBS.log.debug "Lock file #{@file_name} has been deleted." rescue IOError => e PEROBS.log.error "Cannot delete lock file #{@file_name}: " + e.message end end end
ruby
def forced_unlock @file = nil if File.exist?(@file_name) begin File.delete(@file_name) PEROBS.log.debug "Lock file #{@file_name} has been deleted." rescue IOError => e PEROBS.log.error "Cannot delete lock file #{@file_name}: " + e.message end end end
[ "def", "forced_unlock", "@file", "=", "nil", "if", "File", ".", "exist?", "(", "@file_name", ")", "begin", "File", ".", "delete", "(", "@file_name", ")", "PEROBS", ".", "log", ".", "debug", "\"Lock file #{@file_name} has been deleted.\"", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "error", "\"Cannot delete lock file #{@file_name}: \"", "+", "e", ".", "message", "end", "end", "end" ]
Erase the lock file. It's essentially a forced unlock method.
[ "Erase", "the", "lock", "file", ".", "It", "s", "essentially", "a", "forced", "unlock", "method", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/LockFile.rb#L149-L160
4,059
mreq/wmctile
lib/wmctile/router.rb
Wmctile.Router.window
def window(index = 0) if @arguments[:use_active_window] Window.new(@arguments, Wmctile.current_window_id) else Window.new(@arguments, @window_strings[index]) end rescue Errors::WindowNotFound if @arguments[:exec] # Exec the command puts "Executing command: #{@arguments[:exec]}" system "#{@arguments[:exec]} &" else raise Errors::WindowNotFound, @window_strings[index] end end
ruby
def window(index = 0) if @arguments[:use_active_window] Window.new(@arguments, Wmctile.current_window_id) else Window.new(@arguments, @window_strings[index]) end rescue Errors::WindowNotFound if @arguments[:exec] # Exec the command puts "Executing command: #{@arguments[:exec]}" system "#{@arguments[:exec]} &" else raise Errors::WindowNotFound, @window_strings[index] end end
[ "def", "window", "(", "index", "=", "0", ")", "if", "@arguments", "[", ":use_active_window", "]", "Window", ".", "new", "(", "@arguments", ",", "Wmctile", ".", "current_window_id", ")", "else", "Window", ".", "new", "(", "@arguments", ",", "@window_strings", "[", "index", "]", ")", "end", "rescue", "Errors", "::", "WindowNotFound", "if", "@arguments", "[", ":exec", "]", "# Exec the command", "puts", "\"Executing command: #{@arguments[:exec]}\"", "system", "\"#{@arguments[:exec]} &\"", "else", "raise", "Errors", "::", "WindowNotFound", ",", "@window_strings", "[", "index", "]", "end", "end" ]
Starts wmctile, runs the required methods. @param [Hash] command line options @param [Array] window_strings ARGV array Creates a new window based on @arguments and @window_strings. If no window is found, checks for the -x/--exec argument. If present, executes it. If there's no -x command and a window is not found, raises an error. @param [Integer] index index of the window from matching windows array @return [Window] window instance
[ "Starts", "wmctile", "runs", "the", "required", "methods", "." ]
a41af5afa310b09c8ba1bd45a134b9b2a87d1a35
https://github.com/mreq/wmctile/blob/a41af5afa310b09c8ba1bd45a134b9b2a87d1a35/lib/wmctile/router.rb#L55-L69
4,060
mreq/wmctile
lib/wmctile/router.rb
Wmctile.Router.switch_to_workspace
def switch_to_workspace(target_workspace) if target_workspace == 'next' target_workspace = Wmctile.current_workspace + 1 elsif target_workspace == 'previous' target_workspace = Wmctile.current_workspace - 1 elsif target_workspace == 'history' # must be -2 as -1 is the current workspace target_workspace = Wmctile.memory.get(:workspace_history)[-2] end system "wmctrl -s #{target_workspace}" target_workspace end
ruby
def switch_to_workspace(target_workspace) if target_workspace == 'next' target_workspace = Wmctile.current_workspace + 1 elsif target_workspace == 'previous' target_workspace = Wmctile.current_workspace - 1 elsif target_workspace == 'history' # must be -2 as -1 is the current workspace target_workspace = Wmctile.memory.get(:workspace_history)[-2] end system "wmctrl -s #{target_workspace}" target_workspace end
[ "def", "switch_to_workspace", "(", "target_workspace", ")", "if", "target_workspace", "==", "'next'", "target_workspace", "=", "Wmctile", ".", "current_workspace", "+", "1", "elsif", "target_workspace", "==", "'previous'", "target_workspace", "=", "Wmctile", ".", "current_workspace", "-", "1", "elsif", "target_workspace", "==", "'history'", "# must be -2 as -1 is the current workspace", "target_workspace", "=", "Wmctile", ".", "memory", ".", "get", "(", ":workspace_history", ")", "[", "-", "2", "]", "end", "system", "\"wmctrl -s #{target_workspace}\"", "target_workspace", "end" ]
Switch to target_workspace. @param [String] target_workspace Target workspace index or "next"/"previous". @return [Integer] Target workspace number
[ "Switch", "to", "target_workspace", "." ]
a41af5afa310b09c8ba1bd45a134b9b2a87d1a35
https://github.com/mreq/wmctile/blob/a41af5afa310b09c8ba1bd45a134b9b2a87d1a35/lib/wmctile/router.rb#L78-L89
4,061
ghempton/state_manager
lib/state_manager/base.rb
StateManager.Base.transition_to
def transition_to(path, current_state=self.current_state) path = path.to_s state = current_state || self exit_states = [] # Find the nearest parent state on the path of the current state which # has a sub-state at the given path new_states = state.find_states(path) while(!new_states) do exit_states << state state = state.parent_state raise(StateNotFound, transition_error(path)) unless state new_states = state.find_states(path) end # The first time we enter a state, the state_manager gets entered as well new_states.unshift(self) unless has_state? # Can only transition to leaf states # TODO: transition to the initial_state of the state? raise(InvalidTransition, transition_error(path)) unless new_states.last.leaf? enter_states = new_states - exit_states exit_states = exit_states - new_states from_state = current_state # TODO: does it make more sense to throw an error instead of allowing # a transition to the current state? to_state = enter_states.last || from_state run_before_callbacks(from_state, to_state, current_event, enter_states, exit_states) # Set the state on the underlying resource self.current_state = to_state run_after_callbacks(from_state, to_state, current_event, enter_states, exit_states) end
ruby
def transition_to(path, current_state=self.current_state) path = path.to_s state = current_state || self exit_states = [] # Find the nearest parent state on the path of the current state which # has a sub-state at the given path new_states = state.find_states(path) while(!new_states) do exit_states << state state = state.parent_state raise(StateNotFound, transition_error(path)) unless state new_states = state.find_states(path) end # The first time we enter a state, the state_manager gets entered as well new_states.unshift(self) unless has_state? # Can only transition to leaf states # TODO: transition to the initial_state of the state? raise(InvalidTransition, transition_error(path)) unless new_states.last.leaf? enter_states = new_states - exit_states exit_states = exit_states - new_states from_state = current_state # TODO: does it make more sense to throw an error instead of allowing # a transition to the current state? to_state = enter_states.last || from_state run_before_callbacks(from_state, to_state, current_event, enter_states, exit_states) # Set the state on the underlying resource self.current_state = to_state run_after_callbacks(from_state, to_state, current_event, enter_states, exit_states) end
[ "def", "transition_to", "(", "path", ",", "current_state", "=", "self", ".", "current_state", ")", "path", "=", "path", ".", "to_s", "state", "=", "current_state", "||", "self", "exit_states", "=", "[", "]", "# Find the nearest parent state on the path of the current state which", "# has a sub-state at the given path", "new_states", "=", "state", ".", "find_states", "(", "path", ")", "while", "(", "!", "new_states", ")", "do", "exit_states", "<<", "state", "state", "=", "state", ".", "parent_state", "raise", "(", "StateNotFound", ",", "transition_error", "(", "path", ")", ")", "unless", "state", "new_states", "=", "state", ".", "find_states", "(", "path", ")", "end", "# The first time we enter a state, the state_manager gets entered as well", "new_states", ".", "unshift", "(", "self", ")", "unless", "has_state?", "# Can only transition to leaf states", "# TODO: transition to the initial_state of the state?", "raise", "(", "InvalidTransition", ",", "transition_error", "(", "path", ")", ")", "unless", "new_states", ".", "last", ".", "leaf?", "enter_states", "=", "new_states", "-", "exit_states", "exit_states", "=", "exit_states", "-", "new_states", "from_state", "=", "current_state", "# TODO: does it make more sense to throw an error instead of allowing", "# a transition to the current state?", "to_state", "=", "enter_states", ".", "last", "||", "from_state", "run_before_callbacks", "(", "from_state", ",", "to_state", ",", "current_event", ",", "enter_states", ",", "exit_states", ")", "# Set the state on the underlying resource", "self", ".", "current_state", "=", "to_state", "run_after_callbacks", "(", "from_state", ",", "to_state", ",", "current_event", ",", "enter_states", ",", "exit_states", ")", "end" ]
Transitions to the state at the specified path. The path can be relative to any state along the current state's path.
[ "Transitions", "to", "the", "state", "at", "the", "specified", "path", ".", "The", "path", "can", "be", "relative", "to", "any", "state", "along", "the", "current", "state", "s", "path", "." ]
0e10fbb3c4b7718aa6602e240f4d8adf9cd72008
https://github.com/ghempton/state_manager/blob/0e10fbb3c4b7718aa6602e240f4d8adf9cd72008/lib/state_manager/base.rb#L38-L74
4,062
ghempton/state_manager
lib/state_manager/base.rb
StateManager.Base.available_events
def available_events state = current_state ret = {} while(state) do ret = state.class.specification.events.merge(ret) state = state.parent_state end ret end
ruby
def available_events state = current_state ret = {} while(state) do ret = state.class.specification.events.merge(ret) state = state.parent_state end ret end
[ "def", "available_events", "state", "=", "current_state", "ret", "=", "{", "}", "while", "(", "state", ")", "do", "ret", "=", "state", ".", "class", ".", "specification", ".", "events", ".", "merge", "(", "ret", ")", "state", "=", "state", ".", "parent_state", "end", "ret", "end" ]
All events the current state will respond to
[ "All", "events", "the", "current", "state", "will", "respond", "to" ]
0e10fbb3c4b7718aa6602e240f4d8adf9cd72008
https://github.com/ghempton/state_manager/blob/0e10fbb3c4b7718aa6602e240f4d8adf9cd72008/lib/state_manager/base.rb#L165-L173
4,063
tagoh/ruby-bugzilla
lib/bugzilla/product.rb
Bugzilla.Product.enterable_products
def enterable_products ids = get_enterable_products Hash[*get(ids)['products'].map {|x| [x['name'], x]}.flatten] end
ruby
def enterable_products ids = get_enterable_products Hash[*get(ids)['products'].map {|x| [x['name'], x]}.flatten] end
[ "def", "enterable_products", "ids", "=", "get_enterable_products", "Hash", "[", "get", "(", "ids", ")", "[", "'products'", "]", ".", "map", "{", "|", "x", "|", "[", "x", "[", "'name'", "]", ",", "x", "]", "}", ".", "flatten", "]", "end" ]
def selectable_products =begin rdoc ==== Bugzilla::Product#enterable_products Returns Hash table for the products information that the user can enter bugs against. the Hash key is the product name and containing a Hash table which contains id, name, description, is_active, default_milestone, has_uncomfirmed, classification, components, versions and milestones. please see http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/Product.html#get for more details. =end
[ "def", "selectable_products", "=", "begin", "rdoc" ]
5aabec1b045473bcd6e6ac7427b68adb3e3b4886
https://github.com/tagoh/ruby-bugzilla/blob/5aabec1b045473bcd6e6ac7427b68adb3e3b4886/lib/bugzilla/product.rb#L69-L72
4,064
tagoh/ruby-bugzilla
lib/bugzilla/product.rb
Bugzilla.Product.accessible_products
def accessible_products ids = get_accessible_products Hash[*get(ids)['products'].map {|x| [x['name'], x]}.flatten] end
ruby
def accessible_products ids = get_accessible_products Hash[*get(ids)['products'].map {|x| [x['name'], x]}.flatten] end
[ "def", "accessible_products", "ids", "=", "get_accessible_products", "Hash", "[", "get", "(", "ids", ")", "[", "'products'", "]", ".", "map", "{", "|", "x", "|", "[", "x", "[", "'name'", "]", ",", "x", "]", "}", ".", "flatten", "]", "end" ]
def enterable_products =begin rdoc ==== Bugzilla::Product#accessible_products Returns Hash table for the products information that the user can search or enter bugs against. the Hash key is the product name and containing a Hash table which contains id, name, description, is_active, default_milestone, has_uncomfirmed, classification, components, versions and milestones. please see http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/Product.html#get for more details. =end
[ "def", "enterable_products", "=", "begin", "rdoc" ]
5aabec1b045473bcd6e6ac7427b68adb3e3b4886
https://github.com/tagoh/ruby-bugzilla/blob/5aabec1b045473bcd6e6ac7427b68adb3e3b4886/lib/bugzilla/product.rb#L88-L91
4,065
scrapper/perobs
lib/perobs/FlatFileDB.rb
PEROBS.FlatFileDB.put_hash
def put_hash(name, hash) file_name = File.join(@db_dir, name + '.json') begin RobustFile.write(file_name, hash.to_json) rescue IOError => e PEROBS.log.fatal "Cannot write hash file '#{file_name}': #{e.message}" end end
ruby
def put_hash(name, hash) file_name = File.join(@db_dir, name + '.json') begin RobustFile.write(file_name, hash.to_json) rescue IOError => e PEROBS.log.fatal "Cannot write hash file '#{file_name}': #{e.message}" end end
[ "def", "put_hash", "(", "name", ",", "hash", ")", "file_name", "=", "File", ".", "join", "(", "@db_dir", ",", "name", "+", "'.json'", ")", "begin", "RobustFile", ".", "write", "(", "file_name", ",", "hash", ".", "to_json", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot write hash file '#{file_name}': #{e.message}\"", "end", "end" ]
Store a simple Hash as a JSON encoded file into the DB directory. @param name [String] Name of the hash. Will be used as file name. @param hash [Hash] A Hash that maps String objects to strings or numbers.
[ "Store", "a", "simple", "Hash", "as", "a", "JSON", "encoded", "file", "into", "the", "DB", "directory", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/FlatFileDB.rb#L109-L116
4,066
danielpclark/PolyBelongsTo
lib/poly_belongs_to/core.rb
PolyBelongsTo.Core.pbt_parent
def pbt_parent val = pbt if val && !pbt_id.nil? if poly? "#{pbt_type}".constantize.where(id: pbt_id).first else "#{val}".camelize.constantize.where(id: pbt_id).first end end end
ruby
def pbt_parent val = pbt if val && !pbt_id.nil? if poly? "#{pbt_type}".constantize.where(id: pbt_id).first else "#{val}".camelize.constantize.where(id: pbt_id).first end end end
[ "def", "pbt_parent", "val", "=", "pbt", "if", "val", "&&", "!", "pbt_id", ".", "nil?", "if", "poly?", "\"#{pbt_type}\"", ".", "constantize", ".", "where", "(", "id", ":", "pbt_id", ")", ".", "first", "else", "\"#{val}\"", ".", "camelize", ".", "constantize", ".", "where", "(", "id", ":", "pbt_id", ")", ".", "first", "end", "end", "end" ]
Get the parent relation. Polymorphic relations are prioritized first. @return [Object, nil] ActiveRecord object instasnce
[ "Get", "the", "parent", "relation", ".", "Polymorphic", "relations", "are", "prioritized", "first", "." ]
38d51d37f9148613519d6b6d56bdf4d0884f0e86
https://github.com/danielpclark/PolyBelongsTo/blob/38d51d37f9148613519d6b6d56bdf4d0884f0e86/lib/poly_belongs_to/core.rb#L162-L171
4,067
danielpclark/PolyBelongsTo
lib/poly_belongs_to/core.rb
PolyBelongsTo.Core.pbt_top_parent
def pbt_top_parent record = self return nil unless record.pbt_parent no_repeat = PolyBelongsTo::SingletonSet.new while !no_repeat.include?(record.pbt_parent) && !record.pbt_parent.nil? no_repeat.add?(record) record = record.pbt_parent end record end
ruby
def pbt_top_parent record = self return nil unless record.pbt_parent no_repeat = PolyBelongsTo::SingletonSet.new while !no_repeat.include?(record.pbt_parent) && !record.pbt_parent.nil? no_repeat.add?(record) record = record.pbt_parent end record end
[ "def", "pbt_top_parent", "record", "=", "self", "return", "nil", "unless", "record", ".", "pbt_parent", "no_repeat", "=", "PolyBelongsTo", "::", "SingletonSet", ".", "new", "while", "!", "no_repeat", ".", "include?", "(", "record", ".", "pbt_parent", ")", "&&", "!", "record", ".", "pbt_parent", ".", "nil?", "no_repeat", ".", "add?", "(", "record", ")", "record", "=", "record", ".", "pbt_parent", "end", "record", "end" ]
Climb up each parent object in the hierarchy until the top is reached. This has a no-repeat safety built in. Polymorphic parents have priority. @return [Object, nil] top parent ActiveRecord object instace
[ "Climb", "up", "each", "parent", "object", "in", "the", "hierarchy", "until", "the", "top", "is", "reached", ".", "This", "has", "a", "no", "-", "repeat", "safety", "built", "in", ".", "Polymorphic", "parents", "have", "priority", "." ]
38d51d37f9148613519d6b6d56bdf4d0884f0e86
https://github.com/danielpclark/PolyBelongsTo/blob/38d51d37f9148613519d6b6d56bdf4d0884f0e86/lib/poly_belongs_to/core.rb#L176-L185
4,068
danielpclark/PolyBelongsTo
lib/poly_belongs_to/core.rb
PolyBelongsTo.Core.pbt_parents
def pbt_parents if poly? Array[pbt_parent].compact else self.class.pbts.map do |i| try{ "#{i}".camelize.constantize.where(id: send("#{i}_id")).first } end.compact end end
ruby
def pbt_parents if poly? Array[pbt_parent].compact else self.class.pbts.map do |i| try{ "#{i}".camelize.constantize.where(id: send("#{i}_id")).first } end.compact end end
[ "def", "pbt_parents", "if", "poly?", "Array", "[", "pbt_parent", "]", ".", "compact", "else", "self", ".", "class", ".", "pbts", ".", "map", "do", "|", "i", "|", "try", "{", "\"#{i}\"", ".", "camelize", ".", "constantize", ".", "where", "(", "id", ":", "send", "(", "\"#{i}_id\"", ")", ")", ".", "first", "}", "end", ".", "compact", "end", "end" ]
All belongs_to parents as class objects. One if polymorphic. @return [Array<Object>] ActiveRecord classes of parent objects.
[ "All", "belongs_to", "parents", "as", "class", "objects", ".", "One", "if", "polymorphic", "." ]
38d51d37f9148613519d6b6d56bdf4d0884f0e86
https://github.com/danielpclark/PolyBelongsTo/blob/38d51d37f9148613519d6b6d56bdf4d0884f0e86/lib/poly_belongs_to/core.rb#L189-L197
4,069
PublicHealthEngland/ndr_support
lib/ndr_support/password.rb
NdrSupport.Password.valid?
def valid?(string, word_list: []) string = prepare_string(string.to_s.dup) slug = slugify(strip_common_words(string, word_list)) meets_requirements?(slug) end
ruby
def valid?(string, word_list: []) string = prepare_string(string.to_s.dup) slug = slugify(strip_common_words(string, word_list)) meets_requirements?(slug) end
[ "def", "valid?", "(", "string", ",", "word_list", ":", "[", "]", ")", "string", "=", "prepare_string", "(", "string", ".", "to_s", ".", "dup", ")", "slug", "=", "slugify", "(", "strip_common_words", "(", "string", ",", "word_list", ")", ")", "meets_requirements?", "(", "slug", ")", "end" ]
Is the given `string` deemed a good password? An additional `word_list` can be provided; its entries add only minimally when considering the strength of `string`. NdrSupport::Password.valid?('google password') #=> false NdrSupport::Password.valid?(SecureRandom.hex(12)) #=> true
[ "Is", "the", "given", "string", "deemed", "a", "good", "password?", "An", "additional", "word_list", "can", "be", "provided", ";", "its", "entries", "add", "only", "minimally", "when", "considering", "the", "strength", "of", "string", "." ]
6daf98ca972e79de1c8457eb720f058b03ead21c
https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/password.rb#L18-L23
4,070
xinminlabs/synvert-core
lib/synvert/core/rewriter.rb
Synvert::Core.Rewriter.add_file
def add_file(filename, content) return if @sandbox filepath = File.join(Configuration.instance.get(:path), filename) if File.exist?(filepath) puts "File #{filepath} already exists." return end FileUtils.mkdir_p File.dirname(filepath) File.open filepath, 'w' do |file| file.write content end end
ruby
def add_file(filename, content) return if @sandbox filepath = File.join(Configuration.instance.get(:path), filename) if File.exist?(filepath) puts "File #{filepath} already exists." return end FileUtils.mkdir_p File.dirname(filepath) File.open filepath, 'w' do |file| file.write content end end
[ "def", "add_file", "(", "filename", ",", "content", ")", "return", "if", "@sandbox", "filepath", "=", "File", ".", "join", "(", "Configuration", ".", "instance", ".", "get", "(", ":path", ")", ",", "filename", ")", "if", "File", ".", "exist?", "(", "filepath", ")", "puts", "\"File #{filepath} already exists.\"", "return", "end", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "filepath", ")", "File", ".", "open", "filepath", ",", "'w'", "do", "|", "file", "|", "file", ".", "write", "content", "end", "end" ]
Parses add_file dsl, it adds a new file. @param filename [String] file name of newly created file. @param content [String] file body of newly created file.
[ "Parses", "add_file", "dsl", "it", "adds", "a", "new", "file", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter.rb#L227-L240
4,071
xinminlabs/synvert-core
lib/synvert/core/rewriter.rb
Synvert::Core.Rewriter.remove_file
def remove_file(filename) return if @sandbox file_path = File.join(Configuration.instance.get(:path), filename) File.delete(file_path) if File.exist?(file_path) end
ruby
def remove_file(filename) return if @sandbox file_path = File.join(Configuration.instance.get(:path), filename) File.delete(file_path) if File.exist?(file_path) end
[ "def", "remove_file", "(", "filename", ")", "return", "if", "@sandbox", "file_path", "=", "File", ".", "join", "(", "Configuration", ".", "instance", ".", "get", "(", ":path", ")", ",", "filename", ")", "File", ".", "delete", "(", "file_path", ")", "if", "File", ".", "exist?", "(", "file_path", ")", "end" ]
Parses remove_file dsl, it removes a file. @param filename [String] file name.
[ "Parses", "remove_file", "dsl", "it", "removes", "a", "file", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter.rb#L245-L250
4,072
Absolight/epp-client
lib/epp-client/connection.rb
EPPClient.Connection.open_connection
def open_connection @tcpserver = TCPSocket.new(server, port) @socket = OpenSSL::SSL::SSLSocket.new(@tcpserver, @context) # Synchronously close the connection & socket @socket.sync_close # Connect @socket.connect # Get the initial greeting frame greeting_process(one_frame) end
ruby
def open_connection @tcpserver = TCPSocket.new(server, port) @socket = OpenSSL::SSL::SSLSocket.new(@tcpserver, @context) # Synchronously close the connection & socket @socket.sync_close # Connect @socket.connect # Get the initial greeting frame greeting_process(one_frame) end
[ "def", "open_connection", "@tcpserver", "=", "TCPSocket", ".", "new", "(", "server", ",", "port", ")", "@socket", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "(", "@tcpserver", ",", "@context", ")", "# Synchronously close the connection & socket", "@socket", ".", "sync_close", "# Connect", "@socket", ".", "connect", "# Get the initial greeting frame", "greeting_process", "(", "one_frame", ")", "end" ]
Establishes the connection to the server, if successful, will return the greeting frame.
[ "Establishes", "the", "connection", "to", "the", "server", "if", "successful", "will", "return", "the", "greeting", "frame", "." ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/connection.rb#L8-L20
4,073
Absolight/epp-client
lib/epp-client/connection.rb
EPPClient.Connection.close_connection
def close_connection if defined?(@socket) && @socket.is_a?(OpenSSL::SSL::SSLSocket) @socket.close @socket = nil end if defined?(@tcpserver) && @tcpserver.is_a?(TCPSocket) @tcpserver.close @tcpserver = nil end return true if @tcpserver.nil? && @socket.nil? end
ruby
def close_connection if defined?(@socket) && @socket.is_a?(OpenSSL::SSL::SSLSocket) @socket.close @socket = nil end if defined?(@tcpserver) && @tcpserver.is_a?(TCPSocket) @tcpserver.close @tcpserver = nil end return true if @tcpserver.nil? && @socket.nil? end
[ "def", "close_connection", "if", "defined?", "(", "@socket", ")", "&&", "@socket", ".", "is_a?", "(", "OpenSSL", "::", "SSL", "::", "SSLSocket", ")", "@socket", ".", "close", "@socket", "=", "nil", "end", "if", "defined?", "(", "@tcpserver", ")", "&&", "@tcpserver", ".", "is_a?", "(", "TCPSocket", ")", "@tcpserver", ".", "close", "@tcpserver", "=", "nil", "end", "return", "true", "if", "@tcpserver", ".", "nil?", "&&", "@socket", ".", "nil?", "end" ]
Gracefully close the connection
[ "Gracefully", "close", "the", "connection" ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/connection.rb#L34-L46
4,074
Absolight/epp-client
lib/epp-client/connection.rb
EPPClient.Connection.one_frame
def one_frame size = @socket.read(4) raise SocketError, @socket.eof? ? 'Connection closed by remote server' : 'Error reading frame from remote server' if size.nil? size = size.unpack('N')[0] @recv_frame = @socket.read(size - 4) recv_frame_to_xml end
ruby
def one_frame size = @socket.read(4) raise SocketError, @socket.eof? ? 'Connection closed by remote server' : 'Error reading frame from remote server' if size.nil? size = size.unpack('N')[0] @recv_frame = @socket.read(size - 4) recv_frame_to_xml end
[ "def", "one_frame", "size", "=", "@socket", ".", "read", "(", "4", ")", "raise", "SocketError", ",", "@socket", ".", "eof?", "?", "'Connection closed by remote server'", ":", "'Error reading frame from remote server'", "if", "size", ".", "nil?", "size", "=", "size", ".", "unpack", "(", "'N'", ")", "[", "0", "]", "@recv_frame", "=", "@socket", ".", "read", "(", "size", "-", "4", ")", "recv_frame_to_xml", "end" ]
gets a frame from the socket and returns the parsed response.
[ "gets", "a", "frame", "from", "the", "socket", "and", "returns", "the", "parsed", "response", "." ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/connection.rb#L62-L68
4,075
iconara/snogmetrics
lib/snogmetrics/kissmetrics_api.rb
Snogmetrics.KissmetricsApi.identify
def identify(identity) unless @session[:km_identity] == identity queue.delete_if { |e| e.first == 'identify' } queue << ['identify', identity] @session[:km_identity] = identity end end
ruby
def identify(identity) unless @session[:km_identity] == identity queue.delete_if { |e| e.first == 'identify' } queue << ['identify', identity] @session[:km_identity] = identity end end
[ "def", "identify", "(", "identity", ")", "unless", "@session", "[", ":km_identity", "]", "==", "identity", "queue", ".", "delete_if", "{", "|", "e", "|", "e", ".", "first", "==", "'identify'", "}", "queue", "<<", "[", "'identify'", ",", "identity", "]", "@session", "[", ":km_identity", "]", "=", "identity", "end", "end" ]
The equivalent of the `KM.identify` method of the JavaScript API.
[ "The", "equivalent", "of", "the", "KM", ".", "identify", "method", "of", "the", "JavaScript", "API", "." ]
1742fb77dee1378934fbad8b78790f59bff20c35
https://github.com/iconara/snogmetrics/blob/1742fb77dee1378934fbad8b78790f59bff20c35/lib/snogmetrics/kissmetrics_api.rb#L22-L28
4,076
bratta/googlevoiceapi
lib/googlevoiceapi.rb
GoogleVoice.Api.sms
def sms(remote_number, text_message) login unless logged_in? remote_number = validate_number(remote_number) text_message = @coder.encode(text_message) @agent.post('https://www.google.com/voice/sms/send/', :id => '', :phoneNumber => remote_number, :text => text_message, "_rnr_se" => @rnr_se) end
ruby
def sms(remote_number, text_message) login unless logged_in? remote_number = validate_number(remote_number) text_message = @coder.encode(text_message) @agent.post('https://www.google.com/voice/sms/send/', :id => '', :phoneNumber => remote_number, :text => text_message, "_rnr_se" => @rnr_se) end
[ "def", "sms", "(", "remote_number", ",", "text_message", ")", "login", "unless", "logged_in?", "remote_number", "=", "validate_number", "(", "remote_number", ")", "text_message", "=", "@coder", ".", "encode", "(", "text_message", ")", "@agent", ".", "post", "(", "'https://www.google.com/voice/sms/send/'", ",", ":id", "=>", "''", ",", ":phoneNumber", "=>", "remote_number", ",", ":text", "=>", "text_message", ",", "\"_rnr_se\"", "=>", "@rnr_se", ")", "end" ]
Send a text message to remote_number
[ "Send", "a", "text", "message", "to", "remote_number" ]
5d6163209bda665ba0cd7bbe723e59f6f7085705
https://github.com/bratta/googlevoiceapi/blob/5d6163209bda665ba0cd7bbe723e59f6f7085705/lib/googlevoiceapi.rb#L56-L61
4,077
bratta/googlevoiceapi
lib/googlevoiceapi.rb
GoogleVoice.Api.call
def call(remote_number, forwarding_number) login unless logged_in? remote_number = validate_number(remote_number) forwarding_number = validate_number(forwarding_number) @agent.post('https://www.google.com/voice/call/connect/', :outgoingNumber => remote_number, :forwardingNumber => forwarding_number, :phoneType => 2, :subscriberNumber => 'undefined', :remember => '0', "_rnr_se" => @rnr_se) end
ruby
def call(remote_number, forwarding_number) login unless logged_in? remote_number = validate_number(remote_number) forwarding_number = validate_number(forwarding_number) @agent.post('https://www.google.com/voice/call/connect/', :outgoingNumber => remote_number, :forwardingNumber => forwarding_number, :phoneType => 2, :subscriberNumber => 'undefined', :remember => '0', "_rnr_se" => @rnr_se) end
[ "def", "call", "(", "remote_number", ",", "forwarding_number", ")", "login", "unless", "logged_in?", "remote_number", "=", "validate_number", "(", "remote_number", ")", "forwarding_number", "=", "validate_number", "(", "forwarding_number", ")", "@agent", ".", "post", "(", "'https://www.google.com/voice/call/connect/'", ",", ":outgoingNumber", "=>", "remote_number", ",", ":forwardingNumber", "=>", "forwarding_number", ",", ":phoneType", "=>", "2", ",", ":subscriberNumber", "=>", "'undefined'", ",", ":remember", "=>", "'0'", ",", "\"_rnr_se\"", "=>", "@rnr_se", ")", "end" ]
Place a call to remote_number, and ring back forwarding_number which should be set up on the currently logged in Google Voice account
[ "Place", "a", "call", "to", "remote_number", "and", "ring", "back", "forwarding_number", "which", "should", "be", "set", "up", "on", "the", "currently", "logged", "in", "Google", "Voice", "account" ]
5d6163209bda665ba0cd7bbe723e59f6f7085705
https://github.com/bratta/googlevoiceapi/blob/5d6163209bda665ba0cd7bbe723e59f6f7085705/lib/googlevoiceapi.rb#L65-L70
4,078
bratta/googlevoiceapi
lib/googlevoiceapi.rb
GoogleVoice.Api.init_xml_methods
def init_xml_methods() (class << self; self; end).class_eval do %w{ unread inbox starred all spam trash voicemail sms trash recorded placed received missed }.each do |method| define_method "#{method}_xml".to_sym do get_xml_document("https://www.google.com/voice/inbox/recent/#{method}") end end end end
ruby
def init_xml_methods() (class << self; self; end).class_eval do %w{ unread inbox starred all spam trash voicemail sms trash recorded placed received missed }.each do |method| define_method "#{method}_xml".to_sym do get_xml_document("https://www.google.com/voice/inbox/recent/#{method}") end end end end
[ "def", "init_xml_methods", "(", ")", "(", "class", "<<", "self", ";", "self", ";", "end", ")", ".", "class_eval", "do", "%w{", "unread", "inbox", "starred", "all", "spam", "trash", "voicemail", "sms", "trash", "recorded", "placed", "received", "missed", "}", ".", "each", "do", "|", "method", "|", "define_method", "\"#{method}_xml\"", ".", "to_sym", "do", "get_xml_document", "(", "\"https://www.google.com/voice/inbox/recent/#{method}\"", ")", "end", "end", "end", "end" ]
Google provides XML data for various call histories all with the same URL pattern in a getful manner. So here we're just dynamically creating methods to fetch that data in a DRY-manner. Yes, define_method is slow, but we're already making web calls which drags performance down anyway so it shouldn't matter in the long run.
[ "Google", "provides", "XML", "data", "for", "various", "call", "histories", "all", "with", "the", "same", "URL", "pattern", "in", "a", "getful", "manner", ".", "So", "here", "we", "re", "just", "dynamically", "creating", "methods", "to", "fetch", "that", "data", "in", "a", "DRY", "-", "manner", ".", "Yes", "define_method", "is", "slow", "but", "we", "re", "already", "making", "web", "calls", "which", "drags", "performance", "down", "anyway", "so", "it", "shouldn", "t", "matter", "in", "the", "long", "run", "." ]
5d6163209bda665ba0cd7bbe723e59f6f7085705
https://github.com/bratta/googlevoiceapi/blob/5d6163209bda665ba0cd7bbe723e59f6f7085705/lib/googlevoiceapi.rb#L104-L112
4,079
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.setHTTPConnection
def setHTTPConnection( useSSL, org = "www", domain = "quickbase", proxy_options = nil ) @useSSL = useSSL @org = org @domain = domain if USING_HTTPCLIENT if proxy_options @httpConnection = HTTPClient.new( "#{proxy_options["proxy_server"]}:#{proxy_options["proxy_port"] || useSSL ? "443" : "80"}" ) @httpConnection.set_auth(proxy_options["proxy_server"], proxy_options["proxy_user"], proxy_options["proxy_password"]) else @httpConnection = HTTPClient.new end else if proxy_options @httpProxy = Net::HTTP::Proxy(proxy_options["proxy_server"], proxy_options["proxy_port"], proxy_options["proxy_user"], proxy_options["proxy_password"]) @httpConnection = @httpProxy.new( "#{@org}.#{@domain}.com", useSSL ? 443 : 80) else @httpConnection = Net::HTTP.new( "#{@org}.#{@domain}.com", useSSL ? 443 : 80 ) end @httpConnection.use_ssl = useSSL @httpConnection.verify_mode = OpenSSL::SSL::VERIFY_NONE end end
ruby
def setHTTPConnection( useSSL, org = "www", domain = "quickbase", proxy_options = nil ) @useSSL = useSSL @org = org @domain = domain if USING_HTTPCLIENT if proxy_options @httpConnection = HTTPClient.new( "#{proxy_options["proxy_server"]}:#{proxy_options["proxy_port"] || useSSL ? "443" : "80"}" ) @httpConnection.set_auth(proxy_options["proxy_server"], proxy_options["proxy_user"], proxy_options["proxy_password"]) else @httpConnection = HTTPClient.new end else if proxy_options @httpProxy = Net::HTTP::Proxy(proxy_options["proxy_server"], proxy_options["proxy_port"], proxy_options["proxy_user"], proxy_options["proxy_password"]) @httpConnection = @httpProxy.new( "#{@org}.#{@domain}.com", useSSL ? 443 : 80) else @httpConnection = Net::HTTP.new( "#{@org}.#{@domain}.com", useSSL ? 443 : 80 ) end @httpConnection.use_ssl = useSSL @httpConnection.verify_mode = OpenSSL::SSL::VERIFY_NONE end end
[ "def", "setHTTPConnection", "(", "useSSL", ",", "org", "=", "\"www\"", ",", "domain", "=", "\"quickbase\"", ",", "proxy_options", "=", "nil", ")", "@useSSL", "=", "useSSL", "@org", "=", "org", "@domain", "=", "domain", "if", "USING_HTTPCLIENT", "if", "proxy_options", "@httpConnection", "=", "HTTPClient", ".", "new", "(", "\"#{proxy_options[\"proxy_server\"]}:#{proxy_options[\"proxy_port\"] || useSSL ? \"443\" : \"80\"}\"", ")", "@httpConnection", ".", "set_auth", "(", "proxy_options", "[", "\"proxy_server\"", "]", ",", "proxy_options", "[", "\"proxy_user\"", "]", ",", "proxy_options", "[", "\"proxy_password\"", "]", ")", "else", "@httpConnection", "=", "HTTPClient", ".", "new", "end", "else", "if", "proxy_options", "@httpProxy", "=", "Net", "::", "HTTP", "::", "Proxy", "(", "proxy_options", "[", "\"proxy_server\"", "]", ",", "proxy_options", "[", "\"proxy_port\"", "]", ",", "proxy_options", "[", "\"proxy_user\"", "]", ",", "proxy_options", "[", "\"proxy_password\"", "]", ")", "@httpConnection", "=", "@httpProxy", ".", "new", "(", "\"#{@org}.#{@domain}.com\"", ",", "useSSL", "?", "443", ":", "80", ")", "else", "@httpConnection", "=", "Net", "::", "HTTP", ".", "new", "(", "\"#{@org}.#{@domain}.com\"", ",", "useSSL", "?", "443", ":", "80", ")", "end", "@httpConnection", ".", "use_ssl", "=", "useSSL", "@httpConnection", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "end" ]
Initializes the connection to QuickBase.
[ "Initializes", "the", "connection", "to", "QuickBase", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L153-L174
4,080
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.setHTTPConnectionAndqbhost
def setHTTPConnectionAndqbhost( useSSL, org = "www", domain = "quickbase", proxy_options = nil ) setHTTPConnection( useSSL, org, domain, proxy_options ) setqbhost( useSSL, org, domain ) end
ruby
def setHTTPConnectionAndqbhost( useSSL, org = "www", domain = "quickbase", proxy_options = nil ) setHTTPConnection( useSSL, org, domain, proxy_options ) setqbhost( useSSL, org, domain ) end
[ "def", "setHTTPConnectionAndqbhost", "(", "useSSL", ",", "org", "=", "\"www\"", ",", "domain", "=", "\"quickbase\"", ",", "proxy_options", "=", "nil", ")", "setHTTPConnection", "(", "useSSL", ",", "org", ",", "domain", ",", "proxy_options", ")", "setqbhost", "(", "useSSL", ",", "org", ",", "domain", ")", "end" ]
Initializes the connection to QuickBase and sets the QuickBase URL and port to use for requests.
[ "Initializes", "the", "connection", "to", "QuickBase", "and", "sets", "the", "QuickBase", "URL", "and", "port", "to", "use", "for", "requests", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L191-L194
4,081
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.sendRequest
def sendRequest( api_Request, xmlRequestData = nil ) fire( "onSendRequest" ) resetErrorInfo # set up the request getDBforRequestURL( api_Request ) getAuthenticationXMLforRequest( api_Request ) isHTMLRequest = isHTMLRequest?( api_Request ) api_Request = "API_" + api_Request.to_s if prependAPI?( api_Request ) xmlRequestData << toXML( :udata, @udata ) if @udata and @udata.length > 0 xmlRequestData << toXML( :rdr, @rdr ) if @rdr and @rdr.length > 0 xmlRequestData << toXML( :xsl, @xsl ) if @xsl and @xsl.length > 0 xmlRequestData << toXML( :encoding, @encoding ) if @encoding and @encoding.length > 0 if xmlRequestData @requestXML = toXML( :qdbapi, @authenticationXML + xmlRequestData ) else @requestXML = toXML( :qdbapi, @authenticationXML ) end @requestHeaders = @standardRequestHeaders @requestHeaders["Content-Length"] = "#{@requestXML.length}" @requestHeaders["QUICKBASE-ACTION"] = api_Request @requestURL = "#{@qbhost}#{@dbidForRequestURL}" printRequest( @requestURL, @requestHeaders, @requestXML ) if @printRequestsAndResponses @logger.logRequest( @dbidForRequestURL, api_Request, @requestXML ) if @logger begin # send the request if USING_HTTPCLIENT response = @httpConnection.post( @requestURL, @requestXML, @requestHeaders ) @responseCode = response.status @responseXML = response.content else if Net::HTTP.version_1_2? response = @httpConnection.post( @requestURL, @requestXML, @requestHeaders ) @responseCode = response.code @responseXML = response.body else @responseCode, @responseXML = @httpConnection.post( @requestURL, @requestXML, @requestHeaders ) end end printResponse( @responseCode, @responseXML ) if @printRequestsAndResponses if not isHTMLRequest processResponse( @responseXML ) end @logger.logResponse( @lastError, @responseXML ) if @logger fireDBChangeEvents rescue Net::HTTPBadResponse => error @lastError = "Bad HTTP Response: #{error}" rescue Net::HTTPHeaderSyntaxError => error @lastError = "Bad HTTP header syntax: #{error}" rescue StandardError => error @lastError = "Error processing #{api_Request} request: #{error}" end @requestSucceeded = ( @errcode == "0" and @lastError == "" ) fire( @requestSucceeded ? "onRequestSucceeded" : "onRequestFailed" ) if @stopOnError and !@requestSucceeded raise @lastError end end
ruby
def sendRequest( api_Request, xmlRequestData = nil ) fire( "onSendRequest" ) resetErrorInfo # set up the request getDBforRequestURL( api_Request ) getAuthenticationXMLforRequest( api_Request ) isHTMLRequest = isHTMLRequest?( api_Request ) api_Request = "API_" + api_Request.to_s if prependAPI?( api_Request ) xmlRequestData << toXML( :udata, @udata ) if @udata and @udata.length > 0 xmlRequestData << toXML( :rdr, @rdr ) if @rdr and @rdr.length > 0 xmlRequestData << toXML( :xsl, @xsl ) if @xsl and @xsl.length > 0 xmlRequestData << toXML( :encoding, @encoding ) if @encoding and @encoding.length > 0 if xmlRequestData @requestXML = toXML( :qdbapi, @authenticationXML + xmlRequestData ) else @requestXML = toXML( :qdbapi, @authenticationXML ) end @requestHeaders = @standardRequestHeaders @requestHeaders["Content-Length"] = "#{@requestXML.length}" @requestHeaders["QUICKBASE-ACTION"] = api_Request @requestURL = "#{@qbhost}#{@dbidForRequestURL}" printRequest( @requestURL, @requestHeaders, @requestXML ) if @printRequestsAndResponses @logger.logRequest( @dbidForRequestURL, api_Request, @requestXML ) if @logger begin # send the request if USING_HTTPCLIENT response = @httpConnection.post( @requestURL, @requestXML, @requestHeaders ) @responseCode = response.status @responseXML = response.content else if Net::HTTP.version_1_2? response = @httpConnection.post( @requestURL, @requestXML, @requestHeaders ) @responseCode = response.code @responseXML = response.body else @responseCode, @responseXML = @httpConnection.post( @requestURL, @requestXML, @requestHeaders ) end end printResponse( @responseCode, @responseXML ) if @printRequestsAndResponses if not isHTMLRequest processResponse( @responseXML ) end @logger.logResponse( @lastError, @responseXML ) if @logger fireDBChangeEvents rescue Net::HTTPBadResponse => error @lastError = "Bad HTTP Response: #{error}" rescue Net::HTTPHeaderSyntaxError => error @lastError = "Bad HTTP header syntax: #{error}" rescue StandardError => error @lastError = "Error processing #{api_Request} request: #{error}" end @requestSucceeded = ( @errcode == "0" and @lastError == "" ) fire( @requestSucceeded ? "onRequestSucceeded" : "onRequestFailed" ) if @stopOnError and !@requestSucceeded raise @lastError end end
[ "def", "sendRequest", "(", "api_Request", ",", "xmlRequestData", "=", "nil", ")", "fire", "(", "\"onSendRequest\"", ")", "resetErrorInfo", "# set up the request\r", "getDBforRequestURL", "(", "api_Request", ")", "getAuthenticationXMLforRequest", "(", "api_Request", ")", "isHTMLRequest", "=", "isHTMLRequest?", "(", "api_Request", ")", "api_Request", "=", "\"API_\"", "+", "api_Request", ".", "to_s", "if", "prependAPI?", "(", "api_Request", ")", "xmlRequestData", "<<", "toXML", "(", ":udata", ",", "@udata", ")", "if", "@udata", "and", "@udata", ".", "length", ">", "0", "xmlRequestData", "<<", "toXML", "(", ":rdr", ",", "@rdr", ")", "if", "@rdr", "and", "@rdr", ".", "length", ">", "0", "xmlRequestData", "<<", "toXML", "(", ":xsl", ",", "@xsl", ")", "if", "@xsl", "and", "@xsl", ".", "length", ">", "0", "xmlRequestData", "<<", "toXML", "(", ":encoding", ",", "@encoding", ")", "if", "@encoding", "and", "@encoding", ".", "length", ">", "0", "if", "xmlRequestData", "@requestXML", "=", "toXML", "(", ":qdbapi", ",", "@authenticationXML", "+", "xmlRequestData", ")", "else", "@requestXML", "=", "toXML", "(", ":qdbapi", ",", "@authenticationXML", ")", "end", "@requestHeaders", "=", "@standardRequestHeaders", "@requestHeaders", "[", "\"Content-Length\"", "]", "=", "\"#{@requestXML.length}\"", "@requestHeaders", "[", "\"QUICKBASE-ACTION\"", "]", "=", "api_Request", "@requestURL", "=", "\"#{@qbhost}#{@dbidForRequestURL}\"", "printRequest", "(", "@requestURL", ",", "@requestHeaders", ",", "@requestXML", ")", "if", "@printRequestsAndResponses", "@logger", ".", "logRequest", "(", "@dbidForRequestURL", ",", "api_Request", ",", "@requestXML", ")", "if", "@logger", "begin", "# send the request\r", "if", "USING_HTTPCLIENT", "response", "=", "@httpConnection", ".", "post", "(", "@requestURL", ",", "@requestXML", ",", "@requestHeaders", ")", "@responseCode", "=", "response", ".", "status", "@responseXML", "=", "response", ".", "content", "else", "if", "Net", "::", "HTTP", ".", "version_1_2?", "response", "=", "@httpConnection", ".", "post", "(", "@requestURL", ",", "@requestXML", ",", "@requestHeaders", ")", "@responseCode", "=", "response", ".", "code", "@responseXML", "=", "response", ".", "body", "else", "@responseCode", ",", "@responseXML", "=", "@httpConnection", ".", "post", "(", "@requestURL", ",", "@requestXML", ",", "@requestHeaders", ")", "end", "end", "printResponse", "(", "@responseCode", ",", "@responseXML", ")", "if", "@printRequestsAndResponses", "if", "not", "isHTMLRequest", "processResponse", "(", "@responseXML", ")", "end", "@logger", ".", "logResponse", "(", "@lastError", ",", "@responseXML", ")", "if", "@logger", "fireDBChangeEvents", "rescue", "Net", "::", "HTTPBadResponse", "=>", "error", "@lastError", "=", "\"Bad HTTP Response: #{error}\"", "rescue", "Net", "::", "HTTPHeaderSyntaxError", "=>", "error", "@lastError", "=", "\"Bad HTTP header syntax: #{error}\"", "rescue", "StandardError", "=>", "error", "@lastError", "=", "\"Error processing #{api_Request} request: #{error}\"", "end", "@requestSucceeded", "=", "(", "@errcode", "==", "\"0\"", "and", "@lastError", "==", "\"\"", ")", "fire", "(", "@requestSucceeded", "?", "\"onRequestSucceeded\"", ":", "\"onRequestFailed\"", ")", "if", "@stopOnError", "and", "!", "@requestSucceeded", "raise", "@lastError", "end", "end" ]
Sends requests to QuickBase and processes the reponses.
[ "Sends", "requests", "to", "QuickBase", "and", "processes", "the", "reponses", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L203-L276
4,082
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.prependAPI?
def prependAPI?( request ) ret = true ret = false if request.to_s.include?("API_") or request.to_s.include?("QBIS_") ret end
ruby
def prependAPI?( request ) ret = true ret = false if request.to_s.include?("API_") or request.to_s.include?("QBIS_") ret end
[ "def", "prependAPI?", "(", "request", ")", "ret", "=", "true", "ret", "=", "false", "if", "request", ".", "to_s", ".", "include?", "(", "\"API_\"", ")", "or", "request", ".", "to_s", ".", "include?", "(", "\"QBIS_\"", ")", "ret", "end" ]
Returns whether to prepend 'API_' to request string
[ "Returns", "whether", "to", "prepend", "API_", "to", "request", "string" ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L319-L323
4,083
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.toggleTraceInfo
def toggleTraceInfo( showTrace ) if showTrace # this will print a very large amount of stuff set_trace_func proc { |event, file, line, id, binding, classname| printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname } if block_given? yield set_trace_func nil end else set_trace_func nil if block_given? yield set_trace_func proc { |event, file, line, id, binding, classname| printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname } end end self end
ruby
def toggleTraceInfo( showTrace ) if showTrace # this will print a very large amount of stuff set_trace_func proc { |event, file, line, id, binding, classname| printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname } if block_given? yield set_trace_func nil end else set_trace_func nil if block_given? yield set_trace_func proc { |event, file, line, id, binding, classname| printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname } end end self end
[ "def", "toggleTraceInfo", "(", "showTrace", ")", "if", "showTrace", "# this will print a very large amount of stuff\r", "set_trace_func", "proc", "{", "|", "event", ",", "file", ",", "line", ",", "id", ",", "binding", ",", "classname", "|", "printf", "\"%8s %s:%-2d %10s %8s\\n\"", ",", "event", ",", "file", ",", "line", ",", "id", ",", "classname", "}", "if", "block_given?", "yield", "set_trace_func", "nil", "end", "else", "set_trace_func", "nil", "if", "block_given?", "yield", "set_trace_func", "proc", "{", "|", "event", ",", "file", ",", "line", ",", "id", ",", "binding", ",", "classname", "|", "printf", "\"%8s %s:%-2d %10s %8s\\n\"", ",", "event", ",", "file", ",", "line", ",", "id", ",", "classname", "}", "end", "end", "self", "end" ]
Turns program stack tracing on or off. If followed by a block, the tracing will be toggled on or off at the end of the block.
[ "Turns", "program", "stack", "tracing", "on", "or", "off", ".", "If", "followed", "by", "a", "block", "the", "tracing", "will", "be", "toggled", "on", "or", "off", "at", "the", "end", "of", "the", "block", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L327-L343
4,084
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getErrorInfoFromResponse
def getErrorInfoFromResponse if @responseXMLdoc errcode = getResponseValue( :errcode ) @errcode = errcode ? errcode : "" errtext = getResponseValue( :errtext ) @errtext = errtext ? errtext : "" errdetail = getResponseValue( :errdetail ) @errdetail = errdetail ? errdetail : "" if @errcode != "0" @lastError = "Error code: #{@errcode} text: #{@errtext}: detail: #{@errdetail}" end end @lastError end
ruby
def getErrorInfoFromResponse if @responseXMLdoc errcode = getResponseValue( :errcode ) @errcode = errcode ? errcode : "" errtext = getResponseValue( :errtext ) @errtext = errtext ? errtext : "" errdetail = getResponseValue( :errdetail ) @errdetail = errdetail ? errdetail : "" if @errcode != "0" @lastError = "Error code: #{@errcode} text: #{@errtext}: detail: #{@errdetail}" end end @lastError end
[ "def", "getErrorInfoFromResponse", "if", "@responseXMLdoc", "errcode", "=", "getResponseValue", "(", ":errcode", ")", "@errcode", "=", "errcode", "?", "errcode", ":", "\"\"", "errtext", "=", "getResponseValue", "(", ":errtext", ")", "@errtext", "=", "errtext", "?", "errtext", ":", "\"\"", "errdetail", "=", "getResponseValue", "(", ":errdetail", ")", "@errdetail", "=", "errdetail", "?", "errdetail", ":", "\"\"", "if", "@errcode", "!=", "\"0\"", "@lastError", "=", "\"Error code: #{@errcode} text: #{@errtext}: detail: #{@errdetail}\"", "end", "end", "@lastError", "end" ]
Extracts error info from XML responses returned by QuickBase.
[ "Extracts", "error", "info", "from", "XML", "responses", "returned", "by", "QuickBase", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L386-L399
4,085
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.parseResponseXML
def parseResponseXML( xml ) if xml xml.gsub!( "\r", "" ) if @ignoreCR and @ignoreCR == true xml.gsub!( "\n", "" ) if @ignoreLF and @ignoreLF == true xml.gsub!( "\t", "" ) if @ignoreTAB and @ignoreTAB == true xml.gsub!( "<BR/>", "&lt;BR/&gt;" ) if @escapeBR @qdbapi = @responseXMLdoc = REXML::Document.new( xml ) end end
ruby
def parseResponseXML( xml ) if xml xml.gsub!( "\r", "" ) if @ignoreCR and @ignoreCR == true xml.gsub!( "\n", "" ) if @ignoreLF and @ignoreLF == true xml.gsub!( "\t", "" ) if @ignoreTAB and @ignoreTAB == true xml.gsub!( "<BR/>", "&lt;BR/&gt;" ) if @escapeBR @qdbapi = @responseXMLdoc = REXML::Document.new( xml ) end end
[ "def", "parseResponseXML", "(", "xml", ")", "if", "xml", "xml", ".", "gsub!", "(", "\"\\r\"", ",", "\"\"", ")", "if", "@ignoreCR", "and", "@ignoreCR", "==", "true", "xml", ".", "gsub!", "(", "\"\\n\"", ",", "\"\"", ")", "if", "@ignoreLF", "and", "@ignoreLF", "==", "true", "xml", ".", "gsub!", "(", "\"\\t\"", ",", "\"\"", ")", "if", "@ignoreTAB", "and", "@ignoreTAB", "==", "true", "xml", ".", "gsub!", "(", "\"<BR/>\"", ",", "\"&lt;BR/&gt;\"", ")", "if", "@escapeBR", "@qdbapi", "=", "@responseXMLdoc", "=", "REXML", "::", "Document", ".", "new", "(", "xml", ")", "end", "end" ]
Called by processResponse to put the XML from QuickBase into a DOM tree using the REXML module that comes with Ruby.
[ "Called", "by", "processResponse", "to", "put", "the", "XML", "from", "QuickBase", "into", "a", "DOM", "tree", "using", "the", "REXML", "module", "that", "comes", "with", "Ruby", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L403-L411
4,086
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getResponseValue
def getResponseValue( field ) @fieldValue = nil if field and @responseXMLdoc @fieldValue = @responseXMLdoc.root.elements[ field.to_s ] @fieldValue = fieldValue.text if fieldValue and fieldValue.has_text? end @fieldValue end
ruby
def getResponseValue( field ) @fieldValue = nil if field and @responseXMLdoc @fieldValue = @responseXMLdoc.root.elements[ field.to_s ] @fieldValue = fieldValue.text if fieldValue and fieldValue.has_text? end @fieldValue end
[ "def", "getResponseValue", "(", "field", ")", "@fieldValue", "=", "nil", "if", "field", "and", "@responseXMLdoc", "@fieldValue", "=", "@responseXMLdoc", ".", "root", ".", "elements", "[", "field", ".", "to_s", "]", "@fieldValue", "=", "fieldValue", ".", "text", "if", "fieldValue", "and", "fieldValue", ".", "has_text?", "end", "@fieldValue", "end" ]
Gets the value for a specific field at the top level of the XML returned from QuickBase.
[ "Gets", "the", "value", "for", "a", "specific", "field", "at", "the", "top", "level", "of", "the", "XML", "returned", "from", "QuickBase", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L415-L422
4,087
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getResponsePathValues
def getResponsePathValues( path ) @fieldValue = "" e = getResponseElements( path ) e.each{ |e| @fieldValue << e.text if e and e.is_a?( REXML::Element ) and e.has_text? } @fieldValue end
ruby
def getResponsePathValues( path ) @fieldValue = "" e = getResponseElements( path ) e.each{ |e| @fieldValue << e.text if e and e.is_a?( REXML::Element ) and e.has_text? } @fieldValue end
[ "def", "getResponsePathValues", "(", "path", ")", "@fieldValue", "=", "\"\"", "e", "=", "getResponseElements", "(", "path", ")", "e", ".", "each", "{", "|", "e", "|", "@fieldValue", "<<", "e", ".", "text", "if", "e", "and", "e", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "e", ".", "has_text?", "}", "@fieldValue", "end" ]
Gets an array of values at an Xpath in the XML from QuickBase.
[ "Gets", "an", "array", "of", "values", "at", "an", "Xpath", "in", "the", "XML", "from", "QuickBase", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L435-L440
4,088
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getResponsePathValueByDBName
def getResponsePathValueByDBName ( path, dbName) @fieldValue = "" if path and @responseXMLdoc e = @responseXMLdoc.root.elements[ path.to_s ] end e.each { |e| if e and e.is_a?( REXML::Element ) and e.dbinfo.dbname == dbName return e.dbinfo.dbid end } @fieldValue end
ruby
def getResponsePathValueByDBName ( path, dbName) @fieldValue = "" if path and @responseXMLdoc e = @responseXMLdoc.root.elements[ path.to_s ] end e.each { |e| if e and e.is_a?( REXML::Element ) and e.dbinfo.dbname == dbName return e.dbinfo.dbid end } @fieldValue end
[ "def", "getResponsePathValueByDBName", "(", "path", ",", "dbName", ")", "@fieldValue", "=", "\"\"", "if", "path", "and", "@responseXMLdoc", "e", "=", "@responseXMLdoc", ".", "root", ".", "elements", "[", "path", ".", "to_s", "]", "end", "e", ".", "each", "{", "|", "e", "|", "if", "e", "and", "e", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "e", ".", "dbinfo", ".", "dbname", "==", "dbName", "return", "e", ".", "dbinfo", ".", "dbid", "end", "}", "@fieldValue", "end" ]
Gets a dbid at an Xpath in the XML from specified dbName of Quickbase
[ "Gets", "a", "dbid", "at", "an", "Xpath", "in", "the", "XML", "from", "specified", "dbName", "of", "Quickbase" ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L443-L454
4,089
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getAttributeString
def getAttributeString( element ) attributes = "" if element.is_a?( REXML::Element ) and element.has_attributes? attributes = "(" element.attributes.each { |name,value| attributes << "#{name}=#{value} " } attributes << ")" end attributes end
ruby
def getAttributeString( element ) attributes = "" if element.is_a?( REXML::Element ) and element.has_attributes? attributes = "(" element.attributes.each { |name,value| attributes << "#{name}=#{value} " } attributes << ")" end attributes end
[ "def", "getAttributeString", "(", "element", ")", "attributes", "=", "\"\"", "if", "element", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "element", ".", "has_attributes?", "attributes", "=", "\"(\"", "element", ".", "attributes", ".", "each", "{", "|", "name", ",", "value", "|", "attributes", "<<", "\"#{name}=#{value} \"", "}", "attributes", "<<", "\")\"", "end", "attributes", "end" ]
Returns a string representation of the attributes of an XML element.
[ "Returns", "a", "string", "representation", "of", "the", "attributes", "of", "an", "XML", "element", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L472-L482
4,090
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.lookupFieldName
def lookupFieldName( element ) name = "" if element and element.is_a?( REXML::Element ) name = element.name if element.name == "f" and @fields fid = element.attributes[ "id" ] field = lookupField( fid ) if fid label = field.elements[ "label" ] if field name = label.text if label end end name end
ruby
def lookupFieldName( element ) name = "" if element and element.is_a?( REXML::Element ) name = element.name if element.name == "f" and @fields fid = element.attributes[ "id" ] field = lookupField( fid ) if fid label = field.elements[ "label" ] if field name = label.text if label end end name end
[ "def", "lookupFieldName", "(", "element", ")", "name", "=", "\"\"", "if", "element", "and", "element", ".", "is_a?", "(", "REXML", "::", "Element", ")", "name", "=", "element", ".", "name", "if", "element", ".", "name", "==", "\"f\"", "and", "@fields", "fid", "=", "element", ".", "attributes", "[", "\"id\"", "]", "field", "=", "lookupField", "(", "fid", ")", "if", "fid", "label", "=", "field", ".", "elements", "[", "\"label\"", "]", "if", "field", "name", "=", "label", ".", "text", "if", "label", "end", "end", "name", "end" ]
Returns the name of field given an "fid" XML element.
[ "Returns", "the", "name", "of", "field", "given", "an", "fid", "XML", "element", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L498-L510
4,091
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.lookupFieldType
def lookupFieldType( element ) type = "" if element and element.is_a?( REXML::Element ) if element.name == "f" and @fields fid = element.attributes[ "id" ] field = lookupField( fid ) if fid type = field.attributes[ "field_type" ] if field end end type end
ruby
def lookupFieldType( element ) type = "" if element and element.is_a?( REXML::Element ) if element.name == "f" and @fields fid = element.attributes[ "id" ] field = lookupField( fid ) if fid type = field.attributes[ "field_type" ] if field end end type end
[ "def", "lookupFieldType", "(", "element", ")", "type", "=", "\"\"", "if", "element", "and", "element", ".", "is_a?", "(", "REXML", "::", "Element", ")", "if", "element", ".", "name", "==", "\"f\"", "and", "@fields", "fid", "=", "element", ".", "attributes", "[", "\"id\"", "]", "field", "=", "lookupField", "(", "fid", ")", "if", "fid", "type", "=", "field", ".", "attributes", "[", "\"field_type\"", "]", "if", "field", "end", "end", "type", "end" ]
Returns a QuickBase field type, given an XML "fid" element.
[ "Returns", "a", "QuickBase", "field", "type", "given", "an", "XML", "fid", "element", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L513-L523
4,092
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.lookupFieldPropertyByName
def lookupFieldPropertyByName( fieldName, property ) theproperty = nil if isValidFieldProperty?(property) fid = lookupFieldIDByName( fieldName ) field = lookupField( fid ) if fid theproperty = field.elements[ property ] if field theproperty = theproperty.text if theproperty and theproperty.has_text? end theproperty end
ruby
def lookupFieldPropertyByName( fieldName, property ) theproperty = nil if isValidFieldProperty?(property) fid = lookupFieldIDByName( fieldName ) field = lookupField( fid ) if fid theproperty = field.elements[ property ] if field theproperty = theproperty.text if theproperty and theproperty.has_text? end theproperty end
[ "def", "lookupFieldPropertyByName", "(", "fieldName", ",", "property", ")", "theproperty", "=", "nil", "if", "isValidFieldProperty?", "(", "property", ")", "fid", "=", "lookupFieldIDByName", "(", "fieldName", ")", "field", "=", "lookupField", "(", "fid", ")", "if", "fid", "theproperty", "=", "field", ".", "elements", "[", "property", "]", "if", "field", "theproperty", "=", "theproperty", ".", "text", "if", "theproperty", "and", "theproperty", ".", "has_text?", "end", "theproperty", "end" ]
Returns the value of a field property, or nil.
[ "Returns", "the", "value", "of", "a", "field", "property", "or", "nil", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L531-L540
4,093
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.isRecordidField?
def isRecordidField?( fid ) fields = lookupFieldsByType( "recordid" ) (fields and fields.last and fields.last.attributes[ "id" ] == fid) end
ruby
def isRecordidField?( fid ) fields = lookupFieldsByType( "recordid" ) (fields and fields.last and fields.last.attributes[ "id" ] == fid) end
[ "def", "isRecordidField?", "(", "fid", ")", "fields", "=", "lookupFieldsByType", "(", "\"recordid\"", ")", "(", "fields", "and", "fields", ".", "last", "and", "fields", ".", "last", ".", "attributes", "[", "\"id\"", "]", "==", "fid", ")", "end" ]
Returns whether a field ID is the ID for the key field in a QuickBase table.
[ "Returns", "whether", "a", "field", "ID", "is", "the", "ID", "for", "the", "key", "field", "in", "a", "QuickBase", "table", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L555-L558
4,094
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.formatFieldValue
def formatFieldValue( value, type, options = nil ) if value and type case type when "date" value = formatDate( value ) when "date / time","timestamp" value = formatDate( value, "%m-%d-%Y %I:%M %p" ) when "timeofday" value = formatTimeOfDay( value, options ) when "duration" value = formatDuration( value, options ) when "currency" value = formatCurrency( value, options ) when "percent" value = formatPercent( value, options ) end end value end
ruby
def formatFieldValue( value, type, options = nil ) if value and type case type when "date" value = formatDate( value ) when "date / time","timestamp" value = formatDate( value, "%m-%d-%Y %I:%M %p" ) when "timeofday" value = formatTimeOfDay( value, options ) when "duration" value = formatDuration( value, options ) when "currency" value = formatCurrency( value, options ) when "percent" value = formatPercent( value, options ) end end value end
[ "def", "formatFieldValue", "(", "value", ",", "type", ",", "options", "=", "nil", ")", "if", "value", "and", "type", "case", "type", "when", "\"date\"", "value", "=", "formatDate", "(", "value", ")", "when", "\"date / time\"", ",", "\"timestamp\"", "value", "=", "formatDate", "(", "value", ",", "\"%m-%d-%Y %I:%M %p\"", ")", "when", "\"timeofday\"", "value", "=", "formatTimeOfDay", "(", "value", ",", "options", ")", "when", "\"duration\"", "value", "=", "formatDuration", "(", "value", ",", "options", ")", "when", "\"currency\"", "value", "=", "formatCurrency", "(", "value", ",", "options", ")", "when", "\"percent\"", "value", "=", "formatPercent", "(", "value", ",", "options", ")", "end", "end", "value", "end" ]
Returns a human-readable string representation of a QuickBase field value. Also required for subsequent requests to QuickBase.
[ "Returns", "a", "human", "-", "readable", "string", "representation", "of", "a", "QuickBase", "field", "value", ".", "Also", "required", "for", "subsequent", "requests", "to", "QuickBase", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L567-L585
4,095
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.findElementByAttributeValue
def findElementByAttributeValue( elements, attribute_name, attribute_value ) element = nil if elements if elements.is_a?( REXML::Element ) elements.each_element_with_attribute( attribute_name, attribute_value ) { |e| element = e } elsif elements.is_a?( Array ) elements.each{ |e| if e.is_a?( REXML::Element ) and e.attributes[ attribute_name ] == attribute_value element = e end } end end element end
ruby
def findElementByAttributeValue( elements, attribute_name, attribute_value ) element = nil if elements if elements.is_a?( REXML::Element ) elements.each_element_with_attribute( attribute_name, attribute_value ) { |e| element = e } elsif elements.is_a?( Array ) elements.each{ |e| if e.is_a?( REXML::Element ) and e.attributes[ attribute_name ] == attribute_value element = e end } end end element end
[ "def", "findElementByAttributeValue", "(", "elements", ",", "attribute_name", ",", "attribute_value", ")", "element", "=", "nil", "if", "elements", "if", "elements", ".", "is_a?", "(", "REXML", "::", "Element", ")", "elements", ".", "each_element_with_attribute", "(", "attribute_name", ",", "attribute_value", ")", "{", "|", "e", "|", "element", "=", "e", "}", "elsif", "elements", ".", "is_a?", "(", "Array", ")", "elements", ".", "each", "{", "|", "e", "|", "if", "e", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "e", ".", "attributes", "[", "attribute_name", "]", "==", "attribute_value", "element", "=", "e", "end", "}", "end", "end", "element", "end" ]
Returns the first XML sub-element with the specified attribute value.
[ "Returns", "the", "first", "XML", "sub", "-", "element", "with", "the", "specified", "attribute", "value", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L716-L730
4,096
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.findElementsByAttributeName
def findElementsByAttributeName( elements, attribute_name ) elementArray = [] if elements elements.each_element_with_attribute( attribute_name ) { |e| elementArray << e } end elementArray end
ruby
def findElementsByAttributeName( elements, attribute_name ) elementArray = [] if elements elements.each_element_with_attribute( attribute_name ) { |e| elementArray << e } end elementArray end
[ "def", "findElementsByAttributeName", "(", "elements", ",", "attribute_name", ")", "elementArray", "=", "[", "]", "if", "elements", "elements", ".", "each_element_with_attribute", "(", "attribute_name", ")", "{", "|", "e", "|", "elementArray", "<<", "e", "}", "end", "elementArray", "end" ]
Returns an array of XML sub-elements with the specified attribute name.
[ "Returns", "an", "array", "of", "XML", "sub", "-", "elements", "with", "the", "specified", "attribute", "name", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L750-L756
4,097
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.lookupFieldData
def lookupFieldData( fid ) @field_data = nil if @field_data_list @field_data_list.each{ |field| if field and field.is_a?( REXML::Element ) and field.has_elements? fieldid = field.elements[ "fid" ] if fieldid and fieldid.has_text? and fieldid.text == fid.to_s @field_data = field end end } end @field_data end
ruby
def lookupFieldData( fid ) @field_data = nil if @field_data_list @field_data_list.each{ |field| if field and field.is_a?( REXML::Element ) and field.has_elements? fieldid = field.elements[ "fid" ] if fieldid and fieldid.has_text? and fieldid.text == fid.to_s @field_data = field end end } end @field_data end
[ "def", "lookupFieldData", "(", "fid", ")", "@field_data", "=", "nil", "if", "@field_data_list", "@field_data_list", ".", "each", "{", "|", "field", "|", "if", "field", "and", "field", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "field", ".", "has_elements?", "fieldid", "=", "field", ".", "elements", "[", "\"fid\"", "]", "if", "fieldid", "and", "fieldid", ".", "has_text?", "and", "fieldid", ".", "text", "==", "fid", ".", "to_s", "@field_data", "=", "field", "end", "end", "}", "end", "@field_data", "end" ]
Returns the XML element for a field returned by a getRecordInfo call.
[ "Returns", "the", "XML", "element", "for", "a", "field", "returned", "by", "a", "getRecordInfo", "call", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L765-L778
4,098
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getFieldDataValue
def getFieldDataValue(fid) value = nil if @field_data_list field_data = lookupFieldData(fid) if field_data valueElement = field_data.elements[ "value" ] value = valueElement.text if valueElement.has_text? end end value end
ruby
def getFieldDataValue(fid) value = nil if @field_data_list field_data = lookupFieldData(fid) if field_data valueElement = field_data.elements[ "value" ] value = valueElement.text if valueElement.has_text? end end value end
[ "def", "getFieldDataValue", "(", "fid", ")", "value", "=", "nil", "if", "@field_data_list", "field_data", "=", "lookupFieldData", "(", "fid", ")", "if", "field_data", "valueElement", "=", "field_data", ".", "elements", "[", "\"value\"", "]", "value", "=", "valueElement", ".", "text", "if", "valueElement", ".", "has_text?", "end", "end", "value", "end" ]
Returns the value for a field returned by a getRecordInfo call.
[ "Returns", "the", "value", "for", "a", "field", "returned", "by", "a", "getRecordInfo", "call", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L781-L791
4,099
garethlatwork/quickbase_client
lib/QuickBaseClient.rb
QuickBase.Client.getFieldDataPrintableValue
def getFieldDataPrintableValue(fid) printable = nil if @field_data_list field_data = lookupFieldData(fid) if field_data printableElement = field_data.elements[ "printable" ] printable = printableElement.text if printableElement and printableElement.has_text? end end printable end
ruby
def getFieldDataPrintableValue(fid) printable = nil if @field_data_list field_data = lookupFieldData(fid) if field_data printableElement = field_data.elements[ "printable" ] printable = printableElement.text if printableElement and printableElement.has_text? end end printable end
[ "def", "getFieldDataPrintableValue", "(", "fid", ")", "printable", "=", "nil", "if", "@field_data_list", "field_data", "=", "lookupFieldData", "(", "fid", ")", "if", "field_data", "printableElement", "=", "field_data", ".", "elements", "[", "\"printable\"", "]", "printable", "=", "printableElement", ".", "text", "if", "printableElement", "and", "printableElement", ".", "has_text?", "end", "end", "printable", "end" ]
Returns the printable value for a field returned by a getRecordInfo call.
[ "Returns", "the", "printable", "value", "for", "a", "field", "returned", "by", "a", "getRecordInfo", "call", "." ]
13d754de1f22a466806c5a0da74b0ded26c23f05
https://github.com/garethlatwork/quickbase_client/blob/13d754de1f22a466806c5a0da74b0ded26c23f05/lib/QuickBaseClient.rb#L794-L804