idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
22,400
def read ( klass ) size = Delimited . read_uvarint ( io ) klass . decode io . read ( size ) unless size . zero? end
Reads the next message
22,401
def _dirjson ( x ) x = Pathname . new ( x ) x . entries . find_all { | f | f . to_s =~ / \. /i } . map { | f | x + f } end
Search directories for JSON files
22,402
def compile_parser ( * args ) options = @@defaults . dup grammar = nil for arg in args case arg when Hash then options . merge! ( arg ) when String then grammar = arg end end base_class = options . delete ( :class ) || ( Rattler :: Runtime :: const_get @@parser_types [ options [ :type ] ] ) Rattler :: Compiler . compile_parser ( base_class , grammar , options ) end
Define a parser with the given grammar and compile it into a parser class using the given options
22,403
def default_backend = ( value ) raise ArgumentError , "default_backend must be a symbol!" unless value . is_a? Symbol unless @backends . keys . include? value raise ArgumentError , "Unregistered backend cannot be set as default!" end @default_backend = value end
Specify default sms backend . It must be registered .
22,404
def register_backend ( key , classname , params = { } ) raise ArgumentError , "backend key must be a symbol!" unless key . is_a? Symbol unless classname . class == Class raise ArgumentError , "backend class must be class (not instance or string)" end unless classname . method_defined? :send_sms raise ArgumentError , "backend must provide method send_sms" end define_backend ( key , classname , params ) end
Register sms provider backend
22,405
def fetch cfg = File . file? ( @default ) ? YAML . load_file ( @default ) : { } local = fetch_local hsh = strict_merge_with_env ( default : cfg , local : local , prefix : @prefix ) hsh . extend ( :: CConfig :: HashUtils :: Extensions ) hsh . defaults = cfg hsh end
Instantiate an object with default as the path to the default configuration local as the alternate file and prefix as the prefix for environment variables . The prefix will take cconfig as the default .
22,406
def fetch_local if File . file? ( @local ) local = YAML . load_file ( @local ) raise FormatError unless local . is_a? ( :: Hash ) local else { } end end
Returns a hash with the alternate values that have to override the default ones .
22,407
def captcha_challenge ( object_name , options = { } ) options . symbolize_keys! object = options . delete ( :object ) sanitized_object_name = object_name . to_s . gsub ( / \] \[ / , "_" ) . sub ( / / , "" ) ValidatesCaptcha . provider . render_challenge sanitized_object_name , object , options end
Returns the captcha challenge .
22,408
def captcha_field ( object_name , options = { } ) options . delete ( :id ) hidden_field ( object_name , :captcha_challenge , options ) + text_field ( object_name , :captcha_solution , options ) end
Returns an input tag of the text type tailored for entering the captcha solution .
22,409
def regenerate_captcha_challenge_link ( object_name , options = { } , html_options = { } ) options . symbolize_keys! object = options . delete ( :object ) sanitized_object_name = object_name . to_s . gsub ( / \] \[ / , "_" ) . sub ( / / , "" ) ValidatesCaptcha . provider . render_regenerate_challenge_link sanitized_object_name , object , options , html_options end
By default returns an anchor tag that makes an AJAX request to fetch a new captcha challenge and updates the current challenge after the request is complete .
22,410
def sitemap_capture_segments ( segment_mappings = { } , segments = [ ] ) values = { } if segments . kind_of? ( Array ) unless segment_mappings . blank? segments . each do | key | attribute_name = segment_mappings [ key . to_sym ] . blank? ? key : segment_mappings [ key . to_sym ] if self . respond_to? ( attribute_name ) values [ key ] = self . send ( attribute_name ) end end end segments . each do | key | unless values . has_key? ( key ) if self . respond_to? ( key ) values [ key ] = self . send ( key ) end end end end return values end
Segment keys are placeholders for the values that are plugged into a named route when it is constructed .
22,411
def each if block_given? line_number = 1 expanded_line = nil map_lines ( @io . each_line . lazy ) . each do | line | if line . end_with? ( LINE_CONTINUATOR ) expanded_line = "#{expanded_line}#{line.chomp(LINE_CONTINUATOR)}" else expanded_line = "#{expanded_line}#{line}" ast_results = [ ] PARSERS . map do | parser | parser . parse ( expanded_line ) { | ast | ast_results << ast } end yield [ line_number , expanded_line , ast_results ] line_number += 1 expanded_line = nil end end else enum_for ( :each ) end end
Yields AST results for each line of the IO .
22,412
def ping ( data , timeout = 1 ) if data . kind_of? Numeric data = "\0" * data end data += "\0" * ( 64 - data . length ) if data . length < 64 ping_packet = [ @dest_mac , @source_mac , @ether_type , data ] . join response = nil receive_ts = nil send_ts = nil begin Timeout . timeout timeout do send_ts = Time . now @socket . send ping_packet , 0 response = @socket . recv ping_packet . length * 2 receive_ts = Time . now end rescue Timeout :: Error response = nil end return false unless response response_packet = [ @source_mac , @dest_mac , @ether_type , data ] . join response == response_packet ? receive_ts - send_ts : [ response , response_packet ] end
Pings over raw Ethernet sockets .
22,413
def =~ ( domain ) labels . zip ( domain . labels ) . all? { | r , d | [ "*" , d ] . include? r } end
match against a domain name . the domain must be an instance of DomainName
22,414
def each ( unit , options = { } , & block ) iterate ( unit , options . merge ( :map_result => false ) , & block ) end
Executes passed block for each unit of time specified with a new time object for each interval passed to the block .
22,415
def beginning_of_each ( unit , options = { } , & block ) iterate ( unit , options . merge ( :map_result => false , :beginning_of => true ) , & block ) end
Executes passed block for each unit of time specified with a new time object set to the beginning of unit for each interval passed to the block .
22,416
def map_each ( unit , options = { } , & block ) iterate ( unit , options . merge ( :map_result => true ) , & block ) end
Executes passed block for each unit of time specified returning an array with the return values from the passed block .
22,417
def map_beginning_of_each ( unit , options = { } , & block ) iterate ( unit , options . merge ( :map_result => true , :beginning_of => true ) , & block ) end
Executes passed block for each unit of time specified returning an array with the return values from passed block . Additionally the time object passed into the block is set to the beginning of specified unit .
22,418
def build_info ( key , options = { } ) options = DEFAULT_OPTIONS . merge ( options ) note_type = TYPES . fetch ( options . fetch ( :type , :note ) . to_s ) account_name = options . fetch ( :account_name , "" ) service_name = options . fetch ( :service_name , key ) label = options . fetch ( :label , service_name ) { account_name : account_name , service_name : service_name , label : label , kind : note_type . fetch ( :kind ) , type : note_type . fetch ( :type ) , } end
Build an entry info hash .
22,419
def parse_contents ( password_string ) unpacked = password_string [ / /i , 1 ] password = if unpacked [ unpacked ] . pack ( "H*" ) else password_string [ / /m , 1 ] end password ||= "" parsed = Plist . parse_xml ( password . force_encoding ( "" . encoding ) ) if parsed and parsed [ "NOTE" ] parsed [ "NOTE" ] else password end end
Parse entry contents .
22,420
def split ( path , marker = nil ) marker ||= SPLIT_MARKER content = File . read ( path ) filename = File . basename ( path , '.*' ) yfm , content = retrieveYFM ( content ) contents = [ filename ] + content . split ( marker ) prev_name = filename contents . each_slice ( 2 ) . with ( { } ) do | ( fname , text ) , h | fname = prev_name = create_filename ( prev_name ) if fname . strip . empty? h [ fname . strip ] = yfm + text end end
Split a file with SPLIT_MARKER . Returns a Hash of filename key with its content .
22,421
def apply_events ( events ) events . each do | event | method_name = event_handler ( event ) public_send ( method_name , event . data ) if respond_to? ( method_name ) end @revision = events . last &. revision . to_i if events . last . respond_to? ( :revision ) end
Replay events building up the state of the aggregate . Used by Repository .
22,422
def get_pandoc return if has_pandoc Dir . mktmpdir do | dir | Dir . chdir ( dir ) do system ( "wget #{PANDOC_URL} -O pandoc.deb" ) system ( "sudo dpkg -i pandoc.deb" ) end end end
FIXME make this conditional to different types of platforms
22,423
def build clean unless @configuration . skip_clean @configuration . timestamp_plist if @configuration . timestamp_build print "Building Project..." success = xcodebuild @configuration . build_arguments , "build" raise "** BUILD FAILED **" unless success puts "Done" end
desc Build the beta release of the app
22,424
def pod_dry_run print "Pod dry run..." repos = resolved_repos . join "," result = system "pod lib lint #{@configuration.podspec_file} --allow-warnings --sources=#{repos}" raise "** Pod dry run failed **" if ! result puts "Done" end
runs a pod dry run before tagging
22,425
def percentile ( perc ) if perc > 100.0 || perc < 0.0 raise InvalidPercentile , "percentile must be between 0.0 and 100.0" end return 0.0 if data . empty? rank = ( perc / 100.0 ) * ( size + 1 ) return data [ 0 ] if rank < 1 return data [ - 1 ] if rank > size return data [ rank - 1 ] if rank == Integer ( rank ) weighted_average_for ( rank ) end
Generate a percentile for the data set .
22,426
def weighted_average_for ( rank ) above = data [ rank . to_i ] below = data [ rank . to_i - 1 ] fractional = rank - rank . floor below + ( ( above - below ) * fractional ) end
when rank lands between values generated a weighted average of adjacent values
22,427
def to_s ( fmt = nil , coljoin = ', ' , rowjoin = '; ' ) if fmt x = rows_to_a '[' + x . map do | r | if Enumerable === r r . map { | e | sprintf ( fmt , e ) } . join ( coljoin ) else sprintf ( fmt , r ) end end . join ( rowjoin ) + ']' else toString end end
Convert this matrix to a string .
22,428
def by_name_and_dob ( lname , fname , year , month , day ) body = self . gov_talk_request ( { service : 'GetDataUsingCriteriaParameter' , message : 'CRAGetDataUsingCriteria' , class : 'CRAGetDataUsingCriteria' , params : { LastName : lname , FirstName : fname , Year : year , Month : month , Day : day , } } ) CRA :: PassportInfo . list_with_hash ( body ) end
Returns array of passports .
22,429
def by_id_card ( private_number , id_card_serial , id_card_numb ) body = self . gov_talk_request ( { service : 'GetDataUsingPrivateNumberAndIdCardParameter' , message : 'GetDataUsingPrivateNumberAndCard' , class : 'GetDataUsingPrivateNumberAndCard' , params : { PrivateNumber : private_number , IdCardSerial : id_card_serial , IdCardNumber : id_card_numb , } } ) CRA :: PassportInfo . init_with_hash ( body ) end
Returns ID card information .
22,430
def by_passport ( private_number , passport ) body = self . gov_talk_request ( { service : 'FetchPersonInfoByPassportNumberUsingCriteriaParameter' , message : 'CRA_FetchInfoByPassportCriteria' , class : 'CRA_FetchInfoByPassportCriteria' , params : { PrivateNumber : private_number , Number : passport } } ) CRA :: PassportInfo . init_with_hash ( body ) end
Returns passport information .
22,431
def address_by_name ( parent_id , name ) body = self . gov_talk_request ( { service : 'AddrFindeAddressByNameParameter' , message : 'CRA_AddrFindeAddressByName' , class : 'CRA_AddrFindeAddressByName' , params : { Id : parent_id , Word : name , } } ) CRA :: Address . list_from_hash ( body [ 'ArrayOfResults' ] [ 'Results' ] ) end
Returns array of addresses .
22,432
def address_by_parent ( parent_id ) body = self . gov_talk_request ( { message : 'CRA_AddrGetNodesByParentID' , class : 'CRA_AddrGetNodesByParentID' , params : { long : parent_id , } } ) CRA :: AddressNode . list_from_hash ( body [ 'ArrayOfNodeInfo' ] [ 'NodeInfo' ] ) end
Returns array of address nodes .
22,433
def address_info ( id ) body = self . gov_talk_request ( { message : 'CRA_AddrGetAddressInfoByID' , class : 'CRA_AddrGetAddressInfoByID' , params : { long : id , } } ) CRA :: AddressInfo . init_from_hash ( body [ 'AddressInfo' ] ) end
Get address info by it s id .
22,434
def persons_at_address ( address_id ) body = self . gov_talk_request ( { message : 'CRA_GetPersonsAtAddress' , class : 'CRA_GetPersonsAtAddress' , params : { long : address_id , } } ) CRA :: PersonAtAddress . list_from_hash ( body [ 'ArrayOfPersonsAtAddress' ] ) end
Get persons array at the given address .
22,435
def user ( id , & callback ) http ( :get , "/users/#{id}.json" ) do | data , http | Firering :: User . instantiate ( self , data , :user , & callback ) end end
returns a user by id
22,436
def room ( id , & callback ) http ( :get , "/room/#{id}.json" ) do | data , http | Firering :: Room . instantiate ( self , data , :room , & callback ) end end
returns a room by id
22,437
def search_messages ( query , & callback ) http ( :get , "/search/#{query}.json" ) do | data , http | callback . call ( data [ :messages ] . map { | msg | Firering :: Message . instantiate ( self , msg ) } ) if callback end end
Returns all the messages containing the supplied term .
22,438
def star_message ( id , yes_or_no = true , & callback ) http ( yes_or_no ? :post : :delete , "/messages/#{id}/star.json" ) do | data , http | callback . call ( data ) if callback end end
Toggles the star next to a message
22,439
def defaults @values = Hash [ self . class . options . select { | _ , c | c . key? ( :default ) } . map { | n , c | [ n , c [ :default ] ] } ] . merge ( @values ) end
Get a hash of all options with default values . The list of values is initialized with the result .
22,440
def read_yaml ( path ) return unless File . exist? ( path ) source = YAML . load_file ( path ) return unless source . is_a? ( Hash ) update_with { | config | read_yaml_key ( source , config [ :key ] ) } end
Attempt to read option keys from a YAML file
22,441
def update_with ( & blk ) self . class . options . each do | name , config | value = yield ( config ) @values [ name ] = value unless value . nil? end end
For every option we yield the configuration and expect a value back . If the block returns a value we set the option to it .
22,442
def add_collector ( collector_class ) return collector_class . each { | c | add_collector ( c ) } if collector_class . is_a? Array raise ArgumentError , "`collector_class' must be a class" unless collector_class . is_a? Class unless collector_class . included_modules . include? ( Rack :: WebProfiler :: Collector :: DSL ) raise ArgumentError , "#{collector_class.class.name} must be an instance of \"Rack::WebProfiler::Collector::DSL\"" end definition = collector_class . definition if definition_by_identifier ( definition . identifier ) raise ArgumentError , "A collector with identifier \“#{definition.identifier}\" already exists" end return false unless definition . is_enabled? @collectors [ collector_class ] = definition sort_collectors! end
Add a collector .
22,443
def sort_collectors! @sorted_collectors = { } tmp = @collectors . sort_by { | _klass , definition | definition . position } tmp . each { | _k , v | @sorted_collectors [ v . identifier . to_sym ] = v } end
Sort collectors by definition identifier .
22,444
def normalize_value ( val ) if val . is_a? ( Hash ) val = val [ "__content__" ] if val . has_key? ( "__content__" ) val = val . values . first if val . respond_to? ( :values ) && val . values . one? val = val . join ( " " ) if val . respond_to? ( :join ) val . to_s else val end end
Normalizes a value for the formatted hash values TVDB hashes should not contain more hashes Sometimes TVDB returns a hash with content inside which needs to be extracted
22,445
def parse_options! ( args ) @options = { } opts = :: OptionParser . new do | opts | opts . banner = "Usage: syswatch [options]\n\n Options:" opts . on ( "-f" , "--foreground" , "Do not daemonize, just run in foreground." ) do | f | @options [ :foreground ] = f end opts . on ( "-v" , "--verbose" , "Be verbose, print out some messages." ) do | v | @options [ :verbose ] = v end opts . on ( "-t" , "--test" , "Test notifications." ) do | t | @options [ :test ] = t end opts . on ( "-c" , "--config [FILE]" , "Use a specific config file, instead of `#{SysWatch::DEFAULTS[:config]}`" ) do | config | @options [ :config ] = config end end opts . parse! args end
Initialize a new system watcher
22,446
def locate_slugins Gem . refresh ( Gem :: Specification . respond_to? ( :each ) ? Gem :: Specification : Gem . source_index . find_name ( '' ) ) . each do | gem | next if gem . name !~ PREFIX slugin_name = gem . name . split ( '-' , 2 ) . last @slugins << Slugin . new ( slugin_name , gem . name , gem , true ) if ! gem_located? ( gem . name ) end @slugins end
Find all installed Pry slugins and store them in an internal array .
22,447
def to_hash ret = { } @hash . dup . each_pair do | key , val | ret [ key ] = self . convert_value_from_ostruct ( val ) end ret end
recursive open struct
22,448
def define_accessors ( field ) self . generated_methods . module_eval do define_method ( field ) do @hash [ field ] end define_method ( "#{field}=" ) do | val | @hash [ field ] = val end end end
define accessors for an attribute
22,449
def method_missing ( meth , * args , & block ) if meth . to_s =~ / / self . define_accessors ( meth . to_s . gsub ( / / , '' ) ) return self . send ( meth , * args , & block ) end super end
dynamically define getter and setter when an unknown setter is called
22,450
def underscore ( string ) string = string . to_s string = string [ 0 ] . downcase + string [ 1 .. - 1 ] . gsub ( / / , '_\1' ) string . downcase end
take a string an convert it from camelCase to under_scored
22,451
def handle_batch_multiple_actions actions = [ ] @batch . each do | action | actions << to_query ( action [ :params ] ) end results = really_make_call ( { 'method' => 'batch.run' , 'methodFeed' => JSON . dump ( actions ) } , :post ) @batch = nil extract_session_key results results end
This function handles making the call when there is more than one call in the batch .
22,452
def convert_to_rake ( ) object_multitask = prepare_tasks_for_objects ( ) archiver = @tcs [ :ARCHIVER ] res = typed_file_task Rake :: Task :: LIBRARY , get_task_name => object_multitask do cmd = calc_command_line aname = calc_archive_name Dir . chdir ( @project_dir ) do FileUtils . rm ( aname ) if File . exists? ( aname ) rd , wr = IO . pipe cmd << { :err => wr , :out => wr } sp = spawn ( * cmd ) cmd . pop consoleOutput = ProcessHelper . readOutput ( sp , rd , wr ) process_result ( cmd , consoleOutput , @tcs [ :ARCHIVER ] [ :ERROR_PARSER ] , "Creating #{aname}" ) check_config_file ( ) end end res . tags = tags enhance_with_additional_files ( res ) add_output_dir_dependency ( get_task_name , res , true ) add_grouping_tasks ( get_task_name ) setup_rake_dependencies ( res , object_multitask ) return res end
task that will link the given object files to a static lib
22,453
def ancestors a = Array . new self . parent . _ancestors ( a ) unless self . parent . nil? return a end
return all ancestors of this node
22,454
def move_children_to_parent children . each do | c | self . parent . children << c c . parent = self . parent end end
move all children to the parent node !!! need to perform validations here?
22,455
def validate_child! ( ch ) raise InvalidChild . create ( self , ch ) if ( ch == nil ) raise CircularRelation . create ( self , ch ) if self . descendant_of? ( ch ) if base_class . method_defined? :validate_child self . validate_child ( ch ) end end
perform validation on whether this child is an acceptable child or not? the base_class must have a method validate_child? to implement domain logic there
22,456
def do_setup if ( self . taxonomy_node == nil ) self . taxonomy_node = self . respond_to? ( :create_taxonomy_node ) ? self . create_taxonomy_node : Taxonomite :: Node . new self . taxonomy_node . owner = self end end
subclasses should overload create_taxonomy_node to create the appropriate Place object and set it up
22,457
def check_response ( response ) case response . code when 200 , 201 true when 401 raise Calculated :: Session :: PermissionDenied . new ( "Your Request could not be authenticated is your api key valid?" ) when 404 raise Calculated :: Session :: NotFound . new ( "Resource was not found" ) when 412 raise Calculated :: Session :: MissingParameter . new ( "Missing Parameter: #{response.body}" ) else raise Calculated :: Session :: UnknownError . new ( "super strange type unknown error: #{response.code} :body #{response.body}" ) end end
checking the status code of the response ; if we are not authenticated then authenticate the session
22,458
def add_fields ( row , attrs ) fields = ( @config . fields - @config . export_only_fields ) . map ( & :to_s ) fields . each do | name | row . has_key? name or next attrs [ name ] = row . field name end end
Adds configured fields to attrs
22,459
def add_has_manys ( row , attrs ) headers_length = row . headers . compact . length pairs_start_on_evens = headers_length . even? ( headers_length .. row . fields . length ) . each do | i | i . send ( pairs_start_on_evens ? :even? : :odd? ) || next row [ i ] || next m = row [ i ] . match ( / \w \d \w / ) m || next has_many_name = m [ 1 ] . pluralize has_many_index = m [ 2 ] . to_i has_many_field = m [ 3 ] has_many_value = row [ i + 1 ] has_many_config = @config . has_manys [ has_many_name . to_sym ] next unless has_many_config next unless has_many_config . fields . include? ( has_many_field . to_sym ) next if has_many_config . export_only_fields . include? ( has_many_field . to_sym ) attrs [ has_many_name ] ||= [ ] attrs [ has_many_name ] [ has_many_index ] ||= { } attrs [ has_many_name ] [ has_many_index ] [ has_many_field ] = has_many_value end end
Adds configured has manys to attrs
22,460
def add_has_ones ( row , attrs ) @config . has_ones . each do | name , assoc_config | fields = ( assoc_config . fields - assoc_config . export_only_fields ) . map ( & :to_s ) fields . each do | f | csv_name = "#{name}_#{f}" row . has_key? csv_name or next ( attrs [ name . to_s ] ||= { } ) [ f ] = row . field "#{name}_#{f}" end end end
Adds configured has ones to attrs
22,461
def of number raise_on_type_mismatch number digits = convert_number_to_digits ( number ) digits . reduce ( 0 ) { | check , digit | QUASIGROUP [ check ] [ digit ] } end
Calculates Damm checksum
22,462
def generate_sitemap ( basedir ) sitemap_file = File . join ( basedir , 'sitemap.xml' ) File . open ( sitemap_file , 'w' ) do | file | file . write ( sitemap_contents ( basedir ) ) end end
Generates a sitemap at + basedir +
22,463
def save if validate_attrs Activity . create ( activity_attrs ) . tap do | activity | Callbacks . run ( activity ) end else warning end end
This class is for internal usage . No need to initialize this manually instead use controller methods provided .
22,464
def http_headers env . select { | k , _v | ( k . start_with? ( "HTTP_" ) && k != "HTTP_VERSION" ) || k == "CONTENT_TYPE" } . collect { | k , v | [ k . sub ( / / , "" ) , v ] } . collect { | k , v | [ k . split ( "_" ) . collect ( & :capitalize ) . join ( "-" ) , v ] } end
Get HTTP headers .
22,465
def raw headers = http_headers . map { | k , v | "#{k}: #{v}\r\n" } . join format "%s %s %s\r\n%s\r\n%s" , request_method . upcase , fullpath , env [ "SERVER_PROTOCOL" ] , headers , body_string end
Get full HTTP request in HTTP format .
22,466
def copy_filter ( filter ) buffer = { exclude : { } , include : { } } filter [ :exclude ] . each do | part | buffer [ :exclude ] [ part [ 0 ] ] = part [ 1 ] . dup end filter [ :include ] . each do | part | buffer [ :include ] [ part [ 0 ] ] = part [ 1 ] . dup end return buffer end
Copies a filter
22,467
def clear_filter ( section , key ) key = key . kind_of? ( Symbol ) ? key : key . to_sym self . current_filter [ section ] [ key ] = [ ] return nil end
Clears a single type of filter .
22,468
def many? if block_given? to_a . many? { | * block_args | yield ( * block_args ) } else limit_value ? to_a . many? : size > 1 end end
Returns true if there is more than one record .
22,469
def status output = run ( "info" ) result = output . scan ( / \s \w \s \d / ) . flatten LXC :: Status . new ( result . first , result . last ) end
Get current status of container
22,470
def wait ( state ) if ! LXC :: Shell . valid_state? ( status . state ) raise ArgumentError , "Invalid container state: #{state}" end run ( "wait" , "-s" , state ) end
Wait for container to change status
22,471
def cpu_usage result = run ( "cgroup" , "cpuacct.usage" ) . to_s . strip result . empty? ? nil : Float ( "%.4f" % ( result . to_i / 1E9 ) ) end
Get container cpu usage in seconds
22,472
def processes raise ContainerError , "Container is not running" if ! running? str = run ( "ps" , "--" , "-eo pid,user,%cpu,%mem,args" ) . strip lines = str . split ( "\n" ) ; lines . delete_at ( 0 ) lines . map { | l | parse_process_line ( l ) } end
Get container processes
22,473
def create ( path ) raise ContainerError , "Container already exists." if exists? if path . is_a? ( Hash ) args = "-n #{name}" if ! ! path [ :config_file ] unless File . exists? ( path [ :config_file ] ) raise ArgumentError , "File #{path[:config_file]} does not exist." end args += " -f #{path[:config_file]}" end if ! ! path [ :template ] template_dir = path [ :template_dir ] || "/usr/lib/lxc/templates" template_path = File . join ( template_dir , "lxc-#{path[:template]}" ) unless File . exists? ( template_path ) raise ArgumentError , "Template #{path[:template]} does not exist." end args += " -t #{path[:template]} " end args += " -B #{path[:backingstore]}" if ! ! path [ :backingstore ] args += " -- #{path[:template_options].join(" ")}" . strip if ! ! path [ :template_options ] LXC . run ( "create" , args ) exists? else unless File . exists? ( path ) raise ArgumentError , "File #{path} does not exist." end LXC . run ( "create" , "-n" , name , "-f" , path ) exists? end end
Create a new container
22,474
def clone_to ( target ) raise ContainerError , "Container does not exist." unless exists? if LXC . container ( target ) . exists? raise ContainerError , "New container already exists." end LXC . run ( "clone" , "-o" , name , "-n" , target ) LXC . container ( target ) end
Clone to a new container from self
22,475
def clone_from ( source ) raise ContainerError , "Container already exists." if exists? unless LXC . container ( source ) . exists? raise ContainerError , "Source container does not exist." end run ( "clone" , "-o" , source ) exists? end
Create a new container from an existing container
22,476
def add ( name , ip_address , options = { } ) client = CpMgmt . configuration . client CpMgmt . logged_in? params = { name : name , "ip-address" : ip_address } body = params . merge ( options ) . to_json response = client . post do | req | req . url '/web_api/add-host' req . headers [ 'Content-Type' ] = 'application/json' req . headers [ 'X-chkp-sid' ] = ENV . fetch ( "sid" ) req . body = body end CpMgmt . transform_response ( response ) end
Adds a host
22,477
def show ( name ) client = CpMgmt . configuration . client CpMgmt . logged_in? body = { name : name } . to_json response = client . post do | req | req . url '/web_api/show-host' req . headers [ 'Content-Type' ] = 'application/json' req . headers [ 'X-chkp-sid' ] = ENV . fetch ( "sid" ) req . body = body end CpMgmt . transform_response ( response ) end
Shows a host
22,478
def show_all client = CpMgmt . configuration . client CpMgmt . logged_in? response = client . post do | req | req . url '/web_api/show-hosts' req . headers [ 'Content-Type' ] = 'application/json' req . headers [ 'X-chkp-sid' ] = ENV . fetch ( "sid" ) req . body = "{}" end CpMgmt . transform_response ( response ) end
Shows all hosts
22,479
def apply ( match_method_name ) start_pos = @scanner . pos if m = memo_lr ( match_method_name , start_pos ) recall m , match_method_name else lr = LR . new ( false , match_method_name , nil ) @lr_stack . push lr m = inject_memo match_method_name , start_pos , lr , start_pos result = eval_rule match_method_name @lr_stack . pop if lr . head m . end_pos = @scanner . pos lr . seed = result lr_answer match_method_name , start_pos , m else save m , result end end end
Create a new extended packrat parser to parse + source + .
22,480
def generic_objects_for_object_template ( name , params = { } ) api_call ( :get , "/object_templates/#{name}/generic_objects" , params ) do | response | Calculated :: Models :: ObjectTemplate . new ( response [ "object_template" ] ) end end
this request will have loaded generic objects for the ready basically
22,481
def relatable_categories_for_object_template ( name , related_attribute , params = { } ) api_call ( :get , "/object_templates/#{name}/relatable_categories" , params . merge! ( :related_attribute => related_attribute ) ) do | response | Calculated :: Models :: ObjectTemplate . new ( response [ "object_template" ] ) end end
this request will have loaded relatable categories for the object template
22,482
def generic_objects_for_object_template_with_filter ( name , filter , params = { } ) api_call ( :get , "/object_templates/#{name}/generic_objects/filter" , params . merge! ( :filter => filter ) ) do | response | Calculated :: Models :: ObjectTemplate . new ( response [ "object_template" ] ) end end
This will filter the results of the generic objects from a simple text search note this is not an expancive text search so limit to 1 word searches for best results
22,483
def sudo ( * arguments ) options = case arguments . last when Hash then arguments . pop else { } end task = SudoTask . new ( options . delete ( :sudo ) || { } ) task . command = [ @path ] + arguments arguments = task . arguments arguments << options unless options . empty? return System . sudo ( * arguments ) end
Runs the program under sudo .
22,484
def run_task ( task , options = { } ) arguments = task . arguments arguments << options unless options . empty? return run ( * arguments ) end
Runs the program with the arguments from the given task .
22,485
def sudo_task ( task , options = { } , & block ) arguments = task . arguments arguments << options unless options . empty? return sudo ( * arguments , & block ) end
Runs the program under sudo with the arguments from the given task .
22,486
def sitemap ( name = :sitemap , options = { } , & block ) options = name . kind_of? ( Hash ) ? name : options name = name . kind_of? ( String ) || name . kind_of? ( Symbol ) ? name : :sitemap config = { controller : :sitemap , url_limit : nil } . merge ( options ) sitemap_raw_route_name = "#{name}_sitemap" sitemap_route_name = name_for_action ( sitemap_raw_route_name , nil ) begin unless @set . routes . find { | route | route . name . eql? ( sitemap_route_name ) } match %(/#{name}.:format) , controller : config [ :controller ] , action : name , via : [ :get ] , as : sitemap_raw_route_name sitemap_route = @set . routes . find { | route | route . name . eql? ( sitemap_route_name ) } sitemap_route . is_sitemap = true sitemap_route . url_limit = config [ :url_limit ] sitemap_route . sitemap_route_name = sitemap_route_name sitemap_route . sitemap_raw_route_name = sitemap_raw_route_name sitemap_route . defaults [ :controller ] = "sitemap" end rescue ArgumentError => e unless e . message . include? ( "Invalid route name" ) raise e end end sitemap_route = @set . routes . find { | route | route . is_sitemap? && route . name . eql? ( sitemap_route_name ) } unless sitemap_route . sitemap_with_block? sitemap_route . sitemap_with_block = true if block_given? end unless DuckMap :: SitemapControllerHelpers . public_method_defined? ( name ) DuckMap :: SitemapControllerHelpers . send :define_method , name do if DuckMap :: Config . attributes [ :sitemap_content ] . eql? ( :xml ) sitemap_build end respond_to do | format | format . xml { render } end end end if block_given? start_point = @set . routes . length @set . sitemap_filters . push yield total = run_filter ( sitemap_route . sitemap_route_name , start_point ) @set . sitemap_filters . pop DuckMap . logger . debug %(total routes filtered: #{@set.routes.length - start_point} included? #{total}) @set . routes . each do | route | DuckMap . logger . debug %( Route name: #{route.name}) if route . sitemap_route_name . eql? ( sitemap_route . sitemap_route_name ) end end return nil end
Defines a sitemap for a Rails app .
22,487
def pack ( data ) values = [ ] data . each do | k , v | values . push ( [ k , v ] ) end mapped_directives = @directives . map ( & :name ) values = values . select { | x | mapped_directives . include? ( x [ 0 ] ) } values . sort! do | a , b | mapped_directives . index ( a [ 0 ] ) <=> mapped_directives . index ( b [ 0 ] ) end ary = values . map ( & :last ) ary . pack to_s ( data ) end
Packs the given data into a string . The keys of the data correspond to the names of the directives .
22,488
def unpack ( string ) total = "" parts = { } directives . each_with_index do | directive , i | total << directive . to_s ( parts ) parts [ directive . name ] = string . unpack ( total ) [ i ] end parts . delete ( :null ) { } parts end
Unpacks the given string with the directives . Returns a hash containing the values with the keys being the names of the directives .
22,489
def fast_unpack ( string ) out = string . unpack ( to_s ) parts = { } directives . each_with_index do | directive , i | parts [ directive . name ] = out [ i ] end parts . delete ( :null ) { } parts end
This unpacks the entire string at once . It assumes that none of the directives will need the values of other directives . If you re not sure what this means don t use it .
22,490
def method_missing ( method , * arguments , & block ) super if @finalized if arguments . length == 1 && arguments . first . is_a? ( Directive ) arguments . first . add_modifier Modifier . new ( method ) else ( directives . push Directive . new ( method ) ) . last end end
Creates a new directive with the given method and arguments .
22,491
def invoke_dependencies ( * args , options ) self . dependencies . each do | name | if task = self . class [ name ] task . call ( * args , options ) elsif File . exist? ( name ) task_will_run? ( name ) else raise TaskNotFound , "Task with name #{name} doesn't exist" end end end
return true if the task need to be executed false otherwise
22,492
def _ensure_all_items_in_array_are_allowed ( ary ) return if ary . is_a? self . class _ensure_item_is_allowed ( ary , [ Array ] ) ary . each { | item | _ensure_item_is_allowed ( item ) } end
Ensure that all items in the passed Array are allowed
22,493
def _ensure_item_is_allowed ( item , expected = nil ) return if item . nil? expected ||= self . class . restricted_types return if expected . any? { | allowed | item . class <= allowed } raise TypedArray :: UnexpectedTypeException . new ( expected , item . class ) end
Ensure that the specific item passed is allowed
22,494
def parse ( scanner , rules , scope = ParserScope . empty ) backtracking ( scanner ) do if scope = parse_children ( scanner , rules , scope . nest ) yield scope if block_given? parse_result ( scope ) end end end
Try each parser in sequence and if they all succeed return an array of captured results or return + false + if any parser fails .
22,495
def get_tag ( tag_type ) matches = @tags . select { | m | m . type == tag_type } return matches . first end
Return the Tag that matches the given class
22,496
def add ( options = { } ) self . options = options raise ( ArgumentError , 'Mandatory param :name missing' ) unless options [ :name ] if options [ :feature ] features << options SafetyCone :: ViewHelpers . add_method ( options [ :feature ] ) else paths [ make_key ] = options end end
Method add a route or method to be managed by safety cone
22,497
def make_key if options . key? :method options [ :method ] . to_sym elsif options . include? ( :controller ) && options . include? ( :action ) "#{options[:controller]}_#{options[:action]}" . to_sym else raise ( ArgumentError , 'Options should contain :controller and :action or :method.' ) end end
Method to generate a key from the options
22,498
def get options = { } additional_params = options . delete ( :params ) || { } connection ( options ) . get do | req | req . url parsed_url . path req . params = additional_params . merge ( { :url => resource_url , :format => "json" } ) end end
Requests the oembeddable resource
22,499
def create_custom_field! ( params ) response = @@soap . createListCustomField ( :apiKey => @apiKey , :listID => @listID , :fieldName => params [ :fieldName ] , :dataType => params [ :dataType ] , :options => params . fetch ( :options , "" ) ) handle_response response . list_CreateCustomFieldResult end
Creates a new custom field for a list