idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
24,600
def serialize_other_informations serialized = { } serialized [ :publication_datetime ] = post_parent . publication_datetime serialized [ :translations ] = { } post_parent . posts . published . each do | post | next if post . id == id serialized [ :translations ] [ post . meta_language ] = post . serialize_base end seri...
This function serializes other informations for the post .
24,601
def set_attributes_for _exception , _controller , _action , _env self . exception = _exception . class self . message = _exception . message self . controller = _controller self . action = _action self . app_environment = _env end
Sets Exception instance attributes .
24,602
def moved_matrix_with_parent ( i , j , new_i , new_j , open_list , closed_list ) return nil if ! index_exist? ( new_i , new_j ) swapped_matrix = swap ( i , j , new_i , new_j ) new_depth = @depth + 1 swapped_matrix = GameMatrix . new ( swapped_matrix , self , new_depth ) return nil if closed_list . include? ( swapped_ma...
Get swapped matrix check him in closed and open list
24,603
def neighbors ( open_list = [ ] , closed_list = [ ] ) i , j = free_cell up = moved_matrix_with_parent ( i , j , i - 1 , j , open_list , closed_list ) down = moved_matrix_with_parent ( i , j , i + 1 , j , open_list , closed_list ) left = moved_matrix_with_parent ( i , j , i , j - 1 , open_list , closed_list ) right = mo...
Get all possible movement matrixes
24,604
def read_table table table_offset = @archive_header . send "#{table}_table_offset" @io . seek @user_header . archive_header_offset + table_offset table_entries = @archive_header . send "#{table}_table_entries" data = @io . read table_entries * 16 key = Hashing :: hash_for :table , "(#{table} table)" data = Hashing :: d...
In general MPQ archives start with either the MPQ header or they start with a user header which points to the MPQ header . StarCraft 2 replays always have a user header so we don t even bother to check here .
24,605
def read_file filename hash_a = Hashing :: hash_for :hash_a , filename hash_b = Hashing :: hash_for :hash_b , filename hash_entry = @hash_table . find do | h | [ h . hash_a , h . hash_b ] == [ hash_a , hash_b ] end unless hash_entry return nil end block_entry = @block_table [ hash_entry . block_index ] unless block_ent...
To read a file from the MPQ archive we need to locate its blocks .
24,606
def assemble location = 0 @labels = { } @body = [ ] lines . each do | line | @labels [ line . label ] = location if line . label next if line . op . empty? op = Instruction . create ( line . op , line . args , location ) @body << op location += op . size end begin @body . each { | op | op . apply_labels ( @labels ) } r...
Assemble the given input .
24,607
def set_attributes_for exc , request self . backtrace = exc . backtrace . join ( "\n" ) , self . request_url = request . original_url , self . request_method = request . request_method , self . parameters = request . filtered_parameters , self . user_agent = request . user_agent , self . client_ip = request . remote_ip...
Sets Log instance attributes .
24,608
def default_action_block proc do begin create_params = instance_eval ( & @strong_params ) if resource . singular create_params [ "#{parent_resource_name}_id" ] = parent_resource_id end body model . create ( create_params ) rescue ActionController :: ParameterMissing => error body error . message status :bad_request end...
Sets the default action to create a new resource . If the resource is singular sets the parent resource id as well .
24,609
def running puts set_window_width searching = true [ -> { @kat . search @page searching = false } , -> { i = 0 while searching print "\rSearching..." . yellow + '\\|/-' [ i % 4 ] i += 1 sleep 0.1 end } ] . map { | w | Thread . new { w . call } } . each ( & :join ) puts ( ( res = format_results ) ) if res . size > 1 cas...
Do the search output the results and prompt the user for what to do next . Returns false on error or the user enters q otherwise returns true to signify to the main loop it should run again .
24,610
def format_lists ( lists ) lists . inject ( [ nil ] ) do | buf , ( _ , val ) | opts = Kat :: Search . send ( val [ :select ] ) buf << val [ :select ] . to_s . capitalize buf << nil unless opts . values . first . is_a? Array width = opts . keys . sort { | a , b | b . size <=> a . size } . first . size opts . each do | k...
Format a list of options
24,611
def format_results main_width = @window_width - ( ! hide_info? || @show_info ? 42 : 4 ) buf = [ ] if @kat . error return [ "\rConnection failed" . red ] elsif ! @kat . results [ @page ] return [ "\rNo results " . red ] end buf << "\r#{ @kat.message[:message] }\n" . red if @kat . message buf << ( "\r%-#{ main_width +...
Format the list of results with header information
24,612
def prompt n = @kat . results [ @page ] . size @h . ask ( "1#{ "-#{n}" if n > 1}" . cyan ( true ) << ' to download' << "#{ ', ' << '(n)'.cyan(true) << 'ext' if next? }" << "#{ ', ' << '(p)'.cyan(true) << 'rev' if prev? }" << "#{ ", #{ @show_info ? 'hide' : 'show' } " << '(i)'.cyan(true) << 'nfo' if hide_info? }" << ', ...
Set the prompt after the results list has been printed
24,613
def run ( argv ) load_tasks return build_task ( argv ) . run unless argv . empty? print_help_header print_help_body end
Runs a task or prints its help if it needs arguments
24,614
def build_task ( argv ) arguments = argv . dup task_name = arguments . shift klazz = Task . from_name ( task_name ) klazz . new ( * klazz . parse_options! ( arguments ) ) rescue NameError task_not_found ( task_name ) exit false rescue ArgumentError bad_arguments ( task_name ) exit false end
Builds a task and prepares it to run
24,615
def flush ( base = nil ) debug { 'flush ' << base . to_s } @sync . synchronize do if @flush_delay next_flush = @last_flush + @flush_delay if next_flush > Time . now flush_at ( next_flush , base ) else flush_now ( base ) @last_flush = Time . now end else flush_now ( base ) end end end
remove all values from cache
24,616
def []= ( key , value ) debug { '[]= ' << key . to_s } entry = get_locked_entry ( key ) begin return entry . value = value ensure entry . sync . unlock end end
store new value in cache
24,617
def debug return unless @debug message = Thread . current . to_s + ' ' + yield if defined? ( Syslog ) and Syslog . opened? Syslog . debug ( message ) else STDERR << 'syncache: ' + message + "\n" STDERR . flush end end
send debug output to syslog if enabled
24,618
def assert_keys coll , * keys check_responds_to coll , :[] check_not_empty keys assert keys . all? { | key | coll [ key ] } , "Expected coll to include all keys" end
If any key is not present in coll raise AssertionFailureError else return nil .
24,619
def assert_length coll , len check_responds_to coll , :length assert coll . length == len , "Expected coll to have %d items" , len end
If coll is given length return nil else raise AssertionFailureError .
24,620
def js_source ( source_path , namespace = nil , output_as_array = false ) template_name = File . basename ( source_path , ".ejs" ) template_name = "#{namespace}.#{template_name}" if namespace js_source_from_string ( template_name , File . read ( source_path ) , output_as_array ) end
compile a ejs file into javascript
24,621
def js_source_from_string ( template_name , content , output_as_array = false ) buffer = [ ] parsed = @parser . parse ( content ) if parsed . nil? raise ParseError . new ( @parser . failure_reason , @parser . failure_line , @parser . failure_column ) end template_namespace ( buffer , template_name ) template_header ( b...
compile a string containing ejs source into javascript
24,622
def provenance s = [ rdf_uri , RDF :: PROV . SoftwareAgent , @@agent ] rdf . insert ( s ) s = [ rdf_uri , RDF :: PROV . generatedAtTime , rdf_now ] rdf . insert ( s ) end
Assert PROV . SoftwareAgent and PROV . generatedAtTime
24,623
def rdf_find_object ( id ) return nil unless rdf_valid? rdf . each_statement do | s | if s . subject == @iri . to_s return s . object if s . object . to_s =~ Regexp . new ( id , Regexp :: IGNORECASE ) end end nil end
Regexp search to find an object matching a string if it belongs to
24,624
def rdf_find_subject ( id ) return nil unless rdf_valid? rdf . each_subject do | s | return s if s . to_s =~ Regexp . new ( id , Regexp :: IGNORECASE ) end nil end
Regexp search to find a subject matching a string
24,625
def write_to ( io ) write_sc ( io , conformance ) write_sc ( io , 'profile' , profile ) prefixes . each { | prefix , url | write_sc ( io , 'prefix' , "#{prefix}:" , url ) } write_sc ( io , 'fields' , * fields ) entries . each { | entry | io . puts ( entry_line ( entry ) ) } write_sc ( io , 'eof' ) end
Creates a new manifest . Note that the prefix field and entry arrays are copied on initialization as are the individual entry hashes .
24,626
def write_sc ( io , comment , * columns ) io << '#%' << comment io << COLSEP << columns . join ( COLSEP ) unless columns . empty? io << "\n" end
writes a checkm structured comment
24,627
def Scenario ( * args , & example_group_block ) args << { } unless args . last . is_a? ( Hash ) args . last . update ( :scenario => true ) describe ( "Scenario:" , * args , & example_group_block ) end
Defines a new Scenario group
24,628
def skip_examples_after ( example , example_group = self ) examples = example_group . descendant_filtered_examples . flatten examples [ examples . index ( example ) .. - 1 ] . each do | e | e . metadata [ :pending ] = true e . metadata [ :skipped ] = true end end
Skip examples after the example provided .
24,629
def handle_exception ( example ) if example . instance_variable_get ( :@exception ) if metadata [ :background ] skip_examples_after ( example , ancestors [ 1 ] ) else skip_examples_after ( example ) end end end
If the example failed or got an error then skip the dependent examples . If the failure occurred in a background example group then skip all examples in the feature .
24,630
def update_job ( opts = { } ) index = get_job_index ( opts [ :id ] ) job = find_job ( opts [ :id ] ) @jobs [ index ] = job . update ( opts ) end
Replace job with specified id
24,631
def add_job ( opts = { } ) @jobs << Job . new ( Parser :: Schedule . new ( opts [ :schedule ] ) , Parser :: Command . new ( opts [ :command ] ) ) end
Adds a job to
24,632
def call ( env ) env [ 'aker.configuration' ] = @configuration env [ 'aker.authority' ] = @configuration . composite_authority env [ 'aker.interactive' ] = interactive? ( env ) @app . call ( env ) end
Creates a new instance of the middleware .
24,633
def hash_csv ( csv_string ) require 'csv' csv = CSV . parse ( csv_string ) headers = csv . shift output = [ ] csv . each do | row | hash = { } headers . each do | header | hash [ header ] = row . shift . to_s end output << hash end return output end
Needs to be refactored to somewhere more generic
24,634
def retrieve_save ( data ) File . open ( location , 'w' ) do | f | f << ( data . respond_to? ( :read ) ? data . read : data ) end end
stream|string - > create data file
24,635
def wait_until_host_is_available ( host , get_ip = false ) resolved_host = Resolv . getaddresses ( host ) . first if resolved_host . nil? print ( "Waiting for #{host} to resolve" ) wait_until ( 'ready!' ) { resolved_host = Resolv . getaddresses ( host ) . first } end host = resolved_host if get_ip unless remote_is_avai...
Can take a host name or an ip address . Resolves the host name and returns the ip address if get_ip is passed in as true .
24,636
def search ( qry ) rg = Regexp . new ( qry || '' , Regexp :: IGNORECASE ) results = @addresses . values . flatten . each_slice ( 2 ) . find_all do | e , n | e . match ( rg ) || n . match ( rg ) end results . sort { | a , b | a [ 0 ] . downcase <=> b [ 0 ] . downcase } end
Retrieves name and email addresses that contain the passed string sorted by email adddress
24,637
def update ( id , name , addresses ) @cache_last_modified = DateTime . now . to_s @addresses [ id ] = addresses . map { | a | [ a , name ] } end
Update the name and email addresses for the passed GMail ID .
24,638
def mount_rails_info match '/rails/info' => 'rails_info/properties#index' , via : :get , via : :get , as : 'rails_info' match '/rails/info/properties' => 'rails_info/properties#index' , via : :get , via : :get , as : 'rails_info_properties' match '/rails/info/routes' => 'rails_info/routes#index' , via : :get , as : 'ra...
Includes mount_sextant method for routes . This method is responsible to generate all needed routes for sextant
24,639
def build_candidates ( candidates ) candidates . to_a . map do | object , preferences | candidate ( object ) . tap do | c | c . prefer ( * preferences . map { | t | target ( t ) } ) end end end
Builds a list of candidates for the + MatchMaker + . The parameter is a hash of unwrapped canditate objects to their preferred targets .
24,640
def sequel_url return '' unless db_type connect_string = db_type + '://' unless db_user . nil? connect_string += db_user connect_string += db_host ? '@' : '/' connect_string += db_host + '/' if db_host end connect_string + db_name end
Converts the object into a textual string that can be sent to sequel
24,641
def execute ( output : $stdout , errors : $stderr ) if empty_name? output . puts 'No name given' return false end result = run "find #{@path} #{type} -name '#{@name}'" do | _out , err | errors << err if err end @result = result . out . split ( "\n" ) . map { | path | "#{path} NEW_NAME=> #{path}" } . join ( "\n" ) rescu...
Performs the find unless no name provided
24,642
def list ( comment_id = 0 , max = 50 ) req_method = :GET req_uri = '/api/v4/get_comment_list' req_options = { :commentid => comment_id , :count => max } response = request_api ( req_method , req_uri , req_options ) normalize_comments JSON . parse ( response ) end
Get comment list This will contains comments relations in response .
24,643
def total ( resource = nil ) req_method = :GET req_uri = '/api/v4/get_comment_count' req_options = { } case when resource . is_a? ( Integer ) req_options [ :postid ] = resource when resource . is_a? ( String ) req_options [ :url ] = resource end response = request_api ( req_method , req_uri , req_options ) response = J...
Get comment count If resource is nil it will return all posts comment count in an array otherwise just return a hash object .
24,644
def index core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :posts ] ) @posts_status = 'published' @posts_status = 'drafted' if params [ :status ] && params [ :status ] === 'drafted' @posts_status = 'deleted' if params [ :status ] && params [ :status ] === 'deleted' @posts_informations = { publ...
This function shows the list of published posts .
24,645
def new core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :posts_new ] ) @post = LatoBlog :: Post . new set_current_language params [ :language ] if params [ :language ] if params [ :parent ] @post_parent = LatoBlog :: PostParent . find_by ( id : params [ :parent ] ) end fetch_external_objects ...
This function shows the view to create a new post .
24,646
def create @post = LatoBlog :: Post . new ( new_post_params ) unless @post . save flash [ :danger ] = @post . errors . full_messages . to_sentence redirect_to lato_blog . new_post_path return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :post_create_success ] redirect_to lato_blog . post_path ( @pos...
This function creates a new post .
24,647
def edit core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :posts_edit ] ) @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence if @post . meta_language != cookies [ :lato_blog__current_language ] set_current_language @post . meta_language end fetch_exter...
This function show the view to edit a post .
24,648
def update @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence autosaving = params [ :autosave ] && params [ :autosave ] == 'true' if autosaving @post . update ( edit_post_params ) update_fields render status : 200 , json : { } return end unless @post . update ( edit_post_params...
This function updates a post .
24,649
def update_status @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence @post . update ( meta_status : params [ :status ] ) end
This function updates the status of a post .
24,650
def update_categories @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence params [ :categories ] . each do | category_id , value | category = LatoBlog :: Category . find_by ( id : category_id ) next if ! category || category . meta_language != @post . meta_language category_post...
This function updates the categories of a post .
24,651
def update_tags @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence params_tags = params [ :tags ] . map ( & :to_i ) tag_posts = LatoBlog :: TagPost . where ( lato_blog_post_id : @post . id ) params_tags . each do | tag_id | tag = LatoBlog :: Tag . find_by ( id : tag_id ) next i...
This function updates the tags of a post .
24,652
def update_seo_description @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence @post . update ( seo_description : params [ :seo_description ] ) end
This function updates the seo description of a post .
24,653
def destroy @post = LatoBlog :: Post . find_by ( id : params [ :id ] ) return unless check_post_presence unless @post . destroy flash [ :danger ] = @post . post_parent . errors . full_messages . to_sentence redirect_to lato_blog . edit_post_path ( @post . id ) return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ ...
This function destroyes a post .
24,654
def destroy_all_deleted @posts = LatoBlog :: Post . deleted if ! @posts || @posts . empty? flash [ :warning ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :deleted_posts_not_found ] redirect_to lato_blog . posts_path ( status : 'deleted' ) return end @posts . each do | post | unless post . destroy flash [ :danger ] = post...
Tis function destroyes all posts with status deleted .
24,655
def update_field ( field , value ) case field . typology when 'text' update_field_text ( field , value ) when 'textarea' update_field_textarea ( field , value ) when 'datetime' update_field_datetime ( field , value ) when 'editor' update_field_editor ( field , value ) when 'geolocalization' update_field_geolocalization...
This function updates a single field from its key and value .
24,656
def get_attributes url = URI . parse ( 'http://www.blip.tv/' ) res = Net :: HTTP . start ( url . host , url . port ) { | http | http . get ( "http://www.blip.tv/file/#{@id.to_s}?skin=api" ) } hash = Hash . from_xml ( res . body ) if hash [ "response" ] [ "status" ] != "OK" raise VideoResponseError . new ( hash [ "respo...
fire off a HTTP GET response to Blip . tv
24,657
def delete! ( creds = { } , section = "file" , reason = "because" ) BlipTV :: ApiSpec . check_attributes ( 'videos.delete' , creds ) reason = reason . gsub ( " " , "%20" ) if creds [ :username ] && ! creds [ :userlogin ] creds [ :userlogin ] = creds [ :username ] end url , path = "www.blip.tv" , "/?userlogin=#{creds[:u...
delete! will delete the file from Blip . tv
24,658
def _response ( status , body = nil , headers = { } ) body = [ body ] . compact headers = headers . merge ( "Content-Type" => "application/json" ) Rack :: Response . new ( body , status , headers ) . finish end
Returns a valid rack response .
24,659
def option ( name , behaviors = { } , & block ) Ablerc . options << Ablerc :: Option . new ( name , behaviors , & block ) end
Describe the options available
24,660
def value return nil unless @model && @model . status == :optimized value = @model . variable_value self case @type when :integer value . round when :binary [ false , true ] [ value . round ] else value end end
Get the final value of this variable
24,661
def run_parse obj = { 'name' => VRTK :: NAME , 'version' => VRTK :: VERSION , 'codename' => VRTK :: CODENAME , 'ffmpeg' => ffmpeg_version , 'magick' => magick_version , 'license' => VRTK :: LICENSE } puts JSON . pretty_unparse obj end
noinspection RubyStringKeysInHashInspection RubyResolve
24,662
def scrape_main_page page = fetch ( 'http://tf2r.com/raffles.html' ) raffle_links = page . links_with ( href : / \. \/ / ) raffle_links . map! { | x | x . uri . to_s } raffle_links . reverse! end
Scrapes TF2R for all active raffles .
24,663
def scrape_raffle_for_creator ( page ) infos = page . parser . css ( '.raffle_infomation' ) user_anchor = infos [ 2 ] . css ( 'a' ) [ 0 ] steam_id = extract_steam_id ( user_anchor . attribute ( 'href' ) . to_s ) username = user_anchor . text avatar_link = infos [ 1 ] . css ( 'img' ) [ 0 ] . attribute ( 'src' ) . to_s p...
Scrapes a raffle page for information about the creator .
24,664
def scrape_raffle_for_raffle ( page ) infos = page . parser . css ( '.raffle_infomation' ) raffle_tds = infos [ 3 ] . css ( 'td' ) link_snippet = extract_link_snippet ( page . uri . path ) title = extract_title ( infos [ 0 ] . text ) description = raffle_tds [ 1 ] . text start_time = extract_start_time ( raffle_tds [ 9...
Scrapes a raffle page for some information about the raffle .
24,665
def scrape_raffle_for_participants ( page ) participants = [ ] participant_divs = page . parser . css ( '.pentry' ) participant_divs . each do | participant | user_anchor = participant . children [ 1 ] steam_id = extract_steam_id ( user_anchor . to_s ) username = participant . text color = extract_color ( user_anchor ....
Scrapes a raffle page for all the participants .
24,666
def scrape_user ( user_page ) if user_page . parser . css ( '.profile_info' ) . empty? raise InvalidUserPage , 'The given page does not correspond to any user.' else infos = user_page . parser . css ( '.raffle_infomation' ) user_anchor = infos [ 1 ] . css ( 'a' ) [ 0 ] steam_id = extract_steam_id ( user_page . uri . to...
Scrapes a user page for information about the user .
24,667
def scrape_ranks ( info_page ) rank_divs = info_page . parser . css ( '#ranks' ) . children ranks = rank_divs . select { | div | div . children . size == 3 } ranks . map { | div | extract_rank ( div ) } end
Scrapes the TF2R info page for available user ranks .
24,668
def start storage . delete_all ( teams_key ) storage . get_all ( tokens_key ) . each do | id , token | create ( id , token ) end end
Create websocket connections for active tokens
24,669
def stop thr = Thread . new do conns = storage . get_all ( teams_key ) storage . pipeline do conns . each { | k , _ | storage . set ( teams_key , k , 'destroy' ) } end info ( 'Stopped.' ) end thr . join end
Remove all connections from app will disconnect in monitor loop
24,670
def restart conns = storage . get_all ( teams_key ) storage . pipeline do conns . each { | k , _ | storage . set ( teams_key , k , 'restart' ) } end end
Issue restart status on all RTM connections will re - connect in monitor loop
24,671
def find_connection ( id ) connections . each do | _ , conn | return ( conn . connected? ? conn : false ) if conn && conn . id == id end false end
Find the connection based on id and has active connection
24,672
def create ( id , token ) fail SlackBotManager :: TokenAlreadyConnected if find_connection ( id ) conn = SlackBotManager :: Client . new ( token ) conn . connect if conn cid = [ id , Time . now . to_i ] . join ( ':' ) connections [ cid ] = conn info ( "Connected: #{id} (Connection: #{cid})" ) storage . set ( teams_key ...
Create new connection if not exist
24,673
def destroy ( * args ) options = args . extract_options! if options [ :cid ] conn = connections [ options [ :cid ] ] cid = options [ :cid ] elsif options [ :id ] conn , cid = find_connection ( options [ :id ] ) end return false unless conn && cid begin thr = Thread . new do storage . delete ( teams_key , conn . id ) re...
Disconnect from a RTM connection
24,674
def method_missing ( method_name , * args , & block ) if controller . respond_to? method_name controller . send method_name , * args , & block else super end end
useful for path helpers used in event maps
24,675
def publish ( queue , payload = { } ) if queue_list . include? queue begin x_direct . publish ( payload . to_json , mandatory : true , routing_key : get_queue ( queue ) . name ) log_message ( "Publish status: success, Queue : #{queue}, Content : #{payload}" ) :success rescue => ex log_message ( "Publish error:#{ex.mess...
Initialize Instance methods Publish message to the respective queue
24,676
def unicast ( q_name , payload = { } ) begin x_default . publish ( payload . to_json , routing_key : dot_formatted ( q_name ) ) log_message ( "unicast status: success, Queue : #{q_name}, Content : #{payload}" ) :success rescue => ex log_message ( "Unicast error:#{ex.message}" ) :error end end
unicast message to queues
24,677
def multicast ( topic , payload = { } ) begin x_topic . publish ( payload . to_json , routing_key : dot_formatted ( topic ) ) log_message ( "multicast status: success, Topic : #{topic}, Content : #{payload}" ) :success rescue => ex log_message ( "Multicast error:#{ex.message}" ) :error end end
multicast message to queues based on topic subscription
24,678
def clean if @dirty @store = FFI :: MemoryPointer . new @element_size , @items . size , true offset = 0 @items . each do | item | LibC . memcpy ( @store + offset , item . pointer , @element_size ) offset += @element_size end @dirty = false end end
Allocate a contiguous chunk of memory and copy over the PollItem structs to this block . Note that the old +
24,679
def format_value case @type when "string" @value when "date" @value . kind_of? ( Time ) ? @value . iso8601 ( 3 ) : @value when "int" @value . kind_of? ( Integer ) ? @value : @value . to_i when "float" @value . kind_of? ( Float ) ? @value : @value . to_f when "boolean" @value when "id" @value end . to_s end
Format the value .
24,680
def combine_hashes ( array_of_hashes ) array_of_hashes . select { | v | v . kind_of? ( Hash ) } . inject ( { } ) { | sum , hash | hash . inject ( sum ) { | sum , ( k , v ) | sum . merge ( k => v ) } } end
to obtain a hash of all possible keys
24,681
def from format @citero = @citero :: from ( Formats :: valueOf ( format . upcase ) ) self rescue Exception => e raise TypeError , "Mismatched data for #{format}" end
The constructor takes input data taken from the parent module and creates an instance of the Citero java object . Returns itself for builder patttern . The from method is private it takes in a format and gets the appropriate Format java class and then calls the from method in the Citero java object and stores its retur...
24,682
def to format if to_formats . include? format @citero :: to ( Formats :: valueOf ( format . upcase ) ) else @citero :: to ( CitationStyles :: valueOf ( format . upcase ) ) end rescue Exception => e raise ArgumentError , "Missing a source format. Use from_[format] first." end
The to method is private it takes in a format and gets the appropriate Format java class and then calls the to method in the Citero java object and returns the return value as a string .
24,683
def each_data_path ( path ) return enum_for ( :each_data_path , path ) unless block_given? DataPaths . paths . each do | dir | full_path = File . join ( dir , path ) yield ( full_path ) if File . exists? ( full_path ) end end
Passes all existing data paths for the specified path within the data directories to the given block .
24,684
def each_data_file ( path ) return enum_for ( :each_data_file , path ) unless block_given? each_data_path ( path ) do | full_path | yield ( full_path ) if File . file? ( full_path ) end end
Finds all occurrences of a given file path within all data directories .
24,685
def each_data_dir ( path ) return enum_for ( :each_data_dir , path ) unless block_given? each_data_path ( path ) do | full_path | yield ( full_path ) if File . directory? ( full_path ) end end
Finds all occurrences of a given directory path within all data directories .
24,686
def glob_data_paths ( pattern , & block ) return enum_for ( :glob_data_paths , pattern ) . to_a unless block_given? DataPaths . paths . each do | path | Dir . glob ( File . join ( path , pattern ) , & block ) end end
Finds all paths that match a given pattern within all data directories .
24,687
def initWithFrame ( properties = { } ) if properties . is_a? Hash super ( CGRect . new ) initialize_bindings set_properties ( properties ) else super ( properties ) end view_setup self end
Create new instance from a hash of properties with values .
24,688
def add_target ( clazz , options = { } ) pool_name = Celluloid . uuid supervisor . pool ( clazz , as : pool_name , args : [ options ] , size : MultiSync . target_pool_size ) pool_name end
Initialize a new Client object
24,689
def potential_next ( current , base ) candidate = super ( current , base ) return candidate if ( base . year - candidate . year ) . to_i % @interval == 0 years = ( ( base . year - candidate . year ) . to_i % @interval ) ( candidate + years . years ) . beginning_of_year end
closest valid date
24,690
def fed = ( fed ) obj = ICU :: Federation . find ( fed ) @fed = obj ? obj . code : nil raise "invalid tournament federation (#{fed})" if @fed . nil? && fed . to_s . strip . length > 0 end
Constructor . Name and start date must be supplied . Other attributes are optional . Set the tournament federation . Can be _nil_ .
24,691
def add_round_date ( round_date ) round_date = round_date . to_s . strip parsed_date = Util :: Date . parse ( round_date ) raise "invalid round date (#{round_date})" unless parsed_date @round_dates << parsed_date end
Add a round date .
24,692
def tie_breaks = ( tie_breaks ) raise "argument error - always set tie breaks to an array" unless tie_breaks . class == Array @tie_breaks = tie_breaks . map do | str | tb = ICU :: TieBreak . identify ( str ) raise "invalid tie break method '#{str}'" unless tb tb . id end end
Canonicalise the names in the tie break array .
24,693
def add_player ( player ) raise "invalid player" unless player . class == ICU :: Player raise "player number (#{player.num}) should be unique" if @player [ player . num ] @player [ player . num ] = player end
Add a new player to the tournament . Must have a unique player number .
24,694
def rerank tie_break_methods , tie_break_order , tie_break_hash = tie_break_data @player . values . sort do | a , b | cmp = 0 tie_break_methods . each do | m | cmp = ( tie_break_hash [ m ] [ a . num ] <=> tie_break_hash [ m ] [ b . num ] ) * tie_break_order [ m ] if cmp == 0 end cmp end . each_with_index do | p , i | p...
Rerank the tournament by score first and if necessary using a configurable tie breaker method .
24,695
def renumber ( criterion = :rank ) if ( criterion . class == Hash ) map = criterion else map = Hash . new criterion = criterion . to_s . downcase if criterion == 'rank' begin check_ranks rescue criterion = 'name' end end if criterion == 'rank' @player . values . each { | p | map [ p . num ] = p . rank } elsif criterion...
Renumber the players according to a given criterion .
24,696
def validate! ( options = { } ) begin check_ranks rescue rerank end if options [ :rerank ] check_players check_rounds check_dates check_teams check_ranks ( :allow_none => true ) check_type ( options [ :type ] ) if options [ :type ] true end
Raise an exception if a tournament is not valid . The _rerank_ option can be set to _true_ to rank the tournament just prior to the test if ranking data is missing or inconsistent .
24,697
def serialize ( format , arg = { } ) serializer = case format . to_s . downcase when 'krause' then ICU :: Tournament :: Krause . new when 'foreigncsv' then ICU :: Tournament :: ForeignCSV . new when 'spexport' then ICU :: Tournament :: SPExport . new when '' then raise "no format supplied" else raise "unsupported seria...
Convenience method to serialise the tournament into a supported format . Throws an exception unless the name of a supported format is supplied or if the tournament is unsuitable for serialisation in that format .
24,698
def check_players raise "the number of players (#{@player.size}) must be at least 2" if @player . size < 2 ids = Hash . new fide_ids = Hash . new @player . each do | num , p | if p . id raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids [ p . id ] ids [ p . id ] = num end if p . fide_id raise "duplicat...
Check players .
24,699
def check_rounds round = Hash . new round_last = last_round @player . values . each do | p | p . results . each do | r | round [ r . round ] = true end end ( 1 .. round_last ) . each { | r | raise "there are no results for round #{r}" unless round [ r ] } if rounds raise "declared number of rounds is #{rounds} but ther...
Round should go from 1 to a maximum there should be at least one result in every round and if the number of rounds has been set it should agree with the largest round from the results .