idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
24,300
def max_action_length @max_action_length ||= actions . reduce ( 0 ) { | m , a | [ m , a . to_s . length ] . max } end
the maximum length of all the actions known to the logger .
24,301
def browser_name @browser_name ||= begin ua = request . user_agent . to_s . downcase if ua . index ( 'msie' ) && ! ua . index ( 'opera' ) && ! ua . index ( 'webtv' ) 'ie' + ua [ ua . index ( 'msie' ) + 5 ] . chr elsif ua . index ( 'gecko/' ) 'gecko' elsif ua . index ( 'opera' ) 'opera' elsif ua . index ( 'konqueror' ) 'konqueror' elsif ua . index ( 'iphone' ) 'iphone' elsif ua . index ( 'applewebkit/' ) 'safari' elsif ua . index ( 'mozilla/' ) 'gecko' else "" end end end
find the current browser name
24,302
def load ( file ) if File . exist? file symbolize_keys ( YAML . load_file ( File . expand_path ( '.' , file ) ) ) else { } end end
Loads a YAML file parses it and returns a hash with symbolized keys .
24,303
def load_config ( file = @options . config ) config = load ( file ) config [ :timezone_difference ] = 0 if config [ :timezone_difference ] . nil? config [ :mentions ] = { } if config [ :mentions ] . nil? config [ :mentions ] [ :enabled ] = true if config [ :mentions ] [ :enabled ] . nil? config [ :mentions ] [ :top ] = 10 if config [ :mentions ] [ :top ] . nil? config [ :mentions ] [ :notop ] = 20 if config [ :mentions ] [ :notop ] . nil? config [ :clients ] = { } if config [ :clients ] . nil? config [ :clients ] [ :enabled ] = true if config [ :clients ] [ :enabled ] . nil? config [ :clients ] [ :top ] = 10 if config [ :clients ] [ :top ] . nil? config [ :clients ] [ :notop ] = 20 if config [ :clients ] [ :notop ] . nil? config [ :hashtags ] = { } if config [ :hashtags ] . nil? config [ :hashtags ] [ :enabled ] = true if config [ :hashtags ] [ :enabled ] . nil? config [ :hashtags ] [ :top ] = 10 if config [ :hashtags ] [ :top ] . nil? config [ :hashtags ] [ :notop ] = 20 if config [ :hashtags ] [ :notop ] . nil? config [ :smileys ] = { } if config [ :smileys ] . nil? config [ :smileys ] [ :enabled ] = true if config [ :smileys ] [ :enabled ] . nil? config [ :smileys ] [ :top ] = 10 if config [ :smileys ] [ :top ] . nil? config [ :smileys ] [ :notop ] = 0 if config [ :smileys ] [ :notop ] . nil? config [ :ignored_users ] = [ ] if config [ :ignored_users ] . nil? config [ :renamed_users ] = [ ] if config [ :renamed_users ] . nil? args_override config end
Loads a YAML file parses it and checks if all values are given . If a value is missing it will be set with the default value .
24,304
def display_recent load_recent puts ( Problem . total ) . downto ( Problem . total - 9 ) do | i | puts "#{i} - #{Problem[i].title}" end end
Displays the 10 most recently added problems .
24,305
def display_page ( page ) load_page ( page ) puts start = ( page - 1 ) * Page :: LENGTH + 1 start . upto ( start + Page :: LENGTH - 1 ) do | i | puts "#{i} - #{Problem[i].title}" unless i >= Problem . total - 9 end end
Displays the problem numbers and titles for an individual page of the archive .
24,306
def display_problem ( id ) load_problem_details ( id ) puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" puts puts Problem [ id ] . title . upcase puts "Problem #{id}" puts puts Problem [ id ] . published puts Problem [ id ] . solved_by puts Problem [ id ] . difficulty if id < Problem . total - 9 puts puts "https://projecteuler.net/problem=#{id}" puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" end
Displays the details of an individual problem .
24,307
def authorize ( callback_url , code ) data = open ( "#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}" ) . read match_data = data . match ( / / ) @expires = match_data && match_data [ 1 ] || nil @access_token = data . match ( / / ) [ 1 ] end
Take the oauth2 request token and turn it into an access token which can be used to access private data
24,308
def devise_for ( * resources ) @devise_finalized = false options = resources . extract_options! options [ :as ] ||= @scope [ :as ] if @scope [ :as ] . present? options [ :module ] ||= @scope [ :module ] if @scope [ :module ] . present? options [ :path_prefix ] ||= @scope [ :path ] if @scope [ :path ] . present? options [ :path_names ] = ( @scope [ :path_names ] || { } ) . merge ( options [ :path_names ] || { } ) options [ :constraints ] = ( @scope [ :constraints ] || { } ) . merge ( options [ :constraints ] || { } ) options [ :defaults ] = ( @scope [ :defaults ] || { } ) . merge ( options [ :defaults ] || { } ) options [ :options ] = @scope [ :options ] || { } options [ :options ] [ :format ] = false if options [ :format ] == false resources . map! ( & :to_sym ) resources . each do | resource | mapping = Devise . add_mapping ( resource , options ) begin raise_no_devise_method_error! ( mapping . class_name ) unless mapping . to . respond_to? ( :devise ) rescue NameError => e raise unless mapping . class_name == resource . to_s . classify warn "[WARNING] You provided devise_for #{resource.inspect} but there is " << "no model #{mapping.class_name} defined in your application" next rescue NoMethodError => e raise unless e . message . include? ( "undefined method `devise'" ) raise_no_devise_method_error! ( mapping . class_name ) end routes = mapping . used_routes devise_scope mapping . name do if block_given? ActiveSupport :: Deprecation . warn "Passing a block to devise_for is deprecated. " "Please remove the block from devise_for (only the block, the call to " "devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " "with the block instead" , caller yield end with_devise_exclusive_scope mapping . fullpath , mapping . name , options do routes . each { | mod | send ( "devise_#{mod}" , mapping , mapping . controllers ) } end end end end
Includes devise_for method for routes . This method is responsible to generate all needed routes for devise based on what modules you have defined in your model .
24,309
def remove ( channel_or_channel_name ) @mutex . synchronize do if channel_or_channel_name . is_a? ( String ) channel_or_channel_name = find ( channel_or_channel_name ) end @channels . delete ( channel_or_channel_name ) end end
Removes a Channel from the ChannelList .
24,310
def remove_user ( nick ) @mutex . synchronize do channels = Set . new @channels . each do | channel | if channel . remove_user ( nick ) channels << channel end end channels end end
Removes a User from all Channels from the ChannelList . Returning a Set of Channels in which the User was .
24,311
def users users = Set . new @channels . each do | channel | users . merge channel . users end users end
Returns a Set of all Users that are in one of the Channels from the ChannelList .
24,312
def ping ( source_uri , target_uri ) header = request_header target_uri pingback_server = header [ 'X-Pingback' ] unless pingback_server doc = Nokogiri :: HTML ( request_all ( target_uri ) . body ) link = doc . xpath ( '//link[@rel="pingback"]/attribute::href' ) . first pingback_server = URI . escape ( link . content ) if link end raise InvalidTargetException unless pingback_server send_pingback pingback_server , source_uri , target_uri end
send an pingback request to the targets associated pingback server .
24,313
def decode_wind ( s ) if s =~ / \d \d \d / wind = case $4 when "KT" then $2 . to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $2 . to_f when "KMH" then $2 . to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end wind_max = case $4 when "KT" then $3 . to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $3 . to_f when "KMH" then $3 . to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end if wind_max < wind or wind_max . nil? wind_max = wind end @winds << { :wind => wind , :wind_max => wind_max , :wind_direction => $1 . to_i } end if s =~ / \d / wind = case $2 when "KT" then $1 . to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $1 . to_f when "KMH" then $1 . to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end @winds << { :wind => wind } end end
Wind parameters in meters per second
24,314
def recalculate_winds wind_sum = @winds . collect { | w | w [ :wind ] } . inject ( 0 ) { | b , i | b + i } @wind = wind_sum . to_f / @winds . size if @winds . size == 1 @wind_direction = @winds . first [ :wind_direction ] else @wind_direction = nil end end
Calculate wind parameters some metar string has multiple winds recorded
24,315
def add_source ( source ) @semaphore . synchronize do @sources << source end if @registry . frozen? self . reload! else @semaphore . synchronize do Fwissr . merge_conf! ( @registry , source . get_conf ) end end self . ensure_refresh_thread end
Init Add a source to registry
24,316
def get ( key ) key_ary = key . split ( '/' ) key_ary . shift if ( key_ary . first == '' ) cur_hash = self . registry key_ary . each do | key_part | cur_hash = cur_hash [ key_part ] return nil if cur_hash . nil? end cur_hash end
Get a registry key value
24,317
def hints_for ( attribute ) result = Array . new @base . class . validators_on ( attribute ) . map do | v | validator = v . class . to_s . split ( '::' ) . last . underscore . gsub ( '_validator' , '' ) if v . options [ :message ] . is_a? ( Symbol ) message_key = [ validator , v . options [ :message ] ] . join ( '.' ) result << generate_message ( attribute , message_key , v . options ) else message_key = validator message_key = [ validator , ".must_be_a_number" ] . join ( '.' ) if validator == 'numericality' result << generate_message ( attribute , message_key , v . options ) unless VALIDATORS_WITHOUT_MAIN_KEYS . include? ( validator ) v . options . each do | o | if MESSAGES_FOR_OPTIONS . include? ( o . first . to_s ) count = o . last count = ( o . last . to_sentence if %w( inclusion exclusion ) . include? ( validator ) ) rescue o . last result << generate_message ( attribute , [ validator , o . first . to_s ] . join ( '.' ) , { :count => count } ) end end end end result end
Pass in the instance of the object that is using the errors object .
24,318
def select ( statement , build_arg = nil ) result_set = generic_query ( statement ) DohDb . logger . call ( 'result' , "selected #{result_set.size} rows" ) rows = get_row_builder ( build_arg ) . build_rows ( result_set ) rows end
The most generic form of select . It calls to_s on the statement object to facilitate the use of sql builder objects .
24,319
def select_row ( statement , build_arg = nil ) rows = select ( statement , build_arg ) raise UnexpectedQueryResult , "selected #{rows.size} rows; expected 1" unless rows . size == 1 rows [ 0 ] end
Simple convenience wrapper around the generic select call . Throws an exception unless the result set is a single row . Returns the row selected .
24,320
def select_optional_row ( statement , build_arg = nil ) rows = select ( statement , build_arg ) raise UnexpectedQueryResult , "selected #{rows.size} rows; expected 0 or 1" if rows . size > 1 if rows . empty? then nil else rows [ 0 ] end end
Simple convenience wrapper around the generic select call . Throws an exception unless the result set is empty or a single row . Returns nil if the result set is empty or the row selected .
24,321
def select_transpose ( statement , build_arg = nil ) rows = select ( statement , build_arg ) return { } if rows . empty? field_count = rows . first . size if field_count < 2 raise UnexpectedQueryResult , "must select at least 2 fields in order to transpose" elsif field_count == 2 Doh . array_to_hash ( rows ) { | row | [ row . at ( 0 ) , row . at ( 1 ) ] } else key_field = rows . first . keys . first Doh . array_to_hash ( rows ) do | row | value = row . to_h value . delete ( key_field ) [ row . at ( 0 ) , value ] end end end
Rows in the result set must have 2 or more fields . If there are 2 fields returns a hash where each key is the first field in the result set and the value is the second field . If there are more than 2 fields returns a hash where each key is the first field in the result set and the value is the row itself as a Hash and without the field used as a key .
24,322
def get ( * keys ) return self . connection . hget ( @key , keys . first ) if keys . size == 1 return self . connection . mapped_hmget ( @key , * keys ) . reject { | _ , v | v . nil? } end
Returns the value at key
24,323
def set ( key , value , overwrite : true ) result = if overwrite self . connection . hset ( @key , key , value ) else self . connection . hsetnx ( @key , key , value ) end return coerce_bool ( result ) end
Sets or updates the value at key
24,324
def increment ( key , by : 1 ) if by . is_a? ( Float ) self . connection . hincrbyfloat ( @key , key , by . to_f ) . to_f else self . connection . hincrby ( @key , key , by . to_i ) . to_i end end
Increments the value at the given key
24,325
def url_for ( options = { } ) options = case options when String uri = Addressable :: URI . new uri . query_values = @hash_of_additional_params options + ( options . index ( '?' ) . nil? ? '?' : '&' ) + "#{uri.query}" when Hash options . reverse_merge ( @hash_of_additional_params || { } ) else options end super end
override default url_for method . Add ability to set default params .
24,326
def include? ( other ) other_name = case other when Group ; other . name ; else other . to_s ; end self . find { | g | g . name . downcase == other_name . downcase } end
Creates a new group with the given name . You can add children using << .
24,327
def marshal_load ( dumped_tree_array ) nodes = { } for node_hash in dumped_tree_array do name = node_hash [ :name ] parent_name = node_hash [ :parent ] content = Marshal . load ( node_hash [ :content ] ) if parent_name then nodes [ name ] = current_node = self . class . new ( name , content ) nodes [ parent_name ] . add current_node else initialize ( name , content ) nodes [ name ] = self end end end
Copy - pasted from parent in order to use appropriate class when deserializing children .
24,328
def read serialized = File . read ( path ) extract_links ( JSON . parse ( serialized ) ) . flatten . each_slice ( 4 ) . to_a end
Reads the content of the Google Chrome bookmarks file
24,329
def extract_children ( tag , children ) children . map do | child | if child [ "children" ] extract_children ( "#{tag},#{child['name']}" , child [ "children" ] ) else [ child [ "url" ] , child [ "name" ] , "" , tag ] end end end
Extracts the children from the JSON file
24,330
def evaluate ( scope , locals , & block ) c = Handlebarer :: Compiler . new c . compile ( data ) end
Evaluate the template . Compiles the template for JST
24,331
def run ( args ) options = parse_args ( args ) po_file = Extractor . new . extract ( options [ :path ] ) if options [ :output_file ] with_output_file ( options [ :output_file ] ) { | f | po_file . write_to ( f ) } else po_file . write_to ( STDOUT ) end rescue => e error ( e ) end
Run the commmand line tool puttext .
24,332
def put_changes_document_stream_with_http_info ( request ) raise ArgumentError , 'Incorrect request type' unless request . is_a? PutChangesDocumentStreamRequest @api_client . config . logger . debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client . config . debugging local_var_path = '/comparison/compareDocuments/changes/stream' query_params = { } header_params = { } header_params [ 'Accept' ] = @api_client . select_header_accept ( [ 'application/json' , 'application/xml' ] ) header_params [ 'Content-Type' ] = @api_client . select_header_content_type ( [ 'application/json' , 'application/xml' ] ) form_params = { } post_body = @api_client . object_to_http_body ( request . request ) data , status_code , headers = @api_client . call_api ( :PUT , local_var_path , header_params : header_params , query_params : query_params , form_params : form_params , body : post_body , access_token : get_access_token , return_type : 'File' ) if @api_client . config . debugging @api_client . config . logger . debug "API called: ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [ data , status_code , headers ] end
Applies changes to the document and returns stream of document with the result of comparison
24,333
def put_changes_images_with_http_info ( request ) raise ArgumentError , 'Incorrect request type' unless request . is_a? PutChangesImagesRequest @api_client . config . logger . debug 'Calling API: ChangesApi.put_changes_images ...' if @api_client . config . debugging local_var_path = '/comparison/compareDocuments/changes/images' query_params = { } if local_var_path . include? ( '{' + downcase_first_letter ( 'OutFolder' ) + '}' ) local_var_path = local_var_path . sub ( '{' + downcase_first_letter ( 'OutFolder' ) + '}' , request . out_folder . to_s ) else query_params [ downcase_first_letter ( 'OutFolder' ) ] = request . out_folder unless request . out_folder . nil? end header_params = { } header_params [ 'Accept' ] = @api_client . select_header_accept ( [ 'application/json' , 'application/xml' ] ) header_params [ 'Content-Type' ] = @api_client . select_header_content_type ( [ 'application/json' , 'application/xml' ] ) form_params = { } post_body = @api_client . object_to_http_body ( request . request ) data , status_code , headers = @api_client . call_api ( :PUT , local_var_path , header_params : header_params , query_params : query_params , form_params : form_params , body : post_body , access_token : get_access_token , return_type : 'Array<Link>' ) if @api_client . config . debugging @api_client . config . logger . debug "API called: ChangesApi#put_changes_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [ data , status_code , headers ] end
Applies changes to the document and returns images of document with the result of comparison
24,334
def read_definitions ( definition , content_type = nil ) @appliance_parser . load_schemas if File . exists? ( definition ) definition_file_extension = File . extname ( definition ) appliance_config = case definition_file_extension when '.appl' , '.yml' , '.yaml' @appliance_parser . parse_definition ( definition ) else unless content_type . nil? case content_type when 'application/x-yaml' , 'text/yaml' @appliance_parser . parse_definition ( definition ) end end end return if appliance_config . nil? @appliance_configs << appliance_config appliances = [ ] @appliance_configs . each { | config | appliances << config . name } appliance_config . appliances . reverse . each do | appliance_name | read_definitions ( "#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}" ) unless appliances . include? ( appliance_name ) end unless appliance_config . appliances . nil? or ! appliance_config . appliances . is_a? ( Array ) else @appliance_configs << @appliance_parser . parse_definition ( definition , false ) end end
Reads definition provided as string . This string can be a YAML document . In this case definition is parsed and an ApplianceConfig object is returned . In other cases it tries to search for a file with provided name .
24,335
def call ( env ) configuration = configuration ( env ) warden = env [ 'warden' ] if interactive? ( env ) warden . authenticate ( configuration . ui_mode ) else warden . authenticate ( * configuration . api_modes ) end env [ 'aker.check' ] = Facade . new ( configuration , warden . user ) @app . call ( env ) end
Authenticates incoming requests using Warden .
24,336
def locale_from_url path_info = nil @locale_set ||= begin @locale ||= ( match = ( path_info || @env [ 'PATH_INFO' ] ) . match ( locale_pattern ) ) ? match [ 1 ] : nil @env [ 'PATH_INFO' ] = match [ 2 ] if match && @env . try ( :fetch , 'PATH_INFO' ) true end @locale end
Determine locale from the request URL and return it as a string it it is matching any of provided locales If locale matching failed an empty String will be returned .
24,337
def method_missing ( meth , * args , & blk ) value = select { | k , v | k . underscore == meth . to_s } . first if ! value super elsif value . last . is_a? ( Hash ) self . class [ value . last ] else value . last end end
Provides access to price items and groups using magic methods and chaining .
24,338
def get ( path , params = nil , headers = { } ) response = http_client . get ( request_uri ( path ) , params , request_headers ( headers ) ) if response . status == 200 parse_response ( response ) else handle_error_response ( response ) end end
Initialize api client
24,339
def match ( tokens , definitions ) token_index = 0 @pattern . each do | element | name = element . to_s optional = name [ - 1 , 1 ] == '?' name = name . chop if optional case element when Symbol if tags_match? ( name , tokens , token_index ) token_index += 1 next else if optional next else return false end end when String return true if optional && token_index == tokens . size if definitions . key? ( name . to_sym ) sub_handlers = definitions [ name . to_sym ] else raise ChronicPain , "Invalid subset #{name} specified" end sub_handlers . each do | sub_handler | return true if sub_handler . match ( tokens [ token_index .. tokens . size ] , definitions ) end else raise ChronicPain , "Invalid match type: #{element.class}" end end return false if token_index != tokens . size return true end
pattern - An Array of patterns to match tokens against . handler_method - A Symbole representing the method to be invoked when patterns are matched . tokens - An Array of tokens to process . definitions - A Hash of definitions to check against .
24,340
def add_listener ( type , once = false , & callback ) listener = Listener . new ( type , callback , once ) listeners [ type ] ||= [ ] listeners [ type ] << listener emit ( :new_listener , self , type , once , callback ) listener end
Register the given block to be called when the events of type + type + will be emitted . if + once + the block will be called once
24,341
def remove_listener ( listener ) type = listener . type if listeners . has_key? type listeners [ type ] . delete ( listener ) listeners . delete ( type ) if listeners [ type ] . empty? end end
Unregister the given block . It won t be call then went an event is emitted .
24,342
def emit ( type , sender = nil , * args ) listeners [ type ] . each { | l | l . fire ( sender , * args ) } if listeners . has_key? type end
Emit an event of type + type + and call all the registered listeners to this event . The + sender + param will help the listener to identify who is emitting the event . You can pass then every additional arguments you ll need
24,343
def changes_feed_uri query = { 'feed' => 'continuous' , 'heartbeat' => '10000' } customize_query ( query ) uri = ( @db . respond_to? ( :uri ) ? @db . uri : URI ( @db ) ) . dup uri . path += '/_changes' uri . query = build_query ( query ) uri end
Checks services . If all services pass muster enters a read loop .
24,344
def waiter_for ( id ) @waiting [ id ] = true Waiter . new do loop do break true if ! @waiting [ id ] sleep 0.1 end end end
Returns an object that can be used to block a thread until a document with the given ID has been processed .
24,345
def reload Dir . glob ( '**/*.rb' ) . each { | file | Reloader . reload_file ( file ) } self . last_run_passed = true self . rerun_specs = [ ] end
Gets called when the Guard should reload itself .
24,346
def reset_counters ( id , * counters ) object = find ( id ) counters . each do | association | has_many_association = reflect_on_association ( association . to_sym ) if has_many_association . options [ :as ] has_many_association . options [ :as ] . to_s . classify else self . name end if has_many_association . is_a? ActiveRecord :: Reflection :: ThroughReflection has_many_association = has_many_association . through_reflection end foreign_key = has_many_association . foreign_key . to_s child_class = has_many_association . klass belongs_to = child_class . reflect_on_all_associations ( :belongs_to ) reflection = belongs_to . find { | e | e . foreign_key . to_s == foreign_key && e . options [ :counter_cache ] . present? } counter_name = reflection . counter_cache_column stmt = unscoped . where ( arel_table [ primary_key ] . eq ( object . id ) ) . arel . compile_update ( { arel_table [ counter_name ] => object . send ( association ) . count } ) connection . update stmt end return true end
Resets one or more counter caches to their correct value using an SQL count query . This is useful when adding new counter caches or if the counter has been corrupted or modified directly by SQL .
24,347
def build_search_query string = params [ :search ] . split ' ' redeem_codes = DealRedemptions :: RedeemCode . arel_table companies = DealRedemptions :: Company . arel_table query = redeem_codes . project ( redeem_codes [ :id ] , redeem_codes [ :company_id ] , redeem_codes [ :code ] , redeem_codes [ :status ] , redeem_codes [ :created_at ] ) . join ( companies ) . on ( redeem_codes [ :company_id ] . eq ( companies [ :id ] ) ) string . each do | s | query . where ( redeem_codes [ :code ] . matches ( "%#{s}%" ) ) end query . to_sql end
Search redemption codes
24,348
def create ( path ) self . destination_root = path copy_file ( ".gitignore" ) copy_file ( "config.ru" ) copy_file ( "Gemfile" ) copy_file ( "Procfile" ) copy_file ( "README.md" ) copy_content copy_themes end
Creates a new Mango application at the specified path
24,349
def details data = servers_client . get ( server_path , json_headers ) . body JSON . parse ( data ) [ 'server' ] end
A Hash of various matadata about the server
24,350
def add ( name ) response = JSON . parse ( CrateAPI :: Base . call ( "#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}" , :post , { :body => { :name => name } } ) ) raise CrateLimitReachedError , response [ "message" ] unless response [ "status" ] != "failure" end
Add a new crate .
24,351
def authenticate email , credentials = { } if password = credentials [ :with_password ] refresh_token email : email , password : password elsif secret = credentials [ :with_api_secret ] api_key = OpenSSL :: Digest :: SHA256 . new ( "#{email}:#{secret}:#{token.token}" ) . to_s refresh_token email : email , api_key : api_key else raise ArgumentError , "Must provide either `with_password` or `with_api_secret` arguments." end end
Create an new Client object .
24,352
def pricing width , height , pcb_layers , quantity = nil post_request "pricing" , { width_in_mils : width , height_in_mils : height , pcb_layers : pcb_layers , quantity : quantity } end
Request a price estimate
24,353
def add_order_item id , project_id , quantity post_request "orders/#{id}/add_item" , { order : { project_id : project_id , quantity : quantity } } end
Add a Project to an Order
24,354
def sign ( string , secret , algorithm = nil ) plain = :: Base64 . decode64 ( secret . gsub ( / \. / , '' ) ) if algorithm . nil? paramMap = :: CGI . parse string if ! paramMap . has_key? ( "algorithm" ) raise ArgumentError , "missing algorithm" end algorithm = paramMap [ "algorithm" ] . first . gsub ( / /i , '' ) end hmac = :: OpenSSL :: HMAC . digest ( algorithm , plain , string ) Base64 :: encode64 ( hmac ) . gsub ( / \n / , '' ) end
Sign a string with a secret
24,355
def authenticate ( authorization_header , client_secret ) if ! authorization_header . match ( / / ) raise ArgumentError , "Jive authorization header is not properly formatted, must start with JiveEXTN" end paramMap = :: CGI . parse authorization_header . gsub ( / \s / , '' ) if ! paramMap . has_key? ( "algorithm" ) || ! paramMap . has_key? ( "client_id" ) || ! paramMap . has_key? ( "jive_url" ) || ! paramMap . has_key? ( "tenant_id" ) || ! paramMap . has_key? ( "timestamp" ) || ! paramMap . has_key? ( "signature" ) raise ArgumentError , "Jive authorization header is partial" end timestamp = Time . at ( paramMap [ "timestamp" ] . first . to_i / 1000 ) secondsPassed = Time . now - timestamp if secondsPassed < 0 || secondsPassed > ( 5 * 60 ) raise ArgumentError , "Jive authorization is rejected since it's #{ secondsPassed } seconds old (max. allowed is 5 minutes)" end self . sign ( authorization_header . gsub ( / \s / , '' ) . gsub ( / \& / , '' ) , client_secret ) === paramMap [ "signature" ] . first end
Authenticate an authorization header
24,356
def validate_registration ( validationBlock , * args ) options = ( ( args . last . is_a? ( Hash ) ) ? args . pop : { } ) require "open-uri" require "net/http" require "openssl" jive_signature_url = validationBlock [ :jiveSignatureURL ] jive_signature = validationBlock [ :jiveSignature ] validationBlock . delete ( :jiveSignature ) if ! validationBlock [ :clientSecret ] . nil? validationBlock [ :clientSecret ] = Digest :: SHA256 . hexdigest ( validationBlock [ :clientSecret ] ) end uri = URI . parse ( jive_signature_url ) http = Net :: HTTP . new ( uri . host , uri . port ) http . use_ssl = true http . verify_mode = OpenSSL :: SSL :: VERIFY_NONE if http . use_ssl? && ! options [ :verify_ssl ] buffer = '' validationBlock = validationBlock . sort ( validationBlock . respond_to? ( :to_h ) ? validationBlock . to_h : Hash [ validationBlock ] ) . each_pair { | k , v | buffer = "#{buffer}#{k}:#{v}\n" } request = Net :: HTTP :: Post . new ( uri . request_uri ) request . body = buffer request [ "X-Jive-MAC" ] = jive_signature request [ "Content-Type" ] = "application/json" response = http . request ( request ) ( response . code . to_i === 204 ) end
Validates an app registration
24,357
def load_api_keys fallback = load_file ( credentials_path ) if File . exists? ( credentials_path ) @api_keys = Gem :: Keychain :: ApiKeys . new ( fallback : fallback ) end
Override api key methods with proxy object
24,358
def generate_grid_css css = ERB :: new ( File . path_to_string ( CustomLayout :: CSS_ERB_FILE ) ) css . result ( binding ) end
Loads grid . css . erb file binds it to current instance and returns output
24,359
def info_pair ( label , value ) value = content_tag ( :span , "None" , :class => "blank" ) if value . blank? label = content_tag ( :span , "#{label}:" , :class => "label" ) content_tag ( :span , [ label , value ] . join ( " " ) , :class => "info_pair" ) end
Output an easily styleable key - value pair
24,360
def generate_table ( collection , headers = nil , options = { } ) return if collection . blank? thead = content_tag ( :thead ) do content_tag ( :tr ) do headers . map { | header | content_tag ( :th , header ) } end end unless headers . nil? tbody = content_tag ( :tbody ) do collection . map do | values | content_tag ( :tr ) do values . map { | value | content_tag ( :td , value ) } end end end content_tag ( :table , [ thead , tbody ] . compact . join ( "\n" ) , options ) end
Build an HTML table For collection pass an array of arrays For headers pass an array of label strings for the top of the table All other options will be passed along to the table content_tag
24,361
def options_td ( record_or_name_or_array , hide_destroy = false ) items = [ ] items << link_to ( 'Edit' , edit_polymorphic_path ( record_or_name_or_array ) ) items << link_to ( 'Delete' , polymorphic_path ( record_or_name_or_array ) , :confirm => 'Are you sure?' , :method => :delete , :class => "destructive" ) unless hide_destroy list = content_tag ( :ul , convert_to_list_items ( items ) ) content_tag ( :td , list , :class => "options" ) end
Pass in an ActiveRecord object get back edit and delete links inside a TD tag
24,362
def link ( name , options = { } , html_options = { } ) link_to_unless_current ( name , options , html_options ) do html_options [ :class ] = ( html_options [ :class ] || "" ) . split ( " " ) . push ( "active" ) . join ( " " ) link_to ( name , options , html_options ) end end
This works just like link_to but with one difference .. If the link is to the current page a class of active is added
24,363
def list_model_columns ( obj ) items = obj . class . columns . map { | col | info_pair ( col . name , obj [ col . name ] ) } content_tag ( :ul , convert_to_list_items ( items ) , :class => "model_columns" ) end
Generate a list of column name - value pairs for an AR object
24,364
def ddl_transaction ( & block ) if Base . connection . supports_ddl_transactions? Base . transaction { block . call } else block . call end end
Wrap the migration in a transaction only if supported by the adapter .
24,365
def add_vertical ( str , value ) node = nil str . each_char { | c | if ( node == nil ) node = self . add_horizontal_char ( c ) elsif ( node . down != nil ) node = node . down . add_horizontal_char ( c ) else node . down = Node . new ( c , node ) node = node . down end } node . value = value end
Add the given String str and value vertically to this node by adding or finding each character horizontally then stepping down and repeating with the next character and so on writing the value to the last node .
24,366
def find_vertical ( str , offset = 0 , length = str . length - offset ) node = nil i = offset while ( i < offset + length ) c = str [ i ] if ( node == nil ) node = self . find_horizontal ( c ) elsif ( node . down != nil ) node = node . down . find_horizontal ( c ) else return nil end return nil if ( node == nil ) i += 1 end node end
Find the given String str vertically by finding each character horizontally then stepping down and repeating with the next character and so on . Return the last node if found or nil if any horizontal search fails . Optionally set the offset into the string and its length
24,367
def balance node = self i = ( node . count ( :right ) - node . count ( :left ) ) / 2 while ( i! = 0 ) if ( i > 0 ) mvnode = node . right node . right = nil mvnode . add_horizontal node i -= 1 else mvnode = node . left node . left = nil mvnode . add_horizontal node i += 1 end node = mvnode end if ( node . left != nil ) node . left = node . left . balance end if ( node . right != nil ) node . right = node . right . balance end if ( node . down != nil ) node . down = node . down . balance end node end
Recursively balance this node in its own tree and every node in all four directions and return the new root node .
24,368
def walk ( str = "" , & block ) @down . walk ( str + char , & block ) if @down != nil @left . walk ( str , & block ) if @left != nil yield str + @char , @value if @value != nil @right . walk ( str , & block ) if @right != nil end
Walk the tree from this node yielding all strings and values where the value is not nil . Optionally use the given prefix String str .
24,369
def to_s st = @char node = self while node != nil node = node . up break if node == nil st = node . char + st end st end
Return the complete string from the tree root up to and including this node i . e . The total string key for this node from root .
24,370
def all_partials ( str = "" ) list = [ ] @down . walk ( str ) { | str | list << str } unless @down . nil? list end
Return an Array of Strings of all possible partial string from this node . Optionally use the given prefix String str .
24,371
def prune return true if ! @down . nil? && down . prune return true if ! @left . nil? && left . prune return true if ! @right . nil? && right . prune return true unless @value . nil? up . down = nil if ! up . nil? && left . nil? && right . nil? false end
Prune the tree back from this node onward so that all leaves have values .
24,372
def index authorize! :manage , Humpyard :: Page @root_page = Humpyard :: Page . root @page = Humpyard :: Page . find_by_id ( params [ :actual_page_id ] ) unless @page . nil? @page = @page . content_data end render :partial => 'index' end
Probably unneccassary - may be removed later
24,373
def new @page = Humpyard :: config . page_types [ params [ :type ] ] . new unless can? :create , @page . page render :json => { :status => :failed } , :status => 403 return end @page_type = params [ :type ] @prev = Humpyard :: Page . find_by_id ( params [ :prev_id ] ) @next = Humpyard :: Page . find_by_id ( params [ :next_id ] ) render :partial => 'edit' end
Dialog content for a new page
24,374
def update @page = Humpyard :: Page . find ( params [ :id ] ) . content_data if @page unless can? :update , @page . page render :json => { :status => :failed } , :status => 403 return end if @page . update_attributes params [ :page ] @page . title_for_url = @page . page . suggested_title_for_url @page . save render :json => { :status => :ok , :replace => [ { :element => "hy-page-treeview-text-#{@page.id}" , :content => @page . title } ] , :flash => { :level => 'info' , :content => I18n . t ( 'humpyard_form.flashes.update_success' , :model => Humpyard :: Page . model_name . human ) } } else render :json => { :status => :failed , :errors => @page . errors , :flash => { :level => 'error' , :content => I18n . t ( 'humpyard_form.flashes.update_fail' , :model => Humpyard :: Page . model_name . human ) } } end else render :json => { :status => :failed } , :status => 404 end end
Update an existing page
24,375
def move @page = Humpyard :: Page . find ( params [ :id ] ) if @page unless can? :update , @page render :json => { :status => :failed } , :status => 403 return end parent = Humpyard :: Page . find_by_id ( params [ :parent_id ] ) @page . update_attribute :parent , parent @prev = Humpyard :: Page . find_by_id ( params [ :prev_id ] ) @next = Humpyard :: Page . find_by_id ( params [ :next_id ] ) do_move ( @page , @prev , @next ) replace_options = { :element => "hy-page-treeview" , :content => render_to_string ( :partial => "tree.html" , :locals => { :page => @page } ) } render :json => { :status => :ok , :replace => [ replace_options ] } else render :json => { :status => :failed } , :status => 404 end end
Move a page
24,376
def show @page = nil if params [ :locale ] and Humpyard . config . locales . include? params [ :locale ] . to_sym I18n . locale = params [ :locale ] elsif session [ :humpyard_locale ] I18n . locale = session [ :humpyard_locale ] else I18n . locale = Humpyard . config . locales . first end if not params [ :webpath ] . blank? dyn_page_path = false parent_page = nil params [ :webpath ] . split ( '/' ) . each do | path_part | unless ( path_part . blank? ) if ( dyn_page_path ) dyn_page_path << path_part else @page = Page . with_translated_attribute ( :title_for_url , CGI :: escape ( path_part ) , I18n . locale ) . first raise :: ActionController :: RoutingError , "No route matches \"#{request.path}\" (X4201) [#{path_part}]" if @page . nil? raise :: ActionController :: RoutingError , "No route matches \"#{request.path}\" (X4202)" if not ( @page . parent == parent_page or @page . parent == Humpyard :: Page . root_page ) parent_page = @page unless @page . is_root_page? dyn_page_path = [ ] if @page . content_data . is_humpyard_dynamic_page? end end end if @page . content_data . is_humpyard_dynamic_page? and dyn_page_path . size > 0 @sub_page = @page . parse_path ( dyn_page_path ) raise :: ActionController :: RoutingError , "No route matches \"#{request.path}\" (D4201)" if @sub_page . blank? @page_partial = "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/#{@sub_page[:partial]}" if @sub_page [ :partial ] @local_vars = { :page => @page } . merge ( @sub_page [ :locals ] ) if @sub_page [ :locals ] and @sub_page [ :locals ] . class == Hash if request . xhr? respond_to do | format | format . html { render :partial => @page_partial , :locals => @local_vars } end return end end elsif not params [ :id ] . blank? @page = Page . find ( params [ :id ] ) else @page = Page . root_page :force_reload => true unless @page @page = Page . new render '/humpyard/pages/welcome' return false end end raise :: ActionController :: RoutingError , "No route matches \"#{request.path}\"" if @page . nil? or @page . content_data . is_humpyard_virtual_page? response . headers [ 'X-Humpyard-Page' ] = "#{@page.id}" response . headers [ 'X-Humpyard-Modified' ] = "#{@page.last_modified}" response . headers [ 'X-Humpyard-ServerTime' ] = "#{Time.now.utc}" @page_partial ||= "/humpyard/pages/#{@page.content_data_type.split('::').last.underscore.pluralize}/show" @local_vars ||= { :page => @page } self . class . layout ( @page . template_name ) if Rails . application . config . action_controller . perform_caching and not @page . always_refresh fresh_when :etag => "#{humpyard_user.nil? ? '' : humpyard_user}p#{@page.id}m#{@page.last_modified}" , :last_modified => @page . last_modified ( :include_pages => true ) , :public => @humpyard_user . nil? end end
Render a given page
24,377
def sitemap require 'builder' xml = :: Builder :: XmlMarkup . new :indent => 2 xml . instruct! xml . tag! :urlset , { 'xmlns' => "http://www.sitemaps.org/schemas/sitemap/0.9" , 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance" , 'xsi:schemaLocation' => "http://www.sitemaps.org/schemas/sitemap/0.9\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" } do base_url = "#{request.protocol}#{request.host}#{request.port==80 ? '' : ":#{request.port}"}" if root_page = Page . root_page Humpyard . config . locales . each do | locale | add_to_sitemap xml , base_url , locale , [ { :index => true , :url => root_page . human_url ( :locale => locale ) , :lastmod => root_page . last_modified , :children => [ ] } ] + root_page . child_pages ( :single_root => true ) . map { | p | p . content_data . site_map ( locale ) } end end end render :xml => xml . target! end
Render the sitemap . xml for robots
24,378
def update_child_visibility return if meta_visible == meta_visible_was post_fields . map { | pf | pf . update ( meta_visible : meta_visible ) } end
This functions update all post fields child visibility with the current post field visibility .
24,379
def vote ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } if args . length == 2 options . merge! ( :vote => args [ 0 ] ) options . merge! ( :post => args [ 1 ] ) response = post ( 'posts/vote' , options ) else puts "#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]), posts ID" end end
Register a vote for a post .
24,380
def action_options return @action_options unless @monitor_class . outputs . length > 0 action_options = @action_options . clone @monitor_class . outputs . each do | output , _type | action_options . each do | option_key , option_value | action_options [ option_key ] = option_value . gsub ( "{{#{output}}}" , @monitor . send ( output ) . to_s ) end end action_options end
Accepts the path of the YAML file to be parsed into commands - will throw a CommandException should it have invalid parameters
24,381
def remove keys keys = keys . map ( & :to_sym ) @options . reject! { | k , v | keys . include? ( k ) } end
Remove an option .
24,382
def to_hash config = load_base_config config = config . deep_merge ( load_env_config ) config . deep_merge ( load_jvm_config ) end
Returns the Ambience config as a Hash .
24,383
def hash_from_property ( property , value ) property . split ( "." ) . reverse . inject ( value ) { | value , item | { item => value } } end
Returns a Hash generated from a JVM + property + and its + value + .
24,384
def precompute_old warn "This method should not be used, please use precompute instead." word_list . rewind . each do | line | word = line . chomp precomputed_list_old [ word . split ( '' ) . sort . join . freeze ] += [ word ] end end
Initializes word_list instance variable precomputed_list assigning it a hash whose default values is an empty array .
24,385
def initialize_project_from_yaml ( project_name = nil ) return unless ( project_name && File . exist? ( @settings_file ) ) projects = YAML :: load ( File . path_to_string ( @settings_file ) ) if ( project = projects [ project_name ] ) self . namespace = project [ 'namespace' ] || "" self . destination_path = ( self . destination_path == Blueprint :: BLUEPRINT_ROOT_PATH ? project [ 'path' ] : self . destination_path ) || Blueprint :: BLUEPRINT_ROOT_PATH self . custom_css = project [ 'custom_css' ] || { } self . semantic_classes = project [ 'semantic_classes' ] || { } self . plugins = project [ 'plugins' ] || [ ] if ( layout = project [ 'custom_layout' ] ) self . custom_layout = CustomLayout . new ( :column_count => layout [ 'column_count' ] , :column_width => layout [ 'column_width' ] , :gutter_width => layout [ 'gutter_width' ] , :input_padding => layout [ 'input_padding' ] , :input_border => layout [ 'input_border' ] ) end @loaded_from_settings = true end end
attempts to load output settings from settings . yml
24,386
def execute ( command , & block ) logger . info "Executing command '#{command}'" reset pid , stdin , stdout_stream , stderr_stream = Open4 :: popen4 ( command ) @pid = pid stdin . close rescue nil save_exit_status ( pid ) forward_signals_to ( pid ) do handle_streams stdout_stream , stderr_stream , & block end self ensure logger . debug "Closing stdout and stderr streams for process" stdout . close rescue nil stderr . close rescue nil end
Initializes an Executer instance with particular options
24,387
def forward_signals_to ( pid , signals = %w[ INT ] ) logger . debug "Setting up signal handlers for #{signals.inspect}" signal_count = 0 signals . each do | signal | Signal . trap ( signal ) do Process . kill signal , pid rescue nil reset_handlers_for signals if + + signal_count >= 2 end end yield ensure reset_handlers_for signals end
Forward signals to a process while running the given block
24,388
def reset_handlers_for ( signals ) logger . debug "Resetting signal handlers for #{signals.inspect}" signals . each { | signal | Signal . trap signal , "DEFAULT" } end
Resets the handlers for particular signals to the default
24,389
def handle_streams ( stdout_stream , stderr_stream , & block ) logger . debug "Monitoring stdout/stderr streams for output" streams = [ stdout_stream , stderr_stream ] until streams . empty? selected , = select ( streams , nil , nil , 0.1 ) next if selected . nil? or selected . empty? selected . each do | stream | if stream . eof? logger . debug "Stream reached end-of-file" if @success . nil? logger . debug "Process hasn't finished, keeping stream" else logger . debug "Removing stream" streams . delete ( stream ) end next end while data = @reader . call ( stream ) data = ( ( @options [ :mode ] == :chars ) ? data . chr : data ) stream_name = ( stream == stdout_stream ) ? :stdout : :stderr output data , stream_name , & block unless block . nil? buffer data , stream_name unless @options [ :no_buffer ] end end end end
Manages reading from the stdout and stderr streams
24,390
def output ( data , stream_name = :stdout , & block ) if block . arity == 2 args = [ nil , nil ] if stream_name == :stdout args [ 0 ] = data else args [ 1 ] = data end block . call ( * args ) else yield data if stream_name == :stdout end end
Outputs data to the block
24,391
def execute @thread = Thread . new do if Thread . current != Thread . main loop do @datasource . monitor . on_trigger do @datasource . action . activate ( @datasource . action_options ) end end end end end
Create a new command object from a data source
24,392
def response_of_uri ( uri ) begin Net :: HTTP . start ( uri . host , uri . port ) do | http | http . head ( uri . path . size > 0 ? uri . path : "/" ) . code end rescue Exception => e "Error" end end
Checks whether the uri is reachable . If so it returns 200 otherwise Error . uri has to have a host that is uri . host should not be nil
24,393
def register sock , events = XS :: POLLIN | XS :: POLLOUT , fd = 0 return false if ( sock . nil? && fd . zero? ) || events . zero? item = @items . get ( @sockets . index ( sock ) ) unless item @sockets << sock item = LibXS :: PollItem . new if sock . kind_of? ( XS :: Socket ) || sock . kind_of? ( Socket ) item [ :socket ] = sock . socket item [ :fd ] = 0 else item [ :socket ] = FFI :: MemoryPointer . new ( 0 ) item [ :fd ] = fd end @raw_to_socket [ item . socket . address ] = sock @items << item end item [ :events ] |= events end
Register the + sock + for + events + . This method is idempotent meaning it can be called multiple times with the same data and the socket will only get registered at most once . Calling multiple times with different values for + events + will OR the event information together .
24,394
def deregister sock , events , fd = 0 return unless sock || ! fd . zero? item = @items . get ( @sockets . index ( sock ) ) if item && ( item [ :events ] & events ) > 0 item [ :events ] ^= events delete sock if item [ :events ] . zero? true else false end end
Deregister the + sock + for + events + . When there are no events left this also deletes the socket from the poll items .
24,395
def delete sock unless ( size = @sockets . size ) . zero? @sockets . delete_if { | socket | socket . socket . address == sock . socket . address } socket_deleted = size != @sockets . size item_deleted = @items . delete sock raw_deleted = @raw_to_socket . delete ( sock . socket . address ) socket_deleted && item_deleted && raw_deleted else false end end
Deletes the + sock + for all subscribed events . Called internally when a socket has been deregistered and has no more events registered anywhere .
24,396
def update_selectables @readables . clear @writables . clear @items . each do | poll_item | if poll_item . readable? @readables << ( poll_item . socket . address . zero? ? poll_item . fd : @raw_to_socket [ poll_item . socket . address ] ) end if poll_item . writable? @writables << ( poll_item . socket . address . zero? ? poll_item . fd : @raw_to_socket [ poll_item . socket . address ] ) end end end
Update readables and writeables
24,397
def authorize ( auth = { } ) @authentication ||= TaskMapper :: Authenticator . new ( auth ) auth = @authentication if ( auth . username . nil? || auth . url . nil? || auth . password . nil? ) raise "Please provide username, password and url" end url = auth . url . gsub ( / \/ / , '' ) unless url . split ( '/' ) . last == 'xmlrpc.cgi' auth . url = url + '/xmlrpc.cgi' end @bugzilla = Rubyzilla :: Bugzilla . new ( auth . url ) begin @bugzilla . login ( auth . username , auth . password ) rescue warn 'Authentication was invalid' end end
declare needed overloaded methods here
24,398
def file ( options = { } ) options [ :file_name ] ||= 'pass.mswallet' temp_file = Tempfile . new ( options [ :file_name ] ) temp_file . write self . stream . string temp_file . close temp_file end
Return a Tempfile containing our ZipStream
24,399
def request ( message , ** options ) send message , options if block_given? yield receive options else receive options end end
Creates a new Client socket .