id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
3,400
glejeune/soap-lc
lib/soap/lc/request.rb
SOAP.Request.call
def call( methodName, args ) args = (args || {}) #.keys_to_sym! # Get Binding binding = @wsdl.bindings.getBindingForOperationName( @binding, methodName ) if binding.size == 0 raise SOAP::LCNoMethodError, "Undefined method `#{methodName}'" elsif binding.size > 1 raise SOAP::LCError, "Ambigous method name `#{methodName}', please, specify a binding name" else binding = binding[0] @binding = binding.name end # Get Binding Operation binding_operation = binding.operations[methodName] # Get PortType portType = @wsdl.portTypes[binding.type.nns] portType_operation = portType.operations[methodName] # Get message for input operation input_message = @wsdl.messages[portType_operation[:input][:message].nns] # Create method soap_method = "<#{methodName} xmlns=\"#{@wsdl.targetNamespace}\">\n" input_message.parts.each do |_, attrs| case attrs[:mode] when :type if SOAP::XSD::ANY_SIMPLE_TYPE.include?( attrs[attrs[:mode]].nns ) # Part refer to a builtin SimpleType soap_method << SOAP::XSD.displayBuiltinType( attrs[:name], args, 1, 1 ) else # Part refer to an XSD simpleType or complexType defined in types element = @wsdl.types[attrs[attrs[:mode]].nns][:value] case element[:type] when :simpleType soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ########## when :complexType soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ########## else raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}" end end when :element # Part refer to an XSD element element = @wsdl.types[attrs[attrs[:mode]].nns][:value] case element[:type] when :simpleType soap_method << element[element[:type]].display( @wsdl.types, args ) when :complexType soap_method << element[element[:type]].display( @wsdl.types, args ) else raise SOAL::LCWSDLError, "Malformated element `#{attrs[attrs[:mode]]}'" end ## TODO ---------- USE element[:key] else raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}" end end soap_method += "</#{methodName}>\n" # Create SOAP Envelope envelope = soap_envelop do soap_header + soap_body( soap_method ) end # Create headers headers = Hash.new # Add SOAPAction to headers (if exist) action = begin binding_operation[:soapAction] rescue nil end headers['SOAPAction'] = action unless action.nil? or action.length == 0 # Search URI service_port = @wsdl.services.getServicePortForBindingName( binding.name ) address = service_port[:address] # Complete request @request = { :headers => make_header( envelope, headers ), :envelope => envelope, :uri => address, :wsdl => @wsdl, :response => @wsdl.messages[portType_operation[:output][:message].nns].name, :binding => @binding, :method => methodName } return self end
ruby
def call( methodName, args ) args = (args || {}) #.keys_to_sym! # Get Binding binding = @wsdl.bindings.getBindingForOperationName( @binding, methodName ) if binding.size == 0 raise SOAP::LCNoMethodError, "Undefined method `#{methodName}'" elsif binding.size > 1 raise SOAP::LCError, "Ambigous method name `#{methodName}', please, specify a binding name" else binding = binding[0] @binding = binding.name end # Get Binding Operation binding_operation = binding.operations[methodName] # Get PortType portType = @wsdl.portTypes[binding.type.nns] portType_operation = portType.operations[methodName] # Get message for input operation input_message = @wsdl.messages[portType_operation[:input][:message].nns] # Create method soap_method = "<#{methodName} xmlns=\"#{@wsdl.targetNamespace}\">\n" input_message.parts.each do |_, attrs| case attrs[:mode] when :type if SOAP::XSD::ANY_SIMPLE_TYPE.include?( attrs[attrs[:mode]].nns ) # Part refer to a builtin SimpleType soap_method << SOAP::XSD.displayBuiltinType( attrs[:name], args, 1, 1 ) else # Part refer to an XSD simpleType or complexType defined in types element = @wsdl.types[attrs[attrs[:mode]].nns][:value] case element[:type] when :simpleType soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ########## when :complexType soap_method << "<#{attrs[:name]}>\n#{element.display( @wsdl.types, args )}\n</#{attrs[:name]}>\n" # MAYBE ########## else raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}" end end when :element # Part refer to an XSD element element = @wsdl.types[attrs[attrs[:mode]].nns][:value] case element[:type] when :simpleType soap_method << element[element[:type]].display( @wsdl.types, args ) when :complexType soap_method << element[element[:type]].display( @wsdl.types, args ) else raise SOAL::LCWSDLError, "Malformated element `#{attrs[attrs[:mode]]}'" end ## TODO ---------- USE element[:key] else raise SOAP::LCWSDLError, "Malformated part #{attrs[:name]}" end end soap_method += "</#{methodName}>\n" # Create SOAP Envelope envelope = soap_envelop do soap_header + soap_body( soap_method ) end # Create headers headers = Hash.new # Add SOAPAction to headers (if exist) action = begin binding_operation[:soapAction] rescue nil end headers['SOAPAction'] = action unless action.nil? or action.length == 0 # Search URI service_port = @wsdl.services.getServicePortForBindingName( binding.name ) address = service_port[:address] # Complete request @request = { :headers => make_header( envelope, headers ), :envelope => envelope, :uri => address, :wsdl => @wsdl, :response => @wsdl.messages[portType_operation[:output][:message].nns].name, :binding => @binding, :method => methodName } return self end
[ "def", "call", "(", "methodName", ",", "args", ")", "args", "=", "(", "args", "||", "{", "}", ")", "#.keys_to_sym!", "# Get Binding", "binding", "=", "@wsdl", ".", "bindings", ".", "getBindingForOperationName", "(", "@binding", ",", "methodName", ")", "if", "binding", ".", "size", "==", "0", "raise", "SOAP", "::", "LCNoMethodError", ",", "\"Undefined method `#{methodName}'\"", "elsif", "binding", ".", "size", ">", "1", "raise", "SOAP", "::", "LCError", ",", "\"Ambigous method name `#{methodName}', please, specify a binding name\"", "else", "binding", "=", "binding", "[", "0", "]", "@binding", "=", "binding", ".", "name", "end", "# Get Binding Operation", "binding_operation", "=", "binding", ".", "operations", "[", "methodName", "]", "# Get PortType", "portType", "=", "@wsdl", ".", "portTypes", "[", "binding", ".", "type", ".", "nns", "]", "portType_operation", "=", "portType", ".", "operations", "[", "methodName", "]", "# Get message for input operation", "input_message", "=", "@wsdl", ".", "messages", "[", "portType_operation", "[", ":input", "]", "[", ":message", "]", ".", "nns", "]", "# Create method", "soap_method", "=", "\"<#{methodName} xmlns=\\\"#{@wsdl.targetNamespace}\\\">\\n\"", "input_message", ".", "parts", ".", "each", "do", "|", "_", ",", "attrs", "|", "case", "attrs", "[", ":mode", "]", "when", ":type", "if", "SOAP", "::", "XSD", "::", "ANY_SIMPLE_TYPE", ".", "include?", "(", "attrs", "[", "attrs", "[", ":mode", "]", "]", ".", "nns", ")", "# Part refer to a builtin SimpleType", "soap_method", "<<", "SOAP", "::", "XSD", ".", "displayBuiltinType", "(", "attrs", "[", ":name", "]", ",", "args", ",", "1", ",", "1", ")", "else", "# Part refer to an XSD simpleType or complexType defined in types", "element", "=", "@wsdl", ".", "types", "[", "attrs", "[", "attrs", "[", ":mode", "]", "]", ".", "nns", "]", "[", ":value", "]", "case", "element", "[", ":type", "]", "when", ":simpleType", "soap_method", "<<", "\"<#{attrs[:name]}>\\n#{element.display( @wsdl.types, args )}\\n</#{attrs[:name]}>\\n\"", "# MAYBE ########## ", "when", ":complexType", "soap_method", "<<", "\"<#{attrs[:name]}>\\n#{element.display( @wsdl.types, args )}\\n</#{attrs[:name]}>\\n\"", "# MAYBE ########## ", "else", "raise", "SOAP", "::", "LCWSDLError", ",", "\"Malformated part #{attrs[:name]}\"", "end", "end", "when", ":element", "# Part refer to an XSD element", "element", "=", "@wsdl", ".", "types", "[", "attrs", "[", "attrs", "[", ":mode", "]", "]", ".", "nns", "]", "[", ":value", "]", "case", "element", "[", ":type", "]", "when", ":simpleType", "soap_method", "<<", "element", "[", "element", "[", ":type", "]", "]", ".", "display", "(", "@wsdl", ".", "types", ",", "args", ")", "when", ":complexType", "soap_method", "<<", "element", "[", "element", "[", ":type", "]", "]", ".", "display", "(", "@wsdl", ".", "types", ",", "args", ")", "else", "raise", "SOAL", "::", "LCWSDLError", ",", "\"Malformated element `#{attrs[attrs[:mode]]}'\"", "end", "## TODO ---------- USE element[:key]", "else", "raise", "SOAP", "::", "LCWSDLError", ",", "\"Malformated part #{attrs[:name]}\"", "end", "end", "soap_method", "+=", "\"</#{methodName}>\\n\"", "# Create SOAP Envelope", "envelope", "=", "soap_envelop", "do", "soap_header", "+", "soap_body", "(", "soap_method", ")", "end", "# Create headers", "headers", "=", "Hash", ".", "new", "# Add SOAPAction to headers (if exist)", "action", "=", "begin", "binding_operation", "[", ":soapAction", "]", "rescue", "nil", "end", "headers", "[", "'SOAPAction'", "]", "=", "action", "unless", "action", ".", "nil?", "or", "action", ".", "length", "==", "0", "# Search URI", "service_port", "=", "@wsdl", ".", "services", ".", "getServicePortForBindingName", "(", "binding", ".", "name", ")", "address", "=", "service_port", "[", ":address", "]", "# Complete request", "@request", "=", "{", ":headers", "=>", "make_header", "(", "envelope", ",", "headers", ")", ",", ":envelope", "=>", "envelope", ",", ":uri", "=>", "address", ",", ":wsdl", "=>", "@wsdl", ",", ":response", "=>", "@wsdl", ".", "messages", "[", "portType_operation", "[", ":output", "]", "[", ":message", "]", ".", "nns", "]", ".", "name", ",", ":binding", "=>", "@binding", ",", ":method", "=>", "methodName", "}", "return", "self", "end" ]
Call a method for the current Request Example: wsdl = SOAP::LC.new( ).wsdl( "http://..." ) request = wsdl.request( ) response = request.call( "myMethod", :param1 => "hello" ) # => #<SOAP::Response:0xNNNNNN>
[ "Call", "a", "method", "for", "the", "current", "Request" ]
dfb5b56494289f40dc92cff737b37ee2f418ae2b
https://github.com/glejeune/soap-lc/blob/dfb5b56494289f40dc92cff737b37ee2f418ae2b/lib/soap/lc/request.rb#L75-L169
3,401
IUBLibTech/ldap_groups_lookup
lib/ldap_groups_lookup/search.rb
LDAPGroupsLookup.Search.lookup_dn
def lookup_dn(cn) service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn end
ruby
def lookup_dn(cn) service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'dn').first&.dn end
[ "def", "lookup_dn", "(", "cn", ")", "service", ".", "search", "(", "base", ":", "tree", ",", "filter", ":", "Net", "::", "LDAP", "::", "Filter", ".", "equals", "(", "'cn'", ",", "cn", ")", ",", "attributes", ":", "'dn'", ")", ".", "first", "&.", "dn", "end" ]
Returns the DN for the given CN attribute
[ "Returns", "the", "DN", "for", "the", "given", "CN", "attribute" ]
430ff8e1dd084fdc7113fbfe85b6422900b39184
https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L32-L34
3,402
IUBLibTech/ldap_groups_lookup
lib/ldap_groups_lookup/search.rb
LDAPGroupsLookup.Search.lookup_mail
def lookup_mail(cn) service&.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'mail')&.first&.mail&.first.to_s end
ruby
def lookup_mail(cn) service&.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: 'mail')&.first&.mail&.first.to_s end
[ "def", "lookup_mail", "(", "cn", ")", "service", "&.", "search", "(", "base", ":", "tree", ",", "filter", ":", "Net", "::", "LDAP", "::", "Filter", ".", "equals", "(", "'cn'", ",", "cn", ")", ",", "attributes", ":", "'mail'", ")", "&.", "first", "&.", "mail", "&.", "first", ".", "to_s", "end" ]
Returns the mail for a given CN attribute
[ "Returns", "the", "mail", "for", "a", "given", "CN", "attribute" ]
430ff8e1dd084fdc7113fbfe85b6422900b39184
https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L37-L41
3,403
IUBLibTech/ldap_groups_lookup
lib/ldap_groups_lookup/search.rb
LDAPGroupsLookup.Search.walk_ldap_members
def walk_ldap_members(groups, dn, seen = []) groups.each do |g| members = ldap_members(g) return true if members.include? dn next if seen.include? g seen << g member_groups = members.collect do |mg| dn_to_cn(mg) if (mg.include?('OU=Groups') || mg.include?('OU=Applications')) end member_groups.compact! return true if walk_ldap_members(member_groups, dn, seen) end return false end
ruby
def walk_ldap_members(groups, dn, seen = []) groups.each do |g| members = ldap_members(g) return true if members.include? dn next if seen.include? g seen << g member_groups = members.collect do |mg| dn_to_cn(mg) if (mg.include?('OU=Groups') || mg.include?('OU=Applications')) end member_groups.compact! return true if walk_ldap_members(member_groups, dn, seen) end return false end
[ "def", "walk_ldap_members", "(", "groups", ",", "dn", ",", "seen", "=", "[", "]", ")", "groups", ".", "each", "do", "|", "g", "|", "members", "=", "ldap_members", "(", "g", ")", "return", "true", "if", "members", ".", "include?", "dn", "next", "if", "seen", ".", "include?", "g", "seen", "<<", "g", "member_groups", "=", "members", ".", "collect", "do", "|", "mg", "|", "dn_to_cn", "(", "mg", ")", "if", "(", "mg", ".", "include?", "(", "'OU=Groups'", ")", "||", "mg", ".", "include?", "(", "'OU=Applications'", ")", ")", "end", "member_groups", ".", "compact!", "return", "true", "if", "walk_ldap_members", "(", "member_groups", ",", "dn", ",", "seen", ")", "end", "return", "false", "end" ]
Searches a group and its nested member groups for a member DN @param [Array] groups CNs to search @param [String] dn the DN to search for @param [Array] seen groups that have already been traversed @return [Boolean] true if dn was seen in groups
[ "Searches", "a", "group", "and", "its", "nested", "member", "groups", "for", "a", "member", "DN" ]
430ff8e1dd084fdc7113fbfe85b6422900b39184
https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L53-L66
3,404
IUBLibTech/ldap_groups_lookup
lib/ldap_groups_lookup/search.rb
LDAPGroupsLookup.Search.ldap_members
def ldap_members(cn, start=0) return [] if service.nil? # print "Getting members of #{cn} at index #{start}\n" entry = service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: ["member;range=#{start}-*"]).first return [] if entry.nil? field_name = entry.attribute_names[1] # Is this always ordered [dn, member]? return [] if field_name.nil? # Sometimes member is not present. range_end = field_name.to_s.match(/^member;range=\d+-([0-9*]+)$/)[1] # print "#{start}-#{range_end}\n" members = entry[field_name]#.collect { |mo| mo.split(',').first.split('=')[1] } members.concat ldap_members(cn, range_end.to_i+1) unless range_end == '*' return members end
ruby
def ldap_members(cn, start=0) return [] if service.nil? # print "Getting members of #{cn} at index #{start}\n" entry = service.search(base: tree, filter: Net::LDAP::Filter.equals('cn', cn), attributes: ["member;range=#{start}-*"]).first return [] if entry.nil? field_name = entry.attribute_names[1] # Is this always ordered [dn, member]? return [] if field_name.nil? # Sometimes member is not present. range_end = field_name.to_s.match(/^member;range=\d+-([0-9*]+)$/)[1] # print "#{start}-#{range_end}\n" members = entry[field_name]#.collect { |mo| mo.split(',').first.split('=')[1] } members.concat ldap_members(cn, range_end.to_i+1) unless range_end == '*' return members end
[ "def", "ldap_members", "(", "cn", ",", "start", "=", "0", ")", "return", "[", "]", "if", "service", ".", "nil?", "# print \"Getting members of #{cn} at index #{start}\\n\"", "entry", "=", "service", ".", "search", "(", "base", ":", "tree", ",", "filter", ":", "Net", "::", "LDAP", "::", "Filter", ".", "equals", "(", "'cn'", ",", "cn", ")", ",", "attributes", ":", "[", "\"member;range=#{start}-*\"", "]", ")", ".", "first", "return", "[", "]", "if", "entry", ".", "nil?", "field_name", "=", "entry", ".", "attribute_names", "[", "1", "]", "# Is this always ordered [dn, member]?", "return", "[", "]", "if", "field_name", ".", "nil?", "# Sometimes member is not present.", "range_end", "=", "field_name", ".", "to_s", ".", "match", "(", "/", "\\d", "/", ")", "[", "1", "]", "# print \"#{start}-#{range_end}\\n\"", "members", "=", "entry", "[", "field_name", "]", "#.collect { |mo| mo.split(',').first.split('=')[1] }", "members", ".", "concat", "ldap_members", "(", "cn", ",", "range_end", ".", "to_i", "+", "1", ")", "unless", "range_end", "==", "'*'", "return", "members", "end" ]
Gets the entire list of members for a CN. Handles range results. @param [String] cn of the entry to fetch. @param [Integer] start index of range result @return [Array] list of member CNs
[ "Gets", "the", "entire", "list", "of", "members", "for", "a", "CN", ".", "Handles", "range", "results", "." ]
430ff8e1dd084fdc7113fbfe85b6422900b39184
https://github.com/IUBLibTech/ldap_groups_lookup/blob/430ff8e1dd084fdc7113fbfe85b6422900b39184/lib/ldap_groups_lookup/search.rb#L73-L89
3,405
offers/singularity-cli
lib/singularity/request.rb
Singularity.Request.deploy
def deploy if is_paused puts ' PAUSED, SKIPPING.' return else @data['requestId'] = @data['id'] @data['id'] = "#{@release}.#{Time.now.to_i}" @data['containerInfo']['docker']['image'] = File.exist?('dcos-deploy/config.yml') ? YAML.load_file(File.join(Dir.pwd, 'dcos-deploy/config.yml'))['repo']+":#{@release}" : "#{JSON.parse(File.read('.mescal.json'))['image'].split(':').first}:#{@release}" @deploy = { 'deploy' => @data, 'user' => `whoami`.chomp, 'unpauseOnSuccessfulDeploy' => false } # deploy the request RestClient.post "#{@uri}/api/deploys", @deploy.to_json, :content_type => :json puts ' Deploy succeeded: '.green + @data['requestId'].light_blue end end
ruby
def deploy if is_paused puts ' PAUSED, SKIPPING.' return else @data['requestId'] = @data['id'] @data['id'] = "#{@release}.#{Time.now.to_i}" @data['containerInfo']['docker']['image'] = File.exist?('dcos-deploy/config.yml') ? YAML.load_file(File.join(Dir.pwd, 'dcos-deploy/config.yml'))['repo']+":#{@release}" : "#{JSON.parse(File.read('.mescal.json'))['image'].split(':').first}:#{@release}" @deploy = { 'deploy' => @data, 'user' => `whoami`.chomp, 'unpauseOnSuccessfulDeploy' => false } # deploy the request RestClient.post "#{@uri}/api/deploys", @deploy.to_json, :content_type => :json puts ' Deploy succeeded: '.green + @data['requestId'].light_blue end end
[ "def", "deploy", "if", "is_paused", "puts", "' PAUSED, SKIPPING.'", "return", "else", "@data", "[", "'requestId'", "]", "=", "@data", "[", "'id'", "]", "@data", "[", "'id'", "]", "=", "\"#{@release}.#{Time.now.to_i}\"", "@data", "[", "'containerInfo'", "]", "[", "'docker'", "]", "[", "'image'", "]", "=", "File", ".", "exist?", "(", "'dcos-deploy/config.yml'", ")", "?", "YAML", ".", "load_file", "(", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "'dcos-deploy/config.yml'", ")", ")", "[", "'repo'", "]", "+", "\":#{@release}\"", ":", "\"#{JSON.parse(File.read('.mescal.json'))['image'].split(':').first}:#{@release}\"", "@deploy", "=", "{", "'deploy'", "=>", "@data", ",", "'user'", "=>", "`", "`", ".", "chomp", ",", "'unpauseOnSuccessfulDeploy'", "=>", "false", "}", "# deploy the request", "RestClient", ".", "post", "\"#{@uri}/api/deploys\"", ",", "@deploy", ".", "to_json", ",", ":content_type", "=>", ":json", "puts", "' Deploy succeeded: '", ".", "green", "+", "@data", "[", "'requestId'", "]", ".", "light_blue", "end", "end" ]
deploys a request in singularity
[ "deploys", "a", "request", "in", "singularity" ]
c0c769880d06da7b23d0220166e56914e2190d61
https://github.com/offers/singularity-cli/blob/c0c769880d06da7b23d0220166e56914e2190d61/lib/singularity/request.rb#L28-L48
3,406
localmed/outbox
lib/outbox/message.rb
Outbox.Message.body
def body(value) each_message_type do |_, message| next if message.nil? message.body = value end end
ruby
def body(value) each_message_type do |_, message| next if message.nil? message.body = value end end
[ "def", "body", "(", "value", ")", "each_message_type", "do", "|", "_", ",", "message", "|", "next", "if", "message", ".", "nil?", "message", ".", "body", "=", "value", "end", "end" ]
Make a new message. Every message can be created using a hash, block, or direct assignment. message = Message.new do email do subject 'Subject' end end message = Message.new email: { subject: 'Subject' } message = Message.new message.email = Email.new subject: 'Subject' Loops through each registered message type and sets the content body.
[ "Make", "a", "new", "message", ".", "Every", "message", "can", "be", "created", "using", "a", "hash", "block", "or", "direct", "assignment", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message.rb#L36-L41
3,407
localmed/outbox
lib/outbox/message.rb
Outbox.Message.deliver
def deliver(audience) audience = Outbox::Accessor.new(audience) each_message_type do |message_type, message| next if message.nil? recipient = audience[message_type] message.deliver(recipient) if recipient end end
ruby
def deliver(audience) audience = Outbox::Accessor.new(audience) each_message_type do |message_type, message| next if message.nil? recipient = audience[message_type] message.deliver(recipient) if recipient end end
[ "def", "deliver", "(", "audience", ")", "audience", "=", "Outbox", "::", "Accessor", ".", "new", "(", "audience", ")", "each_message_type", "do", "|", "message_type", ",", "message", "|", "next", "if", "message", ".", "nil?", "recipient", "=", "audience", "[", "message_type", "]", "message", ".", "deliver", "(", "recipient", ")", "if", "recipient", "end", "end" ]
Delivers all of the messages to the given 'audience'. An 'audience' object can be a hash or an object that responds to the current message types. Only the message types specified in the 'audience' object will be sent to. message.deliver email: '[email protected]', sms: '+15555555555' audience = OpenStruct.new audience.email = '[email protected]' audience.sms = '+15555555555' message.deliver(audience)
[ "Delivers", "all", "of", "the", "messages", "to", "the", "given", "audience", ".", "An", "audience", "object", "can", "be", "a", "hash", "or", "an", "object", "that", "responds", "to", "the", "current", "message", "types", ".", "Only", "the", "message", "types", "specified", "in", "the", "audience", "object", "will", "be", "sent", "to", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message.rb#L54-L63
3,408
tecfoundary/hicube
app/controllers/hicube/application_controller.rb
Hicube.ApplicationController.notify
def notify(type, message, options = {}) options[:now] ||= false # Convert and cleanup. type = type.to_s.downcase.to_sym # Sanity check for type. unless FLASH_TYPES.include?(type) raise ArgumentError, "Invalid value for argument type: #{type}, expected one of: #{FLASH_TYPES.to_sentence}." end logger.info("FLASH (#{options.inspect}) #{type.to_s.upcase}: #{message}") if options[:now] == true flash.now[type] ||= [] flash.now[type] << message else flash[type] ||= [] flash[type] << message end logger.debug("DEBUG: FLASH #{flash.inspect}") return true end
ruby
def notify(type, message, options = {}) options[:now] ||= false # Convert and cleanup. type = type.to_s.downcase.to_sym # Sanity check for type. unless FLASH_TYPES.include?(type) raise ArgumentError, "Invalid value for argument type: #{type}, expected one of: #{FLASH_TYPES.to_sentence}." end logger.info("FLASH (#{options.inspect}) #{type.to_s.upcase}: #{message}") if options[:now] == true flash.now[type] ||= [] flash.now[type] << message else flash[type] ||= [] flash[type] << message end logger.debug("DEBUG: FLASH #{flash.inspect}") return true end
[ "def", "notify", "(", "type", ",", "message", ",", "options", "=", "{", "}", ")", "options", "[", ":now", "]", "||=", "false", "# Convert and cleanup.", "type", "=", "type", ".", "to_s", ".", "downcase", ".", "to_sym", "# Sanity check for type.", "unless", "FLASH_TYPES", ".", "include?", "(", "type", ")", "raise", "ArgumentError", ",", "\"Invalid value for argument type: #{type}, expected one of: #{FLASH_TYPES.to_sentence}.\"", "end", "logger", ".", "info", "(", "\"FLASH (#{options.inspect}) #{type.to_s.upcase}: #{message}\"", ")", "if", "options", "[", ":now", "]", "==", "true", "flash", ".", "now", "[", "type", "]", "||=", "[", "]", "flash", ".", "now", "[", "type", "]", "<<", "message", "else", "flash", "[", "type", "]", "||=", "[", "]", "flash", "[", "type", "]", "<<", "message", "end", "logger", ".", "debug", "(", "\"DEBUG: FLASH #{flash.inspect}\"", ")", "return", "true", "end" ]
Generate a notification message.
[ "Generate", "a", "notification", "message", "." ]
57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe
https://github.com/tecfoundary/hicube/blob/57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe/app/controllers/hicube/application_controller.rb#L46-L70
3,409
JavonDavis/parallel_appium
lib/parallel_appium/android.rb
ParallelAppium.Android.start_emulators
def start_emulators emulators = `emulator -list-avds`.split("\n") emulators = emulators[0, ENV['THREADS'].to_i] Parallel.map(emulators, in_threads: emulators.size) do |emulator| spawn("emulator -avd #{emulator} -no-snapshot-load -scale 100dpi -no-boot-anim -no-audio -accel on &", out: '/dev/null') end emulators end
ruby
def start_emulators emulators = `emulator -list-avds`.split("\n") emulators = emulators[0, ENV['THREADS'].to_i] Parallel.map(emulators, in_threads: emulators.size) do |emulator| spawn("emulator -avd #{emulator} -no-snapshot-load -scale 100dpi -no-boot-anim -no-audio -accel on &", out: '/dev/null') end emulators end
[ "def", "start_emulators", "emulators", "=", "`", "`", ".", "split", "(", "\"\\n\"", ")", "emulators", "=", "emulators", "[", "0", ",", "ENV", "[", "'THREADS'", "]", ".", "to_i", "]", "Parallel", ".", "map", "(", "emulators", ",", "in_threads", ":", "emulators", ".", "size", ")", "do", "|", "emulator", "|", "spawn", "(", "\"emulator -avd #{emulator} -no-snapshot-load -scale 100dpi -no-boot-anim -no-audio -accel on &\"", ",", "out", ":", "'/dev/null'", ")", "end", "emulators", "end" ]
Fire up the Android emulators
[ "Fire", "up", "the", "Android", "emulators" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/android.rb#L5-L13
3,410
henkm/shake-the-counter
lib/shake_the_counter/section.rb
ShakeTheCounter.Section.make_reservation
def make_reservation(price_type_list: {}, affiliate: '', first_name: '', last_name: '', email: '') # step 1: make the reservation path = "event/#{performance.event.key}/performance/#{performance.key}/section/#{performance_section_key}/reservation/#{performance.event.client.language_code}" body = { PriceTypeList: price_type_list } result = performance.event.client.call(path, http_method: :post, body: body.to_json) reservation = ShakeTheCounter::Reservation.new(result) # step 2: create a contact path = "contact/#{performance.event.client.language_code}" body = { FirstName: first_name, LastName: last_name, MailAddress: email, LanguageCode: performance.event.client.language_code } result = performance.event.client.call(path, http_method: :post, body: body.to_json) contact = ShakeTheCounter::Contact.new(result) # step 3: link contact to the reservation path = "reservation/#{reservation.key}/contact" body = { ContactKey: contact.key } result = performance.event.client.call(path, http_method: :post, body: body.to_json) return reservation end
ruby
def make_reservation(price_type_list: {}, affiliate: '', first_name: '', last_name: '', email: '') # step 1: make the reservation path = "event/#{performance.event.key}/performance/#{performance.key}/section/#{performance_section_key}/reservation/#{performance.event.client.language_code}" body = { PriceTypeList: price_type_list } result = performance.event.client.call(path, http_method: :post, body: body.to_json) reservation = ShakeTheCounter::Reservation.new(result) # step 2: create a contact path = "contact/#{performance.event.client.language_code}" body = { FirstName: first_name, LastName: last_name, MailAddress: email, LanguageCode: performance.event.client.language_code } result = performance.event.client.call(path, http_method: :post, body: body.to_json) contact = ShakeTheCounter::Contact.new(result) # step 3: link contact to the reservation path = "reservation/#{reservation.key}/contact" body = { ContactKey: contact.key } result = performance.event.client.call(path, http_method: :post, body: body.to_json) return reservation end
[ "def", "make_reservation", "(", "price_type_list", ":", "{", "}", ",", "affiliate", ":", "''", ",", "first_name", ":", "''", ",", "last_name", ":", "''", ",", "email", ":", "''", ")", "# step 1: make the reservation", "path", "=", "\"event/#{performance.event.key}/performance/#{performance.key}/section/#{performance_section_key}/reservation/#{performance.event.client.language_code}\"", "body", "=", "{", "PriceTypeList", ":", "price_type_list", "}", "result", "=", "performance", ".", "event", ".", "client", ".", "call", "(", "path", ",", "http_method", ":", ":post", ",", "body", ":", "body", ".", "to_json", ")", "reservation", "=", "ShakeTheCounter", "::", "Reservation", ".", "new", "(", "result", ")", "# step 2: create a contact", "path", "=", "\"contact/#{performance.event.client.language_code}\"", "body", "=", "{", "FirstName", ":", "first_name", ",", "LastName", ":", "last_name", ",", "MailAddress", ":", "email", ",", "LanguageCode", ":", "performance", ".", "event", ".", "client", ".", "language_code", "}", "result", "=", "performance", ".", "event", ".", "client", ".", "call", "(", "path", ",", "http_method", ":", ":post", ",", "body", ":", "body", ".", "to_json", ")", "contact", "=", "ShakeTheCounter", "::", "Contact", ".", "new", "(", "result", ")", "# step 3: link contact to the reservation", "path", "=", "\"reservation/#{reservation.key}/contact\"", "body", "=", "{", "ContactKey", ":", "contact", ".", "key", "}", "result", "=", "performance", ".", "event", ".", "client", ".", "call", "(", "path", ",", "http_method", ":", ":post", ",", "body", ":", "body", ".", "to_json", ")", "return", "reservation", "end" ]
Sets up a new section Makes a reservation for this section POST /api/v1/event/{eventKey}/performance/{performanceKey}/section/{performanceSectionKey}/reservation/{languageCode} @param email: '' [type] [description] @return Reservation
[ "Sets", "up", "a", "new", "section" ]
094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e
https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/section.rb#L36-L64
3,411
G5/modelish
lib/modelish/base.rb
Modelish.Base.to_hash
def to_hash out = {} self.class.properties.each { |p| out[hash_key(p)] = hash_value(p) } out end
ruby
def to_hash out = {} self.class.properties.each { |p| out[hash_key(p)] = hash_value(p) } out end
[ "def", "to_hash", "out", "=", "{", "}", "self", ".", "class", ".", "properties", ".", "each", "{", "|", "p", "|", "out", "[", "hash_key", "(", "p", ")", "]", "=", "hash_value", "(", "p", ")", "}", "out", "end" ]
Convert this Modelish object into a vanilla Hash with stringified keys. @return [Hash] the hash of properties
[ "Convert", "this", "Modelish", "object", "into", "a", "vanilla", "Hash", "with", "stringified", "keys", "." ]
42cb6e07dafd794e0180b858a36fb7b5a8e424b6
https://github.com/G5/modelish/blob/42cb6e07dafd794e0180b858a36fb7b5a8e424b6/lib/modelish/base.rb#L27-L31
3,412
cknadler/git-feats
lib/git-feats/checker.rb
GitFeats.Checker.check
def check(args) # Load history and completed Completed.unserialize History.unserialize # request flag upload = false # Check for feats and update history Feats.all.each do |pattern, feats| if args.match?(pattern) History.add(pattern) feats.each do |feat, value| if History.count(pattern) >= value[:count] unless Completed.exists?(feat) Completed.add(feat) Reporter.report(value) upload = true end end end end end # upload feats if the request flag is set upload_feats if upload # Write out history and completed feats Completed.serialize History.serialize end
ruby
def check(args) # Load history and completed Completed.unserialize History.unserialize # request flag upload = false # Check for feats and update history Feats.all.each do |pattern, feats| if args.match?(pattern) History.add(pattern) feats.each do |feat, value| if History.count(pattern) >= value[:count] unless Completed.exists?(feat) Completed.add(feat) Reporter.report(value) upload = true end end end end end # upload feats if the request flag is set upload_feats if upload # Write out history and completed feats Completed.serialize History.serialize end
[ "def", "check", "(", "args", ")", "# Load history and completed", "Completed", ".", "unserialize", "History", ".", "unserialize", "# request flag", "upload", "=", "false", "# Check for feats and update history", "Feats", ".", "all", ".", "each", "do", "|", "pattern", ",", "feats", "|", "if", "args", ".", "match?", "(", "pattern", ")", "History", ".", "add", "(", "pattern", ")", "feats", ".", "each", "do", "|", "feat", ",", "value", "|", "if", "History", ".", "count", "(", "pattern", ")", ">=", "value", "[", ":count", "]", "unless", "Completed", ".", "exists?", "(", "feat", ")", "Completed", ".", "add", "(", "feat", ")", "Reporter", ".", "report", "(", "value", ")", "upload", "=", "true", "end", "end", "end", "end", "end", "# upload feats if the request flag is set", "upload_feats", "if", "upload", "# Write out history and completed feats", "Completed", ".", "serialize", "History", ".", "serialize", "end" ]
Main interface for checking feats
[ "Main", "interface", "for", "checking", "feats" ]
a2425c2c5998b0c5f817d8a80efc8c2bd053786e
https://github.com/cknadler/git-feats/blob/a2425c2c5998b0c5f817d8a80efc8c2bd053786e/lib/git-feats/checker.rb#L7-L39
3,413
pjaspers/shack
lib/shack/stamp.rb
Shack.Stamp.rounded_corner
def rounded_corner(horizontal, vertical) css = [] << "border" attrs = { top: "bottom", bottom: "top", left: "right", right: "left" } css << attrs.fetch(vertical) css << attrs.fetch(horizontal) css << "radius" css.join("-") end
ruby
def rounded_corner(horizontal, vertical) css = [] << "border" attrs = { top: "bottom", bottom: "top", left: "right", right: "left" } css << attrs.fetch(vertical) css << attrs.fetch(horizontal) css << "radius" css.join("-") end
[ "def", "rounded_corner", "(", "horizontal", ",", "vertical", ")", "css", "=", "[", "]", "<<", "\"border\"", "attrs", "=", "{", "top", ":", "\"bottom\"", ",", "bottom", ":", "\"top\"", ",", "left", ":", "\"right\"", ",", "right", ":", "\"left\"", "}", "css", "<<", "attrs", ".", "fetch", "(", "vertical", ")", "css", "<<", "attrs", ".", "fetch", "(", "horizontal", ")", "css", "<<", "\"radius\"", "css", ".", "join", "(", "\"-\"", ")", "end" ]
Returns the CSS needed to round the correct corner `border-top-left-radius`
[ "Returns", "the", "CSS", "needed", "to", "round", "the", "correct", "corner" ]
bc65001fcd375e6da0c3c4b2f234766a3c0e6e22
https://github.com/pjaspers/shack/blob/bc65001fcd375e6da0c3c4b2f234766a3c0e6e22/lib/shack/stamp.rb#L50-L59
3,414
Chris911/imgurr
lib/imgurr/storage.rb
Imgurr.Storage.bootstrap
def bootstrap return if File.exist?(json_file) FileUtils.touch json_file File.open(json_file, 'w') {|f| f.write(to_json) } save end
ruby
def bootstrap return if File.exist?(json_file) FileUtils.touch json_file File.open(json_file, 'w') {|f| f.write(to_json) } save end
[ "def", "bootstrap", "return", "if", "File", ".", "exist?", "(", "json_file", ")", "FileUtils", ".", "touch", "json_file", "File", ".", "open", "(", "json_file", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "to_json", ")", "}", "save", "end" ]
Takes care of bootstrapping the Json file, both in terms of creating the file and in terms of creating a skeleton Json schema. Return true if successfully saved.
[ "Takes", "care", "of", "bootstrapping", "the", "Json", "file", "both", "in", "terms", "of", "creating", "the", "file", "and", "in", "terms", "of", "creating", "a", "skeleton", "Json", "schema", "." ]
09a492a80b9ec1ddf827501e6da6ad3dfa6d224d
https://github.com/Chris911/imgurr/blob/09a492a80b9ec1ddf827501e6da6ad3dfa6d224d/lib/imgurr/storage.rb#L91-L96
3,415
neo4j-examples/graph_starter
app/helpers/graph_starter/application_helper.rb
GraphStarter.ApplicationHelper.asset_icon
def asset_icon(asset, image = (image_unspecified = true; nil)) image_url = if !image_unspecified image.source.url if image.present? elsif (asset.class.has_images? || asset.class.has_image?) && asset.first_image_source_url.present? asset.first_image_source_url end if image_url image_tag image_url, class: 'ui avatar image' else content_tag :i, '', class: [asset.class.icon_class || 'folder', 'large', 'icon'] end end
ruby
def asset_icon(asset, image = (image_unspecified = true; nil)) image_url = if !image_unspecified image.source.url if image.present? elsif (asset.class.has_images? || asset.class.has_image?) && asset.first_image_source_url.present? asset.first_image_source_url end if image_url image_tag image_url, class: 'ui avatar image' else content_tag :i, '', class: [asset.class.icon_class || 'folder', 'large', 'icon'] end end
[ "def", "asset_icon", "(", "asset", ",", "image", "=", "(", "image_unspecified", "=", "true", ";", "nil", ")", ")", "image_url", "=", "if", "!", "image_unspecified", "image", ".", "source", ".", "url", "if", "image", ".", "present?", "elsif", "(", "asset", ".", "class", ".", "has_images?", "||", "asset", ".", "class", ".", "has_image?", ")", "&&", "asset", ".", "first_image_source_url", ".", "present?", "asset", ".", "first_image_source_url", "end", "if", "image_url", "image_tag", "image_url", ",", "class", ":", "'ui avatar image'", "else", "content_tag", ":i", ",", "''", ",", "class", ":", "[", "asset", ".", "class", ".", "icon_class", "||", "'folder'", ",", "'large'", ",", "'icon'", "]", "end", "end" ]
I know, right?
[ "I", "know", "right?" ]
3c3d28c3df3513ed6ddb3037b245d6c66d0fc05a
https://github.com/neo4j-examples/graph_starter/blob/3c3d28c3df3513ed6ddb3037b245d6c66d0fc05a/app/helpers/graph_starter/application_helper.rb#L38-L50
3,416
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.get_platform_project
def get_platform_project(name) if name =~ /debian/ return DEBIAN_PROJECT elsif name =~ /centos/ return CENTOS_PROJECT elsif name =~ /rhel/ return RHEL_PROJECT elsif name =~ /sles/ return SLES_PROJECT else raise "Unsupported platform for Google Compute Engine: #{name}" end end
ruby
def get_platform_project(name) if name =~ /debian/ return DEBIAN_PROJECT elsif name =~ /centos/ return CENTOS_PROJECT elsif name =~ /rhel/ return RHEL_PROJECT elsif name =~ /sles/ return SLES_PROJECT else raise "Unsupported platform for Google Compute Engine: #{name}" end end
[ "def", "get_platform_project", "(", "name", ")", "if", "name", "=~", "/", "/", "return", "DEBIAN_PROJECT", "elsif", "name", "=~", "/", "/", "return", "CENTOS_PROJECT", "elsif", "name", "=~", "/", "/", "return", "RHEL_PROJECT", "elsif", "name", "=~", "/", "/", "return", "SLES_PROJECT", "else", "raise", "\"Unsupported platform for Google Compute Engine: #{name}\"", "end", "end" ]
Determines the Google Compute project which contains bases instances of type name @param [String] name The platform type to search for @return The Google Compute project name @raise [Exception] If the provided platform type name is unsupported
[ "Determines", "the", "Google", "Compute", "project", "which", "contains", "bases", "instances", "of", "type", "name" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L106-L118
3,417
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.set_compute_api
def set_compute_api version, start, attempts try = (Time.now - start)/SLEEPWAIT while try <= attempts begin @compute = @client.discovered_api('compute', version) @logger.debug("Google Compute API discovered") return rescue => e @logger.debug("Failed to discover Google Compute API") if try >= attempts raise e end end try += 1 end end
ruby
def set_compute_api version, start, attempts try = (Time.now - start)/SLEEPWAIT while try <= attempts begin @compute = @client.discovered_api('compute', version) @logger.debug("Google Compute API discovered") return rescue => e @logger.debug("Failed to discover Google Compute API") if try >= attempts raise e end end try += 1 end end
[ "def", "set_compute_api", "version", ",", "start", ",", "attempts", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "@compute", "=", "@client", ".", "discovered_api", "(", "'compute'", ",", "version", ")", "@logger", ".", "debug", "(", "\"Google Compute API discovered\"", ")", "return", "rescue", "=>", "e", "@logger", ".", "debug", "(", "\"Failed to discover Google Compute API\"", ")", "if", "try", ">=", "attempts", "raise", "e", "end", "end", "try", "+=", "1", "end", "end" ]
Discover the currently active Google Compute API @param [String] version The version of the Google Compute API to discover @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail to discover the Google Compute API, either through errors or running out of attempts
[ "Discover", "the", "currently", "active", "Google", "Compute", "API" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L141-L156
3,418
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.authenticate
def authenticate(keyfile, password, email, start, attempts) # OAuth authentication, using the service account key = ::Google::APIClient::PKCS12.load_key(keyfile, password) service_account = ::Google::APIClient::JWTAsserter.new( email, AUTH_URL, key) try = (Time.now - start) / SLEEPWAIT while try <= attempts begin @client.authorization = service_account.authorize @logger.debug("Authorized to use Google Compute") return rescue => e @logger.debug("Failed to authorize to use Google Compute") if try >= attempts raise e end end try += 1 end end
ruby
def authenticate(keyfile, password, email, start, attempts) # OAuth authentication, using the service account key = ::Google::APIClient::PKCS12.load_key(keyfile, password) service_account = ::Google::APIClient::JWTAsserter.new( email, AUTH_URL, key) try = (Time.now - start) / SLEEPWAIT while try <= attempts begin @client.authorization = service_account.authorize @logger.debug("Authorized to use Google Compute") return rescue => e @logger.debug("Failed to authorize to use Google Compute") if try >= attempts raise e end end try += 1 end end
[ "def", "authenticate", "(", "keyfile", ",", "password", ",", "email", ",", "start", ",", "attempts", ")", "# OAuth authentication, using the service account", "key", "=", "::", "Google", "::", "APIClient", "::", "PKCS12", ".", "load_key", "(", "keyfile", ",", "password", ")", "service_account", "=", "::", "Google", "::", "APIClient", "::", "JWTAsserter", ".", "new", "(", "email", ",", "AUTH_URL", ",", "key", ")", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "@client", ".", "authorization", "=", "service_account", ".", "authorize", "@logger", ".", "debug", "(", "\"Authorized to use Google Compute\"", ")", "return", "rescue", "=>", "e", "@logger", ".", "debug", "(", "\"Failed to authorize to use Google Compute\"", ")", "if", "try", ">=", "attempts", "raise", "e", "end", "end", "try", "+=", "1", "end", "end" ]
Creates an authenticated connection to the Google Compute Engine API @param [String] keyfile The location of the Google Compute Service Account keyfile to use for authentication @param [String] password The password for the provided Google Compute Service Account key @param [String] email The email address of the Google Compute Service Account we are using to connect @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail to create an authenticated connection to the Google Compute API, either through errors or running out of attempts
[ "Creates", "an", "authenticated", "connection", "to", "the", "Google", "Compute", "Engine", "API" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L179-L200
3,419
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.execute
def execute req, start, attempts last_error = parsed = nil try = (Time.now - start) / SLEEPWAIT while try <= attempts begin result = @client.execute(req) parsed = JSON.parse(result.body) if not result.success? error_code = parsed["error"] ? parsed["error"]["code"] : 0 if error_code == 404 raise GoogleComputeError, "Resource Not Found: #{result.body}" elsif error_code == 400 raise GoogleComputeError, "Bad Request: #{result.body}" else raise GoogleComputeError, "Error attempting Google Compute API execute: #{result.body}" end end return parsed # retry errors rescue Faraday::Error::ConnectionFailed => e @logger.debug "ConnectionFailed attempting Google Compute execute command" try += 1 last_error = e end end # we only get down here if we've used up all our tries raise last_error end
ruby
def execute req, start, attempts last_error = parsed = nil try = (Time.now - start) / SLEEPWAIT while try <= attempts begin result = @client.execute(req) parsed = JSON.parse(result.body) if not result.success? error_code = parsed["error"] ? parsed["error"]["code"] : 0 if error_code == 404 raise GoogleComputeError, "Resource Not Found: #{result.body}" elsif error_code == 400 raise GoogleComputeError, "Bad Request: #{result.body}" else raise GoogleComputeError, "Error attempting Google Compute API execute: #{result.body}" end end return parsed # retry errors rescue Faraday::Error::ConnectionFailed => e @logger.debug "ConnectionFailed attempting Google Compute execute command" try += 1 last_error = e end end # we only get down here if we've used up all our tries raise last_error end
[ "def", "execute", "req", ",", "start", ",", "attempts", "last_error", "=", "parsed", "=", "nil", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "result", "=", "@client", ".", "execute", "(", "req", ")", "parsed", "=", "JSON", ".", "parse", "(", "result", ".", "body", ")", "if", "not", "result", ".", "success?", "error_code", "=", "parsed", "[", "\"error\"", "]", "?", "parsed", "[", "\"error\"", "]", "[", "\"code\"", "]", ":", "0", "if", "error_code", "==", "404", "raise", "GoogleComputeError", ",", "\"Resource Not Found: #{result.body}\"", "elsif", "error_code", "==", "400", "raise", "GoogleComputeError", ",", "\"Bad Request: #{result.body}\"", "else", "raise", "GoogleComputeError", ",", "\"Error attempting Google Compute API execute: #{result.body}\"", "end", "end", "return", "parsed", "# retry errors", "rescue", "Faraday", "::", "Error", "::", "ConnectionFailed", "=>", "e", "@logger", ".", "debug", "\"ConnectionFailed attempting Google Compute execute command\"", "try", "+=", "1", "last_error", "=", "e", "end", "end", "# we only get down here if we've used up all our tries", "raise", "last_error", "end" ]
Executes a provided Google Compute request using a previously configured and authenticated Google Compute client connection @param [Hash] req A correctly formatted Google Compute request object @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail to execute the request, either through errors or running out of attempts
[ "Executes", "a", "provided", "Google", "Compute", "request", "using", "a", "previously", "configured", "and", "authenticated", "Google", "Compute", "client", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L215-L242
3,420
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.list_firewalls
def list_firewalls(start, attempts) result = execute( firewall_list_req(), start, attempts ) firewalls = result["items"] firewalls.delete_if{|f| f['name'] =~ /default-allow-internal|default-ssh/} firewalls end
ruby
def list_firewalls(start, attempts) result = execute( firewall_list_req(), start, attempts ) firewalls = result["items"] firewalls.delete_if{|f| f['name'] =~ /default-allow-internal|default-ssh/} firewalls end
[ "def", "list_firewalls", "(", "start", ",", "attempts", ")", "result", "=", "execute", "(", "firewall_list_req", "(", ")", ",", "start", ",", "attempts", ")", "firewalls", "=", "result", "[", "\"items\"", "]", "firewalls", ".", "delete_if", "{", "|", "f", "|", "f", "[", "'name'", "]", "=~", "/", "/", "}", "firewalls", "end" ]
Determines a list of existing Google Compute firewalls @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @return [Array[Hash]] The firewalls array of hashes @raise [Exception] Raised if we fail determine the list of existing firewalls, either through errors or running out of attempts
[ "Determines", "a", "list", "of", "existing", "Google", "Compute", "firewalls" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L363-L368
3,421
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.create_firewall
def create_firewall(name, network, start, attempts) execute( firewall_insert_req( name, network['selfLink'] ), start, attempts ) end
ruby
def create_firewall(name, network, start, attempts) execute( firewall_insert_req( name, network['selfLink'] ), start, attempts ) end
[ "def", "create_firewall", "(", "name", ",", "network", ",", "start", ",", "attempts", ")", "execute", "(", "firewall_insert_req", "(", "name", ",", "network", "[", "'selfLink'", "]", ")", ",", "start", ",", "attempts", ")", "end" ]
Create a Google Compute firewall on the current connection @param [String] name The name of the firewall to create @param [Hash] network The Google Compute network hash in which to create the firewall @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail create the firewall, either through errors or running out of attempts
[ "Create", "a", "Google", "Compute", "firewall", "on", "the", "current", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L386-L388
3,422
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.create_disk
def create_disk(name, img, start, attempts) #create a new boot disk for this instance disk = execute( disk_insert_req( name, img['selfLink'] ), start, attempts ) status = '' try = (Time.now - start) / SLEEPWAIT while status !~ /READY/ and try <= attempts begin disk = execute( disk_get_req( name ), start, attempts ) status = disk['status'] rescue GoogleComputeError => e @logger.debug("Waiting for #{name} disk creation") sleep(SLEEPWAIT) end try += 1 end if status == '' raise "Unable to create disk #{name}" end disk end
ruby
def create_disk(name, img, start, attempts) #create a new boot disk for this instance disk = execute( disk_insert_req( name, img['selfLink'] ), start, attempts ) status = '' try = (Time.now - start) / SLEEPWAIT while status !~ /READY/ and try <= attempts begin disk = execute( disk_get_req( name ), start, attempts ) status = disk['status'] rescue GoogleComputeError => e @logger.debug("Waiting for #{name} disk creation") sleep(SLEEPWAIT) end try += 1 end if status == '' raise "Unable to create disk #{name}" end disk end
[ "def", "create_disk", "(", "name", ",", "img", ",", "start", ",", "attempts", ")", "#create a new boot disk for this instance", "disk", "=", "execute", "(", "disk_insert_req", "(", "name", ",", "img", "[", "'selfLink'", "]", ")", ",", "start", ",", "attempts", ")", "status", "=", "''", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "status", "!~", "/", "/", "and", "try", "<=", "attempts", "begin", "disk", "=", "execute", "(", "disk_get_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "status", "=", "disk", "[", "'status'", "]", "rescue", "GoogleComputeError", "=>", "e", "@logger", ".", "debug", "(", "\"Waiting for #{name} disk creation\"", ")", "sleep", "(", "SLEEPWAIT", ")", "end", "try", "+=", "1", "end", "if", "status", "==", "''", "raise", "\"Unable to create disk #{name}\"", "end", "disk", "end" ]
Create a Google Compute disk on the current connection @param [String] name The name of the disk to create @param [Hash] img The Google Compute image to use for instance creation @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail create the disk, either through errors or running out of attempts
[ "Create", "a", "Google", "Compute", "disk", "on", "the", "current", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L405-L425
3,423
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.create_instance
def create_instance(name, img, machineType, disk, start, attempts) #add a new instance of the image instance = execute( instance_insert_req( name, img['selfLink'], machineType['selfLink'], disk['selfLink'] ), start, attempts) status = '' try = (Time.now - start) / SLEEPWAIT while status !~ /RUNNING/ and try <= attempts begin instance = execute( instance_get_req( name ), start, attempts ) status = instance['status'] rescue GoogleComputeError => e @logger.debug("Waiting for #{name} instance creation") sleep(SLEEPWAIT) end try += 1 end if status == '' raise "Unable to create instance #{name}" end instance end
ruby
def create_instance(name, img, machineType, disk, start, attempts) #add a new instance of the image instance = execute( instance_insert_req( name, img['selfLink'], machineType['selfLink'], disk['selfLink'] ), start, attempts) status = '' try = (Time.now - start) / SLEEPWAIT while status !~ /RUNNING/ and try <= attempts begin instance = execute( instance_get_req( name ), start, attempts ) status = instance['status'] rescue GoogleComputeError => e @logger.debug("Waiting for #{name} instance creation") sleep(SLEEPWAIT) end try += 1 end if status == '' raise "Unable to create instance #{name}" end instance end
[ "def", "create_instance", "(", "name", ",", "img", ",", "machineType", ",", "disk", ",", "start", ",", "attempts", ")", "#add a new instance of the image", "instance", "=", "execute", "(", "instance_insert_req", "(", "name", ",", "img", "[", "'selfLink'", "]", ",", "machineType", "[", "'selfLink'", "]", ",", "disk", "[", "'selfLink'", "]", ")", ",", "start", ",", "attempts", ")", "status", "=", "''", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "status", "!~", "/", "/", "and", "try", "<=", "attempts", "begin", "instance", "=", "execute", "(", "instance_get_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "status", "=", "instance", "[", "'status'", "]", "rescue", "GoogleComputeError", "=>", "e", "@logger", ".", "debug", "(", "\"Waiting for #{name} instance creation\"", ")", "sleep", "(", "SLEEPWAIT", ")", "end", "try", "+=", "1", "end", "if", "status", "==", "''", "raise", "\"Unable to create instance #{name}\"", "end", "instance", "end" ]
Create a Google Compute instance on the current connection @param [String] name The name of the instance to create @param [Hash] img The Google Compute image to use for instance creation @param [Hash] machineType The Google Compute machineType @param [Hash] disk The Google Compute disk to attach to the newly created instance @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail create the instance, either through errors or running out of attempts
[ "Create", "a", "Google", "Compute", "instance", "on", "the", "current", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L447-L466
3,424
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.delete_instance
def delete_instance(name, start, attempts) result = execute( instance_delete_req( name ), start, attempts ) # Ensure deletion of instance try = (Time.now - start) / SLEEPWAIT while try <= attempts begin result = execute( instance_get_req( name ), start, attempts ) @logger.debug("Waiting for #{name} instance deletion") sleep(SLEEPWAIT) rescue GoogleComputeError => e @logger.debug("#{name} instance deleted!") return end try += 1 end @logger.debug("#{name} instance was not removed before timeout, may still exist") end
ruby
def delete_instance(name, start, attempts) result = execute( instance_delete_req( name ), start, attempts ) # Ensure deletion of instance try = (Time.now - start) / SLEEPWAIT while try <= attempts begin result = execute( instance_get_req( name ), start, attempts ) @logger.debug("Waiting for #{name} instance deletion") sleep(SLEEPWAIT) rescue GoogleComputeError => e @logger.debug("#{name} instance deleted!") return end try += 1 end @logger.debug("#{name} instance was not removed before timeout, may still exist") end
[ "def", "delete_instance", "(", "name", ",", "start", ",", "attempts", ")", "result", "=", "execute", "(", "instance_delete_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "# Ensure deletion of instance", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "result", "=", "execute", "(", "instance_get_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Waiting for #{name} instance deletion\"", ")", "sleep", "(", "SLEEPWAIT", ")", "rescue", "GoogleComputeError", "=>", "e", "@logger", ".", "debug", "(", "\"#{name} instance deleted!\"", ")", "return", "end", "try", "+=", "1", "end", "@logger", ".", "debug", "(", "\"#{name} instance was not removed before timeout, may still exist\"", ")", "end" ]
Delete a Google Compute instance on the current connection @param [String] name The name of the instance to delete @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail delete the instance, either through errors or running out of attempts
[ "Delete", "a", "Google", "Compute", "instance", "on", "the", "current", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L521-L538
3,425
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.delete_disk
def delete_disk(name, start, attempts) result = execute( disk_delete_req( name ), start, attempts ) # Ensure deletion of disk try = (Time.now - start) / SLEEPWAIT while try <= attempts begin disk = execute( disk_get_req( name ), start, attempts ) @logger.debug("Waiting for #{name} disk deletion") sleep(SLEEPWAIT) rescue GoogleComputeError => e @logger.debug("#{name} disk deleted!") return end try += 1 end @logger.debug("#{name} disk was not removed before timeout, may still exist") end
ruby
def delete_disk(name, start, attempts) result = execute( disk_delete_req( name ), start, attempts ) # Ensure deletion of disk try = (Time.now - start) / SLEEPWAIT while try <= attempts begin disk = execute( disk_get_req( name ), start, attempts ) @logger.debug("Waiting for #{name} disk deletion") sleep(SLEEPWAIT) rescue GoogleComputeError => e @logger.debug("#{name} disk deleted!") return end try += 1 end @logger.debug("#{name} disk was not removed before timeout, may still exist") end
[ "def", "delete_disk", "(", "name", ",", "start", ",", "attempts", ")", "result", "=", "execute", "(", "disk_delete_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "# Ensure deletion of disk", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "disk", "=", "execute", "(", "disk_get_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Waiting for #{name} disk deletion\"", ")", "sleep", "(", "SLEEPWAIT", ")", "rescue", "GoogleComputeError", "=>", "e", "@logger", ".", "debug", "(", "\"#{name} disk deleted!\"", ")", "return", "end", "try", "+=", "1", "end", "@logger", ".", "debug", "(", "\"#{name} disk was not removed before timeout, may still exist\"", ")", "end" ]
Delete a Google Compute disk on the current connection @param [String] name The name of the disk to delete @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail delete the disk, either through errors or running out of attempts
[ "Delete", "a", "Google", "Compute", "disk", "on", "the", "current", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L553-L570
3,426
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.delete_firewall
def delete_firewall(name, start, attempts) result = execute( firewall_delete_req( name ), start, attempts ) #ensure deletion of disk try = (Time.now - start) / SLEEPWAIT while try <= attempts begin firewall = execute( firewall_get_req( name ), start, attempts ) @logger.debug("Waiting for #{name} firewall deletion") sleep(SLEEPWAIT) rescue GoogleComputeError => e @logger.debug("#{name} firewall deleted!") return end try += 1 end @logger.debug("#{name} firewall was not removed before timeout, may still exist") end
ruby
def delete_firewall(name, start, attempts) result = execute( firewall_delete_req( name ), start, attempts ) #ensure deletion of disk try = (Time.now - start) / SLEEPWAIT while try <= attempts begin firewall = execute( firewall_get_req( name ), start, attempts ) @logger.debug("Waiting for #{name} firewall deletion") sleep(SLEEPWAIT) rescue GoogleComputeError => e @logger.debug("#{name} firewall deleted!") return end try += 1 end @logger.debug("#{name} firewall was not removed before timeout, may still exist") end
[ "def", "delete_firewall", "(", "name", ",", "start", ",", "attempts", ")", "result", "=", "execute", "(", "firewall_delete_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "#ensure deletion of disk", "try", "=", "(", "Time", ".", "now", "-", "start", ")", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "firewall", "=", "execute", "(", "firewall_get_req", "(", "name", ")", ",", "start", ",", "attempts", ")", "@logger", ".", "debug", "(", "\"Waiting for #{name} firewall deletion\"", ")", "sleep", "(", "SLEEPWAIT", ")", "rescue", "GoogleComputeError", "=>", "e", "@logger", ".", "debug", "(", "\"#{name} firewall deleted!\"", ")", "return", "end", "try", "+=", "1", "end", "@logger", ".", "debug", "(", "\"#{name} firewall was not removed before timeout, may still exist\"", ")", "end" ]
Delete a Google Compute firewall on the current connection @param [String] name The name of the firewall to delete @param [Integer] start The time when we started code execution, it is compared to Time.now to determine how many further code execution attempts remain @param [Integer] attempts The total amount of attempts to execute that we are willing to allow @raise [Exception] Raised if we fail delete the firewall, either through errors or running out of attempts
[ "Delete", "a", "Google", "Compute", "firewall", "on", "the", "current", "connection" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L585-L601
3,427
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.instance_setMetadata_req
def instance_setMetadata_req(name, fingerprint, data) { :api_method => @compute.instances.set_metadata, :parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME, 'instance' => name }, :body_object => { 'kind' => 'compute#metadata', 'fingerprint' => fingerprint, 'items' => data } } end
ruby
def instance_setMetadata_req(name, fingerprint, data) { :api_method => @compute.instances.set_metadata, :parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME, 'instance' => name }, :body_object => { 'kind' => 'compute#metadata', 'fingerprint' => fingerprint, 'items' => data } } end
[ "def", "instance_setMetadata_req", "(", "name", ",", "fingerprint", ",", "data", ")", "{", ":api_method", "=>", "@compute", ".", "instances", ".", "set_metadata", ",", ":parameters", "=>", "{", "'project'", "=>", "@options", "[", ":gce_project", "]", ",", "'zone'", "=>", "DEFAULT_ZONE_NAME", ",", "'instance'", "=>", "name", "}", ",", ":body_object", "=>", "{", "'kind'", "=>", "'compute#metadata'", ",", "'fingerprint'", "=>", "fingerprint", ",", "'items'", "=>", "data", "}", "}", "end" ]
Set tags on a Google Compute instance @param [Array<String>] data An array of tags to be added to an instance @return [Hash] A correctly formatted Google Compute request hash
[ "Set", "tags", "on", "a", "Google", "Compute", "instance" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L726-L733
3,428
puppetlabs/beaker-google
lib/beaker/hypervisor/google_compute_helper.rb
Beaker.GoogleComputeHelper.instance_insert_req
def instance_insert_req(name, image, machineType, disk) { :api_method => @compute.instances.insert, :parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME }, :body_object => { 'name' => name, 'image' => image, 'zone' => default_zone, 'machineType' => machineType, 'disks' => [ { 'source' => disk, 'type' => 'PERSISTENT', 'boot' => 'true'} ], 'networkInterfaces' => [ { 'accessConfigs' => [{ 'type' => 'ONE_TO_ONE_NAT', 'name' => 'External NAT' }], 'network' => default_network } ] } } end
ruby
def instance_insert_req(name, image, machineType, disk) { :api_method => @compute.instances.insert, :parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME }, :body_object => { 'name' => name, 'image' => image, 'zone' => default_zone, 'machineType' => machineType, 'disks' => [ { 'source' => disk, 'type' => 'PERSISTENT', 'boot' => 'true'} ], 'networkInterfaces' => [ { 'accessConfigs' => [{ 'type' => 'ONE_TO_ONE_NAT', 'name' => 'External NAT' }], 'network' => default_network } ] } } end
[ "def", "instance_insert_req", "(", "name", ",", "image", ",", "machineType", ",", "disk", ")", "{", ":api_method", "=>", "@compute", ".", "instances", ".", "insert", ",", ":parameters", "=>", "{", "'project'", "=>", "@options", "[", ":gce_project", "]", ",", "'zone'", "=>", "DEFAULT_ZONE_NAME", "}", ",", ":body_object", "=>", "{", "'name'", "=>", "name", ",", "'image'", "=>", "image", ",", "'zone'", "=>", "default_zone", ",", "'machineType'", "=>", "machineType", ",", "'disks'", "=>", "[", "{", "'source'", "=>", "disk", ",", "'type'", "=>", "'PERSISTENT'", ",", "'boot'", "=>", "'true'", "}", "]", ",", "'networkInterfaces'", "=>", "[", "{", "'accessConfigs'", "=>", "[", "{", "'type'", "=>", "'ONE_TO_ONE_NAT'", ",", "'name'", "=>", "'External NAT'", "}", "]", ",", "'network'", "=>", "default_network", "}", "]", "}", "}", "end" ]
Create a Google Compute instance create request @param [String] name The name of the instance to create @param [String] image The link to the image to use for instance create @param [String] machineType The link to the type of Google Compute instance to create (indicates cpus and memory size) @param [String] disk The link to the disk to be used by the newly created instance @return [Hash] A correctly formatted Google Compute request hash
[ "Create", "a", "Google", "Compute", "instance", "create", "request" ]
3d7927f718447547293559d4631e26fcbdbf78e3
https://github.com/puppetlabs/beaker-google/blob/3d7927f718447547293559d4631e26fcbdbf78e3/lib/beaker/hypervisor/google_compute_helper.rb#L776-L787
3,429
schneems/let_it_go
lib/let_it_go/method_call.rb
LetItGo.MethodCall.method_array
def method_array @parser = nil @caller_lines.each do |kaller| code = Ripper.sexp(kaller.contents) code ||= Ripper.sexp(kaller.contents.sub(/^\W*(if|unless)/, ''.freeze)) # if and unless "block" statements aren't valid one line ruby code code ||= Ripper.sexp(kaller.contents.sub(/do \|.*\|$/, ''.freeze)) # remove trailing do |thing| to make valid code code ||= Ripper.sexp(kaller.contents.sub(/(and|or)\W*$/, ''.freeze))# trailing and || or code ||= Ripper.sexp(kaller.contents.sub(/:\W*$/, ''.freeze)) # multi line ternary statements code ||= Ripper.sexp(kaller.contents.sub(/(^\W*)|({ \|?.*\|?)}/, ''.freeze)) # multi line blocks using {} puts "LetItGoFailed parse (#{kaller.file_name}:#{kaller.line_number}: \n \033[0;31m"+ kaller.contents.strip + "\e[0m".freeze if ENV['LET_IT_GO_RECORD_FAILED_CODE'] && code.nil? && kaller.contents.match(/"|'/) parser = ::LetItGo::WTFParser.new(code, contents: kaller.contents) if parser.each_method.any? { |m| m.method_name == method_name } @line_number = kaller.line_number @file_name = kaller.file_name @parser = parser parser.each_method.each(&:arg_types) break else next end end @parser || [] end
ruby
def method_array @parser = nil @caller_lines.each do |kaller| code = Ripper.sexp(kaller.contents) code ||= Ripper.sexp(kaller.contents.sub(/^\W*(if|unless)/, ''.freeze)) # if and unless "block" statements aren't valid one line ruby code code ||= Ripper.sexp(kaller.contents.sub(/do \|.*\|$/, ''.freeze)) # remove trailing do |thing| to make valid code code ||= Ripper.sexp(kaller.contents.sub(/(and|or)\W*$/, ''.freeze))# trailing and || or code ||= Ripper.sexp(kaller.contents.sub(/:\W*$/, ''.freeze)) # multi line ternary statements code ||= Ripper.sexp(kaller.contents.sub(/(^\W*)|({ \|?.*\|?)}/, ''.freeze)) # multi line blocks using {} puts "LetItGoFailed parse (#{kaller.file_name}:#{kaller.line_number}: \n \033[0;31m"+ kaller.contents.strip + "\e[0m".freeze if ENV['LET_IT_GO_RECORD_FAILED_CODE'] && code.nil? && kaller.contents.match(/"|'/) parser = ::LetItGo::WTFParser.new(code, contents: kaller.contents) if parser.each_method.any? { |m| m.method_name == method_name } @line_number = kaller.line_number @file_name = kaller.file_name @parser = parser parser.each_method.each(&:arg_types) break else next end end @parser || [] end
[ "def", "method_array", "@parser", "=", "nil", "@caller_lines", ".", "each", "do", "|", "kaller", "|", "code", "=", "Ripper", ".", "sexp", "(", "kaller", ".", "contents", ")", "code", "||=", "Ripper", ".", "sexp", "(", "kaller", ".", "contents", ".", "sub", "(", "/", "\\W", "/", ",", "''", ".", "freeze", ")", ")", "# if and unless \"block\" statements aren't valid one line ruby code", "code", "||=", "Ripper", ".", "sexp", "(", "kaller", ".", "contents", ".", "sub", "(", "/", "\\|", "\\|", "/", ",", "''", ".", "freeze", ")", ")", "# remove trailing do |thing| to make valid code", "code", "||=", "Ripper", ".", "sexp", "(", "kaller", ".", "contents", ".", "sub", "(", "/", "\\W", "/", ",", "''", ".", "freeze", ")", ")", "# trailing and || or", "code", "||=", "Ripper", ".", "sexp", "(", "kaller", ".", "contents", ".", "sub", "(", "/", "\\W", "/", ",", "''", ".", "freeze", ")", ")", "# multi line ternary statements", "code", "||=", "Ripper", ".", "sexp", "(", "kaller", ".", "contents", ".", "sub", "(", "/", "\\W", "\\|", "\\|", "/", ",", "''", ".", "freeze", ")", ")", "# multi line blocks using {}", "puts", "\"LetItGoFailed parse (#{kaller.file_name}:#{kaller.line_number}: \\n \\033[0;31m\"", "+", "kaller", ".", "contents", ".", "strip", "+", "\"\\e[0m\"", ".", "freeze", "if", "ENV", "[", "'LET_IT_GO_RECORD_FAILED_CODE'", "]", "&&", "code", ".", "nil?", "&&", "kaller", ".", "contents", ".", "match", "(", "/", "/", ")", "parser", "=", "::", "LetItGo", "::", "WTFParser", ".", "new", "(", "code", ",", "contents", ":", "kaller", ".", "contents", ")", "if", "parser", ".", "each_method", ".", "any?", "{", "|", "m", "|", "m", ".", "method_name", "==", "method_name", "}", "@line_number", "=", "kaller", ".", "line_number", "@file_name", "=", "kaller", ".", "file_name", "@parser", "=", "parser", "parser", ".", "each_method", ".", "each", "(", ":arg_types", ")", "break", "else", "next", "end", "end", "@parser", "||", "[", "]", "end" ]
Loop through each line in the caller and see if the method we're watching is being called This is needed due to the way TracePoint deals with inheritance
[ "Loop", "through", "each", "line", "in", "the", "caller", "and", "see", "if", "the", "method", "we", "re", "watching", "is", "being", "called", "This", "is", "needed", "due", "to", "the", "way", "TracePoint", "deals", "with", "inheritance" ]
13557936b35b59d6b222287fd08d5421ce488f10
https://github.com/schneems/let_it_go/blob/13557936b35b59d6b222287fd08d5421ce488f10/lib/let_it_go/method_call.rb#L30-L56
3,430
schneems/let_it_go
lib/let_it_go/method_call.rb
LetItGo.MethodCall.called_with_string_literal?
def called_with_string_literal? @string_allocation_count = 0 method_array.each do |m| positions.each {|position| @string_allocation_count += 1 if m.arg_types[position] == :string_literal } end !@string_allocation_count.zero? end
ruby
def called_with_string_literal? @string_allocation_count = 0 method_array.each do |m| positions.each {|position| @string_allocation_count += 1 if m.arg_types[position] == :string_literal } end !@string_allocation_count.zero? end
[ "def", "called_with_string_literal?", "@string_allocation_count", "=", "0", "method_array", ".", "each", "do", "|", "m", "|", "positions", ".", "each", "{", "|", "position", "|", "@string_allocation_count", "+=", "1", "if", "m", ".", "arg_types", "[", "position", "]", "==", ":string_literal", "}", "end", "!", "@string_allocation_count", ".", "zero?", "end" ]
Parses original method call location Determines if a string literal was used or not
[ "Parses", "original", "method", "call", "location", "Determines", "if", "a", "string", "literal", "was", "used", "or", "not" ]
13557936b35b59d6b222287fd08d5421ce488f10
https://github.com/schneems/let_it_go/blob/13557936b35b59d6b222287fd08d5421ce488f10/lib/let_it_go/method_call.rb#L72-L78
3,431
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.refine
def refine(data) @task ||= '' data = parse_data(data) return puts data if data.is_a?(String) evaluate_severities(data) puts summarize if @config.is_dev? puts dev_format(data) ceiling_warning else # Because this should be returned in the format it was received @output[:raw_data] = data.to_json end @output end
ruby
def refine(data) @task ||= '' data = parse_data(data) return puts data if data.is_a?(String) evaluate_severities(data) puts summarize if @config.is_dev? puts dev_format(data) ceiling_warning else # Because this should be returned in the format it was received @output[:raw_data] = data.to_json end @output end
[ "def", "refine", "(", "data", ")", "@task", "||=", "''", "data", "=", "parse_data", "(", "data", ")", "return", "puts", "data", "if", "data", ".", "is_a?", "(", "String", ")", "evaluate_severities", "(", "data", ")", "puts", "summarize", "if", "@config", ".", "is_dev?", "puts", "dev_format", "(", "data", ")", "ceiling_warning", "else", "# Because this should be returned in the format it was received", "@output", "[", ":raw_data", "]", "=", "data", ".", "to_json", "end", "@output", "end" ]
Perform a lint of relevant code All defined lints require a "result" method @example the result method in the child class def result @task = __method__.to_s @path ||= 'path/or/**/glob/to/files'' lint_data = JSON.parse(`some-command-line-linter`) @output[:files_inspected] ||= files_inspected(extension, delimiter, base_path_replacement) refine data_from_output end Inherits settings from {Config#initialize} @see Config#initialize @param opts [Hash] ({}) options passed directly to the lint @option opts [Hash] :git_files filename: file location @see GitControl#lints_and_stats @option opts [Array, String] :file_paths lint only specific files or directories Accepts globs too which is used to define paths from the URL @option opts [Config object] :config custom Maximus::Config object @return [void] this method is used to set up instance variables Convert raw data into warnings, errors, conventions or refactors. Use this wisely. @param data [Hash] unfiltered lint data @return [Hash] refined lint data and all the other bells and whistles
[ "Perform", "a", "lint", "of", "relevant", "code" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L51-L69
3,432
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.files_inspected
def files_inspected(ext, delimiter = ',', remove = @config.working_dir) @path.is_a?(Array) ? @path.split(delimiter) : file_list(@path, ext, remove) end
ruby
def files_inspected(ext, delimiter = ',', remove = @config.working_dir) @path.is_a?(Array) ? @path.split(delimiter) : file_list(@path, ext, remove) end
[ "def", "files_inspected", "(", "ext", ",", "delimiter", "=", "','", ",", "remove", "=", "@config", ".", "working_dir", ")", "@path", ".", "is_a?", "(", "Array", ")", "?", "@path", ".", "split", "(", "delimiter", ")", ":", "file_list", "(", "@path", ",", "ext", ",", "remove", ")", "end" ]
List all files inspected @param ext [String] extension to search for @param delimiter [String] comma or space separated @param remove [String] remove from all file names @return all_files [Array<string>] list of file names
[ "List", "all", "files", "inspected" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L79-L81
3,433
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.relevant_output
def relevant_output(lint, files) all_files = {} files.each do |file| # sometimes data will be blank but this is good - it means no errors were raised in the lint next if lint.blank? || file.blank? || !file.is_a?(Hash) || !file.key?(:filename) lint_file = lint[file[:filename]] next if lint_file.blank? expanded = lines_added_to_range(file) revert_name = strip_working_dir(file[:filename]) all_files[revert_name] = [] lint_file.each do |l| if expanded.include?(l['line'].to_i) all_files[revert_name] << l end end # If there's nothing there, then it definitely isn't a relevant lint all_files.delete(revert_name) if all_files[revert_name].blank? end @output[:files_linted] = all_files.keys all_files end
ruby
def relevant_output(lint, files) all_files = {} files.each do |file| # sometimes data will be blank but this is good - it means no errors were raised in the lint next if lint.blank? || file.blank? || !file.is_a?(Hash) || !file.key?(:filename) lint_file = lint[file[:filename]] next if lint_file.blank? expanded = lines_added_to_range(file) revert_name = strip_working_dir(file[:filename]) all_files[revert_name] = [] lint_file.each do |l| if expanded.include?(l['line'].to_i) all_files[revert_name] << l end end # If there's nothing there, then it definitely isn't a relevant lint all_files.delete(revert_name) if all_files[revert_name].blank? end @output[:files_linted] = all_files.keys all_files end
[ "def", "relevant_output", "(", "lint", ",", "files", ")", "all_files", "=", "{", "}", "files", ".", "each", "do", "|", "file", "|", "# sometimes data will be blank but this is good - it means no errors were raised in the lint", "next", "if", "lint", ".", "blank?", "||", "file", ".", "blank?", "||", "!", "file", ".", "is_a?", "(", "Hash", ")", "||", "!", "file", ".", "key?", "(", ":filename", ")", "lint_file", "=", "lint", "[", "file", "[", ":filename", "]", "]", "next", "if", "lint_file", ".", "blank?", "expanded", "=", "lines_added_to_range", "(", "file", ")", "revert_name", "=", "strip_working_dir", "(", "file", "[", ":filename", "]", ")", "all_files", "[", "revert_name", "]", "=", "[", "]", "lint_file", ".", "each", "do", "|", "l", "|", "if", "expanded", ".", "include?", "(", "l", "[", "'line'", "]", ".", "to_i", ")", "all_files", "[", "revert_name", "]", "<<", "l", "end", "end", "# If there's nothing there, then it definitely isn't a relevant lint", "all_files", ".", "delete", "(", "revert_name", ")", "if", "all_files", "[", "revert_name", "]", ".", "blank?", "end", "@output", "[", ":files_linted", "]", "=", "all_files", ".", "keys", "all_files", "end" ]
Compare lint output with lines changed in commit @param lint [Hash] output lint data @param files [Hash<String: String>] filename: filepath @return [Array] lints that match the lines in commit
[ "Compare", "lint", "output", "with", "lines", "changed", "in", "commit" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L87-L113
3,434
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.evaluate_severities
def evaluate_severities(data) @output[:lint_warnings] = [] @output[:lint_errors] = [] @output[:lint_conventions] = [] @output[:lint_refactors] = [] @output[:lint_fatals] = [] return if data.blank? data.each do |filename, error_list| error_list.each do |message| # so that :raw_data remains unaffected message = message.clone message.delete('length') message['filename'] = filename.nil? ? '' : strip_working_dir(filename) severity = "lint_#{message['severity']}s".to_sym message.delete('severity') @output[severity] << message if @output.key?(severity) end end @output end
ruby
def evaluate_severities(data) @output[:lint_warnings] = [] @output[:lint_errors] = [] @output[:lint_conventions] = [] @output[:lint_refactors] = [] @output[:lint_fatals] = [] return if data.blank? data.each do |filename, error_list| error_list.each do |message| # so that :raw_data remains unaffected message = message.clone message.delete('length') message['filename'] = filename.nil? ? '' : strip_working_dir(filename) severity = "lint_#{message['severity']}s".to_sym message.delete('severity') @output[severity] << message if @output.key?(severity) end end @output end
[ "def", "evaluate_severities", "(", "data", ")", "@output", "[", ":lint_warnings", "]", "=", "[", "]", "@output", "[", ":lint_errors", "]", "=", "[", "]", "@output", "[", ":lint_conventions", "]", "=", "[", "]", "@output", "[", ":lint_refactors", "]", "=", "[", "]", "@output", "[", ":lint_fatals", "]", "=", "[", "]", "return", "if", "data", ".", "blank?", "data", ".", "each", "do", "|", "filename", ",", "error_list", "|", "error_list", ".", "each", "do", "|", "message", "|", "# so that :raw_data remains unaffected", "message", "=", "message", ".", "clone", "message", ".", "delete", "(", "'length'", ")", "message", "[", "'filename'", "]", "=", "filename", ".", "nil?", "?", "''", ":", "strip_working_dir", "(", "filename", ")", "severity", "=", "\"lint_#{message['severity']}s\"", ".", "to_sym", "message", ".", "delete", "(", "'severity'", ")", "@output", "[", "severity", "]", "<<", "message", "if", "@output", ".", "key?", "(", "severity", ")", "end", "end", "@output", "end" ]
Add severities to @output @since 0.1.5 @param data [Hash]
[ "Add", "severities", "to" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L127-L148
3,435
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.summarize
def summarize success = @task.color(:green) success << ": " success << "[#{@output[:lint_warnings].length}]".color(:yellow) success << " [#{@output[:lint_errors].length}]".color(:red) if @task == 'rubocop' success << " [#{@output[:lint_conventions].length}]".color(:cyan) success << " [#{@output[:lint_refactors].length}]".color(:white) success << " [#{@output[:lint_fatals].length}]".color(:magenta) end success << "\n#{'Warning'.color(:red)}: #{@output[:lint_errors].length} errors found in #{@task}" if @output[:lint_errors].length > 0 success end
ruby
def summarize success = @task.color(:green) success << ": " success << "[#{@output[:lint_warnings].length}]".color(:yellow) success << " [#{@output[:lint_errors].length}]".color(:red) if @task == 'rubocop' success << " [#{@output[:lint_conventions].length}]".color(:cyan) success << " [#{@output[:lint_refactors].length}]".color(:white) success << " [#{@output[:lint_fatals].length}]".color(:magenta) end success << "\n#{'Warning'.color(:red)}: #{@output[:lint_errors].length} errors found in #{@task}" if @output[:lint_errors].length > 0 success end
[ "def", "summarize", "success", "=", "@task", ".", "color", "(", ":green", ")", "success", "<<", "\": \"", "success", "<<", "\"[#{@output[:lint_warnings].length}]\"", ".", "color", "(", ":yellow", ")", "success", "<<", "\" [#{@output[:lint_errors].length}]\"", ".", "color", "(", ":red", ")", "if", "@task", "==", "'rubocop'", "success", "<<", "\" [#{@output[:lint_conventions].length}]\"", ".", "color", "(", ":cyan", ")", "success", "<<", "\" [#{@output[:lint_refactors].length}]\"", ".", "color", "(", ":white", ")", "success", "<<", "\" [#{@output[:lint_fatals].length}]\"", ".", "color", "(", ":magenta", ")", "end", "success", "<<", "\"\\n#{'Warning'.color(:red)}: #{@output[:lint_errors].length} errors found in #{@task}\"", "if", "@output", "[", ":lint_errors", "]", ".", "length", ">", "0", "success", "end" ]
Send abbreviated results to console or to the log @return [String] console message to display
[ "Send", "abbreviated", "results", "to", "console", "or", "to", "the", "log" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L172-L185
3,436
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.ceiling_warning
def ceiling_warning lint_length = (@output[:lint_errors].length + @output[:lint_warnings].length + @output[:lint_conventions].length + @output[:lint_refactors].length + @output[:lint_fatals].length) return unless lint_length > 100 failed_task = @task.color(:green) errors = "#{lint_length} failures.".color(:red) errormsg = [ "You wouldn't stand a chance in Rome.\nResolve thy errors and train with #{failed_task} again.", "The gods frown upon you, mortal.\n#{failed_task}. Again.", "Do not embarrass the city. Fight another day. Use #{failed_task}.", "You are without honor. Replenish it with another #{failed_task}.", "You will never claim the throne with a performance like that.", "Pompeii has been lost.", "A wise choice. Do not be discouraged from another #{failed_task}." ].sample errormsg << "\n\n" go_on = prompt "\n#{errors} Continue? (y/n) " abort errormsg unless truthy?(go_on) end
ruby
def ceiling_warning lint_length = (@output[:lint_errors].length + @output[:lint_warnings].length + @output[:lint_conventions].length + @output[:lint_refactors].length + @output[:lint_fatals].length) return unless lint_length > 100 failed_task = @task.color(:green) errors = "#{lint_length} failures.".color(:red) errormsg = [ "You wouldn't stand a chance in Rome.\nResolve thy errors and train with #{failed_task} again.", "The gods frown upon you, mortal.\n#{failed_task}. Again.", "Do not embarrass the city. Fight another day. Use #{failed_task}.", "You are without honor. Replenish it with another #{failed_task}.", "You will never claim the throne with a performance like that.", "Pompeii has been lost.", "A wise choice. Do not be discouraged from another #{failed_task}." ].sample errormsg << "\n\n" go_on = prompt "\n#{errors} Continue? (y/n) " abort errormsg unless truthy?(go_on) end
[ "def", "ceiling_warning", "lint_length", "=", "(", "@output", "[", ":lint_errors", "]", ".", "length", "+", "@output", "[", ":lint_warnings", "]", ".", "length", "+", "@output", "[", ":lint_conventions", "]", ".", "length", "+", "@output", "[", ":lint_refactors", "]", ".", "length", "+", "@output", "[", ":lint_fatals", "]", ".", "length", ")", "return", "unless", "lint_length", ">", "100", "failed_task", "=", "@task", ".", "color", "(", ":green", ")", "errors", "=", "\"#{lint_length} failures.\"", ".", "color", "(", ":red", ")", "errormsg", "=", "[", "\"You wouldn't stand a chance in Rome.\\nResolve thy errors and train with #{failed_task} again.\"", ",", "\"The gods frown upon you, mortal.\\n#{failed_task}. Again.\"", ",", "\"Do not embarrass the city. Fight another day. Use #{failed_task}.\"", ",", "\"You are without honor. Replenish it with another #{failed_task}.\"", ",", "\"You will never claim the throne with a performance like that.\"", ",", "\"Pompeii has been lost.\"", ",", "\"A wise choice. Do not be discouraged from another #{failed_task}.\"", "]", ".", "sample", "errormsg", "<<", "\"\\n\\n\"", "go_on", "=", "prompt", "\"\\n#{errors} Continue? (y/n) \"", "abort", "errormsg", "unless", "truthy?", "(", "go_on", ")", "end" ]
If there's just too much to handle, through a warning. @param lint_length [Integer] count of how many lints @return [String] console message to display
[ "If", "there", "s", "just", "too", "much", "to", "handle", "through", "a", "warning", "." ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L190-L209
3,437
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.dev_format
def dev_format(errors = @output[:raw_data]) return if errors.blank? pretty_output = '' errors.each do |filename, error_list| filename = strip_working_dir(filename) pretty_output << "\n#{filename.color(:cyan).underline} \n" error_list.each do |message| pretty_output << severity_color(message['severity']) pretty_output << " #{message['line'].to_s.color(:blue)} #{message['linter'].color(:green)}: #{message['reason']} \n" end end pretty_output << "-----\n\n" pretty_output end
ruby
def dev_format(errors = @output[:raw_data]) return if errors.blank? pretty_output = '' errors.each do |filename, error_list| filename = strip_working_dir(filename) pretty_output << "\n#{filename.color(:cyan).underline} \n" error_list.each do |message| pretty_output << severity_color(message['severity']) pretty_output << " #{message['line'].to_s.color(:blue)} #{message['linter'].color(:green)}: #{message['reason']} \n" end end pretty_output << "-----\n\n" pretty_output end
[ "def", "dev_format", "(", "errors", "=", "@output", "[", ":raw_data", "]", ")", "return", "if", "errors", ".", "blank?", "pretty_output", "=", "''", "errors", ".", "each", "do", "|", "filename", ",", "error_list", "|", "filename", "=", "strip_working_dir", "(", "filename", ")", "pretty_output", "<<", "\"\\n#{filename.color(:cyan).underline} \\n\"", "error_list", ".", "each", "do", "|", "message", "|", "pretty_output", "<<", "severity_color", "(", "message", "[", "'severity'", "]", ")", "pretty_output", "<<", "\" #{message['line'].to_s.color(:blue)} #{message['linter'].color(:green)}: #{message['reason']} \\n\"", "end", "end", "pretty_output", "<<", "\"-----\\n\\n\"", "pretty_output", "end" ]
Dev display, executed only when called from command line @param errors [Hash] data from lint @return [String] console message to display
[ "Dev", "display", "executed", "only", "when", "called", "from", "command", "line" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L214-L228
3,438
wearefine/maximus
lib/maximus/lint.rb
Maximus.Lint.parse_data
def parse_data(data) # Prevent abortive empty JSON.parse error data = '{}' if data.blank? return "Error from #{@task}: #{data}" if data.is_a?(String) && data.include?('No such') data = JSON.parse(data) if data.is_a?(String) @output[:relevant_output] = relevant_output( data, @git_files ) unless @git_files.blank? data = @output[:relevant_output] unless @settings[:commit].blank? data end
ruby
def parse_data(data) # Prevent abortive empty JSON.parse error data = '{}' if data.blank? return "Error from #{@task}: #{data}" if data.is_a?(String) && data.include?('No such') data = JSON.parse(data) if data.is_a?(String) @output[:relevant_output] = relevant_output( data, @git_files ) unless @git_files.blank? data = @output[:relevant_output] unless @settings[:commit].blank? data end
[ "def", "parse_data", "(", "data", ")", "# Prevent abortive empty JSON.parse error", "data", "=", "'{}'", "if", "data", ".", "blank?", "return", "\"Error from #{@task}: #{data}\"", "if", "data", ".", "is_a?", "(", "String", ")", "&&", "data", ".", "include?", "(", "'No such'", ")", "data", "=", "JSON", ".", "parse", "(", "data", ")", "if", "data", ".", "is_a?", "(", "String", ")", "@output", "[", ":relevant_output", "]", "=", "relevant_output", "(", "data", ",", "@git_files", ")", "unless", "@git_files", ".", "blank?", "data", "=", "@output", "[", ":relevant_output", "]", "unless", "@settings", "[", ":commit", "]", ".", "blank?", "data", "end" ]
Handle data and generate relevant_output if appropriate @since 0.1.6 @see #refine @param data [String, Hash] @return [String, Hash] String if error, Hash if success
[ "Handle", "data", "and", "generate", "relevant_output", "if", "appropriate" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/lint.rb#L243-L254
3,439
tevren/biffbot
lib/biffbot/bulk.rb
Biffbot.Bulk.generate_post_body
def generate_post_body name, api_url, urls = [], options = {} post_body = {token: @token, name: name, apiUrl: api_url, urls: urls} options.each do |key, value| next unless %w(notifyEmail maxRounds notifyWebHook pageProcessPattern).include?(key.to_s) post_body[key] = value end post_body end
ruby
def generate_post_body name, api_url, urls = [], options = {} post_body = {token: @token, name: name, apiUrl: api_url, urls: urls} options.each do |key, value| next unless %w(notifyEmail maxRounds notifyWebHook pageProcessPattern).include?(key.to_s) post_body[key] = value end post_body end
[ "def", "generate_post_body", "name", ",", "api_url", ",", "urls", "=", "[", "]", ",", "options", "=", "{", "}", "post_body", "=", "{", "token", ":", "@token", ",", "name", ":", "name", ",", "apiUrl", ":", "api_url", ",", "urls", ":", "urls", "}", "options", ".", "each", "do", "|", "key", ",", "value", "|", "next", "unless", "%w(", "notifyEmail", "maxRounds", "notifyWebHook", "pageProcessPattern", ")", ".", "include?", "(", "key", ".", "to_s", ")", "post_body", "[", "key", "]", "=", "value", "end", "post_body", "end" ]
generate the POST body required for bulk job creation @param name [String] Desired name for bulk job @param api_url [String] Desired API url to use for urls @param urls [Array] An array of input urls to pass to bulk job @param options [Hash] An hash of options @return [Hash]
[ "generate", "the", "POST", "body", "required", "for", "bulk", "job", "creation" ]
bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3
https://github.com/tevren/biffbot/blob/bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3/lib/biffbot/bulk.rb#L40-L47
3,440
tevren/biffbot
lib/biffbot/bulk.rb
Biffbot.Bulk.retrieve_data
def retrieve_data jobName, _options = {} # TODO: add support for csv endpoint = "http://api.diffbot.com/v3/bulk/download/#{@token}-#{jobName}_data.json" JSON.parse(HTTParty.get(endpoint).body).each_pair do |key, value| self[key] = value end end
ruby
def retrieve_data jobName, _options = {} # TODO: add support for csv endpoint = "http://api.diffbot.com/v3/bulk/download/#{@token}-#{jobName}_data.json" JSON.parse(HTTParty.get(endpoint).body).each_pair do |key, value| self[key] = value end end
[ "def", "retrieve_data", "jobName", ",", "_options", "=", "{", "}", "# TODO: add support for csv", "endpoint", "=", "\"http://api.diffbot.com/v3/bulk/download/#{@token}-#{jobName}_data.json\"", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "endpoint", ")", ".", "body", ")", ".", "each_pair", "do", "|", "key", ",", "value", "|", "self", "[", "key", "]", "=", "value", "end", "end" ]
retrieve data per given jobName @param jobName [String] Name of bulk job @param _options [Hash] An hash of options @return [Hash]
[ "retrieve", "data", "per", "given", "jobName" ]
bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3
https://github.com/tevren/biffbot/blob/bf1f2aad39c2d5d9ba917f31ff6220f68581e8a3/lib/biffbot/bulk.rb#L71-L77
3,441
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.evaluate_settings
def evaluate_settings(settings_data = @settings) settings_data.each do |key, value| next if value.is_a?(FalseClass) value = {} if value.is_a?(TrueClass) case key when :jshint, :JSHint, :JShint value = load_config(value) jshint_ignore settings_data[key] @settings[:jshint] = temp_it('jshint.json', value.to_json) when :scsslint, :SCSSlint value = load_config(value) @settings[:scsslint] = temp_it('scsslint.yml', value.to_yaml) when :rubocop, :Rubocop, :RuboCop value = load_config(value) @settings[:rubocop] = temp_it('rubocop.yml', value.to_yaml) when :brakeman @settings[:brakeman] = settings_data[key] when :rails_best_practice, :railsbp @settings[:railsbp] = settings_data[key] when :stylestats, :Stylestats value = load_config(value) @settings[:stylestats] = temp_it('stylestats.json', value.to_json) when :phantomas, :Phantomas value = load_config(value) @settings[:phantomas] = temp_it('phantomas.json', value.to_json) when :wraith, :Wraith value = load_config(value) evaluate_for_wraith(value) # Configuration important to all of maximus when :is_dev, :log, :root_dir, :domain, :port, :paths, :commit @settings[key] = settings_data[key] end end @settings end
ruby
def evaluate_settings(settings_data = @settings) settings_data.each do |key, value| next if value.is_a?(FalseClass) value = {} if value.is_a?(TrueClass) case key when :jshint, :JSHint, :JShint value = load_config(value) jshint_ignore settings_data[key] @settings[:jshint] = temp_it('jshint.json', value.to_json) when :scsslint, :SCSSlint value = load_config(value) @settings[:scsslint] = temp_it('scsslint.yml', value.to_yaml) when :rubocop, :Rubocop, :RuboCop value = load_config(value) @settings[:rubocop] = temp_it('rubocop.yml', value.to_yaml) when :brakeman @settings[:brakeman] = settings_data[key] when :rails_best_practice, :railsbp @settings[:railsbp] = settings_data[key] when :stylestats, :Stylestats value = load_config(value) @settings[:stylestats] = temp_it('stylestats.json', value.to_json) when :phantomas, :Phantomas value = load_config(value) @settings[:phantomas] = temp_it('phantomas.json', value.to_json) when :wraith, :Wraith value = load_config(value) evaluate_for_wraith(value) # Configuration important to all of maximus when :is_dev, :log, :root_dir, :domain, :port, :paths, :commit @settings[key] = settings_data[key] end end @settings end
[ "def", "evaluate_settings", "(", "settings_data", "=", "@settings", ")", "settings_data", ".", "each", "do", "|", "key", ",", "value", "|", "next", "if", "value", ".", "is_a?", "(", "FalseClass", ")", "value", "=", "{", "}", "if", "value", ".", "is_a?", "(", "TrueClass", ")", "case", "key", "when", ":jshint", ",", ":JSHint", ",", ":JShint", "value", "=", "load_config", "(", "value", ")", "jshint_ignore", "settings_data", "[", "key", "]", "@settings", "[", ":jshint", "]", "=", "temp_it", "(", "'jshint.json'", ",", "value", ".", "to_json", ")", "when", ":scsslint", ",", ":SCSSlint", "value", "=", "load_config", "(", "value", ")", "@settings", "[", ":scsslint", "]", "=", "temp_it", "(", "'scsslint.yml'", ",", "value", ".", "to_yaml", ")", "when", ":rubocop", ",", ":Rubocop", ",", ":RuboCop", "value", "=", "load_config", "(", "value", ")", "@settings", "[", ":rubocop", "]", "=", "temp_it", "(", "'rubocop.yml'", ",", "value", ".", "to_yaml", ")", "when", ":brakeman", "@settings", "[", ":brakeman", "]", "=", "settings_data", "[", "key", "]", "when", ":rails_best_practice", ",", ":railsbp", "@settings", "[", ":railsbp", "]", "=", "settings_data", "[", "key", "]", "when", ":stylestats", ",", ":Stylestats", "value", "=", "load_config", "(", "value", ")", "@settings", "[", ":stylestats", "]", "=", "temp_it", "(", "'stylestats.json'", ",", "value", ".", "to_json", ")", "when", ":phantomas", ",", ":Phantomas", "value", "=", "load_config", "(", "value", ")", "@settings", "[", ":phantomas", "]", "=", "temp_it", "(", "'phantomas.json'", ",", "value", ".", "to_json", ")", "when", ":wraith", ",", ":Wraith", "value", "=", "load_config", "(", "value", ")", "evaluate_for_wraith", "(", "value", ")", "# Configuration important to all of maximus", "when", ":is_dev", ",", ":log", ",", ":root_dir", ",", ":domain", ",", ":port", ",", ":paths", ",", ":commit", "@settings", "[", "key", "]", "=", "settings_data", "[", "key", "]", "end", "end", "@settings", "end" ]
Global options for all of maximus @param opts [Hash] options passed directly to config @option opts [Boolean] :is_dev (false) whether or not the class was initialized from the command line @option opts [String, Boolean, nil] :log ('log/maximus_git.log') path to log file If not set, logger outputs to STDOUT @option opts [String, Boolean] :git_log (false) path to log file or don't log The git gem is very noisey @option opts [String] :root_dir base directory @option opts [String] :domain ('http://localhost') the host - used for Statistics @option opts [String, Integer] :port ('') port number - used for Statistics and appended to domain. If blank (false, empty string, etc.), will not append to domain @option opts [String, Array] :file_paths ('') path to files. Accepts glob notation @option opts [Hash] :paths ({home: '/'}) labeled relative path to URLs. Statistics only @option opts [String] :commit accepts sha, "working", "last", or "master". @option opts [String] :config_file ('maximus.yml') path to config file @option opts [Boolean] :compile_assets (true) compile and destroy assets automagically @option opts [String] :framework (nil) accepts 'rails' and 'middleman' (should only be used when calling Maximus from a Ruby script) @return [#load_config_file #group_families #evaluate_settings] this method is used to set up instance variables Set global options or generate appropriate config files for lints or statistics @param settings_data [Hash] (@settings) loaded data from the discovered maximus config file @return [Hash] paths to temp config files and static options These should be deleted with destroy_temp after read and loaded
[ "Global", "options", "for", "all", "of", "maximus" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L72-L120
3,442
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.destroy_temp
def destroy_temp(filename = nil) if filename.nil? @temp_files.each { |filename, file| file.unlink } @temp_files = {} else return if @temp_files[filename.to_sym].blank? @temp_files[filename.to_sym].unlink @temp_files.delete(filename.to_sym) end end
ruby
def destroy_temp(filename = nil) if filename.nil? @temp_files.each { |filename, file| file.unlink } @temp_files = {} else return if @temp_files[filename.to_sym].blank? @temp_files[filename.to_sym].unlink @temp_files.delete(filename.to_sym) end end
[ "def", "destroy_temp", "(", "filename", "=", "nil", ")", "if", "filename", ".", "nil?", "@temp_files", ".", "each", "{", "|", "filename", ",", "file", "|", "file", ".", "unlink", "}", "@temp_files", "=", "{", "}", "else", "return", "if", "@temp_files", "[", "filename", ".", "to_sym", "]", ".", "blank?", "@temp_files", "[", "filename", ".", "to_sym", "]", ".", "unlink", "@temp_files", ".", "delete", "(", "filename", ".", "to_sym", ")", "end", "end" ]
Remove all or one created temporary config file @see temp_it @param filename [String] (nil) file to destroy If nil, destroy all temp files
[ "Remove", "all", "or", "one", "created", "temporary", "config", "file" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L139-L148
3,443
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.load_config_file
def load_config_file(file_path, root) conf_location = if file_path.present? && File.exist?(file_path) file_path else config_exists('.maximus.yml', root) || config_exists('maximus.yml', root) || config_exists('config/maximus.yml', root) end return {} if conf_location.is_a?(FalseClass) yaml = YAML.load_file conf_location yaml = {} if yaml.blank? yaml.symbolize_keys end
ruby
def load_config_file(file_path, root) conf_location = if file_path.present? && File.exist?(file_path) file_path else config_exists('.maximus.yml', root) || config_exists('maximus.yml', root) || config_exists('config/maximus.yml', root) end return {} if conf_location.is_a?(FalseClass) yaml = YAML.load_file conf_location yaml = {} if yaml.blank? yaml.symbolize_keys end
[ "def", "load_config_file", "(", "file_path", ",", "root", ")", "conf_location", "=", "if", "file_path", ".", "present?", "&&", "File", ".", "exist?", "(", "file_path", ")", "file_path", "else", "config_exists", "(", "'.maximus.yml'", ",", "root", ")", "||", "config_exists", "(", "'maximus.yml'", ",", "root", ")", "||", "config_exists", "(", "'config/maximus.yml'", ",", "root", ")", "end", "return", "{", "}", "if", "conf_location", ".", "is_a?", "(", "FalseClass", ")", "yaml", "=", "YAML", ".", "load_file", "conf_location", "yaml", "=", "{", "}", "if", "yaml", ".", "blank?", "yaml", ".", "symbolize_keys", "end" ]
Look for a maximus config file Checks ./maximus.yml, ./.maximus.yml, ./config/maximus.yml in order. If there hasn't been a file discovered yet, checks ./config/maximus.yml and if there still isn't a file, load the default one included with the maximus gem. @since 0.1.4 @param file_path [String] @param root [String] file path to root directory @return @settings [Hash]
[ "Look", "for", "a", "maximus", "config", "file" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L170-L184
3,444
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.set_families
def set_families(head_of_house, family) if @settings.key?(head_of_house) family.each { |f| @settings[f] ||= @settings[head_of_house].is_a?(TrueClass) } end end
ruby
def set_families(head_of_house, family) if @settings.key?(head_of_house) family.each { |f| @settings[f] ||= @settings[head_of_house].is_a?(TrueClass) } end end
[ "def", "set_families", "(", "head_of_house", ",", "family", ")", "if", "@settings", ".", "key?", "(", "head_of_house", ")", "family", ".", "each", "{", "|", "f", "|", "@settings", "[", "f", "]", "||=", "@settings", "[", "head_of_house", "]", ".", "is_a?", "(", "TrueClass", ")", "}", "end", "end" ]
Allow shorthand to be declared for groups Maximus executions @example disable statistics @settings[:statistics] = false set_families('statistics', ['phantomas', 'stylestats', 'wraith']) Sets as Boolean based on whether or not the queried label is `true` @param head_of_house [String] @settings key and group label @param family [Array] group of other @settings keys to be disabled @return [void] modified @settings
[ "Allow", "shorthand", "to", "be", "declared", "for", "groups", "Maximus", "executions" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L196-L200
3,445
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.load_config
def load_config(value) return value unless value.is_a?(String) if value =~ /^http/ begin open(value) YAML.load open(value).read rescue puts "#{value} not accessible" {} end elsif File.exist?(value) YAML.load_file(value) else puts "#{value} not found" {} end end
ruby
def load_config(value) return value unless value.is_a?(String) if value =~ /^http/ begin open(value) YAML.load open(value).read rescue puts "#{value} not accessible" {} end elsif File.exist?(value) YAML.load_file(value) else puts "#{value} not found" {} end end
[ "def", "load_config", "(", "value", ")", "return", "value", "unless", "value", ".", "is_a?", "(", "String", ")", "if", "value", "=~", "/", "/", "begin", "open", "(", "value", ")", "YAML", ".", "load", "open", "(", "value", ")", ".", "read", "rescue", "puts", "\"#{value} not accessible\"", "{", "}", "end", "elsif", "File", ".", "exist?", "(", "value", ")", "YAML", ".", "load_file", "(", "value", ")", "else", "puts", "\"#{value} not found\"", "{", "}", "end", "end" ]
Load config files if filename supplied @param value [Mixed] value from base config file @param [Hash] return blank hash if file not found so the reset of the process doesn't break
[ "Load", "config", "files", "if", "filename", "supplied" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L207-L224
3,446
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.temp_it
def temp_it(filename, data) ext = filename.split('.') file = Tempfile.new([filename, ".#{ext[1]}"]).tap do |f| f.rewind f.write(data) f.close end @temp_files[ext[0].to_sym] = file file.path end
ruby
def temp_it(filename, data) ext = filename.split('.') file = Tempfile.new([filename, ".#{ext[1]}"]).tap do |f| f.rewind f.write(data) f.close end @temp_files[ext[0].to_sym] = file file.path end
[ "def", "temp_it", "(", "filename", ",", "data", ")", "ext", "=", "filename", ".", "split", "(", "'.'", ")", "file", "=", "Tempfile", ".", "new", "(", "[", "filename", ",", "\".#{ext[1]}\"", "]", ")", ".", "tap", "do", "|", "f", "|", "f", ".", "rewind", "f", ".", "write", "(", "data", ")", "f", ".", "close", "end", "@temp_files", "[", "ext", "[", "0", "]", ".", "to_sym", "]", "=", "file", "file", ".", "path", "end" ]
Create a temp file with config data Stores all temp files in @temp_files or self.temp_files In Hash with filename minus extension as the key. @param filename [String] the preferred name/identifier of the file @param data [Mixed] config data important to each lint or statistic @return [String] absolute path to new config file
[ "Create", "a", "temp", "file", "with", "config", "data" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L234-L243
3,447
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.split_paths
def split_paths(paths) new_paths = {} paths.each do |p| if p.split('/').length > 1 new_paths[p.split('/').last.to_s] = p else new_paths['home'] = '/' end end new_paths end
ruby
def split_paths(paths) new_paths = {} paths.each do |p| if p.split('/').length > 1 new_paths[p.split('/').last.to_s] = p else new_paths['home'] = '/' end end new_paths end
[ "def", "split_paths", "(", "paths", ")", "new_paths", "=", "{", "}", "paths", ".", "each", "do", "|", "p", "|", "if", "p", ".", "split", "(", "'/'", ")", ".", "length", ">", "1", "new_paths", "[", "p", ".", "split", "(", "'/'", ")", ".", "last", ".", "to_s", "]", "=", "p", "else", "new_paths", "[", "'home'", "]", "=", "'/'", "end", "end", "new_paths", "end" ]
Accounting for space-separated command line arrays @since 0.1.4 @param paths [Array] @return [Hash]
[ "Accounting", "for", "space", "-", "separated", "command", "line", "arrays" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L249-L259
3,448
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.wraith_setup
def wraith_setup(value, name = 'phantomjs') if @settings.key?(:urls) value['domains'] = @settings[:urls] else value['domains'] = {} # @see #domain value['domains']['main'] = domain end # Set wraith defaults unless they're already defined # Wraith requires this screen_width config to be present value['screen_widths'] ||= [1280, 1024, 767] value['fuzz'] ||= '20%' value['threshold'] ||= 0 value['paths'] = @settings[:paths] temp_it("#{name}.yaml", value.to_yaml) end
ruby
def wraith_setup(value, name = 'phantomjs') if @settings.key?(:urls) value['domains'] = @settings[:urls] else value['domains'] = {} # @see #domain value['domains']['main'] = domain end # Set wraith defaults unless they're already defined # Wraith requires this screen_width config to be present value['screen_widths'] ||= [1280, 1024, 767] value['fuzz'] ||= '20%' value['threshold'] ||= 0 value['paths'] = @settings[:paths] temp_it("#{name}.yaml", value.to_yaml) end
[ "def", "wraith_setup", "(", "value", ",", "name", "=", "'phantomjs'", ")", "if", "@settings", ".", "key?", "(", ":urls", ")", "value", "[", "'domains'", "]", "=", "@settings", "[", ":urls", "]", "else", "value", "[", "'domains'", "]", "=", "{", "}", "# @see #domain", "value", "[", "'domains'", "]", "[", "'main'", "]", "=", "domain", "end", "# Set wraith defaults unless they're already defined", "# Wraith requires this screen_width config to be present", "value", "[", "'screen_widths'", "]", "||=", "[", "1280", ",", "1024", ",", "767", "]", "value", "[", "'fuzz'", "]", "||=", "'20%'", "value", "[", "'threshold'", "]", "||=", "0", "value", "[", "'paths'", "]", "=", "@settings", "[", ":paths", "]", "temp_it", "(", "\"#{name}.yaml\"", ",", "value", ".", "to_yaml", ")", "end" ]
Wraith is a complicated gem with significant configuration @see yaml_evaluate, temp_it @param value [Hash] modified data from a wraith config or injected data @param name [String] ('wraith') config file name to write and eventually load @return [String] temp file path
[ "Wraith", "is", "a", "complicated", "gem", "with", "significant", "configuration" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L278-L296
3,449
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.config_exists
def config_exists(file, root) present_location = File.join(root, file) File.exist?(present_location) ? present_location : false end
ruby
def config_exists(file, root) present_location = File.join(root, file) File.exist?(present_location) ? present_location : false end
[ "def", "config_exists", "(", "file", ",", "root", ")", "present_location", "=", "File", ".", "join", "(", "root", ",", "file", ")", "File", ".", "exist?", "(", "present_location", ")", "?", "present_location", ":", "false", "end" ]
See if a config file exists @see load_config_file This is used exclusively for the load_config_file method @param file [String] file name @param root [String] file path to root directory @return [String, FalseClass] if file is found return the absolute path otherwise return false so we can keep checking
[ "See", "if", "a", "config", "file", "exists" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L349-L352
3,450
wearefine/maximus
lib/maximus/config.rb
Maximus.Config.jshint_ignore
def jshint_ignore(settings_data_key) return unless settings_data_key.is_a?(Hash) && settings_data_key.key?('jshintignore') jshintignore_file = [] settings_data_key['jshintignore'].each { |i| jshintignore_file << "#{i}\n" } @settings[:jshintignore] = temp_it('jshintignore.json', jshintignore_file) end
ruby
def jshint_ignore(settings_data_key) return unless settings_data_key.is_a?(Hash) && settings_data_key.key?('jshintignore') jshintignore_file = [] settings_data_key['jshintignore'].each { |i| jshintignore_file << "#{i}\n" } @settings[:jshintignore] = temp_it('jshintignore.json', jshintignore_file) end
[ "def", "jshint_ignore", "(", "settings_data_key", ")", "return", "unless", "settings_data_key", ".", "is_a?", "(", "Hash", ")", "&&", "settings_data_key", ".", "key?", "(", "'jshintignore'", ")", "jshintignore_file", "=", "[", "]", "settings_data_key", "[", "'jshintignore'", "]", ".", "each", "{", "|", "i", "|", "jshintignore_file", "<<", "\"#{i}\\n\"", "}", "@settings", "[", ":jshintignore", "]", "=", "temp_it", "(", "'jshintignore.json'", ",", "jshintignore_file", ")", "end" ]
Save jshintignore if available @since 0.1.7 @param settings_data_key [Hash] @return updates settings
[ "Save", "jshintignore", "if", "available" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/config.rb#L358-L364
3,451
ryanbreed/cef
lib/cef/event.rb
CEF.Event.format_prefix
def format_prefix values = CEF::PREFIX_ATTRIBUTES.keys.map { |k| self.send(k) } escaped = values.map do |value| escape_prefix_value(value) end escaped.join('|') end
ruby
def format_prefix values = CEF::PREFIX_ATTRIBUTES.keys.map { |k| self.send(k) } escaped = values.map do |value| escape_prefix_value(value) end escaped.join('|') end
[ "def", "format_prefix", "values", "=", "CEF", "::", "PREFIX_ATTRIBUTES", ".", "keys", ".", "map", "{", "|", "k", "|", "self", ".", "send", "(", "k", ")", "}", "escaped", "=", "values", ".", "map", "do", "|", "value", "|", "escape_prefix_value", "(", "value", ")", "end", "escaped", ".", "join", "(", "'|'", ")", "end" ]
returns a pipe-delimeted list of prefix attributes
[ "returns", "a", "pipe", "-", "delimeted", "list", "of", "prefix", "attributes" ]
99a717b392c796377eaa70be0baa9bfce3e30379
https://github.com/ryanbreed/cef/blob/99a717b392c796377eaa70be0baa9bfce3e30379/lib/cef/event.rb#L109-L115
3,452
ryanbreed/cef
lib/cef/event.rb
CEF.Event.format_extension
def format_extension extensions = CEF::EXTENSION_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::EXTENSION_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end # make sure time comes out as milliseconds since epoch times = CEF::TIME_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::TIME_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end (extensions + times).compact.join(" ") end
ruby
def format_extension extensions = CEF::EXTENSION_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::EXTENSION_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end # make sure time comes out as milliseconds since epoch times = CEF::TIME_ATTRIBUTES.keys.map do |meth| value = self.send(meth) next if value.nil? shortname = CEF::TIME_ATTRIBUTES[meth] [shortname, escape_extension_value(value)].join("=") end (extensions + times).compact.join(" ") end
[ "def", "format_extension", "extensions", "=", "CEF", "::", "EXTENSION_ATTRIBUTES", ".", "keys", ".", "map", "do", "|", "meth", "|", "value", "=", "self", ".", "send", "(", "meth", ")", "next", "if", "value", ".", "nil?", "shortname", "=", "CEF", "::", "EXTENSION_ATTRIBUTES", "[", "meth", "]", "[", "shortname", ",", "escape_extension_value", "(", "value", ")", "]", ".", "join", "(", "\"=\"", ")", "end", "# make sure time comes out as milliseconds since epoch", "times", "=", "CEF", "::", "TIME_ATTRIBUTES", ".", "keys", ".", "map", "do", "|", "meth", "|", "value", "=", "self", ".", "send", "(", "meth", ")", "next", "if", "value", ".", "nil?", "shortname", "=", "CEF", "::", "TIME_ATTRIBUTES", "[", "meth", "]", "[", "shortname", ",", "escape_extension_value", "(", "value", ")", "]", ".", "join", "(", "\"=\"", ")", "end", "(", "extensions", "+", "times", ")", ".", "compact", ".", "join", "(", "\" \"", ")", "end" ]
returns a space-delimeted list of attribute=value pairs for all optionals
[ "returns", "a", "space", "-", "delimeted", "list", "of", "attribute", "=", "value", "pairs", "for", "all", "optionals" ]
99a717b392c796377eaa70be0baa9bfce3e30379
https://github.com/ryanbreed/cef/blob/99a717b392c796377eaa70be0baa9bfce3e30379/lib/cef/event.rb#L118-L134
3,453
adonespitogo/unsakini
app/controllers/unsakini/share_board_controller.rb
Unsakini.ShareBoardController.validate_params
def validate_params if params[:encrypted_password].nil? or params[:shared_user_ids].nil? or params[:board].nil? render json: {}, status: 422 return end result = has_board_access(params[:board][:id]) if result[:status] != :ok render json: {}, status: result[:status] return else if !result[:user_board].is_admin render json: {}, status: :forbidden return end @board = result[:board] @user_board = result[:user_board] end if params[:posts] params[:posts].each do |post| s = has_post_access(params[:board][:id], post[:id])[:status] if s != :ok render json: {}, status: s return end if post[:comments] post[:comments].each do |comment| s = has_comment_access(post[:id], comment[:id])[:status] if s != :ok render json: {}, status: s return end end end end end end
ruby
def validate_params if params[:encrypted_password].nil? or params[:shared_user_ids].nil? or params[:board].nil? render json: {}, status: 422 return end result = has_board_access(params[:board][:id]) if result[:status] != :ok render json: {}, status: result[:status] return else if !result[:user_board].is_admin render json: {}, status: :forbidden return end @board = result[:board] @user_board = result[:user_board] end if params[:posts] params[:posts].each do |post| s = has_post_access(params[:board][:id], post[:id])[:status] if s != :ok render json: {}, status: s return end if post[:comments] post[:comments].each do |comment| s = has_comment_access(post[:id], comment[:id])[:status] if s != :ok render json: {}, status: s return end end end end end end
[ "def", "validate_params", "if", "params", "[", ":encrypted_password", "]", ".", "nil?", "or", "params", "[", ":shared_user_ids", "]", ".", "nil?", "or", "params", "[", ":board", "]", ".", "nil?", "render", "json", ":", "{", "}", ",", "status", ":", "422", "return", "end", "result", "=", "has_board_access", "(", "params", "[", ":board", "]", "[", ":id", "]", ")", "if", "result", "[", ":status", "]", "!=", ":ok", "render", "json", ":", "{", "}", ",", "status", ":", "result", "[", ":status", "]", "return", "else", "if", "!", "result", "[", ":user_board", "]", ".", "is_admin", "render", "json", ":", "{", "}", ",", "status", ":", ":forbidden", "return", "end", "@board", "=", "result", "[", ":board", "]", "@user_board", "=", "result", "[", ":user_board", "]", "end", "if", "params", "[", ":posts", "]", "params", "[", ":posts", "]", ".", "each", "do", "|", "post", "|", "s", "=", "has_post_access", "(", "params", "[", ":board", "]", "[", ":id", "]", ",", "post", "[", ":id", "]", ")", "[", ":status", "]", "if", "s", "!=", ":ok", "render", "json", ":", "{", "}", ",", "status", ":", "s", "return", "end", "if", "post", "[", ":comments", "]", "post", "[", ":comments", "]", ".", "each", "do", "|", "comment", "|", "s", "=", "has_comment_access", "(", "post", "[", ":id", "]", ",", "comment", "[", ":id", "]", ")", "[", ":status", "]", "if", "s", "!=", ":ok", "render", "json", ":", "{", "}", ",", "status", ":", "s", "return", "end", "end", "end", "end", "end", "end" ]
Validates the contents of params against the database records.
[ "Validates", "the", "contents", "of", "params", "against", "the", "database", "records", "." ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/share_board_controller.rb#L75-L118
3,454
adonespitogo/unsakini
app/controllers/unsakini/users_controller.rb
Unsakini.UsersController.create
def create user = User.new(user_params) if user.save UserMailer.confirm_account(user).deliver_now render json: user, status: :created else render json: user.errors, status: 422 end end
ruby
def create user = User.new(user_params) if user.save UserMailer.confirm_account(user).deliver_now render json: user, status: :created else render json: user.errors, status: 422 end end
[ "def", "create", "user", "=", "User", ".", "new", "(", "user_params", ")", "if", "user", ".", "save", "UserMailer", ".", "confirm_account", "(", "user", ")", ".", "deliver_now", "render", "json", ":", "user", ",", "status", ":", ":created", "else", "render", "json", ":", "user", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Creates a new user
[ "Creates", "a", "new", "user" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/users_controller.rb#L11-L20
3,455
adonespitogo/unsakini
app/controllers/unsakini/users_controller.rb
Unsakini.UsersController.confirm
def confirm token = params[:token].to_s user = User.find_by(confirmation_token: token) if user.present? && user.confirmation_token_valid? if user.mark_as_confirmed! render json: {status: 'Account confirmed successfully.'} else render json: user.errors, status: 422 end else render json: ['Invalid token'], status: :not_found end end
ruby
def confirm token = params[:token].to_s user = User.find_by(confirmation_token: token) if user.present? && user.confirmation_token_valid? if user.mark_as_confirmed! render json: {status: 'Account confirmed successfully.'} else render json: user.errors, status: 422 end else render json: ['Invalid token'], status: :not_found end end
[ "def", "confirm", "token", "=", "params", "[", ":token", "]", ".", "to_s", "user", "=", "User", ".", "find_by", "(", "confirmation_token", ":", "token", ")", "if", "user", ".", "present?", "&&", "user", ".", "confirmation_token_valid?", "if", "user", ".", "mark_as_confirmed!", "render", "json", ":", "{", "status", ":", "'Account confirmed successfully.'", "}", "else", "render", "json", ":", "user", ".", "errors", ",", "status", ":", "422", "end", "else", "render", "json", ":", "[", "'Invalid token'", "]", ",", "status", ":", ":not_found", "end", "end" ]
confirm user account
[ "confirm", "user", "account" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/users_controller.rb#L23-L37
3,456
adonespitogo/unsakini
app/controllers/unsakini/users_controller.rb
Unsakini.UsersController.search
def search user = User.where("email = ? AND id != ?", params[:email], @user.id).first if user render json: user else render json: {}, status: :not_found end end
ruby
def search user = User.where("email = ? AND id != ?", params[:email], @user.id).first if user render json: user else render json: {}, status: :not_found end end
[ "def", "search", "user", "=", "User", ".", "where", "(", "\"email = ? AND id != ?\"", ",", "params", "[", ":email", "]", ",", "@user", ".", "id", ")", ".", "first", "if", "user", "render", "json", ":", "user", "else", "render", "json", ":", "{", "}", ",", "status", ":", ":not_found", "end", "end" ]
Returns the user with matching email `GET /api/users/search?email=xxx`
[ "Returns", "the", "user", "with", "matching", "email" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/users_controller.rb#L51-L58
3,457
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.commit_export
def commit_export(commit_sha = head_sha) commit_sha = commit_sha.to_s ce_commit = @g.gcommit(commit_sha) if first_commit == commit_sha ce_diff = diff_initial(first_commit) else last_commit = @g.gcommit(previous_commit(commit_sha)) ce_diff = diff(last_commit, ce_commit) end { commit_sha: commit_sha, branch: branch, message: ce_commit.message, remote_repo: remote, git_author: ce_commit.author.name, git_author_email: ce_commit.author.email, commit_date: ce_commit.author.date.to_s, diff: ce_diff } end
ruby
def commit_export(commit_sha = head_sha) commit_sha = commit_sha.to_s ce_commit = @g.gcommit(commit_sha) if first_commit == commit_sha ce_diff = diff_initial(first_commit) else last_commit = @g.gcommit(previous_commit(commit_sha)) ce_diff = diff(last_commit, ce_commit) end { commit_sha: commit_sha, branch: branch, message: ce_commit.message, remote_repo: remote, git_author: ce_commit.author.name, git_author_email: ce_commit.author.email, commit_date: ce_commit.author.date.to_s, diff: ce_diff } end
[ "def", "commit_export", "(", "commit_sha", "=", "head_sha", ")", "commit_sha", "=", "commit_sha", ".", "to_s", "ce_commit", "=", "@g", ".", "gcommit", "(", "commit_sha", ")", "if", "first_commit", "==", "commit_sha", "ce_diff", "=", "diff_initial", "(", "first_commit", ")", "else", "last_commit", "=", "@g", ".", "gcommit", "(", "previous_commit", "(", "commit_sha", ")", ")", "ce_diff", "=", "diff", "(", "last_commit", ",", "ce_commit", ")", "end", "{", "commit_sha", ":", "commit_sha", ",", "branch", ":", "branch", ",", "message", ":", "ce_commit", ".", "message", ",", "remote_repo", ":", "remote", ",", "git_author", ":", "ce_commit", ".", "author", ".", "name", ",", "git_author_email", ":", "ce_commit", ".", "author", ".", "email", ",", "commit_date", ":", "ce_commit", ".", "author", ".", "date", ".", "to_s", ",", "diff", ":", "ce_diff", "}", "end" ]
Set up instance variables Inherits settings from {Config#initialize} @param opts [Hash] options passed directly to config @option opts [Config object] :config custom Maximus::Config object @option opts [String] :commit accepts sha, "working", "last", or "master". 30,000 foot view of a commit @param commit_sha [String] (head_sha) the sha of the commit @return [Hash] commit data
[ "Set", "up", "instance", "variables" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L31-L53
3,458
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.compare
def compare(sha1 = master_commit_sha, sha2 = head_sha) diff_return = {} sha1 = define_psuedo_commit if @settings[:commit] # Reverse so that we go in chronological order git_spread = commit_range(sha1, sha2).reverse git_spread.each do |git_sha| # Grab all files in that commit and group them by extension # If working copy, just give the diff names of the files changed files = @psuedo_commit ? working_copy_files : files_by_sha(git_sha) diff_return[git_sha] = match_associations(git_sha, files) end diff_return end
ruby
def compare(sha1 = master_commit_sha, sha2 = head_sha) diff_return = {} sha1 = define_psuedo_commit if @settings[:commit] # Reverse so that we go in chronological order git_spread = commit_range(sha1, sha2).reverse git_spread.each do |git_sha| # Grab all files in that commit and group them by extension # If working copy, just give the diff names of the files changed files = @psuedo_commit ? working_copy_files : files_by_sha(git_sha) diff_return[git_sha] = match_associations(git_sha, files) end diff_return end
[ "def", "compare", "(", "sha1", "=", "master_commit_sha", ",", "sha2", "=", "head_sha", ")", "diff_return", "=", "{", "}", "sha1", "=", "define_psuedo_commit", "if", "@settings", "[", ":commit", "]", "# Reverse so that we go in chronological order", "git_spread", "=", "commit_range", "(", "sha1", ",", "sha2", ")", ".", "reverse", "git_spread", ".", "each", "do", "|", "git_sha", "|", "# Grab all files in that commit and group them by extension", "# If working copy, just give the diff names of the files changed", "files", "=", "@psuedo_commit", "?", "working_copy_files", ":", "files_by_sha", "(", "git_sha", ")", "diff_return", "[", "git_sha", "]", "=", "match_associations", "(", "git_sha", ",", "files", ")", "end", "diff_return", "end" ]
Compare two commits and get line number ranges of changed patches @example output from the method { 'sha': { rb: { filename: 'file.rb', changes: { ['0..4'], ['10..20'] } } } } @param sha1 [String] @param sha2 [String] @return [Hash] diff_return files changed grouped by file extension and line number
[ "Compare", "two", "commits", "and", "get", "line", "number", "ranges", "of", "changed", "patches" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L72-L89
3,459
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lints_and_stats
def lints_and_stats(lint_by_path = false, git_shas = compare, nuclear = false) return false if git_shas.blank? base_branch = branch git_ouput = {} git_shas.each do |sha, exts| create_branch(sha) unless @psuedo_commit sha = sha.to_s puts sha.color(:blue) exts.each do |ext, files| # For relevant_lines data lint_opts = { git_files: files, config: @config, file_paths: (lint_file_paths(files, ext) if lint_by_path) } git_ouput[sha] = nuclear ? lints_and_stats_nuclear(lint_opts) : lints_and_stats_switch(ext, lint_opts) end destroy_branch(base_branch, sha) unless @psuedo_commit end git_ouput end
ruby
def lints_and_stats(lint_by_path = false, git_shas = compare, nuclear = false) return false if git_shas.blank? base_branch = branch git_ouput = {} git_shas.each do |sha, exts| create_branch(sha) unless @psuedo_commit sha = sha.to_s puts sha.color(:blue) exts.each do |ext, files| # For relevant_lines data lint_opts = { git_files: files, config: @config, file_paths: (lint_file_paths(files, ext) if lint_by_path) } git_ouput[sha] = nuclear ? lints_and_stats_nuclear(lint_opts) : lints_and_stats_switch(ext, lint_opts) end destroy_branch(base_branch, sha) unless @psuedo_commit end git_ouput end
[ "def", "lints_and_stats", "(", "lint_by_path", "=", "false", ",", "git_shas", "=", "compare", ",", "nuclear", "=", "false", ")", "return", "false", "if", "git_shas", ".", "blank?", "base_branch", "=", "branch", "git_ouput", "=", "{", "}", "git_shas", ".", "each", "do", "|", "sha", ",", "exts", "|", "create_branch", "(", "sha", ")", "unless", "@psuedo_commit", "sha", "=", "sha", ".", "to_s", "puts", "sha", ".", "color", "(", ":blue", ")", "exts", ".", "each", "do", "|", "ext", ",", "files", "|", "# For relevant_lines data", "lint_opts", "=", "{", "git_files", ":", "files", ",", "config", ":", "@config", ",", "file_paths", ":", "(", "lint_file_paths", "(", "files", ",", "ext", ")", "if", "lint_by_path", ")", "}", "git_ouput", "[", "sha", "]", "=", "nuclear", "?", "lints_and_stats_nuclear", "(", "lint_opts", ")", ":", "lints_and_stats_switch", "(", "ext", ",", "lint_opts", ")", "end", "destroy_branch", "(", "base_branch", ",", "sha", ")", "unless", "@psuedo_commit", "end", "git_ouput", "end" ]
Run appropriate lint for every sha in commit history. For each sha a new branch is created then deleted @example sample output { 'sha': { lints: { scsslint: { files_inspec... }, }, statisti... }, 'sha'... } @see compare @param lint_by_path [Boolean] only lint by files in git commit and not the commit as a whole @param git_shas [Hash] (#compare) a hash of gitcommit shas and relevant file types in the commit @param nuclear [Boolean] do everything regardless of what's in the commit @return [Hash] data all data grouped by task
[ "Run", "appropriate", "lint", "for", "every", "sha", "in", "commit", "history", ".", "For", "each", "sha", "a", "new", "branch", "is", "created", "then", "deleted" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L114-L141
3,460
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.associations
def associations { css: ['css'], scss: ['scss', 'sass'], js: ['js'], ruby: ['rb', 'Gemfile', 'lock', 'yml', 'Rakefile', 'ru', 'rdoc', 'rake', 'Capfile', 'jbuilder'], rails: ['slim', 'haml', 'jbuilder', 'erb'], images: ['png', 'jpg', 'jpeg', 'gif'], static: ['pdf', 'txt', 'doc', 'docx', 'csv', 'xls', 'xlsx'], markup: ['html', 'xml', 'xhtml'], markdown: ['md', 'markdown', 'mdown'], php: ['php', 'ini'] } end
ruby
def associations { css: ['css'], scss: ['scss', 'sass'], js: ['js'], ruby: ['rb', 'Gemfile', 'lock', 'yml', 'Rakefile', 'ru', 'rdoc', 'rake', 'Capfile', 'jbuilder'], rails: ['slim', 'haml', 'jbuilder', 'erb'], images: ['png', 'jpg', 'jpeg', 'gif'], static: ['pdf', 'txt', 'doc', 'docx', 'csv', 'xls', 'xlsx'], markup: ['html', 'xml', 'xhtml'], markdown: ['md', 'markdown', 'mdown'], php: ['php', 'ini'] } end
[ "def", "associations", "{", "css", ":", "[", "'css'", "]", ",", "scss", ":", "[", "'scss'", ",", "'sass'", "]", ",", "js", ":", "[", "'js'", "]", ",", "ruby", ":", "[", "'rb'", ",", "'Gemfile'", ",", "'lock'", ",", "'yml'", ",", "'Rakefile'", ",", "'ru'", ",", "'rdoc'", ",", "'rake'", ",", "'Capfile'", ",", "'jbuilder'", "]", ",", "rails", ":", "[", "'slim'", ",", "'haml'", ",", "'jbuilder'", ",", "'erb'", "]", ",", "images", ":", "[", "'png'", ",", "'jpg'", ",", "'jpeg'", ",", "'gif'", "]", ",", "static", ":", "[", "'pdf'", ",", "'txt'", ",", "'doc'", ",", "'docx'", ",", "'csv'", ",", "'xls'", ",", "'xlsx'", "]", ",", "markup", ":", "[", "'html'", ",", "'xml'", ",", "'xhtml'", "]", ",", "markdown", ":", "[", "'md'", ",", "'markdown'", ",", "'mdown'", "]", ",", "php", ":", "[", "'php'", ",", "'ini'", "]", "}", "end" ]
Define associations to linters based on file extension @return [Hash] linters and extension arrays
[ "Define", "associations", "to", "linters", "based", "on", "file", "extension" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L145-L158
3,461
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.diff
def diff(old_commit, new_commit) stats = @g.diff(old_commit, new_commit).stats lines = lines_added(new_commit.sha) return if !lines.is_a?(Hash) || stats.blank? lines.each do |filename, filelines| stats[:files][filename][:lines_added] = filelines if stats[:files].key?(filename) end stats end
ruby
def diff(old_commit, new_commit) stats = @g.diff(old_commit, new_commit).stats lines = lines_added(new_commit.sha) return if !lines.is_a?(Hash) || stats.blank? lines.each do |filename, filelines| stats[:files][filename][:lines_added] = filelines if stats[:files].key?(filename) end stats end
[ "def", "diff", "(", "old_commit", ",", "new_commit", ")", "stats", "=", "@g", ".", "diff", "(", "old_commit", ",", "new_commit", ")", ".", "stats", "lines", "=", "lines_added", "(", "new_commit", ".", "sha", ")", "return", "if", "!", "lines", ".", "is_a?", "(", "Hash", ")", "||", "stats", ".", "blank?", "lines", ".", "each", "do", "|", "filename", ",", "filelines", "|", "stats", "[", ":files", "]", "[", "filename", "]", "[", ":lines_added", "]", "=", "filelines", "if", "stats", "[", ":files", "]", ".", "key?", "(", "filename", ")", "end", "stats", "end" ]
Get general stats of commit on HEAD versus last commit on master branch @modified 0.1.4 @param old_commit [Git::Object] @param new_commit [Git::Object] @return [Git::Diff] hash of abbreviated, useful stats with added lines
[ "Get", "general", "stats", "of", "commit", "on", "HEAD", "versus", "last", "commit", "on", "master", "branch" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L227-L237
3,462
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.diff_initial
def diff_initial(commit_sha) data = commit_information(commit_sha) value = { total: { insertions: 0, deletions: 0, lines: 0, files: data.length }, files: {} } data.each do |d| item = d.split("\t") insertions = item[0].to_i value[:total][:insertions] += insertions value[:total][:lines] += insertions value[:files][item[2]] = { insertions: insertions, deletions: 0, lines_added: ["0..#{item[0]}"] } end value end
ruby
def diff_initial(commit_sha) data = commit_information(commit_sha) value = { total: { insertions: 0, deletions: 0, lines: 0, files: data.length }, files: {} } data.each do |d| item = d.split("\t") insertions = item[0].to_i value[:total][:insertions] += insertions value[:total][:lines] += insertions value[:files][item[2]] = { insertions: insertions, deletions: 0, lines_added: ["0..#{item[0]}"] } end value end
[ "def", "diff_initial", "(", "commit_sha", ")", "data", "=", "commit_information", "(", "commit_sha", ")", "value", "=", "{", "total", ":", "{", "insertions", ":", "0", ",", "deletions", ":", "0", ",", "lines", ":", "0", ",", "files", ":", "data", ".", "length", "}", ",", "files", ":", "{", "}", "}", "data", ".", "each", "do", "|", "d", "|", "item", "=", "d", ".", "split", "(", "\"\\t\"", ")", "insertions", "=", "item", "[", "0", "]", ".", "to_i", "value", "[", ":total", "]", "[", ":insertions", "]", "+=", "insertions", "value", "[", ":total", "]", "[", ":lines", "]", "+=", "insertions", "value", "[", ":files", "]", "[", "item", "[", "2", "]", "]", "=", "{", "insertions", ":", "insertions", ",", "deletions", ":", "0", ",", "lines_added", ":", "[", "\"0..#{item[0]}\"", "]", "}", "end", "value", "end" ]
Get diff stats on just the initial commit Ruby-git doesn't support this well @see diff @since 0.1.5 @param commit_sha [String] @return [Hash] stat data similar to Ruby-git's Diff.stats return
[ "Get", "diff", "stats", "on", "just", "the", "initial", "commit", "Ruby", "-", "git", "doesn", "t", "support", "this", "well" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L245-L268
3,463
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.match_associations
def match_associations(commit_sha, files) new_lines = lines_added(commit_sha) files = files.split("\n").group_by { |f| f.split('.').pop } associations.each do |ext, related| files[ext] ||= [] related.each do |child| next if files[child].blank? files[child].each do |c| # hack to ignore deleted files files[child] = new_lines[c].blank? ? [] : [ filename: File.join(@config.working_dir, c), changes: new_lines[c] ] end files[ext].concat(files[child]) files.delete(child) end end files.delete_if { |k,v| v.blank? || k.nil? } files end
ruby
def match_associations(commit_sha, files) new_lines = lines_added(commit_sha) files = files.split("\n").group_by { |f| f.split('.').pop } associations.each do |ext, related| files[ext] ||= [] related.each do |child| next if files[child].blank? files[child].each do |c| # hack to ignore deleted files files[child] = new_lines[c].blank? ? [] : [ filename: File.join(@config.working_dir, c), changes: new_lines[c] ] end files[ext].concat(files[child]) files.delete(child) end end files.delete_if { |k,v| v.blank? || k.nil? } files end
[ "def", "match_associations", "(", "commit_sha", ",", "files", ")", "new_lines", "=", "lines_added", "(", "commit_sha", ")", "files", "=", "files", ".", "split", "(", "\"\\n\"", ")", ".", "group_by", "{", "|", "f", "|", "f", ".", "split", "(", "'.'", ")", ".", "pop", "}", "associations", ".", "each", "do", "|", "ext", ",", "related", "|", "files", "[", "ext", "]", "||=", "[", "]", "related", ".", "each", "do", "|", "child", "|", "next", "if", "files", "[", "child", "]", ".", "blank?", "files", "[", "child", "]", ".", "each", "do", "|", "c", "|", "# hack to ignore deleted files", "files", "[", "child", "]", "=", "new_lines", "[", "c", "]", ".", "blank?", "?", "[", "]", ":", "[", "filename", ":", "File", ".", "join", "(", "@config", ".", "working_dir", ",", "c", ")", ",", "changes", ":", "new_lines", "[", "c", "]", "]", "end", "files", "[", "ext", "]", ".", "concat", "(", "files", "[", "child", "]", ")", "files", ".", "delete", "(", "child", ")", "end", "end", "files", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "blank?", "||", "k", ".", "nil?", "}", "files", "end" ]
Associate files by extension and match their changes @since 0.1.5 @param commit_sha [String] @param files [String] list of files from git @return [Hash] files with matched extensions and changes
[ "Associate", "files", "by", "extension", "and", "match", "their", "changes" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L275-L296
3,464
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lints_and_stats_nuclear
def lints_and_stats_nuclear(lint_opts) { lints: { scsslint: Maximus::Scsslint.new(lint_opts).result, jshint: Maximus::Jshint.new(lint_opts).result, rubocop: Maximus::Rubocop.new(lint_opts).result, railsbp: Maximus::Railsbp.new(lint_opts).result, brakeman: Maximus::Brakeman.new(lint_opts).result }, statistics: { stylestat: Maximus::Stylestats.new({config: @config}).result, phantomas: Maximus::Phantomas.new({config: @config}).result, wraith: Maximus::Wraith.new({config: @config}).result } } end
ruby
def lints_and_stats_nuclear(lint_opts) { lints: { scsslint: Maximus::Scsslint.new(lint_opts).result, jshint: Maximus::Jshint.new(lint_opts).result, rubocop: Maximus::Rubocop.new(lint_opts).result, railsbp: Maximus::Railsbp.new(lint_opts).result, brakeman: Maximus::Brakeman.new(lint_opts).result }, statistics: { stylestat: Maximus::Stylestats.new({config: @config}).result, phantomas: Maximus::Phantomas.new({config: @config}).result, wraith: Maximus::Wraith.new({config: @config}).result } } end
[ "def", "lints_and_stats_nuclear", "(", "lint_opts", ")", "{", "lints", ":", "{", "scsslint", ":", "Maximus", "::", "Scsslint", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "jshint", ":", "Maximus", "::", "Jshint", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "rubocop", ":", "Maximus", "::", "Rubocop", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "railsbp", ":", "Maximus", "::", "Railsbp", ".", "new", "(", "lint_opts", ")", ".", "result", ",", "brakeman", ":", "Maximus", "::", "Brakeman", ".", "new", "(", "lint_opts", ")", ".", "result", "}", ",", "statistics", ":", "{", "stylestat", ":", "Maximus", "::", "Stylestats", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", ",", "phantomas", ":", "Maximus", "::", "Phantomas", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", ",", "wraith", ":", "Maximus", "::", "Wraith", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "}", "}", "end" ]
All data retrieved from reports @since 0.1.6 @param lint_opts [Hash] @return [Hash]
[ "All", "data", "retrieved", "from", "reports" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L302-L317
3,465
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lints_and_stats_switch
def lints_and_stats_switch(ext, lint_opts) result = { lints: {}, statistics: {} } lints = result[:lints] statistics = result[:statistics] case ext when :scss lints[:scsslint] = Maximus::Scsslint.new(lint_opts).result # @todo stylestat is singular here because model name in Rails is singular. # But adding a .classify when it's converted to a model chops off the end s on 'phantomas', # which breaks the model name. statistics[:stylestat] = Maximus::Stylestats.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :js lints[:jshint] = Maximus::Jshint.new(lint_opts).result statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :ruby lints[:rubocop] = Maximus::Rubocop.new(lint_opts).result lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result lints[:brakeman] = Maximus::Brakeman.new(lint_opts).result when :rails lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result end result end
ruby
def lints_and_stats_switch(ext, lint_opts) result = { lints: {}, statistics: {} } lints = result[:lints] statistics = result[:statistics] case ext when :scss lints[:scsslint] = Maximus::Scsslint.new(lint_opts).result # @todo stylestat is singular here because model name in Rails is singular. # But adding a .classify when it's converted to a model chops off the end s on 'phantomas', # which breaks the model name. statistics[:stylestat] = Maximus::Stylestats.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :js lints[:jshint] = Maximus::Jshint.new(lint_opts).result statistics[:phantomas] ||= Maximus::Phantomas.new({config: @config}).result # @todo double pipe here is best way to say, if it's already run, don't run again, right? statistics[:wraith] ||= Maximus::Wraith.new({config: @config}).result when :ruby lints[:rubocop] = Maximus::Rubocop.new(lint_opts).result lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result lints[:brakeman] = Maximus::Brakeman.new(lint_opts).result when :rails lints[:railsbp] ||= Maximus::Railsbp.new(lint_opts).result end result end
[ "def", "lints_and_stats_switch", "(", "ext", ",", "lint_opts", ")", "result", "=", "{", "lints", ":", "{", "}", ",", "statistics", ":", "{", "}", "}", "lints", "=", "result", "[", ":lints", "]", "statistics", "=", "result", "[", ":statistics", "]", "case", "ext", "when", ":scss", "lints", "[", ":scsslint", "]", "=", "Maximus", "::", "Scsslint", ".", "new", "(", "lint_opts", ")", ".", "result", "# @todo stylestat is singular here because model name in Rails is singular.", "# But adding a .classify when it's converted to a model chops off the end s on 'phantomas',", "# which breaks the model name.", "statistics", "[", ":stylestat", "]", "=", "Maximus", "::", "Stylestats", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "# @todo double pipe here is best way to say, if it's already run, don't run again, right?", "statistics", "[", ":phantomas", "]", "||=", "Maximus", "::", "Phantomas", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "statistics", "[", ":wraith", "]", "||=", "Maximus", "::", "Wraith", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "when", ":js", "lints", "[", ":jshint", "]", "=", "Maximus", "::", "Jshint", ".", "new", "(", "lint_opts", ")", ".", "result", "statistics", "[", ":phantomas", "]", "||=", "Maximus", "::", "Phantomas", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "# @todo double pipe here is best way to say, if it's already run, don't run again, right?", "statistics", "[", ":wraith", "]", "||=", "Maximus", "::", "Wraith", ".", "new", "(", "{", "config", ":", "@config", "}", ")", ".", "result", "when", ":ruby", "lints", "[", ":rubocop", "]", "=", "Maximus", "::", "Rubocop", ".", "new", "(", "lint_opts", ")", ".", "result", "lints", "[", ":railsbp", "]", "||=", "Maximus", "::", "Railsbp", ".", "new", "(", "lint_opts", ")", ".", "result", "lints", "[", ":brakeman", "]", "=", "Maximus", "::", "Brakeman", ".", "new", "(", "lint_opts", ")", ".", "result", "when", ":rails", "lints", "[", ":railsbp", "]", "||=", "Maximus", "::", "Railsbp", ".", "new", "(", "lint_opts", ")", ".", "result", "end", "result", "end" ]
Specific data retrieved by file extension @since 0.1.6 @param ext [String] @param lint_opts [Hash] @return [Hash]
[ "Specific", "data", "retrieved", "by", "file", "extension" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L324-L361
3,466
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.destroy_branch
def destroy_branch(base_branch, sha) if base_branch == "maximus_#{sha}" @g.branch('master').checkout else @g.branch(base_branch).checkout end @g.branch("maximus_#{sha}").delete end
ruby
def destroy_branch(base_branch, sha) if base_branch == "maximus_#{sha}" @g.branch('master').checkout else @g.branch(base_branch).checkout end @g.branch("maximus_#{sha}").delete end
[ "def", "destroy_branch", "(", "base_branch", ",", "sha", ")", "if", "base_branch", "==", "\"maximus_#{sha}\"", "@g", ".", "branch", "(", "'master'", ")", ".", "checkout", "else", "@g", ".", "branch", "(", "base_branch", ")", ".", "checkout", "end", "@g", ".", "branch", "(", "\"maximus_#{sha}\"", ")", ".", "delete", "end" ]
Destroy created branch @since 0.1.5 @param base_branch [String] branch we started on @param sha [String] used to check against created branch name
[ "Destroy", "created", "branch" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L377-L384
3,467
wearefine/maximus
lib/maximus/git_control.rb
Maximus.GitControl.lint_file_paths
def lint_file_paths(files, ext) file_list = files.map { |f| f[:filename] }.compact # Lints accept files differently ext == :ruby ? file_list.join(' ') : file_list.join(',') end
ruby
def lint_file_paths(files, ext) file_list = files.map { |f| f[:filename] }.compact # Lints accept files differently ext == :ruby ? file_list.join(' ') : file_list.join(',') end
[ "def", "lint_file_paths", "(", "files", ",", "ext", ")", "file_list", "=", "files", ".", "map", "{", "|", "f", "|", "f", "[", ":filename", "]", "}", ".", "compact", "# Lints accept files differently", "ext", "==", ":ruby", "?", "file_list", ".", "join", "(", "' '", ")", ":", "file_list", ".", "join", "(", "','", ")", "end" ]
Get list of file paths @param files [Hash] hash of files denoted by key 'filename' @param ext [String] file extension - different extensions are joined different ways @return [String] file paths delimited by comma or space
[ "Get", "list", "of", "file", "paths" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/git_control.rb#L390-L394
3,468
ronin-ruby/ronin-support
lib/ronin/path.rb
Ronin.Path.join
def join(*names) joined_path = if root? then '' else self.to_s end names.each do |name| name = name.to_s joined_path << @separator unless name.start_with?(@separator) joined_path << name unless name == @separator end return self.class.new(joined_path,@separator) end
ruby
def join(*names) joined_path = if root? then '' else self.to_s end names.each do |name| name = name.to_s joined_path << @separator unless name.start_with?(@separator) joined_path << name unless name == @separator end return self.class.new(joined_path,@separator) end
[ "def", "join", "(", "*", "names", ")", "joined_path", "=", "if", "root?", "then", "''", "else", "self", ".", "to_s", "end", "names", ".", "each", "do", "|", "name", "|", "name", "=", "name", ".", "to_s", "joined_path", "<<", "@separator", "unless", "name", ".", "start_with?", "(", "@separator", ")", "joined_path", "<<", "name", "unless", "name", "==", "@separator", "end", "return", "self", ".", "class", ".", "new", "(", "joined_path", ",", "@separator", ")", "end" ]
Joins directory names together with the path, but does not resolve the resulting path. @param [Array] names The names to join together. @return [Path] The joined path. @example Path.up(7).join('etc/passwd') # => #<Ronin::Path:../../../../../../../etc/passwd>
[ "Joins", "directory", "names", "together", "with", "the", "path", "but", "does", "not", "resolve", "the", "resulting", "path", "." ]
bc2af0e75098c13133789118245cb185f8c6b4c9
https://github.com/ronin-ruby/ronin-support/blob/bc2af0e75098c13133789118245cb185f8c6b4c9/lib/ronin/path.rb#L115-L128
3,469
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_claims
def validate_claims(options = {}) validate_exp(options[:max_clock_skew]) unless options[:ignore_exp] validate_nbf(options[:max_clock_skew]) unless options[:ignore_nbf] validate_iss(options[:valid_iss]) validate_aud(options[:valid_aud]) self end
ruby
def validate_claims(options = {}) validate_exp(options[:max_clock_skew]) unless options[:ignore_exp] validate_nbf(options[:max_clock_skew]) unless options[:ignore_nbf] validate_iss(options[:valid_iss]) validate_aud(options[:valid_aud]) self end
[ "def", "validate_claims", "(", "options", "=", "{", "}", ")", "validate_exp", "(", "options", "[", ":max_clock_skew", "]", ")", "unless", "options", "[", ":ignore_exp", "]", "validate_nbf", "(", "options", "[", ":max_clock_skew", "]", ")", "unless", "options", "[", ":ignore_nbf", "]", "validate_iss", "(", "options", "[", ":valid_iss", "]", ")", "validate_aud", "(", "options", "[", ":valid_aud", "]", ")", "self", "end" ]
Validates the set of claims. @param options [Hash] The claim validation options (see {Sandal::DEFAULT_OPTIONS} for details). @return [Hash] A reference to self. @raise [Sandal::ClaimError] One or more claims is invalid.
[ "Validates", "the", "set", "of", "claims", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L12-L18
3,470
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_exp
def validate_exp(max_clock_skew = 0) max_clock_skew ||= 0 exp = time_claim("exp") if exp && exp <= (Time.now - max_clock_skew) raise Sandal::ExpiredTokenError, "The token has expired." end end
ruby
def validate_exp(max_clock_skew = 0) max_clock_skew ||= 0 exp = time_claim("exp") if exp && exp <= (Time.now - max_clock_skew) raise Sandal::ExpiredTokenError, "The token has expired." end end
[ "def", "validate_exp", "(", "max_clock_skew", "=", "0", ")", "max_clock_skew", "||=", "0", "exp", "=", "time_claim", "(", "\"exp\"", ")", "if", "exp", "&&", "exp", "<=", "(", "Time", ".", "now", "-", "max_clock_skew", ")", "raise", "Sandal", "::", "ExpiredTokenError", ",", "\"The token has expired.\"", "end", "end" ]
Validates the expires claim. @param max_clock_skew [Numeric] The maximum clock skew, in seconds. @return [void]. @raise [Sandal::ClaimError] The "exp" claim is invalid, or the token has expired.
[ "Validates", "the", "expires", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L26-L33
3,471
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_nbf
def validate_nbf(max_clock_skew = 0) max_clock_skew ||= 0 nbf = time_claim("nbf") if nbf && nbf > (Time.now + max_clock_skew) raise Sandal::ClaimError, "The token is not valid yet." end end
ruby
def validate_nbf(max_clock_skew = 0) max_clock_skew ||= 0 nbf = time_claim("nbf") if nbf && nbf > (Time.now + max_clock_skew) raise Sandal::ClaimError, "The token is not valid yet." end end
[ "def", "validate_nbf", "(", "max_clock_skew", "=", "0", ")", "max_clock_skew", "||=", "0", "nbf", "=", "time_claim", "(", "\"nbf\"", ")", "if", "nbf", "&&", "nbf", ">", "(", "Time", ".", "now", "+", "max_clock_skew", ")", "raise", "Sandal", "::", "ClaimError", ",", "\"The token is not valid yet.\"", "end", "end" ]
Validates the not-before claim. @param max_clock_skew [Numeric] The maximum clock skew, in seconds. @return [void]. @raise [Sandal::ClaimError] The "nbf" claim is invalid, or the token is not valid yet.
[ "Validates", "the", "not", "-", "before", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L41-L48
3,472
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_iss
def validate_iss(valid_iss) return unless valid_iss && valid_iss.length > 0 unless valid_iss.include?(self["iss"]) raise Sandal::ClaimError, "The issuer is invalid." end end
ruby
def validate_iss(valid_iss) return unless valid_iss && valid_iss.length > 0 unless valid_iss.include?(self["iss"]) raise Sandal::ClaimError, "The issuer is invalid." end end
[ "def", "validate_iss", "(", "valid_iss", ")", "return", "unless", "valid_iss", "&&", "valid_iss", ".", "length", ">", "0", "unless", "valid_iss", ".", "include?", "(", "self", "[", "\"iss\"", "]", ")", "raise", "Sandal", "::", "ClaimError", ",", "\"The issuer is invalid.\"", "end", "end" ]
Validates the issuer claim. @param valid_iss [Array] The valid issuers. @return [void]. @raise [Sandal::ClaimError] The "iss" claim value is not a valid issuer.
[ "Validates", "the", "issuer", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L55-L61
3,473
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.validate_aud
def validate_aud(valid_aud) return unless valid_aud && valid_aud.length > 0 aud = self["aud"] aud = [aud] unless aud.is_a?(Array) unless (aud & valid_aud).length > 0 raise Sandal::ClaimError, "The audence is invalid." end end
ruby
def validate_aud(valid_aud) return unless valid_aud && valid_aud.length > 0 aud = self["aud"] aud = [aud] unless aud.is_a?(Array) unless (aud & valid_aud).length > 0 raise Sandal::ClaimError, "The audence is invalid." end end
[ "def", "validate_aud", "(", "valid_aud", ")", "return", "unless", "valid_aud", "&&", "valid_aud", ".", "length", ">", "0", "aud", "=", "self", "[", "\"aud\"", "]", "aud", "=", "[", "aud", "]", "unless", "aud", ".", "is_a?", "(", "Array", ")", "unless", "(", "aud", "&", "valid_aud", ")", ".", "length", ">", "0", "raise", "Sandal", "::", "ClaimError", ",", "\"The audence is invalid.\"", "end", "end" ]
Validates the audience claim. @param valid_aud [Array] The valid audiences. @return [void]. @raise [Sandal::ClaimError] The "aud" claim value does not contain a valid audience.
[ "Validates", "the", "audience", "claim", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L69-L77
3,474
gregbeech/sandal
lib/sandal/claims.rb
Sandal.Claims.time_claim
def time_claim(name) claim = self[name] if claim begin Time.at(claim) rescue raise Sandal::ClaimError, "The \"#{name}\" claim is invalid." end end end
ruby
def time_claim(name) claim = self[name] if claim begin Time.at(claim) rescue raise Sandal::ClaimError, "The \"#{name}\" claim is invalid." end end end
[ "def", "time_claim", "(", "name", ")", "claim", "=", "self", "[", "name", "]", "if", "claim", "begin", "Time", ".", "at", "(", "claim", ")", "rescue", "raise", "Sandal", "::", "ClaimError", ",", "\"The \\\"#{name}\\\" claim is invalid.\"", "end", "end", "end" ]
Gets the value of a claim as a Time.
[ "Gets", "the", "value", "of", "a", "claim", "as", "a", "Time", "." ]
ff965259af1572d74baab6d03fffa44b6c6e0224
https://github.com/gregbeech/sandal/blob/ff965259af1572d74baab6d03fffa44b6c6e0224/lib/sandal/claims.rb#L82-L91
3,475
paulsamuels/xcunique
lib/xcunique/sorter.rb
Xcunique.Sorter.sort
def sort objects.values.each do |object| SORTABLE_ITEMS.select { |key| object.has_key?(key) }.each do |key| object[key].sort_by!(&method(:comparator)) end end project end
ruby
def sort objects.values.each do |object| SORTABLE_ITEMS.select { |key| object.has_key?(key) }.each do |key| object[key].sort_by!(&method(:comparator)) end end project end
[ "def", "sort", "objects", ".", "values", ".", "each", "do", "|", "object", "|", "SORTABLE_ITEMS", ".", "select", "{", "|", "key", "|", "object", ".", "has_key?", "(", "key", ")", "}", ".", "each", "do", "|", "key", "|", "object", "[", "key", "]", ".", "sort_by!", "(", "method", "(", ":comparator", ")", ")", "end", "end", "project", "end" ]
Returns a new instance of Sorter @param project [Hash] the project to sort Traverses the objects in the project clone and sorts in place objects that are held under the `SORTABLE_ITEMS` keys @return [Hash] a sorted project
[ "Returns", "a", "new", "instance", "of", "Sorter" ]
0a95740109dc504734acf01dfbb979d09fb5d9fd
https://github.com/paulsamuels/xcunique/blob/0a95740109dc504734acf01dfbb979d09fb5d9fd/lib/xcunique/sorter.rb#L24-L31
3,476
paulsamuels/xcunique
lib/xcunique/sorter.rb
Xcunique.Sorter.comparator
def comparator uuid prefix = objects[uuid][Keys::ISA] == Keys::PBXGroup ? ' ' : '' prefix + Helpers.resolve_attributes(uuid, objects) end
ruby
def comparator uuid prefix = objects[uuid][Keys::ISA] == Keys::PBXGroup ? ' ' : '' prefix + Helpers.resolve_attributes(uuid, objects) end
[ "def", "comparator", "uuid", "prefix", "=", "objects", "[", "uuid", "]", "[", "Keys", "::", "ISA", "]", "==", "Keys", "::", "PBXGroup", "?", "' '", ":", "''", "prefix", "+", "Helpers", ".", "resolve_attributes", "(", "uuid", ",", "objects", ")", "end" ]
The comparator used during the sort The comparator resolves the attributes for the node and appends a known prefix to objects where `isa = PBXGroup` to ensure that groups are sorted above files @param uuid [String] the uuid of the object to examine @!visibility public
[ "The", "comparator", "used", "during", "the", "sort" ]
0a95740109dc504734acf01dfbb979d09fb5d9fd
https://github.com/paulsamuels/xcunique/blob/0a95740109dc504734acf01dfbb979d09fb5d9fd/lib/xcunique/sorter.rb#L45-L48
3,477
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.check
def check(filename, content) node = parse(filename, content) node.file = filename check_node(node) end
ruby
def check(filename, content) node = parse(filename, content) node.file = filename check_node(node) end
[ "def", "check", "(", "filename", ",", "content", ")", "node", "=", "parse", "(", "filename", ",", "content", ")", "node", ".", "file", "=", "filename", "check_node", "(", "node", ")", "end" ]
check the ruby sexp nodes for the ruby file. @param [String] filename is the filename of ruby code. @param [String] content is the content of ruby file.
[ "check", "the", "ruby", "sexp", "nodes", "for", "the", "ruby", "file", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L21-L25
3,478
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.after_check
def after_check @checkers.each do |checker| after_check_callbacks = checker.class.get_callbacks(:after_check) after_check_callbacks.each do |block| checker.instance_exec &block end end end
ruby
def after_check @checkers.each do |checker| after_check_callbacks = checker.class.get_callbacks(:after_check) after_check_callbacks.each do |block| checker.instance_exec &block end end end
[ "def", "after_check", "@checkers", ".", "each", "do", "|", "checker", "|", "after_check_callbacks", "=", "checker", ".", "class", ".", "get_callbacks", "(", ":after_check", ")", "after_check_callbacks", ".", "each", "do", "|", "block", "|", "checker", ".", "instance_exec", "block", "end", "end", "end" ]
trigger all after_check callbacks defined in all checkers.
[ "trigger", "all", "after_check", "callbacks", "defined", "in", "all", "checkers", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L28-L35
3,479
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.parse
def parse(filename, content) Sexp.from_array(Ripper::SexpBuilder.new(content).parse) rescue Exception raise AnalyzerException.new("#{filename} looks like it's not a valid Ruby file. Skipping...") end
ruby
def parse(filename, content) Sexp.from_array(Ripper::SexpBuilder.new(content).parse) rescue Exception raise AnalyzerException.new("#{filename} looks like it's not a valid Ruby file. Skipping...") end
[ "def", "parse", "(", "filename", ",", "content", ")", "Sexp", ".", "from_array", "(", "Ripper", "::", "SexpBuilder", ".", "new", "(", "content", ")", ".", "parse", ")", "rescue", "Exception", "raise", "AnalyzerException", ".", "new", "(", "\"#{filename} looks like it's not a valid Ruby file. Skipping...\"", ")", "end" ]
parse ruby code. @param [String] filename is the filename of ruby code. @param [String] content is the content of ruby file.
[ "parse", "ruby", "code", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L41-L45
3,480
flyerhzm/code_analyzer
lib/code_analyzer/checking_visitor/default.rb
CodeAnalyzer::CheckingVisitor.Default.check_node
def check_node(node) checkers = @checks[node.sexp_type] if checkers checkers.each { |checker| checker.node_start(node) if checker.parse_file?(node.file) } end node.children.each { |child_node| child_node.file = node.file check_node(child_node) } if checkers checkers.each { |checker| checker.node_end(node) if checker.parse_file?(node.file) } end end
ruby
def check_node(node) checkers = @checks[node.sexp_type] if checkers checkers.each { |checker| checker.node_start(node) if checker.parse_file?(node.file) } end node.children.each { |child_node| child_node.file = node.file check_node(child_node) } if checkers checkers.each { |checker| checker.node_end(node) if checker.parse_file?(node.file) } end end
[ "def", "check_node", "(", "node", ")", "checkers", "=", "@checks", "[", "node", ".", "sexp_type", "]", "if", "checkers", "checkers", ".", "each", "{", "|", "checker", "|", "checker", ".", "node_start", "(", "node", ")", "if", "checker", ".", "parse_file?", "(", "node", ".", "file", ")", "}", "end", "node", ".", "children", ".", "each", "{", "|", "child_node", "|", "child_node", ".", "file", "=", "node", ".", "file", "check_node", "(", "child_node", ")", "}", "if", "checkers", "checkers", ".", "each", "{", "|", "checker", "|", "checker", ".", "node_end", "(", "node", ")", "if", "checker", ".", "parse_file?", "(", "node", ".", "file", ")", "}", "end", "end" ]
recursively check ruby sexp node. 1. it triggers the interesting checkers' start callbacks. 2. recursively check the sexp children. 3. it triggers the interesting checkers' end callbacks.
[ "recursively", "check", "ruby", "sexp", "node", "." ]
f4d63ae835574b3e48a3154df3e0ce83457502bd
https://github.com/flyerhzm/code_analyzer/blob/f4d63ae835574b3e48a3154df3e0ce83457502bd/lib/code_analyzer/checking_visitor/default.rb#L52-L64
3,481
ryanbreed/cef
lib/cef/sender.rb
CEF.UDPSender.emit
def emit(event) self.socksetup if self.sock.nil? # process eventDefaults - we are expecting a hash here. These will # override any values in the events passed to us. i know. brutal. unless self.eventDefaults.nil? self.eventDefaults.each do |k,v| event.send("%s=" % k,v) end end self.sock.send event.to_s, 0 end
ruby
def emit(event) self.socksetup if self.sock.nil? # process eventDefaults - we are expecting a hash here. These will # override any values in the events passed to us. i know. brutal. unless self.eventDefaults.nil? self.eventDefaults.each do |k,v| event.send("%s=" % k,v) end end self.sock.send event.to_s, 0 end
[ "def", "emit", "(", "event", ")", "self", ".", "socksetup", "if", "self", ".", "sock", ".", "nil?", "# process eventDefaults - we are expecting a hash here. These will", "# override any values in the events passed to us. i know. brutal.", "unless", "self", ".", "eventDefaults", ".", "nil?", "self", ".", "eventDefaults", ".", "each", "do", "|", "k", ",", "v", "|", "event", ".", "send", "(", "\"%s=\"", "%", "k", ",", "v", ")", "end", "end", "self", ".", "sock", ".", "send", "event", ".", "to_s", ",", "0", "end" ]
fire the message off
[ "fire", "the", "message", "off" ]
99a717b392c796377eaa70be0baa9bfce3e30379
https://github.com/ryanbreed/cef/blob/99a717b392c796377eaa70be0baa9bfce3e30379/lib/cef/sender.rb#L22-L32
3,482
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.bind_meta_app
def bind_meta_app args={}, &block arg_string = args.values_at(:key, :listen_to, :respond_on, :application).join(" ") arg_string += "::#{args[:parameters]}" if args[:parameters] application "bind_meta_app", arg_string, &block end
ruby
def bind_meta_app args={}, &block arg_string = args.values_at(:key, :listen_to, :respond_on, :application).join(" ") arg_string += "::#{args[:parameters]}" if args[:parameters] application "bind_meta_app", arg_string, &block end
[ "def", "bind_meta_app", "args", "=", "{", "}", ",", "&", "block", "arg_string", "=", "args", ".", "values_at", "(", ":key", ",", ":listen_to", ",", ":respond_on", ",", ":application", ")", ".", "join", "(", "\" \"", ")", "arg_string", "+=", "\"::#{args[:parameters]}\"", "if", "args", "[", ":parameters", "]", "application", "\"bind_meta_app\"", ",", "arg_string", ",", "block", "end" ]
Binds an application to the specified call legs. @example bind_meta_app :key => 2, :listen_to => "a", :respond_on => "s", :application => "execute_extension", :parameters => "dx XML features" @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_bind_meta_app
[ "Binds", "an", "application", "to", "the", "specified", "call", "legs", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L32-L38
3,483
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.bridge
def bridge *args, &block variables = if args.last.is_a? Hash # We need to sort the key/value pairs to facilitate testing. # This can be removed once 1.8-compat is dropped. key_value_pairs = args.pop.sort {|x,y| x.to_s <=> y.to_s} key_value_pairs.map! {|k,v| "#{k}=#{v}"} "{#{key_value_pairs.join(",")}}" else "" end endpoints = if args.first.is_a? Array args.map {|e| e.join(",")}.join("|") else args.join "," end application "bridge", variables + endpoints, &block end
ruby
def bridge *args, &block variables = if args.last.is_a? Hash # We need to sort the key/value pairs to facilitate testing. # This can be removed once 1.8-compat is dropped. key_value_pairs = args.pop.sort {|x,y| x.to_s <=> y.to_s} key_value_pairs.map! {|k,v| "#{k}=#{v}"} "{#{key_value_pairs.join(",")}}" else "" end endpoints = if args.first.is_a? Array args.map {|e| e.join(",")}.join("|") else args.join "," end application "bridge", variables + endpoints, &block end
[ "def", "bridge", "*", "args", ",", "&", "block", "variables", "=", "if", "args", ".", "last", ".", "is_a?", "Hash", "# We need to sort the key/value pairs to facilitate testing.", "# This can be removed once 1.8-compat is dropped.", "key_value_pairs", "=", "args", ".", "pop", ".", "sort", "{", "|", "x", ",", "y", "|", "x", ".", "to_s", "<=>", "y", ".", "to_s", "}", "key_value_pairs", ".", "map!", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v}\"", "}", "\"{#{key_value_pairs.join(\",\")}}\"", "else", "\"\"", "end", "endpoints", "=", "if", "args", ".", "first", ".", "is_a?", "Array", "args", ".", "map", "{", "|", "e", "|", "e", ".", "join", "(", "\",\"", ")", "}", ".", "join", "(", "\"|\"", ")", "else", "args", ".", "join", "\",\"", "end", "application", "\"bridge\"", ",", "variables", "+", "endpoints", ",", "block", "end" ]
Bridges an incoming call to an endpoint, optionally taking an array of channel variables to set. If given an array of arrays, each contained array of endpoints will be called simultaneously, with the next array of endpoints as failover. See the examples below for different constructs and the callstring it sends to FreeSWITCH. @example bridge "user/coltrane", "user/backup-office" #=> user/coltrane,user/backup-office @example With channel variables bridge "user/coltrane", "user/backup-office", :some_var => "value" #=> {some_var=value}user/coltrane,user/backup-office @example With failover bridge ['user/coltrane', 'user/davis'], ['user/sun-ra', 'user/taylor'] #=> user/coltrane,user/davis|user/sun-ra,user/taylor @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_bridge
[ "Bridges", "an", "incoming", "call", "to", "an", "endpoint", "optionally", "taking", "an", "array", "of", "channel", "variables", "to", "set", ".", "If", "given", "an", "array", "of", "arrays", "each", "contained", "array", "of", "endpoints", "will", "be", "called", "simultaneously", "with", "the", "next", "array", "of", "endpoints", "as", "failover", ".", "See", "the", "examples", "below", "for", "different", "constructs", "and", "the", "callstring", "it", "sends", "to", "FreeSWITCH", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L56-L74
3,484
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.play_and_get_digits
def play_and_get_digits file, invalid_file, args={}, &block min = args[:min] || 1 max = args[:max] || 2 tries = args[:tries] || 3 terminators = args[:terminators] || "#" timeout = args[:timeout] || 5000 variable = args[:variable] || "read_digits_var" regexp = args[:regexp] || "\\d+" args = [min, max, tries, timeout, terminators, file, invalid_file, variable, regexp].join " " params = {:variable => variable} application "play_and_get_digits", args, params, &block end
ruby
def play_and_get_digits file, invalid_file, args={}, &block min = args[:min] || 1 max = args[:max] || 2 tries = args[:tries] || 3 terminators = args[:terminators] || "#" timeout = args[:timeout] || 5000 variable = args[:variable] || "read_digits_var" regexp = args[:regexp] || "\\d+" args = [min, max, tries, timeout, terminators, file, invalid_file, variable, regexp].join " " params = {:variable => variable} application "play_and_get_digits", args, params, &block end
[ "def", "play_and_get_digits", "file", ",", "invalid_file", ",", "args", "=", "{", "}", ",", "&", "block", "min", "=", "args", "[", ":min", "]", "||", "1", "max", "=", "args", "[", ":max", "]", "||", "2", "tries", "=", "args", "[", ":tries", "]", "||", "3", "terminators", "=", "args", "[", ":terminators", "]", "||", "\"#\"", "timeout", "=", "args", "[", ":timeout", "]", "||", "5000", "variable", "=", "args", "[", ":variable", "]", "||", "\"read_digits_var\"", "regexp", "=", "args", "[", ":regexp", "]", "||", "\"\\\\d+\"", "args", "=", "[", "min", ",", "max", ",", "tries", ",", "timeout", ",", "terminators", ",", "file", ",", "invalid_file", ",", "variable", ",", "regexp", "]", ".", "join", "\" \"", "params", "=", "{", ":variable", "=>", "variable", "}", "application", "\"play_and_get_digits\"", ",", "args", ",", "params", ",", "block", "end" ]
Plays a sound file and reads DTMF presses. @example play_and_get_digits "please-enter.wav", "wrong-choice.wav", :min => 1, :max => 2, :tries => 3, :terminators => "#", :timeout => 5000, :regexp => '\d+' @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_play_and_get_digits
[ "Plays", "a", "sound", "file", "and", "reads", "DTMF", "presses", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L137-L152
3,485
vangberg/librevox
lib/librevox/applications.rb
Librevox.Applications.record
def record path, params={}, &block args = [path, params[:limit]].compact.join(" ") application "record", args, &block end
ruby
def record path, params={}, &block args = [path, params[:limit]].compact.join(" ") application "record", args, &block end
[ "def", "record", "path", ",", "params", "=", "{", "}", ",", "&", "block", "args", "=", "[", "path", ",", "params", "[", ":limit", "]", "]", ".", "compact", ".", "join", "(", "\" \"", ")", "application", "\"record\"", ",", "args", ",", "block", "end" ]
Records a message, with an optional limit on the maximum duration of the recording. @example Without limit record "/path/to/new/file.wac" @example With 20 second limit record "/path/to/new/file.wac", :limit => 20 @see http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_record
[ "Records", "a", "message", "with", "an", "optional", "limit", "on", "the", "maximum", "duration", "of", "the", "recording", "." ]
b894e6c4857ce768fdb961444f197b43d985b5e2
https://github.com/vangberg/librevox/blob/b894e6c4857ce768fdb961444f197b43d985b5e2/lib/librevox/applications.rb#L193-L196
3,486
matttproud/ruby_quantile_estimation
lib/quantile/estimator.rb
Quantile.Estimator.query
def query(rank) flush current = @head return unless current mid_rank = (rank * @observations).floor max_rank = mid_rank + (invariant(mid_rank, @observations) / 2).floor rank = 0.0 while current.successor rank += current.rank if rank + current.successor.rank + current.successor.delta > max_rank return current.value end current = current.successor end return current.value end
ruby
def query(rank) flush current = @head return unless current mid_rank = (rank * @observations).floor max_rank = mid_rank + (invariant(mid_rank, @observations) / 2).floor rank = 0.0 while current.successor rank += current.rank if rank + current.successor.rank + current.successor.delta > max_rank return current.value end current = current.successor end return current.value end
[ "def", "query", "(", "rank", ")", "flush", "current", "=", "@head", "return", "unless", "current", "mid_rank", "=", "(", "rank", "*", "@observations", ")", ".", "floor", "max_rank", "=", "mid_rank", "+", "(", "invariant", "(", "mid_rank", ",", "@observations", ")", "/", "2", ")", ".", "floor", "rank", "=", "0.0", "while", "current", ".", "successor", "rank", "+=", "current", ".", "rank", "if", "rank", "+", "current", ".", "successor", ".", "rank", "+", "current", ".", "successor", ".", "delta", ">", "max_rank", "return", "current", ".", "value", "end", "current", "=", "current", ".", "successor", "end", "return", "current", ".", "value", "end" ]
Get a quantile value for a given rank. @param rank [Float] The target quantile to retrieve. It *must* be one of the invariants provided in the constructor. @return [Numeric, nil] The quantile value for the rank or nil if no observations are present.
[ "Get", "a", "quantile", "value", "for", "a", "given", "rank", "." ]
49c660bffdc36a8283ecc730a102bae7232a438f
https://github.com/matttproud/ruby_quantile_estimation/blob/49c660bffdc36a8283ecc730a102bae7232a438f/lib/quantile/estimator.rb#L89-L109
3,487
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.file_list
def file_list(path, ext = 'scss', remover = '') # Necessary so that directories aren't counted collect_path = path.include?("*") ? path : "#{path}/**/*.#{ext}" # Remove first slash from path if present. probably a better way to do this. Dir[collect_path].collect { |file| file.gsub(remover, '').gsub(/^\/app\//, 'app/') if File.file?(file) } end
ruby
def file_list(path, ext = 'scss', remover = '') # Necessary so that directories aren't counted collect_path = path.include?("*") ? path : "#{path}/**/*.#{ext}" # Remove first slash from path if present. probably a better way to do this. Dir[collect_path].collect { |file| file.gsub(remover, '').gsub(/^\/app\//, 'app/') if File.file?(file) } end
[ "def", "file_list", "(", "path", ",", "ext", "=", "'scss'", ",", "remover", "=", "''", ")", "# Necessary so that directories aren't counted", "collect_path", "=", "path", ".", "include?", "(", "\"*\"", ")", "?", "path", ":", "\"#{path}/**/*.#{ext}\"", "# Remove first slash from path if present. probably a better way to do this.", "Dir", "[", "collect_path", "]", ".", "collect", "{", "|", "file", "|", "file", ".", "gsub", "(", "remover", ",", "''", ")", ".", "gsub", "(", "/", "\\/", "\\/", "/", ",", "'app/'", ")", "if", "File", ".", "file?", "(", "file", ")", "}", "end" ]
Find all files that were linted by extension @param path [String] path to folders @param ext [String] file extension to search for @return [Array<String>] list of file paths
[ "Find", "all", "files", "that", "were", "linted", "by", "extension" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L59-L64
3,488
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.truthy?
def truthy?(str) return true if str == true || str =~ (/^(true|t|yes|y|1)$/i) return false if str == false || str.blank? || str =~ (/^(false|f|no|n|0)$/i) end
ruby
def truthy?(str) return true if str == true || str =~ (/^(true|t|yes|y|1)$/i) return false if str == false || str.blank? || str =~ (/^(false|f|no|n|0)$/i) end
[ "def", "truthy?", "(", "str", ")", "return", "true", "if", "str", "==", "true", "||", "str", "=~", "(", "/", "/i", ")", "return", "false", "if", "str", "==", "false", "||", "str", ".", "blank?", "||", "str", "=~", "(", "/", "/i", ")", "end" ]
Convert string to boolean @param str [String] the string to evaluate @return [Boolean] whether or not the string is true
[ "Convert", "string", "to", "boolean" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L78-L81
3,489
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.edit_yaml
def edit_yaml(yaml_location, &block) d = YAML.load_file(yaml_location) block.call(d) File.open(yaml_location, 'w') {|f| f.write d.to_yaml } end
ruby
def edit_yaml(yaml_location, &block) d = YAML.load_file(yaml_location) block.call(d) File.open(yaml_location, 'w') {|f| f.write d.to_yaml } end
[ "def", "edit_yaml", "(", "yaml_location", ",", "&", "block", ")", "d", "=", "YAML", ".", "load_file", "(", "yaml_location", ")", "block", ".", "call", "(", "d", ")", "File", ".", "open", "(", "yaml_location", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "d", ".", "to_yaml", "}", "end" ]
Edit and save a YAML file @param yaml_location [String] YAML absolute file path @return [void]
[ "Edit", "and", "save", "a", "YAML", "file" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L86-L90
3,490
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.path_exists?
def path_exists?(path = @path) path = path.split(' ') if path.is_a?(String) && path.include?(' ') if path.is_a?(Array) path.each do |p| unless File.exist?(p) puts "#{p} does not exist" return false end end else path = path.gsub('/**', '').gsub('/*', '').gsub(/\/\.*/, '') if path.include?('*') if File.exist?(path) return true else puts "#{path} does not exist" return false end end end
ruby
def path_exists?(path = @path) path = path.split(' ') if path.is_a?(String) && path.include?(' ') if path.is_a?(Array) path.each do |p| unless File.exist?(p) puts "#{p} does not exist" return false end end else path = path.gsub('/**', '').gsub('/*', '').gsub(/\/\.*/, '') if path.include?('*') if File.exist?(path) return true else puts "#{path} does not exist" return false end end end
[ "def", "path_exists?", "(", "path", "=", "@path", ")", "path", "=", "path", ".", "split", "(", "' '", ")", "if", "path", ".", "is_a?", "(", "String", ")", "&&", "path", ".", "include?", "(", "' '", ")", "if", "path", ".", "is_a?", "(", "Array", ")", "path", ".", "each", "do", "|", "p", "|", "unless", "File", ".", "exist?", "(", "p", ")", "puts", "\"#{p} does not exist\"", "return", "false", "end", "end", "else", "path", "=", "path", ".", "gsub", "(", "'/**'", ",", "''", ")", ".", "gsub", "(", "'/*'", ",", "''", ")", ".", "gsub", "(", "/", "\\/", "\\.", "/", ",", "''", ")", "if", "path", ".", "include?", "(", "'*'", ")", "if", "File", ".", "exist?", "(", "path", ")", "return", "true", "else", "puts", "\"#{path} does not exist\"", "return", "false", "end", "end", "end" ]
Ensure path exists @param path [String, Array] path to files can be directory or glob @return [Boolean]
[ "Ensure", "path", "exists" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L103-L121
3,491
wearefine/maximus
lib/maximus/helper.rb
Maximus.Helper.discover_path
def discover_path(root = @config.working_dir, folder = '', extension = '') return @path unless @path.blank? if is_middleman? File.join(root, 'source', folder) elsif is_rails? File.join(root, 'app', 'assets', folder) else extension.blank? ? File.join(root) : File.join(root, '/**', "/*.#{extension}") end end
ruby
def discover_path(root = @config.working_dir, folder = '', extension = '') return @path unless @path.blank? if is_middleman? File.join(root, 'source', folder) elsif is_rails? File.join(root, 'app', 'assets', folder) else extension.blank? ? File.join(root) : File.join(root, '/**', "/*.#{extension}") end end
[ "def", "discover_path", "(", "root", "=", "@config", ".", "working_dir", ",", "folder", "=", "''", ",", "extension", "=", "''", ")", "return", "@path", "unless", "@path", ".", "blank?", "if", "is_middleman?", "File", ".", "join", "(", "root", ",", "'source'", ",", "folder", ")", "elsif", "is_rails?", "File", ".", "join", "(", "root", ",", "'app'", ",", "'assets'", ",", "folder", ")", "else", "extension", ".", "blank?", "?", "File", ".", "join", "(", "root", ")", ":", "File", ".", "join", "(", "root", ",", "'/**'", ",", "\"/*.#{extension}\"", ")", "end", "end" ]
Default paths to check for lints and some stats @since 0.1.6.1 Note: is_rails? must be defined second-to-last if more frameworks are added @param root [String] base directory @param folder [String] nested folder to search for for Rails or Middleman @param extension [String] file glob type to search for if neither @return [String] path to desired files
[ "Default", "paths", "to", "check", "for", "lints", "and", "some", "stats" ]
d3a6ad1826694c98a5e6a5a3175b78e69aac7945
https://github.com/wearefine/maximus/blob/d3a6ad1826694c98a5e6a5a3175b78e69aac7945/lib/maximus/helper.rb#L130-L139
3,492
adonespitogo/unsakini
app/controllers/concerns/unsakini/comment_owner_controller_concern.rb
Unsakini.CommentOwnerControllerConcern.ensure_comment
def ensure_comment post_id = params[:post_id] comment_id = params[:comment_id] || params[:id] result = has_comment_access post_id, comment_id @comment = result[:comment] status = result[:status] head status if status != :ok end
ruby
def ensure_comment post_id = params[:post_id] comment_id = params[:comment_id] || params[:id] result = has_comment_access post_id, comment_id @comment = result[:comment] status = result[:status] head status if status != :ok end
[ "def", "ensure_comment", "post_id", "=", "params", "[", ":post_id", "]", "comment_id", "=", "params", "[", ":comment_id", "]", "||", "params", "[", ":id", "]", "result", "=", "has_comment_access", "post_id", ",", "comment_id", "@comment", "=", "result", "[", ":comment", "]", "status", "=", "result", "[", ":status", "]", "head", "status", "if", "status", "!=", ":ok", "end" ]
Ensures user is owner of the comment and sets the `@comment` variable in the controllers
[ "Ensures", "user", "is", "owner", "of", "the", "comment", "and", "sets", "the" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/comment_owner_controller_concern.rb#L7-L14
3,493
adonespitogo/unsakini
app/controllers/concerns/unsakini/comment_owner_controller_concern.rb
Unsakini.CommentOwnerControllerConcern.has_comment_access
def has_comment_access(post_id, comment_id) comment = Unsakini::Comment.where(id: comment_id, post_id: post_id, user_id: @user.id).first if comment.nil? return {status: :forbidden, comment: comment} else return {status: :ok, comment: comment} end end
ruby
def has_comment_access(post_id, comment_id) comment = Unsakini::Comment.where(id: comment_id, post_id: post_id, user_id: @user.id).first if comment.nil? return {status: :forbidden, comment: comment} else return {status: :ok, comment: comment} end end
[ "def", "has_comment_access", "(", "post_id", ",", "comment_id", ")", "comment", "=", "Unsakini", "::", "Comment", ".", "where", "(", "id", ":", "comment_id", ",", "post_id", ":", "post_id", ",", "user_id", ":", "@user", ".", "id", ")", ".", "first", "if", "comment", ".", "nil?", "return", "{", "status", ":", ":forbidden", ",", "comment", ":", "comment", "}", "else", "return", "{", "status", ":", ":ok", ",", "comment", ":", "comment", "}", "end", "end" ]
Validate if user has access to comment in the post @param post_id [Integer] post id @param comment_id [Integer] comment id
[ "Validate", "if", "user", "has", "access", "to", "comment", "in", "the", "post" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/comment_owner_controller_concern.rb#L20-L27
3,494
michaeledgar/ripper-plus
lib/ripper-plus/scope_stack.rb
RipperPlus.ScopeStack.with_closed_scope
def with_closed_scope(is_method = false) old_in_method = @in_method @in_method ||= is_method @stack.push(SCOPE_BLOCKER_9000) @stack.push(Set.new) yield ensure @stack.pop # pop closed scope @stack.pop # pop scope blocker @in_method = old_in_method end
ruby
def with_closed_scope(is_method = false) old_in_method = @in_method @in_method ||= is_method @stack.push(SCOPE_BLOCKER_9000) @stack.push(Set.new) yield ensure @stack.pop # pop closed scope @stack.pop # pop scope blocker @in_method = old_in_method end
[ "def", "with_closed_scope", "(", "is_method", "=", "false", ")", "old_in_method", "=", "@in_method", "@in_method", "||=", "is_method", "@stack", ".", "push", "(", "SCOPE_BLOCKER_9000", ")", "@stack", ".", "push", "(", "Set", ".", "new", ")", "yield", "ensure", "@stack", ".", "pop", "# pop closed scope", "@stack", ".", "pop", "# pop scope blocker", "@in_method", "=", "old_in_method", "end" ]
An open scope denies reference to local variables in enclosing scopes.
[ "An", "open", "scope", "denies", "reference", "to", "local", "variables", "in", "enclosing", "scopes", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/scope_stack.rb#L44-L54
3,495
michaeledgar/ripper-plus
lib/ripper-plus/scope_stack.rb
RipperPlus.ScopeStack.has_variable?
def has_variable?(var) @stack.reverse_each do |scope| if SCOPE_BLOCKER_9000 == scope return false elsif scope.include?(var) return true end end end
ruby
def has_variable?(var) @stack.reverse_each do |scope| if SCOPE_BLOCKER_9000 == scope return false elsif scope.include?(var) return true end end end
[ "def", "has_variable?", "(", "var", ")", "@stack", ".", "reverse_each", "do", "|", "scope", "|", "if", "SCOPE_BLOCKER_9000", "==", "scope", "return", "false", "elsif", "scope", ".", "include?", "(", "var", ")", "return", "true", "end", "end", "end" ]
Checks if the given variable is in scope.
[ "Checks", "if", "the", "given", "variable", "is", "in", "scope", "." ]
bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e
https://github.com/michaeledgar/ripper-plus/blob/bfe2cf4fc866cfa9f5cc70e61589a8fd9af9f87e/lib/ripper-plus/scope_stack.rb#L57-L65
3,496
adonespitogo/unsakini
app/controllers/unsakini/comments_controller.rb
Unsakini.CommentsController.create
def create @comment = Comment.new(params.permit(:content)) @comment.user = @user @comment.post = @post if @comment.save render json: @comment else render json: @comment.errors, status: 422 end end
ruby
def create @comment = Comment.new(params.permit(:content)) @comment.user = @user @comment.post = @post if @comment.save render json: @comment else render json: @comment.errors, status: 422 end end
[ "def", "create", "@comment", "=", "Comment", ".", "new", "(", "params", ".", "permit", "(", ":content", ")", ")", "@comment", ".", "user", "=", "@user", "@comment", ".", "post", "=", "@post", "if", "@comment", ".", "save", "render", "json", ":", "@comment", "else", "render", "json", ":", "@comment", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Creates new comment belonging to the post `POST /api/boards/:board_id/posts/:post_id/`
[ "Creates", "new", "comment", "belonging", "to", "the", "post" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/comments_controller.rb#L23-L32
3,497
adonespitogo/unsakini
app/controllers/unsakini/comments_controller.rb
Unsakini.CommentsController.update
def update if @comment.update(params.permit(:content)) render json: @comment else render json: @comment.errors, status: 422 end end
ruby
def update if @comment.update(params.permit(:content)) render json: @comment else render json: @comment.errors, status: 422 end end
[ "def", "update", "if", "@comment", ".", "update", "(", "params", ".", "permit", "(", ":content", ")", ")", "render", "json", ":", "@comment", "else", "render", "json", ":", "@comment", ".", "errors", ",", "status", ":", "422", "end", "end" ]
Updates a comment `PUT /api/boards/:board_id/posts/:post_id/comments/:id`
[ "Updates", "a", "comment" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/unsakini/comments_controller.rb#L37-L43
3,498
adonespitogo/unsakini
app/controllers/concerns/unsakini/board_owner_controller_concern.rb
Unsakini.BoardOwnerControllerConcern.ensure_board
def ensure_board board_id = params[:board_id] || params[:id] result = has_board_access(board_id) @board = result[:board] @user_board = result[:user_board] head result[:status] if result[:status] != :ok end
ruby
def ensure_board board_id = params[:board_id] || params[:id] result = has_board_access(board_id) @board = result[:board] @user_board = result[:user_board] head result[:status] if result[:status] != :ok end
[ "def", "ensure_board", "board_id", "=", "params", "[", ":board_id", "]", "||", "params", "[", ":id", "]", "result", "=", "has_board_access", "(", "board_id", ")", "@board", "=", "result", "[", ":board", "]", "@user_board", "=", "result", "[", ":user_board", "]", "head", "result", "[", ":status", "]", "if", "result", "[", ":status", "]", "!=", ":ok", "end" ]
Ensure user has access to the board and sets the `@board` variable in the controller
[ "Ensure", "user", "has", "access", "to", "the", "board", "and", "sets", "the" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/board_owner_controller_concern.rb#L8-L14
3,499
adonespitogo/unsakini
app/controllers/concerns/unsakini/board_owner_controller_concern.rb
Unsakini.BoardOwnerControllerConcern.has_board_access
def has_board_access(board_id) board = nil if !board_id.nil? board = Unsakini::Board.find_by_id(board_id) else return {status: :bad_request} end if (board) user_board = Unsakini::UserBoard.where(user_id: @user.id, board_id: board_id).first return {status: :forbidden } if user_board.nil? return {status: :ok, board: board, user_board: user_board} else return {status: :not_found} end end
ruby
def has_board_access(board_id) board = nil if !board_id.nil? board = Unsakini::Board.find_by_id(board_id) else return {status: :bad_request} end if (board) user_board = Unsakini::UserBoard.where(user_id: @user.id, board_id: board_id).first return {status: :forbidden } if user_board.nil? return {status: :ok, board: board, user_board: user_board} else return {status: :not_found} end end
[ "def", "has_board_access", "(", "board_id", ")", "board", "=", "nil", "if", "!", "board_id", ".", "nil?", "board", "=", "Unsakini", "::", "Board", ".", "find_by_id", "(", "board_id", ")", "else", "return", "{", "status", ":", ":bad_request", "}", "end", "if", "(", "board", ")", "user_board", "=", "Unsakini", "::", "UserBoard", ".", "where", "(", "user_id", ":", "@user", ".", "id", ",", "board_id", ":", "board_id", ")", ".", "first", "return", "{", "status", ":", ":forbidden", "}", "if", "user_board", ".", "nil?", "return", "{", "status", ":", ":ok", ",", "board", ":", "board", ",", "user_board", ":", "user_board", "}", "else", "return", "{", "status", ":", ":not_found", "}", "end", "end" ]
Validate if user has access to board @param board_id [Integer] board id
[ "Validate", "if", "user", "has", "access", "to", "board" ]
3e77e8e374a605961023e77a5c374734415b9f9d
https://github.com/adonespitogo/unsakini/blob/3e77e8e374a605961023e77a5c374734415b9f9d/app/controllers/concerns/unsakini/board_owner_controller_concern.rb#L19-L33