idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
21,900 | def prefix? ( other ) other = other . to_key_path return false if other . length > length key_enum = each other . all? { | other_key | key_enum . next == other_key } end | Is + other + a prefix? |
21,901 | def max_job_ids connection_pairs = connection_pool . connections . map do | connection | [ connection , connection . max_job_id ] end return Hash [ connection_pairs ] end | Creates a new Climber instance optionally yielding the instance for configuration if a block is given |
21,902 | def task ( name , options = { } ) options [ :is ] = options [ :is ] . is_a? ( Array ) ? options [ :is ] : [ options [ :is ] ] . compact @tasks [ name ] = Task . new ( name , options ) end | Define a new task . |
21,903 | def add_permission ( target , * args ) raise '#can and #can_not have to be used inside a role block' unless @role options = args . last . is_a? ( Hash ) ? args . pop : { } tasks = [ ] models = [ ] models << args . pop if args . last == :any args . each { | arg | arg . is_a? ( Symbol ) ? tasks << arg : models << arg } tasks . each do | task | models . each do | model | if permission = target [ task ] [ model ] [ @role ] permission . load_options ( options ) else target [ task ] [ model ] [ @role ] = Permission . new ( @role , task , model , options ) end end end end | Creates an internal Permission |
21,904 | def process_tasks @tasks . each_value do | task | task . options [ :ancestors ] = [ ] set_ancestor_tasks ( task ) set_alternative_tasks ( task ) if @permissions . key? task . name end end | Flattens the tasks . It sets the ancestors and the alternative tasks |
21,905 | def set_ancestor_tasks ( task , ancestor = nil ) task . options [ :ancestors ] += ( ancestor || task ) . options [ :is ] ( ancestor || task ) . options [ :is ] . each do | parent_task | set_ancestor_tasks ( task , @tasks [ parent_task ] ) end end | Set the ancestors on task . |
21,906 | def set_alternative_tasks ( task , ancestor = nil ) ( ancestor || task ) . options [ :is ] . each do | task_name | if @permissions . key? task_name ( @tasks [ task_name ] . options [ :alternatives ] ||= [ ] ) << task . name else set_alternative_tasks ( task , @tasks [ task_name ] ) end end end | Set the alternatives of the task . Alternatives are the nearest ancestors which are used in permission definitions . |
21,907 | def set_descendant_roles ( descendant_role , ancestor_role = nil ) role = ancestor_role || descendant_role return unless role [ :is ] role [ :is ] . each do | role_name | ( @roles [ role_name ] [ :descendants ] ||= [ ] ) << descendant_role [ :name ] set_descendant_roles ( descendant_role , @roles [ role_name ] ) end end | Set the descendant_role as a descendant of the ancestor |
21,908 | def big_classes ( max_size = 1 . megabytes ) return @big_classes if @big_classes @big_classes = { } ObjectInformation . where ( :group_instance_id => self . id , :memsize . gt => max_size ) . all . each do | object | @big_classes [ object . class_name ] ||= { total_mem : 0 , average : 0 , count : 0 } @big_classes [ object . class_name ] [ :total_mem ] += object . memsize @big_classes [ object . class_name ] [ :count ] += 1 end @big_classes . each_pair do | klass , hash | @big_classes [ klass ] [ :average ] = @big_classes [ klass ] [ :total_mem ] / @big_classes [ klass ] [ :count ] end @big_classes end | Return an array of hashed that contains some information about the classes that consume more than max_size bytess |
21,909 | def categories add_breadcrumb I18n . t ( "generic.categories" ) , :admin_article_categories_path , :title => I18n . t ( "controllers.admin.terms.categories.breadcrumb_title" ) set_title ( I18n . t ( "generic.categories" ) ) @type = 'category' @records = Term . term_cats ( 'category' , nil , true ) render 'view' end | displays all the current categories and creates a new category object for creating a new one |
21,910 | def create @category = Term . new ( term_params ) redirect_url = Term . get_redirect_url ( params ) respond_to do | format | if @category . save @term_anatomy = @category . create_term_anatomy ( :taxonomy => params [ :type_taxonomy ] ) format . html { redirect_to URI . parse ( redirect_url ) . path , only_path : true , notice : I18n . t ( "controllers.admin.terms.create.flash.success" , term : Term . get_type_of_term ( params ) ) } else flash [ :error ] = I18n . t ( "controllers.admin.terms.create.flash.error" ) format . html { redirect_to URI . parse ( redirect_url ) . path , only_path : true } end end end | create tag or category - this is set within the form |
21,911 | def update @category = Term . find ( params [ :id ] ) @category . deal_with_cover ( params [ :has_cover_image ] ) respond_to do | format | if @category . update_attributes ( term_params ) format . html { redirect_to edit_admin_term_path ( @category ) , notice : I18n . t ( "controllers.admin.terms.update.flash.success" , term : Term . get_type_of_term ( params ) ) } else format . html { render action : "edit" } end end end | update the term record with the given parameters |
21,912 | def destroy @term = Term . find ( params [ :id ] ) redirect_url = Term . get_redirect_url ( { type_taxonomy : @term . term_anatomy . taxonomy } ) @term . destroy respond_to do | format | format . html { redirect_to URI . parse ( redirect_url ) . path , notice : I18n . t ( "controllers.admin.terms.destroy.flash.success" ) } end end | delete the term |
21,913 | def edit_title if @category . term_anatomy . taxonomy == 'category' add_breadcrumb I18n . t ( "generic.categories" ) , :admin_article_categories_path , :title => I18n . t ( "controllers.admin.terms.edit_title.category.breadcrumb_title" ) add_breadcrumb I18n . t ( "controllers.admin.terms.edit_title.category.title" ) title = I18n . t ( "controllers.admin.terms.edit_title.category.title" ) else add_breadcrumb I18n . t ( "generic.tags" ) , :admin_article_tags_path , :title => I18n . t ( "controllers.admin.terms.edit_title.tag.breadcrumb_title" ) add_breadcrumb I18n . t ( "controllers.admin.terms.edit_title.tag.title" ) title = I18n . t ( "controllers.admin.terms.edit_title.tag.title" ) end return title end | set the title and breadcrumbs for the edit screen |
21,914 | def upload ( aFile ) logger . debug "Uploading #{aFile} to S3 bucket #{config[:bucket]} ..." logger . info "Uploading #{File.basename(aFile)} to S3 bucket #{config[:bucket]} ..." s3client . upload_backup ( aFile , config [ :bucket ] , File . basename ( aFile ) ) end | uploads the given file to the current bucket as its basename |
21,915 | def decode_file_name ( aFilename ) prefix , date , ext = aFilename . scan ( / \- \. / ) . flatten return Time . from_date_numeric ( date ) end | return date based on filename |
21,916 | def call ( definition , klass ) variable = definition . instance_variable klass . instance_eval do define_method ( definition . reader ) { instance_variable_get ( variable ) } end end | Creates read method |
21,917 | def fixed ( value , places = 2 ) value = value . to_s . to_f unless value . is_a? ( Float ) sprintf ( "%0.#{places}f" , value . round ( places ) ) end | Formats a number to the specified number of decimal places . |
21,918 | def split_name ( name ) name ||= '' if name . include? ( ',' ) last , first = name . split ( ',' , 2 ) first , middle = first . to_s . strip . split ( ' ' , 2 ) else first , middle , last = name . split ( ' ' , 3 ) if middle && ! last middle , last = last , middle end end [ first . to_s . strip , middle . to_s . strip , last . to_s . strip ] end | Splits a name into First Middle and Last parts . |
21,919 | def parse if pre_parse messages = @file_reader . other_lines . map do | line | basic_message_match = @line_regex . match ( line ) meta_message_match = @line_regex_status . match ( line ) if basic_message_match create_message ( basic_message_match ) elsif meta_message_match create_status_or_event_message ( meta_message_match ) end end Chat . new ( messages , @metadata ) end end | This method returns a Chat instance or false if it could not parse the file . |
21,920 | def pre_parse @file_reader . read metadata = Metadata . new ( MetadataParser . new ( @file_reader . first_line ) . parse ) if metadata . valid? @metadata = metadata @alias_registry = AliasRegistry . new ( @metadata . their_screen_name ) @my_aliases . each do | my_alias | @alias_registry [ my_alias ] = @metadata . my_screen_name end end end | Extract required data from the file . Run by parse . |
21,921 | def time ( name , opts = { } ) opts [ :ez ] ||= true start = Time . now yield if block_given? if opts [ :ez ] == true ez_value ( name , ( Time . now - start ) ) else value ( name , ( Time . now - start ) ) end end | Time a block of code and send the duration as a value |
21,922 | def add_entity section , key , value , enclosure_value = null if ( tags = self . class . const_get ( "#{section.upcase}_TAGS" ) ) key = key . bowl . to_sym tags [ key ] = value . to_sym self . class . const_get ( "ENCLOSURES_TAGS" ) [ key ] = enclosure_value . to_sym if enclosure_value self . class . const_get ( "ENTITIES" ) [ section . to_sym ] [ key ] = value . to_sym self . class . class_eval %Q{ alias_method :#{key}, :∀_#{section} } @shadows = nil else logger . warn "Trying to add key “#{key}” in an invalid section “#{section}”. Ignoring…" end end | Adds new + entity + in the section specified . E . g . call to |
21,923 | def restrict_flags ( declarer , * flags ) copy = restrict ( declarer ) copy . qualify ( * flags ) copy end | Creates a new declarer attribute which qualifies this attribute for the given declarer . |
21,924 | def inverse = ( attribute ) return if inverse == attribute return clear_inverse if attribute . nil? begin @inv_prop = type . property ( attribute ) rescue NameError => e raise MetadataError . new ( "#{@declarer.qp}.#{self} inverse attribute #{type.qp}.#{attribute} not found" ) end inv_inv_prop = @inv_prop . inverse_property if inv_inv_prop and not ( inv_inv_prop == self or inv_inv_prop . restriction? ( self ) ) raise MetadataError . new ( "Cannot set #{type.qp}.#{attribute} inverse attribute to #{@declarer.qp}.#{self}@#{object_id} since it conflicts with existing inverse #{inv_inv_prop.declarer.qp}.#{inv_inv_prop}@#{inv_inv_prop.object_id}" ) end @inv_prop . inverse = @attribute @inv_prop . qualify ( :disjoint ) if disjoint? logger . debug { "Assigned #{@declarer.qp}.#{self} attribute inverse to #{type.qp}.#{attribute}." } end | Sets the inverse of the subject attribute to the given attribute . The inverse relation is symmetric i . e . the inverse of the referenced Property is set to this Property s subject attribute . |
21,925 | def owner_flag_set if dependent? then raise MetadataError . new ( "#{declarer.qp}.#{self} cannot be set as a #{type.qp} owner since it is already defined as a #{type.qp} dependent" ) end inv_prop = inverse_property if inv_prop then inv_prop . qualify ( :dependent ) unless inv_prop . dependent? else inv_attr = type . dependent_attribute ( @declarer ) if inv_attr . nil? then raise MetadataError . new ( "The #{@declarer.qp} owner attribute #{self} of type #{type.qp} does not have an inverse" ) end logger . debug { "#{declarer.qp}.#{self} inverse is the #{type.qp} dependent attribute #{inv_attr}." } self . inverse = inv_attr end end | This method is called when the owner flag is set . The inverse is inferred as the referenced owner type s dependent attribute which references this attribute s type . |
21,926 | def get_token ( url ) req = Net :: HTTP :: Post . new ( '/' , initheader = { 'Content-Type' => 'application/json' } ) req . body = { url : url , format : 'json' } . to_json res = @http . request ( req ) data = JSON :: parse ( res . body ) data [ 'trunct' ] [ 'token' ] end | Shortens a URL returns the shortened token |
21,927 | def on_worker_exit ( worker ) mutex . synchronize do @pool . delete ( worker ) if @pool . empty? && ! running? stop_event . set stopped_event . set end end end | Run when a thread worker exits . |
21,928 | def execute ( * args , & task ) if ensure_capacity? @scheduled_task_count += 1 @queue << [ args , task ] else if @max_queue != 0 && @queue . length >= @max_queue handle_fallback ( * args , & task ) end end prune_pool end | A T T E N Z I O N E A R E A P R O T E T T A |
21,929 | def ensure_capacity? additional = 0 capacity = true if @pool . size < @min_length additional = @min_length - @pool . size elsif @queue . empty? && @queue . num_waiting >= 1 additional = 0 elsif @pool . size == 0 && @min_length == 0 additional = 1 elsif @pool . size < @max_length || @max_length == 0 additional = 1 elsif @max_queue == 0 || @queue . size < @max_queue additional = 0 else capacity = false end additional . times do @pool << create_worker_thread end if additional > 0 @largest_length = [ @largest_length , @pool . length ] . max end capacity end | Check the thread pool configuration and determine if the pool has enought capacity to handle the request . Will grow the size of the pool if necessary . |
21,930 | def prune_pool if Garcon . monotonic_time - @gc_interval >= @last_gc_time @pool . delete_if { | worker | worker . dead? } @pool . select { | worker | @idletime != 0 && Garcon . monotonic_time - @idletime > worker . last_activity } . each { @queue << :stop } @last_gc_time = Garcon . monotonic_time end end | Scan all threads in the pool and reclaim any that are dead or have been idle too long . Will check the last time the pool was pruned and only run if the configured garbage collection interval has passed . |
21,931 | def create_worker_thread wrkr = ThreadPoolWorker . new ( @queue , self ) Thread . new ( wrkr , self ) do | worker , parent | Thread . current . abort_on_exception = false worker . run parent . on_worker_exit ( worker ) end return wrkr end | Create a single worker thread to be added to the pool . |
21,932 | def render ignore = [ ComfyPress :: Tag :: Partial , ComfyPress :: Tag :: Helper ] . member? ( self . class ) ComfyPress :: Tag . sanitize_irb ( content , ignore ) end | Content that is used during page rendering . Outputting existing content as a default . |
21,933 | def merge_attributes ( other , attributes = nil , matches = nil , & filter ) return self if other . nil? or other . equal? ( self ) attributes = [ attributes ] if Symbol === attributes attributes ||= self . class . mergeable_attributes vh = Hasher === other ? other : other . value_hash ( attributes ) vh . each { | pa , value | merge_attribute ( pa , value , matches , & filter ) } self end | Merges the values of the other attributes into this object and returns self . The other argument can be either a Hash or an object whose class responds to the + mergeable_attributes + method . The optional attributes argument can be either a single attribute symbol or a collection of attribute symbols . |
21,934 | def perform_webhook http_request . body = { 'text' => params [ :text ] } . to_json . to_s http_request . query = { 'token' => params [ :token ] } HTTPI . post ( http_request ) end | Webhooks are handled in a non - compatible way with the other APIs |
21,935 | def irc_upcase! ( irc_string , casemapping = :rfc1459 ) case casemapping when :ascii irc_string . tr! ( * @@ascii_map ) when :rfc1459 irc_string . tr! ( * @@rfc1459_map ) when :' ' irc_string . tr! ( * @@strict_rfc1459_map ) else raise ArgumentError , "Unsupported casemapping #{casemapping}" end return irc_string end | Turn a string into IRC upper case modifying it in place . |
21,936 | def irc_upcase ( irc_string , casemapping = :rfc1459 ) result = irc_string . dup irc_upcase! ( result , casemapping ) return result end | Turn a string into IRC upper case . |
21,937 | def irc_downcase! ( irc_string , casemapping = :rfc1459 ) case casemapping when :ascii irc_string . tr! ( * @@ascii_map . reverse ) when :rfc1459 irc_string . tr! ( * @@rfc1459_map . reverse ) when :' ' irc_string . tr! ( * @@strict_rfc1459_map . reverse ) else raise ArgumentError , "Unsupported casemapping #{casemapping}" end return irc_string end | Turn a string into IRC lower case modifying it in place . |
21,938 | def irc_downcase ( irc_string , casemapping = :rfc1459 ) result = irc_string . dup irc_downcase! ( result , casemapping ) return result end | Turn a string into IRC lower case . |
21,939 | def render_js_message ( type , hash = { } ) unless [ :ok , :redirect , :error ] . include? ( type ) raise "Invalid js_message response type: #{type}" end js_message = { :status => type , :html => nil , :message => nil , :to => nil } . merge ( hash ) render_options = { :json => js_message } render_options [ :status ] = 400 if type == :error render ( render_options ) end | Helper to render the js_message response . |
21,940 | def scaled_digit ( group ) unless group . size == @base_scale raise "Invalid digits group size for scaled_digit (is #{group.size}; should be #{@base_scale})" end v = 0 group . each do | digit | v *= @setter . base v += digit end v end | Return the scaled_base digit corresponding to a group of base_scale exponent_base digits |
21,941 | def grouped_digits ( digits ) unless ( digits . size % @base_scale ) == 0 raise "Invalid number of digits for group_digits (#{digits.size} is not a multiple of #{@base_scale})" end digits . each_slice ( @base_scale ) . map { | group | scaled_digit ( group ) } end | Convert base exponent_base digits to base scaled_base digits the number of digits must be a multiple of base_scale |
21,942 | def call target_method , receiver , * args , & block unless target_method . parameters . empty? raise NRSER :: ArgumentError . new "{NRSER::LazyAttr} can only decorate methods with 0 params" , receiver : receiver , target_method : target_method end unless args . empty? raise NRSER :: ArgumentError . new "wrong number of arguments for" , target_method , "(given" , args . length , "expected 0)" , receiver : receiver , target_method : target_method end unless block . nil? raise NRSER :: ArgumentError . new "wrong number of arguments (given #{ args.length }, expected 0)" , receiver : receiver , target_method : target_method end var_name = self . class . instance_var_name target_method unless receiver . instance_variable_defined? var_name receiver . instance_variable_set var_name , target_method . call end receiver . instance_variable_get var_name end | . instance_var_name Execute the decorator . |
21,943 | def column name , options = { } , & block @columns << TableMe :: Column . new ( name , options , & block ) @names << name end | Define a column |
21,944 | def op = ( op ) fail "OP must be 128 bits" unless op . each_byte . to_a . length == 16 @opc = xor ( enc ( op ) , op ) end | Create a single user s kernel instance remember to set OP or OPc before attempting to use the security functions . |
21,945 | def remove_unnecessary_cache_files! current_keys = cache_files . map do | file | get_cache_key_from_filename ( file ) end inmemory_keys = responses . keys unneeded_keys = current_keys - inmemory_keys unneeded_keys . each do | key | File . unlink ( filepath_for ( key ) ) end end | Removes any cache files that aren t needed anymore |
21,946 | def read_cache_fixtures! files = cache_files files . each do | file | cache_key = get_cache_key_from_filename ( file ) responses [ cache_key ] = Marshal . load ( File . read ( file ) ) end end | Reads in the cache fixture files to in - memory cache . |
21,947 | def dump_cache_fixtures! responses . each do | cache_key , response | path = filepath_for ( cache_key ) unless File . exist? ( path ) File . open ( path , "wb" ) do | fp | fp . write ( Marshal . dump ( response ) ) end end end end | Dumps out any cached items to disk . |
21,948 | def get_theme_options hash = [ ] Dir . glob ( "#{Rails.root}/app/views/themes/*/" ) do | themes | opt = themes . split ( '/' ) . last if File . exists? ( "#{themes}theme.yml" ) info = YAML . load ( File . read ( "#{themes}theme.yml" ) ) hash << info if ! info [ 'name' ] . blank? && ! info [ 'author' ] . blank? && ! info [ 'foldername' ] . blank? && ! info [ 'view_extension' ] . blank? end end hash end | returns a hash of the different themes as a hash with the details kept in the theme . yml file |
21,949 | def get_templates hash = [ ] current_theme = Setting . get ( 'theme_folder' ) Dir . glob ( "#{Rails.root}/app/views/themes/#{current_theme}/template-*.html.erb" ) do | my_text_file | opt = my_text_file . split ( '/' ) . last opt [ 'template-' ] = '' opt [ '.html.erb' ] = '' hash << opt . titleize end hash end | retuns a hash of the template files within the current theme |
21,950 | def theme_exists if ! Dir . exists? ( "app/views/themes/#{Setting.get('theme_folder')}/" ) html = "<div class='alert alert-danger'><strong>" + I18n . t ( "helpers.admin_roroa_helper.theme_exists.warning" ) + "!</strong> " + I18n . t ( "helpers.admin_roroa_helper.theme_exists.message" ) + "!</div>" render :inline => html . html_safe end end | checks if the current theme being used actually exists . If not it will return an error message to the user |
21,951 | def get_notifications html = '' if flash [ :error ] html += "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n . t ( "helpers.view_helper.generic.flash.error" ) + "!</strong> #{flash[:error]}</div>" end if flash [ :notice ] html += "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n . t ( "helpers.view_helper.generic.flash.success" ) + "!</strong> #{flash[:notice]}</div>" end render :inline => html . html_safe end | Returns generic notifications if the flash data exists |
21,952 | def append_application_menu html = '' Roroacms . append_menu . each do | f | html += ( render :partial => 'roroacms/admin/partials/append_sidebar_menu' , :locals => { :menu_block => f } ) end html . html_safe end | appends any extra menu items that are set in the applications configurations |
21,953 | def request ( method , url , body = nil ) unless [ '/' , '' ] . include? ( URI :: parse ( url ) . path ) setup_oauth_token end begin raw = connection ( current_options . merge ( { url : url } ) ) . send ( method ) do | req | if [ :post , :put ] . include? ( method . to_sym ) && ! body . blank? req . body = PMP :: CollectionDocument . to_persist_json ( body ) end end rescue Faraday :: Error :: ResourceNotFound => not_found_ex if ( method . to_sym == :get ) raw = OpenStruct . new ( body : nil , status : 404 ) else raise not_found_ex end end PMP :: Response . new ( raw , { method : method , url : url , body : body } ) end | url includes any params - full url |
21,954 | def like ( likeable ) if ! self . disliked? ( likeable ) and @@likeable_model_names . include? likeable . class . to_s . downcase likeable . likers << self self . save else false end end | user likes a likeable |
21,955 | def unlike ( likeable ) if @@likeable_model_names . include? likeable . class . to_s . downcase likeable . likers . delete self self . save else false end end | user unlike a likeable |
21,956 | def birth birth = births . find { | b | ! b . selected . nil? } birth ||= births [ 0 ] birth end | It should return the selected birth assertion unless it is not set in which case it will return the first |
21,957 | def death death = deaths . find { | b | ! b . selected . nil? } death ||= deaths [ 0 ] death end | It should return the selected death assertion unless it is not set in which case it will return the first |
21,958 | def select_mother_summary ( person_id ) add_parents! couple = parents [ 0 ] || ParentsReference . new couple . select_parent ( person_id , 'Female' ) parents [ 0 ] = couple end | Select the mother for the summary view . This should be called on a Person record that contains a person id and version . |
21,959 | def select_father_summary ( person_id ) add_parents! couple = parents [ 0 ] || ParentsReference . new couple . select_parent ( person_id , 'Male' ) parents [ 0 ] = couple end | Select the father for the summary view . This should be called on a Person record that contains a person id and version . |
21,960 | def select_spouse_summary ( person_id ) add_families! family = FamilyReference . new family . select_spouse ( person_id ) families << family end | Select the spouse for the summary view . This should be called on a Person record that contains a person id and version . |
21,961 | def add_sealing_to_parents ( options ) raise ArgumentError , ":mother option is required" if options [ :mother ] . nil? raise ArgumentError , ":father option is required" if options [ :father ] . nil? add_assertions! options [ :type ] = OrdinanceType :: Sealing_to_Parents assertions . add_ordinance ( options ) end | Add a sealing to parents ordinance |
21,962 | def select_relationship_ordinances ( options ) raise ArgumentError , ":id required" if options [ :id ] . nil? if self . relationships spouse_relationship = self . relationships . spouses . find { | s | s . id == options [ :id ] } if spouse_relationship && spouse_relationship . assertions && spouse_relationship . assertions . ordinances spouse_relationship . assertions . ordinances else [ ] end end end | only ordinance type is Sealing_to_Spouse |
21,963 | def read ( length = nil , filter = nil , & block ) buffer = "" pos = 0 if length . kind_of? Proc filter = length end worker = Proc :: new do if not length . nil? rlen = length - buffer . length if rlen > @rw_len rlen = @rw_len end else rlen = @rw_len end begin chunk = @native . read ( rlen ) if not filter . nil? chunk = filter . call ( chunk ) end buffer << chunk rescue Errno :: EBADF if @native . kind_of? :: File self . reopen! @native . seek ( pos ) redo else raise end end pos = @native . pos if @native . eof? or ( buffer . length == length ) if not block . nil? yield buffer end else EM :: next_tick { worker . call ( ) } end end worker . call ( ) end | Constructor . If IO object is given instead of filepath uses it as native one and + mode + argument is ignored . |
21,964 | def write ( data , filter = nil , & block ) pos = 0 if data . kind_of? IO io = data else io = StringIO :: new ( data ) end worker = Proc :: new do begin chunk = io . read ( @rw_len ) if not filter . nil? chunk = filter . call ( chunk ) end @native . write ( chunk ) rescue Errno :: EBADF if @native . kind_of? File self . reopen! @native . seek ( pos ) redo else raise end end pos = @native . pos if io . eof? if not block . nil? yield pos end else EM :: next_tick { worker . call ( ) } end end worker . call ( ) end | Writes data to file . Supports writing both strings or copying from another IO object . Returns length of written data to callback if filename given or current position of output string if IO used . |
21,965 | def verify differences = expected_calls . keys - actual_calls . keys if differences . any? raise MockExpectationError , "expected #{differences.first.inspect}" else true end end | Verify that all methods were called as expected . Raises + MockExpectationError + if not called as expected . |
21,966 | def time ( task = :default , type = :current ) return nil unless tasks . keys . include? ( task ) numbers = tasks [ task ] [ :history ] . map { | v | v [ :time ] } case type when :current return nil unless tasks [ task ] [ :current ] Time . now . to_f - tasks [ task ] [ :current ] when :min , :max , :first , :last numbers . send ( type ) when :avg numbers . size . zero? ? nil : numbers . inject { | sum , n | sum + n } . to_f / numbers . size when :sum numbers . inject { | sum , n | sum + n } when :all numbers when :count numbers . size end end | Returns an aggregated metric for a given type . |
21,967 | def clear ( task = :default ) return nil unless tasks . keys . include? ( task ) stop task tasks [ task ] [ :history ] . clear end | Removes all history for a given task |
21,968 | def start ( task = :default ) tasks [ task ] = { history : [ ] , current : nil } unless tasks . keys . include? ( task ) stop task if tasks [ task ] [ :current ] tasks [ task ] [ :current ] = Time . now . to_f 0 end | Start a new timer for the referenced task . If a timer is already running for that task it will be stopped first . |
21,969 | def stop ( task = :default ) return nil unless tasks . keys . include? ( task ) && active? ( task ) time_taken = Time . now . to_f - tasks [ task ] [ :current ] . to_f tasks [ task ] [ :history ] << { start : tasks [ task ] [ :current ] , stop : Time . now . to_f , time : time_taken } tasks [ task ] [ :current ] = nil if retention && tasks [ task ] [ :history ] . size > retention then tasks [ task ] [ :history ] . shift end time_taken end | Stop the referenced timer . |
21,970 | def create_file ( file , name , requires_edit = false ) FileUtils . cp ( file + '.example' , file ) if requires_edit puts "Update #{file} and run `bundle exec rake setup` to continue" . color ( :red ) system ( ENV [ 'EDITOR' ] , file ) unless ENV [ 'EDITOR' ] . blank? exit end end | Creates a file based on a . example version saved in the same folder Will optionally open the new file in the default editor after creation |
21,971 | def find_or_create_file ( file , name , requires_edit = false ) if File . exists? ( file ) file else create_file ( file , name , requires_edit ) end end | Looks for the specificed file and creates it if it does not exist |
21,972 | def inherit_strategy ( strategy ) AvoDeploy :: Deployment . instance . log . debug "Loading deployment strategy #{strategy.to_s}..." strategy_file_path = File . dirname ( __FILE__ ) + "/strategy/#{strategy.to_s}.rb" if File . exist? ( strategy_file_path ) require strategy_file_path else raise RuntimeError , "The requested strategy '#{strategy.to_s}' does not exist" end end | Loads a strategy . Because the strategy files are loaded in the specified order it s possible to override tasks . This is how inheritance of strategies is realized . |
21,973 | def task ( name , options = { } , & block ) AvoDeploy :: Deployment . instance . log . debug "registering task #{name}..." AvoDeploy :: Deployment . instance . task_manager . add_task ( name , options , & block ) end | Defines a task |
21,974 | def setup_stage ( name , options = { } , & block ) stages [ name ] = '' if options . has_key? ( :desc ) stages [ name ] = options [ :desc ] end if name . to_s == get ( :stage ) . to_s @loaded_stage = name instance_eval ( & block ) end end | Defines a stage |
21,975 | def dot ( a , b ) unless a . size == b . size raise "Vectors must be the same length" end ( a . to_a ) . zip ( b . to_a ) . inject ( 0 ) { | tot , pair | tot = tot + pair [ 0 ] * pair [ 1 ] } end | Dot product of two n - element arrays |
21,976 | def cross ( b , c ) unless b . size == 3 and c . size == 3 raise "Vectors must be of length 3" end Vector [ b [ 1 ] * c [ 2 ] - b [ 2 ] * c [ 1 ] , b [ 2 ] * c [ 0 ] - b [ 0 ] * c [ 2 ] , b [ 0 ] * c [ 1 ] - b [ 1 ] * c [ 0 ] ] end | Cross product of two arrays of length 3 |
21,977 | def xml_encode string puts string . each_char . size string . each_char . map do | p | case when CONVERTIBLES [ p ] CONVERTIBLES [ p ] when XML_ENTITIES [ p ] "&##{XML_ENTITIES[p]};" else p end end . reduce ( :+ ) end | Encode Russian UTF - 8 string to XML Entities format converting weird Unicode chars along the way |
21,978 | def debug ( msg = nil ) if @logger msg = build_log ( msg || yield , ActionCommand :: LOG_KIND_DEBUG ) @logger . info ( format_log ( msg ) ) end end | display an debugging message to the logger if there is one . |
21,979 | def info ( msg = nil ) if @logger msg = build_log ( msg || yield , ActionCommand :: LOG_KIND_INFO ) @logger . info ( format_log ( msg ) ) end end | display an informational message to the logger if there is one . |
21,980 | def error ( msg ) if @logger msg = build_log ( msg , ActionCommand :: LOG_KIND_ERROR ) @logger . error ( format_log ( msg ) ) end end | display an error message to the logger if there is one . |
21,981 | def push ( key , cmd ) return unless key old_cur = current if old_cur . key? ( key ) @values << old_cur [ key ] else @values << { } old_cur [ key ] = @values . last end @stack << { key : key , cmd : cmd } if @logger end | adds results under the subkey until pop is called |
21,982 | def log_input ( params ) return unless @logger output = params . reject { | k , _v | internal_key? ( k ) } log_info_hash ( output , ActionCommand :: LOG_KIND_COMMAND_INPUT ) end | Used internally to log the input parameters to a command |
21,983 | def log_output return unless @logger output = current . reject { | k , v | v . is_a? ( Hash ) || internal_key? ( k ) } log_info_hash ( output , ActionCommand :: LOG_KIND_COMMAND_OUTPUT ) end | Used internally to log the output parameters for a command . |
21,984 | def merge! ( * args ) val = args . pop keys = args . flatten StorageFile . merge! ( path , [ * @parents , * keys ] , val ) end | Merge Hash value with existing Hash value . |
21,985 | def parse_message ( msg ) msg = msg . to_s re = / / msg_split = re . match ( msg ) if msg_split . nil? re = / / msg_split = re . match ( msg ) raise "Error: Malformed Message" if not msg_split type = msg_split [ 1 ] data = { } else type = msg_split [ 1 ] data = JSON . parse ( msg_split [ 2 ] ) end { type : type , data : data } end | Parses a message |
21,986 | def send_message ( type , message = nil ) message = message . nil? ? message = '' : message . to_json body = type + ' ' + message body . strip! length = body . bytesize @client . write ( "#{length}\n#{body}" ) end | Sends a message of a specific type |
21,987 | def list_aggregated_resources ( uri_prefix ) $logger . debug { "ApiClient#list_aggregated_resources(#{uri_prefix.inspect})" } resources_api = TriglavClient :: ResourcesApi . new ( @api_client ) handle_error { resources_api . list_aggregated_resources ( uri_prefix ) } end | List resources required to be monitored |
21,988 | def render_properties! ( xml ) self . class . properties . each do | property , options | next unless instance_variable_get ( "@_set_#{property}" ) property_value = self . send ( property ) render_property! ( property , property_value , xml , options ) end end | By default loops through all registered properties and renders each that has been explicitly set . |
21,989 | def compose ( line ) raise ArgumentError , "You must specify a command" if ! line . command raw_line = '' raw_line << ":#{line.prefix} " if line . prefix raw_line << line . command if line . args line . args . each_with_index do | arg , idx | raw_line << ' ' if idx != line . args . count - 1 and arg . match ( @@space ) raise ArgumentError , "Only the last argument may contain spaces" end if idx == line . args . count - 1 raw_line << ':' if arg . match ( @@space ) end raw_line << arg end end return raw_line end | Compose an IRC protocol line . |
21,990 | def parse ( raw_line ) line = decompose ( raw_line ) if line . command =~ / / && line . args [ 1 ] =~ / \x01 / return handle_ctcp_message ( line ) end msg_class = case when line . command =~ / \d / begin constantize ( "IRCSupport::Message::Numeric#{line.command}" ) rescue constantize ( "IRCSupport::Message::Numeric" ) end when line . command == "MODE" if @isupport [ 'CHANTYPES' ] . include? ( line . args [ 0 ] [ 0 ] ) constantize ( "IRCSupport::Message::ChannelModeChange" ) else constantize ( "IRCSupport::Message::UserModeChange" ) end when line . command == "NOTICE" && ( ! line . prefix || line . prefix !~ / / ) constantize ( "IRCSupport::Message::ServerNotice" ) when line . command == "CAP" && %w{ LS LIST ACK } . include? ( line . args [ 0 ] ) constantize ( "IRCSupport::Message::CAP::#{line.args[0]}" ) else begin constantize ( "IRCSupport::Message::#{line.command.capitalize}" ) rescue constantize ( "IRCSupport::Message" ) end end message = msg_class . new ( line , @isupport , @capabilities ) case message . type when :' ' @isupport . merge! message . isupport when :cap_ack message . capabilities . each do | capability , options | if options . include? ( :disable ) @capabilities = @capabilities - [ capability ] elsif options . include? ( :enable ) @capabilities = @capabilities + [ capability ] end end end return message end | Parse an IRC protocol line into a complete message object . |
21,991 | def send_initialization_message entry_properties = @connection . objects . convert_object_to_properties ( @connection . local_entry ) message = Messages :: Initialization . build ( entry : entry_properties ) @connection . messenger . send ( message ) end | Build and send an initialization message . |
21,992 | def process_initialization_message ( message ) entry = @connection . objects . convert_properties_to_object ( message . entry ) @connection . remote_entry . set ( entry ) end | Processes a initialization message from the remote endpoint . |
21,993 | def run_once ( event ) unless StripeWebhooks :: PerformedCallback . exists? ( stripe_event_id : event . id , label : label ) run ( event ) StripeWebhooks :: PerformedCallback . create ( stripe_event_id : event . id , label : label ) end end | Run the callback only if we have not run it once before |
21,994 | def migrate ( & block ) unless block_given? then return migrate { | tgt , row | tgt } end if @extract then if String === @extract then logger . debug { "Opening migration extract #{@extract}..." } FileUtils :: mkdir_p ( File . dirname ( @extract ) ) if @extract_hdrs then logger . debug { "Migration extract headers: #{@extract_hdrs.join(', ')}." } CsvIO . open ( @extract , :mode => 'w' , :headers => @extract_hdrs ) do | io | @extract = io return migrate ( & block ) end else File . open ( @extract , 'w' ) do | io | @extract = io return migrate ( & block ) end end end io , @extract = @extract , nil return migrate do | tgt , row | res = yield ( tgt , row ) tgt . extract ( io ) res end end begin migrate_rows ( & block ) ensure @rejects . close if @rejects remove_migration_methods end end | Creates a new Migrator from the given options . |
21,995 | def remove_migration_methods @mgt_mths . each do | klass , hash | hash . each_value do | sym | while klass . method_defined? ( sym ) klass . instance_method ( sym ) . owner . module_eval { remove_method ( sym ) } end end end @creatable_classes . each do | klass | while ( k = klass . instance_method ( :migrate ) . owner ) < Migratable k . module_eval { remove_method ( :migrate ) } end end remove_extract_method ( @target ) if @extract end | Cleans up after the migration by removing the methods injected by migration shims . |
21,996 | def load_shims ( files ) logger . debug { "Loading the migration shims with load path #{$:.pp_s}..." } files . enumerate do | file | load file logger . info { "The migrator loaded the shim file #{file}." } end end | Loads the shim files . |
21,997 | def migrate_rows if @bad_file then @rejects = open_rejects ( @bad_file ) logger . info ( "Unmigrated records will be written to #{File.expand_path(@bad_file)}." ) end @rec_cnt = mgt_cnt = 0 logger . info { "Migrating #{@input}..." } puts "Migrating #{@input}..." if @verbose @reader . each do | row | rec_no = @rec_cnt + 1 if rec_no == @from and @rec_cnt > 0 then logger . info ( "Skipped the initial #{@rec_cnt} records." ) elsif rec_no == @to then logger . info ( "Ending the migration after processing record #{@rec_cnt}." ) return elsif rec_no < @from then @rec_cnt += 1 next end begin logger . debug { "Migrating record #{rec_no}..." } tgt = migrate_row ( row ) if tgt then logger . debug { "The migrator built #{tgt} with the following content:\n#{tgt.dump}" } yield ( tgt , row ) end rescue Exception => e logger . error ( "Migration error on record #{rec_no} - #{e.message}:\n#{e.backtrace.pp_s}" ) raise unless @rejects clear ( tgt ) rescue nil tgt = nil end if tgt then logger . info { "Migrated record #{rec_no}." } mgt_cnt += 1 if @verbose then print_progress ( mgt_cnt ) end clear ( tgt ) elsif @rejects then logger . warn ( "Migration not performed on record #{rec_no}." ) @rejects << row @rejects . flush logger . debug ( "Invalid record #{rec_no} was written to the rejects file #{@bad_file}." ) else raise MigrationError . new ( "Migration not performed on record #{rec_no}" ) end @rec_cnt += 1 end logger . info ( "Migrated #{mgt_cnt} of #{@rec_cnt} records." ) if @verbose then puts puts "Migrated #{mgt_cnt} of #{@rec_cnt} records." end end | Migrates all rows in the input . |
21,998 | def open_rejects ( file ) FileUtils . mkdir_p ( File . dirname ( file ) ) FasterCSV . open ( file , 'w' , :headers => true , :header_converters => :symbol , :write_headers => true ) end | Makes the rejects CSV output file . |
21,999 | def migrate_row ( row ) created = Set . new migrated = @creatable_classes . map { | klass | create_instance ( klass , row , created ) } migrated . each do | obj | if @unique and Unique === obj then logger . debug { "The migrator is making #{obj} unique..." } obj . uniquify end obj . migrate ( row , migrated ) end @migrated = migrate_valid_references ( row , migrated ) tgts = @migrated . select { | obj | @target_class === obj } if tgts . size > 1 then raise MigrationError . new ( "Ambiguous #{@target_class} targets #{tgts.to_series}" ) end target = tgts . first || return logger . debug { "Migrated target #{target}." } target end | Imports the given CSV row into a target object . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.