idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
11,500
def create_socket socket = :: Socket . new ( :: Socket :: AF_INET , :: Socket :: SOCK_STREAM , 0 ) sockaddr = :: Socket . sockaddr_in ( PORTS . sample , self . hostname ) begin socket . connect_nonblock ( sockaddr ) rescue IO :: WaitWritable IO . select ( nil , [ socket ] ) begin socket . connect_nonblock ( sockaddr ) ...
Create a new socket connection with DeathByCaptcha API . This method is necessary because Ruby 1 . 9 . 7 doesn t support connection timeout and only Ruby 2 . 2 . 0 fixes a bug with unsafe sockets threads .
11,501
def perform ( action , method = :get , payload = { } ) payload . merge! ( username : self . username , password : self . password ) headers = { 'User-Agent' => DeathByCaptcha :: API_VERSION } if method == :post uri = URI ( "http://#{self.hostname}/api/#{action}" ) req = Net :: HTTP :: Post . new ( uri . request_uri , h...
Perform an HTTP request to the DeathByCaptcha API .
11,502
def create @message = Message . new ( message_params ) if @message . valid? MessageMailer . message_me ( @message ) . deliver_now redirect_to new_message_path , notice : "Thank you for your message." else render :new end end
Create Message from Info Entered
11,503
def message_me ( msg ) @msg = msg mail from : @msg . email , subject : @msg . subject , body : @msg . content end
Put Togther Messange
11,504
def send_input ( input ) raise ArgumentError if input . nil? or input . try ( :empty? ) input . each_char { | char | @input . putc ( char ) } end
Sends input to the slave process STDIN .
11,505
def pending_output ( chunk_len = 49152 ) return unless pending_output? pending = String . new while chunk = @output . read_nonblock ( chunk_len ) pending << chunk end pending . force_encoding ( 'UTF-8' ) rescue IO :: WaitReadable pending . force_encoding ( 'UTF-8' ) rescue raise Closed if READING_ON_CLOSED_END_ERRORS ....
Gets the pending output of the process .
11,506
def flatten_params ( obj , ns = nil ) case obj when Hash pairs = obj . map { | k , v | flatten_params ( v , ns ? "#{ns}[#{k}]" : k ) } pairs . empty? ? [ ] : pairs . inject ( & :+ ) when Array obj . map { | v | flatten_params ( v , "#{ns}[]" ) } . inject ( & :+ ) || [ ] when Time [ [ ns . to_s , iso_format_time ( obj )...
Flatten a hash containing nested hashes and arrays to a non - nested array of key - value pairs .
11,507
def iso_format_time ( time ) return time unless time . is_a? Time or time . is_a? Date time = time . getutc if time . is_a? Time time = time . new_offset ( 0 ) if time . is_a? DateTime time . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) end
Format a Time object according to ISO 8601 and convert to UTC .
11,508
def stringify_times ( obj ) case obj when Hash Hash [ obj . map { | k , v | [ k , stringify_times ( v ) ] } ] when Array obj . map { | v | stringify_times ( v ) } else iso_format_time ( obj ) end end
Recursively ISO format all time and date values .
11,509
def load_page ( page_num ) params = @query . merge ( pagination_params ( page_num ) ) response = @client . api_request ( :get , @path , :params => params ) metadata = parse_metadata ( response ) @num_records , @num_pages = metadata [ 'records' ] , metadata [ 'pages' ] Page . new ( @resource_class , response . parsed , ...
Fetch and return a single page .
11,510
def each_page page_obj = load_page ( 1 ) loop do yield page_obj break unless page_obj . has_next? page_obj = load_page ( page_obj . next_page ) end end
Fetch and yield each page of results .
11,511
def authorize_url ( options ) raise ArgumentError , ':redirect_uri required' unless options [ :redirect_uri ] params = { :client_id => @app_id , :response_type => 'code' , :scope => 'manage_merchant' } options = Hash [ Utils . flatten_params ( options ) ] @oauth_client . authorize_url ( params . merge ( options ) ) end
Generate the OAuth authorize url
11,512
def fetch_access_token ( auth_code , options ) raise ArgumentError , ':redirect_uri required' unless options [ :redirect_uri ] @access_token = @oauth_client . auth_code . get_token ( auth_code , options ) scope = @access_token . params [ :scope ] || @access_token . params [ 'scope' ] set_merchant_id_from_scope ( scope ...
Exchange the authorization code for an access token
11,513
def access_token = ( token ) token , scope = token . sub ( / \s /i , '' ) . split ( ' ' , 2 ) if scope warn "[DEPRECATION] (gocardless-ruby) merchant_id is now a separate " + "attribute, the manage_merchant scope should no longer be " + "included in the 'token' attribute. See http://git.io/G9y37Q " + "for more info." e...
Set the client s access token
11,514
def set_merchant_id_from_scope ( scope ) perm = scope . split . select { | p | p . start_with? ( 'manage_merchant:' ) } . first @merchant_id = perm . split ( ':' ) [ 1 ] if perm end
Pull the merchant id out of the access scope
11,515
def request ( method , path , opts = { } ) raise ClientError , 'Access token missing' unless @access_token opts [ :headers ] = { } if opts [ :headers ] . nil? opts [ :headers ] [ 'Accept' ] = 'application/json' opts [ :headers ] [ 'Content-Type' ] = 'application/json' unless method == :get opts [ :headers ] [ 'User-Age...
Send a request to the GoCardless API servers
11,516
def prepare_params ( params ) params = Utils . symbolize_keys ( Hash [ params ] ) keys = [ :resource_id , :resource_type , :resource_uri , :state , :signature ] params = Hash [ params . select { | k , v | keys . include? k } ] ( keys - [ :state ] ) . each do | key | raise ArgumentError , "Parameters missing #{key}" if ...
Prepare a Hash of parameters for signing . Presence of required parameters is checked and the others are discarded .
11,517
def new_limit_url ( type , limit_params ) url = URI . parse ( "#{base_url}/connect/#{type}s/new" ) limit_params [ :merchant_id ] = merchant_id redirect_uri = limit_params . delete ( :redirect_uri ) cancel_uri = limit_params . delete ( :cancel_uri ) state = limit_params . delete ( :state ) params = { :nonce => generate_...
Generate the URL for creating a limit of type + type + including the provided params nonce timestamp and signature
11,518
def run ( scope , * args ) inject ( Results . new ) do | results , callback | executed = execute_callback ( scope , callback , * args ) return results . halted! unless continue_execution? ( executed ) results << executed end end
The chain contains the return values of the executed callbacks .
11,519
def command? ( cmd ) ! ! system ( cmd , out : :: File :: NULL , err : :: File :: NULL ) end
Check if command can be run
11,520
def remove ( spy ) if @constant_spies [ spy . constant_name ] == spy @constant_spies . delete ( spy . constant_name ) else raise NoSpyError , "#{spy.constant_name} was not stubbed on #{base_module.name}" end self end
removes the spy from the records
11,521
def hook ( opts = { } ) raise AlreadyHookedError , "#{base_object} method '#{method_name}' has already been hooked" if self . class . get ( base_object , method_name , singleton_method ) @hook_opts = opts @original_method_visibility = method_visibility_of ( method_name ) hook_opts [ :visibility ] ||= original_method_vi...
set what object and method the spy should watch
11,522
def unhook raise NeverHookedError , "'#{method_name}' method has not been hooked" unless hooked? method_owner . send ( :remove_method , method_name ) if original_method && method_owner == original_method . owner original_method . owner . send ( :define_method , method_name , original_method ) original_method . owner . ...
unhooks method from object
11,523
def and_yield ( * args ) yield eval_context = Object . new if block_given? @plan = Proc . new do | & block | eval_context . instance_exec ( * args , & block ) end self end
Tells the object to yield one or more args to a block when the message is received .
11,524
def and_call_through if @base_object . is_a? Class @plan = Proc . new do | object , * args , & block | if original_method if original_method . is_a? UnboundMethod bound_method = original_method . bind ( object ) bound_method . call ( * args , & block ) else original_method . call ( * args , & block ) end else base_obje...
tells the spy to call the original method
11,525
def has_been_called_with? ( * args ) raise NeverHookedError unless @was_hooked match = block_given? ? Proc . new : proc { | call | call . args == args } calls . any? ( & match ) end
check if the method was called with the exact arguments
11,526
def invoke ( object , args , block , called_from ) check_arity! ( args . size ) if base_object . is_a? Class result = if @plan check_for_too_many_arguments! ( @plan ) @plan . call ( object , * args , & block ) end else result = if @plan check_for_too_many_arguments! ( @plan ) @plan . call ( * args , & block ) end end e...
invoke that the method has been called . You really shouldn t use this method .
11,527
def recruit ( spy ) raise AlreadyStubbedError if @spies [ spy . object_id ] check_spy! ( spy ) @spies [ spy . object_id ] = spy end
Record that a spy was initialized and hooked
11,528
def hook ( opts = { } ) opts [ :force ] ||= false Nest . fetch ( base_module ) . add ( self ) Agency . instance . recruit ( self ) @previously_defined = currently_defined? if previously_defined? || ! opts [ :force ] @original_value = base_module . const_get ( constant_name , false ) end and_return ( @new_value ) self e...
stashes the original constant then overwrites it with nil
11,529
def unhook Nest . get ( base_module ) . remove ( self ) Agency . instance . retire ( self ) and_return ( @original_value ) if previously_defined? @original_value = @previously_defined = nil self end
restores the original value of the constant or unsets it if it was unset
11,530
def method ( method_name ) new_method = super parameters = new_method . parameters if parameters . size >= 1 && parameters . last . last == :mock_method self . class . instance_method ( method_name ) . bind ( self ) else new_method end end
returns the original class method if the current method is a mock_method
11,531
def text_field ( name , row , column , length , editable = true ) define_method ( name ) do platform . get_string ( row , column , length ) end define_method ( "#{name}=" ) do | value | platform . put_string ( value , row , column ) end if editable end
adds two methods to the screen object - one to set text in a text field another to retrieve text from a text field .
11,532
def populate_screen_with ( hsh ) hsh . each do | key , value | self . send ( "#{key}=" , value ) if self . respond_to? "#{key}=" . to_sym end end
This method will populate all matched screen text fields from the Hash passed as an argument . The way it find an element is by matching the Hash key to the name you provided when declaring the text field on your screen .
11,533
def size_of frame_type detection = "is_#{frame_type.to_s.sub(/frames$/, 'frame')}?" @meta . select { | m | Frame . new ( nil , m [ :id ] , m [ :flag ] ) . send detection } . size end
Returns the number of the specific + frame_type + .
11,534
def concat other_frames raise TypeError unless other_frames . kind_of? ( Frames ) this_data = Tempfile . new 'this' , binmode : true self . frames_data_as_io this_data other_data = Tempfile . new 'other' , binmode : true other_frames . frames_data_as_io other_data this_size = this_data . size other_data . rewind while ...
Appends the frames in the other Frames into the tail of self . It is destructive like Array does .
11,535
def * times result = self . slice 0 , 0 frames = self . slice 0 .. - 1 times . times do result . concat frames end result end
Returns the new Frames as a + times + times repeated concatenation of the original Frames .
11,536
def slice * args b , l = get_beginning_and_length * args if l . nil? self . at b else e = b + l - 1 r = self . to_avi r . frames . each_with_index do | f , i | unless i >= b && i <= e f . data = nil end end r . frames end end
Returns the Frame object at the given index or returns new Frames object that sliced with the given index and length or with the Range . Just like Array .
11,537
def at n m = @meta [ n ] return nil if m . nil? @io . pos = @pos_of_movi + m [ :offset ] + 8 frame = Frame . new ( @io . read ( m [ :size ] ) , m [ :id ] , m [ :flag ] ) @io . rewind frame end
Returns one Frame object at the given index .
11,538
def push frame raise TypeError unless frame . kind_of? Frame this_data = Tempfile . new 'this' , binmode : true self . frames_data_as_io this_data this_size = this_data . size this_data . print frame . id this_data . print [ frame . data . size ] . pack ( 'V' ) this_data . print frame . data this_data . print "\000" if...
Appends the given Frame into the tail of self .
11,539
def insert n , * args new_frames = self . slice ( 0 , n ) args . each do | f | new_frames . push f end new_frames . concat self . slice ( n .. - 1 ) self . clear self . concat new_frames self end
Inserts the given Frame objects into the given index .
11,540
def mutate_keyframes_into_deltaframes! range = nil range = 0 .. self . size if range . nil? self . each_with_index do | frame , i | if range . include? i frame . flag = 0 if frame . is_keyframe? end end self end
Mutates keyframes into deltaframes at given range or all .
11,541
def glitch target = :all , & block if block_given? @frames . each do | frame | if valid_target? target , frame frame . data = yield frame . data end end self else self . enum_for :glitch , target end end
Glitches each frame data . It is a convenient method to iterate each frame .
11,542
def glitch_with_index target = :all , & block if block_given? self . glitch ( target ) . with_index do | x , i | yield x , i end self else self . glitch target end end
Do glitch with index .
11,543
def has_keyframe? result = false self . frames . each do | f | if f . is_keyframe? result = true break end end result end
Check if it has keyframes .
11,544
def frames = other raise TypeError unless other . kind_of? ( Frames ) @frames . clear @frames . concat other end
Swaps the frames with other Frames data .
11,545
def binary? ( relative_path ) bytes = :: File . new ( relative_path ) . size bytes = 2 ** 12 if bytes > 2 ** 12 buffer = :: File . read ( relative_path , bytes , 0 ) || '' buffer = buffer . force_encoding ( Encoding . default_external ) begin return buffer !~ / \A \s \z /m rescue ArgumentError => error return true if e...
Check if file is binary
11,546
def checksum_file ( source , * args , ** options ) mode = args . size . zero? ? 'sha256' : args . pop digester = DigestFile . new ( source , mode , options ) digester . call unless options [ :noop ] end
Create checksum for a file io or string objects
11,547
def chmod ( relative_path , permissions , ** options ) mode = :: File . lstat ( relative_path ) . mode if permissions . to_s =~ / \d / mode = permissions else permissions . scan ( / / ) do | setting | who , action = setting [ 0 ] , setting [ 1 ] setting [ 2 .. setting . size ] . each_byte do | perm | mask = const_get (...
Change file permissions
11,548
def create_directory ( destination , * args , ** options ) parent = args . size . nonzero? ? args . pop : nil if destination . is_a? ( String ) || destination . is_a? ( Pathname ) destination = { destination . to_s => [ ] } end destination . each do | dir , files | path = parent . nil? ? dir : :: File . join ( parent ,...
Create directory structure
11,549
def create_file ( relative_path , * args , ** options , & block ) relative_path = relative_path . to_s content = block_given? ? block [ ] : args . join CreateFile . new ( self , relative_path , content , options ) . call end
Create new file if doesn t exist
11,550
def copy_file ( source_path , * args , ** options , & block ) source_path = source_path . to_s dest_path = ( args . first || source_path ) . to_s . sub ( / \. / , '' ) ctx = if ( vars = options [ :context ] ) vars . instance_eval ( 'binding' ) else instance_eval ( 'binding' ) end create_file ( dest_path , options ) do ...
Copy file from the relative source to the relative destination running it through ERB .
11,551
def copy_metadata ( src_path , dest_path , ** options ) stats = :: File . lstat ( src_path ) :: File . utime ( stats . atime , stats . mtime , dest_path ) chmod ( dest_path , stats . mode , options ) end
Copy file metadata
11,552
def copy_directory ( source_path , * args , ** options , & block ) source_path = source_path . to_s check_path ( source_path ) source = escape_glob_path ( source_path ) dest_path = ( args . first || source ) . to_s opts = { recursive : true } . merge ( options ) pattern = opts [ :recursive ] ? :: File . join ( source ,...
Copy directory recursively from source to destination path
11,553
def diff ( path_a , path_b , ** options ) threshold = options [ :threshold ] || 10_000_000 output = [ ] open_tempfile_if_missing ( path_a ) do | file_a | if :: File . size ( file_a ) > threshold raise ArgumentError , "(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)" end if binary? ( fil...
Diff files line by line
11,554
def download_file ( uri , * args , ** options , & block ) uri = uri . to_s dest_path = ( args . first || :: File . basename ( uri ) ) . to_s unless uri =~ %r{ \: } copy_file ( uri , dest_path , options ) return end content = DownloadFile . new ( uri , dest_path , options ) . call if block_given? content = ( block . ari...
Download the content from a given address and save at the given relative destination . If block is provided in place of destination the content of of the uri is yielded .
11,555
def prepend_to_file ( relative_path , * args , ** options , & block ) log_status ( :prepend , relative_path , options . fetch ( :verbose , true ) , options . fetch ( :color , :green ) ) options . merge! ( before : / \A / , verbose : false ) inject_into_file ( relative_path , * ( args << options ) , & block ) end
Prepend to a file
11,556
def append_to_file ( relative_path , * args , ** options , & block ) log_status ( :append , relative_path , options . fetch ( :verbose , true ) , options . fetch ( :color , :green ) ) options . merge! ( after : / \z / , verbose : false ) inject_into_file ( relative_path , * ( args << options ) , & block ) end
Append to a file
11,557
def safe_append_to_file ( relative_path , * args , ** options , & block ) append_to_file ( relative_path , * args , ** ( options . merge ( force : false ) ) , & block ) end
Safely append to file checking if content is not already present
11,558
def remove_file ( relative_path , * args , ** options ) relative_path = relative_path . to_s log_status ( :remove , relative_path , options . fetch ( :verbose , true ) , options . fetch ( :color , :red ) ) return if options [ :noop ] || ! :: File . exist? ( relative_path ) :: FileUtils . rm_r ( relative_path , force : ...
Remove a file or a directory at specified relative path .
11,559
def tail_file ( relative_path , num_lines = 10 , ** options , & block ) file = :: File . open ( relative_path ) chunk_size = options . fetch ( :chunk_size , 512 ) line_sep = $/ lines = [ ] newline_count = 0 ReadBackwardFile . new ( file , chunk_size ) . each_chunk do | chunk | while ( nl_index = chunk . rindex ( line_s...
Provide the last number of lines from a file
11,560
def log_status ( cmd , message , verbose , color = false ) return unless verbose cmd = cmd . to_s . rjust ( 12 ) if color i = cmd . index ( / / ) cmd = cmd [ 0 ... i ] + decorate ( cmd [ i .. - 1 ] , color ) end message = "#{cmd} #{message}" message += "\n" unless message . end_with? ( "\n" ) @output . print ( message...
Log file operation
11,561
def open_tempfile_if_missing ( object , & block ) if :: FileTest . file? ( object ) :: File . open ( object , & block ) else tempfile = Tempfile . new ( 'tty-file-diff' ) tempfile << object tempfile . rewind block [ tempfile ] unless tempfile . nil? tempfile . close tempfile . unlink end end end
If content is not a path to a file create a tempfile and open it instead .
11,562
def load_relationship ( name ) populate_relationship ( :parent , interface . parent ) populate_relationship ( :machine , interface . machine ) populate_relationship ( :children , interface . children ) end
Loads the lazy relationships .
11,563
def restore ( & block ) machine . with_open_session do | session | session . console . restore_snapshot ( interface ) . wait ( & block ) end end
Restore a snapshot . This will restore this snapshot s virtual machine to the state that this snapshot represents . This method will block while the restore occurs .
11,564
def destroy ( & block ) machine . with_open_session do | session | session . console . delete_snapshot ( uuid ) . wait ( & block ) end end
Destroy a snapshot . This will physically remove the snapshot . Once this method is called there is no undo . If this snapshot is a parent of other snapshots the differencing image of this snapshot will be merged with the child snapshots so no data is lost . This process can sometimes take some time . This method will ...
11,565
def validate super validates_presence_of :name , :os_type_id , :memory_size , :vram_size , :cpu_count validates_numericality_of :memory_balloon_size , :monitor_count validates_inclusion_of :accelerate_3d_enabled , :accelerate_2d_video_enabled , :teleporter_enabled , :in => [ true , false ] if ! errors_on ( :name ) vms_...
Validates the virtual machine
11,566
def root_snapshot return nil if current_snapshot . nil? current = current_snapshot current = current . parent while current . parent != nil current end
Returns the root snapshot of this virtual machine . This root snapshot can be used to traverse the tree of snapshots .
11,567
def find_snapshot ( name ) find_helper = lambda do | name , root | return nil if root . nil? return root if root . name == name || root . uuid == name root . children . each do | child | result = find_helper . call ( name , child ) return result unless result . nil? end nil end find_helper . call ( name , root_snapshot...
Find a snapshot by name or UUID . This allows you to find a snapshot by a given name rather than having to resort to traversing the entire tree structure manually .
11,568
def with_open_session ( mode = :write ) session = Lib . lib . session close_session = false if session . state != :open interface . lock_machine ( session , mode ) close_session = true end yield session if block_given? if close_session session . machine . save_settings if mode == :write && session . machine . state != ...
Opens a direct session with the machine this VM represents and yields the session object to a block . Many of the VirtualBox s settings can only be modified with an open session on a machine . An open session is similar to a write - lock . Once the session is completed it must be closed which this method does as well .
11,569
def export ( filename , options = { } , & block ) app = Appliance . new app . path = filename app . add_machine ( self , options ) app . export ( & block ) end
Exports a virtual machine . The virtual machine will be exported to the specified OVF file name . This directory will also have the mf file which contains the file checksums and also the virtual drives of the machine .
11,570
def take_snapshot ( name , description = "" , & block ) with_open_session do | session | session . console . take_snapshot ( name , description ) . wait ( & block ) end end
Take a snapshot of the current state of the machine . This method can be called while the VM is running and also while it is powered off . This method will block while the snapshot is being taken .
11,571
def get_boot_order ( interface , key ) max_boot = Global . global . system_properties . max_boot_position ( 1 .. max_boot ) . inject ( [ ] ) do | order , position | order << interface . get_boot_order ( position ) order end end
Loads the boot order for this virtual machine . This method should never be called directly . Instead use the boot_order attribute to read and modify the boot order .
11,572
def set_boot_order ( interface , key , value ) max_boot = Global . global . system_properties . max_boot_position value = value . dup value . concat ( Array . new ( max_boot - value . size ) ) if value . size < max_boot ( 1 .. max_boot ) . each do | position | interface . set_boot_order ( position , value [ position - ...
Sets the boot order for this virtual machine . This method should never be called directly . Instead modify the boot_order array .
11,573
def initialize_from_path ( path ) interface . read ( path ) . wait_for_completion ( - 1 ) interface . interpret load_interface_attributes ( interface ) populate_relationship ( :virtual_systems , interface . virtual_system_descriptions ) existing_record! end
Initializes this Appliance instance from a path to an OVF file . This sets up the relationships and so on .
11,574
def add_machine ( vm , options = { } ) sys_desc = vm . interface . export ( interface , path ) options . each do | key , value | sys_desc . add_description ( key , value , value ) end end
Adds a VM to the appliance
11,575
def save changes . each do | key , value | interface . set_extra_data ( key . to_s , value [ 1 ] . to_s ) clear_dirty! ( key ) if value [ 1 ] . nil? hash_delete ( key . to_s ) end end end
Saves extra data . This method does the same thing for both new and existing extra data since virtualbox will overwrite old data or create it if it doesn t exist .
11,576
def initialize_attributes ( parent , inat ) write_attribute ( :parent , parent ) write_attribute ( :interface , inat ) load_interface_attributes ( inat ) populate_relationships ( inat ) clear_dirty! existing_record! end
Initializes the attributes of an existing NAT engine .
11,577
def dhcp_server ( create_if_not_found = true ) return nil if interface_type != :host_only dhcp_name = "HostInterfaceNetworking-#{name}" result = parent . parent . dhcp_servers . find do | dhcp | dhcp . network_name == dhcp_name end result = parent . parent . dhcp_servers . create ( dhcp_name ) if result . nil? && creat...
Gets the DHCP server associated with the network interface . Only host only network interfaces have dhcp servers . If a DHCP server doesn t exist for this network interface one will be created .
11,578
def attached_vms parent . parent . vms . find_all do | vm | next if ! vm . accessible? result = vm . network_adapters . find do | adapter | adapter . enabled? && adapter . host_only_interface == name end ! result . nil? end end
Gets the VMs which have an adapter which is attached to this network interface .
11,579
def enable_static ( ip , netmask = nil ) netmask ||= network_mask interface . enable_static_ip_config ( ip , netmask ) reload end
Sets up the static IPV4 configuration for the host only network interface . This allows the caller to set the IPV4 address of the interface as well as the netmask .
11,580
def destroy parent . lib . virtualbox . remove_dhcp_server ( interface ) parent_collection . delete ( self , true ) true end
Removes the DHCP server .
11,581
def host_network return nil unless network_name =~ / / parent . host . network_interfaces . detect do | i | i . interface_type == :host_only && i . name == $1 . to_s end end
Returns the host network associated with this DHCP server if it exists .
11,582
def save return true if ! new_record? && ! changed? raise Exceptions :: ValidationFailedException . new ( errors ) if ! valid? if ! new_record? destroy ( false ) end create end
Saves or creates a shared folder .
11,583
def added_to_relationship ( proxy ) was_clean = parent . nil? && ! changed? write_attribute ( :parent , proxy . parent ) write_attribute ( :parent_collection , proxy ) clear_dirty! if ! new_record? && was_clean end
Relationship callback when added to a collection . This is automatically called by any relationship collection when this object is added .
11,584
def destroy ( update_collection = true ) parent . with_open_session do | session | machine = session . machine machine . remove_shared_folder ( name ) end parent_collection . delete ( self , true ) if parent_collection && update_collection new_record! end
Destroys the shared folder . This doesn t actually delete the folder from the host system . Instead it simply removes the mapping to the virtual machine meaning it will no longer be possible to mount it from within the virtual machine .
11,585
def errors self . class . relationships . inject ( super ) do | acc , data | name , options = data if options && options [ :klass ] . respond_to? ( :errors_for_relationship ) errors = options [ :klass ] . errors_for_relationship ( self , relationship_data [ name ] ) acc . merge! ( name => errors ) if errors && ! errors...
Returns the errors for a model .
11,586
def validate ( * args ) clear_errors failed = false self . class . relationships . each do | name , options | next unless options && options [ :klass ] . respond_to? ( :validate_relationship ) failed = true if ! options [ :klass ] . validate_relationship ( self , relationship_data [ name ] , * args ) end return ! faile...
Validates the model and relationships .
11,587
def save ( * args ) changes . each do | key , values | save_attribute ( key , values [ 1 ] , * args ) end self . class . relationships . each do | name , options | save_relationship ( name , * args ) end @new_record = false true end
Saves the model attributes and relationships .
11,588
def device return read_attribute ( :device ) if ! new_record? || device_changed? || parent . nil? device_map = { :Am79C970A => "pcnet" , :Am79C973 => "pcnet" , :I82540EM => "e1000" , :I82543GC => "e1000" , :I82545EM => "e1000" } return device_map [ parent . network_adapters [ 0 ] . adapter_type ] end
Retrieves the device for the forwarded port . This tries to do the right thing depending on the first NIC of the VM parent by either setting the forwarded port type to pcnet or e1000 . If the device was already set manually this method will simply return that value instead .
11,589
def snapshot_map ( snapshots , & block ) applier = lambda do | snapshot | return if ! snapshot || snapshot . empty? snapshot [ :children ] . each do | child | applier . call ( child ) end block . call ( snapshot ) end applier . call ( snapshots ) end
Applies a function to every snapshot .
11,590
def validate super medium_formats = Global . global . system_properties . medium_formats . collect { | mf | mf . id } validates_inclusion_of :format , :in => medium_formats , :message => "must be one of the following: #{medium_formats.join(', ')}." validates_presence_of :location max_vdi_size = Global . global . system...
Validates a hard drive for the minimum attributes required to create or save .
11,591
def create return false unless new_record? raise Exceptions :: ValidationFailedException . new ( errors ) if ! valid? new_medium = create_hard_disk_medium ( location , format ) new_medium . create_base_storage ( logical_size , :standard ) . wait_for_completion ( - 1 ) write_attribute ( :interface , new_medium ) initial...
Clone hard drive possibly also converting formats . All formats supported by your local VirtualBox installation are supported here . If no format is specified the systems default will be used .
11,592
def save return true if ! new_record? && ! changed? raise Exceptions :: ValidationFailedException . new ( errors ) if ! valid? if new_record? create else msg = "Hard Drives cannot be updated. You need to create one from scratch." raise Exceptions :: MediumNotUpdatableException . new ( msg ) end end
Saves the hard drive object . If the hard drive is new this will create a new hard drive . Otherwise it will save any other details about the existing hard drive .
11,593
def initialize_attributes ( parent , inetwork ) write_attribute ( :parent , parent ) write_attribute ( :interface , inetwork ) load_interface_attributes ( inetwork ) clear_dirty! existing_record! end
Initializes the attributes of an existing shared folder .
11,594
def host_interface_object VirtualBox :: Global . global . host . network_interfaces . find do | ni | ni . name == host_only_interface end end
Gets the host interface object associated with the class if it exists .
11,595
def bridged_interface_object VirtualBox :: Global . global . host . network_interfaces . find do | ni | ni . name == bridged_interface end end
Gets the bridged interface object associated with the class if it exists .
11,596
def modify_adapter parent_machine . with_open_session do | session | machine = session . machine yield machine . get_network_adapter ( slot ) end end
Opens a session yields the adapter and then saves the machine at the end
11,597
def html ( html_string = '' ) html = %Q{<div id="opal-jquery-test-div">#{html_string}</div>} before do @_spec_html = Element . parse ( html ) @_spec_html . append_to_body end after { @_spec_html . remove } end
Add some html code to the body tag ready for testing . This will be added before each test then removed after each test . It is convenient for adding html setup quickly . The code is wrapped inside a div which is directly inside the body element .
11,598
def versioned_script? return chunks . size == 1 && chunks [ 0 ] . pushdata? && chunks [ 0 ] . canonical? && chunks [ 0 ] . pushdata . bytesize > 2 end
Returns true if this is an output script wrapped in a versioned pushdata for segwit softfork .
11,599
def open_assets_marker? return false if ! op_return_data_only_script? data = op_return_data return false if ! data || data . bytesize < 6 if data [ 0 , AssetMarker :: PREFIX_V1 . bytesize ] == AssetMarker :: PREFIX_V1 return true end false end
Returns true if this script may be a valid OpenAssets marker . Only checks the prefix and minimal length does not validate the content . Use this method to quickly filter out non - asset transactions .