repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.get_email_template
def get_email_template url = ApiRequest.base_path("questionpro.survey.getEmailTemplate") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_template = EmailTemplate.new(result['response']['emailTemplate']) return email_template end
ruby
def get_email_template url = ApiRequest.base_path("questionpro.survey.getEmailTemplate") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_template = EmailTemplate.new(result['response']['emailTemplate']) return email_template end
[ "def", "get_email_template", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.getEmailTemplate\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "email_template", "=", "EmailTemplate", ".", "new", "(", "result", "[", "'response'", "]", "[", "'emailTemplate'", "]", ")", "return", "email_template", "end" ]
Get Specific Template. Template ID must be set inside the api request object. @return [QuestionproRails::Template] Template.
[ "Get", "Specific", "Template", ".", "Template", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L257-L267
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.get_all_accounts
def get_all_accounts url = ApiRequest.base_path("questionpro.survey.getAllAccounts") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] accounts = [] result_accounts = result['response']['accounts'] result_accounts.each do |account| accounts.push(Account.new(account)) end return accounts end
ruby
def get_all_accounts url = ApiRequest.base_path("questionpro.survey.getAllAccounts") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] accounts = [] result_accounts = result['response']['accounts'] result_accounts.each do |account| accounts.push(Account.new(account)) end return accounts end
[ "def", "get_all_accounts", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.getAllAccounts\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "accounts", "=", "[", "]", "result_accounts", "=", "result", "[", "'response'", "]", "[", "'accounts'", "]", "result_accounts", ".", "each", "do", "|", "account", "|", "accounts", ".", "push", "(", "Account", ".", "new", "(", "account", ")", ")", "end", "return", "accounts", "end" ]
Get all the accounts that belongs to the api key's owner. @return [Array<QuestionproRails::Account>] Accounts.
[ "Get", "all", "the", "accounts", "that", "belongs", "to", "the", "api", "key", "s", "owner", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L287-L301
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.get_account
def get_account url = ApiRequest.base_path("questionpro.survey.getAccount") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] account = Account.new(result['response']['account']) return account end
ruby
def get_account url = ApiRequest.base_path("questionpro.survey.getAccount") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] account = Account.new(result['response']['account']) return account end
[ "def", "get_account", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.getAccount\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "account", "=", "Account", ".", "new", "(", "result", "[", "'response'", "]", "[", "'account'", "]", ")", "return", "account", "end" ]
Get Specific Account. User ID must be set inside the api request object. @return [QuestionproRails::Account] Account.
[ "Get", "Specific", "Account", ".", "User", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L307-L317
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.get_unsubscribers
def get_unsubscribers url = ApiRequest.base_path("questionpro.survey.getUnsubscribedEmailAddresses") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] unsubscribers = [] result_unsubscribers = result['response']['response'] result_unsubscribers.each do |unsubscriber| unsubscribers.push(UnsubscribedEmail.new(unsubscriber)) end return unsubscribers end
ruby
def get_unsubscribers url = ApiRequest.base_path("questionpro.survey.getUnsubscribedEmailAddresses") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] unsubscribers = [] result_unsubscribers = result['response']['response'] result_unsubscribers.each do |unsubscriber| unsubscribers.push(UnsubscribedEmail.new(unsubscriber)) end return unsubscribers end
[ "def", "get_unsubscribers", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.getUnsubscribedEmailAddresses\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "unsubscribers", "=", "[", "]", "result_unsubscribers", "=", "result", "[", "'response'", "]", "[", "'response'", "]", "result_unsubscribers", ".", "each", "do", "|", "unsubscriber", "|", "unsubscribers", ".", "push", "(", "UnsubscribedEmail", ".", "new", "(", "unsubscriber", ")", ")", "end", "return", "unsubscribers", "end" ]
Get Unsubscribed Emails related to the api key. @return [Array<QuestionproRails::UnsubscribedEmail>] Unsubscribed Emails.
[ "Get", "Unsubscribed", "Emails", "related", "to", "the", "api", "key", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L322-L336
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.get_survey_meta
def get_survey_meta url = ApiRequest.base_path("questionpro.survey.sendSurveyMetaData") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] survey_meta = SurveyMeta.new(result['response']) return survey_meta end
ruby
def get_survey_meta url = ApiRequest.base_path("questionpro.survey.sendSurveyMetaData") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] survey_meta = SurveyMeta.new(result['response']) return survey_meta end
[ "def", "get_survey_meta", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.sendSurveyMetaData\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "survey_meta", "=", "SurveyMeta", ".", "new", "(", "result", "[", "'response'", "]", ")", "return", "survey_meta", "end" ]
Survey ID must be set inside the api request object. @return [QuestionproRails::SurveyMeta] Survey meta.
[ "Survey", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L341-L351
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.send_survey
def send_survey(mode = 1, emails = nil, template_id = nil) url = ApiRequest.base_path("questionpro.survey.sendSurvey") result = self.class.get(url, body: {surveyID: self.survey_id, mode: mode, emailGroupID: self.email_group_id, emails: emails, templateID: self.template_id, template: template_id}.compact.to_json) self.full_response = result self.status = result['status'] self.message = result['response']['result'] end
ruby
def send_survey(mode = 1, emails = nil, template_id = nil) url = ApiRequest.base_path("questionpro.survey.sendSurvey") result = self.class.get(url, body: {surveyID: self.survey_id, mode: mode, emailGroupID: self.email_group_id, emails: emails, templateID: self.template_id, template: template_id}.compact.to_json) self.full_response = result self.status = result['status'] self.message = result['response']['result'] end
[ "def", "send_survey", "(", "mode", "=", "1", ",", "emails", "=", "nil", ",", "template_id", "=", "nil", ")", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.sendSurvey\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "{", "surveyID", ":", "self", ".", "survey_id", ",", "mode", ":", "mode", ",", "emailGroupID", ":", "self", ".", "email_group_id", ",", "emails", ":", "emails", ",", "templateID", ":", "self", ".", "template_id", ",", "template", ":", "template_id", "}", ".", "compact", ".", "to_json", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "self", ".", "message", "=", "result", "[", "'response'", "]", "[", "'result'", "]", "end" ]
Send Specific Survey. Survey ID must be set inside the api request object. @param [Integer] mode (1). @param [Array<String>] emails to send to (nil). @param [Integer] template_id of email (nil). @return sets ApiRequest message attribute to "Message successful.".
[ "Send", "Specific", "Survey", ".", "Survey", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L360-L369
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.get_send_history
def get_send_history url = ApiRequest.base_path("questionpro.survey.emailBatchStatistics") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_batches = [] result_email_batches = result['response']['emailBatches'] result_email_batches.each do |email_batch| email_batches.push(EmailBatch.new(email_batch)) end return email_batches end
ruby
def get_send_history url = ApiRequest.base_path("questionpro.survey.emailBatchStatistics") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_batches = [] result_email_batches = result['response']['emailBatches'] result_email_batches.each do |email_batch| email_batches.push(EmailBatch.new(email_batch)) end return email_batches end
[ "def", "get_send_history", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.emailBatchStatistics\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "email_batches", "=", "[", "]", "result_email_batches", "=", "result", "[", "'response'", "]", "[", "'emailBatches'", "]", "result_email_batches", ".", "each", "do", "|", "email_batch", "|", "email_batches", ".", "push", "(", "EmailBatch", ".", "new", "(", "email_batch", ")", ")", "end", "return", "email_batches", "end" ]
Get Send History related to a specific survey. Survey ID must be set inside the api request object. @return [Array<QuestionproRails::EmailBatch>] Email Batches.
[ "Get", "Send", "History", "related", "to", "a", "specific", "survey", ".", "Survey", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L375-L389
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.send_reminders
def send_reminders url = ApiRequest.base_path("questionpro.survey.sendReminder") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] self.message = result['response']['result'] end
ruby
def send_reminders url = ApiRequest.base_path("questionpro.survey.sendReminder") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] self.message = result['response']['result'] end
[ "def", "send_reminders", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.sendReminder\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "self", ".", "options", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "self", ".", "message", "=", "result", "[", "'response'", "]", "[", "'result'", "]", "end" ]
Send Reminders. Survey ID must be set inside the api request object. Email Group ID must be set inside the api request object. Template ID must be set inside the api request object. @return sets ApiRequest message attribute to "Message successful.".
[ "Send", "Reminders", ".", "Survey", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", ".", "Email", "Group", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", ".", "Template", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L397-L404
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/api_request.rb
QuestionproRails.ApiRequest.create_email_list
def create_email_list (emails = [], email_group_name = nil) url = ApiRequest.base_path("questionpro.survey.createEmailGroup") result = self.class.get(url, body: {id: self.survey_id, emails: emails, emailGroupName: email_group_name}.compact.to_json) self.full_response = result self.status = result['status'] unless result['response']['result']['emailGroupID'].nil? self.email_group_id = result['response']['result']['emailGroupID'] end end
ruby
def create_email_list (emails = [], email_group_name = nil) url = ApiRequest.base_path("questionpro.survey.createEmailGroup") result = self.class.get(url, body: {id: self.survey_id, emails: emails, emailGroupName: email_group_name}.compact.to_json) self.full_response = result self.status = result['status'] unless result['response']['result']['emailGroupID'].nil? self.email_group_id = result['response']['result']['emailGroupID'] end end
[ "def", "create_email_list", "(", "emails", "=", "[", "]", ",", "email_group_name", "=", "nil", ")", "url", "=", "ApiRequest", ".", "base_path", "(", "\"questionpro.survey.createEmailGroup\"", ")", "result", "=", "self", ".", "class", ".", "get", "(", "url", ",", "body", ":", "{", "id", ":", "self", ".", "survey_id", ",", "emails", ":", "emails", ",", "emailGroupName", ":", "email_group_name", "}", ".", "compact", ".", "to_json", ")", "self", ".", "full_response", "=", "result", "self", ".", "status", "=", "result", "[", "'status'", "]", "unless", "result", "[", "'response'", "]", "[", "'result'", "]", "[", "'emailGroupID'", "]", ".", "nil?", "self", ".", "email_group_id", "=", "result", "[", "'response'", "]", "[", "'result'", "]", "[", "'emailGroupID'", "]", "end", "end" ]
Create Email List. Survey ID must be set inside the api request object. @param [Array<String>] emails ([]). @param [String] email_group_name (nil). @return sets ApiRequest email_group_id to the created email list id.
[ "Create", "Email", "List", ".", "Survey", "ID", "must", "be", "set", "inside", "the", "api", "request", "object", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L412-L423
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/section.rb
QuestionproRails.Section.questions
def questions extracted_questions = [] unless self.qp_questions.nil? self.qp_questions.each do |question| extracted_questions.push(Question.new(question)) end end return extracted_questions end
ruby
def questions extracted_questions = [] unless self.qp_questions.nil? self.qp_questions.each do |question| extracted_questions.push(Question.new(question)) end end return extracted_questions end
[ "def", "questions", "extracted_questions", "=", "[", "]", "unless", "self", ".", "qp_questions", ".", "nil?", "self", ".", "qp_questions", ".", "each", "do", "|", "question", "|", "extracted_questions", ".", "push", "(", "Question", ".", "new", "(", "question", ")", ")", "end", "end", "return", "extracted_questions", "end" ]
Extract the Questions from the hashes stored inside qp_questions attribute. @return [Array<QuestionproRails::Question>] Questions.
[ "Extract", "the", "Questions", "from", "the", "hashes", "stored", "inside", "qp_questions", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/section.rb#L43-L53
train
yegor256/xcop
lib/xcop.rb
Xcop.Document.ldiff
def ldiff(license) xml = Nokogiri::XML(File.open(@path), &:noblanks) comment = xml.xpath('/comment()')[0] now = comment.nil? ? '' : comment.text.to_s.strip ideal = license.strip differ(ideal, now) end
ruby
def ldiff(license) xml = Nokogiri::XML(File.open(@path), &:noblanks) comment = xml.xpath('/comment()')[0] now = comment.nil? ? '' : comment.text.to_s.strip ideal = license.strip differ(ideal, now) end
[ "def", "ldiff", "(", "license", ")", "xml", "=", "Nokogiri", "::", "XML", "(", "File", ".", "open", "(", "@path", ")", ",", "&", ":noblanks", ")", "comment", "=", "xml", ".", "xpath", "(", "'/comment()'", ")", "[", "0", "]", "now", "=", "comment", ".", "nil?", "?", "''", ":", "comment", ".", "text", ".", "to_s", ".", "strip", "ideal", "=", "license", ".", "strip", "differ", "(", "ideal", ",", "now", ")", "end" ]
Return the difference for the license.
[ "Return", "the", "difference", "for", "the", "license", "." ]
281a053cb9b96ed9dbcf931271daf716ba10e4b5
https://github.com/yegor256/xcop/blob/281a053cb9b96ed9dbcf931271daf716ba10e4b5/lib/xcop.rb#L84-L90
train
yegor256/xcop
lib/xcop.rb
Xcop.Document.fix
def fix(license = '') xml = Nokogiri::XML(File.open(@path), &:noblanks) unless license.empty? xml.xpath('/comment()').remove xml.children.before( Nokogiri::XML::Comment.new(xml, "\n#{license.strip}\n") ) end ideal = xml.to_xml(indent: 2) File.write(@path, ideal) end
ruby
def fix(license = '') xml = Nokogiri::XML(File.open(@path), &:noblanks) unless license.empty? xml.xpath('/comment()').remove xml.children.before( Nokogiri::XML::Comment.new(xml, "\n#{license.strip}\n") ) end ideal = xml.to_xml(indent: 2) File.write(@path, ideal) end
[ "def", "fix", "(", "license", "=", "''", ")", "xml", "=", "Nokogiri", "::", "XML", "(", "File", ".", "open", "(", "@path", ")", ",", "&", ":noblanks", ")", "unless", "license", ".", "empty?", "xml", ".", "xpath", "(", "'/comment()'", ")", ".", "remove", "xml", ".", "children", ".", "before", "(", "Nokogiri", "::", "XML", "::", "Comment", ".", "new", "(", "xml", ",", "\"\\n#{license.strip}\\n\"", ")", ")", "end", "ideal", "=", "xml", ".", "to_xml", "(", "indent", ":", "2", ")", "File", ".", "write", "(", "@path", ",", "ideal", ")", "end" ]
Fixes the document.
[ "Fixes", "the", "document", "." ]
281a053cb9b96ed9dbcf931271daf716ba10e4b5
https://github.com/yegor256/xcop/blob/281a053cb9b96ed9dbcf931271daf716ba10e4b5/lib/xcop.rb#L93-L103
train
dwayne/xo
lib/xo/engine/init.rb
XO.Init.start
def start(turn) game_context.check_turn(turn) game_context.set_turn_and_clear_grid(turn) engine.transition_to_state_and_send_event(Playing, :game_started) end
ruby
def start(turn) game_context.check_turn(turn) game_context.set_turn_and_clear_grid(turn) engine.transition_to_state_and_send_event(Playing, :game_started) end
[ "def", "start", "(", "turn", ")", "game_context", ".", "check_turn", "(", "turn", ")", "game_context", ".", "set_turn_and_clear_grid", "(", "turn", ")", "engine", ".", "transition_to_state_and_send_event", "(", "Playing", ",", ":game_started", ")", "end" ]
Starts a new game. The engine is transitioned into the {Playing} state and the event { name: :game_started } is triggered. @param turn [Grid::X, Grid::O] specifies which token has first play @raise [ArgumentError] unless turn is either {Grid::X} or {Grid::O}
[ "Starts", "a", "new", "game", "." ]
bd6524cf8882585fd5cca940f1daa5fb5f75d2bb
https://github.com/dwayne/xo/blob/bd6524cf8882585fd5cca940f1daa5fb5f75d2bb/lib/xo/engine/init.rb#L18-L22
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/survey.rb
QuestionproRails.Survey.sections
def sections extracted_sections = [] unless self.qp_sections.nil? self.qp_sections.each do |section| extracted_sections.push(Section.new(section)) end end return extracted_sections end
ruby
def sections extracted_sections = [] unless self.qp_sections.nil? self.qp_sections.each do |section| extracted_sections.push(Section.new(section)) end end return extracted_sections end
[ "def", "sections", "extracted_sections", "=", "[", "]", "unless", "self", ".", "qp_sections", ".", "nil?", "self", ".", "qp_sections", ".", "each", "do", "|", "section", "|", "extracted_sections", ".", "push", "(", "Section", ".", "new", "(", "section", ")", ")", "end", "end", "return", "extracted_sections", "end" ]
Extract the Sections from the hashes stored inside qp_sections attribute. @return [Array<QuestionproRails::Section>] Sections.
[ "Extract", "the", "Sections", "from", "the", "hashes", "stored", "inside", "qp_sections", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/survey.rb#L28-L38
train
isabanin/mercurial-ruby
lib/mercurial-ruby/commit.rb
Mercurial.Commit.stats
def stats(cmd_options={}) raw = hg(["log -r ? --stat --template '{node}\n'", hash_id], cmd_options) result = raw.scan(/(\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(\-\)$/).flatten.map{|r| r.to_i} return {} if result.empty? # that commit has no stats { 'files' => result[0], 'additions' => result[1], 'deletions' => result[2], 'total' => result[1] + result[2] } end
ruby
def stats(cmd_options={}) raw = hg(["log -r ? --stat --template '{node}\n'", hash_id], cmd_options) result = raw.scan(/(\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(\-\)$/).flatten.map{|r| r.to_i} return {} if result.empty? # that commit has no stats { 'files' => result[0], 'additions' => result[1], 'deletions' => result[2], 'total' => result[1] + result[2] } end
[ "def", "stats", "(", "cmd_options", "=", "{", "}", ")", "raw", "=", "hg", "(", "[", "\"log -r ? --stat --template '{node}\\n'\"", ",", "hash_id", "]", ",", "cmd_options", ")", "result", "=", "raw", ".", "scan", "(", "/", "\\d", "\\d", "\\(", "\\+", "\\)", "\\d", "\\(", "\\-", "\\)", "/", ")", ".", "flatten", ".", "map", "{", "|", "r", "|", "r", ".", "to_i", "}", "return", "{", "}", "if", "result", ".", "empty?", "{", "'files'", "=>", "result", "[", "0", "]", ",", "'additions'", "=>", "result", "[", "1", "]", ",", "'deletions'", "=>", "result", "[", "2", "]", ",", "'total'", "=>", "result", "[", "1", "]", "+", "result", "[", "2", "]", "}", "end" ]
Returns a Hash of diffstat-style summary of changes for the commit.
[ "Returns", "a", "Hash", "of", "diffstat", "-", "style", "summary", "of", "changes", "for", "the", "commit", "." ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/commit.rb#L102-L112
train
buren/honey_format
lib/honey_format/matrix/row_builder.rb
HoneyFormat.RowBuilder.build
def build(row) build_row!(row) rescue ArgumentError => e raise unless e.message == 'struct size differs' raise_invalid_row_length!(e, row) end
ruby
def build(row) build_row!(row) rescue ArgumentError => e raise unless e.message == 'struct size differs' raise_invalid_row_length!(e, row) end
[ "def", "build", "(", "row", ")", "build_row!", "(", "row", ")", "rescue", "ArgumentError", "=>", "e", "raise", "unless", "e", ".", "message", "==", "'struct size differs'", "raise_invalid_row_length!", "(", "e", ",", "row", ")", "end" ]
Returns a new instance of RowBuilder. @return [RowBuilder] a new instance of RowBuilder. @param [Array<Symbol>] columns an array of symbols. @param builder [#call, #to_csv] optional row builder. @param type_map [Hash] map of column_name => type conversion to perform. @raise [RowError] super class of errors raised when there is a row error. @raise [EmptyRowColumnsError] raised when there are no columns. @raise [InvalidRowLengthError] raised when row has more columns than header columns. @example Create new row RowBuilder.new!([:id]) Returns an object representing the row. @return [Row, Object] a new instance of built row. @param row [Array] the row array. @raise [InvalidRowLengthError] raised when there are more row elements longer than columns @example Build new row r = RowBuilder.new([:id]) r.build(['1']).id #=> '1'
[ "Returns", "a", "new", "instance", "of", "RowBuilder", "." ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/row_builder.rb#L38-L44
train
isabanin/mercurial-ruby
lib/mercurial-ruby/config_file.rb
Mercurial.ConfigFile.find_header
def find_header(header) {}.tap do |returning| contents.scan(header_with_content_regexp(header)).flatten.first.split("\n").each do |setting| name, value = *setting.split('=').map(&:strip) returning[name] = value end end end
ruby
def find_header(header) {}.tap do |returning| contents.scan(header_with_content_regexp(header)).flatten.first.split("\n").each do |setting| name, value = *setting.split('=').map(&:strip) returning[name] = value end end end
[ "def", "find_header", "(", "header", ")", "{", "}", ".", "tap", "do", "|", "returning", "|", "contents", ".", "scan", "(", "header_with_content_regexp", "(", "header", ")", ")", ".", "flatten", ".", "first", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "setting", "|", "name", ",", "value", "=", "*", "setting", ".", "split", "(", "'='", ")", ".", "map", "(", "&", ":strip", ")", "returning", "[", "name", "]", "=", "value", "end", "end", "end" ]
Returns content of the specified section of hgrc.
[ "Returns", "content", "of", "the", "specified", "section", "of", "hgrc", "." ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/config_file.rb#L93-L100
train
isabanin/mercurial-ruby
lib/mercurial-ruby/config_file.rb
Mercurial.ConfigFile.find_setting
def find_setting(header, setting) #:nodoc: return nil if contents.nil? contents.scan(setting_regexp(header, setting)).flatten.first end
ruby
def find_setting(header, setting) #:nodoc: return nil if contents.nil? contents.scan(setting_regexp(header, setting)).flatten.first end
[ "def", "find_setting", "(", "header", ",", "setting", ")", "return", "nil", "if", "contents", ".", "nil?", "contents", ".", "scan", "(", "setting_regexp", "(", "header", ",", "setting", ")", ")", ".", "flatten", ".", "first", "end" ]
Returns content of the specified setting from a section.
[ "Returns", "content", "of", "the", "specified", "setting", "from", "a", "section", "." ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/config_file.rb#L105-L108
train
isabanin/mercurial-ruby
lib/mercurial-ruby/factories/hook_factory.rb
Mercurial.HookFactory.add
def add(name, value) build(name, value).tap do |hook| hook.save end end
ruby
def add(name, value) build(name, value).tap do |hook| hook.save end end
[ "def", "add", "(", "name", ",", "value", ")", "build", "(", "name", ",", "value", ")", ".", "tap", "do", "|", "hook", "|", "hook", ".", "save", "end", "end" ]
Adds a new hook to the repository. === Example: repository.hooks.add('changegroup', 'do_something')
[ "Adds", "a", "new", "hook", "to", "the", "repository", "." ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/factories/hook_factory.rb#L47-L51
train
couchrest/couchrest_extended_document
lib/couchrest/extended_document.rb
CouchRest.ExtendedDocument.create_without_callbacks
def create_without_callbacks(bulk =false) raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database set_unique_id if new? && self.respond_to?(:set_unique_id) result = database.save_doc(self, bulk) (result["ok"] == true) ? self : false end
ruby
def create_without_callbacks(bulk =false) raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database set_unique_id if new? && self.respond_to?(:set_unique_id) result = database.save_doc(self, bulk) (result["ok"] == true) ? self : false end
[ "def", "create_without_callbacks", "(", "bulk", "=", "false", ")", "raise", "ArgumentError", ",", "\"a document requires a database to be created to (The document or the #{self.class} default database were not set)\"", "unless", "database", "set_unique_id", "if", "new?", "&&", "self", ".", "respond_to?", "(", ":set_unique_id", ")", "result", "=", "database", ".", "save_doc", "(", "self", ",", "bulk", ")", "(", "result", "[", "\"ok\"", "]", "==", "true", ")", "?", "self", ":", "false", "end" ]
unlike save, create returns the newly created document
[ "unlike", "save", "create", "returns", "the", "newly", "created", "document" ]
71511202ae10d3010dcf7b98fcba017cb37c76da
https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/extended_document.rb#L185-L190
train
acaprojects/doorkeeper-couchbase
lib/support/orm/couchbase/access_token.rb
Doorkeeper.AccessToken.save
def save(**options) if use_refresh_token? options[:ttl] = self.created_at + 6.months else options[:ttl] = self.created_at + self.expires_in + 30 end super(**options) end
ruby
def save(**options) if use_refresh_token? options[:ttl] = self.created_at + 6.months else options[:ttl] = self.created_at + self.expires_in + 30 end super(**options) end
[ "def", "save", "(", "**", "options", ")", "if", "use_refresh_token?", "options", "[", ":ttl", "]", "=", "self", ".", "created_at", "+", "6", ".", "months", "else", "options", "[", ":ttl", "]", "=", "self", ".", "created_at", "+", "self", ".", "expires_in", "+", "30", "end", "super", "(", "**", "options", ")", "end" ]
Lets make sure these keys are not clogging up the database forever
[ "Lets", "make", "sure", "these", "keys", "are", "not", "clogging", "up", "the", "database", "forever" ]
534747e4e58c44805c99a6f2e746de6ffc5c4e59
https://github.com/acaprojects/doorkeeper-couchbase/blob/534747e4e58c44805c99a6f2e746de6ffc5c4e59/lib/support/orm/couchbase/access_token.rb#L212-L219
train
buren/honey_format
lib/honey_format/matrix/row.rb
HoneyFormat.Row.to_csv
def to_csv(columns: nil) attributes = members attributes = columns & attributes if columns row = attributes.map! { |column| to_csv_value(column) } ::CSV.generate_line(row) end
ruby
def to_csv(columns: nil) attributes = members attributes = columns & attributes if columns row = attributes.map! { |column| to_csv_value(column) } ::CSV.generate_line(row) end
[ "def", "to_csv", "(", "columns", ":", "nil", ")", "attributes", "=", "members", "attributes", "=", "columns", "&", "attributes", "if", "columns", "row", "=", "attributes", ".", "map!", "{", "|", "column", "|", "to_csv_value", "(", "column", ")", "}", "::", "CSV", ".", "generate_line", "(", "row", ")", "end" ]
Represent row as CSV @param columns [Array<Symbol>, Set<Symbol>, NilClass] the columns to output, nil means all columns (default: nil) @return [String] CSV-string representation.
[ "Represent", "row", "as", "CSV" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/row.rb#L20-L27
train
buren/honey_format
lib/honey_format/matrix/row.rb
HoneyFormat.Row.inspect
def inspect attributes = members.map do |field| value = self[field] value = "\"#{value}\"" if value.is_a?(String) [field, value].join('=') end.join(', ') "#<Row #{attributes}>" end
ruby
def inspect attributes = members.map do |field| value = self[field] value = "\"#{value}\"" if value.is_a?(String) [field, value].join('=') end.join(', ') "#<Row #{attributes}>" end
[ "def", "inspect", "attributes", "=", "members", ".", "map", "do", "|", "field", "|", "value", "=", "self", "[", "field", "]", "value", "=", "\"\\\"#{value}\\\"\"", "if", "value", ".", "is_a?", "(", "String", ")", "[", "field", ",", "value", "]", ".", "join", "(", "'='", ")", "end", ".", "join", "(", "', '", ")", "\"#<Row #{attributes}>\"", "end" ]
Describe the contents of this row in a string. @return [String] content of this row
[ "Describe", "the", "contents", "of", "this", "row", "in", "a", "string", "." ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/row.rb#L31-L40
train
buren/honey_format
lib/honey_format/matrix/row.rb
HoneyFormat.Row.to_csv_value
def to_csv_value(column) value = public_send(column) return if value.nil? return value.to_csv if value.respond_to?(:to_csv) value.to_s end
ruby
def to_csv_value(column) value = public_send(column) return if value.nil? return value.to_csv if value.respond_to?(:to_csv) value.to_s end
[ "def", "to_csv_value", "(", "column", ")", "value", "=", "public_send", "(", "column", ")", "return", "if", "value", ".", "nil?", "return", "value", ".", "to_csv", "if", "value", ".", "respond_to?", "(", ":to_csv", ")", "value", ".", "to_s", "end" ]
Returns the column in CSV format @param [Symbol] column name @return [String] column value as CSV string
[ "Returns", "the", "column", "in", "CSV", "format" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/row.rb#L48-L54
train
isabanin/mercurial-ruby
lib/mercurial-ruby/file_index.rb
Mercurial.FileIndex.update
def update(oldrev=nil, newrev=nil) if index_file_exists? && oldrev != "0"*40 hg([ "log --debug -r ?:? --style ? >> ?", oldrev, newrev, Style.file_index, path ]) else hg(["log --debug -r : --style ? > ?", Style.file_index, path]) end end
ruby
def update(oldrev=nil, newrev=nil) if index_file_exists? && oldrev != "0"*40 hg([ "log --debug -r ?:? --style ? >> ?", oldrev, newrev, Style.file_index, path ]) else hg(["log --debug -r : --style ? > ?", Style.file_index, path]) end end
[ "def", "update", "(", "oldrev", "=", "nil", ",", "newrev", "=", "nil", ")", "if", "index_file_exists?", "&&", "oldrev", "!=", "\"0\"", "*", "40", "hg", "(", "[", "\"log --debug -r ?:? --style ? >> ?\"", ",", "oldrev", ",", "newrev", ",", "Style", ".", "file_index", ",", "path", "]", ")", "else", "hg", "(", "[", "\"log --debug -r : --style ? > ?\"", ",", "Style", ".", "file_index", ",", "path", "]", ")", "end", "end" ]
updates file index
[ "updates", "file", "index" ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/file_index.rb#L37-L46
train
isabanin/mercurial-ruby
lib/mercurial-ruby/file_index.rb
Mercurial.FileIndex.commits_from
def commits_from(commit_sha) raise UnsupportedRef if commit_sha.is_a? Array read_if_needed already = {} final = [] left_to_do = [commit_sha] while commit_sha = left_to_do.shift next if already[commit_sha] final << commit_sha already[commit_sha] = true commit = @commit_index[commit_sha] commit[:parents].each do |sha| left_to_do << sha end if commit end sort_commits(final) end
ruby
def commits_from(commit_sha) raise UnsupportedRef if commit_sha.is_a? Array read_if_needed already = {} final = [] left_to_do = [commit_sha] while commit_sha = left_to_do.shift next if already[commit_sha] final << commit_sha already[commit_sha] = true commit = @commit_index[commit_sha] commit[:parents].each do |sha| left_to_do << sha end if commit end sort_commits(final) end
[ "def", "commits_from", "(", "commit_sha", ")", "raise", "UnsupportedRef", "if", "commit_sha", ".", "is_a?", "Array", "read_if_needed", "already", "=", "{", "}", "final", "=", "[", "]", "left_to_do", "=", "[", "commit_sha", "]", "while", "commit_sha", "=", "left_to_do", ".", "shift", "next", "if", "already", "[", "commit_sha", "]", "final", "<<", "commit_sha", "already", "[", "commit_sha", "]", "=", "true", "commit", "=", "@commit_index", "[", "commit_sha", "]", "commit", "[", ":parents", "]", ".", "each", "do", "|", "sha", "|", "left_to_do", "<<", "sha", "end", "if", "commit", "end", "sort_commits", "(", "final", ")", "end" ]
builds a list of all commits reachable from a single commit
[ "builds", "a", "list", "of", "all", "commits", "reachable", "from", "a", "single", "commit" ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/file_index.rb#L63-L84
train
couchrest/couchrest_extended_document
lib/couchrest/casted_model.rb
CouchRest.CastedModel.update_attributes_without_saving
def update_attributes_without_saving(hash) hash.each do |k, v| raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=") end hash.each do |k, v| self.send("#{k}=",v) end end
ruby
def update_attributes_without_saving(hash) hash.each do |k, v| raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=") end hash.each do |k, v| self.send("#{k}=",v) end end
[ "def", "update_attributes_without_saving", "(", "hash", ")", "hash", ".", "each", "do", "|", "k", ",", "v", "|", "raise", "NoMethodError", ",", "\"#{k}= method not available, use property :#{k}\"", "unless", "self", ".", "respond_to?", "(", "\"#{k}=\"", ")", "end", "hash", ".", "each", "do", "|", "k", ",", "v", "|", "self", ".", "send", "(", "\"#{k}=\"", ",", "v", ")", "end", "end" ]
Sets the attributes from a hash
[ "Sets", "the", "attributes", "from", "a", "hash" ]
71511202ae10d3010dcf7b98fcba017cb37c76da
https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/casted_model.rb#L42-L49
train
mjy/obo_parser
lib/obo_parser.rb
OboParser.OboParser.term_hash
def term_hash @terms.inject({}) {|sum, t| sum.update(t.name.value => t.id.value)} end
ruby
def term_hash @terms.inject({}) {|sum, t| sum.update(t.name.value => t.id.value)} end
[ "def", "term_hash", "@terms", ".", "inject", "(", "{", "}", ")", "{", "|", "sum", ",", "t", "|", "sum", ".", "update", "(", "t", ".", "name", ".", "value", "=>", "t", ".", "id", ".", "value", ")", "}", "end" ]
Warning! This assumes terms are unique, they are NOT required to be so in an OBO file. Ignores hash colisions!! @return [Hash] (String => String) (name => id)
[ "Warning!", "This", "assumes", "terms", "are", "unique", "they", "are", "NOT", "required", "to", "be", "so", "in", "an", "OBO", "file", ".", "Ignores", "hash", "colisions!!" ]
f81757b512f3557277909c46372ab89a42704722
https://github.com/mjy/obo_parser/blob/f81757b512f3557277909c46372ab89a42704722/lib/obo_parser.rb#L32-L34
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/response_set.rb
QuestionproRails.ResponseSet.answers
def answers extracted_answers = [] unless self.qp_values.nil? self.qp_values.each do |answer| extracted_answers.push(ResponseAnswer.new(answer)) end end return extracted_answers end
ruby
def answers extracted_answers = [] unless self.qp_values.nil? self.qp_values.each do |answer| extracted_answers.push(ResponseAnswer.new(answer)) end end return extracted_answers end
[ "def", "answers", "extracted_answers", "=", "[", "]", "unless", "self", ".", "qp_values", ".", "nil?", "self", ".", "qp_values", ".", "each", "do", "|", "answer", "|", "extracted_answers", ".", "push", "(", "ResponseAnswer", ".", "new", "(", "answer", ")", ")", "end", "end", "return", "extracted_answers", "end" ]
Extract the Answers from the hashes stored inside qp_values attribute. @return [Array<QuestionproRails::ResponseAnswer>] Response Answers.
[ "Extract", "the", "Answers", "from", "the", "hashes", "stored", "inside", "qp_values", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/response_set.rb#L23-L33
train
Tapjoy/acts_as_approvable
lib/acts_as_approvable/model.rb
ActsAsApprovable.Model.acts_as_approvable
def acts_as_approvable(options = {}) extend ClassMethods include InstanceMethods cattr_accessor :approvable_on self.approvable_on = Array.wrap(options.delete(:on) { [:create, :update, :destroy] }) cattr_accessor :approvable_field self.approvable_field = options.delete(:state_field) cattr_accessor :approvable_ignore ignores = Array.wrap(options.delete(:ignore) { [] }) ignores.push('created_at', 'updated_at', primary_key, self.approvable_field) self.approvable_ignore = ignores.compact.uniq.map(&:to_s) cattr_accessor :approvable_only self.approvable_only = Array.wrap(options.delete(:only) { [] }).uniq.map(&:to_s) cattr_accessor :approvals_disabled self.approvals_disabled = false has_many :approvals, :as => :item, :dependent => :destroy if approvable_on?(:update) include UpdateInstanceMethods before_update :approvable_update, :if => :approvable_update? end if approvable_on?(:create) include CreateInstanceMethods before_create :approvable_create, :if => :approvable_create? end if approvable_on?(:destroy) include DestroyInstanceMethods end after_save :approvable_save, :if => :approvals_enabled? end
ruby
def acts_as_approvable(options = {}) extend ClassMethods include InstanceMethods cattr_accessor :approvable_on self.approvable_on = Array.wrap(options.delete(:on) { [:create, :update, :destroy] }) cattr_accessor :approvable_field self.approvable_field = options.delete(:state_field) cattr_accessor :approvable_ignore ignores = Array.wrap(options.delete(:ignore) { [] }) ignores.push('created_at', 'updated_at', primary_key, self.approvable_field) self.approvable_ignore = ignores.compact.uniq.map(&:to_s) cattr_accessor :approvable_only self.approvable_only = Array.wrap(options.delete(:only) { [] }).uniq.map(&:to_s) cattr_accessor :approvals_disabled self.approvals_disabled = false has_many :approvals, :as => :item, :dependent => :destroy if approvable_on?(:update) include UpdateInstanceMethods before_update :approvable_update, :if => :approvable_update? end if approvable_on?(:create) include CreateInstanceMethods before_create :approvable_create, :if => :approvable_create? end if approvable_on?(:destroy) include DestroyInstanceMethods end after_save :approvable_save, :if => :approvals_enabled? end
[ "def", "acts_as_approvable", "(", "options", "=", "{", "}", ")", "extend", "ClassMethods", "include", "InstanceMethods", "cattr_accessor", ":approvable_on", "self", ".", "approvable_on", "=", "Array", ".", "wrap", "(", "options", ".", "delete", "(", ":on", ")", "{", "[", ":create", ",", ":update", ",", ":destroy", "]", "}", ")", "cattr_accessor", ":approvable_field", "self", ".", "approvable_field", "=", "options", ".", "delete", "(", ":state_field", ")", "cattr_accessor", ":approvable_ignore", "ignores", "=", "Array", ".", "wrap", "(", "options", ".", "delete", "(", ":ignore", ")", "{", "[", "]", "}", ")", "ignores", ".", "push", "(", "'created_at'", ",", "'updated_at'", ",", "primary_key", ",", "self", ".", "approvable_field", ")", "self", ".", "approvable_ignore", "=", "ignores", ".", "compact", ".", "uniq", ".", "map", "(", "&", ":to_s", ")", "cattr_accessor", ":approvable_only", "self", ".", "approvable_only", "=", "Array", ".", "wrap", "(", "options", ".", "delete", "(", ":only", ")", "{", "[", "]", "}", ")", ".", "uniq", ".", "map", "(", "&", ":to_s", ")", "cattr_accessor", ":approvals_disabled", "self", ".", "approvals_disabled", "=", "false", "has_many", ":approvals", ",", ":as", "=>", ":item", ",", ":dependent", "=>", ":destroy", "if", "approvable_on?", "(", ":update", ")", "include", "UpdateInstanceMethods", "before_update", ":approvable_update", ",", ":if", "=>", ":approvable_update?", "end", "if", "approvable_on?", "(", ":create", ")", "include", "CreateInstanceMethods", "before_create", ":approvable_create", ",", ":if", "=>", ":approvable_create?", "end", "if", "approvable_on?", "(", ":destroy", ")", "include", "DestroyInstanceMethods", "end", "after_save", ":approvable_save", ",", ":if", "=>", ":approvals_enabled?", "end" ]
Declare this in your model to require approval on new records or changes to fields. @param [Hash] options the options for this models approval workflow. @option options [Symbol,Array] :on The events to require approval on (`:create`, `:update` or `:destroy`). @option options [String] :state_field The local field to store `:create` approval state. @option options [Array] :ignore A list of fields to ignore. By default we ignore `:created_at`, `:updated_at` and the field specified in `:state_field`. @option options [Array] :only A list of fields to explicitly require approval on. This list supercedes `:ignore`.
[ "Declare", "this", "in", "your", "model", "to", "require", "approval", "on", "new", "records", "or", "changes", "to", "fields", "." ]
5113ba6fd2a05a1cc95bd657519f3334c596eed5
https://github.com/Tapjoy/acts_as_approvable/blob/5113ba6fd2a05a1cc95bd657519f3334c596eed5/lib/acts_as_approvable/model.rb#L20-L58
train
jrochkind/traject_horizon
lib/traject/horizon_reader.rb
Traject.HorizonReader.require_jars!
def require_jars! require 'jruby' # ask marc-marc4j gem to load the marc4j jars MARC::MARC4J.new(:jardir => settings['marc4j_reader.jar_dir']) # For some reason we seem to need to java_import it, and use # a string like this. can't just refer to it by full # qualified name, not sure why, but this seems to work. java_import "org.marc4j.converter.impl.AnselToUnicode" unless defined? Java::net.sourceforge.jtds.jdbc.Driver jtds_jar_dir = settings["jtds.jar_path"] || File.expand_path("../../vendor/jtds", File.dirname(__FILE__)) Dir.glob("#{jtds_jar_dir}/*.jar") do |x| require x end # For confusing reasons, in normal Java need to # Class.forName("net.sourceforge.jtds.jdbc.Driver") # to get the jtds driver to actually be recognized by JDBC. # # In Jruby, Class.forName doesn't work, but this seems # to do the same thing: Java::net.sourceforge.jtds.jdbc.Driver end # So we can refer to these classes as just ResultSet, etc. java_import java.sql.ResultSet, java.sql.PreparedStatement, java.sql.Driver end
ruby
def require_jars! require 'jruby' # ask marc-marc4j gem to load the marc4j jars MARC::MARC4J.new(:jardir => settings['marc4j_reader.jar_dir']) # For some reason we seem to need to java_import it, and use # a string like this. can't just refer to it by full # qualified name, not sure why, but this seems to work. java_import "org.marc4j.converter.impl.AnselToUnicode" unless defined? Java::net.sourceforge.jtds.jdbc.Driver jtds_jar_dir = settings["jtds.jar_path"] || File.expand_path("../../vendor/jtds", File.dirname(__FILE__)) Dir.glob("#{jtds_jar_dir}/*.jar") do |x| require x end # For confusing reasons, in normal Java need to # Class.forName("net.sourceforge.jtds.jdbc.Driver") # to get the jtds driver to actually be recognized by JDBC. # # In Jruby, Class.forName doesn't work, but this seems # to do the same thing: Java::net.sourceforge.jtds.jdbc.Driver end # So we can refer to these classes as just ResultSet, etc. java_import java.sql.ResultSet, java.sql.PreparedStatement, java.sql.Driver end
[ "def", "require_jars!", "require", "'jruby'", "MARC", "::", "MARC4J", ".", "new", "(", ":jardir", "=>", "settings", "[", "'marc4j_reader.jar_dir'", "]", ")", "java_import", "\"org.marc4j.converter.impl.AnselToUnicode\"", "unless", "defined?", "Java", "::", "net", ".", "sourceforge", ".", "jtds", ".", "jdbc", ".", "Driver", "jtds_jar_dir", "=", "settings", "[", "\"jtds.jar_path\"", "]", "||", "File", ".", "expand_path", "(", "\"../../vendor/jtds\"", ",", "File", ".", "dirname", "(", "__FILE__", ")", ")", "Dir", ".", "glob", "(", "\"#{jtds_jar_dir}/*.jar\"", ")", "do", "|", "x", "|", "require", "x", "end", "Java", "::", "net", ".", "sourceforge", ".", "jtds", ".", "jdbc", ".", "Driver", "end", "java_import", "java", ".", "sql", ".", "ResultSet", ",", "java", ".", "sql", ".", "PreparedStatement", ",", "java", ".", "sql", ".", "Driver", "end" ]
We ignore the iostream even though we get one, we're gonna read from a Horizon DB! Requires marc4j and jtds, and java_import's some classes.
[ "We", "ignore", "the", "iostream", "even", "though", "we", "get", "one", "we", "re", "gonna", "read", "from", "a", "Horizon", "DB!", "Requires", "marc4j", "and", "jtds", "and", "java_import", "s", "some", "classes", "." ]
f56f1785fccfb2cb123ce3100a3051fca4db39ac
https://github.com/jrochkind/traject_horizon/blob/f56f1785fccfb2cb123ce3100a3051fca4db39ac/lib/traject/horizon_reader.rb#L161-L190
train
jrochkind/traject_horizon
lib/traject/horizon_reader.rb
Traject.HorizonReader.convert_text!
def convert_text!(text, error_handler) text = AnselToUnicode.new(error_handler, true).convert(text) if convert_marc8_to_utf8? # Turn Horizon's weird escaping into UTF8: <U+nnnn> where nnnn is a hex unicode # codepoint, turn it UTF8 for that codepoint if settings["horizon.destination_encoding"] == "UTF8" && (settings["horizon.codepoint_translate"].to_s == "true" || settings["horizon.character_reference_translate"].to_s == "true") regexp = if settings["horizon.codepoint_translate"].to_s == "true" && settings["horizon.character_reference_translate"].to_s == "true" # unicode codepoint in either HTML char reference form OR # weird horizon form. /(?:\<U\+|&#x)([0-9A-Fa-f]{4})(?:\>|;)/ elsif settings["horizon.codepoint_translate"].to_s == "true" # just weird horizon form /\<U\+([0-9A-Fa-f]{4})\>/ else # just character references /&#x([0-9A-Fa-f]{4});/ end text.gsub!(regexp) do [$1.hex].pack("U") end end # eliminate illegal control chars. All ASCII less than 0x20 # _except_ for four legal ones (including MARC delimiters). # http://www.loc.gov/marc/specifications/specchargeneral.html#controlfunction # this is all bytes from 0x00 to 0x19 except for the allowed 1B, 1D, 1E, 1F. text.gsub!(/[\x00-\x1A\x1C]/, '') return text end
ruby
def convert_text!(text, error_handler) text = AnselToUnicode.new(error_handler, true).convert(text) if convert_marc8_to_utf8? # Turn Horizon's weird escaping into UTF8: <U+nnnn> where nnnn is a hex unicode # codepoint, turn it UTF8 for that codepoint if settings["horizon.destination_encoding"] == "UTF8" && (settings["horizon.codepoint_translate"].to_s == "true" || settings["horizon.character_reference_translate"].to_s == "true") regexp = if settings["horizon.codepoint_translate"].to_s == "true" && settings["horizon.character_reference_translate"].to_s == "true" # unicode codepoint in either HTML char reference form OR # weird horizon form. /(?:\<U\+|&#x)([0-9A-Fa-f]{4})(?:\>|;)/ elsif settings["horizon.codepoint_translate"].to_s == "true" # just weird horizon form /\<U\+([0-9A-Fa-f]{4})\>/ else # just character references /&#x([0-9A-Fa-f]{4});/ end text.gsub!(regexp) do [$1.hex].pack("U") end end # eliminate illegal control chars. All ASCII less than 0x20 # _except_ for four legal ones (including MARC delimiters). # http://www.loc.gov/marc/specifications/specchargeneral.html#controlfunction # this is all bytes from 0x00 to 0x19 except for the allowed 1B, 1D, 1E, 1F. text.gsub!(/[\x00-\x1A\x1C]/, '') return text end
[ "def", "convert_text!", "(", "text", ",", "error_handler", ")", "text", "=", "AnselToUnicode", ".", "new", "(", "error_handler", ",", "true", ")", ".", "convert", "(", "text", ")", "if", "convert_marc8_to_utf8?", "if", "settings", "[", "\"horizon.destination_encoding\"", "]", "==", "\"UTF8\"", "&&", "(", "settings", "[", "\"horizon.codepoint_translate\"", "]", ".", "to_s", "==", "\"true\"", "||", "settings", "[", "\"horizon.character_reference_translate\"", "]", ".", "to_s", "==", "\"true\"", ")", "regexp", "=", "if", "settings", "[", "\"horizon.codepoint_translate\"", "]", ".", "to_s", "==", "\"true\"", "&&", "settings", "[", "\"horizon.character_reference_translate\"", "]", ".", "to_s", "==", "\"true\"", "/", "\\<", "\\+", "\\>", "/", "elsif", "settings", "[", "\"horizon.codepoint_translate\"", "]", ".", "to_s", "==", "\"true\"", "/", "\\<", "\\+", "\\>", "/", "else", "/", "/", "end", "text", ".", "gsub!", "(", "regexp", ")", "do", "[", "$1", ".", "hex", "]", ".", "pack", "(", "\"U\"", ")", "end", "end", "text", ".", "gsub!", "(", "/", "\\x00", "\\x1A", "\\x1C", "/", ",", "''", ")", "return", "text", "end" ]
Converts from Marc8 to UTF8 if neccesary. Also replaces escaped unicode codepoints using custom Horizon "<U+nnnn>" format Or standard MARC 'lossless encoding' "&#xHHHH;" format.
[ "Converts", "from", "Marc8", "to", "UTF8", "if", "neccesary", "." ]
f56f1785fccfb2cb123ce3100a3051fca4db39ac
https://github.com/jrochkind/traject_horizon/blob/f56f1785fccfb2cb123ce3100a3051fca4db39ac/lib/traject/horizon_reader.rb#L275-L307
train
jrochkind/traject_horizon
lib/traject/horizon_reader.rb
Traject.HorizonReader.fix_leader!
def fix_leader!(leader) if leader.length < 24 # pad it to 24 bytes, leader is supposed to be 24 bytes leader.replace( leader.ljust(24, ' ') ) elsif leader.length > 24 # Also a problem, slice it leader.replace( leader.byteslice(0, 24)) end # http://www.loc.gov/marc/bibliographic/ecbdldrd.html leader[10..11] = '22' leader[20..23] = '4500' if settings['horizon.destination_encoding'] == "UTF8" leader[9] = 'a' end # leader should only have ascii chars in it; invalid non-ascii # chars can cause ruby encoding problems down the line. # additionally, a force_encoding may be neccesary to # deal with apparent weird hard to isolate jruby bug prob same one # as at https://github.com/jruby/jruby/issues/886 leader.force_encoding('ascii') unless leader.valid_encoding? # replace any non-ascii chars with a space. # Can't access leader.chars when it's not a valid encoding # without a weird index out of bounds exception, think it's # https://github.com/jruby/jruby/issues/886 # Grr. #leader.replace( leader.chars.collect { |c| c.valid_encoding? ? c : ' ' }.join('') ) leader.replace(leader.split('').collect { |c| c.valid_encoding? ? c : ' ' }.join('')) end end
ruby
def fix_leader!(leader) if leader.length < 24 # pad it to 24 bytes, leader is supposed to be 24 bytes leader.replace( leader.ljust(24, ' ') ) elsif leader.length > 24 # Also a problem, slice it leader.replace( leader.byteslice(0, 24)) end # http://www.loc.gov/marc/bibliographic/ecbdldrd.html leader[10..11] = '22' leader[20..23] = '4500' if settings['horizon.destination_encoding'] == "UTF8" leader[9] = 'a' end # leader should only have ascii chars in it; invalid non-ascii # chars can cause ruby encoding problems down the line. # additionally, a force_encoding may be neccesary to # deal with apparent weird hard to isolate jruby bug prob same one # as at https://github.com/jruby/jruby/issues/886 leader.force_encoding('ascii') unless leader.valid_encoding? # replace any non-ascii chars with a space. # Can't access leader.chars when it's not a valid encoding # without a weird index out of bounds exception, think it's # https://github.com/jruby/jruby/issues/886 # Grr. #leader.replace( leader.chars.collect { |c| c.valid_encoding? ? c : ' ' }.join('') ) leader.replace(leader.split('').collect { |c| c.valid_encoding? ? c : ' ' }.join('')) end end
[ "def", "fix_leader!", "(", "leader", ")", "if", "leader", ".", "length", "<", "24", "leader", ".", "replace", "(", "leader", ".", "ljust", "(", "24", ",", "' '", ")", ")", "elsif", "leader", ".", "length", ">", "24", "leader", ".", "replace", "(", "leader", ".", "byteslice", "(", "0", ",", "24", ")", ")", "end", "leader", "[", "10", "..", "11", "]", "=", "'22'", "leader", "[", "20", "..", "23", "]", "=", "'4500'", "if", "settings", "[", "'horizon.destination_encoding'", "]", "==", "\"UTF8\"", "leader", "[", "9", "]", "=", "'a'", "end", "leader", ".", "force_encoding", "(", "'ascii'", ")", "unless", "leader", ".", "valid_encoding?", "leader", ".", "replace", "(", "leader", ".", "split", "(", "''", ")", ".", "collect", "{", "|", "c", "|", "c", ".", "valid_encoding?", "?", "c", ":", "' '", "}", ".", "join", "(", "''", ")", ")", "end", "end" ]
Mutate string passed in to fix leader bytes for marc21
[ "Mutate", "string", "passed", "in", "to", "fix", "leader", "bytes", "for", "marc21" ]
f56f1785fccfb2cb123ce3100a3051fca4db39ac
https://github.com/jrochkind/traject_horizon/blob/f56f1785fccfb2cb123ce3100a3051fca4db39ac/lib/traject/horizon_reader.rb#L633-L671
train
arjunmenon/smalltext
lib/smalltext.rb
Smalltext.Classifier.softmax
def softmax(w) e = Numo::NMath.exp(w - (w.max)) dist = e / (e.sum) return dist end
ruby
def softmax(w) e = Numo::NMath.exp(w - (w.max)) dist = e / (e.sum) return dist end
[ "def", "softmax", "(", "w", ")", "e", "=", "Numo", "::", "NMath", ".", "exp", "(", "w", "-", "(", "w", ".", "max", ")", ")", "dist", "=", "e", "/", "(", "e", ".", "sum", ")", "return", "dist", "end" ]
using softmax as output layer is recommended for classification where outputs are mutually exclusive
[ "using", "softmax", "as", "output", "layer", "is", "recommended", "for", "classification", "where", "outputs", "are", "mutually", "exclusive" ]
0d208f70d0300ac7a5a375568a7457fb2a6bbd9a
https://github.com/arjunmenon/smalltext/blob/0d208f70d0300ac7a5a375568a7457fb2a6bbd9a/lib/smalltext.rb#L329-L333
train
wingrunr21/gitolite
lib/gitolite/config.rb
Gitolite.Config.normalize_name
def normalize_name(context, constant = nil) case context when constant context.name when Symbol context.to_s else context end end
ruby
def normalize_name(context, constant = nil) case context when constant context.name when Symbol context.to_s else context end end
[ "def", "normalize_name", "(", "context", ",", "constant", "=", "nil", ")", "case", "context", "when", "constant", "context", ".", "name", "when", "Symbol", "context", ".", "to_s", "else", "context", "end", "end" ]
Normalizes the various different input objects to Strings
[ "Normalizes", "the", "various", "different", "input", "objects", "to", "Strings" ]
f86ec83e0885734000432b9502ccaa2dc26f4376
https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/config.rb#L192-L201
train
murakmii/cborb
lib/cborb/decoding/state.rb
Cborb::Decoding.State.<<
def <<(cbor) @buffer.write(cbor) @decoding_fiber.resume rescue FiberError => e msg = e.message # umm... if msg.include?("dead") raise Cborb::InvalidByteSequenceError elsif msg.include?("threads") raise Cborb::DecodingError, "Can't decode across threads" else raise end end
ruby
def <<(cbor) @buffer.write(cbor) @decoding_fiber.resume rescue FiberError => e msg = e.message # umm... if msg.include?("dead") raise Cborb::InvalidByteSequenceError elsif msg.include?("threads") raise Cborb::DecodingError, "Can't decode across threads" else raise end end
[ "def", "<<", "(", "cbor", ")", "@buffer", ".", "write", "(", "cbor", ")", "@decoding_fiber", ".", "resume", "rescue", "FiberError", "=>", "e", "msg", "=", "e", ".", "message", "if", "msg", ".", "include?", "(", "\"dead\"", ")", "raise", "Cborb", "::", "InvalidByteSequenceError", "elsif", "msg", ".", "include?", "(", "\"threads\"", ")", "raise", "Cborb", "::", "DecodingError", ",", "\"Can't decode across threads\"", "else", "raise", "end", "end" ]
Buffering new CBOR data @param [String] cbor
[ "Buffering", "new", "CBOR", "data" ]
ea4763ff815889f31e19375db8284d9337d409eb
https://github.com/murakmii/cborb/blob/ea4763ff815889f31e19375db8284d9337d409eb/lib/cborb/decoding/state.rb#L21-L36
train
murakmii/cborb
lib/cborb/decoding/state.rb
Cborb::Decoding.State.consume
def consume(size) data = @buffer.read(size).to_s # If buffered data is not enought, yield fiber until new data will be buffered. if data.size < size @buffer.reset! while data.size != size Fiber.yield data += @buffer.read(size - data.size) end end data end
ruby
def consume(size) data = @buffer.read(size).to_s # If buffered data is not enought, yield fiber until new data will be buffered. if data.size < size @buffer.reset! while data.size != size Fiber.yield data += @buffer.read(size - data.size) end end data end
[ "def", "consume", "(", "size", ")", "data", "=", "@buffer", ".", "read", "(", "size", ")", ".", "to_s", "if", "data", ".", "size", "<", "size", "@buffer", ".", "reset!", "while", "data", ".", "size", "!=", "size", "Fiber", ".", "yield", "data", "+=", "@buffer", ".", "read", "(", "size", "-", "data", ".", "size", ")", "end", "end", "data", "end" ]
Consume CBOR data. This method will be called only in fiber. @param [Integer] size Size to consume @return [String]
[ "Consume", "CBOR", "data", ".", "This", "method", "will", "be", "called", "only", "in", "fiber", "." ]
ea4763ff815889f31e19375db8284d9337d409eb
https://github.com/murakmii/cborb/blob/ea4763ff815889f31e19375db8284d9337d409eb/lib/cborb/decoding/state.rb#L43-L57
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/survey_meta.rb
QuestionproRails.SurveyMeta.email_groups
def email_groups extracted_groups = [] unless self.email_groups_list.nil? self.email_groups_list.each do |email_group| extracted_groups.push(EmailGroup.new(email_group)) end end return extracted_groups end
ruby
def email_groups extracted_groups = [] unless self.email_groups_list.nil? self.email_groups_list.each do |email_group| extracted_groups.push(EmailGroup.new(email_group)) end end return extracted_groups end
[ "def", "email_groups", "extracted_groups", "=", "[", "]", "unless", "self", ".", "email_groups_list", ".", "nil?", "self", ".", "email_groups_list", ".", "each", "do", "|", "email_group", "|", "extracted_groups", ".", "push", "(", "EmailGroup", ".", "new", "(", "email_group", ")", ")", "end", "end", "return", "extracted_groups", "end" ]
Extract the Email Groups from the hashes stored inside email_groups_list attribute. @return [Array<QuestionproRails::EmailGroup>] Email Groups.
[ "Extract", "the", "Email", "Groups", "from", "the", "hashes", "stored", "inside", "email_groups_list", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/survey_meta.rb#L22-L32
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/survey_meta.rb
QuestionproRails.SurveyMeta.templates
def templates extracted_templates = [] unless self.templates_list.nil? self.templates_list.each do |template| extracted_templates.push(Template.new(template)) end end return extracted_templates end
ruby
def templates extracted_templates = [] unless self.templates_list.nil? self.templates_list.each do |template| extracted_templates.push(Template.new(template)) end end return extracted_templates end
[ "def", "templates", "extracted_templates", "=", "[", "]", "unless", "self", ".", "templates_list", ".", "nil?", "self", ".", "templates_list", ".", "each", "do", "|", "template", "|", "extracted_templates", ".", "push", "(", "Template", ".", "new", "(", "template", ")", ")", "end", "end", "return", "extracted_templates", "end" ]
Extract the Templates from the hashes stored inside templates_list attribute. @return [Array<QuestionproRails::Template>] Templates.
[ "Extract", "the", "Templates", "from", "the", "hashes", "stored", "inside", "templates_list", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/survey_meta.rb#L38-L48
train
culturecode/stagehand
lib/stagehand/production.rb
Stagehand.Production.matching
def matching(staging_record, table_name = nil) table_name, id = Stagehand::Key.generate(staging_record, :table_name => table_name) prepare_to_modify(table_name) return Record.where(:id => id) end
ruby
def matching(staging_record, table_name = nil) table_name, id = Stagehand::Key.generate(staging_record, :table_name => table_name) prepare_to_modify(table_name) return Record.where(:id => id) end
[ "def", "matching", "(", "staging_record", ",", "table_name", "=", "nil", ")", "table_name", ",", "id", "=", "Stagehand", "::", "Key", ".", "generate", "(", "staging_record", ",", ":table_name", "=>", "table_name", ")", "prepare_to_modify", "(", "table_name", ")", "return", "Record", ".", "where", "(", ":id", "=>", "id", ")", "end" ]
Returns a scope that limits results any occurrences of the specified record. Record can be specified by passing a staging record, or an id and table_name.
[ "Returns", "a", "scope", "that", "limits", "results", "any", "occurrences", "of", "the", "specified", "record", ".", "Record", "can", "be", "specified", "by", "passing", "a", "staging", "record", "or", "an", "id", "and", "table_name", "." ]
af627f1948b9dfc39ec13aefe77a47c21b4456a5
https://github.com/culturecode/stagehand/blob/af627f1948b9dfc39ec13aefe77a47c21b4456a5/lib/stagehand/production.rb#L62-L66
train
alexdovzhanyn/rydux
lib/rydux/store.rb
Rydux.Store.subscribe
def subscribe(caller = nil, &block) if block_given? notify_when = block.call(state) @listeners << { obj: block.binding.receiver, notify_when: notify_when } else @listeners << { obj: caller } end end
ruby
def subscribe(caller = nil, &block) if block_given? notify_when = block.call(state) @listeners << { obj: block.binding.receiver, notify_when: notify_when } else @listeners << { obj: caller } end end
[ "def", "subscribe", "(", "caller", "=", "nil", ",", "&", "block", ")", "if", "block_given?", "notify_when", "=", "block", ".", "call", "(", "state", ")", "@listeners", "<<", "{", "obj", ":", "block", ".", "binding", ".", "receiver", ",", "notify_when", ":", "notify_when", "}", "else", "@listeners", "<<", "{", "obj", ":", "caller", "}", "end", "end" ]
Allow subscribing either by passing a reference to self or by passing a block which defines the state keys that this listener cares about
[ "Allow", "subscribing", "either", "by", "passing", "a", "reference", "to", "self", "or", "by", "passing", "a", "block", "which", "defines", "the", "state", "keys", "that", "this", "listener", "cares", "about" ]
04983f5fd5cff8c2e9a0eb230ca72e9eb954170f
https://github.com/alexdovzhanyn/rydux/blob/04983f5fd5cff8c2e9a0eb230ca72e9eb954170f/lib/rydux/store.rb#L13-L20
train
alexdovzhanyn/rydux
lib/rydux/store.rb
Rydux.Store.strap_reducers
def strap_reducers(reducers) reducers.each {|k, reducer| set_state *[k, reducer.map_state(type: nil)]} reducers end
ruby
def strap_reducers(reducers) reducers.each {|k, reducer| set_state *[k, reducer.map_state(type: nil)]} reducers end
[ "def", "strap_reducers", "(", "reducers", ")", "reducers", ".", "each", "{", "|", "k", ",", "reducer", "|", "set_state", "*", "[", "k", ",", "reducer", ".", "map_state", "(", "type", ":", "nil", ")", "]", "}", "reducers", "end" ]
Initialize state with the key-value pair associated with each reducer
[ "Initialize", "state", "with", "the", "key", "-", "value", "pair", "associated", "with", "each", "reducer" ]
04983f5fd5cff8c2e9a0eb230ca72e9eb954170f
https://github.com/alexdovzhanyn/rydux/blob/04983f5fd5cff8c2e9a0eb230ca72e9eb954170f/lib/rydux/store.rb#L60-L63
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.add
def add(path, prefix = nil) path = File.expand_path path prefix ||= '/' in_work_tree File.dirname(path) do index = @git.index index.read_tree 'HEAD' add = lambda do |f, p| file = File.basename f pre = (p == '/') ? file : File.join(p, file) dir = File.stat(f).directory? if dir (Dir.entries(f) - %w{. ..}).each do |child| add.call File.join(f, child), pre end else index.add pre, IO.read(f) end dir end dir = add.call path, prefix type = dir ? 'directory' : 'file' commit_msg = "Added #{type} #{path} into '#{prefix}'" index.commit commit_msg, [@git.head.commit.sha] end end
ruby
def add(path, prefix = nil) path = File.expand_path path prefix ||= '/' in_work_tree File.dirname(path) do index = @git.index index.read_tree 'HEAD' add = lambda do |f, p| file = File.basename f pre = (p == '/') ? file : File.join(p, file) dir = File.stat(f).directory? if dir (Dir.entries(f) - %w{. ..}).each do |child| add.call File.join(f, child), pre end else index.add pre, IO.read(f) end dir end dir = add.call path, prefix type = dir ? 'directory' : 'file' commit_msg = "Added #{type} #{path} into '#{prefix}'" index.commit commit_msg, [@git.head.commit.sha] end end
[ "def", "add", "(", "path", ",", "prefix", "=", "nil", ")", "path", "=", "File", ".", "expand_path", "path", "prefix", "||=", "'/'", "in_work_tree", "File", ".", "dirname", "(", "path", ")", "do", "index", "=", "@git", ".", "index", "index", ".", "read_tree", "'HEAD'", "add", "=", "lambda", "do", "|", "f", ",", "p", "|", "file", "=", "File", ".", "basename", "f", "pre", "=", "(", "p", "==", "'/'", ")", "?", "file", ":", "File", ".", "join", "(", "p", ",", "file", ")", "dir", "=", "File", ".", "stat", "(", "f", ")", ".", "directory?", "if", "dir", "(", "Dir", ".", "entries", "(", "f", ")", "-", "%w{", ".", "..", "}", ")", ".", "each", "do", "|", "child", "|", "add", ".", "call", "File", ".", "join", "(", "f", ",", "child", ")", ",", "pre", "end", "else", "index", ".", "add", "pre", ",", "IO", ".", "read", "(", "f", ")", "end", "dir", "end", "dir", "=", "add", ".", "call", "path", ",", "prefix", "type", "=", "dir", "?", "'directory'", ":", "'file'", "commit_msg", "=", "\"Added #{type} #{path} into '#{prefix}'\"", "index", ".", "commit", "commit_msg", ",", "[", "@git", ".", "head", ".", "commit", ".", "sha", "]", "end", "end" ]
Creates a new repository instance on the given path @param [Hash] options A hash of options @option options [Boolean] :create (true) Creates the backing Git repository if it does not already exist @option options [Boolean] :prepare (true) Prepares the backing Git repository for use with Silo if not already done @raise [Grit::InvalidGitRepositoryError] if the path exists, but is not a valid Git repository @raise [Grit::NoSuchPathError] if the path does not exist and option :create is +false+ @raise [InvalidRepositoryError] if the path contains another Git repository that does not contain data managed by Silo. Stores a file or full directory structure into the repository inside an optional prefix path This adds one commit to the history of the repository including the file or directory structure. If the file or directory already existed inside the prefix, Git will only save the changes. @param [String] path The path of the file or directory to store into the repository @param [String] prefix An optional prefix where the file is stored inside the repository
[ "Creates", "a", "new", "repository", "instance", "on", "the", "given", "path" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L91-L115
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.add_remote
def add_remote(name, url) @remotes[name] = Remote::Git.new(self, name, url) @remotes[name].add end
ruby
def add_remote(name, url) @remotes[name] = Remote::Git.new(self, name, url) @remotes[name].add end
[ "def", "add_remote", "(", "name", ",", "url", ")", "@remotes", "[", "name", "]", "=", "Remote", "::", "Git", ".", "new", "(", "self", ",", "name", ",", "url", ")", "@remotes", "[", "name", "]", ".", "add", "end" ]
Adds a new remote to this Repository @param [String] name The name of the remote to add @param [String] url The URL of the remote repository @see Remote
[ "Adds", "a", "new", "remote", "to", "this", "Repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L122-L125
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.contents
def contents(path = nil) contents = [] object = find_object(path || '/') contents << path unless path.nil? || object.nil? if object.is_a? Grit::Tree (object.blobs + object.trees).each do |obj| contents += contents(path.nil? ? obj.basename : File.join(path, obj.basename)) end end contents end
ruby
def contents(path = nil) contents = [] object = find_object(path || '/') contents << path unless path.nil? || object.nil? if object.is_a? Grit::Tree (object.blobs + object.trees).each do |obj| contents += contents(path.nil? ? obj.basename : File.join(path, obj.basename)) end end contents end
[ "def", "contents", "(", "path", "=", "nil", ")", "contents", "=", "[", "]", "object", "=", "find_object", "(", "path", "||", "'/'", ")", "contents", "<<", "path", "unless", "path", ".", "nil?", "||", "object", ".", "nil?", "if", "object", ".", "is_a?", "Grit", "::", "Tree", "(", "object", ".", "blobs", "+", "object", ".", "trees", ")", ".", "each", "do", "|", "obj", "|", "contents", "+=", "contents", "(", "path", ".", "nil?", "?", "obj", ".", "basename", ":", "File", ".", "join", "(", "path", ",", "obj", ".", "basename", ")", ")", "end", "end", "contents", "end" ]
Gets a list of files and directories in the specified path inside the repository @param [String] path The path to search for inside the repository @return [Array<String>] All files and directories found in the specidied path
[ "Gets", "a", "list", "of", "files", "and", "directories", "in", "the", "specified", "path", "inside", "the", "repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L133-L145
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.git_remotes
def git_remotes remotes = {} @git.git.remote.split.each do |remote| url = @git.git.config({}, '--get', "remote.#{remote}.url").strip remotes[remote] = Remote::Git.new(self, remote, url) end remotes end
ruby
def git_remotes remotes = {} @git.git.remote.split.each do |remote| url = @git.git.config({}, '--get', "remote.#{remote}.url").strip remotes[remote] = Remote::Git.new(self, remote, url) end remotes end
[ "def", "git_remotes", "remotes", "=", "{", "}", "@git", ".", "git", ".", "remote", ".", "split", ".", "each", "do", "|", "remote", "|", "url", "=", "@git", ".", "git", ".", "config", "(", "{", "}", ",", "'--get'", ",", "\"remote.#{remote}.url\"", ")", ".", "strip", "remotes", "[", "remote", "]", "=", "Remote", "::", "Git", ".", "new", "(", "self", ",", "remote", ",", "url", ")", "end", "remotes", "end" ]
Loads remotes from the backing Git repository's configuration @see Remote::Git
[ "Loads", "remotes", "from", "the", "backing", "Git", "repository", "s", "configuration" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L167-L174
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.history
def history(path = nil) params = ['--format=raw'] params += ['--', path] unless path.nil? output = @git.git.log({}, *params) Grit::Commit.list_from_string @git, output end
ruby
def history(path = nil) params = ['--format=raw'] params += ['--', path] unless path.nil? output = @git.git.log({}, *params) Grit::Commit.list_from_string @git, output end
[ "def", "history", "(", "path", "=", "nil", ")", "params", "=", "[", "'--format=raw'", "]", "params", "+=", "[", "'--'", ",", "path", "]", "unless", "path", ".", "nil?", "output", "=", "@git", ".", "git", ".", "log", "(", "{", "}", ",", "*", "params", ")", "Grit", "::", "Commit", ".", "list_from_string", "@git", ",", "output", "end" ]
Generate a history of Git commits for either the complete repository or a specified file or directory @param [String] path The path of the file or directory to generate the history for. If +nil+, the history of the entire repository will be returned. @return [Array<Grit::Commit>] The commit history for the repository or given path
[ "Generate", "a", "history", "of", "Git", "commits", "for", "either", "the", "complete", "repository", "or", "a", "specified", "file", "or", "directory" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L184-L189
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.info
def info(path) info = {} object = object! path info[:history] = history path info[:mode] = object.mode info[:name] = object.name info[:path] = path info[:sha] = object.id info[:created] = info[:history].last.committed_date info[:modified] = info[:history].first.committed_date if object.is_a? Grit::Blob info[:mime] = object.mime_type info[:size] = object.size info[:type] = :blob else info[:path] += '/' info[:type] = :tree end info end
ruby
def info(path) info = {} object = object! path info[:history] = history path info[:mode] = object.mode info[:name] = object.name info[:path] = path info[:sha] = object.id info[:created] = info[:history].last.committed_date info[:modified] = info[:history].first.committed_date if object.is_a? Grit::Blob info[:mime] = object.mime_type info[:size] = object.size info[:type] = :blob else info[:path] += '/' info[:type] = :tree end info end
[ "def", "info", "(", "path", ")", "info", "=", "{", "}", "object", "=", "object!", "path", "info", "[", ":history", "]", "=", "history", "path", "info", "[", ":mode", "]", "=", "object", ".", "mode", "info", "[", ":name", "]", "=", "object", ".", "name", "info", "[", ":path", "]", "=", "path", "info", "[", ":sha", "]", "=", "object", ".", "id", "info", "[", ":created", "]", "=", "info", "[", ":history", "]", ".", "last", ".", "committed_date", "info", "[", ":modified", "]", "=", "info", "[", ":history", "]", ".", "first", ".", "committed_date", "if", "object", ".", "is_a?", "Grit", "::", "Blob", "info", "[", ":mime", "]", "=", "object", ".", "mime_type", "info", "[", ":size", "]", "=", "object", ".", "size", "info", "[", ":type", "]", "=", ":blob", "else", "info", "[", ":path", "]", "+=", "'/'", "info", "[", ":type", "]", "=", ":tree", "end", "info", "end" ]
Get information about a file or directory in the repository @param [String] path The path of the file or directory to get information about @return [Hash<Symbol, Object>] Information about the requested file or directory.
[ "Get", "information", "about", "a", "file", "or", "directory", "in", "the", "repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L218-L241
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.prepare
def prepare raise AlreadyPreparedError.new(@path) if prepared? in_work_tree :tmp do FileUtils.touch '.silo' @git.add '.silo' @git.commit_index 'Enabled Silo for this repository' end end
ruby
def prepare raise AlreadyPreparedError.new(@path) if prepared? in_work_tree :tmp do FileUtils.touch '.silo' @git.add '.silo' @git.commit_index 'Enabled Silo for this repository' end end
[ "def", "prepare", "raise", "AlreadyPreparedError", ".", "new", "(", "@path", ")", "if", "prepared?", "in_work_tree", ":tmp", "do", "FileUtils", ".", "touch", "'.silo'", "@git", ".", "add", "'.silo'", "@git", ".", "commit_index", "'Enabled Silo for this repository'", "end", "end" ]
Prepares the Git repository backing this Silo repository for use with Silo @raise [AlreadyPreparedError] if the repository has been already prepared
[ "Prepares", "the", "Git", "repository", "backing", "this", "Silo", "repository", "for", "use", "with", "Silo" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L259-L266
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.purge
def purge(path, prune = true) object = object! path if object.is_a? Grit::Tree (object.blobs + object.trees).each do |blob| purge File.join(path, blob.basename), prune end else params = ['-f', '--index-filter', "git rm --cached --ignore-unmatch #{path}"] params << '--prune-empty' if prune params << 'HEAD' @git.git.filter_branch({}, *params) end end
ruby
def purge(path, prune = true) object = object! path if object.is_a? Grit::Tree (object.blobs + object.trees).each do |blob| purge File.join(path, blob.basename), prune end else params = ['-f', '--index-filter', "git rm --cached --ignore-unmatch #{path}"] params << '--prune-empty' if prune params << 'HEAD' @git.git.filter_branch({}, *params) end end
[ "def", "purge", "(", "path", ",", "prune", "=", "true", ")", "object", "=", "object!", "path", "if", "object", ".", "is_a?", "Grit", "::", "Tree", "(", "object", ".", "blobs", "+", "object", ".", "trees", ")", ".", "each", "do", "|", "blob", "|", "purge", "File", ".", "join", "(", "path", ",", "blob", ".", "basename", ")", ",", "prune", "end", "else", "params", "=", "[", "'-f'", ",", "'--index-filter'", ",", "\"git rm --cached --ignore-unmatch #{path}\"", "]", "params", "<<", "'--prune-empty'", "if", "prune", "params", "<<", "'HEAD'", "@git", ".", "git", ".", "filter_branch", "(", "{", "}", ",", "*", "params", ")", "end", "end" ]
Purges a single file or the complete structure of a directory with the given path from the repository *WARNING*: This will cause a complete rewrite of the repository history and therefore deletes the data completely. @param [String] path The path of the file or directory to purge from the repository @param [Boolean] prune Remove empty commits in the Git history
[ "Purges", "a", "single", "file", "or", "the", "complete", "structure", "of", "a", "directory", "with", "the", "given", "path", "from", "the", "repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L285-L298
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.remove
def remove(path) object = object! path path += '/' if object.is_a?(Grit::Tree) && path[-1].chr != '/' index = @git.index index.read_tree 'HEAD' index.delete path type = object.is_a?(Grit::Tree) ? 'directory' : 'file' commit_msg = "Removed #{type} #{path}" index.commit commit_msg, [@git.head.commit.sha] end
ruby
def remove(path) object = object! path path += '/' if object.is_a?(Grit::Tree) && path[-1].chr != '/' index = @git.index index.read_tree 'HEAD' index.delete path type = object.is_a?(Grit::Tree) ? 'directory' : 'file' commit_msg = "Removed #{type} #{path}" index.commit commit_msg, [@git.head.commit.sha] end
[ "def", "remove", "(", "path", ")", "object", "=", "object!", "path", "path", "+=", "'/'", "if", "object", ".", "is_a?", "(", "Grit", "::", "Tree", ")", "&&", "path", "[", "-", "1", "]", ".", "chr", "!=", "'/'", "index", "=", "@git", ".", "index", "index", ".", "read_tree", "'HEAD'", "index", ".", "delete", "path", "type", "=", "object", ".", "is_a?", "(", "Grit", "::", "Tree", ")", "?", "'directory'", ":", "'file'", "commit_msg", "=", "\"Removed #{type} #{path}\"", "index", ".", "commit", "commit_msg", ",", "[", "@git", ".", "head", ".", "commit", ".", "sha", "]", "end" ]
Removes a single file or the complete structure of a directory with the given path from the HEAD revision of the repository *NOTE*: The data won't be lost as it will be preserved in the history of the Git repository. @param [String] path The path of the file or directory to remove from the repository
[ "Removes", "a", "single", "file", "or", "the", "complete", "structure", "of", "a", "directory", "with", "the", "given", "path", "from", "the", "HEAD", "revision", "of", "the", "repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L308-L317
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.remove_remote
def remove_remote(name) remote = @remotes[name] raise UndefinedRemoteError.new(name) if remote.nil? remote.remove @remotes[name] = nil end
ruby
def remove_remote(name) remote = @remotes[name] raise UndefinedRemoteError.new(name) if remote.nil? remote.remove @remotes[name] = nil end
[ "def", "remove_remote", "(", "name", ")", "remote", "=", "@remotes", "[", "name", "]", "raise", "UndefinedRemoteError", ".", "new", "(", "name", ")", "if", "remote", ".", "nil?", "remote", ".", "remove", "@remotes", "[", "name", "]", "=", "nil", "end" ]
Removes the remote with the given name from this repository @param [String] name The name of the remote to remove @see Remote
[ "Removes", "the", "remote", "with", "the", "given", "name", "from", "this", "repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L324-L329
train
koraktor/silo
lib/silo/repository.rb
Silo.Repository.restore
def restore(path, prefix = '.') object = object! path prefix = File.expand_path prefix FileUtils.mkdir_p prefix unless File.exists? prefix file_path = File.join prefix, File.basename(path) if object.is_a? Grit::Tree FileUtils.mkdir file_path unless File.directory? file_path (object.blobs + object.trees).each do |obj| restore File.join(path, obj.basename), file_path end else file = File.new file_path, 'w' file.write object.data file.close end end
ruby
def restore(path, prefix = '.') object = object! path prefix = File.expand_path prefix FileUtils.mkdir_p prefix unless File.exists? prefix file_path = File.join prefix, File.basename(path) if object.is_a? Grit::Tree FileUtils.mkdir file_path unless File.directory? file_path (object.blobs + object.trees).each do |obj| restore File.join(path, obj.basename), file_path end else file = File.new file_path, 'w' file.write object.data file.close end end
[ "def", "restore", "(", "path", ",", "prefix", "=", "'.'", ")", "object", "=", "object!", "path", "prefix", "=", "File", ".", "expand_path", "prefix", "FileUtils", ".", "mkdir_p", "prefix", "unless", "File", ".", "exists?", "prefix", "file_path", "=", "File", ".", "join", "prefix", ",", "File", ".", "basename", "(", "path", ")", "if", "object", ".", "is_a?", "Grit", "::", "Tree", "FileUtils", ".", "mkdir", "file_path", "unless", "File", ".", "directory?", "file_path", "(", "object", ".", "blobs", "+", "object", ".", "trees", ")", ".", "each", "do", "|", "obj", "|", "restore", "File", ".", "join", "(", "path", ",", "obj", ".", "basename", ")", ",", "file_path", "end", "else", "file", "=", "File", ".", "new", "file_path", ",", "'w'", "file", ".", "write", "object", ".", "data", "file", ".", "close", "end", "end" ]
Restores a single file or the complete structure of a directory with the given path from the repository @param [String] path The path of the file or directory to restore from the repository @param [String] prefix An optional prefix where the file is restored
[ "Restores", "a", "single", "file", "or", "the", "complete", "structure", "of", "a", "directory", "with", "the", "given", "path", "from", "the", "repository" ]
19a5fcc162dc24dd4846d154756a7c3bdeab400d
https://github.com/koraktor/silo/blob/19a5fcc162dc24dd4846d154756a7c3bdeab400d/lib/silo/repository.rb#L337-L354
train
samvera-labs/geo_works
lib/generators/geo_works/install_generator.rb
GeoWorks.Install.inject_solr_document_behavior
def inject_solr_document_behavior file_path = 'app/models/solr_document.rb' if File.exist?(file_path) inject_into_file file_path, after: /include Blacklight::Solr::Document.*$/ do "\n # Adds GeoWorks behaviors to the SolrDocument.\n" \ " include GeoWorks::SolrDocumentBehavior\n" end else Rails.logger.info " \e[31mFailure\e[0m GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist." end end
ruby
def inject_solr_document_behavior file_path = 'app/models/solr_document.rb' if File.exist?(file_path) inject_into_file file_path, after: /include Blacklight::Solr::Document.*$/ do "\n # Adds GeoWorks behaviors to the SolrDocument.\n" \ " include GeoWorks::SolrDocumentBehavior\n" end else Rails.logger.info " \e[31mFailure\e[0m GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist." end end
[ "def", "inject_solr_document_behavior", "file_path", "=", "'app/models/solr_document.rb'", "if", "File", ".", "exist?", "(", "file_path", ")", "inject_into_file", "file_path", ",", "after", ":", "/", "/", "do", "\"\\n # Adds GeoWorks behaviors to the SolrDocument.\\n\"", "\" include GeoWorks::SolrDocumentBehavior\\n\"", "end", "else", "Rails", ".", "logger", ".", "info", "\" \\e[31mFailure\\e[0m GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist.\"", "end", "end" ]
Add behaviors to the SolrDocument model
[ "Add", "behaviors", "to", "the", "SolrDocument", "model" ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/lib/generators/geo_works/install_generator.rb#L96-L106
train
AssemDeghady/questionpro_rails
lib/questionpro_rails/survey_response.rb
QuestionproRails.SurveyResponse.response_set
def response_set extracted_sets = [] unless self.qp_response_set.nil? self.qp_response_set.each do |set| extracted_sets.push(ResponseSet.new(set)) end end return extracted_sets end
ruby
def response_set extracted_sets = [] unless self.qp_response_set.nil? self.qp_response_set.each do |set| extracted_sets.push(ResponseSet.new(set)) end end return extracted_sets end
[ "def", "response_set", "extracted_sets", "=", "[", "]", "unless", "self", ".", "qp_response_set", ".", "nil?", "self", ".", "qp_response_set", ".", "each", "do", "|", "set", "|", "extracted_sets", ".", "push", "(", "ResponseSet", ".", "new", "(", "set", ")", ")", "end", "end", "return", "extracted_sets", "end" ]
Extract the Response Set from the hash stored inside qp_response_set attribute. @return [Array<QuestionproRails::ResponseSet>] Response Sets.
[ "Extract", "the", "Response", "Set", "from", "the", "hash", "stored", "inside", "qp_response_set", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/survey_response.rb#L31-L41
train
phatworx/rails_paginate
lib/rails_paginate/renderers/base.rb
RailsPaginate::Renderers.Base.url_for_page
def url_for_page(page) view.url_for(view.default_url_options.merge({page_param.to_sym => page}).merge(options[:params] || {})) end
ruby
def url_for_page(page) view.url_for(view.default_url_options.merge({page_param.to_sym => page}).merge(options[:params] || {})) end
[ "def", "url_for_page", "(", "page", ")", "view", ".", "url_for", "(", "view", ".", "default_url_options", ".", "merge", "(", "{", "page_param", ".", "to_sym", "=>", "page", "}", ")", ".", "merge", "(", "options", "[", ":params", "]", "||", "{", "}", ")", ")", "end" ]
setup rails_paginate collection build url
[ "setup", "rails_paginate", "collection", "build", "url" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/base.rb#L18-L20
train
phatworx/rails_paginate
lib/rails_paginate/renderers/base.rb
RailsPaginate::Renderers.Base.link_to_page
def link_to_page(page, key, link_options = {}) css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}" if key.nil? content_tag :span, "..", :class => "spacer" elsif page.nil? content_tag :span, t(key), :class => "#{css_class} unavailable" else link_to t(key, :page => page), url_for_page(page), :class => css_class, :alt => view.strip_tags(t(key, :page => page)), :remote => options[:remote], :method => options[:method] end end
ruby
def link_to_page(page, key, link_options = {}) css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}" if key.nil? content_tag :span, "..", :class => "spacer" elsif page.nil? content_tag :span, t(key), :class => "#{css_class} unavailable" else link_to t(key, :page => page), url_for_page(page), :class => css_class, :alt => view.strip_tags(t(key, :page => page)), :remote => options[:remote], :method => options[:method] end end
[ "def", "link_to_page", "(", "page", ",", "key", ",", "link_options", "=", "{", "}", ")", "css_class", "=", "\"#{link_options[:class]} #{page == current_page ? 'current' : ''}\"", "if", "key", ".", "nil?", "content_tag", ":span", ",", "\"..\"", ",", ":class", "=>", "\"spacer\"", "elsif", "page", ".", "nil?", "content_tag", ":span", ",", "t", "(", "key", ")", ",", ":class", "=>", "\"#{css_class} unavailable\"", "else", "link_to", "t", "(", "key", ",", ":page", "=>", "page", ")", ",", "url_for_page", "(", "page", ")", ",", ":class", "=>", "css_class", ",", ":alt", "=>", "view", ".", "strip_tags", "(", "t", "(", "key", ",", ":page", "=>", "page", ")", ")", ",", ":remote", "=>", "options", "[", ":remote", "]", ",", ":method", "=>", "options", "[", ":method", "]", "end", "end" ]
link to page with i18n support
[ "link", "to", "page", "with", "i18n", "support" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/base.rb#L30-L39
train
piotrmurach/communist
lib/communist/server.rb
Communist.Server.stop
def stop server = Communist.servers.delete(app.object_id) { |s| NullServer.new } if Communist.server.respond_to?(:shutdown) server.shutdown elsif Communist.server.respond_to?(:stop!) server.stop! else server.stop end @server_thread.join end
ruby
def stop server = Communist.servers.delete(app.object_id) { |s| NullServer.new } if Communist.server.respond_to?(:shutdown) server.shutdown elsif Communist.server.respond_to?(:stop!) server.stop! else server.stop end @server_thread.join end
[ "def", "stop", "server", "=", "Communist", ".", "servers", ".", "delete", "(", "app", ".", "object_id", ")", "{", "|", "s", "|", "NullServer", ".", "new", "}", "if", "Communist", ".", "server", ".", "respond_to?", "(", ":shutdown", ")", "server", ".", "shutdown", "elsif", "Communist", ".", "server", ".", "respond_to?", "(", ":stop!", ")", "server", ".", "stop!", "else", "server", ".", "stop", "end", "@server_thread", ".", "join", "end" ]
Stops the server after handling the connection. Attempts to stop the server gracefully, otherwise shuts current connection right away.
[ "Stops", "the", "server", "after", "handling", "the", "connection", ".", "Attempts", "to", "stop", "the", "server", "gracefully", "otherwise", "shuts", "current", "connection", "right", "away", "." ]
1f660ee1f201a265a65842d348414c17fcc0810a
https://github.com/piotrmurach/communist/blob/1f660ee1f201a265a65842d348414c17fcc0810a/lib/communist/server.rb#L85-L95
train
sinefunc/pagination
lib/pagination/collection.rb
Pagination.Collection.displayed_pages
def displayed_pages(limit = 10, left_offset = -5, right_offset = 4) lower, upper = nil, nil if page + left_offset < 1 || page + right_offset > pages.last lower = [page, [pages.last - limit, 0].max + 1].min upper = [page + limit - 1, pages.last].min else lower = page + left_offset upper = page + right_offset end (lower..upper).to_a end
ruby
def displayed_pages(limit = 10, left_offset = -5, right_offset = 4) lower, upper = nil, nil if page + left_offset < 1 || page + right_offset > pages.last lower = [page, [pages.last - limit, 0].max + 1].min upper = [page + limit - 1, pages.last].min else lower = page + left_offset upper = page + right_offset end (lower..upper).to_a end
[ "def", "displayed_pages", "(", "limit", "=", "10", ",", "left_offset", "=", "-", "5", ",", "right_offset", "=", "4", ")", "lower", ",", "upper", "=", "nil", ",", "nil", "if", "page", "+", "left_offset", "<", "1", "||", "page", "+", "right_offset", ">", "pages", ".", "last", "lower", "=", "[", "page", ",", "[", "pages", ".", "last", "-", "limit", ",", "0", "]", ".", "max", "+", "1", "]", ".", "min", "upper", "=", "[", "page", "+", "limit", "-", "1", ",", "pages", ".", "last", "]", ".", "min", "else", "lower", "=", "page", "+", "left_offset", "upper", "=", "page", "+", "right_offset", "end", "(", "lower", "..", "upper", ")", ".", "to_a", "end" ]
Provides dirt-simple logic for spitting out page numbers based on the current page. If we have 100 pages for example and we're at page 50, this would simply return [45, 46, 47, 48, 49, 50, 51, 52, 53, 54] When we're at page 1, it displays 1 to 10. You can pass in a number to limit the total displayed pages.
[ "Provides", "dirt", "-", "simple", "logic", "for", "spitting", "out", "page", "numbers", "based", "on", "the", "current", "page", "." ]
e4d8684676dab2d4d9755af334fd35958bbfc3c8
https://github.com/sinefunc/pagination/blob/e4d8684676dab2d4d9755af334fd35958bbfc3c8/lib/pagination/collection.rb#L56-L68
train
Vasfed/orangedata
lib/orange_data/transport.rb
OrangeData.Transport.ping
def ping res = transport.get(''){|r| r.headers['Accept'] = 'text/plain' } res.status == 200 && res.body == "Nebula.Api v2" rescue StandardError => _e return false end
ruby
def ping res = transport.get(''){|r| r.headers['Accept'] = 'text/plain' } res.status == 200 && res.body == "Nebula.Api v2" rescue StandardError => _e return false end
[ "def", "ping", "res", "=", "transport", ".", "get", "(", "''", ")", "{", "|", "r", "|", "r", ".", "headers", "[", "'Accept'", "]", "=", "'text/plain'", "}", "res", ".", "status", "==", "200", "&&", "res", ".", "body", "==", "\"Nebula.Api v2\"", "rescue", "StandardError", "=>", "_e", "return", "false", "end" ]
Below actual methods from api
[ "Below", "actual", "methods", "from", "api" ]
020c332b1d11855e6bd0e9ba3b40f42276d013b5
https://github.com/Vasfed/orangedata/blob/020c332b1d11855e6bd0e9ba3b40f42276d013b5/lib/orange_data/transport.rb#L157-L162
train
unipept/unipept-cli
lib/batch_order.rb
Unipept.BatchOrder.wait
def wait(i, &block) @order[i] = block return unless i == @current while order[@current] order.delete(@current).call @current += 1 end end
ruby
def wait(i, &block) @order[i] = block return unless i == @current while order[@current] order.delete(@current).call @current += 1 end end
[ "def", "wait", "(", "i", ",", "&", "block", ")", "@order", "[", "i", "]", "=", "block", "return", "unless", "i", "==", "@current", "while", "order", "[", "@current", "]", "order", ".", "delete", "(", "@current", ")", ".", "call", "@current", "+=", "1", "end", "end" ]
Executes block if it's its turn, queues the block in the other case.
[ "Executes", "block", "if", "it", "s", "its", "turn", "queues", "the", "block", "in", "the", "other", "case", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/batch_order.rb#L11-L19
train
restaurant-cheetah/take2
lib/take2.rb
Take2.InstanceMethods.call_api_with_retry
def call_api_with_retry(options = {}) config = self.class.retriable_configuration config.merge!(Take2.local_defaults(options)) unless options.empty? tries ||= config[:retries] begin yield rescue => e if config[:retriable].map { |klass| e.class <= klass }.any? unless tries.zero? || config[:retry_condition_proc]&.call(e) config[:retry_proc]&.call(e, tries) rest(config, tries) tries -= 1 retry end end raise e end end
ruby
def call_api_with_retry(options = {}) config = self.class.retriable_configuration config.merge!(Take2.local_defaults(options)) unless options.empty? tries ||= config[:retries] begin yield rescue => e if config[:retriable].map { |klass| e.class <= klass }.any? unless tries.zero? || config[:retry_condition_proc]&.call(e) config[:retry_proc]&.call(e, tries) rest(config, tries) tries -= 1 retry end end raise e end end
[ "def", "call_api_with_retry", "(", "options", "=", "{", "}", ")", "config", "=", "self", ".", "class", ".", "retriable_configuration", "config", ".", "merge!", "(", "Take2", ".", "local_defaults", "(", "options", ")", ")", "unless", "options", ".", "empty?", "tries", "||=", "config", "[", ":retries", "]", "begin", "yield", "rescue", "=>", "e", "if", "config", "[", ":retriable", "]", ".", "map", "{", "|", "klass", "|", "e", ".", "class", "<=", "klass", "}", ".", "any?", "unless", "tries", ".", "zero?", "||", "config", "[", ":retry_condition_proc", "]", "&.", "call", "(", "e", ")", "config", "[", ":retry_proc", "]", "&.", "call", "(", "e", ",", "tries", ")", "rest", "(", "config", ",", "tries", ")", "tries", "-=", "1", "retry", "end", "end", "raise", "e", "end", "end" ]
Yields a block and retries on retriable errors n times. The raised error could be the defined retriable or it child. Example: class PizzaService include Take2 number_of_retries 3 retriable_errors Net::HTTPRetriableError retriable_condition proc { |error| response_status(error.response) < 500 } on_retry proc { |error, tries| puts "#{self.name} - Retrying.. #{tries} of #{self.retriable_configuration[:retries]} (#{error})" } backoff_strategy type: :exponential, start: 3 def give_me_food call_api_with_retry do # Some logic that might raise.. # If it will raise retriable, magic happens. # If not the original error re raised end end end
[ "Yields", "a", "block", "and", "retries", "on", "retriable", "errors", "n", "times", ".", "The", "raised", "error", "could", "be", "the", "defined", "retriable", "or", "it", "child", "." ]
21bf2c67dd4aaca63e2c13733deef09cde195661
https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L59-L76
train
restaurant-cheetah/take2
lib/take2.rb
Take2.ClassMethods.number_of_retries
def number_of_retries(num) raise ArgumentError, 'Must be positive Integer' unless num.is_a?(Integer) && num.positive? self.retries = num end
ruby
def number_of_retries(num) raise ArgumentError, 'Must be positive Integer' unless num.is_a?(Integer) && num.positive? self.retries = num end
[ "def", "number_of_retries", "(", "num", ")", "raise", "ArgumentError", ",", "'Must be positive Integer'", "unless", "num", ".", "is_a?", "(", "Integer", ")", "&&", "num", ".", "positive?", "self", ".", "retries", "=", "num", "end" ]
Sets number of retries. Example: class PizzaService include Take2 number_of_retries 3 end Arguments: num: integer
[ "Sets", "number", "of", "retries", "." ]
21bf2c67dd4aaca63e2c13733deef09cde195661
https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L105-L108
train
restaurant-cheetah/take2
lib/take2.rb
Take2.ClassMethods.retriable_errors
def retriable_errors(*errors) message = 'All retriable errors must be StandardError decendants' raise ArgumentError, message unless errors.all? { |e| e <= StandardError } self.retriable = errors end
ruby
def retriable_errors(*errors) message = 'All retriable errors must be StandardError decendants' raise ArgumentError, message unless errors.all? { |e| e <= StandardError } self.retriable = errors end
[ "def", "retriable_errors", "(", "*", "errors", ")", "message", "=", "'All retriable errors must be StandardError decendants'", "raise", "ArgumentError", ",", "message", "unless", "errors", ".", "all?", "{", "|", "e", "|", "e", "<=", "StandardError", "}", "self", ".", "retriable", "=", "errors", "end" ]
Sets list of errors on which the block will retry. Example: class PizzaService include Take2 retriable_errors Net::HTTPRetriableError, Errno::ECONNRESET end Arguments: errors: List of retiable errors
[ "Sets", "list", "of", "errors", "on", "which", "the", "block", "will", "retry", "." ]
21bf2c67dd4aaca63e2c13733deef09cde195661
https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L119-L123
train
restaurant-cheetah/take2
lib/take2.rb
Take2.ClassMethods.backoff_strategy
def backoff_strategy(options) available_types = [:constant, :linear, :fibonacci, :exponential] raise ArgumentError, 'Incorrect backoff type' unless available_types.include?(options[:type]) self.backoff_intervals = Backoff.new(options[:type], options[:start]).intervals end
ruby
def backoff_strategy(options) available_types = [:constant, :linear, :fibonacci, :exponential] raise ArgumentError, 'Incorrect backoff type' unless available_types.include?(options[:type]) self.backoff_intervals = Backoff.new(options[:type], options[:start]).intervals end
[ "def", "backoff_strategy", "(", "options", ")", "available_types", "=", "[", ":constant", ",", ":linear", ",", ":fibonacci", ",", ":exponential", "]", "raise", "ArgumentError", ",", "'Incorrect backoff type'", "unless", "available_types", ".", "include?", "(", "options", "[", ":type", "]", ")", "self", ".", "backoff_intervals", "=", "Backoff", ".", "new", "(", "options", "[", ":type", "]", ",", "options", "[", ":start", "]", ")", ".", "intervals", "end" ]
Sets the backoff strategy Example: class PizzaService include Take2 backoff_strategy type: :exponential, start: 3 end Arguments: hash: object
[ "Sets", "the", "backoff", "strategy" ]
21bf2c67dd4aaca63e2c13733deef09cde195661
https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L172-L176
train
restaurant-cheetah/take2
lib/take2.rb
Take2.ClassMethods.retriable_configuration
def retriable_configuration Take2::Configuration::CONFIG_ATTRS.each_with_object({}) do |key, hash| hash[key] = send(key) end end
ruby
def retriable_configuration Take2::Configuration::CONFIG_ATTRS.each_with_object({}) do |key, hash| hash[key] = send(key) end end
[ "def", "retriable_configuration", "Take2", "::", "Configuration", "::", "CONFIG_ATTRS", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key", ",", "hash", "|", "hash", "[", "key", "]", "=", "send", "(", "key", ")", "end", "end" ]
Exposes current class configuration
[ "Exposes", "current", "class", "configuration" ]
21bf2c67dd4aaca63e2c13733deef09cde195661
https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L179-L183
train
quirkey/jim
lib/jim/installer.rb
Jim.Installer.install
def install fetch parse_package_json determine_name_and_version if !name || name.to_s =~ /^\s*$/ # blank raise(Jim::InstallError, "Could not determine name for #{@fetched_path}") end logger.info "Installing #{name} #{version}" logger.debug "fetched_path #{@fetched_path}" if options[:shallow] shallow_filename = [name, (version == "0" ? nil : version)].compact.join('-') final_path = install_path + "#{shallow_filename}#{fetched_path.extname}" else final_path = install_path + 'lib' + "#{name}-#{version}" + "#{name}.js" end if @fetched_path.directory? # install every js file installed_paths = [] sub_options = options.merge({ :name => nil, :version => nil, :parent_version => version, :package_json => package_json.merge("name" => nil) }) Jim.each_path_in_directories([@fetched_path], '.js', IGNORE_DIRS) do |subfile| logger.debug "Found file #{subfile}" installed_paths << Jim::Installer.new(subfile, install_path, sub_options).install end logger.debug "Extracted to #{install_path}, #{installed_paths.length} file(s)" return installed_paths end logger.debug "Installing to #{final_path}" if final_path.exist? logger.debug "#{final_path} already exists" if options[:force] FileUtils.rm_rf(final_path) elsif Digest::MD5.hexdigest(File.read(final_path)) == Digest::MD5.hexdigest(File.read(@fetched_path)) logger.warn "Duplicate file, skipping" return final_path else logger.error "Trying to install to #{final_path}, but file already exists and is different." return false end end Downlow.extract(@fetched_path, :destination => final_path, :tmp_dir => tmp_root) # install json install_package_json(final_path.dirname + 'package.json') if !options[:shallow] installed = final_path.directory? ? Dir.glob(final_path + '**/*').length : 1 logger.debug "Extracted to #{final_path}, #{installed} file(s)" final_path ensure FileUtils.rm_rf(@fetched_path) if @fetched_path && @fetched_path.exist? final_path end
ruby
def install fetch parse_package_json determine_name_and_version if !name || name.to_s =~ /^\s*$/ # blank raise(Jim::InstallError, "Could not determine name for #{@fetched_path}") end logger.info "Installing #{name} #{version}" logger.debug "fetched_path #{@fetched_path}" if options[:shallow] shallow_filename = [name, (version == "0" ? nil : version)].compact.join('-') final_path = install_path + "#{shallow_filename}#{fetched_path.extname}" else final_path = install_path + 'lib' + "#{name}-#{version}" + "#{name}.js" end if @fetched_path.directory? # install every js file installed_paths = [] sub_options = options.merge({ :name => nil, :version => nil, :parent_version => version, :package_json => package_json.merge("name" => nil) }) Jim.each_path_in_directories([@fetched_path], '.js', IGNORE_DIRS) do |subfile| logger.debug "Found file #{subfile}" installed_paths << Jim::Installer.new(subfile, install_path, sub_options).install end logger.debug "Extracted to #{install_path}, #{installed_paths.length} file(s)" return installed_paths end logger.debug "Installing to #{final_path}" if final_path.exist? logger.debug "#{final_path} already exists" if options[:force] FileUtils.rm_rf(final_path) elsif Digest::MD5.hexdigest(File.read(final_path)) == Digest::MD5.hexdigest(File.read(@fetched_path)) logger.warn "Duplicate file, skipping" return final_path else logger.error "Trying to install to #{final_path}, but file already exists and is different." return false end end Downlow.extract(@fetched_path, :destination => final_path, :tmp_dir => tmp_root) # install json install_package_json(final_path.dirname + 'package.json') if !options[:shallow] installed = final_path.directory? ? Dir.glob(final_path + '**/*').length : 1 logger.debug "Extracted to #{final_path}, #{installed} file(s)" final_path ensure FileUtils.rm_rf(@fetched_path) if @fetched_path && @fetched_path.exist? final_path end
[ "def", "install", "fetch", "parse_package_json", "determine_name_and_version", "if", "!", "name", "||", "name", ".", "to_s", "=~", "/", "\\s", "/", "raise", "(", "Jim", "::", "InstallError", ",", "\"Could not determine name for #{@fetched_path}\"", ")", "end", "logger", ".", "info", "\"Installing #{name} #{version}\"", "logger", ".", "debug", "\"fetched_path #{@fetched_path}\"", "if", "options", "[", ":shallow", "]", "shallow_filename", "=", "[", "name", ",", "(", "version", "==", "\"0\"", "?", "nil", ":", "version", ")", "]", ".", "compact", ".", "join", "(", "'-'", ")", "final_path", "=", "install_path", "+", "\"#{shallow_filename}#{fetched_path.extname}\"", "else", "final_path", "=", "install_path", "+", "'lib'", "+", "\"#{name}-#{version}\"", "+", "\"#{name}.js\"", "end", "if", "@fetched_path", ".", "directory?", "installed_paths", "=", "[", "]", "sub_options", "=", "options", ".", "merge", "(", "{", ":name", "=>", "nil", ",", ":version", "=>", "nil", ",", ":parent_version", "=>", "version", ",", ":package_json", "=>", "package_json", ".", "merge", "(", "\"name\"", "=>", "nil", ")", "}", ")", "Jim", ".", "each_path_in_directories", "(", "[", "@fetched_path", "]", ",", "'.js'", ",", "IGNORE_DIRS", ")", "do", "|", "subfile", "|", "logger", ".", "debug", "\"Found file #{subfile}\"", "installed_paths", "<<", "Jim", "::", "Installer", ".", "new", "(", "subfile", ",", "install_path", ",", "sub_options", ")", ".", "install", "end", "logger", ".", "debug", "\"Extracted to #{install_path}, #{installed_paths.length} file(s)\"", "return", "installed_paths", "end", "logger", ".", "debug", "\"Installing to #{final_path}\"", "if", "final_path", ".", "exist?", "logger", ".", "debug", "\"#{final_path} already exists\"", "if", "options", "[", ":force", "]", "FileUtils", ".", "rm_rf", "(", "final_path", ")", "elsif", "Digest", "::", "MD5", ".", "hexdigest", "(", "File", ".", "read", "(", "final_path", ")", ")", "==", "Digest", "::", "MD5", ".", "hexdigest", "(", "File", ".", "read", "(", "@fetched_path", ")", ")", "logger", ".", "warn", "\"Duplicate file, skipping\"", "return", "final_path", "else", "logger", ".", "error", "\"Trying to install to #{final_path}, but file already exists and is different.\"", "return", "false", "end", "end", "Downlow", ".", "extract", "(", "@fetched_path", ",", ":destination", "=>", "final_path", ",", ":tmp_dir", "=>", "tmp_root", ")", "install_package_json", "(", "final_path", ".", "dirname", "+", "'package.json'", ")", "if", "!", "options", "[", ":shallow", "]", "installed", "=", "final_path", ".", "directory?", "?", "Dir", ".", "glob", "(", "final_path", "+", "'**/*'", ")", ".", "length", ":", "1", "logger", ".", "debug", "\"Extracted to #{final_path}, #{installed} file(s)\"", "final_path", "ensure", "FileUtils", ".", "rm_rf", "(", "@fetched_path", ")", "if", "@fetched_path", "&&", "@fetched_path", ".", "exist?", "final_path", "end" ]
Fetch and install the files determining their name and version if not provided. If the fetch_path contains a directory of files, it iterates over the directory installing each file that isn't in IGNORE_DIRS and a name and version can be determined for. It also installs a package.json file along side the JS file that contains meta data including the name and version, also merging with the original package.json if found. If options[:shallow] == true it will just copy the single file without any leading directories or a package.json. 'shallow' installation is used for Bundle#vendor
[ "Fetch", "and", "install", "the", "files", "determining", "their", "name", "and", "version", "if", "not", "provided", ".", "If", "the", "fetch_path", "contains", "a", "directory", "of", "files", "it", "iterates", "over", "the", "directory", "installing", "each", "file", "that", "isn", "t", "in", "IGNORE_DIRS", "and", "a", "name", "and", "version", "can", "be", "determined", "for", ".", "It", "also", "installs", "a", "package", ".", "json", "file", "along", "side", "the", "JS", "file", "that", "contains", "meta", "data", "including", "the", "name", "and", "version", "also", "merging", "with", "the", "original", "package", ".", "json", "if", "found", "." ]
ad5dbf06527a1d0376055a02b58bb11b5a0ebc35
https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/installer.rb#L61-L120
train
couchrest/couchrest_extended_document
lib/couchrest/validation.rb
CouchRest.Validation.validate_casted_arrays
def validate_casted_arrays result = true array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) } array_casted_properties.each do |property| casted_values = self.send(property.name) next unless casted_values.is_a?(Array) && casted_values.first.respond_to?(:valid?) casted_values.each do |value| result = (result && value.valid?) if value.respond_to?(:valid?) end end result end
ruby
def validate_casted_arrays result = true array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) } array_casted_properties.each do |property| casted_values = self.send(property.name) next unless casted_values.is_a?(Array) && casted_values.first.respond_to?(:valid?) casted_values.each do |value| result = (result && value.valid?) if value.respond_to?(:valid?) end end result end
[ "def", "validate_casted_arrays", "result", "=", "true", "array_casted_properties", "=", "self", ".", "class", ".", "properties", ".", "select", "{", "|", "property", "|", "property", ".", "casted", "&&", "property", ".", "type", ".", "instance_of?", "(", "Array", ")", "}", "array_casted_properties", ".", "each", "do", "|", "property", "|", "casted_values", "=", "self", ".", "send", "(", "property", ".", "name", ")", "next", "unless", "casted_values", ".", "is_a?", "(", "Array", ")", "&&", "casted_values", ".", "first", ".", "respond_to?", "(", ":valid?", ")", "casted_values", ".", "each", "do", "|", "value", "|", "result", "=", "(", "result", "&&", "value", ".", "valid?", ")", "if", "value", ".", "respond_to?", "(", ":valid?", ")", "end", "end", "result", "end" ]
checking on casted objects
[ "checking", "on", "casted", "objects" ]
71511202ae10d3010dcf7b98fcba017cb37c76da
https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/validation.rb#L126-L137
train
couchrest/couchrest_extended_document
lib/couchrest/validation.rb
CouchRest.Validation.recursive_valid?
def recursive_valid?(target, context, state) valid = state target.each do |key, prop| if prop.is_a?(Array) prop.each do |item| if item.validatable? valid = recursive_valid?(item, context, valid) && valid end end elsif prop.validatable? valid = recursive_valid?(prop, context, valid) && valid end end target._run_validate_callbacks do target.class.validators.execute(context, target) && valid end end
ruby
def recursive_valid?(target, context, state) valid = state target.each do |key, prop| if prop.is_a?(Array) prop.each do |item| if item.validatable? valid = recursive_valid?(item, context, valid) && valid end end elsif prop.validatable? valid = recursive_valid?(prop, context, valid) && valid end end target._run_validate_callbacks do target.class.validators.execute(context, target) && valid end end
[ "def", "recursive_valid?", "(", "target", ",", "context", ",", "state", ")", "valid", "=", "state", "target", ".", "each", "do", "|", "key", ",", "prop", "|", "if", "prop", ".", "is_a?", "(", "Array", ")", "prop", ".", "each", "do", "|", "item", "|", "if", "item", ".", "validatable?", "valid", "=", "recursive_valid?", "(", "item", ",", "context", ",", "valid", ")", "&&", "valid", "end", "end", "elsif", "prop", ".", "validatable?", "valid", "=", "recursive_valid?", "(", "prop", ",", "context", ",", "valid", ")", "&&", "valid", "end", "end", "target", ".", "_run_validate_callbacks", "do", "target", ".", "class", ".", "validators", ".", "execute", "(", "context", ",", "target", ")", "&&", "valid", "end", "end" ]
Do recursive validity checking
[ "Do", "recursive", "validity", "checking" ]
71511202ae10d3010dcf7b98fcba017cb37c76da
https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/validation.rb#L141-L157
train
buren/honey_format
lib/honey_format/registry.rb
HoneyFormat.Registry.call
def call(value, type) return type.call(value) if type.respond_to?(:call) self[type].call(value) end
ruby
def call(value, type) return type.call(value) if type.respond_to?(:call) self[type].call(value) end
[ "def", "call", "(", "value", ",", "type", ")", "return", "type", ".", "call", "(", "value", ")", "if", "type", ".", "respond_to?", "(", ":call", ")", "self", "[", "type", "]", ".", "call", "(", "value", ")", "end" ]
Call value type @param [Symbol, String, #call] type the name of the type @param [Object] value to be converted
[ "Call", "value", "type" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/registry.rb#L43-L47
train
buren/honey_format
lib/honey_format/registry.rb
HoneyFormat.Registry.[]=
def []=(type, caller) type = to_key(type) if type?(type) raise(Errors::TypeExistsError, "type '#{type}' already exists") end @callers[type] = caller end
ruby
def []=(type, caller) type = to_key(type) if type?(type) raise(Errors::TypeExistsError, "type '#{type}' already exists") end @callers[type] = caller end
[ "def", "[]=", "(", "type", ",", "caller", ")", "type", "=", "to_key", "(", "type", ")", "if", "type?", "(", "type", ")", "raise", "(", "Errors", "::", "TypeExistsError", ",", "\"type '#{type}' already exists\"", ")", "end", "@callers", "[", "type", "]", "=", "caller", "end" ]
Register a caller @param [Symbol, String] type the name of the type @param [#call] caller that responds to #call @return [Object] returns the caller @raise [TypeExistsError] if type is already registered
[ "Register", "a", "caller" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/registry.rb#L54-L62
train
benmanns/cleverbot
lib/cleverbot/client.rb
Cleverbot.Client.write
def write message='' response = self.class.write message, @params message = response['message'] response.keep_if { |key, value| DEFAULT_PARAMS.keys.include? key } @params.merge! response @params.delete_if { |key, value| DEFAULT_PARAMS[key] == value } message end
ruby
def write message='' response = self.class.write message, @params message = response['message'] response.keep_if { |key, value| DEFAULT_PARAMS.keys.include? key } @params.merge! response @params.delete_if { |key, value| DEFAULT_PARAMS[key] == value } message end
[ "def", "write", "message", "=", "''", "response", "=", "self", ".", "class", ".", "write", "message", ",", "@params", "message", "=", "response", "[", "'message'", "]", "response", ".", "keep_if", "{", "|", "key", ",", "value", "|", "DEFAULT_PARAMS", ".", "keys", ".", "include?", "key", "}", "@params", ".", "merge!", "response", "@params", ".", "delete_if", "{", "|", "key", ",", "value", "|", "DEFAULT_PARAMS", "[", "key", "]", "==", "value", "}", "message", "end" ]
Initializes a Client with given parameters. ==== Parameters [<tt>params</tt>] Optional <tt>Hash</tt> holding the initial parameters. Defaults to <tt>{}</tt>. Sends a message and returns a <tt>String</tt> with the message received. Updates #params to maintain state. ==== Parameters [<tt>message</tt>] Optional <tt>String</tt> holding the message to be sent. Defaults to <tt>''</tt>.
[ "Initializes", "a", "Client", "with", "given", "parameters", "." ]
9040073227d3b2a68792838a1f036f76b739998b
https://github.com/benmanns/cleverbot/blob/9040073227d3b2a68792838a1f036f76b739998b/lib/cleverbot/client.rb#L74-L81
train
medcat/command-runner
lib/command/runner.rb
Command.Runner.pass!
def pass!(interops = {}, options = {}, &block) options[:unsafe] = @unsafe env = options.delete(:env) || {} backend.call(*contents(interops), env, options, &block) rescue Errno::ENOENT raise NoCommandError, @command end
ruby
def pass!(interops = {}, options = {}, &block) options[:unsafe] = @unsafe env = options.delete(:env) || {} backend.call(*contents(interops), env, options, &block) rescue Errno::ENOENT raise NoCommandError, @command end
[ "def", "pass!", "(", "interops", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "options", "[", ":unsafe", "]", "=", "@unsafe", "env", "=", "options", ".", "delete", "(", ":env", ")", "||", "{", "}", "backend", ".", "call", "(", "*", "contents", "(", "interops", ")", ",", "env", ",", "options", ",", "&", "block", ")", "rescue", "Errno", "::", "ENOENT", "raise", "NoCommandError", ",", "@command", "end" ]
Initialize the messenger. @param command [String] the name of the command file to run. @param arguments [String] the arguments to pass to the command. may contain interpolated values, like +{key}+ or +{{key}}+. @param options [Hash] the options for the messenger. Runs the command and arguments with the given interpolations; defaults to no interpolations. @note This method may not raise a {NoCommandError} and instead return a {Message} with the error code +127+, even if the command doesn't exist. @yield [Message] when the command finishes. @raise [NoCommandError] on no command. @param interops [Hash<Symbol, Object>] the interpolations to make. @param options [Hash<Symbol, Object>] the options for the backend. @return [Message, Object] message if no block was given, the return value of the block otherwise.
[ "Initialize", "the", "messenger", "." ]
a18f00ae4cf7633656e4715db73536ae8294ac51
https://github.com/medcat/command-runner/blob/a18f00ae4cf7633656e4715db73536ae8294ac51/lib/command/runner.rb#L103-L110
train
dwayne/xo
lib/xo/grid.rb
XO.Grid.each
def each (1..ROWS).each do |r| (1..COLS).each do |c| yield(r, c, self[r, c]) end end end
ruby
def each (1..ROWS).each do |r| (1..COLS).each do |c| yield(r, c, self[r, c]) end end end
[ "def", "each", "(", "1", "..", "ROWS", ")", ".", "each", "do", "|", "r", "|", "(", "1", "..", "COLS", ")", ".", "each", "do", "|", "c", "|", "yield", "(", "r", ",", "c", ",", "self", "[", "r", ",", "c", "]", ")", "end", "end", "end" ]
Iterates over all the positions of this grid from left to right and top to bottom. @example g = Grid.new g.each do |r, c, k| puts "(#{r}, #{c}) -> #{k}" end
[ "Iterates", "over", "all", "the", "positions", "of", "this", "grid", "from", "left", "to", "right", "and", "top", "to", "bottom", "." ]
bd6524cf8882585fd5cca940f1daa5fb5f75d2bb
https://github.com/dwayne/xo/blob/bd6524cf8882585fd5cca940f1daa5fb5f75d2bb/lib/xo/grid.rb#L86-L92
train
dwayne/xo
lib/xo/grid.rb
XO.Grid.each_open
def each_open self.each { |r, c, _| yield(r, c) if open?(r, c) } end
ruby
def each_open self.each { |r, c, _| yield(r, c) if open?(r, c) } end
[ "def", "each_open", "self", ".", "each", "{", "|", "r", ",", "c", ",", "_", "|", "yield", "(", "r", ",", "c", ")", "if", "open?", "(", "r", ",", "c", ")", "}", "end" ]
Iterates over all the open positions of this grid from left to right and top to bottom. @example g = Grid.new g[1, 1] = g[2, 1] = Grid::X g[2, 2] = g[3, 1] = Grid::O g.each_open do |r, c| puts "(#{r}, #{c}) is open" end
[ "Iterates", "over", "all", "the", "open", "positions", "of", "this", "grid", "from", "left", "to", "right", "and", "top", "to", "bottom", "." ]
bd6524cf8882585fd5cca940f1daa5fb5f75d2bb
https://github.com/dwayne/xo/blob/bd6524cf8882585fd5cca940f1daa5fb5f75d2bb/lib/xo/grid.rb#L105-L107
train
sauspiel/postamt
lib/postamt/connection_handler.rb
Postamt.ConnectionHandler.connected?
def connected?(klass) return false if Process.pid != @process_pid.get conn = self.retrieve_connection_pool(klass) conn && conn.connected? end
ruby
def connected?(klass) return false if Process.pid != @process_pid.get conn = self.retrieve_connection_pool(klass) conn && conn.connected? end
[ "def", "connected?", "(", "klass", ")", "return", "false", "if", "Process", ".", "pid", "!=", "@process_pid", ".", "get", "conn", "=", "self", ".", "retrieve_connection_pool", "(", "klass", ")", "conn", "&&", "conn", ".", "connected?", "end" ]
Returns true if a connection that's accessible to this class has already been opened.
[ "Returns", "true", "if", "a", "connection", "that", "s", "accessible", "to", "this", "class", "has", "already", "been", "opened", "." ]
bafbcbd6ab6ab00e45e4afab89f1ecadffe4341a
https://github.com/sauspiel/postamt/blob/bafbcbd6ab6ab00e45e4afab89f1ecadffe4341a/lib/postamt/connection_handler.rb#L57-L61
train
ftomassetti/codemodels
lib/codemodels/navigation.rb
CodeModels.NavigationExtensions.all_children
def all_children(flag=nil) also_foreign = (flag==:also_foreign) arr = [] ecore = self.class.ecore # Awful hack to forbid the same reference is visited twice when # two references with the same name are found already_used_references = [] ecore.eAllReferences.sort_by{|r| r.name}.select {|r| r.containment}.each do |ref| unless already_used_references.include?(ref.name) res = self.send(ref.name.to_sym) if ref.many d = arr.count res.each do |el| arr << el unless res==nil end elsif res!=nil d = arr.count arr << res end already_used_references << ref.name end end if also_foreign arr.concat(self.foreign_asts) end arr end
ruby
def all_children(flag=nil) also_foreign = (flag==:also_foreign) arr = [] ecore = self.class.ecore # Awful hack to forbid the same reference is visited twice when # two references with the same name are found already_used_references = [] ecore.eAllReferences.sort_by{|r| r.name}.select {|r| r.containment}.each do |ref| unless already_used_references.include?(ref.name) res = self.send(ref.name.to_sym) if ref.many d = arr.count res.each do |el| arr << el unless res==nil end elsif res!=nil d = arr.count arr << res end already_used_references << ref.name end end if also_foreign arr.concat(self.foreign_asts) end arr end
[ "def", "all_children", "(", "flag", "=", "nil", ")", "also_foreign", "=", "(", "flag", "==", ":also_foreign", ")", "arr", "=", "[", "]", "ecore", "=", "self", ".", "class", ".", "ecore", "already_used_references", "=", "[", "]", "ecore", ".", "eAllReferences", ".", "sort_by", "{", "|", "r", "|", "r", ".", "name", "}", ".", "select", "{", "|", "r", "|", "r", ".", "containment", "}", ".", "each", "do", "|", "ref", "|", "unless", "already_used_references", ".", "include?", "(", "ref", ".", "name", ")", "res", "=", "self", ".", "send", "(", "ref", ".", "name", ".", "to_sym", ")", "if", "ref", ".", "many", "d", "=", "arr", ".", "count", "res", ".", "each", "do", "|", "el", "|", "arr", "<<", "el", "unless", "res", "==", "nil", "end", "elsif", "res!", "=", "nil", "d", "=", "arr", ".", "count", "arr", "<<", "res", "end", "already_used_references", "<<", "ref", ".", "name", "end", "end", "if", "also_foreign", "arr", ".", "concat", "(", "self", ".", "foreign_asts", ")", "end", "arr", "end" ]
All direct children
[ "All", "direct", "children" ]
fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2
https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/navigation.rb#L9-L35
train
ftomassetti/codemodels
lib/codemodels/navigation.rb
CodeModels.NavigationExtensions.all_children_deep
def all_children_deep(flag=nil) arr = [] all_children(flag).each do |c| arr << c c.all_children_deep(flag).each do |cc| arr << cc end end arr end
ruby
def all_children_deep(flag=nil) arr = [] all_children(flag).each do |c| arr << c c.all_children_deep(flag).each do |cc| arr << cc end end arr end
[ "def", "all_children_deep", "(", "flag", "=", "nil", ")", "arr", "=", "[", "]", "all_children", "(", "flag", ")", ".", "each", "do", "|", "c", "|", "arr", "<<", "c", "c", ".", "all_children_deep", "(", "flag", ")", ".", "each", "do", "|", "cc", "|", "arr", "<<", "cc", "end", "end", "arr", "end" ]
All direct and indirect children
[ "All", "direct", "and", "indirect", "children" ]
fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2
https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/navigation.rb#L38-L47
train
ftomassetti/codemodels
lib/codemodels/navigation.rb
CodeModels.NavigationExtensions.traverse
def traverse(flag=nil,&op) op.call(self) all_children_deep(flag).each do |c| op.call(c) end end
ruby
def traverse(flag=nil,&op) op.call(self) all_children_deep(flag).each do |c| op.call(c) end end
[ "def", "traverse", "(", "flag", "=", "nil", ",", "&", "op", ")", "op", ".", "call", "(", "self", ")", "all_children_deep", "(", "flag", ")", ".", "each", "do", "|", "c", "|", "op", ".", "call", "(", "c", ")", "end", "end" ]
Execute an operation on the node itself and all children, direct and indirect.
[ "Execute", "an", "operation", "on", "the", "node", "itself", "and", "all", "children", "direct", "and", "indirect", "." ]
fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2
https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/navigation.rb#L51-L56
train
dropofwill/rtasklib
lib/rtasklib/execute.rb
Rtasklib.Execute.handle_response
def handle_response stdout, stderr, thread unless thread.value.success? dump = "#{thread.value} \n Stderr: #{stderr.read} \n Stdout: #{stdout.read} \n" raise dump end end
ruby
def handle_response stdout, stderr, thread unless thread.value.success? dump = "#{thread.value} \n Stderr: #{stderr.read} \n Stdout: #{stdout.read} \n" raise dump end end
[ "def", "handle_response", "stdout", ",", "stderr", ",", "thread", "unless", "thread", ".", "value", ".", "success?", "dump", "=", "\"#{thread.value} \\n Stderr: #{stderr.read} \\n Stdout: #{stdout.read} \\n\"", "raise", "dump", "end", "end" ]
Default error handling called in every popen3 call. Only executes if thread had a failing exit code @raise [RuntimeError] if failing exit code
[ "Default", "error", "handling", "called", "in", "every", "popen3", "call", ".", "Only", "executes", "if", "thread", "had", "a", "failing", "exit", "code" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/execute.rb#L91-L96
train
buren/honey_format
lib/honey_format/configuration.rb
HoneyFormat.Configuration.header_deduplicator=
def header_deduplicator=(strategy) if header_deduplicator_registry.type?(strategy) @header_deduplicator = header_deduplicator_registry[strategy] elsif strategy.respond_to?(:call) @header_deduplicator = strategy else message = "unknown deduplication strategy: '#{strategy}'" raise(Errors::UnknownDeduplicationStrategyError, message) end end
ruby
def header_deduplicator=(strategy) if header_deduplicator_registry.type?(strategy) @header_deduplicator = header_deduplicator_registry[strategy] elsif strategy.respond_to?(:call) @header_deduplicator = strategy else message = "unknown deduplication strategy: '#{strategy}'" raise(Errors::UnknownDeduplicationStrategyError, message) end end
[ "def", "header_deduplicator", "=", "(", "strategy", ")", "if", "header_deduplicator_registry", ".", "type?", "(", "strategy", ")", "@header_deduplicator", "=", "header_deduplicator_registry", "[", "strategy", "]", "elsif", "strategy", ".", "respond_to?", "(", ":call", ")", "@header_deduplicator", "=", "strategy", "else", "message", "=", "\"unknown deduplication strategy: '#{strategy}'\"", "raise", "(", "Errors", "::", "UnknownDeduplicationStrategyError", ",", "message", ")", "end", "end" ]
Set the deduplication header strategy @param [Symbol, #call] symbol with known strategy identifier or method that responds to #call(colums, key_count) @return [#call] the header deduplication strategy @raise [UnknownDeduplicationStrategyError]
[ "Set", "the", "deduplication", "header", "strategy" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/configuration.rb#L55-L64
train
buren/honey_format
lib/honey_format/configuration.rb
HoneyFormat.Configuration.default_header_deduplicators
def default_header_deduplicators @default_header_deduplicators ||= { deduplicate: proc do |columns| Helpers.key_count_to_deduplicated_array(columns) end, raise: proc do |columns| duplicates = Helpers.duplicated_items(columns) if duplicates.any? message = "all columns must be unique, duplicates are: #{duplicates}" raise(Errors::DuplicateHeaderColumnError, message) end columns end, none: proc { |columns| columns }, }.freeze end
ruby
def default_header_deduplicators @default_header_deduplicators ||= { deduplicate: proc do |columns| Helpers.key_count_to_deduplicated_array(columns) end, raise: proc do |columns| duplicates = Helpers.duplicated_items(columns) if duplicates.any? message = "all columns must be unique, duplicates are: #{duplicates}" raise(Errors::DuplicateHeaderColumnError, message) end columns end, none: proc { |columns| columns }, }.freeze end
[ "def", "default_header_deduplicators", "@default_header_deduplicators", "||=", "{", "deduplicate", ":", "proc", "do", "|", "columns", "|", "Helpers", ".", "key_count_to_deduplicated_array", "(", "columns", ")", "end", ",", "raise", ":", "proc", "do", "|", "columns", "|", "duplicates", "=", "Helpers", ".", "duplicated_items", "(", "columns", ")", "if", "duplicates", ".", "any?", "message", "=", "\"all columns must be unique, duplicates are: #{duplicates}\"", "raise", "(", "Errors", "::", "DuplicateHeaderColumnError", ",", "message", ")", "end", "columns", "end", ",", "none", ":", "proc", "{", "|", "columns", "|", "columns", "}", ",", "}", ".", "freeze", "end" ]
Default header deduplicate strategies @return [Hash] the default header deduplicatation strategies
[ "Default", "header", "deduplicate", "strategies" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/configuration.rb#L68-L83
train
buren/honey_format
lib/honey_format/configuration.rb
HoneyFormat.Configuration.default_converters
def default_converters @default_converters ||= { # strict variants decimal!: StrictConvertDecimal, integer!: StrictConvertInteger, date!: StrictConvertDate, datetime!: StrictConvertDatetime, symbol!: StrictConvertSymbol, downcase!: StrictConvertDowncase, upcase!: StrictConvertUpcase, boolean!: StrictConvertBoolean, # safe variants decimal: ConvertDecimal, decimal_or_zero: ConvertDecimalOrZero, integer: ConvertInteger, integer_or_zero: ConvertIntegerOrZero, date: ConvertDate, datetime: ConvertDatetime, symbol: ConvertSymbol, downcase: ConvertDowncase, upcase: ConvertUpcase, boolean: ConvertBoolean, md5: ConvertMD5, hex: ConvertHex, nil: ConvertNil, blank: ConvertBlank, header_column: ConvertHeaderColumn, method_name: ConvertHeaderColumn, }.freeze end
ruby
def default_converters @default_converters ||= { # strict variants decimal!: StrictConvertDecimal, integer!: StrictConvertInteger, date!: StrictConvertDate, datetime!: StrictConvertDatetime, symbol!: StrictConvertSymbol, downcase!: StrictConvertDowncase, upcase!: StrictConvertUpcase, boolean!: StrictConvertBoolean, # safe variants decimal: ConvertDecimal, decimal_or_zero: ConvertDecimalOrZero, integer: ConvertInteger, integer_or_zero: ConvertIntegerOrZero, date: ConvertDate, datetime: ConvertDatetime, symbol: ConvertSymbol, downcase: ConvertDowncase, upcase: ConvertUpcase, boolean: ConvertBoolean, md5: ConvertMD5, hex: ConvertHex, nil: ConvertNil, blank: ConvertBlank, header_column: ConvertHeaderColumn, method_name: ConvertHeaderColumn, }.freeze end
[ "def", "default_converters", "@default_converters", "||=", "{", "decimal!", ":", "StrictConvertDecimal", ",", "integer!", ":", "StrictConvertInteger", ",", "date!", ":", "StrictConvertDate", ",", "datetime!", ":", "StrictConvertDatetime", ",", "symbol!", ":", "StrictConvertSymbol", ",", "downcase!", ":", "StrictConvertDowncase", ",", "upcase!", ":", "StrictConvertUpcase", ",", "boolean!", ":", "StrictConvertBoolean", ",", "decimal", ":", "ConvertDecimal", ",", "decimal_or_zero", ":", "ConvertDecimalOrZero", ",", "integer", ":", "ConvertInteger", ",", "integer_or_zero", ":", "ConvertIntegerOrZero", ",", "date", ":", "ConvertDate", ",", "datetime", ":", "ConvertDatetime", ",", "symbol", ":", "ConvertSymbol", ",", "downcase", ":", "ConvertDowncase", ",", "upcase", ":", "ConvertUpcase", ",", "boolean", ":", "ConvertBoolean", ",", "md5", ":", "ConvertMD5", ",", "hex", ":", "ConvertHex", ",", "nil", ":", "ConvertNil", ",", "blank", ":", "ConvertBlank", ",", "header_column", ":", "ConvertHeaderColumn", ",", "method_name", ":", "ConvertHeaderColumn", ",", "}", ".", "freeze", "end" ]
Default converter registry @return [Hash] hash with default converters
[ "Default", "converter", "registry" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/configuration.rb#L99-L128
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.host
def host # find host in opts first host = options[:host] || @configuration['host'] host = 'http://api.unipept.ugent.be' if host.nil? || host.empty? # add http:// if needed if host.start_with?('http://', 'https://') host else "http://#{host}" end end
ruby
def host # find host in opts first host = options[:host] || @configuration['host'] host = 'http://api.unipept.ugent.be' if host.nil? || host.empty? # add http:// if needed if host.start_with?('http://', 'https://') host else "http://#{host}" end end
[ "def", "host", "host", "=", "options", "[", ":host", "]", "||", "@configuration", "[", "'host'", "]", "host", "=", "'http://api.unipept.ugent.be'", "if", "host", ".", "nil?", "||", "host", ".", "empty?", "if", "host", ".", "start_with?", "(", "'http://'", ",", "'https://'", ")", "host", "else", "\"http://#{host}\"", "end", "end" ]
Returns the host. If a value is defined by both an option and the config file, the value of the option is used.
[ "Returns", "the", "host", ".", "If", "a", "value", "is", "defined", "by", "both", "an", "option", "and", "the", "config", "file", "the", "value", "of", "the", "option", "is", "used", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L23-L34
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.input_iterator
def input_iterator return arguments.each unless arguments.empty? return IO.foreach(options[:input]) if options[:input] $stdin.each_line end
ruby
def input_iterator return arguments.each unless arguments.empty? return IO.foreach(options[:input]) if options[:input] $stdin.each_line end
[ "def", "input_iterator", "return", "arguments", ".", "each", "unless", "arguments", ".", "empty?", "return", "IO", ".", "foreach", "(", "options", "[", ":input", "]", ")", "if", "options", "[", ":input", "]", "$stdin", ".", "each_line", "end" ]
Returns an input iterator to use for the request. - if arguments are given, uses arguments - if the input file option is given, uses file input - if none of the previous are given, uses stdin
[ "Returns", "an", "input", "iterator", "to", "use", "for", "the", "request", ".", "-", "if", "arguments", "are", "given", "uses", "arguments", "-", "if", "the", "input", "file", "option", "is", "given", "uses", "file", "input", "-", "if", "none", "of", "the", "previous", "are", "given", "uses", "stdin" ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L40-L45
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.selected_fields
def selected_fields return @selected_fields unless @selected_fields.nil? fields = [*options[:select]].map { |f| f.split(',') }.flatten fields.concat(required_fields) if @fasta && !fields.empty? @selected_fields = fields.map { |f| glob_to_regex(f) } end
ruby
def selected_fields return @selected_fields unless @selected_fields.nil? fields = [*options[:select]].map { |f| f.split(',') }.flatten fields.concat(required_fields) if @fasta && !fields.empty? @selected_fields = fields.map { |f| glob_to_regex(f) } end
[ "def", "selected_fields", "return", "@selected_fields", "unless", "@selected_fields", ".", "nil?", "fields", "=", "[", "*", "options", "[", ":select", "]", "]", ".", "map", "{", "|", "f", "|", "f", ".", "split", "(", "','", ")", "}", ".", "flatten", "fields", ".", "concat", "(", "required_fields", ")", "if", "@fasta", "&&", "!", "fields", ".", "empty?", "@selected_fields", "=", "fields", ".", "map", "{", "|", "f", "|", "glob_to_regex", "(", "f", ")", "}", "end" ]
Returns an array of regular expressions containing all the selected fields
[ "Returns", "an", "array", "of", "regular", "expressions", "containing", "all", "the", "selected", "fields" ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L88-L94
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.run
def run ServerMessage.new(@host).print unless options[:quiet] hydra = Typhoeus::Hydra.new(max_concurrency: concurrent_requests) batch_order = Unipept::BatchOrder.new last_id = 0 batch_iterator.iterate(input_iterator) do |input_slice, batch_id, fasta_mapper| last_id = batch_id @fasta = !fasta_mapper.nil? request = ::RetryableTyphoeus::Request.new( @url, method: :post, body: construct_request_body(input_slice), accept_encoding: 'gzip', headers: { 'User-Agent' => @user_agent } ) request.on_complete do |resp| block = handle_response(resp, batch_id, fasta_mapper) batch_order.wait(batch_id, &block) end hydra.queue request hydra.run if (batch_id % queue_size).zero? end hydra.run batch_order.wait(last_id + 1) { output_writer.write_line formatter.footer } end
ruby
def run ServerMessage.new(@host).print unless options[:quiet] hydra = Typhoeus::Hydra.new(max_concurrency: concurrent_requests) batch_order = Unipept::BatchOrder.new last_id = 0 batch_iterator.iterate(input_iterator) do |input_slice, batch_id, fasta_mapper| last_id = batch_id @fasta = !fasta_mapper.nil? request = ::RetryableTyphoeus::Request.new( @url, method: :post, body: construct_request_body(input_slice), accept_encoding: 'gzip', headers: { 'User-Agent' => @user_agent } ) request.on_complete do |resp| block = handle_response(resp, batch_id, fasta_mapper) batch_order.wait(batch_id, &block) end hydra.queue request hydra.run if (batch_id % queue_size).zero? end hydra.run batch_order.wait(last_id + 1) { output_writer.write_line formatter.footer } end
[ "def", "run", "ServerMessage", ".", "new", "(", "@host", ")", ".", "print", "unless", "options", "[", ":quiet", "]", "hydra", "=", "Typhoeus", "::", "Hydra", ".", "new", "(", "max_concurrency", ":", "concurrent_requests", ")", "batch_order", "=", "Unipept", "::", "BatchOrder", ".", "new", "last_id", "=", "0", "batch_iterator", ".", "iterate", "(", "input_iterator", ")", "do", "|", "input_slice", ",", "batch_id", ",", "fasta_mapper", "|", "last_id", "=", "batch_id", "@fasta", "=", "!", "fasta_mapper", ".", "nil?", "request", "=", "::", "RetryableTyphoeus", "::", "Request", ".", "new", "(", "@url", ",", "method", ":", ":post", ",", "body", ":", "construct_request_body", "(", "input_slice", ")", ",", "accept_encoding", ":", "'gzip'", ",", "headers", ":", "{", "'User-Agent'", "=>", "@user_agent", "}", ")", "request", ".", "on_complete", "do", "|", "resp", "|", "block", "=", "handle_response", "(", "resp", ",", "batch_id", ",", "fasta_mapper", ")", "batch_order", ".", "wait", "(", "batch_id", ",", "&", "block", ")", "end", "hydra", ".", "queue", "request", "hydra", ".", "run", "if", "(", "batch_id", "%", "queue_size", ")", ".", "zero?", "end", "hydra", ".", "run", "batch_order", ".", "wait", "(", "last_id", "+", "1", ")", "{", "output_writer", ".", "write_line", "formatter", ".", "footer", "}", "end" ]
Runs the command
[ "Runs", "the", "command" ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L112-L140
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.save_error
def save_error(message) path = error_file_path FileUtils.mkdir_p File.dirname(path) File.open(path, 'w') { |f| f.write message } warn "API request failed! log can be found in #{path}" end
ruby
def save_error(message) path = error_file_path FileUtils.mkdir_p File.dirname(path) File.open(path, 'w') { |f| f.write message } warn "API request failed! log can be found in #{path}" end
[ "def", "save_error", "(", "message", ")", "path", "=", "error_file_path", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "path", ")", "File", ".", "open", "(", "path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "message", "}", "warn", "\"API request failed! log can be found in #{path}\"", "end" ]
Saves an error to a new file in the .unipept directory in the users home directory.
[ "Saves", "an", "error", "to", "a", "new", "file", "in", "the", ".", "unipept", "directory", "in", "the", "users", "home", "directory", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L144-L149
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.handle_response
def handle_response(response, batch_id, fasta_mapper) if response.success? handle_success_response(response, batch_id, fasta_mapper) else handle_failed_response(response) end end
ruby
def handle_response(response, batch_id, fasta_mapper) if response.success? handle_success_response(response, batch_id, fasta_mapper) else handle_failed_response(response) end end
[ "def", "handle_response", "(", "response", ",", "batch_id", ",", "fasta_mapper", ")", "if", "response", ".", "success?", "handle_success_response", "(", "response", ",", "batch_id", ",", "fasta_mapper", ")", "else", "handle_failed_response", "(", "response", ")", "end", "end" ]
Handles the response of an API request. Returns a block to execute.
[ "Handles", "the", "response", "of", "an", "API", "request", ".", "Returns", "a", "block", "to", "execute", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L159-L165
train
unipept/unipept-cli
lib/commands/unipept/api_runner.rb
Unipept.Commands::ApiRunner.filter_result
def filter_result(json_response) result = JSON[json_response] rescue [] result = [result] unless result.is_a? Array result.map! { |r| r.select! { |k, _v| selected_fields.any? { |f| f.match k } } } unless selected_fields.empty? result end
ruby
def filter_result(json_response) result = JSON[json_response] rescue [] result = [result] unless result.is_a? Array result.map! { |r| r.select! { |k, _v| selected_fields.any? { |f| f.match k } } } unless selected_fields.empty? result end
[ "def", "filter_result", "(", "json_response", ")", "result", "=", "JSON", "[", "json_response", "]", "rescue", "[", "]", "result", "=", "[", "result", "]", "unless", "result", ".", "is_a?", "Array", "result", ".", "map!", "{", "|", "r", "|", "r", ".", "select!", "{", "|", "k", ",", "_v", "|", "selected_fields", ".", "any?", "{", "|", "f", "|", "f", ".", "match", "k", "}", "}", "}", "unless", "selected_fields", ".", "empty?", "result", "end" ]
Parses the json_response, wraps it in an array if needed and filters the fields based on the selected_fields
[ "Parses", "the", "json_response", "wraps", "it", "in", "an", "array", "if", "needed", "and", "filters", "the", "fields", "based", "on", "the", "selected_fields" ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L190-L195
train
wingrunr21/gitolite
lib/gitolite/gitolite_admin.rb
Gitolite.GitoliteAdmin.save
def save Dir.chdir(@gl_admin.working_dir) do #Process config file (if loaded, i.e. may be modified) if @config new_conf = @config.to_file(@confdir) @gl_admin.add(new_conf) end #Process ssh keys (if loaded, i.e. may be modified) if @ssh_keys files = list_keys(@keydir).map{|f| File.basename f} keys = @ssh_keys.values.map{|f| f.map {|t| t.filename}}.flatten to_remove = (files - keys).map { |f| File.join(@keydir, f)} @gl_admin.remove(to_remove) @ssh_keys.each_value do |key| #Write only keys from sets that has been modified next if key.respond_to?(:dirty?) && !key.dirty? key.each do |k| @gl_admin.add(k.to_file(@keydir)) end end end end end
ruby
def save Dir.chdir(@gl_admin.working_dir) do #Process config file (if loaded, i.e. may be modified) if @config new_conf = @config.to_file(@confdir) @gl_admin.add(new_conf) end #Process ssh keys (if loaded, i.e. may be modified) if @ssh_keys files = list_keys(@keydir).map{|f| File.basename f} keys = @ssh_keys.values.map{|f| f.map {|t| t.filename}}.flatten to_remove = (files - keys).map { |f| File.join(@keydir, f)} @gl_admin.remove(to_remove) @ssh_keys.each_value do |key| #Write only keys from sets that has been modified next if key.respond_to?(:dirty?) && !key.dirty? key.each do |k| @gl_admin.add(k.to_file(@keydir)) end end end end end
[ "def", "save", "Dir", ".", "chdir", "(", "@gl_admin", ".", "working_dir", ")", "do", "if", "@config", "new_conf", "=", "@config", ".", "to_file", "(", "@confdir", ")", "@gl_admin", ".", "add", "(", "new_conf", ")", "end", "if", "@ssh_keys", "files", "=", "list_keys", "(", "@keydir", ")", ".", "map", "{", "|", "f", "|", "File", ".", "basename", "f", "}", "keys", "=", "@ssh_keys", ".", "values", ".", "map", "{", "|", "f", "|", "f", ".", "map", "{", "|", "t", "|", "t", ".", "filename", "}", "}", ".", "flatten", "to_remove", "=", "(", "files", "-", "keys", ")", ".", "map", "{", "|", "f", "|", "File", ".", "join", "(", "@keydir", ",", "f", ")", "}", "@gl_admin", ".", "remove", "(", "to_remove", ")", "@ssh_keys", ".", "each_value", "do", "|", "key", "|", "next", "if", "key", ".", "respond_to?", "(", ":dirty?", ")", "&&", "!", "key", ".", "dirty?", "key", ".", "each", "do", "|", "k", "|", "@gl_admin", ".", "add", "(", "k", ".", "to_file", "(", "@keydir", ")", ")", "end", "end", "end", "end", "end" ]
Writes all changed aspects out to the file system will also stage all changes
[ "Writes", "all", "changed", "aspects", "out", "to", "the", "file", "system", "will", "also", "stage", "all", "changes" ]
f86ec83e0885734000432b9502ccaa2dc26f4376
https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L65-L90
train
wingrunr21/gitolite
lib/gitolite/gitolite_admin.rb
Gitolite.GitoliteAdmin.reset!
def reset! Dir.chdir(@gl_admin.working_dir) do @gl_admin.git.reset({:hard => true}, 'HEAD') @gl_admin.git.clean({:d => true, :q => true, :f => true}) end reload! end
ruby
def reset! Dir.chdir(@gl_admin.working_dir) do @gl_admin.git.reset({:hard => true}, 'HEAD') @gl_admin.git.clean({:d => true, :q => true, :f => true}) end reload! end
[ "def", "reset!", "Dir", ".", "chdir", "(", "@gl_admin", ".", "working_dir", ")", "do", "@gl_admin", ".", "git", ".", "reset", "(", "{", ":hard", "=>", "true", "}", ",", "'HEAD'", ")", "@gl_admin", ".", "git", ".", "clean", "(", "{", ":d", "=>", "true", ",", ":q", "=>", "true", ",", ":f", "=>", "true", "}", ")", "end", "reload!", "end" ]
This method will destroy all local tracked changes, resetting the local gitolite git repo to HEAD and reloading the entire repository Note that this will also delete all untracked files
[ "This", "method", "will", "destroy", "all", "local", "tracked", "changes", "resetting", "the", "local", "gitolite", "git", "repo", "to", "HEAD", "and", "reloading", "the", "entire", "repository", "Note", "that", "this", "will", "also", "delete", "all", "untracked", "files" ]
f86ec83e0885734000432b9502ccaa2dc26f4376
https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L95-L101
train
wingrunr21/gitolite
lib/gitolite/gitolite_admin.rb
Gitolite.GitoliteAdmin.update
def update(options = {}) options = {:reset => true, :rebase => false }.merge(options) reset! if options[:reset] Dir.chdir(@gl_admin.working_dir) do @gl_admin.git.pull({:rebase => options[:rebase]}, "origin", "master") end reload! end
ruby
def update(options = {}) options = {:reset => true, :rebase => false }.merge(options) reset! if options[:reset] Dir.chdir(@gl_admin.working_dir) do @gl_admin.git.pull({:rebase => options[:rebase]}, "origin", "master") end reload! end
[ "def", "update", "(", "options", "=", "{", "}", ")", "options", "=", "{", ":reset", "=>", "true", ",", ":rebase", "=>", "false", "}", ".", "merge", "(", "options", ")", "reset!", "if", "options", "[", ":reset", "]", "Dir", ".", "chdir", "(", "@gl_admin", ".", "working_dir", ")", "do", "@gl_admin", ".", "git", ".", "pull", "(", "{", ":rebase", "=>", "options", "[", ":rebase", "]", "}", ",", "\"origin\"", ",", "\"master\"", ")", "end", "reload!", "end" ]
Updates the repo with changes from remote master
[ "Updates", "the", "repo", "with", "changes", "from", "remote", "master" ]
f86ec83e0885734000432b9502ccaa2dc26f4376
https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L127-L137
train
wingrunr21/gitolite
lib/gitolite/gitolite_admin.rb
Gitolite.GitoliteAdmin.load_keys
def load_keys(path = nil) path ||= File.join(@path, @keydir) keys = Hash.new {|k,v| k[v] = DirtyProxy.new([])} list_keys(path).each do |key| new_key = SSHKey.from_file(File.join(path, key)) owner = new_key.owner keys[owner] << new_key end #Mark key sets as unmodified (for dirty checking) keys.values.each{|set| set.clean_up!} keys end
ruby
def load_keys(path = nil) path ||= File.join(@path, @keydir) keys = Hash.new {|k,v| k[v] = DirtyProxy.new([])} list_keys(path).each do |key| new_key = SSHKey.from_file(File.join(path, key)) owner = new_key.owner keys[owner] << new_key end #Mark key sets as unmodified (for dirty checking) keys.values.each{|set| set.clean_up!} keys end
[ "def", "load_keys", "(", "path", "=", "nil", ")", "path", "||=", "File", ".", "join", "(", "@path", ",", "@keydir", ")", "keys", "=", "Hash", ".", "new", "{", "|", "k", ",", "v", "|", "k", "[", "v", "]", "=", "DirtyProxy", ".", "new", "(", "[", "]", ")", "}", "list_keys", "(", "path", ")", ".", "each", "do", "|", "key", "|", "new_key", "=", "SSHKey", ".", "from_file", "(", "File", ".", "join", "(", "path", ",", "key", ")", ")", "owner", "=", "new_key", ".", "owner", "keys", "[", "owner", "]", "<<", "new_key", "end", "keys", ".", "values", ".", "each", "{", "|", "set", "|", "set", ".", "clean_up!", "}", "keys", "end" ]
Loads all .pub files in the gitolite-admin keydir directory
[ "Loads", "all", ".", "pub", "files", "in", "the", "gitolite", "-", "admin", "keydir", "directory" ]
f86ec83e0885734000432b9502ccaa2dc26f4376
https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L178-L192
train
dailycred/dailycred
lib/dailycred/client.rb
Dailycred.Client.event
def event(user_id, key, val="") opts = { :key => key, :valuestring => val, :user_id => user_id } post "/admin/api/customevent.json", opts end
ruby
def event(user_id, key, val="") opts = { :key => key, :valuestring => val, :user_id => user_id } post "/admin/api/customevent.json", opts end
[ "def", "event", "(", "user_id", ",", "key", ",", "val", "=", "\"\"", ")", "opts", "=", "{", ":key", "=>", "key", ",", ":valuestring", "=>", "val", ",", ":user_id", "=>", "user_id", "}", "post", "\"/admin/api/customevent.json\"", ",", "opts", "end" ]
Initializes a dailycred object - @param [String] client\_id the client's daiycred client id - @param [String] secret\_key the clients secret key - @param [Hash] opts a hash of options Generates a Dailycred event - @param [String] user_id the user's dailycred user id - @param [String] key the name of the event type - @param [String] val the value of the event (optional)
[ "Initializes", "a", "dailycred", "object" ]
e4c504e26b2f56de819b5828bb5ca93d1f583e0d
https://github.com/dailycred/dailycred/blob/e4c504e26b2f56de819b5828bb5ca93d1f583e0d/lib/dailycred/client.rb#L31-L38
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/adapter.rb
Mongoid::Globalize.Adapter.prepare_translations!
def prepare_translations! stash.each do |locale, attrs| if attrs.any? translation = record.translations.find_by_locale(locale) translation ||= record.translations.build(:locale => locale) attrs.each{ |name, value| translation[name] = value } end end reset end
ruby
def prepare_translations! stash.each do |locale, attrs| if attrs.any? translation = record.translations.find_by_locale(locale) translation ||= record.translations.build(:locale => locale) attrs.each{ |name, value| translation[name] = value } end end reset end
[ "def", "prepare_translations!", "stash", ".", "each", "do", "|", "locale", ",", "attrs", "|", "if", "attrs", ".", "any?", "translation", "=", "record", ".", "translations", ".", "find_by_locale", "(", "locale", ")", "translation", "||=", "record", ".", "translations", ".", "build", "(", ":locale", "=>", "locale", ")", "attrs", ".", "each", "{", "|", "name", ",", "value", "|", "translation", "[", "name", "]", "=", "value", "}", "end", "end", "reset", "end" ]
Prepares data from stash for persisting in embeded Translation documents. Also clears stash for further operations.
[ "Prepares", "data", "from", "stash", "for", "persisting", "in", "embeded", "Translation", "documents", ".", "Also", "clears", "stash", "for", "further", "operations", "." ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/adapter.rb#L48-L57
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/adapter.rb
Mongoid::Globalize.Adapter.fetch_attribute
def fetch_attribute(locale, name) translation = record.translation_for(locale) return translation && translation.send(name) end
ruby
def fetch_attribute(locale, name) translation = record.translation_for(locale) return translation && translation.send(name) end
[ "def", "fetch_attribute", "(", "locale", ",", "name", ")", "translation", "=", "record", ".", "translation_for", "(", "locale", ")", "return", "translation", "&&", "translation", ".", "send", "(", "name", ")", "end" ]
Returns persisted value of attribute for given locale or nil.
[ "Returns", "persisted", "value", "of", "attribute", "for", "given", "locale", "or", "nil", "." ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/adapter.rb#L66-L69
train
blinkist/grantinee
lib/grantinee/configuration.rb
Grantinee.Configuration.url=
def url=(url) uri = URI.parse url case uri.scheme when /^mysql/ default_port = 3306 @engine = :mysql when /^postgres/ default_port = 5432 @engine = :postgres end raise 'Invalid database url' unless uri.user && uri.host && uri.path @username = uri.user @password = uri.password @hostname = uri.host @port = uri.port || default_port @database = (uri.path || '').split('/').last end
ruby
def url=(url) uri = URI.parse url case uri.scheme when /^mysql/ default_port = 3306 @engine = :mysql when /^postgres/ default_port = 5432 @engine = :postgres end raise 'Invalid database url' unless uri.user && uri.host && uri.path @username = uri.user @password = uri.password @hostname = uri.host @port = uri.port || default_port @database = (uri.path || '').split('/').last end
[ "def", "url", "=", "(", "url", ")", "uri", "=", "URI", ".", "parse", "url", "case", "uri", ".", "scheme", "when", "/", "/", "default_port", "=", "3306", "@engine", "=", ":mysql", "when", "/", "/", "default_port", "=", "5432", "@engine", "=", ":postgres", "end", "raise", "'Invalid database url'", "unless", "uri", ".", "user", "&&", "uri", ".", "host", "&&", "uri", ".", "path", "@username", "=", "uri", ".", "user", "@password", "=", "uri", ".", "password", "@hostname", "=", "uri", ".", "host", "@port", "=", "uri", ".", "port", "||", "default_port", "@database", "=", "(", "uri", ".", "path", "||", "''", ")", ".", "split", "(", "'/'", ")", ".", "last", "end" ]
Handle url -> fields conversion
[ "Handle", "url", "-", ">", "fields", "conversion" ]
ba0c9a8ccaf377c2484c814d39359f01f7e56ded
https://github.com/blinkist/grantinee/blob/ba0c9a8ccaf377c2484c814d39359f01f7e56ded/lib/grantinee/configuration.rb#L32-L51
train
quirkey/jim
lib/jim/bundler.rb
Jim.Bundler.bundle_dir=
def bundle_dir=(new_dir) if new_dir new_dir = Pathname.new(new_dir) new_dir.mkpath end @bundle_dir = new_dir end
ruby
def bundle_dir=(new_dir) if new_dir new_dir = Pathname.new(new_dir) new_dir.mkpath end @bundle_dir = new_dir end
[ "def", "bundle_dir", "=", "(", "new_dir", ")", "if", "new_dir", "new_dir", "=", "Pathname", ".", "new", "(", "new_dir", ")", "new_dir", ".", "mkpath", "end", "@bundle_dir", "=", "new_dir", "end" ]
Set the `bundle_dir` where bundles will be written. If `bundle_dir` is set to nil, all bundles will be written to STDOUT
[ "Set", "the", "bundle_dir", "where", "bundles", "will", "be", "written", ".", "If", "bundle_dir", "is", "set", "to", "nil", "all", "bundles", "will", "be", "written", "to", "STDOUT" ]
ad5dbf06527a1d0376055a02b58bb11b5a0ebc35
https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/bundler.rb#L70-L76
train
quirkey/jim
lib/jim/bundler.rb
Jim.Bundler.jimfile_to_json
def jimfile_to_json h = { "bundle_dir" => bundle_dir }.merge(options) h['bundles'] = {} self.bundles.each do |bundle_name, requirements| h['bundles'][bundle_name] = [] requirements.each do |name, version| h['bundles'][bundle_name] << if version.nil? || version.strip == '' name else [name, version] end end end Yajl::Encoder.encode(h, :pretty => true) end
ruby
def jimfile_to_json h = { "bundle_dir" => bundle_dir }.merge(options) h['bundles'] = {} self.bundles.each do |bundle_name, requirements| h['bundles'][bundle_name] = [] requirements.each do |name, version| h['bundles'][bundle_name] << if version.nil? || version.strip == '' name else [name, version] end end end Yajl::Encoder.encode(h, :pretty => true) end
[ "def", "jimfile_to_json", "h", "=", "{", "\"bundle_dir\"", "=>", "bundle_dir", "}", ".", "merge", "(", "options", ")", "h", "[", "'bundles'", "]", "=", "{", "}", "self", ".", "bundles", ".", "each", "do", "|", "bundle_name", ",", "requirements", "|", "h", "[", "'bundles'", "]", "[", "bundle_name", "]", "=", "[", "]", "requirements", ".", "each", "do", "|", "name", ",", "version", "|", "h", "[", "'bundles'", "]", "[", "bundle_name", "]", "<<", "if", "version", ".", "nil?", "||", "version", ".", "strip", "==", "''", "name", "else", "[", "name", ",", "version", "]", "end", "end", "end", "Yajl", "::", "Encoder", ".", "encode", "(", "h", ",", ":pretty", "=>", "true", ")", "end" ]
Output the parse Jimfile requirements and options as a Jimfile-ready JSON-encoded string
[ "Output", "the", "parse", "Jimfile", "requirements", "and", "options", "as", "a", "Jimfile", "-", "ready", "JSON", "-", "encoded", "string" ]
ad5dbf06527a1d0376055a02b58bb11b5a0ebc35
https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/bundler.rb#L80-L96
train