idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
5,200 | def sample ( str ) @sample_x ||= 100 @sample_y ||= 100 rect x : 460 , y : @sample_y - 40 , width : 600 , height : 180 , fill_color : '#FFD655' , stroke_color : 'black' , radius : 15 text str : str , x : 460 , y : @sample_y - 40 , width : 540 , height : 180 , valign : 'middle' , align : 'center' , font : 'Times New Roma... | Define a set of samples on some graph paper |
5,201 | def enable_groups_from_env! return if ENV [ 'SQUIB_BUILD' ] . nil? ENV [ 'SQUIB_BUILD' ] . split ( ',' ) . each do | grp | enable_build grp . strip . to_sym end end | Not a DSL method but initialized from Deck . new |
5,202 | def parents_exist? ( yml , key ) exists = true Array ( yml [ key ] [ 'extends' ] ) . each do | parent | unless yml . key? ( parent ) exists = false unless Squib . logger . error "Processing layout: '#{key}' attempts to extend a missing '#{yml[key]['extends']}'" end end return exists end | Checks if we have any absentee parents |
5,203 | def compute_carve ( rule , range ) w = rule [ :box ] . width [ @index ] if w == :native file = rule [ :file ] [ @index ] . file case rule [ :type ] when :png Squib . cache_load_image ( file ) . width . to_f / ( range . size - 1 ) when :svg svg_data = rule [ :svg_args ] . data [ @index ] unless file . to_s . empty? || s... | Compute the width of the carve that we need |
5,204 | def render_hand ( range , sheet , hand ) cards = range . collect { | i | @cards [ i ] } center_x = width / 2.0 center_y = hand . radius + height out_size = 3.0 * center_y angle_delta = ( hand . angle_range . last - hand . angle_range . first ) / cards . size cxt = Cairo :: Context . new ( Cairo :: RecordingSurface . ne... | Draw cards in a fan . |
5,205 | def parse_crop_line ( line ) new_line = @crop_line_default . merge line new_line [ 'width' ] = Args :: UnitConversion . parse ( new_line [ 'width' ] , @dpi ) new_line [ 'color' ] = colorify new_line [ 'color' ] new_line [ 'style_desc' ] = new_line [ 'style' ] new_line [ 'style' ] = Sprues :: CropLineDash . new ( new_li... | Parse crop line definitions from template . |
5,206 | def parse_card ( card ) new_card = card . clone x = Args :: UnitConversion . parse ( card [ 'x' ] , @dpi ) y = Args :: UnitConversion . parse ( card [ 'y' ] , @dpi ) if @template_hash [ 'position_reference' ] == :center x -= card_width / 2 y -= card_height / 2 end new_card [ 'x' ] = x new_card [ 'y' ] = y new_card [ 'r... | Parse card definitions from template . |
5,207 | def save_habtm_associations ( version ) @record . class . reflect_on_all_associations ( :has_and_belongs_to_many ) . each do | a | next unless save_habtm_association? ( a ) habtm_assoc_ids ( a ) . each do | id | :: PaperTrail :: VersionAssociation . create ( version_id : version . transaction_id , foreign_key_name : a ... | When a record is created updated or destroyed we determine what the HABTM associations looked like before any changes were made by using the paper_trail_habtm data structure . Then we create VersionAssociation records for each of the associated records . |
5,208 | def habtm_assoc_ids ( habtm_assoc ) current = @record . send ( habtm_assoc . name ) . to_a . map ( & :id ) removed = @record . paper_trail_habtm . try ( :[] , habtm_assoc . name ) . try ( :[] , :removed ) || [ ] added = @record . paper_trail_habtm . try ( :[] , habtm_assoc . name ) . try ( :[] , :added ) || [ ] current... | Given a HABTM association returns an array of ids . |
5,209 | def save_bt_association ( assoc , version ) assoc_version_args = { version_id : version . id , foreign_key_name : assoc . foreign_key } if assoc . options [ :polymorphic ] foreign_type = @record . send ( assoc . foreign_type ) if foreign_type && :: PaperTrail . request . enabled_for_model? ( foreign_type . constantize ... | Save a single belongs_to association . |
5,210 | def save_habtm_association? ( assoc ) @record . class . paper_trail_save_join_tables . include? ( assoc . name ) || :: PaperTrail . request . enabled_for_model? ( assoc . klass ) end | Returns true if the given HABTM association should be saved . |
5,211 | def assert_concrete_activerecord_class ( class_name ) if class_name . constantize . abstract_class? raise format ( :: PaperTrail :: ModelConfig :: E_HPT_ABSTRACT_CLASS , @model_class , class_name ) end end | Raises an error if the provided class is an abstract_class . |
5,212 | def wait_for ( opts = { } ) aws_object = opts [ :aws_object ] query_method = opts [ :query_method ] expected_responses = [ opts [ :expected_responses ] ] . flatten acceptable_errors = [ opts [ :acceptable_errors ] || [ ] ] . flatten tries = opts [ :tries ] || 60 sleep = opts [ :sleep ] || 5 Retryable . retryable ( trie... | Wait until aws_object obtains one of expected_responses |
5,213 | def _random_seed ( size = 32 ) if defined? OpenSSL :: Random return OpenSSL :: Random . random_bytes ( size ) else chars = ( "a" .. "z" ) . to_a + ( "A" .. "Z" ) . to_a + ( "0" .. "9" ) . to_a ( 1 .. size ) . collect { | a | chars [ rand ( chars . size ) ] } . join end end | Generates a random seed value |
5,214 | def b64_d ( data ) iv_and_ctext = [ ] data . split ( '$' ) . each do | part | iv_and_ctext << Base64 . decode64 ( part ) end iv_and_ctext end | Un - Base64 s the IV and CipherText Returns an array containing the IV and CipherText |
5,215 | def _setup ( action ) @cipher ||= OpenSSL :: Cipher . new ( @options [ :cipher ] ) @cipher . send ( action ) @cipher . padding = @options [ :padding ] @cipher . key = @key . unpack ( 'a2' * 32 ) . map { | x | x . hex } . pack ( 'c' * 32 ) end | Create a new cipher using the cipher type specified |
5,216 | def default_load_paths paths = [ "#{RADIANT_ROOT}/test/mocks/#{environment}" ] paths . concat ( Dir [ "#{RADIANT_ROOT}/app/controllers/" ] ) paths . concat %w( app app/metal app/models app/controllers app/helpers config lib vendor ) . map { | dir | "#{RADIANT_ROOT}/#{dir}" } . select { | dir | File . directory? ( dir )... | Provide the load paths for the Radiant installation |
5,217 | def extension_enabled? ( extension ) begin extension = ( extension . to_s . camelcase + 'Extension' ) . constantize extension . enabled? rescue NameError false end end | Determine if another extension is installed and up to date . |
5,218 | def check_subdirectory ( subpath ) subdirectory = File . join ( path , subpath ) subdirectory if File . directory? ( subdirectory ) end | If the supplied path within the extension root exists and is a directory its absolute path is returned . Otherwise nil . |
5,219 | def load_extension ( name ) extension_path = ExtensionPath . find ( name ) begin constant = "#{name}_extension" . camelize extension = constant . constantize extension . unloadable extension . path = extension_path extension rescue LoadError , NameError => e $stderr . puts "Could not load extension: #{name}.\n#{e.inspe... | Loads the specified extension . |
5,220 | def pagination_for ( list , options = { } ) if list . respond_to? :total_pages options = { max_per_page : detail [ 'pagination.max_per_page' ] || 500 , depaginate : true } . merge ( options . symbolize_keys ) depaginate = options . delete ( :depaginate ) depagination_limit = options . delete ( :max_per_page ) html = wi... | returns the usual set of pagination links . options are passed through to will_paginate and a show all depagination link is added if relevant . |
5,221 | def get_xml_attributes obj , parent = true attribs = obj . reject { | k , _ | @@ignored_attributes . include? k } if parent attribs = attribs . reject { | k , _ | @@parent_ignored_attributes . include? k } end attribs = attribs . reject { | _ , v | v . kind_of? ( Hash ) || v . kind_of? ( Array ) } attribs . each_pair d... | Return renderable attributes |
5,222 | def clear return if commontable . blank? || ! is_closed? new_thread = Thread . new new_thread . commontable = commontable with_lock do self . commontable = nil save! new_thread . save! subscriptions . each do | s | s . thread = new_thread s . save! end end end | Creates a new empty thread and assigns it to the commontable The old thread is kept in the database for archival purposes |
5,223 | def can_be_edited_by? ( user ) ! commontable . nil? && ! user . nil? && user . is_commontator && config . thread_moderator_proc . call ( self , user ) end | Thread moderator capabilities |
5,224 | def shorten ( original_chars , chars , length_without_trailing ) truncated = [ ] char_width = display_width ( chars [ 0 ] ) while length_without_trailing - char_width > 0 orig_char = original_chars . shift char = chars . shift break unless char while orig_char != char ansi = true truncated << orig_char orig_char = orig... | Perform actual shortening of the text |
5,225 | def pad ( text , padding , fill : SPACE , separator : NEWLINE ) padding = Strings :: Padder . parse ( padding ) text_copy = text . dup line_width = max_line_length ( text , separator ) output = [ ] filler_line = fill * line_width padding . top . times do output << pad_around ( filler_line , padding , fill : fill ) end ... | Apply padding to multiline text with ANSI codes |
5,226 | def pad_around ( text , padding , fill : SPACE ) fill * padding . left + text + fill * padding . right end | Apply padding to left and right side of string |
5,227 | def align_left ( text , width , fill : SPACE , separator : NEWLINE ) return if width . nil? each_line ( text , separator ) do | line | width_diff = width - display_width ( line ) if width_diff > 0 line + fill * width_diff else line end end end | Aligns text to the left at given length |
5,228 | def align_center ( text , width , fill : SPACE , separator : NEWLINE ) return text if width . nil? each_line ( text , separator ) do | line | width_diff = width - display_width ( line ) if width_diff > 0 right_count = ( width_diff . to_f / 2 ) . ceil left_count = width_diff - right_count [ fill * left_count , line , fi... | Centers text within the width |
5,229 | def each_line ( text , separator ) lines = text . split ( separator ) return yield ( text ) if text . empty? lines . reduce ( [ ] ) do | aligned , line | aligned << yield ( line ) end . join ( separator ) end | Enumerate text line by line |
5,230 | def execute ( method : , path : nil , headers : { } , query : { } , payload : nil ) timeout = ENDPOINT_TIMEOUTS . fetch ( path , 230 ) request = build_request ( method : method , path : path , headers : headers , query : query , payload : payload , timeout : timeout ) rest_client_execute ( ** request ) do | response , ... | Sends a request to the Nylas API and rai |
5,231 | def get ( path : nil , headers : { } , query : { } ) execute ( method : :get , path : path , query : query , headers : headers ) end | Syntactical sugar for making GET requests via the API . |
5,232 | def post ( path : nil , payload : nil , headers : { } , query : { } ) execute ( method : :post , path : path , headers : headers , query : query , payload : payload ) end | Syntactical sugar for making POST requests via the API . |
5,233 | def put ( path : nil , payload : , headers : { } , query : { } ) execute ( method : :put , path : path , headers : headers , query : query , payload : payload ) end | Syntactical sugar for making PUT requests via the API . |
5,234 | def delete ( path : nil , payload : nil , headers : { } , query : { } ) execute ( method : :delete , path : path , headers : headers , query : query , payload : payload ) end | Syntactical sugar for making DELETE requests via the API . |
5,235 | def where ( filters ) raise ModelNotFilterableError , model unless model . filterable? self . class . new ( model : model , api : api , constraints : constraints . merge ( where : filters ) ) end | Merges in additional filters when querying the collection |
5,236 | def raw raise ModelNotAvailableAsRawError , model unless model . exposable_as_raw? self . class . new ( model : model , api : api , constraints : constraints . merge ( accept : model . raw_mime_type ) ) end | The collection now returns a string representation of the model in a particular mime type instead of Model objects |
5,237 | def each return enum_for ( :each ) unless block_given? execute . each do | result | yield ( model . new ( result . merge ( api : api ) ) ) end end | Iterates over a single page of results based upon current pagination settings |
5,238 | def find_each return enum_for ( :find_each ) unless block_given? query = self accumulated = 0 while query results = query . each do | instance | yield ( instance ) end accumulated += results . length query = query . next_page ( accumulated : accumulated , current_page : results ) end end | Iterates over every result that meets the filters retrieving a page at a time |
5,239 | def download! return download if file . nil? file . close file . unlink self . file = nil download end | Redownloads a file even if it s been cached . Closes and unlinks the tempfile to help memory usage . |
5,240 | def revoke ( access_token ) response = client . as ( access_token ) . post ( path : "/oauth/revoke" ) response . code == 200 && response . empty? end | Revokes access to the Nylas API for the given access token |
5,241 | def valid_paths? paths = options [ :cookbook_paths ] + options [ :role_paths ] + options [ :environment_paths ] paths . any? && paths . all? { | path | File . exist? ( path ) } end | If the paths provided are valid |
5,242 | def valid_grammar? return true unless options . key? ( :search_grammar ) return false unless File . exist? ( options [ :search_grammar ] ) search = FoodCritic :: Chef :: Search . new search . create_parser ( [ options [ :search_grammar ] ] ) search . parser? end | Is the search grammar specified valid? |
5,243 | def list ( options = { } ) options = setup_defaults ( options ) @options = options load_rules if options [ :tags ] . any? @rules = active_rules ( options [ :tags ] ) end RuleList . new ( @rules ) end | List the rules that are currently in effect . |
5,244 | def check ( options = { } ) options = setup_defaults ( options ) @options = options @chef_version = options [ :chef_version ] || DEFAULT_CHEF_VERSION warnings = [ ] ; last_dir = nil ; matched_rule_tags = Set . new load_rules paths = specified_paths! ( options ) files = files_to_process ( paths ) if options [ :progress ... | Review the cookbooks at the provided path identifying potential improvements . |
5,245 | def applies_to_version? ( rule , version ) return true unless version rule . applies_to . yield ( Gem :: Version . create ( version ) ) end | Some rules are version specific . |
5,246 | def rule_file_tags ( file ) cookbook = cookbook_dir ( file ) @tag_cache ||= { } cb_tags = @tag_cache [ cookbook ] return cb_tags unless cb_tags . nil? tags = if @options [ :rule_file ] raise "ERROR: Could not find the specified rule file at #{@options[:rule_file]}" unless File . exist? ( @options [ :rule_file ] ) parse... | given a file in the cookbook lookup all the applicable tag rules defined in rule files . The rule file is either that specified via CLI or the . foodcritic file in the cookbook . We cache this information at the cookbook level to prevent looking up the same thing dozens of times |
5,247 | def parse_rule_file ( file ) tags = [ ] begin tag_text = File . read file tags = tag_text . split ( / \s / ) rescue raise "ERROR: Could not read or parse the specified rule file at #{file}" end tags end | given a filename parse any tag rules in that file |
5,248 | def cookbook_dir ( file ) @dir_cache ||= { } abs_file = File . absolute_path ( file ) cook_val = @dir_cache [ abs_file ] return cook_val unless cook_val . nil? if file =~ / \. / dir_array = File . dirname ( file ) . split ( File :: SEPARATOR ) position = - 1 position -= 1 until dir_array [ position ] == "templates" pos... | provides the path to the cookbook from a file within the cookbook we cache this data in a hash because this method gets called often for the same files . |
5,249 | def files_to_process ( paths ) paths . reject { | type , _ | type == :exclude } . map do | path_type , dirs | dirs . map do | dir | exclusions = [ ] unless paths [ :exclude ] . empty? exclusions = Dir . glob ( paths [ :exclude ] . map do | p | File . join ( dir , p , "**/**" ) end ) end if File . directory? ( dir ) glo... | Return the files within a cookbook tree that we are interested in trying to match rules against . |
5,250 | def matches ( match_method , * params ) return [ ] unless match_method . respond_to? ( :yield ) matches = match_method . yield ( * params ) return [ ] unless matches . respond_to? ( :each ) matches . map do | m | if m . respond_to? ( :node_name ) match ( m ) elsif m . respond_to? ( :xpath ) m . to_a . map { | n | match... | Invoke the DSL method with the provided parameters . |
5,251 | def valid_query? ( query ) raise ArgumentError , "Query cannot be nil or empty" if query . to_s . empty? search = FoodCritic :: Chef :: Search . new search . create_parser ( search . chef_search_grammars ) if search . parser? search . parser . parse ( query . to_s ) else true end end | Is this a valid Lucene query? |
5,252 | def load_metadata version = if respond_to? ( :chef_version ) chef_version else Linter :: DEFAULT_CHEF_VERSION end metadata_path = [ version , version . sub ( / \. / , "" ) , Linter :: DEFAULT_CHEF_VERSION ] . map do | ver | metadata_path ( ver ) end . find { | m | File . exist? ( m ) } @dsl_metadata ||= FFI_Yajl :: Par... | To avoid the runtime hit of loading the Chef gem and its dependencies we load the DSL metadata from a JSON file shipped with our gem . |
5,253 | def output ( review ) unless review . respond_to? ( :warnings ) puts review ; return end context = 3 print_fn = lambda { | fn | ansi_print ( fn , :red , nil , :bold ) } print_rule = lambda { | warn | ansi_print ( warn , :cyan , nil , :bold ) } print_line = lambda { | line | ansi_print ( line , nil , :red , :bold ) } ke... | Output the review showing matching lines with context . |
5,254 | def key_by_file_and_line ( review ) warn_hash = { } review . warnings . each do | warning | filename = Pathname . new ( warning . match [ :filename ] ) . cleanpath . to_s line_num = warning . match [ :line ] . to_i warn_hash [ filename ] = { } unless warn_hash . key? ( filename ) unless warn_hash [ filename ] . key? ( ... | Build a hash lookup by filename and line number for warnings found in the specified review . |
5,255 | def ensure_file_exists ( basepath , filepath ) path = File . join ( basepath , filepath ) [ file_match ( path ) ] unless File . exist? ( path ) end | Match unless a file exists using the basepath of the cookbook and the filepath |
5,256 | def attribute_access ( ast , options = { } ) options = { type : :any , ignore_calls : false } . merge! ( options ) return [ ] unless ast . respond_to? ( :xpath ) unless [ :any , :string , :symbol , :vivified ] . include? ( options [ :type ] ) raise ArgumentError , "Node type not recognised" end case options [ :type ] w... | Find attribute access by type . |
5,257 | def cookbook_base_path ( file ) file = File . expand_path ( file ) file = File . dirname ( file ) unless File . directory? ( file ) until ( Dir . entries ( file ) & %w{ metadata.rb metadata.json } ) . any? file = File . dirname ( file ) end file end | The absolute path of a cookbook from the specified file . |
5,258 | def metadata_field ( file , field ) until ( file . split ( File :: SEPARATOR ) & standard_cookbook_subdirs ) . empty? file = File . absolute_path ( File . dirname ( file . to_s ) ) end file = File . dirname ( file ) unless File . extname ( file ) . empty? md_path = File . join ( file , "metadata.rb" ) if File . exist? ... | Retrieves a value of a metadata field . |
5,259 | def cookbook_name ( file ) raise ArgumentError , "File cannot be nil or empty" if file . to_s . empty? begin metadata_field ( file , "name" ) rescue RuntimeError until ( file . split ( File :: SEPARATOR ) & standard_cookbook_subdirs ) . empty? file = File . absolute_path ( File . dirname ( file . to_s ) ) end file = Fi... | The name of the cookbook containing the specified file . |
5,260 | def declared_dependencies ( ast ) raise_unless_xpath! ( ast ) deps = [ ] deps += field ( ast , "depends" ) . xpath ( "descendant::args_add/descendant::tstring_content[1]" ) deps += word_list_values ( field ( ast , "depends" ) ) deps . uniq! deps . map! { | dep | dep [ "value" ] . strip } deps end | The dependencies declared in cookbook metadata . |
5,261 | def field ( ast , field_name ) if field_name . nil? || field_name . to_s . empty? raise ArgumentError , "Field name cannot be nil or empty" end ast . xpath ( "(.//command[ident/@value='#{field_name}']|.//fcall[ident/@value='#{field_name}']/..)" ) end | Look for a method call with a given name . |
5,262 | def field_value ( ast , field_name ) field ( ast , field_name ) . xpath ( './/args_add_block//tstring_content [count(ancestor::args_add) = 1][count(ancestor::string_add) = 1] /@value' ) . map { | a | a . to_s } . last end | The value for a specific key in an environment or role ruby file |
5,263 | def file_match ( file ) raise ArgumentError , "Filename cannot be nil" if file . nil? { filename : file , matched : file , line : 1 , column : 1 } end | Create a match for a specified file . Use this if the presence of the file triggers the warning rather than content . |
5,264 | def included_recipes ( ast , options = { with_partial_names : true } ) raise_unless_xpath! ( ast ) filter = [ "[count(descendant::args_add) = 1]" ] unless options [ :with_partial_names ] filter << "[count(descendant::string_embexpr) = 0]" end string_desc = '[descendant::args_add/string_literal]/ descendant::tstr... | Retrieve the recipes that are included within the given recipe AST . |
5,265 | def match ( node ) raise_unless_xpath! ( node ) pos = node . xpath ( "descendant::pos" ) . first return nil if pos . nil? { matched : node . respond_to? ( :name ) ? node . name : "" , line : pos [ "line" ] . to_i , column : pos [ "column" ] . to_i } end | Create a match from the specified node . |
5,266 | def read_ast ( file ) @ast_cache ||= Rufus :: Lru :: Hash . new ( 5 ) if @ast_cache . include? ( file ) @ast_cache [ file ] else @ast_cache [ file ] = uncached_read_ast ( file ) end end | Read the AST for the given Ruby source file |
5,267 | def resource_attribute ( resource , name ) raise ArgumentError , "Attribute name cannot be empty" if name . empty? resource_attributes ( resource ) [ name . to_s ] end | Retrieve a single - valued attribute from the specified resource . |
5,268 | def resource_attributes ( resource , options = { } ) atts = { } name = resource_name ( resource , options ) atts [ :name ] = name unless name . empty? atts . merge! ( normal_attributes ( resource , options ) ) atts . merge! ( block_attributes ( resource ) ) atts end | Retrieve all attributes from the specified resource . |
5,269 | def resource_attributes_by_type ( ast ) result = { } resources_by_type ( ast ) . each do | type , resources | result [ type ] = resources . map do | resource | resource_attributes ( resource ) end end result end | Resources keyed by type with an array of matching nodes for each . |
5,270 | def resource_name ( resource , options = { } ) raise_unless_xpath! ( resource ) options = { return_expressions : false } . merge ( options ) if options [ :return_expressions ] name = resource . xpath ( "command/args_add_block" ) if name . xpath ( "descendant::string_add" ) . size == 1 && name . xpath ( "descendant::str... | Retrieve the name attribute associated with the specified resource . |
5,271 | def resources_by_type ( ast ) raise_unless_xpath! ( ast ) result = Hash . new { | hash , key | hash [ key ] = Array . new } find_resources ( ast ) . each do | resource | result [ resource_type ( resource ) ] << resource end result end | Resources in an AST keyed by type . |
5,272 | def ruby_code? ( str ) str = str . to_s return false if str . empty? checker = FoodCritic :: ErrorChecker . new ( str ) checker . parse ! checker . error? end | Does the provided string look like ruby code? |
5,273 | def supported_platforms ( ast ) platforms_ast = field ( ast , "supports" ) platforms = platforms_ast . xpath ( "(.//args_new)[1]/../*[not(.//string_embexpr)]" ) . xpath ( ".//tstring_content|.//symbol/ident" ) | word_list_values ( platforms_ast ) platforms . map do | platform | versions = platform . xpath ( "ancestor::... | Platforms declared as supported in cookbook metadata . Returns an array of hashes containing the name and version constraints for each platform . |
5,274 | def template_paths ( recipe_path ) Dir . glob ( Pathname . new ( recipe_path ) . dirname . dirname + "templates" + "**/*" , File :: FNM_DOTMATCH ) . select do | path | File . file? ( path ) end . reject do | path | File . basename ( path ) == ".DS_Store" || File . extname ( path ) == ".swp" end end | Templates in the current cookbook |
5,275 | def json_file_to_hash ( filename ) raise "File #{filename} not found" unless File . exist? ( filename ) file = File . read ( filename ) begin FFI_Yajl :: Parser . parse ( file ) rescue FFI_Yajl :: ParseError raise "File #{filename} does not appear to contain valid JSON" end end | Give a filename path it returns the hash of the JSON contents |
5,276 | def build_xml ( node , doc = nil , xml_node = nil ) doc , xml_node = xml_document ( doc , xml_node ) if node . respond_to? ( :each ) node . each do | child | if position_node? ( child ) xml_position_node ( doc , xml_node , child ) else if ast_node_has_children? ( child ) if ast_hash_node? ( child ) xml_hash_node ( doc ... | Recurse the nested arrays provided by Ripper to create a tree we can more easily apply expressions to . |
5,277 | def node_method? ( meth , cookbook_dir ) chef_dsl_methods . include? ( meth ) || meth == :set || meth == :set_unless || patched_node_method? ( meth , cookbook_dir ) end | check to see if the passed method is a node method we generally look this up from the chef DSL data we have but we specifically check for set and set_unless since those exist in cookbooks but are not longer part of chef 14 + this prevents false positives in FC019 anytime node . set is found |
5,278 | def expect_warning ( code , options = { } ) if options . has_key? ( :file_type ) options [ :file ] = { :attributes => "attributes/default.rb" , :definition => "definitions/apache_site.rb" , :metadata => "metadata.rb" , :provider => "providers/site.rb" , :resource => "resources/site.rb" , :libraries => "libraries/lib.rb... | Expect a warning to be included in the command output . |
5,279 | def usage_displayed ( is_exit_zero ) expect_output "foodcritic [cookbook_paths]" usage_options . each do | option | expect_usage_option ( option [ :short ] , option [ :long ] , option [ :description ] ) end if is_exit_zero assert_no_error_occurred else assert_error_occurred end end | Assert that the usage message is displayed . |
5,280 | def run_lint ( cmd_args ) cd "." do show_context = cmd_args . include? ( "-C" ) review , @status = FoodCritic :: Linter . run ( CommandLine . new ( cmd_args ) ) @review = if review . nil? || ( review . respond_to? ( :warnings ) && review . warnings . empty? ) "" elsif show_context ContextOutput . new . output ( review ... | Run a lint check with the provided command line arguments . |
5,281 | def assert_build_result ( success , warnings ) success ? assert_no_error_occurred : assert_error_occurred warnings . each do | code | expect_warning ( code , :warning_only => true ) end end | Assert the build outcome |
5,282 | def build_tasks all_output . split ( "\n" ) . map do | task | next unless task . start_with? "rake" task . split ( "#" ) . map { | t | t . strip . sub ( / / , "" ) } end . compact end | The available tasks for this build |
5,283 | def expect_output ( output ) if output . respond_to? ( :~ ) assert_matching_output ( output . to_s , all_output ) else assert_partial_output ( output , all_output ) end end | Assert that the output contains the specified warning . |
5,284 | def notifications ( ast ) return [ ] unless ast . respond_to? ( :xpath ) notification_nodes ( ast ) . map do | notify | notified_resource = if new_style_notification? ( notify ) new_style_notification ( notify ) else old_style_notification ( notify ) end next unless notified_resource notified_resource . merge ( { type ... | Extracts notification details from the provided AST returning an array of notification hashes . |
5,285 | def notification_action ( notify ) is_variable = true unless notify . xpath ( "args_add_block/args_add//args_add[aref or vcall or call or var_ref]" ) . empty? string_val = notify . xpath ( "descendant::args_add/string_literal/string_add/tstring_content/@value" ) . first symbol_val = notify . xpath ( 'descendant::args_a... | return the notification action as either a symbol or string or nil if it s a variable . Yes you can notify an action as a string but it s wrong and we want to return it as a string so we can tell people not to do that . |
5,286 | def cookbook_that_matches_rules ( codes ) recipe = "" codes . each do | code | if code == "FC002" recipe += %q{ directory "#{node['base_dir']}" do action :create end } elsif code == "FC004" recipe += %q{ execute "stop-jetty" do command "/etc/init.d/jet... | Create a cookbook that will match the specified rules . |
5,287 | def cookbook_with_lwrp ( lwrp ) lwrp = { :default_action => false , :notifies => :does_not_notify , :use_inline_resources => false } . merge! ( lwrp ) ruby_default_action = %q{ def initialize(*args) super @action = :create end } . strip write_resource ( "site" , %Q{ actions :... | Create a cookbook with a LRWP |
5,288 | def cookbook_with_maintainer ( name , email ) write_recipe %q{ # # Cookbook Name:: example # Recipe:: default # # Copyright 2011, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # } fields = { } fields [ "maintainer" ] = name unless name . nil... | Create an cookbook with the maintainer specified in the metadata |
5,289 | def rakefile ( task , options ) rakefile_content = "task :default => []" task_def = case task when :no_block then "FoodCritic::Rake::LintTask.new" else %Q{ FoodCritic::Rake::LintTask.new do |t| #{"t.name = '#{options[:name]}'" if options[:name]} #{"t.files = #{options[:files]}" if options... | Create a Rakefile that uses the linter rake task |
5,290 | def recipe_installs_gem ( type , action = :install ) case type when :simple write_recipe %Q{ gem_package "bluepill" do action :#{action} end } . strip when :compile_time write_recipe %Q{ r = gem_package "mysql" do action :nothing end ... | Install a gem using the specified approach . |
5,291 | def recipe_with_dependency ( dep ) dep = { :is_scoped => true , :is_declared => true , :parentheses => false } . merge! ( dep ) recipe = "foo#{dep[:is_scoped] ? '::default' : ''}" write_recipe ( if dep [ :parentheses ] "include_recipe('#{recipe}')" else "include_recipe '#{recipe}'" end ) write_metadata %Q{ versi... | Create a recipe with an external dependency on another cookbook . |
5,292 | def recipe_with_ruby_block ( length ) recipe = "" if length == :short || length == :both recipe << %q{ ruby_block "subexpressions" do block do rc = Chef::Util::FileEdit.new("/foo/bar.conf") rc.search_file_replace_line(/^search/, "search #{node["foo"]["bar"]} compute-1.internal") ... | Create a recipe with a ruby_block resource . |
5,293 | def role ( options = { } ) options = { :format => :ruby , :dir => "roles" } . merge ( options ) content = if options [ :format ] == :json %Q{ { "chef_type": "role", "json_class": "Chef::Role", #{Array(options[:role_name]).map { |r| "name:... | Create a role file |
5,294 | def to_s @warnings . map do | w | [ "#{w.rule.code}: #{w.rule.name}: #{w.match[:filename]}" , w . match [ :line ] . to_i ] end . sort do | x , y | x . first == y . first ? x [ 1 ] <=> y [ 1 ] : x . first <=> y . first end . map { | w | "#{w.first}:#{w[1]}" } . uniq . join ( "\n" ) end | Returns a string representation of this review . This representation is liable to change . |
5,295 | def get_artifact ( job_name , filename ) @artifact = job . find_artifact ( job_name ) response = make_http_request ( Net :: HTTP :: Get . new ( @artifact ) ) if response . code == "200" File . write ( File . expand_path ( filename ) , response . body ) else raise "Couldn't get the artifact" end end | Connects to the server and downloads artifacts to a specified location |
5,296 | def get_artifacts ( job_name , dldir , build_number = nil ) @artifacts = job . find_artifacts ( job_name , build_number ) results = [ ] @artifacts . each do | artifact | uri = URI . parse ( artifact ) http = Net :: HTTP . new ( uri . host , uri . port ) http . verify_mode = OpenSSL :: SSL :: VERIFY_NONE http . use_ssl ... | Connects to the server and download all artifacts of a build to a specified location |
5,297 | def make_http_request ( request , follow_redirect = @follow_redirects ) request . basic_auth @username , @password if @username request [ 'Cookie' ] = @cookies if @cookies if @proxy_ip case @proxy_protocol when 'http' http = Net :: HTTP :: Proxy ( @proxy_ip , @proxy_port ) . new ( @server_ip , @server_port ) when 'sock... | Connects to the Jenkins server sends the specified request and returns the response . |
5,298 | def api_get_request ( url_prefix , tree = nil , url_suffix = "/api/json" , raw_response = false ) url_prefix = "#{@jenkins_path}#{url_prefix}" to_get = "" if tree to_get = "#{url_prefix}#{url_suffix}?#{tree}" else to_get = "#{url_prefix}#{url_suffix}" end request = Net :: HTTP :: Get . new ( to_get ) @logger . debug "G... | Sends a GET request to the Jenkins CI server with the specified URL |
5,299 | def api_post_request ( url_prefix , form_data = { } , raw_response = false ) retries = @crumb_max_retries begin refresh_crumbs request = Net :: HTTP :: Post . new ( "#{@jenkins_path}#{url_prefix}" ) @logger . debug "POST #{url_prefix}" if @crumbs_enabled request [ @crumb [ "crumbRequestField" ] ] = @crumb [ "crumb" ] e... | Sends a POST message to the Jenkins CI server with the specified URL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.