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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
5,700
fulldecent/structured-acceptance-test
implementations/ruby/lib/finding.rb
StatModule.Finding.categories=
def categories=(categories) raise TypeException unless categories.is_a?(Array) categories.each { |item| raise TypeException unless Category.all.include?(item) raise DuplicateElementException if @categories.include?(item) @categories.push(item) } end
ruby
def categories=(categories) raise TypeException unless categories.is_a?(Array) categories.each { |item| raise TypeException unless Category.all.include?(item) raise DuplicateElementException if @categories.include?(item) @categories.push(item) } end
[ "def", "categories", "=", "(", "categories", ")", "raise", "TypeException", "unless", "categories", ".", "is_a?", "(", "Array", ")", "categories", ".", "each", "{", "|", "item", "|", "raise", "TypeException", "unless", "Category", ".", "all", ".", "include?", "(", "item", ")", "raise", "DuplicateElementException", "if", "@categories", ".", "include?", "(", "item", ")", "@categories", ".", "push", "(", "item", ")", "}", "end" ]
Set array of categories Params: +categories+:: array of StatModule::Category
[ "Set", "array", "of", "categories" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/finding.rb#L92-L99
5,701
fulldecent/structured-acceptance-test
implementations/ruby/lib/finding.rb
StatModule.Finding.print
def print(formatted = false) result = "#{rule}, #{description}" if formatted if failure result = "#{FORMATTING_BALL} #{result}".colorize(:red) else result = "#{FORMATTING_WARNING} #{result}".colorize(:yellow) end end result += "\n#{location.print}" unless location.nil? result += "\nRECOMMENDATION: #{recommendation}" unless recommendation.nil? result end
ruby
def print(formatted = false) result = "#{rule}, #{description}" if formatted if failure result = "#{FORMATTING_BALL} #{result}".colorize(:red) else result = "#{FORMATTING_WARNING} #{result}".colorize(:yellow) end end result += "\n#{location.print}" unless location.nil? result += "\nRECOMMENDATION: #{recommendation}" unless recommendation.nil? result end
[ "def", "print", "(", "formatted", "=", "false", ")", "result", "=", "\"#{rule}, #{description}\"", "if", "formatted", "if", "failure", "result", "=", "\"#{FORMATTING_BALL} #{result}\"", ".", "colorize", "(", ":red", ")", "else", "result", "=", "\"#{FORMATTING_WARNING} #{result}\"", ".", "colorize", "(", ":yellow", ")", "end", "end", "result", "+=", "\"\\n#{location.print}\"", "unless", "location", ".", "nil?", "result", "+=", "\"\\nRECOMMENDATION: #{recommendation}\"", "unless", "recommendation", ".", "nil?", "result", "end" ]
Get formatted information about findings Params: +formatted+:: indicate weather print boring or pretty colorful finding
[ "Get", "formatted", "information", "about", "findings" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/finding.rb#L181-L193
5,702
dennmart/wanikani-gem
lib/wanikani/critical_items.rb
Wanikani.CriticalItems.critical_items
def critical_items(percentage = 75) raise ArgumentError, "Percentage must be an Integer between 0 and 100" if !percentage.between?(0, 100) response = api_response("critical-items", percentage) return response["requested_information"] end
ruby
def critical_items(percentage = 75) raise ArgumentError, "Percentage must be an Integer between 0 and 100" if !percentage.between?(0, 100) response = api_response("critical-items", percentage) return response["requested_information"] end
[ "def", "critical_items", "(", "percentage", "=", "75", ")", "raise", "ArgumentError", ",", "\"Percentage must be an Integer between 0 and 100\"", "if", "!", "percentage", ".", "between?", "(", "0", ",", "100", ")", "response", "=", "api_response", "(", "\"critical-items\"", ",", "percentage", ")", "return", "response", "[", "\"requested_information\"", "]", "end" ]
Gets the user's current items under 'Critical Items'. @param percentage [Integer] the maximum percentage of correctness. @return [Array<Hash>] critical items and their related information.
[ "Gets", "the", "user", "s", "current", "items", "under", "Critical", "Items", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/critical_items.rb#L8-L12
5,703
rocky/rbx-trepanning
app/method.rb
Trepanning.Method.find_method_with_line
def find_method_with_line(cm, line) unless cm.kind_of?(Rubinius::CompiledMethod) return nil end lines = lines_of_method(cm) return cm if lines.member?(line) scope = cm.scope return nil unless scope and scope.current_script cm = scope.current_script.compiled_code lines = lines_of_method(cm) until lines.member?(line) do child = scope scope = scope.parent unless scope # child is the top-most scope. Search down from here. cm = child.current_script.compiled_code pair = locate_line(line, cm) ## pair = cm.locate_line(line) return pair ? pair[0] : nil end cm = scope.current_script.compiled_code lines = lines_of_method(cm) end return cm end
ruby
def find_method_with_line(cm, line) unless cm.kind_of?(Rubinius::CompiledMethod) return nil end lines = lines_of_method(cm) return cm if lines.member?(line) scope = cm.scope return nil unless scope and scope.current_script cm = scope.current_script.compiled_code lines = lines_of_method(cm) until lines.member?(line) do child = scope scope = scope.parent unless scope # child is the top-most scope. Search down from here. cm = child.current_script.compiled_code pair = locate_line(line, cm) ## pair = cm.locate_line(line) return pair ? pair[0] : nil end cm = scope.current_script.compiled_code lines = lines_of_method(cm) end return cm end
[ "def", "find_method_with_line", "(", "cm", ",", "line", ")", "unless", "cm", ".", "kind_of?", "(", "Rubinius", "::", "CompiledMethod", ")", "return", "nil", "end", "lines", "=", "lines_of_method", "(", "cm", ")", "return", "cm", "if", "lines", ".", "member?", "(", "line", ")", "scope", "=", "cm", ".", "scope", "return", "nil", "unless", "scope", "and", "scope", ".", "current_script", "cm", "=", "scope", ".", "current_script", ".", "compiled_code", "lines", "=", "lines_of_method", "(", "cm", ")", "until", "lines", ".", "member?", "(", "line", ")", "do", "child", "=", "scope", "scope", "=", "scope", ".", "parent", "unless", "scope", "# child is the top-most scope. Search down from here.", "cm", "=", "child", ".", "current_script", ".", "compiled_code", "pair", "=", "locate_line", "(", "line", ",", "cm", ")", "## pair = cm.locate_line(line)", "return", "pair", "?", "pair", "[", "0", "]", ":", "nil", "end", "cm", "=", "scope", ".", "current_script", ".", "compiled_code", "lines", "=", "lines_of_method", "(", "cm", ")", "end", "return", "cm", "end" ]
Returns a CompiledMethod for the specified line. We search the current method +meth+ and then up the parent scope. If we hit the top and we can't find +line+ that way, then we reverse the search from the top and search down. This will add all siblings of ancestors of +meth+.
[ "Returns", "a", "CompiledMethod", "for", "the", "specified", "line", ".", "We", "search", "the", "current", "method", "+", "meth", "+", "and", "then", "up", "the", "parent", "scope", ".", "If", "we", "hit", "the", "top", "and", "we", "can", "t", "find", "+", "line", "+", "that", "way", "then", "we", "reverse", "the", "search", "from", "the", "top", "and", "search", "down", ".", "This", "will", "add", "all", "siblings", "of", "ancestors", "of", "+", "meth", "+", "." ]
192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1
https://github.com/rocky/rbx-trepanning/blob/192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1/app/method.rb#L78-L103
5,704
cyberarm/rewrite-gameoverseer
lib/gameoverseer/channels/channel_manager.rb
GameOverseer.ChannelManager.register_channel
def register_channel(channel, service) _channel = channel.downcase unless @channels[_channel] @channels[_channel] = service GameOverseer::Console.log("ChannelManager> mapped '#{_channel}' to '#{service.class}'.") else raise "Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it." end end
ruby
def register_channel(channel, service) _channel = channel.downcase unless @channels[_channel] @channels[_channel] = service GameOverseer::Console.log("ChannelManager> mapped '#{_channel}' to '#{service.class}'.") else raise "Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it." end end
[ "def", "register_channel", "(", "channel", ",", "service", ")", "_channel", "=", "channel", ".", "downcase", "unless", "@channels", "[", "_channel", "]", "@channels", "[", "_channel", "]", "=", "service", "GameOverseer", "::", "Console", ".", "log", "(", "\"ChannelManager> mapped '#{_channel}' to '#{service.class}'.\"", ")", "else", "raise", "\"Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it.\"", "end", "end" ]
Enables a service to subscribe to a channel @param channel [String] @param service [Service]
[ "Enables", "a", "service", "to", "subscribe", "to", "a", "channel" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/channels/channel_manager.rb#L18-L26
5,705
nysa/ruby-opencnam
lib/opencnam/client.rb
Opencnam.Client.phone
def phone(phone_number, options = {}) # Build query string options = { :account_sid => account_sid, :auth_token => auth_token, :format => 'text', }.merge(options) options[:format] = options[:format].to_s.strip.downcase # Check for supported format unless %w(text json).include? options[:format] raise ArgumentError.new "Unsupported format: #{options[:format]}" end # Send request http = Net::HTTP.new(API_HOST, (use_ssl? ? '443' : '80')) http.use_ssl = true if use_ssl? query = URI.encode_www_form(options) res = http.request_get("/v2/phone/#{phone_number.strip}?#{query}") # Look up was unsuccessful raise OpencnamError.new res.message unless res.kind_of? Net::HTTPOK return res.body if options[:format] == 'text' return parse_json(res.body) if options[:format] == 'json' end
ruby
def phone(phone_number, options = {}) # Build query string options = { :account_sid => account_sid, :auth_token => auth_token, :format => 'text', }.merge(options) options[:format] = options[:format].to_s.strip.downcase # Check for supported format unless %w(text json).include? options[:format] raise ArgumentError.new "Unsupported format: #{options[:format]}" end # Send request http = Net::HTTP.new(API_HOST, (use_ssl? ? '443' : '80')) http.use_ssl = true if use_ssl? query = URI.encode_www_form(options) res = http.request_get("/v2/phone/#{phone_number.strip}?#{query}") # Look up was unsuccessful raise OpencnamError.new res.message unless res.kind_of? Net::HTTPOK return res.body if options[:format] == 'text' return parse_json(res.body) if options[:format] == 'json' end
[ "def", "phone", "(", "phone_number", ",", "options", "=", "{", "}", ")", "# Build query string", "options", "=", "{", ":account_sid", "=>", "account_sid", ",", ":auth_token", "=>", "auth_token", ",", ":format", "=>", "'text'", ",", "}", ".", "merge", "(", "options", ")", "options", "[", ":format", "]", "=", "options", "[", ":format", "]", ".", "to_s", ".", "strip", ".", "downcase", "# Check for supported format", "unless", "%w(", "text", "json", ")", ".", "include?", "options", "[", ":format", "]", "raise", "ArgumentError", ".", "new", "\"Unsupported format: #{options[:format]}\"", "end", "# Send request", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "API_HOST", ",", "(", "use_ssl?", "?", "'443'", ":", "'80'", ")", ")", "http", ".", "use_ssl", "=", "true", "if", "use_ssl?", "query", "=", "URI", ".", "encode_www_form", "(", "options", ")", "res", "=", "http", ".", "request_get", "(", "\"/v2/phone/#{phone_number.strip}?#{query}\"", ")", "# Look up was unsuccessful", "raise", "OpencnamError", ".", "new", "res", ".", "message", "unless", "res", ".", "kind_of?", "Net", "::", "HTTPOK", "return", "res", ".", "body", "if", "options", "[", ":format", "]", "==", "'text'", "return", "parse_json", "(", "res", ".", "body", ")", "if", "options", "[", ":format", "]", "==", "'json'", "end" ]
Look up a phone number and return the caller's name. @param [String] phone_number The phone number to look up @param [Hash] options Described below @option options [String] :account_sid Specify a different OpenCNAM account_sid @option options [String] :auth_token Specify a different OpenCNAM auth_token @option options [String, Symbol] :format (:text) The format to retrieve, can be :text or :json @return [String, Hash] the phone number owner's name if :format is :string, or a Hash of additional fields from OpenCNAM if :format is :json (:created, :updated, :name, :price, :uri, and :number)
[ "Look", "up", "a", "phone", "number", "and", "return", "the", "caller", "s", "name", "." ]
7c9e62f6efc59466ab307977bc04070d19c4cadf
https://github.com/nysa/ruby-opencnam/blob/7c9e62f6efc59466ab307977bc04070d19c4cadf/lib/opencnam/client.rb#L51-L76
5,706
betterplace/spell_number
lib/spell_number/speller.rb
SpellNumber.Speller.two_digit_number
def two_digit_number(number, combined = false) words = combined ? simple_number_to_words_combined(number) : simple_number_to_words(number) return words if(words != 'not_found') rest = number % 10 format = "spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}" first_digit = simple_number_to_words(number - rest) second_digit = simple_number_to_words_combined(rest) I18n.t(format, :locale => @options[:locale], :first_digit => first_digit, :second_digit => second_digit) end
ruby
def two_digit_number(number, combined = false) words = combined ? simple_number_to_words_combined(number) : simple_number_to_words(number) return words if(words != 'not_found') rest = number % 10 format = "spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}" first_digit = simple_number_to_words(number - rest) second_digit = simple_number_to_words_combined(rest) I18n.t(format, :locale => @options[:locale], :first_digit => first_digit, :second_digit => second_digit) end
[ "def", "two_digit_number", "(", "number", ",", "combined", "=", "false", ")", "words", "=", "combined", "?", "simple_number_to_words_combined", "(", "number", ")", ":", "simple_number_to_words", "(", "number", ")", "return", "words", "if", "(", "words", "!=", "'not_found'", ")", "rest", "=", "number", "%", "10", "format", "=", "\"spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}\"", "first_digit", "=", "simple_number_to_words", "(", "number", "-", "rest", ")", "second_digit", "=", "simple_number_to_words_combined", "(", "rest", ")", "I18n", ".", "t", "(", "format", ",", ":locale", "=>", "@options", "[", ":locale", "]", ",", ":first_digit", "=>", "first_digit", ",", ":second_digit", "=>", "second_digit", ")", "end" ]
Transforms a two-digit number from 0 to 99
[ "Transforms", "a", "two", "-", "digit", "number", "from", "0", "to", "99" ]
3dbe6208f365ae5bd848392d1fda134874425c8c
https://github.com/betterplace/spell_number/blob/3dbe6208f365ae5bd848392d1fda134874425c8c/lib/spell_number/speller.rb#L54-L63
5,707
betterplace/spell_number
lib/spell_number/speller.rb
SpellNumber.Speller.simple_number_to_words_combined
def simple_number_to_words_combined(number) words = I18n.t("spell_number.numbers.number_#{number}_combined", :locale => @options[:locale], :default => 'not_found') words = simple_number_to_words(number) if(words == 'not_found') words end
ruby
def simple_number_to_words_combined(number) words = I18n.t("spell_number.numbers.number_#{number}_combined", :locale => @options[:locale], :default => 'not_found') words = simple_number_to_words(number) if(words == 'not_found') words end
[ "def", "simple_number_to_words_combined", "(", "number", ")", "words", "=", "I18n", ".", "t", "(", "\"spell_number.numbers.number_#{number}_combined\"", ",", ":locale", "=>", "@options", "[", ":locale", "]", ",", ":default", "=>", "'not_found'", ")", "words", "=", "simple_number_to_words", "(", "number", ")", "if", "(", "words", "==", "'not_found'", ")", "words", "end" ]
Returns the "combined" number if it exists in the file, otherwise it will return the simple_number_to_words
[ "Returns", "the", "combined", "number", "if", "it", "exists", "in", "the", "file", "otherwise", "it", "will", "return", "the", "simple_number_to_words" ]
3dbe6208f365ae5bd848392d1fda134874425c8c
https://github.com/betterplace/spell_number/blob/3dbe6208f365ae5bd848392d1fda134874425c8c/lib/spell_number/speller.rb#L67-L71
5,708
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.combine_pdfs
def combine_pdfs(combine_pdfs_data, opts = {}) data, _status_code, _headers = combine_pdfs_with_http_info(combine_pdfs_data, opts) data end
ruby
def combine_pdfs(combine_pdfs_data, opts = {}) data, _status_code, _headers = combine_pdfs_with_http_info(combine_pdfs_data, opts) data end
[ "def", "combine_pdfs", "(", "combine_pdfs_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "combine_pdfs_with_http_info", "(", "combine_pdfs_data", ",", "opts", ")", "data", "end" ]
Merge submission PDFs, template PDFs, or custom files @param combine_pdfs_data @param [Hash] opts the optional parameters @return [CreateCombinedSubmissionResponse]
[ "Merge", "submission", "PDFs", "template", "PDFs", "or", "custom", "files" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L138-L141
5,709
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.combine_submissions
def combine_submissions(combined_submission_data, opts = {}) data, _status_code, _headers = combine_submissions_with_http_info(combined_submission_data, opts) data end
ruby
def combine_submissions(combined_submission_data, opts = {}) data, _status_code, _headers = combine_submissions_with_http_info(combined_submission_data, opts) data end
[ "def", "combine_submissions", "(", "combined_submission_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "combine_submissions_with_http_info", "(", "combined_submission_data", ",", "opts", ")", "data", "end" ]
Merge generated PDFs together @param combined_submission_data @param [Hash] opts the optional parameters @return [CreateCombinedSubmissionResponse]
[ "Merge", "generated", "PDFs", "together" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L191-L194
5,710
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.create_custom_file_from_upload
def create_custom_file_from_upload(create_custom_file_data, opts = {}) data, _status_code, _headers = create_custom_file_from_upload_with_http_info(create_custom_file_data, opts) data end
ruby
def create_custom_file_from_upload(create_custom_file_data, opts = {}) data, _status_code, _headers = create_custom_file_from_upload_with_http_info(create_custom_file_data, opts) data end
[ "def", "create_custom_file_from_upload", "(", "create_custom_file_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_custom_file_from_upload_with_http_info", "(", "create_custom_file_data", ",", "opts", ")", "data", "end" ]
Create a new custom file from a cached presign upload @param create_custom_file_data @param [Hash] opts the optional parameters @return [CreateCustomFileResponse]
[ "Create", "a", "new", "custom", "file", "from", "a", "cached", "presign", "upload" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L244-L247
5,711
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.create_data_request_token
def create_data_request_token(data_request_id, opts = {}) data, _status_code, _headers = create_data_request_token_with_http_info(data_request_id, opts) data end
ruby
def create_data_request_token(data_request_id, opts = {}) data, _status_code, _headers = create_data_request_token_with_http_info(data_request_id, opts) data end
[ "def", "create_data_request_token", "(", "data_request_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_data_request_token_with_http_info", "(", "data_request_id", ",", "opts", ")", "data", "end" ]
Creates a new data request token for form authentication @param data_request_id @param [Hash] opts the optional parameters @return [CreateSubmissionDataRequestTokenResponse]
[ "Creates", "a", "new", "data", "request", "token", "for", "form", "authentication" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L297-L300
5,712
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.create_template_from_upload
def create_template_from_upload(create_template_data, opts = {}) data, _status_code, _headers = create_template_from_upload_with_http_info(create_template_data, opts) data end
ruby
def create_template_from_upload(create_template_data, opts = {}) data, _status_code, _headers = create_template_from_upload_with_http_info(create_template_data, opts) data end
[ "def", "create_template_from_upload", "(", "create_template_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_template_from_upload_with_http_info", "(", "create_template_data", ",", "opts", ")", "data", "end" ]
Create a new PDF template from a cached presign upload @param create_template_data @param [Hash] opts the optional parameters @return [PendingTemplate]
[ "Create", "a", "new", "PDF", "template", "from", "a", "cached", "presign", "upload" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L409-L412
5,713
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.expire_combined_submission
def expire_combined_submission(combined_submission_id, opts = {}) data, _status_code, _headers = expire_combined_submission_with_http_info(combined_submission_id, opts) data end
ruby
def expire_combined_submission(combined_submission_id, opts = {}) data, _status_code, _headers = expire_combined_submission_with_http_info(combined_submission_id, opts) data end
[ "def", "expire_combined_submission", "(", "combined_submission_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "expire_combined_submission_with_http_info", "(", "combined_submission_id", ",", "opts", ")", "data", "end" ]
Expire a combined submission @param combined_submission_id @param [Hash] opts the optional parameters @return [CombinedSubmission]
[ "Expire", "a", "combined", "submission" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L462-L465
5,714
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.expire_submission
def expire_submission(submission_id, opts = {}) data, _status_code, _headers = expire_submission_with_http_info(submission_id, opts) data end
ruby
def expire_submission(submission_id, opts = {}) data, _status_code, _headers = expire_submission_with_http_info(submission_id, opts) data end
[ "def", "expire_submission", "(", "submission_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "expire_submission_with_http_info", "(", "submission_id", ",", "opts", ")", "data", "end" ]
Expire a PDF submission @param submission_id @param [Hash] opts the optional parameters @return [Submission]
[ "Expire", "a", "PDF", "submission" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L513-L516
5,715
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.generate_pdf
def generate_pdf(template_id, submission_data, opts = {}) data, _status_code, _headers = generate_pdf_with_http_info(template_id, submission_data, opts) data end
ruby
def generate_pdf(template_id, submission_data, opts = {}) data, _status_code, _headers = generate_pdf_with_http_info(template_id, submission_data, opts) data end
[ "def", "generate_pdf", "(", "template_id", ",", "submission_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "generate_pdf_with_http_info", "(", "template_id", ",", "submission_data", ",", "opts", ")", "data", "end" ]
Generates a new PDF @param template_id @param submission_data @param [Hash] opts the optional parameters @return [CreateSubmissionResponse]
[ "Generates", "a", "new", "PDF" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L565-L568
5,716
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_data_request
def get_data_request(data_request_id, opts = {}) data, _status_code, _headers = get_data_request_with_http_info(data_request_id, opts) data end
ruby
def get_data_request(data_request_id, opts = {}) data, _status_code, _headers = get_data_request_with_http_info(data_request_id, opts) data end
[ "def", "get_data_request", "(", "data_request_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_data_request_with_http_info", "(", "data_request_id", ",", "opts", ")", "data", "end" ]
Look up a submission data request @param data_request_id @param [Hash] opts the optional parameters @return [SubmissionDataRequest]
[ "Look", "up", "a", "submission", "data", "request" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L674-L677
5,717
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_submission
def get_submission(submission_id, opts = {}) data, _status_code, _headers = get_submission_with_http_info(submission_id, opts) data end
ruby
def get_submission(submission_id, opts = {}) data, _status_code, _headers = get_submission_with_http_info(submission_id, opts) data end
[ "def", "get_submission", "(", "submission_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_submission_with_http_info", "(", "submission_id", ",", "opts", ")", "data", "end" ]
Check the status of a PDF @param submission_id @param [Hash] opts the optional parameters @option opts [BOOLEAN] :include_data @return [Submission]
[ "Check", "the", "status", "of", "a", "PDF" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L771-L774
5,718
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_submission_batch
def get_submission_batch(submission_batch_id, opts = {}) data, _status_code, _headers = get_submission_batch_with_http_info(submission_batch_id, opts) data end
ruby
def get_submission_batch(submission_batch_id, opts = {}) data, _status_code, _headers = get_submission_batch_with_http_info(submission_batch_id, opts) data end
[ "def", "get_submission_batch", "(", "submission_batch_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_submission_batch_with_http_info", "(", "submission_batch_id", ",", "opts", ")", "data", "end" ]
Check the status of a submission batch job @param submission_batch_id @param [Hash] opts the optional parameters @option opts [BOOLEAN] :include_submissions @return [SubmissionBatch]
[ "Check", "the", "status", "of", "a", "submission", "batch", "job" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L825-L828
5,719
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_template
def get_template(template_id, opts = {}) data, _status_code, _headers = get_template_with_http_info(template_id, opts) data end
ruby
def get_template(template_id, opts = {}) data, _status_code, _headers = get_template_with_http_info(template_id, opts) data end
[ "def", "get_template", "(", "template_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_template_with_http_info", "(", "template_id", ",", "opts", ")", "data", "end" ]
Check the status of an uploaded template @param template_id @param [Hash] opts the optional parameters @return [Template]
[ "Check", "the", "status", "of", "an", "uploaded", "template" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L878-L881
5,720
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.get_template_schema
def get_template_schema(template_id, opts = {}) data, _status_code, _headers = get_template_schema_with_http_info(template_id, opts) data end
ruby
def get_template_schema(template_id, opts = {}) data, _status_code, _headers = get_template_schema_with_http_info(template_id, opts) data end
[ "def", "get_template_schema", "(", "template_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_template_schema_with_http_info", "(", "template_id", ",", "opts", ")", "data", "end" ]
Fetch the JSON schema for a template @param template_id @param [Hash] opts the optional parameters @return [Hash<String, Object>]
[ "Fetch", "the", "JSON", "schema", "for", "a", "template" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L929-L932
5,721
FormAPI/formapi-ruby
lib/form_api/api/pdf_api.rb
FormAPI.PDFApi.update_data_request
def update_data_request(data_request_id, update_submission_data_request_data, opts = {}) data, _status_code, _headers = update_data_request_with_http_info(data_request_id, update_submission_data_request_data, opts) data end
ruby
def update_data_request(data_request_id, update_submission_data_request_data, opts = {}) data, _status_code, _headers = update_data_request_with_http_info(data_request_id, update_submission_data_request_data, opts) data end
[ "def", "update_data_request", "(", "data_request_id", ",", "update_submission_data_request_data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_data_request_with_http_info", "(", "data_request_id", ",", "update_submission_data_request_data", ",", "opts", ")", "data", "end" ]
Update a submission data request @param data_request_id @param update_submission_data_request_data @param [Hash] opts the optional parameters @return [UpdateDataRequestResponse]
[ "Update", "a", "submission", "data", "request" ]
247859d884def43e365b7110b77104245ea8033c
https://github.com/FormAPI/formapi-ruby/blob/247859d884def43e365b7110b77104245ea8033c/lib/form_api/api/pdf_api.rb#L1089-L1092
5,722
grzlus/acts_as_nested_interval
lib/acts_as_nested_interval/instance_methods.rb
ActsAsNestedInterval.InstanceMethods.next_root_lft
def next_root_lft last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots? last_root.try(:right) || 0.to_r end
ruby
def next_root_lft last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots? last_root.try(:right) || 0.to_r end
[ "def", "next_root_lft", "last_root", "=", "nested_interval_scope", ".", "roots", ".", "order", "(", "rgtp", ":", ":desc", ",", "rgtq", ":", ":desc", ")", ".", "first", "raise", "Exception", ".", "new", "(", "\"Only one root allowed\"", ")", "if", "last_root", ".", "present?", "&&", "!", "self", ".", "class", ".", "nested_interval", ".", "multiple_roots?", "last_root", ".", "try", "(", ":right", ")", "||", "0", ".", "to_r", "end" ]
Returns left end of interval for next root.
[ "Returns", "left", "end", "of", "interval", "for", "next", "root", "." ]
9a588bf515570e4a1e1311dc58dc5eea8bfffd8e
https://github.com/grzlus/acts_as_nested_interval/blob/9a588bf515570e4a1e1311dc58dc5eea8bfffd8e/lib/acts_as_nested_interval/instance_methods.rb#L39-L43
5,723
mudbugmedia/fusebox
lib/fusebox/request.rb
Fusebox.Request.report
def report (opts = {}) default_options = { :user => 'all', :group_subaccount => true, :report_type => 'basic' } opts.reverse_merge! default_options post 'report', opts, "report_#{opts[:report_type]}".to_sym end
ruby
def report (opts = {}) default_options = { :user => 'all', :group_subaccount => true, :report_type => 'basic' } opts.reverse_merge! default_options post 'report', opts, "report_#{opts[:report_type]}".to_sym end
[ "def", "report", "(", "opts", "=", "{", "}", ")", "default_options", "=", "{", ":user", "=>", "'all'", ",", ":group_subaccount", "=>", "true", ",", ":report_type", "=>", "'basic'", "}", "opts", ".", "reverse_merge!", "default_options", "post", "'report'", ",", "opts", ",", "\"report_#{opts[:report_type]}\"", ".", "to_sym", "end" ]
This request will provide information about one or more accounts under your platform in CSV format @see https://www.fusemail.com/support/api-documentation/requests#report report API documentation @param [Array] opts @option opts [String] :user ('all') The username you wish to query for information; you may also enter the username "all" to get information about all users under your platform @option opts [Boolean] :group_subaccount (true) Provide information not only for the Group Administration account but also for the group sub-accounts under the Group Administration account @option opts ['basic', 'extended'] :report_type ('basic') Level of detailed in returned results @return [Response]
[ "This", "request", "will", "provide", "information", "about", "one", "or", "more", "accounts", "under", "your", "platform", "in", "CSV", "format" ]
2c691495b180380552947ce67477b51c14676eee
https://github.com/mudbugmedia/fusebox/blob/2c691495b180380552947ce67477b51c14676eee/lib/fusebox/request.rb#L277-L286
5,724
mudbugmedia/fusebox
lib/fusebox/request.rb
Fusebox.Request.load_auth_from_yaml
def load_auth_from_yaml self.class.auth_yaml_paths.map { |path| File.expand_path(path) }.select { |path| File.exist?(path) }.each do |path| auth = YAML.load(File.read(path)) @username = auth['username'] @password = auth['password'] return if @username && @password end raise "Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}" end
ruby
def load_auth_from_yaml self.class.auth_yaml_paths.map { |path| File.expand_path(path) }.select { |path| File.exist?(path) }.each do |path| auth = YAML.load(File.read(path)) @username = auth['username'] @password = auth['password'] return if @username && @password end raise "Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}" end
[ "def", "load_auth_from_yaml", "self", ".", "class", ".", "auth_yaml_paths", ".", "map", "{", "|", "path", "|", "File", ".", "expand_path", "(", "path", ")", "}", ".", "select", "{", "|", "path", "|", "File", ".", "exist?", "(", "path", ")", "}", ".", "each", "do", "|", "path", "|", "auth", "=", "YAML", ".", "load", "(", "File", ".", "read", "(", "path", ")", ")", "@username", "=", "auth", "[", "'username'", "]", "@password", "=", "auth", "[", "'password'", "]", "return", "if", "@username", "&&", "@password", "end", "raise", "\"Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}\"", "end" ]
Load the platform authentication informaiton from a YAML file @see Request.auth_yaml_paths
[ "Load", "the", "platform", "authentication", "informaiton", "from", "a", "YAML", "file" ]
2c691495b180380552947ce67477b51c14676eee
https://github.com/mudbugmedia/fusebox/blob/2c691495b180380552947ce67477b51c14676eee/lib/fusebox/request.rb#L329-L338
5,725
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.download_manifest_only
def download_manifest_only FastlaneCore::UI.message('download_manifest_only...') rsa_key = load_rsa_key(rsa_keypath) success = true if !rsa_key.nil? FastlaneCore::UI.message('Logging in with RSA key for download...') Net::SSH.start(host, user, key_data: rsa_key, keys_only: true) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end else FastlaneCore::UI.message('Logging in for download...') Net::SSH.start(host, user, password: password) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end end success end
ruby
def download_manifest_only FastlaneCore::UI.message('download_manifest_only...') rsa_key = load_rsa_key(rsa_keypath) success = true if !rsa_key.nil? FastlaneCore::UI.message('Logging in with RSA key for download...') Net::SSH.start(host, user, key_data: rsa_key, keys_only: true) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end else FastlaneCore::UI.message('Logging in for download...') Net::SSH.start(host, user, password: password) do |ssh| FastlaneCore::UI.message('Uploading UPA & Manifest...') success = ssh_sftp_download(ssh, manifest_path) end end success end
[ "def", "download_manifest_only", "FastlaneCore", "::", "UI", ".", "message", "(", "'download_manifest_only...'", ")", "rsa_key", "=", "load_rsa_key", "(", "rsa_keypath", ")", "success", "=", "true", "if", "!", "rsa_key", ".", "nil?", "FastlaneCore", "::", "UI", ".", "message", "(", "'Logging in with RSA key for download...'", ")", "Net", "::", "SSH", ".", "start", "(", "host", ",", "user", ",", "key_data", ":", "rsa_key", ",", "keys_only", ":", "true", ")", "do", "|", "ssh", "|", "FastlaneCore", "::", "UI", ".", "message", "(", "'Uploading UPA & Manifest...'", ")", "success", "=", "ssh_sftp_download", "(", "ssh", ",", "manifest_path", ")", "end", "else", "FastlaneCore", "::", "UI", ".", "message", "(", "'Logging in for download...'", ")", "Net", "::", "SSH", ".", "start", "(", "host", ",", "user", ",", "password", ":", "password", ")", "do", "|", "ssh", "|", "FastlaneCore", "::", "UI", ".", "message", "(", "'Uploading UPA & Manifest...'", ")", "success", "=", "ssh_sftp_download", "(", "ssh", ",", "manifest_path", ")", "end", "end", "success", "end" ]
Download metadata only rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength
[ "Download", "metadata", "only" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L92-L110
5,726
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.check_ipa
def check_ipa(local_ipa_path) if File.exist?(local_ipa_path) FastlaneCore::UI.important('IPA found at ' + local_ipa_path) return true else FastlaneCore::UI.verbose('IPA at given path does not exist yet.') return false end end
ruby
def check_ipa(local_ipa_path) if File.exist?(local_ipa_path) FastlaneCore::UI.important('IPA found at ' + local_ipa_path) return true else FastlaneCore::UI.verbose('IPA at given path does not exist yet.') return false end end
[ "def", "check_ipa", "(", "local_ipa_path", ")", "if", "File", ".", "exist?", "(", "local_ipa_path", ")", "FastlaneCore", "::", "UI", ".", "important", "(", "'IPA found at '", "+", "local_ipa_path", ")", "return", "true", "else", "FastlaneCore", "::", "UI", ".", "verbose", "(", "'IPA at given path does not exist yet.'", ")", "return", "false", "end", "end" ]
Check IPA existence locally @param local_ipa_path
[ "Check", "IPA", "existence", "locally" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L147-L155
5,727
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.download_manifest
def download_manifest(sftp) FastlaneCore::UI.message('Checking remote Manifest') json = nil remote_manifest_path = remote_manifest_path(appcode) begin sftp.stat!(remote_manifest_path) do |response| if response.ok? FastlaneCore::UI.success('Loading remote manifest:') manifest = sftp.download!(remote_manifest_path) json = JSON.parse(manifest) end end rescue FastlaneCore::UI.message('No previous Manifest found') end json end
ruby
def download_manifest(sftp) FastlaneCore::UI.message('Checking remote Manifest') json = nil remote_manifest_path = remote_manifest_path(appcode) begin sftp.stat!(remote_manifest_path) do |response| if response.ok? FastlaneCore::UI.success('Loading remote manifest:') manifest = sftp.download!(remote_manifest_path) json = JSON.parse(manifest) end end rescue FastlaneCore::UI.message('No previous Manifest found') end json end
[ "def", "download_manifest", "(", "sftp", ")", "FastlaneCore", "::", "UI", ".", "message", "(", "'Checking remote Manifest'", ")", "json", "=", "nil", "remote_manifest_path", "=", "remote_manifest_path", "(", "appcode", ")", "begin", "sftp", ".", "stat!", "(", "remote_manifest_path", ")", "do", "|", "response", "|", "if", "response", ".", "ok?", "FastlaneCore", "::", "UI", ".", "success", "(", "'Loading remote manifest:'", ")", "manifest", "=", "sftp", ".", "download!", "(", "remote_manifest_path", ")", "json", "=", "JSON", ".", "parse", "(", "manifest", ")", "end", "end", "rescue", "FastlaneCore", "::", "UI", ".", "message", "(", "'No previous Manifest found'", ")", "end", "json", "end" ]
Downloads remote manifest, self.appcode required by options. @param sftp @param [String] remote_path @returns [JSON] json or nil
[ "Downloads", "remote", "manifest", "self", ".", "appcode", "required", "by", "options", "." ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L201-L217
5,728
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.upload_ipa
def upload_ipa(sftp, local_ipa_path, remote_ipa_path) msg = "[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}" FastlaneCore::UI.message(msg) result = sftp.upload!(local_ipa_path, remote_ipa_path) do |event, _uploader, *_args| case event when :open then putc '.' when :put then putc '.' $stdout.flush when :close then puts "\n" when :finish then FastlaneCore::UI.success('IPA upload successful') end end end
ruby
def upload_ipa(sftp, local_ipa_path, remote_ipa_path) msg = "[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}" FastlaneCore::UI.message(msg) result = sftp.upload!(local_ipa_path, remote_ipa_path) do |event, _uploader, *_args| case event when :open then putc '.' when :put then putc '.' $stdout.flush when :close then puts "\n" when :finish then FastlaneCore::UI.success('IPA upload successful') end end end
[ "def", "upload_ipa", "(", "sftp", ",", "local_ipa_path", ",", "remote_ipa_path", ")", "msg", "=", "\"[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}\"", "FastlaneCore", "::", "UI", ".", "message", "(", "msg", ")", "result", "=", "sftp", ".", "upload!", "(", "local_ipa_path", ",", "remote_ipa_path", ")", "do", "|", "event", ",", "_uploader", ",", "*", "_args", "|", "case", "event", "when", ":open", "then", "putc", "'.'", "when", ":put", "then", "putc", "'.'", "$stdout", ".", "flush", "when", ":close", "then", "puts", "\"\\n\"", "when", ":finish", "then", "FastlaneCore", "::", "UI", ".", "success", "(", "'IPA upload successful'", ")", "end", "end", "end" ]
Upload current IPA @param sftp @param [String] local_ipa_path @param [String] remote_ipa_path
[ "Upload", "current", "IPA" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L224-L240
5,729
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.upload_manifest
def upload_manifest(sftp, local_path, remote_path) msg = '[Uploading Manifest] ' + local_path + ' to ' + remote_path FastlaneCore::UI.message(msg) result = sftp.upload!(local_path, remote_path) do |event, _uploader, *_args| case event when :finish then FastlaneCore::UI.success('Manifest upload successful') end end end
ruby
def upload_manifest(sftp, local_path, remote_path) msg = '[Uploading Manifest] ' + local_path + ' to ' + remote_path FastlaneCore::UI.message(msg) result = sftp.upload!(local_path, remote_path) do |event, _uploader, *_args| case event when :finish then FastlaneCore::UI.success('Manifest upload successful') end end end
[ "def", "upload_manifest", "(", "sftp", ",", "local_path", ",", "remote_path", ")", "msg", "=", "'[Uploading Manifest] '", "+", "local_path", "+", "' to '", "+", "remote_path", "FastlaneCore", "::", "UI", ".", "message", "(", "msg", ")", "result", "=", "sftp", ".", "upload!", "(", "local_path", ",", "remote_path", ")", "do", "|", "event", ",", "_uploader", ",", "*", "_args", "|", "case", "event", "when", ":finish", "then", "FastlaneCore", "::", "UI", ".", "success", "(", "'Manifest upload successful'", ")", "end", "end", "end" ]
Upload current manifest.json @param sftp @param [String] manifest_path @param [String] remote_manifest_path
[ "Upload", "current", "manifest", ".", "json" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L247-L256
5,730
suculent/apprepo
lib/apprepo/uploader.rb
AppRepo.Uploader.load_rsa_key
def load_rsa_key(rsa_keypath) File.open(rsa_keypath, 'r') do |file| rsa_key = nil rsa_key = [file.read] if !rsa_key.nil? FastlaneCore::UI.success('Successfully loaded RSA key...') else FastlaneCore::UI.user_error!('Failed to load RSA key...') end rsa_key end end
ruby
def load_rsa_key(rsa_keypath) File.open(rsa_keypath, 'r') do |file| rsa_key = nil rsa_key = [file.read] if !rsa_key.nil? FastlaneCore::UI.success('Successfully loaded RSA key...') else FastlaneCore::UI.user_error!('Failed to load RSA key...') end rsa_key end end
[ "def", "load_rsa_key", "(", "rsa_keypath", ")", "File", ".", "open", "(", "rsa_keypath", ",", "'r'", ")", "do", "|", "file", "|", "rsa_key", "=", "nil", "rsa_key", "=", "[", "file", ".", "read", "]", "if", "!", "rsa_key", ".", "nil?", "FastlaneCore", "::", "UI", ".", "success", "(", "'Successfully loaded RSA key...'", ")", "else", "FastlaneCore", "::", "UI", ".", "user_error!", "(", "'Failed to load RSA key...'", ")", "end", "rsa_key", "end", "end" ]
Private methods - Local Operations
[ "Private", "methods", "-", "Local", "Operations" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/uploader.rb#L284-L295
5,731
ivanzotov/constructor
pages/app/models/constructor_pages/field.rb
ConstructorPages.Field.check_code_name
def check_code_name(code_name) [code_name.pluralize, code_name.singularize].each {|name| %w{self_and_ancestors descendants}.each {|m| return false if template.send(m).map(&:code_name).include?(name)}} true end
ruby
def check_code_name(code_name) [code_name.pluralize, code_name.singularize].each {|name| %w{self_and_ancestors descendants}.each {|m| return false if template.send(m).map(&:code_name).include?(name)}} true end
[ "def", "check_code_name", "(", "code_name", ")", "[", "code_name", ".", "pluralize", ",", "code_name", ".", "singularize", "]", ".", "each", "{", "|", "name", "|", "%w{", "self_and_ancestors", "descendants", "}", ".", "each", "{", "|", "m", "|", "return", "false", "if", "template", ".", "send", "(", "m", ")", ".", "map", "(", ":code_name", ")", ".", "include?", "(", "name", ")", "}", "}", "true", "end" ]
Check if there is code_name in template branch
[ "Check", "if", "there", "is", "code_name", "in", "template", "branch" ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/field.rb#L52-L57
5,732
fulldecent/structured-acceptance-test
implementations/ruby/lib/location.rb
StatModule.Location.print
def print result = "in #{path}" if !begin_line.nil? && !end_line.nil? if begin_line != end_line if !begin_column.nil? && !end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}" elsif !begin_column.nil? && end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}" elsif begin_column.nil? && !end_column.nil? result += ", line #{begin_line} to line #{end_line}:#{end_column}" else result += ", lines #{begin_line}-#{end_line}" end else if begin_column.nil? result += ", line #{begin_line}" else result += ", line #{begin_line}:#{begin_column}" result += "-#{end_column}" unless end_column.nil? end end end result end
ruby
def print result = "in #{path}" if !begin_line.nil? && !end_line.nil? if begin_line != end_line if !begin_column.nil? && !end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}" elsif !begin_column.nil? && end_column.nil? result += ", line #{begin_line}:#{begin_column} to line #{end_line}" elsif begin_column.nil? && !end_column.nil? result += ", line #{begin_line} to line #{end_line}:#{end_column}" else result += ", lines #{begin_line}-#{end_line}" end else if begin_column.nil? result += ", line #{begin_line}" else result += ", line #{begin_line}:#{begin_column}" result += "-#{end_column}" unless end_column.nil? end end end result end
[ "def", "print", "result", "=", "\"in #{path}\"", "if", "!", "begin_line", ".", "nil?", "&&", "!", "end_line", ".", "nil?", "if", "begin_line", "!=", "end_line", "if", "!", "begin_column", ".", "nil?", "&&", "!", "end_column", ".", "nil?", "result", "+=", "\", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}\"", "elsif", "!", "begin_column", ".", "nil?", "&&", "end_column", ".", "nil?", "result", "+=", "\", line #{begin_line}:#{begin_column} to line #{end_line}\"", "elsif", "begin_column", ".", "nil?", "&&", "!", "end_column", ".", "nil?", "result", "+=", "\", line #{begin_line} to line #{end_line}:#{end_column}\"", "else", "result", "+=", "\", lines #{begin_line}-#{end_line}\"", "end", "else", "if", "begin_column", ".", "nil?", "result", "+=", "\", line #{begin_line}\"", "else", "result", "+=", "\", line #{begin_line}:#{begin_column}\"", "result", "+=", "\"-#{end_column}\"", "unless", "end_column", ".", "nil?", "end", "end", "end", "result", "end" ]
Get formatted information about location
[ "Get", "formatted", "information", "about", "location" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/location.rb#L103-L126
5,733
dennmart/wanikani-gem
lib/wanikani/level.rb
Wanikani.Level.level_items_list
def level_items_list(type, levels) levels = levels.join(',') if levels.is_a?(Array) response = api_response(type, levels) # The vocabulary API call without specifying levels returns a Hash instead # of an Array, so this is a hacky way of dealing with it. if response["requested_information"].is_a?(Hash) return response["requested_information"]["general"] else return response["requested_information"] end end
ruby
def level_items_list(type, levels) levels = levels.join(',') if levels.is_a?(Array) response = api_response(type, levels) # The vocabulary API call without specifying levels returns a Hash instead # of an Array, so this is a hacky way of dealing with it. if response["requested_information"].is_a?(Hash) return response["requested_information"]["general"] else return response["requested_information"] end end
[ "def", "level_items_list", "(", "type", ",", "levels", ")", "levels", "=", "levels", ".", "join", "(", "','", ")", "if", "levels", ".", "is_a?", "(", "Array", ")", "response", "=", "api_response", "(", "type", ",", "levels", ")", "# The vocabulary API call without specifying levels returns a Hash instead", "# of an Array, so this is a hacky way of dealing with it.", "if", "response", "[", "\"requested_information\"", "]", ".", "is_a?", "(", "Hash", ")", "return", "response", "[", "\"requested_information\"", "]", "[", "\"general\"", "]", "else", "return", "response", "[", "\"requested_information\"", "]", "end", "end" ]
Fetches the specified item type list from WaniKani's API @param type [String] The type of item to fetch. @param levels [Integer, Array<Integer>] a specific level or array of levels to fetch items for. @return [Hash] list of items of the specified type and levels.
[ "Fetches", "the", "specified", "item", "type", "list", "from", "WaniKani", "s", "API" ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/level.rb#L55-L66
5,734
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.check_expired_resources
def check_expired_resources net_resources = ::NetResource.expired net_resources.each do |resource| http = EM::HttpRequest.new(resource.url).get http.callback{ |response| resource.set_next_update if resource_changed?(resource, response) resource.body = response.response update_changed_resource(resource, response) notify_subscribers(resource) end } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
ruby
def check_expired_resources net_resources = ::NetResource.expired net_resources.each do |resource| http = EM::HttpRequest.new(resource.url).get http.callback{ |response| resource.set_next_update if resource_changed?(resource, response) resource.body = response.response update_changed_resource(resource, response) notify_subscribers(resource) end } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
[ "def", "check_expired_resources", "net_resources", "=", "::", "NetResource", ".", "expired", "net_resources", ".", "each", "do", "|", "resource", "|", "http", "=", "EM", "::", "HttpRequest", ".", "new", "(", "resource", ".", "url", ")", ".", "get", "http", ".", "callback", "{", "|", "response", "|", "resource", ".", "set_next_update", "if", "resource_changed?", "(", "resource", ",", "response", ")", "resource", ".", "body", "=", "response", ".", "response", "update_changed_resource", "(", "resource", ",", "response", ")", "notify_subscribers", "(", "resource", ")", "end", "}", "http", ".", "errback", "{", "|", "response", "|", "# Do something here, maybe setting the resource", "# to be not checked anymore.", "}", "end", "end" ]
Adds a periodic timer to the Eventmachine reactor loop and immediately starts grabbing expired resources and checking them. Gets all of the expired NetResources from the database and sends an HTTP GET requests for each one. Subscribers to a NetResource will be notified if it has changed since the last time it was grabbed.
[ "Adds", "a", "periodic", "timer", "to", "the", "Eventmachine", "reactor", "loop", "and", "immediately", "starts", "grabbing", "expired", "resources", "and", "checking", "them", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L20-L38
5,735
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.notify_subscribers
def notify_subscribers(resource) resource.subscriptions.each do |subscription| http = EM::HttpRequest.new(subscription.url).post(:body => {:data => resource.body}) http.callback{ |response| puts "POSTed updated data for #{resource.url}, #{resource.body.length} characters" } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
ruby
def notify_subscribers(resource) resource.subscriptions.each do |subscription| http = EM::HttpRequest.new(subscription.url).post(:body => {:data => resource.body}) http.callback{ |response| puts "POSTed updated data for #{resource.url}, #{resource.body.length} characters" } http.errback {|response| # Do something here, maybe setting the resource # to be not checked anymore. } end end
[ "def", "notify_subscribers", "(", "resource", ")", "resource", ".", "subscriptions", ".", "each", "do", "|", "subscription", "|", "http", "=", "EM", "::", "HttpRequest", ".", "new", "(", "subscription", ".", "url", ")", ".", "post", "(", ":body", "=>", "{", ":data", "=>", "resource", ".", "body", "}", ")", "http", ".", "callback", "{", "|", "response", "|", "puts", "\"POSTed updated data for #{resource.url}, #{resource.body.length} characters\"", "}", "http", ".", "errback", "{", "|", "response", "|", "# Do something here, maybe setting the resource", "# to be not checked anymore.", "}", "end", "end" ]
Notifies each of a NetResource's subscribers that the resource has changed by doing an HTTP POST request to the subscriber's callback url. The POST body contains a key called "data" which contains the feed value.
[ "Notifies", "each", "of", "a", "NetResource", "s", "subscribers", "that", "the", "resource", "has", "changed", "by", "doing", "an", "HTTP", "POST", "request", "to", "the", "subscriber", "s", "callback", "url", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L45-L56
5,736
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.resource_changed?
def resource_changed?(resource, response) changed = false puts "checking for changes on #{resource.url}" puts "response.response.hash: #{response.response.hash}" puts "resource.last_modified_hash: #{resource.last_modified_hash}" if response.response.hash != resource.last_modified_hash puts "changed!!!!\n\n\n\n" changed = true end end
ruby
def resource_changed?(resource, response) changed = false puts "checking for changes on #{resource.url}" puts "response.response.hash: #{response.response.hash}" puts "resource.last_modified_hash: #{resource.last_modified_hash}" if response.response.hash != resource.last_modified_hash puts "changed!!!!\n\n\n\n" changed = true end end
[ "def", "resource_changed?", "(", "resource", ",", "response", ")", "changed", "=", "false", "puts", "\"checking for changes on #{resource.url}\"", "puts", "\"response.response.hash: #{response.response.hash}\"", "puts", "\"resource.last_modified_hash: #{resource.last_modified_hash}\"", "if", "response", ".", "response", ".", "hash", "!=", "resource", ".", "last_modified_hash", "puts", "\"changed!!!!\\n\\n\\n\\n\"", "changed", "=", "true", "end", "end" ]
Determines whether a resource has changed by comparing its saved hash value with the hash value of the response content.
[ "Determines", "whether", "a", "resource", "has", "changed", "by", "comparing", "its", "saved", "hash", "value", "with", "the", "hash", "value", "of", "the", "response", "content", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L61-L70
5,737
futurechimp/octopus
lib/octopus/grabbers/generic_http.rb
Grabbers.GenericHttp.update_changed_resource
def update_changed_resource(resource, response) resource.last_modified_hash = response.response.hash resource.last_updated = Time.now resource.body = response.response resource.save end
ruby
def update_changed_resource(resource, response) resource.last_modified_hash = response.response.hash resource.last_updated = Time.now resource.body = response.response resource.save end
[ "def", "update_changed_resource", "(", "resource", ",", "response", ")", "resource", ".", "last_modified_hash", "=", "response", ".", "response", ".", "hash", "resource", ".", "last_updated", "=", "Time", ".", "now", "resource", ".", "body", "=", "response", ".", "response", "resource", ".", "save", "end" ]
Updates the resource's fields when the resource has changed. The last_modified_hash is set to the hash value of the response body, the response body itself is saved so that it can be sent to consumers during notifications, and the resource's last_updated time is set to the current time.
[ "Updates", "the", "resource", "s", "fields", "when", "the", "resource", "has", "changed", ".", "The", "last_modified_hash", "is", "set", "to", "the", "hash", "value", "of", "the", "response", "body", "the", "response", "body", "itself", "is", "saved", "so", "that", "it", "can", "be", "sent", "to", "consumers", "during", "notifications", "and", "the", "resource", "s", "last_updated", "time", "is", "set", "to", "the", "current", "time", "." ]
2b9dca7894de7c37b02849bc9af2e28eb8d625fe
https://github.com/futurechimp/octopus/blob/2b9dca7894de7c37b02849bc9af2e28eb8d625fe/lib/octopus/grabbers/generic_http.rb#L78-L83
5,738
Falkor/falkorlib
lib/falkorlib/config.rb
FalkorLib.Config.default
def default res = FalkorLib::Config::DEFAULTS.clone $LOADED_FEATURES.each do |path| res[:git] = FalkorLib::Config::Git::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:gitflow] = FalkorLib::Config::GitFlow::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:versioning] = FalkorLib::Config::Versioning::DEFAULTS if path.include?('lib/falkorlib/versioning.rb') if path.include?('lib/falkorlib/puppet.rb') res[:puppet] = FalkorLib::Config::Puppet::DEFAULTS res[:templates][:puppet][:modules] = FalkorLib::Config::Puppet::Modules::DEFAULTS[:metadata] end end # Check the potential local customizations [:local, :private].each do |type| custom_cfg = File.join( res[:root], res[:config_files][type.to_sym]) if File.exist?( custom_cfg ) res.deep_merge!( load_config( custom_cfg ) ) end end res end
ruby
def default res = FalkorLib::Config::DEFAULTS.clone $LOADED_FEATURES.each do |path| res[:git] = FalkorLib::Config::Git::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:gitflow] = FalkorLib::Config::GitFlow::DEFAULTS if path.include?('lib/falkorlib/git.rb') res[:versioning] = FalkorLib::Config::Versioning::DEFAULTS if path.include?('lib/falkorlib/versioning.rb') if path.include?('lib/falkorlib/puppet.rb') res[:puppet] = FalkorLib::Config::Puppet::DEFAULTS res[:templates][:puppet][:modules] = FalkorLib::Config::Puppet::Modules::DEFAULTS[:metadata] end end # Check the potential local customizations [:local, :private].each do |type| custom_cfg = File.join( res[:root], res[:config_files][type.to_sym]) if File.exist?( custom_cfg ) res.deep_merge!( load_config( custom_cfg ) ) end end res end
[ "def", "default", "res", "=", "FalkorLib", "::", "Config", "::", "DEFAULTS", ".", "clone", "$LOADED_FEATURES", ".", "each", "do", "|", "path", "|", "res", "[", ":git", "]", "=", "FalkorLib", "::", "Config", "::", "Git", "::", "DEFAULTS", "if", "path", ".", "include?", "(", "'lib/falkorlib/git.rb'", ")", "res", "[", ":gitflow", "]", "=", "FalkorLib", "::", "Config", "::", "GitFlow", "::", "DEFAULTS", "if", "path", ".", "include?", "(", "'lib/falkorlib/git.rb'", ")", "res", "[", ":versioning", "]", "=", "FalkorLib", "::", "Config", "::", "Versioning", "::", "DEFAULTS", "if", "path", ".", "include?", "(", "'lib/falkorlib/versioning.rb'", ")", "if", "path", ".", "include?", "(", "'lib/falkorlib/puppet.rb'", ")", "res", "[", ":puppet", "]", "=", "FalkorLib", "::", "Config", "::", "Puppet", "::", "DEFAULTS", "res", "[", ":templates", "]", "[", ":puppet", "]", "[", ":modules", "]", "=", "FalkorLib", "::", "Config", "::", "Puppet", "::", "Modules", "::", "DEFAULTS", "[", ":metadata", "]", "end", "end", "# Check the potential local customizations", "[", ":local", ",", ":private", "]", ".", "each", "do", "|", "type", "|", "custom_cfg", "=", "File", ".", "join", "(", "res", "[", ":root", "]", ",", "res", "[", ":config_files", "]", "[", "type", ".", "to_sym", "]", ")", "if", "File", ".", "exist?", "(", "custom_cfg", ")", "res", ".", "deep_merge!", "(", "load_config", "(", "custom_cfg", ")", ")", "end", "end", "res", "end" ]
Build the default configuration hash, to be used to initiate the default. The hash is built depending on the loaded files.
[ "Build", "the", "default", "configuration", "hash", "to", "be", "used", "to", "initiate", "the", "default", ".", "The", "hash", "is", "built", "depending", "on", "the", "loaded", "files", "." ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/config.rb#L83-L102
5,739
Falkor/falkorlib
lib/falkorlib/config.rb
FalkorLib.Config.config_file
def config_file(dir = Dir.pwd, type = :local, options = {}) path = normalized_path(dir) path = FalkorLib::Git.rootdir(path) if FalkorLib::Git.init?(path) raise FalkorLib::Error, "Wrong FalkorLib configuration type" unless FalkorLib.config[:config_files].keys.include?( type.to_sym) (options[:file]) ? options[:file] : File.join(path, FalkorLib.config[:config_files][type.to_sym]) end
ruby
def config_file(dir = Dir.pwd, type = :local, options = {}) path = normalized_path(dir) path = FalkorLib::Git.rootdir(path) if FalkorLib::Git.init?(path) raise FalkorLib::Error, "Wrong FalkorLib configuration type" unless FalkorLib.config[:config_files].keys.include?( type.to_sym) (options[:file]) ? options[:file] : File.join(path, FalkorLib.config[:config_files][type.to_sym]) end
[ "def", "config_file", "(", "dir", "=", "Dir", ".", "pwd", ",", "type", "=", ":local", ",", "options", "=", "{", "}", ")", "path", "=", "normalized_path", "(", "dir", ")", "path", "=", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", "if", "FalkorLib", "::", "Git", ".", "init?", "(", "path", ")", "raise", "FalkorLib", "::", "Error", ",", "\"Wrong FalkorLib configuration type\"", "unless", "FalkorLib", ".", "config", "[", ":config_files", "]", ".", "keys", ".", "include?", "(", "type", ".", "to_sym", ")", "(", "options", "[", ":file", "]", ")", "?", "options", "[", ":file", "]", ":", "File", ".", "join", "(", "path", ",", "FalkorLib", ".", "config", "[", ":config_files", "]", "[", "type", ".", "to_sym", "]", ")", "end" ]
get get_or_save wrapper for get and save operations
[ "get", "get_or_save", "wrapper", "for", "get", "and", "save", "operations" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/config.rb#L119-L124
5,740
ktemkin/ruby-ise
lib/ise/project_navigator.rb
ISE.ProjectNavigator.most_recent_project_path
def most_recent_project_path #Re-load the preference file, so we have the most recent project. @preferences = PreferenceFile.load #And retrieve the first project in the recent projects list. project = preference(RecentProjectsPath).split(', ').first #If the project exists, return it; otherwise, return nil. File::exists?(project) ? project : nil end
ruby
def most_recent_project_path #Re-load the preference file, so we have the most recent project. @preferences = PreferenceFile.load #And retrieve the first project in the recent projects list. project = preference(RecentProjectsPath).split(', ').first #If the project exists, return it; otherwise, return nil. File::exists?(project) ? project : nil end
[ "def", "most_recent_project_path", "#Re-load the preference file, so we have the most recent project.", "@preferences", "=", "PreferenceFile", ".", "load", "#And retrieve the first project in the recent projects list.", "project", "=", "preference", "(", "RecentProjectsPath", ")", ".", "split", "(", "', '", ")", ".", "first", "#If the project exists, return it; otherwise, return nil.", "File", "::", "exists?", "(", "project", ")", "?", "project", ":", "nil", "end" ]
Returns most recently open project. If Project Navigator has a project open, that project will be used. This function re-loads the preferences file upon each call, to ensure we don't have stale data. TODO: When more than one ISE version is loaded, parse _all_ of the recent projects, and then return the project with the latest timestamp.
[ "Returns", "most", "recently", "open", "project", ".", "If", "Project", "Navigator", "has", "a", "project", "open", "that", "project", "will", "be", "used", ".", "This", "function", "re", "-", "loads", "the", "preferences", "file", "upon", "each", "call", "to", "ensure", "we", "don", "t", "have", "stale", "data", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/project_navigator.rb#L62-L73
5,741
bachya/cliutils
lib/cliutils/configurator.rb
CLIUtils.Configurator.ingest_prefs
def ingest_prefs(prefs) fail 'Invaid Prefs class' unless prefs.kind_of?(Prefs) prefs.prompts.each do |p| section_sym = p.config_section.to_sym add_section(section_sym) unless @data.key?(section_sym) @data[section_sym].merge!(p.config_key.to_sym => p.answer) end end
ruby
def ingest_prefs(prefs) fail 'Invaid Prefs class' unless prefs.kind_of?(Prefs) prefs.prompts.each do |p| section_sym = p.config_section.to_sym add_section(section_sym) unless @data.key?(section_sym) @data[section_sym].merge!(p.config_key.to_sym => p.answer) end end
[ "def", "ingest_prefs", "(", "prefs", ")", "fail", "'Invaid Prefs class'", "unless", "prefs", ".", "kind_of?", "(", "Prefs", ")", "prefs", ".", "prompts", ".", "each", "do", "|", "p", "|", "section_sym", "=", "p", ".", "config_section", ".", "to_sym", "add_section", "(", "section_sym", ")", "unless", "@data", ".", "key?", "(", "section_sym", ")", "@data", "[", "section_sym", "]", ".", "merge!", "(", "p", ".", "config_key", ".", "to_sym", "=>", "p", ".", "answer", ")", "end", "end" ]
Ingests a Prefs class and adds its answers to the configuration data. @param [Prefs] prefs The Prefs class to examine @return [void]
[ "Ingests", "a", "Prefs", "class", "and", "adds", "its", "answers", "to", "the", "configuration", "data", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/configurator.rb#L101-L108
5,742
bachya/cliutils
lib/cliutils/configurator.rb
CLIUtils.Configurator.method_missing
def method_missing(name, *args, &block) if name[-1,1] == '=' @data[name[0..-2].to_sym] = args[0] else @data[name.to_sym] ||= {} end end
ruby
def method_missing(name, *args, &block) if name[-1,1] == '=' @data[name[0..-2].to_sym] = args[0] else @data[name.to_sym] ||= {} end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "if", "name", "[", "-", "1", ",", "1", "]", "==", "'='", "@data", "[", "name", "[", "0", "..", "-", "2", "]", ".", "to_sym", "]", "=", "args", "[", "0", "]", "else", "@data", "[", "name", ".", "to_sym", "]", "||=", "{", "}", "end", "end" ]
Hook that fires when a non-existent method is called. Allows this module to return data from the config Hash when given a method name that matches a key. @param [<String, Symbol>] name The name of the method @param [Array] args The arguments @yield if a block is passed @return [Hash] The hash with the method's name as key
[ "Hook", "that", "fires", "when", "a", "non", "-", "existent", "method", "is", "called", ".", "Allows", "this", "module", "to", "return", "data", "from", "the", "config", "Hash", "when", "given", "a", "method", "name", "that", "matches", "a", "key", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/configurator.rb#L117-L123
5,743
eprothro/cassie
lib/cassie/schema/version_loader.rb
Cassie::Schema.VersionLoader.load
def load return false unless filename require filename begin # ensure the migration class is now defined version.migration_class_name.constantize if version.migration.is_a?(Cassie::Schema::Migration) version else false end rescue NameError raise NameError.new("Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.") end end
ruby
def load return false unless filename require filename begin # ensure the migration class is now defined version.migration_class_name.constantize if version.migration.is_a?(Cassie::Schema::Migration) version else false end rescue NameError raise NameError.new("Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.") end end
[ "def", "load", "return", "false", "unless", "filename", "require", "filename", "begin", "# ensure the migration class is now defined", "version", ".", "migration_class_name", ".", "constantize", "if", "version", ".", "migration", ".", "is_a?", "(", "Cassie", "::", "Schema", "::", "Migration", ")", "version", "else", "false", "end", "rescue", "NameError", "raise", "NameError", ".", "new", "(", "\"Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.\"", ")", "end", "end" ]
Requires the ruby file, thus loading the Migration class into the ObjectSpace. @return [Version, Boolean] The Version object if successful. In other words, if object representing the version returns a Cassie::Schema::Migration object. Otherwise returns false. @raise [NameError] if the migration class could not be loaded
[ "Requires", "the", "ruby", "file", "thus", "loading", "the", "Migration", "class", "into", "the", "ObjectSpace", "." ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/version_loader.rb#L14-L29
5,744
govdelivery/govdelivery-tms-ruby
lib/govdelivery/tms/instance_resource.rb
GovDelivery::TMS::InstanceResource.ClassMethods.nullable_attributes
def nullable_attributes(*attrs) @nullable_attributes ||= [] if attrs.any? @nullable_attributes.map!(&:to_sym).concat(attrs).uniq! if attrs.any? end @nullable_attributes end
ruby
def nullable_attributes(*attrs) @nullable_attributes ||= [] if attrs.any? @nullable_attributes.map!(&:to_sym).concat(attrs).uniq! if attrs.any? end @nullable_attributes end
[ "def", "nullable_attributes", "(", "*", "attrs", ")", "@nullable_attributes", "||=", "[", "]", "if", "attrs", ".", "any?", "@nullable_attributes", ".", "map!", "(", ":to_sym", ")", ".", "concat", "(", "attrs", ")", ".", "uniq!", "if", "attrs", ".", "any?", "end", "@nullable_attributes", "end" ]
Nullable attributes are sent as null in the request
[ "Nullable", "attributes", "are", "sent", "as", "null", "in", "the", "request" ]
073d6a451222cda3cddf29b6ac246af353f82335
https://github.com/govdelivery/govdelivery-tms-ruby/blob/073d6a451222cda3cddf29b6ac246af353f82335/lib/govdelivery/tms/instance_resource.rb#L50-L56
5,745
flori/bullshit
lib/bullshit.rb
Bullshit.ModuleFunctions.array_window
def array_window(array, window_size) window_size < 1 and raise ArgumentError, "window_size = #{window_size} < 1" window_size = window_size.to_i window_size += 1 if window_size % 2 == 0 radius = window_size / 2 array.each_index do |i| ws = window_size from = i - radius negative_from = false if from < 0 negative_from = true ws += from from = 0 end a = array[from, ws] if (diff = window_size - a.size) > 0 mean = a.inject(0.0) { |s, x| s + x } / a.size a = if negative_from [ mean ] * diff + a else a + [ mean ] * diff end end yield a end nil end
ruby
def array_window(array, window_size) window_size < 1 and raise ArgumentError, "window_size = #{window_size} < 1" window_size = window_size.to_i window_size += 1 if window_size % 2 == 0 radius = window_size / 2 array.each_index do |i| ws = window_size from = i - radius negative_from = false if from < 0 negative_from = true ws += from from = 0 end a = array[from, ws] if (diff = window_size - a.size) > 0 mean = a.inject(0.0) { |s, x| s + x } / a.size a = if negative_from [ mean ] * diff + a else a + [ mean ] * diff end end yield a end nil end
[ "def", "array_window", "(", "array", ",", "window_size", ")", "window_size", "<", "1", "and", "raise", "ArgumentError", ",", "\"window_size = #{window_size} < 1\"", "window_size", "=", "window_size", ".", "to_i", "window_size", "+=", "1", "if", "window_size", "%", "2", "==", "0", "radius", "=", "window_size", "/", "2", "array", ".", "each_index", "do", "|", "i", "|", "ws", "=", "window_size", "from", "=", "i", "-", "radius", "negative_from", "=", "false", "if", "from", "<", "0", "negative_from", "=", "true", "ws", "+=", "from", "from", "=", "0", "end", "a", "=", "array", "[", "from", ",", "ws", "]", "if", "(", "diff", "=", "window_size", "-", "a", ".", "size", ")", ">", "0", "mean", "=", "a", ".", "inject", "(", "0.0", ")", "{", "|", "s", ",", "x", "|", "s", "+", "x", "}", "/", "a", ".", "size", "a", "=", "if", "negative_from", "[", "mean", "]", "*", "diff", "+", "a", "else", "a", "+", "[", "mean", "]", "*", "diff", "end", "end", "yield", "a", "end", "nil", "end" ]
Let a window of size +window_size+ slide over the array +array+ and yield to the window array.
[ "Let", "a", "window", "of", "size", "+", "window_size", "+", "slide", "over", "the", "array", "+", "array", "+", "and", "yield", "to", "the", "window", "array", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L33-L59
5,746
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.<<
def <<(times) r = times.shift @repeat += 1 if @times[:repeat].last != r @times[:repeat] << r TIMES.zip(times) { |t, time| @times[t] << time.to_f } self end
ruby
def <<(times) r = times.shift @repeat += 1 if @times[:repeat].last != r @times[:repeat] << r TIMES.zip(times) { |t, time| @times[t] << time.to_f } self end
[ "def", "<<", "(", "times", ")", "r", "=", "times", ".", "shift", "@repeat", "+=", "1", "if", "@times", "[", ":repeat", "]", ".", "last", "!=", "r", "@times", "[", ":repeat", "]", "<<", "r", "TIMES", ".", "zip", "(", "times", ")", "{", "|", "t", ",", "time", "|", "@times", "[", "t", "]", "<<", "time", ".", "to_f", "}", "self", "end" ]
Add the array +times+ to this clock's time measurements. +times+ consists of the time measurements in float values in order of TIMES.
[ "Add", "the", "array", "+", "times", "+", "to", "this", "clock", "s", "time", "measurements", ".", "+", "times", "+", "consists", "of", "the", "time", "measurements", "in", "float", "values", "in", "order", "of", "TIMES", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L172-L178
5,747
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.analysis
def analysis @analysis ||= Hash.new do |h, time| time = time.to_sym times = @times[time] h[time] = MoreMath::Sequence.new(times) end end
ruby
def analysis @analysis ||= Hash.new do |h, time| time = time.to_sym times = @times[time] h[time] = MoreMath::Sequence.new(times) end end
[ "def", "analysis", "@analysis", "||=", "Hash", ".", "new", "do", "|", "h", ",", "time", "|", "time", "=", "time", ".", "to_sym", "times", "=", "@times", "[", "time", "]", "h", "[", "time", "]", "=", "MoreMath", "::", "Sequence", ".", "new", "(", "times", ")", "end", "end" ]
Returns a Hash of Sequence object for all of TIMES's time keys.
[ "Returns", "a", "Hash", "of", "Sequence", "object", "for", "all", "of", "TIMES", "s", "time", "keys", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L181-L187
5,748
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.cover?
def cover?(other) time = self.case.compare_time.to_sym analysis[time].cover?(other.analysis[time], self.case.covering.alpha_level.abs) end
ruby
def cover?(other) time = self.case.compare_time.to_sym analysis[time].cover?(other.analysis[time], self.case.covering.alpha_level.abs) end
[ "def", "cover?", "(", "other", ")", "time", "=", "self", ".", "case", ".", "compare_time", ".", "to_sym", "analysis", "[", "time", "]", ".", "cover?", "(", "other", ".", "analysis", "[", "time", "]", ",", "self", ".", "case", ".", "covering", ".", "alpha_level", ".", "abs", ")", "end" ]
Return true, if other's mean value is indistinguishable from this object's mean after filtering out the noise from the measurements with a Welch's t-Test. This mean's that differences in the mean of both clocks might not inidicate a real performance difference and may be caused by chance.
[ "Return", "true", "if", "other", "s", "mean", "value", "is", "indistinguishable", "from", "this", "object", "s", "mean", "after", "filtering", "out", "the", "noise", "from", "the", "measurements", "with", "a", "Welch", "s", "t", "-", "Test", ".", "This", "mean", "s", "that", "differences", "in", "the", "mean", "of", "both", "clocks", "might", "not", "inidicate", "a", "real", "performance", "difference", "and", "may", "be", "caused", "by", "chance", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L194-L197
5,749
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.to_a
def to_a if @repeat >= 1 (::Bullshit::Clock::ALL_COLUMNS).map do |t| analysis[t].elements end.transpose else [] end end
ruby
def to_a if @repeat >= 1 (::Bullshit::Clock::ALL_COLUMNS).map do |t| analysis[t].elements end.transpose else [] end end
[ "def", "to_a", "if", "@repeat", ">=", "1", "(", "::", "Bullshit", "::", "Clock", "::", "ALL_COLUMNS", ")", ".", "map", "do", "|", "t", "|", "analysis", "[", "t", "]", ".", "elements", "end", ".", "transpose", "else", "[", "]", "end", "end" ]
Returns the measurements as an array of arrays.
[ "Returns", "the", "measurements", "as", "an", "array", "of", "arrays", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L205-L213
5,750
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.take_time
def take_time @time, times = Time.now, Process.times user_time = times.utime + times.cutime # user time of this process and its children system_time = times.stime + times.cstime # system time of this process and its children total_time = user_time + system_time # total time of this process and its children [ @time.to_f, total_time, user_time, system_time ] end
ruby
def take_time @time, times = Time.now, Process.times user_time = times.utime + times.cutime # user time of this process and its children system_time = times.stime + times.cstime # system time of this process and its children total_time = user_time + system_time # total time of this process and its children [ @time.to_f, total_time, user_time, system_time ] end
[ "def", "take_time", "@time", ",", "times", "=", "Time", ".", "now", ",", "Process", ".", "times", "user_time", "=", "times", ".", "utime", "+", "times", ".", "cutime", "# user time of this process and its children", "system_time", "=", "times", ".", "stime", "+", "times", ".", "cstime", "# system time of this process and its children", "total_time", "=", "user_time", "+", "system_time", "# total time of this process and its children", "[", "@time", ".", "to_f", ",", "total_time", ",", "user_time", ",", "system_time", "]", "end" ]
Takes the times an returns an array, consisting of the times in the order of enumerated in the TIMES constant.
[ "Takes", "the", "times", "an", "returns", "an", "array", "consisting", "of", "the", "times", "in", "the", "order", "of", "enumerated", "in", "the", "TIMES", "constant", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L217-L223
5,751
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.measure
def measure before = take_time yield after = take_time @repeat += 1 @times[:repeat] << @repeat @times[:scatter] << @scatter bs = self.case.batch_size.abs if bs and bs > 1 TIMES.each_with_index { |t, i| @times[t] << (after[i] - before[i]) / bs } else TIMES.each_with_index { |t, i| @times[t] << after[i] - before[i] } end @analysis = nil end
ruby
def measure before = take_time yield after = take_time @repeat += 1 @times[:repeat] << @repeat @times[:scatter] << @scatter bs = self.case.batch_size.abs if bs and bs > 1 TIMES.each_with_index { |t, i| @times[t] << (after[i] - before[i]) / bs } else TIMES.each_with_index { |t, i| @times[t] << after[i] - before[i] } end @analysis = nil end
[ "def", "measure", "before", "=", "take_time", "yield", "after", "=", "take_time", "@repeat", "+=", "1", "@times", "[", ":repeat", "]", "<<", "@repeat", "@times", "[", ":scatter", "]", "<<", "@scatter", "bs", "=", "self", ".", "case", ".", "batch_size", ".", "abs", "if", "bs", "and", "bs", ">", "1", "TIMES", ".", "each_with_index", "{", "|", "t", ",", "i", "|", "@times", "[", "t", "]", "<<", "(", "after", "[", "i", "]", "-", "before", "[", "i", "]", ")", "/", "bs", "}", "else", "TIMES", ".", "each_with_index", "{", "|", "t", ",", "i", "|", "@times", "[", "t", "]", "<<", "after", "[", "i", "]", "-", "before", "[", "i", "]", "}", "end", "@analysis", "=", "nil", "end" ]
Take a single measurement. This method should be called with the code to benchmark in a block.
[ "Take", "a", "single", "measurement", ".", "This", "method", "should", "be", "called", "with", "the", "code", "to", "benchmark", "in", "a", "block", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L232-L246
5,752
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.detect_autocorrelation
def detect_autocorrelation(time) analysis[time.to_sym].detect_autocorrelation( self.case.autocorrelation.max_lags.to_i, self.case.autocorrelation.alpha_level.abs) end
ruby
def detect_autocorrelation(time) analysis[time.to_sym].detect_autocorrelation( self.case.autocorrelation.max_lags.to_i, self.case.autocorrelation.alpha_level.abs) end
[ "def", "detect_autocorrelation", "(", "time", ")", "analysis", "[", "time", ".", "to_sym", "]", ".", "detect_autocorrelation", "(", "self", ".", "case", ".", "autocorrelation", ".", "max_lags", ".", "to_i", ",", "self", ".", "case", ".", "autocorrelation", ".", "alpha_level", ".", "abs", ")", "end" ]
Returns the q value for the Ljung-Box statistic of this +time+'s analysis.detect_autocorrelation method.
[ "Returns", "the", "q", "value", "for", "the", "Ljung", "-", "Box", "statistic", "of", "this", "+", "time", "+", "s", "analysis", ".", "detect_autocorrelation", "method", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L282-L286
5,753
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.autocorrelation_plot
def autocorrelation_plot(time) r = autocorrelation time start = @times[:repeat].first ende = (start + r.size) (start...ende).to_a.zip(r) end
ruby
def autocorrelation_plot(time) r = autocorrelation time start = @times[:repeat].first ende = (start + r.size) (start...ende).to_a.zip(r) end
[ "def", "autocorrelation_plot", "(", "time", ")", "r", "=", "autocorrelation", "time", "start", "=", "@times", "[", ":repeat", "]", ".", "first", "ende", "=", "(", "start", "+", "r", ".", "size", ")", "(", "start", "...", "ende", ")", ".", "to_a", ".", "zip", "(", "r", ")", "end" ]
Returns the arrays for the autocorrelation plot, the first array for the numbers of lag measured, the second for the autocorrelation value.
[ "Returns", "the", "arrays", "for", "the", "autocorrelation", "plot", "the", "first", "array", "for", "the", "numbers", "of", "lag", "measured", "the", "second", "for", "the", "autocorrelation", "value", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L365-L370
5,754
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.truncate_data
def truncate_data(offset) for t in ALL_COLUMNS times = @times[t] @times[t] = @times[t][offset, times.size] @repeat = @times[t].size end @analysis = nil self end
ruby
def truncate_data(offset) for t in ALL_COLUMNS times = @times[t] @times[t] = @times[t][offset, times.size] @repeat = @times[t].size end @analysis = nil self end
[ "def", "truncate_data", "(", "offset", ")", "for", "t", "in", "ALL_COLUMNS", "times", "=", "@times", "[", "t", "]", "@times", "[", "t", "]", "=", "@times", "[", "t", "]", "[", "offset", ",", "times", ".", "size", "]", "@repeat", "=", "@times", "[", "t", "]", ".", "size", "end", "@analysis", "=", "nil", "self", "end" ]
Truncate the measurements stored in this clock starting from the integer +offset+.
[ "Truncate", "the", "measurements", "stored", "in", "this", "clock", "starting", "from", "the", "integer", "+", "offset", "+", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L379-L387
5,755
flori/bullshit
lib/bullshit.rb
Bullshit.Clock.find_truncation_offset
def find_truncation_offset truncation = self.case.truncate_data slope_angle = self.case.truncate_data.slope_angle.abs time = self.case.compare_time.to_sym ms = analysis[time].elements.reverse offset = ms.size - 1 @slopes = [] ModuleFunctions.array_window(ms, truncation.window_size) do |data| lr = LinearRegression.new(data) a = lr.a @slopes << [ offset, a ] a.abs > slope_angle and break offset -= 1 end offset < 0 ? 0 : offset end
ruby
def find_truncation_offset truncation = self.case.truncate_data slope_angle = self.case.truncate_data.slope_angle.abs time = self.case.compare_time.to_sym ms = analysis[time].elements.reverse offset = ms.size - 1 @slopes = [] ModuleFunctions.array_window(ms, truncation.window_size) do |data| lr = LinearRegression.new(data) a = lr.a @slopes << [ offset, a ] a.abs > slope_angle and break offset -= 1 end offset < 0 ? 0 : offset end
[ "def", "find_truncation_offset", "truncation", "=", "self", ".", "case", ".", "truncate_data", "slope_angle", "=", "self", ".", "case", ".", "truncate_data", ".", "slope_angle", ".", "abs", "time", "=", "self", ".", "case", ".", "compare_time", ".", "to_sym", "ms", "=", "analysis", "[", "time", "]", ".", "elements", ".", "reverse", "offset", "=", "ms", ".", "size", "-", "1", "@slopes", "=", "[", "]", "ModuleFunctions", ".", "array_window", "(", "ms", ",", "truncation", ".", "window_size", ")", "do", "|", "data", "|", "lr", "=", "LinearRegression", ".", "new", "(", "data", ")", "a", "=", "lr", ".", "a", "@slopes", "<<", "[", "offset", ",", "a", "]", "a", ".", "abs", ">", "slope_angle", "and", "break", "offset", "-=", "1", "end", "offset", "<", "0", "?", "0", ":", "offset", "end" ]
Find an offset from the start of the measurements in this clock to truncate the initial data until a stable state has been reached and return it as an integer.
[ "Find", "an", "offset", "from", "the", "start", "of", "the", "measurements", "in", "this", "clock", "to", "truncate", "the", "initial", "data", "until", "a", "stable", "state", "has", "been", "reached", "and", "return", "it", "as", "an", "integer", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L392-L407
5,756
flori/bullshit
lib/bullshit.rb
Bullshit.CaseMethod.load
def load(fp = file_path) self.clock = self.case.class.clock.new self $DEBUG and warn "Loading '#{fp}' into clock." File.open(fp, 'r') do |f| f.each do |line| line.chomp! line =~ /^\s*#/ and next clock << line.split(/\t/) end end self rescue Errno::ENOENT end
ruby
def load(fp = file_path) self.clock = self.case.class.clock.new self $DEBUG and warn "Loading '#{fp}' into clock." File.open(fp, 'r') do |f| f.each do |line| line.chomp! line =~ /^\s*#/ and next clock << line.split(/\t/) end end self rescue Errno::ENOENT end
[ "def", "load", "(", "fp", "=", "file_path", ")", "self", ".", "clock", "=", "self", ".", "case", ".", "class", ".", "clock", ".", "new", "self", "$DEBUG", "and", "warn", "\"Loading '#{fp}' into clock.\"", "File", ".", "open", "(", "fp", ",", "'r'", ")", "do", "|", "f", "|", "f", ".", "each", "do", "|", "line", "|", "line", ".", "chomp!", "line", "=~", "/", "\\s", "/", "and", "next", "clock", "<<", "line", ".", "split", "(", "/", "\\t", "/", ")", "end", "end", "self", "rescue", "Errno", "::", "ENOENT", "end" ]
Load the data of file +fp+ into this clock.
[ "Load", "the", "data", "of", "file", "+", "fp", "+", "into", "this", "clock", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L481-L493
5,757
flori/bullshit
lib/bullshit.rb
Bullshit.Case.longest_name
def longest_name bmethods.empty? and return 0 bmethods.map { |x| x.short_name.size }.max end
ruby
def longest_name bmethods.empty? and return 0 bmethods.map { |x| x.short_name.size }.max end
[ "def", "longest_name", "bmethods", ".", "empty?", "and", "return", "0", "bmethods", ".", "map", "{", "|", "x", "|", "x", ".", "short_name", ".", "size", "}", ".", "max", "end" ]
Return the length of the longest_name of all these methods' names.
[ "Return", "the", "length", "of", "the", "longest_name", "of", "all", "these", "methods", "names", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L745-L748
5,758
flori/bullshit
lib/bullshit.rb
Bullshit.Case.pre_run
def pre_run(bc_method) setup_name = bc_method.setup_name if respond_to? setup_name $DEBUG and warn "Calling #{setup_name}." __send__(setup_name) end self.class.output.puts "#{bc_method.long_name}:" end
ruby
def pre_run(bc_method) setup_name = bc_method.setup_name if respond_to? setup_name $DEBUG and warn "Calling #{setup_name}." __send__(setup_name) end self.class.output.puts "#{bc_method.long_name}:" end
[ "def", "pre_run", "(", "bc_method", ")", "setup_name", "=", "bc_method", ".", "setup_name", "if", "respond_to?", "setup_name", "$DEBUG", "and", "warn", "\"Calling #{setup_name}.\"", "__send__", "(", "setup_name", ")", "end", "self", ".", "class", ".", "output", ".", "puts", "\"#{bc_method.long_name}:\"", "end" ]
Output before +bc_method+ is run.
[ "Output", "before", "+", "bc_method", "+", "is", "run", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L885-L892
5,759
flori/bullshit
lib/bullshit.rb
Bullshit.Case.run_method
def run_method(bc_method) pre_run bc_method clock = self.class.clock.__send__(self.class.clock_method, bc_method) do __send__(bc_method.name) end bc_method.clock = clock post_run bc_method clock end
ruby
def run_method(bc_method) pre_run bc_method clock = self.class.clock.__send__(self.class.clock_method, bc_method) do __send__(bc_method.name) end bc_method.clock = clock post_run bc_method clock end
[ "def", "run_method", "(", "bc_method", ")", "pre_run", "bc_method", "clock", "=", "self", ".", "class", ".", "clock", ".", "__send__", "(", "self", ".", "class", ".", "clock_method", ",", "bc_method", ")", "do", "__send__", "(", "bc_method", ".", "name", ")", "end", "bc_method", ".", "clock", "=", "clock", "post_run", "bc_method", "clock", "end" ]
Run only pre_run and post_run methods. Yield to the block, if one was given.
[ "Run", "only", "pre_run", "and", "post_run", "methods", ".", "Yield", "to", "the", "block", "if", "one", "was", "given", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L896-L904
5,760
flori/bullshit
lib/bullshit.rb
Bullshit.Case.post_run
def post_run(bc_method) teardown_name = bc_method.teardown_name if respond_to? teardown_name $DEBUG and warn "Calling #{teardown_name}." __send__(bc_method.teardown_name) end end
ruby
def post_run(bc_method) teardown_name = bc_method.teardown_name if respond_to? teardown_name $DEBUG and warn "Calling #{teardown_name}." __send__(bc_method.teardown_name) end end
[ "def", "post_run", "(", "bc_method", ")", "teardown_name", "=", "bc_method", ".", "teardown_name", "if", "respond_to?", "teardown_name", "$DEBUG", "and", "warn", "\"Calling #{teardown_name}.\"", "__send__", "(", "bc_method", ".", "teardown_name", ")", "end", "end" ]
Output after +bc_method+ is run.
[ "Output", "after", "+", "bc_method", "+", "is", "run", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L913-L919
5,761
flori/bullshit
lib/bullshit.rb
Bullshit.Comparison.output_filename
def output_filename(name) path = File.expand_path(name, output_dir) output File.new(path, 'a+') end
ruby
def output_filename(name) path = File.expand_path(name, output_dir) output File.new(path, 'a+') end
[ "def", "output_filename", "(", "name", ")", "path", "=", "File", ".", "expand_path", "(", "name", ",", "output_dir", ")", "output", "File", ".", "new", "(", "path", ",", "'a+'", ")", "end" ]
Output results to the file named +name+.
[ "Output", "results", "to", "the", "file", "named", "+", "name", "+", "." ]
dc5d078bfb82d42bb6bafd9248972c20f52ae40c
https://github.com/flori/bullshit/blob/dc5d078bfb82d42bb6bafd9248972c20f52ae40c/lib/bullshit.rb#L1162-L1165
5,762
SebastianSzturo/inaho
lib/inaho/dictionary.rb
Inaho.Dictionary.validate
def validate errors = [] schema_path = File.expand_path("../../../vendor/AppleDictionarySchema.rng", __FILE__) schema = Nokogiri::XML::RelaxNG(File.open(schema_path)) schema.validate(Nokogiri::XML(self.to_xml)).each do |error| errors << error end if errors.size > 0 return errors else return true end end
ruby
def validate errors = [] schema_path = File.expand_path("../../../vendor/AppleDictionarySchema.rng", __FILE__) schema = Nokogiri::XML::RelaxNG(File.open(schema_path)) schema.validate(Nokogiri::XML(self.to_xml)).each do |error| errors << error end if errors.size > 0 return errors else return true end end
[ "def", "validate", "errors", "=", "[", "]", "schema_path", "=", "File", ".", "expand_path", "(", "\"../../../vendor/AppleDictionarySchema.rng\"", ",", "__FILE__", ")", "schema", "=", "Nokogiri", "::", "XML", "::", "RelaxNG", "(", "File", ".", "open", "(", "schema_path", ")", ")", "schema", ".", "validate", "(", "Nokogiri", "::", "XML", "(", "self", ".", "to_xml", ")", ")", ".", "each", "do", "|", "error", "|", "errors", "<<", "error", "end", "if", "errors", ".", "size", ">", "0", "return", "errors", "else", "return", "true", "end", "end" ]
Validate Dictionary xml with Apple's RelaxNG schema. Returns true if xml is valid. Returns List of Nokogiri::XML::SyntaxError objects if xml is not valid.
[ "Validate", "Dictionary", "xml", "with", "Apple", "s", "RelaxNG", "schema", "." ]
e3664bc59aa90197258d715a9032c18f82b84ebd
https://github.com/SebastianSzturo/inaho/blob/e3664bc59aa90197258d715a9032c18f82b84ebd/lib/inaho/dictionary.rb#L33-L47
5,763
SebastianSzturo/inaho
lib/inaho/dictionary.rb
Inaho.Dictionary.to_xml
def to_xml xml = "" xml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" xml << "<d:dictionary xmlns=\"http://www.w3.org/1999/xhtml\" " xml << "xmlns:d=\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\">\n" @entries.each do |entry| next if entry.to_xml.nil? xml << entry.to_xml end xml << "</d:dictionary>" return xml end
ruby
def to_xml xml = "" xml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" xml << "<d:dictionary xmlns=\"http://www.w3.org/1999/xhtml\" " xml << "xmlns:d=\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\">\n" @entries.each do |entry| next if entry.to_xml.nil? xml << entry.to_xml end xml << "</d:dictionary>" return xml end
[ "def", "to_xml", "xml", "=", "\"\"", "xml", "<<", "\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"", "xml", "<<", "\"<d:dictionary xmlns=\\\"http://www.w3.org/1999/xhtml\\\" \"", "xml", "<<", "\"xmlns:d=\\\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\\\">\\n\"", "@entries", ".", "each", "do", "|", "entry", "|", "next", "if", "entry", ".", "to_xml", ".", "nil?", "xml", "<<", "entry", ".", "to_xml", "end", "xml", "<<", "\"</d:dictionary>\"", "return", "xml", "end" ]
Generates xml for Dictionary and Entry objects. Returns String.
[ "Generates", "xml", "for", "Dictionary", "and", "Entry", "objects", "." ]
e3664bc59aa90197258d715a9032c18f82b84ebd
https://github.com/SebastianSzturo/inaho/blob/e3664bc59aa90197258d715a9032c18f82b84ebd/lib/inaho/dictionary.rb#L52-L65
5,764
wilddima/stribog
lib/stribog/create_hash.rb
Stribog.CreateHash.return_hash
def return_hash(final_vector) case digest_length when 512 create_digest(final_vector) when 256 create_digest(vector_from_array(final_vector[0..31])) else raise ArgumentError, "digest length must be equal to 256 or 512, not #{digest_length}" end end
ruby
def return_hash(final_vector) case digest_length when 512 create_digest(final_vector) when 256 create_digest(vector_from_array(final_vector[0..31])) else raise ArgumentError, "digest length must be equal to 256 or 512, not #{digest_length}" end end
[ "def", "return_hash", "(", "final_vector", ")", "case", "digest_length", "when", "512", "create_digest", "(", "final_vector", ")", "when", "256", "create_digest", "(", "vector_from_array", "(", "final_vector", "[", "0", "..", "31", "]", ")", ")", "else", "raise", "ArgumentError", ",", "\"digest length must be equal to 256 or 512, not #{digest_length}\"", "end", "end" ]
Method, which return digest, dependent on them length
[ "Method", "which", "return", "digest", "dependent", "on", "them", "length" ]
696e0d4f18f5c210a0fa9e20af49bbb55c29ad72
https://github.com/wilddima/stribog/blob/696e0d4f18f5c210a0fa9e20af49bbb55c29ad72/lib/stribog/create_hash.rb#L58-L68
5,765
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.parse_options
def parse_options(parser_configuration = {}) raise_on_invalid_option = parser_configuration.has_key?(:raise_on_invalid_option) ? parser_configuration[:raise_on_invalid_option] : true parse_base_options = parser_configuration.has_key?(:parse_base_options) ? parser_configuration[:parse_base_options] : true logger.debug "parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}" @option_parser ||= OptionParser.new option_parser.banner = help + "\n\nOptions:" if parse_base_options option_parser.on("--template [NAME]", "Use a template to render output. (default=default.slim)") do |t| options[:template] = t.nil? ? "default.slim" : t @template = options[:template] end option_parser.on("--output FILENAME", "Render output directly to a file") do |f| options[:output] = f @output = options[:output] end option_parser.on("--force", "Overwrite file output without prompting") do |f| options[:force] = f end option_parser.on("-r", "--repos a1,a2,a3", "--asset a1,a2,a3", "--filter a1,a2,a3", Array, "List of regex asset name filters") do |list| options[:filter] = list end # NOTE: OptionParser will add short options, there is no way to stop '-m' from being the same as '--match' option_parser.on("--match [MODE]", "Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)") do |m| options[:match] = m || "ALL" options[:match].upcase! unless ["ALL", "FIRST", "EXACT", "ONE"].include?(options[:match]) puts "invalid match mode option: #{options[:match]}" exit 1 end end end # allow decendants to add options yield option_parser if block_given? # reprocess args for known options, see binary wrapper for first pass # (first pass doesn't know about action specific options), find all # action options that may come after the action/subcommand (options # before subcommand have already been processed) and its args logger.debug "args before reprocessing: #{@args.inspect}" begin option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end logger.debug "args before unknown collection: #{@args.inspect}" unknown_args = [] while unknown_arg = @args.shift logger.debug "unknown_arg: #{unknown_arg.inspect}" unknown_args << unknown_arg begin # consume options and stop at an arg option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end end logger.debug "args after unknown collection: #{@args.inspect}" @args = unknown_args.dup logger.debug "args after reprocessing: #{@args.inspect}" logger.debug "configuration after reprocessing: #{@configuration.inspect}" logger.debug "options after reprocessing: #{@options.inspect}" option_parser end
ruby
def parse_options(parser_configuration = {}) raise_on_invalid_option = parser_configuration.has_key?(:raise_on_invalid_option) ? parser_configuration[:raise_on_invalid_option] : true parse_base_options = parser_configuration.has_key?(:parse_base_options) ? parser_configuration[:parse_base_options] : true logger.debug "parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}" @option_parser ||= OptionParser.new option_parser.banner = help + "\n\nOptions:" if parse_base_options option_parser.on("--template [NAME]", "Use a template to render output. (default=default.slim)") do |t| options[:template] = t.nil? ? "default.slim" : t @template = options[:template] end option_parser.on("--output FILENAME", "Render output directly to a file") do |f| options[:output] = f @output = options[:output] end option_parser.on("--force", "Overwrite file output without prompting") do |f| options[:force] = f end option_parser.on("-r", "--repos a1,a2,a3", "--asset a1,a2,a3", "--filter a1,a2,a3", Array, "List of regex asset name filters") do |list| options[:filter] = list end # NOTE: OptionParser will add short options, there is no way to stop '-m' from being the same as '--match' option_parser.on("--match [MODE]", "Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)") do |m| options[:match] = m || "ALL" options[:match].upcase! unless ["ALL", "FIRST", "EXACT", "ONE"].include?(options[:match]) puts "invalid match mode option: #{options[:match]}" exit 1 end end end # allow decendants to add options yield option_parser if block_given? # reprocess args for known options, see binary wrapper for first pass # (first pass doesn't know about action specific options), find all # action options that may come after the action/subcommand (options # before subcommand have already been processed) and its args logger.debug "args before reprocessing: #{@args.inspect}" begin option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end logger.debug "args before unknown collection: #{@args.inspect}" unknown_args = [] while unknown_arg = @args.shift logger.debug "unknown_arg: #{unknown_arg.inspect}" unknown_args << unknown_arg begin # consume options and stop at an arg option_parser.order!(@args) rescue OptionParser::InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else # parse and consume until we hit an unknown option (not arg), put it back so it # can be shifted into the new array e.recover(@args) end end end logger.debug "args after unknown collection: #{@args.inspect}" @args = unknown_args.dup logger.debug "args after reprocessing: #{@args.inspect}" logger.debug "configuration after reprocessing: #{@configuration.inspect}" logger.debug "options after reprocessing: #{@options.inspect}" option_parser end
[ "def", "parse_options", "(", "parser_configuration", "=", "{", "}", ")", "raise_on_invalid_option", "=", "parser_configuration", ".", "has_key?", "(", ":raise_on_invalid_option", ")", "?", "parser_configuration", "[", ":raise_on_invalid_option", "]", ":", "true", "parse_base_options", "=", "parser_configuration", ".", "has_key?", "(", ":parse_base_options", ")", "?", "parser_configuration", "[", ":parse_base_options", "]", ":", "true", "logger", ".", "debug", "\"parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}\"", "@option_parser", "||=", "OptionParser", ".", "new", "option_parser", ".", "banner", "=", "help", "+", "\"\\n\\nOptions:\"", "if", "parse_base_options", "option_parser", ".", "on", "(", "\"--template [NAME]\"", ",", "\"Use a template to render output. (default=default.slim)\"", ")", "do", "|", "t", "|", "options", "[", ":template", "]", "=", "t", ".", "nil?", "?", "\"default.slim\"", ":", "t", "@template", "=", "options", "[", ":template", "]", "end", "option_parser", ".", "on", "(", "\"--output FILENAME\"", ",", "\"Render output directly to a file\"", ")", "do", "|", "f", "|", "options", "[", ":output", "]", "=", "f", "@output", "=", "options", "[", ":output", "]", "end", "option_parser", ".", "on", "(", "\"--force\"", ",", "\"Overwrite file output without prompting\"", ")", "do", "|", "f", "|", "options", "[", ":force", "]", "=", "f", "end", "option_parser", ".", "on", "(", "\"-r\"", ",", "\"--repos a1,a2,a3\"", ",", "\"--asset a1,a2,a3\"", ",", "\"--filter a1,a2,a3\"", ",", "Array", ",", "\"List of regex asset name filters\"", ")", "do", "|", "list", "|", "options", "[", ":filter", "]", "=", "list", "end", "# NOTE: OptionParser will add short options, there is no way to stop '-m' from being the same as '--match'", "option_parser", ".", "on", "(", "\"--match [MODE]\"", ",", "\"Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)\"", ")", "do", "|", "m", "|", "options", "[", ":match", "]", "=", "m", "||", "\"ALL\"", "options", "[", ":match", "]", ".", "upcase!", "unless", "[", "\"ALL\"", ",", "\"FIRST\"", ",", "\"EXACT\"", ",", "\"ONE\"", "]", ".", "include?", "(", "options", "[", ":match", "]", ")", "puts", "\"invalid match mode option: #{options[:match]}\"", "exit", "1", "end", "end", "end", "# allow decendants to add options", "yield", "option_parser", "if", "block_given?", "# reprocess args for known options, see binary wrapper for first pass", "# (first pass doesn't know about action specific options), find all", "# action options that may come after the action/subcommand (options", "# before subcommand have already been processed) and its args", "logger", ".", "debug", "\"args before reprocessing: #{@args.inspect}\"", "begin", "option_parser", ".", "order!", "(", "@args", ")", "rescue", "OptionParser", "::", "InvalidOption", "=>", "e", "if", "raise_on_invalid_option", "puts", "\"option error: #{e}\"", "puts", "option_parser", "exit", "1", "else", "# parse and consume until we hit an unknown option (not arg), put it back so it", "# can be shifted into the new array", "e", ".", "recover", "(", "@args", ")", "end", "end", "logger", ".", "debug", "\"args before unknown collection: #{@args.inspect}\"", "unknown_args", "=", "[", "]", "while", "unknown_arg", "=", "@args", ".", "shift", "logger", ".", "debug", "\"unknown_arg: #{unknown_arg.inspect}\"", "unknown_args", "<<", "unknown_arg", "begin", "# consume options and stop at an arg", "option_parser", ".", "order!", "(", "@args", ")", "rescue", "OptionParser", "::", "InvalidOption", "=>", "e", "if", "raise_on_invalid_option", "puts", "\"option error: #{e}\"", "puts", "option_parser", "exit", "1", "else", "# parse and consume until we hit an unknown option (not arg), put it back so it", "# can be shifted into the new array", "e", ".", "recover", "(", "@args", ")", "end", "end", "end", "logger", ".", "debug", "\"args after unknown collection: #{@args.inspect}\"", "@args", "=", "unknown_args", ".", "dup", "logger", ".", "debug", "\"args after reprocessing: #{@args.inspect}\"", "logger", ".", "debug", "\"configuration after reprocessing: #{@configuration.inspect}\"", "logger", ".", "debug", "\"options after reprocessing: #{@options.inspect}\"", "option_parser", "end" ]
Parse generic action options for all decendant actions @return [OptionParser] for use by decendant actions
[ "Parse", "generic", "action", "options", "for", "all", "decendant", "actions" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L47-L136
5,766
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.asset_options
def asset_options # include all base action options result = options.deep_clone # anything left on the command line should be filters as all options have # been consumed, for pass through options, filters must be ignored by overwritting them filters = args.dup filters += result[:filter] if result[:filter] result = result.merge(:filter => filters) unless filters.empty? # asset type to create type = result[:type] || asset_type result = result.merge(:type => type) # optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified result = result.merge(:assets_folder => configuration[:folders][:assets]) if configuration[:folders] # optional key: :base_folder is the folder that contains the main config file result = result.merge(:base_folder => File.dirname(configuration[:configuration_filename])) if configuration[:configuration_filename] result end
ruby
def asset_options # include all base action options result = options.deep_clone # anything left on the command line should be filters as all options have # been consumed, for pass through options, filters must be ignored by overwritting them filters = args.dup filters += result[:filter] if result[:filter] result = result.merge(:filter => filters) unless filters.empty? # asset type to create type = result[:type] || asset_type result = result.merge(:type => type) # optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified result = result.merge(:assets_folder => configuration[:folders][:assets]) if configuration[:folders] # optional key: :base_folder is the folder that contains the main config file result = result.merge(:base_folder => File.dirname(configuration[:configuration_filename])) if configuration[:configuration_filename] result end
[ "def", "asset_options", "# include all base action options", "result", "=", "options", ".", "deep_clone", "# anything left on the command line should be filters as all options have", "# been consumed, for pass through options, filters must be ignored by overwritting them", "filters", "=", "args", ".", "dup", "filters", "+=", "result", "[", ":filter", "]", "if", "result", "[", ":filter", "]", "result", "=", "result", ".", "merge", "(", ":filter", "=>", "filters", ")", "unless", "filters", ".", "empty?", "# asset type to create", "type", "=", "result", "[", ":type", "]", "||", "asset_type", "result", "=", "result", ".", "merge", "(", ":type", "=>", "type", ")", "# optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified", "result", "=", "result", ".", "merge", "(", ":assets_folder", "=>", "configuration", "[", ":folders", "]", "[", ":assets", "]", ")", "if", "configuration", "[", ":folders", "]", "# optional key: :base_folder is the folder that contains the main config file", "result", "=", "result", ".", "merge", "(", ":base_folder", "=>", "File", ".", "dirname", "(", "configuration", "[", ":configuration_filename", "]", ")", ")", "if", "configuration", "[", ":configuration_filename", "]", "result", "end" ]
asset options separated from assets to make it easier to override assets
[ "asset", "options", "separated", "from", "assets", "to", "make", "it", "easier", "to", "override", "assets" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L185-L206
5,767
robertwahler/repo_manager
lib/repo_manager/actions/base_action.rb
RepoManager.BaseAction.render
def render(view_options=configuration) logger.debug "rendering" result = "" if template logger.debug "rendering with template : #{template}" view = AppView.new(items, view_options) view.template = template result = view.render else items.each_with_index do |item, index| result += "\n" unless index == 0 result += item.name.green + ":\n" if item.respond_to?(:attributes) attributes = item.attributes.deep_clone result += attributes.recursively_stringify_keys!.to_conf.gsub(/\s+$/, '') # strip trailing whitespace from YAML result += "\n" end end end result end
ruby
def render(view_options=configuration) logger.debug "rendering" result = "" if template logger.debug "rendering with template : #{template}" view = AppView.new(items, view_options) view.template = template result = view.render else items.each_with_index do |item, index| result += "\n" unless index == 0 result += item.name.green + ":\n" if item.respond_to?(:attributes) attributes = item.attributes.deep_clone result += attributes.recursively_stringify_keys!.to_conf.gsub(/\s+$/, '') # strip trailing whitespace from YAML result += "\n" end end end result end
[ "def", "render", "(", "view_options", "=", "configuration", ")", "logger", ".", "debug", "\"rendering\"", "result", "=", "\"\"", "if", "template", "logger", ".", "debug", "\"rendering with template : #{template}\"", "view", "=", "AppView", ".", "new", "(", "items", ",", "view_options", ")", "view", ".", "template", "=", "template", "result", "=", "view", ".", "render", "else", "items", ".", "each_with_index", "do", "|", "item", ",", "index", "|", "result", "+=", "\"\\n\"", "unless", "index", "==", "0", "result", "+=", "item", ".", "name", ".", "green", "+", "\":\\n\"", "if", "item", ".", "respond_to?", "(", ":attributes", ")", "attributes", "=", "item", ".", "attributes", ".", "deep_clone", "result", "+=", "attributes", ".", "recursively_stringify_keys!", ".", "to_conf", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", "# strip trailing whitespace from YAML", "result", "+=", "\"\\n\"", "end", "end", "end", "result", "end" ]
Render items result to a string @return [String] suitable for displaying on STDOUT or writing to a file
[ "Render", "items", "result", "to", "a", "string" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/actions/base_action.rb#L218-L238
5,768
Yellowen/site_framework
lib/site_framework/middleware.rb
SiteFramework.Middleware.call
def call(env) # Create a method called domain which will return the current domain # name Rails.application.send :define_singleton_method, 'domain_name' do env['SERVER_NAME'] end # Create `fetch_domain` method on `Rails.application` # only if it didn't already define. unless Rails.application.respond_to? :fetch_domain Rails.application.send :define_singleton_method, 'fetch_domain' do if defined? ActiveRecord Domain.find_by(nam: Rails.application.domain_name) elsif defined? Mongoid Site.where('domains.name' => Rails.application.domain_name).domains.first end end end Rails.application.send :define_singleton_method, 'site' do site = nil unless Rails.application.domain.nil? site = Rails.application.domain.site end site end Rails.application @app.call(env) end
ruby
def call(env) # Create a method called domain which will return the current domain # name Rails.application.send :define_singleton_method, 'domain_name' do env['SERVER_NAME'] end # Create `fetch_domain` method on `Rails.application` # only if it didn't already define. unless Rails.application.respond_to? :fetch_domain Rails.application.send :define_singleton_method, 'fetch_domain' do if defined? ActiveRecord Domain.find_by(nam: Rails.application.domain_name) elsif defined? Mongoid Site.where('domains.name' => Rails.application.domain_name).domains.first end end end Rails.application.send :define_singleton_method, 'site' do site = nil unless Rails.application.domain.nil? site = Rails.application.domain.site end site end Rails.application @app.call(env) end
[ "def", "call", "(", "env", ")", "# Create a method called domain which will return the current domain", "# name", "Rails", ".", "application", ".", "send", ":define_singleton_method", ",", "'domain_name'", "do", "env", "[", "'SERVER_NAME'", "]", "end", "# Create `fetch_domain` method on `Rails.application`", "# only if it didn't already define.", "unless", "Rails", ".", "application", ".", "respond_to?", ":fetch_domain", "Rails", ".", "application", ".", "send", ":define_singleton_method", ",", "'fetch_domain'", "do", "if", "defined?", "ActiveRecord", "Domain", ".", "find_by", "(", "nam", ":", "Rails", ".", "application", ".", "domain_name", ")", "elsif", "defined?", "Mongoid", "Site", ".", "where", "(", "'domains.name'", "=>", "Rails", ".", "application", ".", "domain_name", ")", ".", "domains", ".", "first", "end", "end", "end", "Rails", ".", "application", ".", "send", ":define_singleton_method", ",", "'site'", "do", "site", "=", "nil", "unless", "Rails", ".", "application", ".", "domain", ".", "nil?", "site", "=", "Rails", ".", "application", ".", "domain", ".", "site", "end", "site", "end", "Rails", ".", "application", "@app", ".", "call", "(", "env", ")", "end" ]
Middleware initializer method which gets the `app` from previous middleware
[ "Middleware", "initializer", "method", "which", "gets", "the", "app", "from", "previous", "middleware" ]
d4b1067c37c09c802aa4e1d5588ffdd3631f6395
https://github.com/Yellowen/site_framework/blob/d4b1067c37c09c802aa4e1d5588ffdd3631f6395/lib/site_framework/middleware.rb#L13-L42
5,769
janlelis/fresh
lib/ripl/fresh.rb
Ripl.Fresh.loop_eval
def loop_eval(input) if input == '' @command_mode = :system and return end case @command_mode when :system # generate ruby code to execute the command if !@result_storage ruby_command_code = "_ = system '#{ input }'\n" else temp_file = "/tmp/ripl-fresh_#{ rand 12345678901234567890 }" ruby_command_code = "_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\n" # assign result to result storage variable case @result_operator when '=>', '=>>' result_literal = "[]" formatted_result = "File.read('#{ temp_file }').split($/)" operator = @result_operator == '=>>' ? '+=' : '=' when '~>', '~>>' result_literal = "''" formatted_result = "File.read('#{ temp_file }')" operator = @result_operator == '~>>' ? '<<' : '=' end ruby_command_code << %Q% #{ @result_storage } ||= #{ result_literal } #{ @result_storage } #{ operator } #{ formatted_result } FileUtils.rm '#{ temp_file }' % end # ruby_command_code << "raise( SystemCallError.new $?.exitstatus ) if !_\n" # easy auto indent ruby_command_code << "if !_ raise( SystemCallError.new $?.exitstatus ) end;" super @input = ruby_command_code when :mixed # call the ruby method, but with shell style arguments TODO more shell like (e.g. "") method_name, *args = *input.split super @input = "#{ method_name }(*#{ args })" else # good old :ruby super end end
ruby
def loop_eval(input) if input == '' @command_mode = :system and return end case @command_mode when :system # generate ruby code to execute the command if !@result_storage ruby_command_code = "_ = system '#{ input }'\n" else temp_file = "/tmp/ripl-fresh_#{ rand 12345678901234567890 }" ruby_command_code = "_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\n" # assign result to result storage variable case @result_operator when '=>', '=>>' result_literal = "[]" formatted_result = "File.read('#{ temp_file }').split($/)" operator = @result_operator == '=>>' ? '+=' : '=' when '~>', '~>>' result_literal = "''" formatted_result = "File.read('#{ temp_file }')" operator = @result_operator == '~>>' ? '<<' : '=' end ruby_command_code << %Q% #{ @result_storage } ||= #{ result_literal } #{ @result_storage } #{ operator } #{ formatted_result } FileUtils.rm '#{ temp_file }' % end # ruby_command_code << "raise( SystemCallError.new $?.exitstatus ) if !_\n" # easy auto indent ruby_command_code << "if !_ raise( SystemCallError.new $?.exitstatus ) end;" super @input = ruby_command_code when :mixed # call the ruby method, but with shell style arguments TODO more shell like (e.g. "") method_name, *args = *input.split super @input = "#{ method_name }(*#{ args })" else # good old :ruby super end end
[ "def", "loop_eval", "(", "input", ")", "if", "input", "==", "''", "@command_mode", "=", ":system", "and", "return", "end", "case", "@command_mode", "when", ":system", "# generate ruby code to execute the command", "if", "!", "@result_storage", "ruby_command_code", "=", "\"_ = system '#{ input }'\\n\"", "else", "temp_file", "=", "\"/tmp/ripl-fresh_#{ rand 12345678901234567890 }\"", "ruby_command_code", "=", "\"_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\\n\"", "# assign result to result storage variable", "case", "@result_operator", "when", "'=>'", ",", "'=>>'", "result_literal", "=", "\"[]\"", "formatted_result", "=", "\"File.read('#{ temp_file }').split($/)\"", "operator", "=", "@result_operator", "==", "'=>>'", "?", "'+='", ":", "'='", "when", "'~>'", ",", "'~>>'", "result_literal", "=", "\"''\"", "formatted_result", "=", "\"File.read('#{ temp_file }')\"", "operator", "=", "@result_operator", "==", "'~>>'", "?", "'<<'", ":", "'='", "end", "ruby_command_code", "<<", "%Q%\n #{ @result_storage } ||= #{ result_literal }\n #{ @result_storage } #{ operator } #{ formatted_result }\n FileUtils.rm '#{ temp_file }'\n %", "end", "# ruby_command_code << \"raise( SystemCallError.new $?.exitstatus ) if !_\\n\" # easy auto indent", "ruby_command_code", "<<", "\"if !_\n raise( SystemCallError.new $?.exitstatus )\n end;\"", "super", "@input", "=", "ruby_command_code", "when", ":mixed", "# call the ruby method, but with shell style arguments TODO more shell like (e.g. \"\")", "method_name", ",", "*", "args", "=", "input", ".", "split", "super", "@input", "=", "\"#{ method_name }(*#{ args })\"", "else", "# good old :ruby", "super", "end", "end" ]
get result (depending on @command_mode)
[ "get", "result", "(", "depending", "on" ]
5bd2417232cf035f28b8ee16c212da162f2770a5
https://github.com/janlelis/fresh/blob/5bd2417232cf035f28b8ee16c212da162f2770a5/lib/ripl/fresh.rb#L60-L105
5,770
fcheung/corefoundation
lib/corefoundation/data.rb
CF.Data.to_s
def to_s ptr = CF.CFDataGetBytePtr(self) if CF::String::HAS_ENCODING ptr.read_string(CF.CFDataGetLength(self)).force_encoding(Encoding::ASCII_8BIT) else ptr.read_string(CF.CFDataGetLength(self)) end end
ruby
def to_s ptr = CF.CFDataGetBytePtr(self) if CF::String::HAS_ENCODING ptr.read_string(CF.CFDataGetLength(self)).force_encoding(Encoding::ASCII_8BIT) else ptr.read_string(CF.CFDataGetLength(self)) end end
[ "def", "to_s", "ptr", "=", "CF", ".", "CFDataGetBytePtr", "(", "self", ")", "if", "CF", "::", "String", "::", "HAS_ENCODING", "ptr", ".", "read_string", "(", "CF", ".", "CFDataGetLength", "(", "self", ")", ")", ".", "force_encoding", "(", "Encoding", "::", "ASCII_8BIT", ")", "else", "ptr", ".", "read_string", "(", "CF", ".", "CFDataGetLength", "(", "self", ")", ")", "end", "end" ]
Creates a ruby string from the wrapped data. The encoding will always be ASCII_8BIT @return [String]
[ "Creates", "a", "ruby", "string", "from", "the", "wrapped", "data", ".", "The", "encoding", "will", "always", "be", "ASCII_8BIT" ]
a5c766359e74f873902d916e9fb051ec7fdedbb9
https://github.com/fcheung/corefoundation/blob/a5c766359e74f873902d916e9fb051ec7fdedbb9/lib/corefoundation/data.rb#L24-L31
5,771
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.set_build_vars
def set_build_vars warning_flags = ' -W -Wall' if 'release' == @config.release optimization_flags = " #{@config.optimization_release} -DRELEASE" else optimization_flags = " #{@config.optimization_dbg} -g" end # we could make these also arrays of source directories ... @settings['APP_SRC_DIR'] = 'src/app' @settings['LIB_SRC_DIR'] = 'src/lib' # derived settings @settings['BUILD_DIR'] = "#{build_dir}" @settings['LIB_OUT'] = "#{@settings['BUILD_DIR']}/libs" @settings['APP_OUT'] = "#{@settings['BUILD_DIR']}/apps" unless @settings['OECORE_TARGET_SYSROOT'].nil? || @settings['OECORE_TARGET_SYSROOT'].empty? @settings['SYS_LFLAGS'] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib" end # set LD_LIBRARY_PATH @settings['LD_LIBRARY_PATH'] = @settings['LIB_OUT'] # standard settings @settings['CXXFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_cpp}" @settings['CFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_c}" if @settings['PRJ_TYPE'] == 'SOLIB' @settings['CXXFLAGS'] += ' -fPIC' @settings['CFLAGS'] += ' -fPIC' end # !! don't change order of the following string components without care !! @settings['LDFLAGS'] = @settings['LDFLAGS'] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group" end
ruby
def set_build_vars warning_flags = ' -W -Wall' if 'release' == @config.release optimization_flags = " #{@config.optimization_release} -DRELEASE" else optimization_flags = " #{@config.optimization_dbg} -g" end # we could make these also arrays of source directories ... @settings['APP_SRC_DIR'] = 'src/app' @settings['LIB_SRC_DIR'] = 'src/lib' # derived settings @settings['BUILD_DIR'] = "#{build_dir}" @settings['LIB_OUT'] = "#{@settings['BUILD_DIR']}/libs" @settings['APP_OUT'] = "#{@settings['BUILD_DIR']}/apps" unless @settings['OECORE_TARGET_SYSROOT'].nil? || @settings['OECORE_TARGET_SYSROOT'].empty? @settings['SYS_LFLAGS'] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib" end # set LD_LIBRARY_PATH @settings['LD_LIBRARY_PATH'] = @settings['LIB_OUT'] # standard settings @settings['CXXFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_cpp}" @settings['CFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_c}" if @settings['PRJ_TYPE'] == 'SOLIB' @settings['CXXFLAGS'] += ' -fPIC' @settings['CFLAGS'] += ' -fPIC' end # !! don't change order of the following string components without care !! @settings['LDFLAGS'] = @settings['LDFLAGS'] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group" end
[ "def", "set_build_vars", "warning_flags", "=", "' -W -Wall'", "if", "'release'", "==", "@config", ".", "release", "optimization_flags", "=", "\" #{@config.optimization_release} -DRELEASE\"", "else", "optimization_flags", "=", "\" #{@config.optimization_dbg} -g\"", "end", "# we could make these also arrays of source directories ...", "@settings", "[", "'APP_SRC_DIR'", "]", "=", "'src/app'", "@settings", "[", "'LIB_SRC_DIR'", "]", "=", "'src/lib'", "# derived settings", "@settings", "[", "'BUILD_DIR'", "]", "=", "\"#{build_dir}\"", "@settings", "[", "'LIB_OUT'", "]", "=", "\"#{@settings['BUILD_DIR']}/libs\"", "@settings", "[", "'APP_OUT'", "]", "=", "\"#{@settings['BUILD_DIR']}/apps\"", "unless", "@settings", "[", "'OECORE_TARGET_SYSROOT'", "]", ".", "nil?", "||", "@settings", "[", "'OECORE_TARGET_SYSROOT'", "]", ".", "empty?", "@settings", "[", "'SYS_LFLAGS'", "]", "=", "\"-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib\"", "end", "# set LD_LIBRARY_PATH", "@settings", "[", "'LD_LIBRARY_PATH'", "]", "=", "@settings", "[", "'LIB_OUT'", "]", "# standard settings", "@settings", "[", "'CXXFLAGS'", "]", "+=", "warning_flags", "+", "optimization_flags", "+", "\" #{@config.language_std_cpp}\"", "@settings", "[", "'CFLAGS'", "]", "+=", "warning_flags", "+", "optimization_flags", "+", "\" #{@config.language_std_c}\"", "if", "@settings", "[", "'PRJ_TYPE'", "]", "==", "'SOLIB'", "@settings", "[", "'CXXFLAGS'", "]", "+=", "' -fPIC'", "@settings", "[", "'CFLAGS'", "]", "+=", "' -fPIC'", "end", "# !! don't change order of the following string components without care !!", "@settings", "[", "'LDFLAGS'", "]", "=", "@settings", "[", "'LDFLAGS'", "]", "+", "\" -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group\"", "end" ]
Set common build variables
[ "Set", "common", "build", "variables" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L188-L220
5,772
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.reduce_libs_to_bare_minimum
def reduce_libs_to_bare_minimum(libs) rv = libs.clone lib_entries = RakeOE::PrjFileCache.get_lib_entries(libs) lib_entries.each_pair do |lib, entry| rv.delete(lib) unless RakeOE::PrjFileCache.project_entry_buildable?(entry, @target) end rv end
ruby
def reduce_libs_to_bare_minimum(libs) rv = libs.clone lib_entries = RakeOE::PrjFileCache.get_lib_entries(libs) lib_entries.each_pair do |lib, entry| rv.delete(lib) unless RakeOE::PrjFileCache.project_entry_buildable?(entry, @target) end rv end
[ "def", "reduce_libs_to_bare_minimum", "(", "libs", ")", "rv", "=", "libs", ".", "clone", "lib_entries", "=", "RakeOE", "::", "PrjFileCache", ".", "get_lib_entries", "(", "libs", ")", "lib_entries", ".", "each_pair", "do", "|", "lib", ",", "entry", "|", "rv", ".", "delete", "(", "lib", ")", "unless", "RakeOE", "::", "PrjFileCache", ".", "project_entry_buildable?", "(", "entry", ",", "@target", ")", "end", "rv", "end" ]
Reduces the given list of libraries to bare minimum, i.e. the minimum needed for actual platform @libs list of libraries @return reduced list of libraries
[ "Reduces", "the", "given", "list", "of", "libraries", "to", "bare", "minimum", "i", ".", "e", ".", "the", "minimum", "needed", "for", "actual", "platform" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L322-L329
5,773
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.libs_for_binary
def libs_for_binary(a_binary, visited=[]) return [] if visited.include?(a_binary) visited << a_binary pre = Rake::Task[a_binary].prerequisites rv = [] pre.each do |p| next if (File.extname(p) != '.a') && (File.extname(p) != '.so') next if p =~ /\-app\.a/ rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '') rv += libs_for_binary(p, visited) # Recursive call end reduce_libs_to_bare_minimum(rv.uniq) end
ruby
def libs_for_binary(a_binary, visited=[]) return [] if visited.include?(a_binary) visited << a_binary pre = Rake::Task[a_binary].prerequisites rv = [] pre.each do |p| next if (File.extname(p) != '.a') && (File.extname(p) != '.so') next if p =~ /\-app\.a/ rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '') rv += libs_for_binary(p, visited) # Recursive call end reduce_libs_to_bare_minimum(rv.uniq) end
[ "def", "libs_for_binary", "(", "a_binary", ",", "visited", "=", "[", "]", ")", "return", "[", "]", "if", "visited", ".", "include?", "(", "a_binary", ")", "visited", "<<", "a_binary", "pre", "=", "Rake", "::", "Task", "[", "a_binary", "]", ".", "prerequisites", "rv", "=", "[", "]", "pre", ".", "each", "do", "|", "p", "|", "next", "if", "(", "File", ".", "extname", "(", "p", ")", "!=", "'.a'", ")", "&&", "(", "File", ".", "extname", "(", "p", ")", "!=", "'.so'", ")", "next", "if", "p", "=~", "/", "\\-", "\\.", "/", "rv", "<<", "File", ".", "basename", "(", "p", ")", ".", "gsub", "(", "/", "\\.", "\\.", "/", ",", "''", ")", "rv", "+=", "libs_for_binary", "(", "p", ",", "visited", ")", "# Recursive call", "end", "reduce_libs_to_bare_minimum", "(", "rv", ".", "uniq", ")", "end" ]
Return array of library prerequisites for given file
[ "Return", "array", "of", "library", "prerequisites", "for", "given", "file" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L333-L348
5,774
rakeoe/rakeoe
lib/rakeoe/toolchain.rb
RakeOE.Toolchain.obj
def obj(params = {}) extension = File.extname(params[:source]) object = params[:object] source = params[:source] incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}" case when cpp_source_extensions.include?(extension) flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS'] compiler = "#{@settings['CXX']} -x c++ " when c_source_extensions.include?(extension) flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS'] compiler = "#{@settings['CC']} -x c " when as_source_extensions.include?(extension) flags = '' compiler = "#{@settings['AS']}" else raise "unsupported source file extension (#{extension}) for creating object!" end sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}" end
ruby
def obj(params = {}) extension = File.extname(params[:source]) object = params[:object] source = params[:source] incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}" case when cpp_source_extensions.include?(extension) flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS'] compiler = "#{@settings['CXX']} -x c++ " when c_source_extensions.include?(extension) flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS'] compiler = "#{@settings['CC']} -x c " when as_source_extensions.include?(extension) flags = '' compiler = "#{@settings['AS']}" else raise "unsupported source file extension (#{extension}) for creating object!" end sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}" end
[ "def", "obj", "(", "params", "=", "{", "}", ")", "extension", "=", "File", ".", "extname", "(", "params", "[", ":source", "]", ")", "object", "=", "params", "[", ":object", "]", "source", "=", "params", "[", ":source", "]", "incs", "=", "compiler_incs_for", "(", "params", "[", ":includes", "]", ")", "+", "\" #{@settings['LIB_INC']}\"", "case", "when", "cpp_source_extensions", ".", "include?", "(", "extension", ")", "flags", "=", "@settings", "[", "'CXXFLAGS'", "]", "+", "' '", "+", "params", "[", ":settings", "]", "[", "'ADD_CXXFLAGS'", "]", "compiler", "=", "\"#{@settings['CXX']} -x c++ \"", "when", "c_source_extensions", ".", "include?", "(", "extension", ")", "flags", "=", "@settings", "[", "'CFLAGS'", "]", "+", "' '", "+", "params", "[", ":settings", "]", "[", "'ADD_CFLAGS'", "]", "compiler", "=", "\"#{@settings['CC']} -x c \"", "when", "as_source_extensions", ".", "include?", "(", "extension", ")", "flags", "=", "''", "compiler", "=", "\"#{@settings['AS']}\"", "else", "raise", "\"unsupported source file extension (#{extension}) for creating object!\"", "end", "sh", "\"#{compiler} #{flags} #{incs} -c #{source} -o #{object}\"", "end" ]
Creates compilation object @param [Hash] params @option params [String] :source source filename with path @option params [String] :object object filename path @option params [Hash] :settings project specific settings @option params [Array] :includes include paths used
[ "Creates", "compilation", "object" ]
af7713fb238058509a34103829e37a62873c4ecb
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/toolchain.rb#L403-L423
5,775
fogonthedowns/rubychem
lib/rubychem/equation.rb
RubyChem.Equation.solve_equivalent_fractions
def solve_equivalent_fractions last = 0 array = Array.new @reduced_row_echelon_form.each do |x| array = last.gcdlcm(x.last.denominator) last = x.last.denominator end array.max end
ruby
def solve_equivalent_fractions last = 0 array = Array.new @reduced_row_echelon_form.each do |x| array = last.gcdlcm(x.last.denominator) last = x.last.denominator end array.max end
[ "def", "solve_equivalent_fractions", "last", "=", "0", "array", "=", "Array", ".", "new", "@reduced_row_echelon_form", ".", "each", "do", "|", "x", "|", "array", "=", "last", ".", "gcdlcm", "(", "x", ".", "last", ".", "denominator", ")", "last", "=", "x", ".", "last", ".", "denominator", "end", "array", ".", "max", "end" ]
from the reduced row echelon form we are left with a set of equivalent fractions to transform into a whole number we do this by using the gcdlcm method
[ "from", "the", "reduced", "row", "echelon", "form", "we", "are", "left", "with", "a", "set", "of", "equivalent", "fractions", "to", "transform", "into", "a", "whole", "number", "we", "do", "this", "by", "using", "the", "gcdlcm", "method" ]
7750e29465538b7c67f5a41a5cae6b7f74a7faac
https://github.com/fogonthedowns/rubychem/blob/7750e29465538b7c67f5a41a5cae6b7f74a7faac/lib/rubychem/equation.rb#L158-L166
5,776
fogonthedowns/rubychem
lib/rubychem/equation.rb
RubyChem.Equation.apply_solved_equivalent_fractions_to_fraction
def apply_solved_equivalent_fractions_to_fraction int = self.solve_equivalent_fractions answer = [] @reduced_row_echelon_form.each do |row| answer << row.last * int end answer << int count = 0 @balanced = Hash.new @left_system_of_equations.each do |x,v| answer[count] @left_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end @right_system_of_equations.each do |x,v| answer[count] @right_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end answer @balanced = {left:@left_system_of_equations,right:@right_system_of_equations} self.balanced_string.gsub(/([\D^])1([\D$])/, '\1\2') # or (/1(?!\d)/,"") end
ruby
def apply_solved_equivalent_fractions_to_fraction int = self.solve_equivalent_fractions answer = [] @reduced_row_echelon_form.each do |row| answer << row.last * int end answer << int count = 0 @balanced = Hash.new @left_system_of_equations.each do |x,v| answer[count] @left_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end @right_system_of_equations.each do |x,v| answer[count] @right_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil? count += 1 end answer @balanced = {left:@left_system_of_equations,right:@right_system_of_equations} self.balanced_string.gsub(/([\D^])1([\D$])/, '\1\2') # or (/1(?!\d)/,"") end
[ "def", "apply_solved_equivalent_fractions_to_fraction", "int", "=", "self", ".", "solve_equivalent_fractions", "answer", "=", "[", "]", "@reduced_row_echelon_form", ".", "each", "do", "|", "row", "|", "answer", "<<", "row", ".", "last", "*", "int", "end", "answer", "<<", "int", "count", "=", "0", "@balanced", "=", "Hash", ".", "new", "@left_system_of_equations", ".", "each", "do", "|", "x", ",", "v", "|", "answer", "[", "count", "]", "@left_system_of_equations", "[", "x", "]", "=", "answer", "[", "count", "]", ".", "to_i", ".", "abs", "unless", "answer", "[", "count", "]", ".", "nil?", "count", "+=", "1", "end", "@right_system_of_equations", ".", "each", "do", "|", "x", ",", "v", "|", "answer", "[", "count", "]", "@right_system_of_equations", "[", "x", "]", "=", "answer", "[", "count", "]", ".", "to_i", ".", "abs", "unless", "answer", "[", "count", "]", ".", "nil?", "count", "+=", "1", "end", "answer", "@balanced", "=", "{", "left", ":", "@left_system_of_equations", ",", "right", ":", "@right_system_of_equations", "}", "self", ".", "balanced_string", ".", "gsub", "(", "/", "\\D", "\\D", "/", ",", "'\\1\\2'", ")", "# or (/1(?!\\d)/,\"\")", "end" ]
Now that we have the whole number from solve_equivalent_fractions we must apply that to each of the fractions to solve for the balanced equation
[ "Now", "that", "we", "have", "the", "whole", "number", "from", "solve_equivalent_fractions", "we", "must", "apply", "that", "to", "each", "of", "the", "fractions", "to", "solve", "for", "the", "balanced", "equation" ]
7750e29465538b7c67f5a41a5cae6b7f74a7faac
https://github.com/fogonthedowns/rubychem/blob/7750e29465538b7c67f5a41a5cae6b7f74a7faac/lib/rubychem/equation.rb#L172-L194
5,777
fogonthedowns/rubychem
lib/rubychem/equation.rb
RubyChem.Equation.reduced_row_echelon_form
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to_rational(ary) # use rational arithmetic catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end # swap rows i and r rary[i], rary[r] = rary[r], rary[i] # normalize row r v = rary[r][lead] rary[r].collect! {|x| x /= v} # reduce other rows rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end
ruby
def reduced_row_echelon_form(ary) lead = 0 rows = ary.size cols = ary[0].size rary = convert_to_rational(ary) # use rational arithmetic catch :done do rows.times do |r| throw :done if cols <= lead i = r while rary[i][lead] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end # swap rows i and r rary[i], rary[r] = rary[r], rary[i] # normalize row r v = rary[r][lead] rary[r].collect! {|x| x /= v} # reduce other rows rows.times do |i| next if i == r v = rary[i][lead] rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]} end lead += 1 end end rary end
[ "def", "reduced_row_echelon_form", "(", "ary", ")", "lead", "=", "0", "rows", "=", "ary", ".", "size", "cols", "=", "ary", "[", "0", "]", ".", "size", "rary", "=", "convert_to_rational", "(", "ary", ")", "# use rational arithmetic", "catch", ":done", "do", "rows", ".", "times", "do", "|", "r", "|", "throw", ":done", "if", "cols", "<=", "lead", "i", "=", "r", "while", "rary", "[", "i", "]", "[", "lead", "]", "==", "0", "i", "+=", "1", "if", "rows", "==", "i", "i", "=", "r", "lead", "+=", "1", "throw", ":done", "if", "cols", "==", "lead", "end", "end", "# swap rows i and r ", "rary", "[", "i", "]", ",", "rary", "[", "r", "]", "=", "rary", "[", "r", "]", ",", "rary", "[", "i", "]", "# normalize row r", "v", "=", "rary", "[", "r", "]", "[", "lead", "]", "rary", "[", "r", "]", ".", "collect!", "{", "|", "x", "|", "x", "/=", "v", "}", "# reduce other rows", "rows", ".", "times", "do", "|", "i", "|", "next", "if", "i", "==", "r", "v", "=", "rary", "[", "i", "]", "[", "lead", "]", "rary", "[", "i", "]", ".", "each_index", "{", "|", "j", "|", "rary", "[", "i", "]", "[", "j", "]", "-=", "v", "*", "rary", "[", "r", "]", "[", "j", "]", "}", "end", "lead", "+=", "1", "end", "end", "rary", "end" ]
returns an 2-D array where each element is a Rational
[ "returns", "an", "2", "-", "D", "array", "where", "each", "element", "is", "a", "Rational" ]
7750e29465538b7c67f5a41a5cae6b7f74a7faac
https://github.com/fogonthedowns/rubychem/blob/7750e29465538b7c67f5a41a5cae6b7f74a7faac/lib/rubychem/equation.rb#L207-L239
5,778
wvanbergen/http_status_exceptions
lib/http_status_exceptions.rb
HTTPStatus.ControllerAddition.http_status_exception
def http_status_exception(exception) @exception = exception render_options = {:template => exception.template, :status => exception.status} render_options[:layout] = exception.template_layout if exception.template_layout render(render_options) rescue ActionView::MissingTemplate head(exception.status) end
ruby
def http_status_exception(exception) @exception = exception render_options = {:template => exception.template, :status => exception.status} render_options[:layout] = exception.template_layout if exception.template_layout render(render_options) rescue ActionView::MissingTemplate head(exception.status) end
[ "def", "http_status_exception", "(", "exception", ")", "@exception", "=", "exception", "render_options", "=", "{", ":template", "=>", "exception", ".", "template", ",", ":status", "=>", "exception", ".", "status", "}", "render_options", "[", ":layout", "]", "=", "exception", ".", "template_layout", "if", "exception", ".", "template_layout", "render", "(", "render_options", ")", "rescue", "ActionView", "::", "MissingTemplate", "head", "(", "exception", ".", "status", ")", "end" ]
The default handler for raised HTTP status exceptions. It will render a template if available, or respond with an empty response with the HTTP status corresponding to the exception. You can override this method in your <tt>ApplicationController</tt> to handle the exceptions yourself. <tt>exception</tt>:: The HTTP status exception to handle.
[ "The", "default", "handler", "for", "raised", "HTTP", "status", "exceptions", ".", "It", "will", "render", "a", "template", "if", "available", "or", "respond", "with", "an", "empty", "response", "with", "the", "HTTP", "status", "corresponding", "to", "the", "exception", "." ]
8b88105f4784d03cb16cb4d36efb161394d02a2d
https://github.com/wvanbergen/http_status_exceptions/blob/8b88105f4784d03cb16cb4d36efb161394d02a2d/lib/http_status_exceptions.rb#L138-L145
5,779
rocky/rbx-trepanning
app/eventbuffer.rb
Trace.EventBuffer.append
def append(event, frame, arg) item = EventStruct.new(event, arg, frame) @pos = self.succ_pos @marks.shift if @marks[0] == @pos @buf[@pos] = item @size += 1 unless @maxsize && @size == @maxsize end
ruby
def append(event, frame, arg) item = EventStruct.new(event, arg, frame) @pos = self.succ_pos @marks.shift if @marks[0] == @pos @buf[@pos] = item @size += 1 unless @maxsize && @size == @maxsize end
[ "def", "append", "(", "event", ",", "frame", ",", "arg", ")", "item", "=", "EventStruct", ".", "new", "(", "event", ",", "arg", ",", "frame", ")", "@pos", "=", "self", ".", "succ_pos", "@marks", ".", "shift", "if", "@marks", "[", "0", "]", "==", "@pos", "@buf", "[", "@pos", "]", "=", "item", "@size", "+=", "1", "unless", "@maxsize", "&&", "@size", "==", "@maxsize", "end" ]
Add a new event dropping off old events if that was declared marks are also dropped if buffer has a limit.
[ "Add", "a", "new", "event", "dropping", "off", "old", "events", "if", "that", "was", "declared", "marks", "are", "also", "dropped", "if", "buffer", "has", "a", "limit", "." ]
192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1
https://github.com/rocky/rbx-trepanning/blob/192e5d3b8236f0c1094f7ba3a6b5d2c42ed43fc1/app/eventbuffer.rb#L25-L31
5,780
ivanzotov/constructor
pages/app/models/constructor_pages/template.rb
ConstructorPages.Template.check_code_name
def check_code_name(cname) [cname.pluralize, cname.singularize].each {|name| return false if root.descendants.map{|t| t.code_name unless t.code_name == cname}.include?(name)} true end
ruby
def check_code_name(cname) [cname.pluralize, cname.singularize].each {|name| return false if root.descendants.map{|t| t.code_name unless t.code_name == cname}.include?(name)} true end
[ "def", "check_code_name", "(", "cname", ")", "[", "cname", ".", "pluralize", ",", "cname", ".", "singularize", "]", ".", "each", "{", "|", "name", "|", "return", "false", "if", "root", ".", "descendants", ".", "map", "{", "|", "t", "|", "t", ".", "code_name", "unless", "t", ".", "code_name", "==", "cname", "}", ".", "include?", "(", "name", ")", "}", "true", "end" ]
Check if there is code_name in same branch
[ "Check", "if", "there", "is", "code_name", "in", "same", "branch" ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/template.rb#L39-L43
5,781
aelogica/express_templates
lib/express_templates/renderer.rb
ExpressTemplates.Renderer.render
def render context=nil, template_or_src=nil, &block compiled_template = compile(template_or_src, &block) context.instance_eval compiled_template end
ruby
def render context=nil, template_or_src=nil, &block compiled_template = compile(template_or_src, &block) context.instance_eval compiled_template end
[ "def", "render", "context", "=", "nil", ",", "template_or_src", "=", "nil", ",", "&", "block", "compiled_template", "=", "compile", "(", "template_or_src", ",", "block", ")", "context", ".", "instance_eval", "compiled_template", "end" ]
render accepts source or block, evaluates the resulting string of ruby in the context provided
[ "render", "accepts", "source", "or", "block", "evaluates", "the", "resulting", "string", "of", "ruby", "in", "the", "context", "provided" ]
d5d447357e737c9220ca0025feb9e6f8f6249b5b
https://github.com/aelogica/express_templates/blob/d5d447357e737c9220ca0025feb9e6f8f6249b5b/lib/express_templates/renderer.rb#L4-L7
5,782
robertwahler/repo_manager
lib/repo_manager/settings.rb
RepoManager.Settings.configure
def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO', :short => false, :unmodified => 'HIDE', :match => 'ALL', :list => 'ALL' }, :commands => [ 'diff', 'grep', 'log', 'ls-files', 'show', 'status' ] } # set default config if not given on command line config = options[:config] if config.nil? config = [ File.join(@working_dir, "repo.conf"), File.join(@working_dir, ".repo.conf"), File.join(@working_dir, "repo_manager", "repo.conf"), File.join(@working_dir, ".repo_manager", "repo.conf"), File.join(@working_dir, "config", "repo.conf"), File.expand_path(File.join("~", ".repo.conf")), File.expand_path(File.join("~", "repo.conf")), File.expand_path(File.join("~", "repo_manager", "repo.conf")), File.expand_path(File.join("~", ".repo_manager", "repo.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # load options from the config file, overwriting hard-coded defaults logger.debug "reading configuration file: #{config}" config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if options[:config] end # store the original full config filename for later use configuration[:configuration_filename] = config configuration.recursively_symbolize_keys! # the command line options override options read from the config file configuration[:options].merge!(options) configuration end
ruby
def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO', :short => false, :unmodified => 'HIDE', :match => 'ALL', :list => 'ALL' }, :commands => [ 'diff', 'grep', 'log', 'ls-files', 'show', 'status' ] } # set default config if not given on command line config = options[:config] if config.nil? config = [ File.join(@working_dir, "repo.conf"), File.join(@working_dir, ".repo.conf"), File.join(@working_dir, "repo_manager", "repo.conf"), File.join(@working_dir, ".repo_manager", "repo.conf"), File.join(@working_dir, "config", "repo.conf"), File.expand_path(File.join("~", ".repo.conf")), File.expand_path(File.join("~", "repo.conf")), File.expand_path(File.join("~", "repo_manager", "repo.conf")), File.expand_path(File.join("~", ".repo_manager", "repo.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # load options from the config file, overwriting hard-coded defaults logger.debug "reading configuration file: #{config}" config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if options[:config] end # store the original full config filename for later use configuration[:configuration_filename] = config configuration.recursively_symbolize_keys! # the command line options override options read from the config file configuration[:options].merge!(options) configuration end
[ "def", "configure", "(", "options", ")", "# config file default options", "configuration", "=", "{", ":options", "=>", "{", ":verbose", "=>", "false", ",", ":color", "=>", "'AUTO'", ",", ":short", "=>", "false", ",", ":unmodified", "=>", "'HIDE'", ",", ":match", "=>", "'ALL'", ",", ":list", "=>", "'ALL'", "}", ",", ":commands", "=>", "[", "'diff'", ",", "'grep'", ",", "'log'", ",", "'ls-files'", ",", "'show'", ",", "'status'", "]", "}", "# set default config if not given on command line", "config", "=", "options", "[", ":config", "]", "if", "config", ".", "nil?", "config", "=", "[", "File", ".", "join", "(", "@working_dir", ",", "\"repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\".repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\"repo_manager\"", ",", "\"repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\".repo_manager\"", ",", "\"repo.conf\"", ")", ",", "File", ".", "join", "(", "@working_dir", ",", "\"config\"", ",", "\"repo.conf\"", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\".repo.conf\"", ")", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\"repo.conf\"", ")", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\"repo_manager\"", ",", "\"repo.conf\"", ")", ")", ",", "File", ".", "expand_path", "(", "File", ".", "join", "(", "\"~\"", ",", "\".repo_manager\"", ",", "\"repo.conf\"", ")", ")", "]", ".", "detect", "{", "|", "filename", "|", "File", ".", "exists?", "(", "filename", ")", "}", "end", "if", "config", "&&", "File", ".", "exists?", "(", "config", ")", "# load options from the config file, overwriting hard-coded defaults", "logger", ".", "debug", "\"reading configuration file: #{config}\"", "config_contents", "=", "YAML", ".", "load", "(", "ERB", ".", "new", "(", "File", ".", "open", "(", "config", ",", "\"rb\"", ")", ".", "read", ")", ".", "result", ")", "configuration", ".", "merge!", "(", "config_contents", ".", "symbolize_keys!", ")", "if", "config_contents", "&&", "config_contents", ".", "is_a?", "(", "Hash", ")", "else", "# user specified a config file?, no error if user did not specify config file", "raise", "\"config file not found\"", "if", "options", "[", ":config", "]", "end", "# store the original full config filename for later use", "configuration", "[", ":configuration_filename", "]", "=", "config", "configuration", ".", "recursively_symbolize_keys!", "# the command line options override options read from the config file", "configuration", "[", ":options", "]", ".", "merge!", "(", "options", ")", "configuration", "end" ]
read options from YAML config
[ "read", "options", "from", "YAML", "config" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/settings.rb#L38-L94
5,783
eprothro/cassie
lib/cassie/statements/execution/batched_fetching.rb
Cassie::Statements::Execution.BatchedFetching.fetch_in_batches
def fetch_in_batches(opts={}) opts[:batch_size] ||= 1000 # spawn the new query as soon as the enumerable is created # rather than waiting until the firt iteration is executed. # The client could mutate the object between these moments, # however we don't want to spawn twice if a block isn't passed. paged_query = opts.delete(:_paged_query) || self.clone return to_enum(:fetch_in_batches, opts.merge(_paged_query: paged_query)) unless block_given? # use Cassandra internal paging # but clone the query to isolate it # and allow all paging queries # to execute within a Cassie::Query # for use of other features, like logging # # note: stateless page size is independent from limit paged_query.stateless_page_size = opts[:batch_size] paged_query.paging_state = nil loop do # done if the previous result was the last page break if paged_query.result && paged_query.result.last_page? raise page_size_changed_error(opts[:batch_size]) if opts[:batch_size] != paged_query.stateless_page_size batch = paged_query.fetch paged_query.paging_state = paged_query.result.paging_state yield batch end end
ruby
def fetch_in_batches(opts={}) opts[:batch_size] ||= 1000 # spawn the new query as soon as the enumerable is created # rather than waiting until the firt iteration is executed. # The client could mutate the object between these moments, # however we don't want to spawn twice if a block isn't passed. paged_query = opts.delete(:_paged_query) || self.clone return to_enum(:fetch_in_batches, opts.merge(_paged_query: paged_query)) unless block_given? # use Cassandra internal paging # but clone the query to isolate it # and allow all paging queries # to execute within a Cassie::Query # for use of other features, like logging # # note: stateless page size is independent from limit paged_query.stateless_page_size = opts[:batch_size] paged_query.paging_state = nil loop do # done if the previous result was the last page break if paged_query.result && paged_query.result.last_page? raise page_size_changed_error(opts[:batch_size]) if opts[:batch_size] != paged_query.stateless_page_size batch = paged_query.fetch paged_query.paging_state = paged_query.result.paging_state yield batch end end
[ "def", "fetch_in_batches", "(", "opts", "=", "{", "}", ")", "opts", "[", ":batch_size", "]", "||=", "1000", "# spawn the new query as soon as the enumerable is created", "# rather than waiting until the firt iteration is executed.", "# The client could mutate the object between these moments,", "# however we don't want to spawn twice if a block isn't passed.", "paged_query", "=", "opts", ".", "delete", "(", ":_paged_query", ")", "||", "self", ".", "clone", "return", "to_enum", "(", ":fetch_in_batches", ",", "opts", ".", "merge", "(", "_paged_query", ":", "paged_query", ")", ")", "unless", "block_given?", "# use Cassandra internal paging", "# but clone the query to isolate it", "# and allow all paging queries", "# to execute within a Cassie::Query", "# for use of other features, like logging", "#", "# note: stateless page size is independent from limit", "paged_query", ".", "stateless_page_size", "=", "opts", "[", ":batch_size", "]", "paged_query", ".", "paging_state", "=", "nil", "loop", "do", "# done if the previous result was the last page", "break", "if", "paged_query", ".", "result", "&&", "paged_query", ".", "result", ".", "last_page?", "raise", "page_size_changed_error", "(", "opts", "[", ":batch_size", "]", ")", "if", "opts", "[", ":batch_size", "]", "!=", "paged_query", ".", "stateless_page_size", "batch", "=", "paged_query", ".", "fetch", "paged_query", ".", "paging_state", "=", "paged_query", ".", "result", ".", "paging_state", "yield", "batch", "end", "end" ]
Yields each batch of records that was found by the options as an array. If you do not provide a block to find_in_batches, it will return an Enumerator for chaining with other methods. query.fetch_in_batches do |records| puts "max score in group: #{records.max{ |a, b| a.score <=> b.score }}" end "max score in group: 26" ==== Options * <tt>:batch_size</tt> - Specifies the size of the batch. Default to 1000. NOTE: Any limit specified on the query will affect the batched set. Cassandra internal paging is used for batching.
[ "Yields", "each", "batch", "of", "records", "that", "was", "found", "by", "the", "options", "as", "an", "array", "." ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution/batched_fetching.rb#L50-L81
5,784
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_movie.rb
GuideboxWrapper.GuideboxMovie.search_for
def search_for(name) url = build_query(name) url += '/fuzzy/web' data = @client.query(url) sleep(1) data["results"] end
ruby
def search_for(name) url = build_query(name) url += '/fuzzy/web' data = @client.query(url) sleep(1) data["results"] end
[ "def", "search_for", "(", "name", ")", "url", "=", "build_query", "(", "name", ")", "url", "+=", "'/fuzzy/web'", "data", "=", "@client", ".", "query", "(", "url", ")", "sleep", "(", "1", ")", "data", "[", "\"results\"", "]", "end" ]
Search for show
[ "Search", "for", "show" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_movie.rb#L8-L14
5,785
pwnieexpress/snapi
lib/snapi/argument.rb
Snapi.Argument.valid_input?
def valid_input?(input) case @attributes[:type] when :boolean [true,false].include?(input) when :enum raise MissingValuesError unless @attributes[:values] raise InvalidValuesError unless @attributes[:values].class == Array @attributes[:values].include?(input) when :string format = @attributes[:format] || :anything Validator.valid_input?(format, input) when :number [Integer, Fixnum].include?(input.class) when :timestamp # TODO timestamp pending # raise PendingBranchError true else false end end
ruby
def valid_input?(input) case @attributes[:type] when :boolean [true,false].include?(input) when :enum raise MissingValuesError unless @attributes[:values] raise InvalidValuesError unless @attributes[:values].class == Array @attributes[:values].include?(input) when :string format = @attributes[:format] || :anything Validator.valid_input?(format, input) when :number [Integer, Fixnum].include?(input.class) when :timestamp # TODO timestamp pending # raise PendingBranchError true else false end end
[ "def", "valid_input?", "(", "input", ")", "case", "@attributes", "[", ":type", "]", "when", ":boolean", "[", "true", ",", "false", "]", ".", "include?", "(", "input", ")", "when", ":enum", "raise", "MissingValuesError", "unless", "@attributes", "[", ":values", "]", "raise", "InvalidValuesError", "unless", "@attributes", "[", ":values", "]", ".", "class", "==", "Array", "@attributes", "[", ":values", "]", ".", "include?", "(", "input", ")", "when", ":string", "format", "=", "@attributes", "[", ":format", "]", "||", ":anything", "Validator", ".", "valid_input?", "(", "format", ",", "input", ")", "when", ":number", "[", "Integer", ",", "Fixnum", "]", ".", "include?", "(", "input", ".", "class", ")", "when", ":timestamp", "# TODO timestamp pending", "# raise PendingBranchError", "true", "else", "false", "end", "end" ]
Check if a value provided will suffice for the way this argument is defined. @param input, Just about anything... @returns Boolean. true if valid
[ "Check", "if", "a", "value", "provided", "will", "suffice", "for", "the", "way", "this", "argument", "is", "defined", "." ]
3c2a6fe454721945e4e58b8b496d3c20ada55df7
https://github.com/pwnieexpress/snapi/blob/3c2a6fe454721945e4e58b8b496d3c20ada55df7/lib/snapi/argument.rb#L139-L159
5,786
eprothro/cassie
lib/cassie/statements/execution/fetching.rb
Cassie::Statements::Execution.Fetching.fetch
def fetch(args={}) args.each do |k, v| setter = "#{k}=" send(setter, v) if respond_to? setter end execute result end
ruby
def fetch(args={}) args.each do |k, v| setter = "#{k}=" send(setter, v) if respond_to? setter end execute result end
[ "def", "fetch", "(", "args", "=", "{", "}", ")", "args", ".", "each", "do", "|", "k", ",", "v", "|", "setter", "=", "\"#{k}=\"", "send", "(", "setter", ",", "v", ")", "if", "respond_to?", "setter", "end", "execute", "result", "end" ]
Returns array of rows or empty array query.fetch(id: 1) => [{id: 1, name: 'eprothro'}]
[ "Returns", "array", "of", "rows", "or", "empty", "array" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/statements/execution/fetching.rb#L19-L27
5,787
fcheung/corefoundation
lib/corefoundation/base.rb
CF.Base.inspect
def inspect cf = CF::String.new(CF.CFCopyDescription(self)) cf.to_s.tap {cf.release} end
ruby
def inspect cf = CF::String.new(CF.CFCopyDescription(self)) cf.to_s.tap {cf.release} end
[ "def", "inspect", "cf", "=", "CF", "::", "String", ".", "new", "(", "CF", ".", "CFCopyDescription", "(", "self", ")", ")", "cf", ".", "to_s", ".", "tap", "{", "cf", ".", "release", "}", "end" ]
Returns a ruby string containing the output of CFCopyDescription for the wrapped object @return [String]
[ "Returns", "a", "ruby", "string", "containing", "the", "output", "of", "CFCopyDescription", "for", "the", "wrapped", "object" ]
a5c766359e74f873902d916e9fb051ec7fdedbb9
https://github.com/fcheung/corefoundation/blob/a5c766359e74f873902d916e9fb051ec7fdedbb9/lib/corefoundation/base.rb#L146-L149
5,788
fcheung/corefoundation
lib/corefoundation/base.rb
CF.Base.equals?
def equals?(other) if other.is_a?(CF::Base) @ptr.address == other.to_ptr.address else false end end
ruby
def equals?(other) if other.is_a?(CF::Base) @ptr.address == other.to_ptr.address else false end end
[ "def", "equals?", "(", "other", ")", "if", "other", ".", "is_a?", "(", "CF", "::", "Base", ")", "@ptr", ".", "address", "==", "other", ".", "to_ptr", ".", "address", "else", "false", "end", "end" ]
Uses CFHash to return a hash code @return [Integer] eql? (and ==) are implemented using CFEqual equals? is defined as returning true if the wrapped pointer is the same
[ "Uses", "CFHash", "to", "return", "a", "hash", "code" ]
a5c766359e74f873902d916e9fb051ec7fdedbb9
https://github.com/fcheung/corefoundation/blob/a5c766359e74f873902d916e9fb051ec7fdedbb9/lib/corefoundation/base.rb#L172-L178
5,789
bachya/cliutils
lib/cliutils/pretty_io.rb
CLIUtils.PrettyIO.color_chart
def color_chart [0, 1, 4, 5, 7].each do |attr| puts '----------------------------------------------------------------' puts "ESC[#{attr};Foreground;Background" 30.upto(37) do |fg| 40.upto(47) do |bg| print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg} " end puts "\033[0m" end end end
ruby
def color_chart [0, 1, 4, 5, 7].each do |attr| puts '----------------------------------------------------------------' puts "ESC[#{attr};Foreground;Background" 30.upto(37) do |fg| 40.upto(47) do |bg| print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg} " end puts "\033[0m" end end end
[ "def", "color_chart", "[", "0", ",", "1", ",", "4", ",", "5", ",", "7", "]", ".", "each", "do", "|", "attr", "|", "puts", "'----------------------------------------------------------------'", "puts", "\"ESC[#{attr};Foreground;Background\"", "30", ".", "upto", "(", "37", ")", "do", "|", "fg", "|", "40", ".", "upto", "(", "47", ")", "do", "|", "bg", "|", "print", "\"\\033[#{attr};#{fg};#{bg}m #{fg};#{bg} \"", "end", "puts", "\"\\033[0m\"", "end", "end", "end" ]
Displays a chart of all the possible ANSI foreground and background color combinations. @return [void]
[ "Displays", "a", "chart", "of", "all", "the", "possible", "ANSI", "foreground", "and", "background", "color", "combinations", "." ]
af5280bcadf7196922ab1bb7285787149cadbb9d
https://github.com/bachya/cliutils/blob/af5280bcadf7196922ab1bb7285787149cadbb9d/lib/cliutils/pretty_io.rb#L28-L39
5,790
lml/lev
lib/lev/handler.rb
Lev.Handler.validate_paramified_params
def validate_paramified_params self.class.paramify_methods.each do |method| params = send(method) transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid? end end
ruby
def validate_paramified_params self.class.paramify_methods.each do |method| params = send(method) transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid? end end
[ "def", "validate_paramified_params", "self", ".", "class", ".", "paramify_methods", ".", "each", "do", "|", "method", "|", "params", "=", "send", "(", "method", ")", "transfer_errors_from", "(", "params", ",", "TermMapper", ".", "scope", "(", "params", ".", "group", ")", ")", "if", "!", "params", ".", "valid?", "end", "end" ]
Helper method to validate paramified params and to transfer any errors into the handler.
[ "Helper", "method", "to", "validate", "paramified", "params", "and", "to", "transfer", "any", "errors", "into", "the", "handler", "." ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/handler.rb#L222-L227
5,791
GenieBelt/gb-dispatch
lib/gb_dispatch/queue.rb
GBDispatch.Queue.perform_after
def perform_after(time, block=nil) task = Concurrent::ScheduledTask.new(time) do block = ->(){ yield } unless block self.async.perform_now block end task.execute task end
ruby
def perform_after(time, block=nil) task = Concurrent::ScheduledTask.new(time) do block = ->(){ yield } unless block self.async.perform_now block end task.execute task end
[ "def", "perform_after", "(", "time", ",", "block", "=", "nil", ")", "task", "=", "Concurrent", "::", "ScheduledTask", ".", "new", "(", "time", ")", "do", "block", "=", "->", "(", ")", "{", "yield", "}", "unless", "block", "self", ".", "async", ".", "perform_now", "block", "end", "task", ".", "execute", "task", "end" ]
Perform block after given period @param time [Fixnum] @param block [Proc] @yield if there is no block given it yield without param. @return [Concurrent::ScheduledTask]
[ "Perform", "block", "after", "given", "period" ]
6ee932de9b397b96c82271478db1bf5933449e94
https://github.com/GenieBelt/gb-dispatch/blob/6ee932de9b397b96c82271478db1bf5933449e94/lib/gb_dispatch/queue.rb#L57-L64
5,792
ktemkin/ruby-ise
lib/ise/preference_file.rb
ISE.PreferenceFile.set_by_path
def set_by_path(path, value, target=@ini) #Split the path into its components. keys = path.split('/') #Traverse the path, creating any "folders" necessary along the way. until keys.one? target[keys.first] = {} unless target[keys.first].is_a?(Hash) target = target[keys.shift] end #And finally, place the value into the appropriate "leaf". target[keys.shift] = value end
ruby
def set_by_path(path, value, target=@ini) #Split the path into its components. keys = path.split('/') #Traverse the path, creating any "folders" necessary along the way. until keys.one? target[keys.first] = {} unless target[keys.first].is_a?(Hash) target = target[keys.shift] end #And finally, place the value into the appropriate "leaf". target[keys.shift] = value end
[ "def", "set_by_path", "(", "path", ",", "value", ",", "target", "=", "@ini", ")", "#Split the path into its components.", "keys", "=", "path", ".", "split", "(", "'/'", ")", "#Traverse the path, creating any \"folders\" necessary along the way.", "until", "keys", ".", "one?", "target", "[", "keys", ".", "first", "]", "=", "{", "}", "unless", "target", "[", "keys", ".", "first", "]", ".", "is_a?", "(", "Hash", ")", "target", "=", "target", "[", "keys", ".", "shift", "]", "end", "#And finally, place the value into the appropriate \"leaf\".", "target", "[", "keys", ".", "shift", "]", "=", "value", "end" ]
Sets the value of a key in a hash-of-hashes via a unix-style path. path: The path to the target key, in a unix-style path structure. See example below. value: The value to put into the key. target: The hash to operate on. If target isn't provided, we work with the base INI. Example: set_by_path('foo/bar/tab', 3, a) would set a[foo][bar][tab] = 3; setting foo and bar to
[ "Sets", "the", "value", "of", "a", "key", "in", "a", "hash", "-", "of", "-", "hashes", "via", "a", "unix", "-", "style", "path", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/preference_file.rb#L46-L60
5,793
ktemkin/ruby-ise
lib/ise/preference_file.rb
ISE.PreferenceFile.get_by_path
def get_by_path(path, target=@ini) #Split the path into its components... keys = path.split('/') #And traverse the hasn until we've fully navigated the path. target = target[keys.shift] until keys.empty? #Returns the final value. target end
ruby
def get_by_path(path, target=@ini) #Split the path into its components... keys = path.split('/') #And traverse the hasn until we've fully navigated the path. target = target[keys.shift] until keys.empty? #Returns the final value. target end
[ "def", "get_by_path", "(", "path", ",", "target", "=", "@ini", ")", "#Split the path into its components...", "keys", "=", "path", ".", "split", "(", "'/'", ")", "#And traverse the hasn until we've fully navigated the path.", "target", "=", "target", "[", "keys", ".", "shift", "]", "until", "keys", ".", "empty?", "#Returns the final value.", "target", "end" ]
Gets the value of a key in a hash-of-hashes via a unix-style path. path: The path to the target key, in a unix-style path structure. See example below. target: The hash to operate on. If target isn't provided, we work with the base INI. Example: set_by_path('foo/bar/tab', 3, a) would set a[foo][bar][tab] = 3; setting foo and bar to
[ "Gets", "the", "value", "of", "a", "key", "in", "a", "hash", "-", "of", "-", "hashes", "via", "a", "unix", "-", "style", "path", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/preference_file.rb#L74-L85
5,794
ktemkin/ruby-ise
lib/ise/preference_file.rb
ISE.PreferenceFile.process_property
def process_property(property, value) value.chomp! #If either the property or value are empty (or contain invalid whitespace), #abort. return if property.empty? and value.empty? return if value.sub!(%r/\\\s*\z/, '') #Strip any leading/trailing characters. property.strip! value.strip! #Raise an error if we have an invalid property name. parse_error if property.empty? #Parse ISE's value into a path. set_by_path(CGI::unescape(property), unescape_value(value.dup), current_section) #And continue processing the property and value. property.slice!(0, property.length) value.slice!(0, value.length) #Return nil. nil end
ruby
def process_property(property, value) value.chomp! #If either the property or value are empty (or contain invalid whitespace), #abort. return if property.empty? and value.empty? return if value.sub!(%r/\\\s*\z/, '') #Strip any leading/trailing characters. property.strip! value.strip! #Raise an error if we have an invalid property name. parse_error if property.empty? #Parse ISE's value into a path. set_by_path(CGI::unescape(property), unescape_value(value.dup), current_section) #And continue processing the property and value. property.slice!(0, property.length) value.slice!(0, value.length) #Return nil. nil end
[ "def", "process_property", "(", "property", ",", "value", ")", "value", ".", "chomp!", "#If either the property or value are empty (or contain invalid whitespace),", "#abort.", "return", "if", "property", ".", "empty?", "and", "value", ".", "empty?", "return", "if", "value", ".", "sub!", "(", "%r/", "\\\\", "\\s", "\\z", "/", ",", "''", ")", "#Strip any leading/trailing characters.", "property", ".", "strip!", "value", ".", "strip!", "#Raise an error if we have an invalid property name.", "parse_error", "if", "property", ".", "empty?", "#Parse ISE's value into a path.", "set_by_path", "(", "CGI", "::", "unescape", "(", "property", ")", ",", "unescape_value", "(", "value", ".", "dup", ")", ",", "current_section", ")", "#And continue processing the property and value.", "property", ".", "slice!", "(", "0", ",", "property", ".", "length", ")", "value", ".", "slice!", "(", "0", ",", "value", ".", "length", ")", "#Return nil.", "nil", "end" ]
Processes a given name-value pair, adding them to the current INI database. Code taken from the 'inifile' gem.
[ "Processes", "a", "given", "name", "-", "value", "pair", "adding", "them", "to", "the", "current", "INI", "database", "." ]
db34c9bac5f9986ee4d2750e314dac4b6f139a24
https://github.com/ktemkin/ruby-ise/blob/db34c9bac5f9986ee4d2750e314dac4b6f139a24/lib/ise/preference_file.rb#L93-L119
5,795
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.init?
def init?(path = Dir.pwd) begin MiniGit.new(path) rescue Exception return false end true end
ruby
def init?(path = Dir.pwd) begin MiniGit.new(path) rescue Exception return false end true end
[ "def", "init?", "(", "path", "=", "Dir", ".", "pwd", ")", "begin", "MiniGit", ".", "new", "(", "path", ")", "rescue", "Exception", "return", "false", "end", "true", "end" ]
Check if a git directory has been initialized
[ "Check", "if", "a", "git", "directory", "has", "been", "initialized" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L40-L47
5,796
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.commits?
def commits?(path) res = false Dir.chdir(path) do _stdout, _stderr, exit_status = Open3.capture3( "git rev-parse HEAD" ) res = (exit_status.to_i.zero?) end res end
ruby
def commits?(path) res = false Dir.chdir(path) do _stdout, _stderr, exit_status = Open3.capture3( "git rev-parse HEAD" ) res = (exit_status.to_i.zero?) end res end
[ "def", "commits?", "(", "path", ")", "res", "=", "false", "Dir", ".", "chdir", "(", "path", ")", "do", "_stdout", ",", "_stderr", ",", "exit_status", "=", "Open3", ".", "capture3", "(", "\"git rev-parse HEAD\"", ")", "res", "=", "(", "exit_status", ".", "to_i", ".", "zero?", ")", "end", "res", "end" ]
Check if the repositories already holds some commits
[ "Check", "if", "the", "repositories", "already", "holds", "some", "commits" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L50-L57
5,797
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.command?
def command?(cmd) cg = MiniGit::Capturing.new cmd_list = cg.help :a => true # typical run: # usage: git [--version] [--help] [-C <path>] [-c name=value] # [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] # [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] # [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] # <command> [<args>] # # available git commands in '/usr/local/Cellar/git/1.8.5.2/libexec/git-core' # # add [...] \ # [...] | The part we are interested in, delimited by '\n\n' sequence # [...] / # # 'git help -a' and 'git help -g' lists available subcommands and some # concept guides. See 'git help <command>' or 'git help <concept>' # to read about a specific subcommand or concept l = cmd_list.split("\n\n") l.shift # useless first part #ap l subl = l.each_index.select { |i| l[i] =~ /^\s\s+/ } # find sublines that starts with at least two whitespaces #ap subl return false if subl.empty? subl.any? { |i| l[i].split.include?(cmd) } end
ruby
def command?(cmd) cg = MiniGit::Capturing.new cmd_list = cg.help :a => true # typical run: # usage: git [--version] [--help] [-C <path>] [-c name=value] # [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] # [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] # [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] # <command> [<args>] # # available git commands in '/usr/local/Cellar/git/1.8.5.2/libexec/git-core' # # add [...] \ # [...] | The part we are interested in, delimited by '\n\n' sequence # [...] / # # 'git help -a' and 'git help -g' lists available subcommands and some # concept guides. See 'git help <command>' or 'git help <concept>' # to read about a specific subcommand or concept l = cmd_list.split("\n\n") l.shift # useless first part #ap l subl = l.each_index.select { |i| l[i] =~ /^\s\s+/ } # find sublines that starts with at least two whitespaces #ap subl return false if subl.empty? subl.any? { |i| l[i].split.include?(cmd) } end
[ "def", "command?", "(", "cmd", ")", "cg", "=", "MiniGit", "::", "Capturing", ".", "new", "cmd_list", "=", "cg", ".", "help", ":a", "=>", "true", "# typical run:", "# usage: git [--version] [--help] [-C <path>] [-c name=value]", "# [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]", "# [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]", "# [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]", "# <command> [<args>]", "#", "# available git commands in '/usr/local/Cellar/git/1.8.5.2/libexec/git-core'", "#", "# add [...] \\", "# [...] | The part we are interested in, delimited by '\\n\\n' sequence", "# [...] /", "#", "# 'git help -a' and 'git help -g' lists available subcommands and some", "# concept guides. See 'git help <command>' or 'git help <concept>'", "# to read about a specific subcommand or concept", "l", "=", "cmd_list", ".", "split", "(", "\"\\n\\n\"", ")", "l", ".", "shift", "# useless first part", "#ap l", "subl", "=", "l", ".", "each_index", ".", "select", "{", "|", "i", "|", "l", "[", "i", "]", "=~", "/", "\\s", "\\s", "/", "}", "# find sublines that starts with at least two whitespaces", "#ap subl", "return", "false", "if", "subl", ".", "empty?", "subl", ".", "any?", "{", "|", "i", "|", "l", "[", "i", "]", ".", "split", ".", "include?", "(", "cmd", ")", "}", "end" ]
Check the availability of a given git command
[ "Check", "the", "availability", "of", "a", "given", "git", "command" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L60-L86
5,798
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.init
def init(path = Dir.pwd, _options = {}) # FIXME: for travis test: ensure the global git configurations # 'user.email' and 'user.name' are set [ 'user.name', 'user.email' ].each do |userconf| next unless MiniGit[userconf].nil? warn "The Git global configuration '#{userconf}' is not set so" warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'" default_val = ENV['USER'] default_val += '@domain.org' if userconf =~ /email/ warn "Now putting a default value '#{default_val}' you could change later on" run %( git config --global #{userconf} "#{default_val}" ) #MiniGit[userconf] = default_val end exit_status = 1 Dir.mkdir( path ) unless Dir.exist?( path ) Dir.chdir( path ) do execute "git init" unless FalkorLib.config.debug exit_status = $?.to_i end # #puts "#init #{path}" # Dir.chdir( "#{path}" ) do # %x[ pwd && git init ] unless FalkorLib.config.debug # end exit_status end
ruby
def init(path = Dir.pwd, _options = {}) # FIXME: for travis test: ensure the global git configurations # 'user.email' and 'user.name' are set [ 'user.name', 'user.email' ].each do |userconf| next unless MiniGit[userconf].nil? warn "The Git global configuration '#{userconf}' is not set so" warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'" default_val = ENV['USER'] default_val += '@domain.org' if userconf =~ /email/ warn "Now putting a default value '#{default_val}' you could change later on" run %( git config --global #{userconf} "#{default_val}" ) #MiniGit[userconf] = default_val end exit_status = 1 Dir.mkdir( path ) unless Dir.exist?( path ) Dir.chdir( path ) do execute "git init" unless FalkorLib.config.debug exit_status = $?.to_i end # #puts "#init #{path}" # Dir.chdir( "#{path}" ) do # %x[ pwd && git init ] unless FalkorLib.config.debug # end exit_status end
[ "def", "init", "(", "path", "=", "Dir", ".", "pwd", ",", "_options", "=", "{", "}", ")", "# FIXME: for travis test: ensure the global git configurations", "# 'user.email' and 'user.name' are set", "[", "'user.name'", ",", "'user.email'", "]", ".", "each", "do", "|", "userconf", "|", "next", "unless", "MiniGit", "[", "userconf", "]", ".", "nil?", "warn", "\"The Git global configuration '#{userconf}' is not set so\"", "warn", "\"you should *seriously* consider setting them by running\\n\\t git config --global #{userconf} 'your_#{userconf.sub(/\\./, '_')}'\"", "default_val", "=", "ENV", "[", "'USER'", "]", "default_val", "+=", "'@domain.org'", "if", "userconf", "=~", "/", "/", "warn", "\"Now putting a default value '#{default_val}' you could change later on\"", "run", "%(\n git config --global #{userconf} \"#{default_val}\"\n )", "#MiniGit[userconf] = default_val", "end", "exit_status", "=", "1", "Dir", ".", "mkdir", "(", "path", ")", "unless", "Dir", ".", "exist?", "(", "path", ")", "Dir", ".", "chdir", "(", "path", ")", "do", "execute", "\"git init\"", "unless", "FalkorLib", ".", "config", ".", "debug", "exit_status", "=", "$?", ".", "to_i", "end", "# #puts \"#init #{path}\"", "# Dir.chdir( \"#{path}\" ) do", "# %x[ pwd && git init ] unless FalkorLib.config.debug", "# end", "exit_status", "end" ]
Initialize a git repository
[ "Initialize", "a", "git", "repository" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L91-L117
5,799
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.create_branch
def create_branch(branch, path = Dir.pwd) #ap method(__method__).parameters.map { |arg| arg[1] } g = MiniGit.new(path) error "not yet any commit performed -- You shall do one" unless commits?(path) g.branch branch.to_s end
ruby
def create_branch(branch, path = Dir.pwd) #ap method(__method__).parameters.map { |arg| arg[1] } g = MiniGit.new(path) error "not yet any commit performed -- You shall do one" unless commits?(path) g.branch branch.to_s end
[ "def", "create_branch", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ")", "#ap method(__method__).parameters.map { |arg| arg[1] }", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "error", "\"not yet any commit performed -- You shall do one\"", "unless", "commits?", "(", "path", ")", "g", ".", "branch", "branch", ".", "to_s", "end" ]
Create a new branch
[ "Create", "a", "new", "branch" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L132-L137