idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
14,800 | def run_executable ( exec , options ) script_href = "right_script_href=" + exec . href params = options . collect { | k , v | "&inputs[][name]=#{k}&inputs[][value]=#{v}" unless k == :ignore_lock } . join ( '&' ) if options [ :ignore_lock ] params += "&ignore_lock=true" end Log . debug "[#{Chimp.get_job_uuid}] Running e... | In order to run the task we need to call run_executable on ourselves |
14,801 | def main program_desc 'Read values from the Grin PhaseRunner Controller primarily for logging' version Phaserunner :: VERSION subcommand_option_handling :normal arguments :strict sort_help :manually desc 'Serial (USB) device' default_value '/dev/ttyUSB0' arg 'tty' flag [ :t , :tty ] desc 'Serial port baudrate' default_... | Does all the CLI work |
14,802 | def handle_delete_propagation if replicable . tracking_deleted && has_deleted_ids? RailsRedshiftReplicator . logger . info propagation_message ( :propagating_deletes ) delete_on_target ? purge_deleted : RailsRedshiftReplicator . logger . error ( propagation_message ( :delete_propagation_error ) ) end end | Deletes records flagged for deletion on target and then delete the queue from source |
14,803 | def process_list_page ( page ) @logger . info ( "Processing list page with URL: #{page.uri}" ) new_items_found = nil items = page . links items_len = items . length - 1 @total = @total + items_len items . each do | anchor | next if anchor . text == '../' new_items_found = false if new_items_found . nil? pid = anchor . ... | NOTUSED by islam |
14,804 | def deliver ( event ) info do recipients = Array ( event . payload [ :to ] ) . join ( ', ' ) "\nSent SMS to #{recipients} (#{event.duration.round(1)}ms)" end debug { event . payload [ :sms ] } end | An SMS was delivered . |
14,805 | def to_hash hash = { } hash [ "attrs" ] = @attrs self . instance_variables . keep_if { | key | key != :@attrs } . each do | var | val = self . instance_variable_get ( var ) hash [ "attrs" ] [ var . to_s . delete ( "@" ) . to_sym ] = val . to_hash if val . is_a? ACTV :: Base end hash [ "attrs" ] end | Creation of object hash when sending request to soap |
14,806 | def check ( path_prefix , key_path , predicate = nil ) value = query ( key_path , path_prefix ) return true if ! value . nil? && predicate . nil? case predicate when :: String , :: Regexp , :: Integer , :: Float , :: DateTime , true , false return predicate === value when :: Proc return predicate . call ( value ) when ... | Checks that the the condition is met . This means the attribute identified by path_prefix and key_path satisfies the optional predicate which when nil simply checks for existence . |
14,807 | def describe ( shallow = true , example : nil ) description = { } TOP_LEVEL_OPTIONS . each do | option_name | description [ option_name ] = options [ option_name ] if options . key? option_name end if ( ex_def = description . delete ( :example ) ) description [ :example_definition ] = ex_def end special_options = optio... | Options we don t want to expose when describing attributes |
14,808 | def validate ( object , context = Attributor :: DEFAULT_ROOT_CONTEXT ) raise "INVALID CONTEXT!! #{context}" unless context if object . nil? return validate_missing_value ( context ) end errors = validate_type ( object , context ) return errors if errors . any? if options [ :values ] && ! options [ :values ] . include? ... | Validates stuff and checks dependencies |
14,809 | def sort_pipe ( object , sort ) sort_lambda = lambda { } if object [ 0 ] . is_a? ( Hash ) if sort . to_s [ / \d / ] sort = sort . to_i elsif object [ 0 ] . keys . all? { | e | e . is_a? ( Symbol ) } sort = sort . to_sym end sort_lambda = untouched_sort? ( object . map { | e | e [ sort ] } ) ? lambda { | e | e [ sort ] ... | Sorts an array of objects or hashes using a sort field . Sort is reversed with reverse_sort set to true . |
14,810 | def pipes_pipe ( obj , arr ) arr . inject ( obj ) { | acc , e | Boson . full_invoke ( e , [ acc ] ) } end | Pipes output of multiple commands recursively given initial object |
14,811 | def readline ( options = { } ) suppress_warnings initialize_parms ( options ) MiniTerm . raw { @edit . edit_process } ensure restore_warnings puts end | Read a line from the console with edit and history . |
14,812 | def set_options ( options ) @options = MiniReadline :: BASE_OPTIONS . merge ( instance_options ) . merge ( options ) @options [ :window_width ] = MiniTerm . width - 1 set_prompt ( @options [ :prompt ] ) verify_mask ( @options [ :secret_mask ] ) end | Set up the options |
14,813 | def set_prompt ( prompt ) @options [ :base_prompt ] = Prompt . new ( prompt ) @options [ :scroll_prompt ] = Prompt . new ( @options [ :alt_prompt ] || prompt ) verify_prompt ( @options [ :base_prompt ] ) verify_prompt ( @options [ :scroll_prompt ] ) end | Set up the prompt . |
14,814 | def hd_picker_tag ( field_name , value = nil , cls = "datepicker" , opts = { } , locale_format = nil ) draw_ext_input_tag ( field_name , value , cls , locale_format , opts ) end | for when there s no rails form object and you really just need inputs |
14,815 | def distance_from ( lat , long ) dLat = self . degrees_to_radians ( lat - self . latitude ) dLon = self . degrees_to_radians ( long - self . longitude ) lat1 = self . degrees_to_radians ( lat ) lat2 = self . degrees_to_radians ( self . latitude ) a = Math . sin ( dLat / 2 ) * Math . sin ( dLat / 2 ) + Math . sin ( dLon... | Returns the distance this object is from the given latitude and longitude . Distance is as the crow flies . |
14,816 | def method_missing ( sym , * args , & block ) if self . internal_object . key? ( sym . to_s ) return self . internal_object [ sym . to_s ] end super end | Allow hash keys to be used as methods |
14,817 | def reports_to_flush suffix = suffix_for_unique_naming report_keys = report_keys_to_flush ( suffix ) if report_keys . empty? logger . warn "No reports available to flush" report_keys else reports ( report_keys , suffix ) end end | This performs a cleanup of the reports to be flushed . We can decide later whether it is better to leave this responsibility to the caller of the method . |
14,818 | def join_name ( parts , separator : ObjectInspector . configuration . name_separator ) the_parts = Array ( parts ) . tap ( & :compact! ) the_parts . join ( separator ) if the_parts . any? end | Join the passed - in name parts with the passed in separator . |
14,819 | def join_flags ( flags , separator : ObjectInspector . configuration . flags_separator ) the_flags = Array ( flags ) . tap ( & :compact! ) the_flags . join ( separator ) if the_flags . any? end | Join the passed - in flags with the passed in separator . |
14,820 | def join_issues ( issues , separator : ObjectInspector . configuration . issues_separator ) the_issues = Array ( issues ) . tap ( & :compact! ) the_issues . join ( separator ) if the_issues . any? end | Join the passed - in issues with the passed in separator . |
14,821 | def join_info ( items , separator : ObjectInspector . configuration . info_separator ) the_items = Array ( items ) . tap ( & :compact! ) the_items . join ( separator ) if the_items . any? end | Join the passed - in items with the passed in separator . |
14,822 | def execute_with_locale ( locale = :: I18n . locale , & block ) actual_locale = :: I18n . locale :: I18n . locale = locale block . call :: I18n . locale = actual_locale end | Auxiliar function to execute a block with other locale set |
14,823 | def maintenance_window return nil if maintenance_weekday . nil? weekday = Date :: DAYNAMES [ maintenance_weekday ] sprintf ( "%s %02d:00 UTC" , weekday , maintenance_hour ) end | A more humanised version of the maintenance window |
14,824 | def ticker ticker = get ( '/api/1/BTCUSD/ticker' ) Ticker . instance . buy = value_currency ticker [ 'buy' ] Ticker . instance . high = value_currency ticker [ 'high' ] Ticker . instance . price = value_currency ticker [ 'last_all' ] Ticker . instance . low = value_currency ticker [ 'low' ] Ticker . instance . sell = v... | Fetch the latest ticker data |
14,825 | def offers offers = get ( '/api/1/BTCUSD/depth/fetch' ) asks = offers [ 'asks' ] . sort_by { | ask | ask [ 'price_int' ] . to_i } . collect { | ask | Ask . new ( self , ask ) } bids = offers [ 'bids' ] . sort_by { | bid | - bid [ 'price_int' ] . to_i } . collect { | bid | Bid . new ( self , bid ) } { :asks => asks , :b... | Fetch both bids and asks in one call for network efficiency |
14,826 | def trades ( opts = { } ) get ( '/api/1/BTCUSD/trades/fetch' , opts ) . sort_by { | trade | trade [ 'date' ] } . collect do | trade | Trade . new ( trade ) end end | Fetch recent trades |
14,827 | def order! ( type , amount , price ) order = { :type => order_type ( type ) , :amount_int => intify ( amount , :btc ) } order [ :price_int ] = intify ( price , :usd ) if price != :market post ( '/api/1/BTCUSD/order/add' , order ) end | Create a new order |
14,828 | def withdraw! ( amount , address ) if amount >= 1000 fail ( FilthyRichError . new ( "#withdraw! take bitcoin amount as parameter (you are trying to withdraw #{amount} BTC" ) ) else post ( '/api/1/generic/bitcoin/send_simple' , :amount_int => intify ( amount , :btc ) , :address => address ) [ 'trx' ] end end | Transfer bitcoins from your Mt . Gox account into another account |
14,829 | def scientist_process ( object , global_opt , env = { } ) @env = env [ :query , :sort , :reverse_sort ] . each { | e | global_opt . delete ( e ) } unless object . is_a? ( Array ) process_pipes ( object , global_opt ) end | Process pipes for Scientist |
14,830 | def process_pipes ( obj , options ) internal_pipes ( options ) . each { | pipe | obj = Pipes . send ( "#{pipe}_pipe" , obj , options [ pipe ] ) if options [ pipe ] } process_user_pipes ( obj , options ) end | Main method which processes all pipe commands both default and user - defined ones . |
14,831 | def process_user_pipes ( result , global_opt ) pipes_to_process ( global_opt ) . each { | e | args = [ pipe ( e ) [ :pipe ] , result ] args << global_opt [ e ] unless pipe ( e ) [ :type ] == :boolean args << get_env ( e , global_opt ) if pipe ( e ) [ :env ] pipe_result = Boson . invoke ( * args ) result = pipe_result i... | global_opt can come from Hirb callback or Scientist |
14,832 | def errors xsd = Nokogiri :: XML :: Schema ( File . open ( AIXM . schema ( :xsd ) ) ) xsd . validate ( Nokogiri :: XML ( to_xml ) ) . reject do | error | AIXM . config . ignored_errors && error . message . match? ( AIXM . config . ignored_errors ) end end | Validate the generated AIXM or OFMX atainst it s XSD and return the errors found . |
14,833 | def full_invoke ( cmd , args ) command , subcommand = cmd . include? ( NAMESPACE ) ? cmd . split ( NAMESPACE , 2 ) : [ cmd , nil ] dispatcher = subcommand ? Boson . invoke ( command ) : Boson . main_object dispatcher . send ( subcommand || command , * args ) end | Invoke command string even with namespaces |
14,834 | def parse_nodes ( nodes ) output = '' return output if ! nodes || nodes . empty? nodes . each do | node | case node . name when 'h1' , 'h2' , 'h3' , 'h4' , 'h5' , 'h6' level = node . name . match ( / \A \d \Z / ) [ 1 ] . to_i if @options [ :underline_headers ] && level < 3 content = parse_content ( node ) output << con... | Parse the children of a node |
14,835 | def parse_content ( node ) content = if node . children . empty? node . content else parse_nodes ( node . children ) end end | Get the content from a node |
14,836 | def invert build ( precision : precision , deg : ( deg + 180 ) % 360 , suffix : SUFFIX_INVERSIONS . fetch ( suffix , suffix ) ) end | Invert an angle by 180 degrees |
14,837 | def async_authorization_tasks ( reports ) reports . map do | report | task = Concurrent :: Future . new ( executor : thread_pool ) do authorizer . authorizations ( report [ :service_id ] , report [ :credentials ] , report [ :usage ] . keys ) end [ report , task ] end . to_h end | Returns a Hash . The keys are the reports and the values their associated async authorization tasks . |
14,838 | def on ( cls , & block ) @current_screen = @current_page = cls . new waiting_for = "#{cls} to be active" wait_until ( 10 , waiting_for ) { @current_screen . active? } if @current_screen . respond_to? ( :active? ) block . call @current_screen if block @current_screen end | create a new screen given a class name |
14,839 | def markdown ( string , options = { } ) text Prawndown :: Parser . new ( string ) . to_prawn , options . merge ( inline_format : true ) end | Renders Markdown in the current document |
14,840 | def edit_loop while @working @edit_window . sync_window ( edit_buffer , edit_posn ) @edit_window . sync_cursor ( edit_posn ) process_keystroke ( MiniTerm . get_mapped_char ) end edit_buffer end | The line editor processing loop . |
14,841 | def word_right ( _keyboard_args ) if @edit_posn < length right = @edit_buffer [ ( @edit_posn + 1 ) .. - 1 ] @edit_posn = ( posn = right . index ( / \s \S / ) ) ? @edit_posn + posn + 2 : length else MiniTerm . beep end end | A little more to the right please! |
14,842 | def log_view_rendering ( options ) return do_nothing_on_null ( :log_view_rendering ) if null? Utils . require_key ( options , :name ) Utils . require_key ( options , :begin_time ) Utils . require_key ( options , :end_time ) @transaction . log_activity ( next_view_rendering_name , options [ :begin_time ] , options [ :en... | Logs timing information about the rendering of a single view template or partial . |
14,843 | def ComparableVersion ( value ) case value when String , Integer , Float , -> ( val ) { val . respond_to? ( :to_ary ) } ComparableVersion . new ( value ) when -> ( val ) { val . respond_to? ( :to_comparable_version ) } value . to_comparable_version else raise TypeError , "Cannot convert #{value.inspect} to ComparableVe... | Strict conversion method for creating a ComparableVersion object out of anything that can be interpreted is a ComparableVersion . |
14,844 | def archive ( path = nil , configuration_suffix : nil ) path ||= epub_name ( configuration_suffix ) epub_path = File . expand_path ( path ) Dir . chdir ( @file_resolver . destination_path ) do new_paths = @file_resolver . package_files . map ( & :pkg_destination_path ) if :: File . exists? ( epub_path ) Zip :: File . o... | Archives current target files to epub |
14,845 | def epub_name ( configuration_suffix = nil ) epub_name = if ! @book . output_base_name . nil? @book . output_base_name elsif @book . from_file? :: File . basename ( @book . file_path , :: File . extname ( @book . file_path ) ) else @book . title end epub_name += @book . build_version . to_s unless @book . build_version... | Creates name of epub file for current book and current target |
14,846 | def run_all_commits commits = get_commits until commits . empty? do commits . each { | c | run_commit ( c ) } commits = get_commits end end | Repeatedly gets the list of eligable commits and runs TinyCI against them until there are no more remaining |
14,847 | def as_json ( options = nil ) encoder = options && options [ :encoder ] || ActiveSupport :: JSON :: Encoding :: Encoder . new ( options ) map { | v | encoder . as_json ( v ) } end | A couple json serialization methods copied from active_support |
14,848 | def add_asset_to_node ( namespace , type , id , asset_type , asset_id , opts = { } ) data , _status_code , _headers = add_asset_to_node_with_http_info ( namespace , type , id , asset_type , asset_id , opts ) return data end | Add an asset to the node . Body must be empty . Will upsert the asset if it doesn t exist |
14,849 | def delete_asset ( namespace , asset_id , asset_type , opts = { } ) delete_asset_with_http_info ( namespace , asset_id , asset_type , opts ) return nil end | Delete an Asset |
14,850 | def get_asset ( namespace , asset_type , asset_id , opts = { } ) data , _status_code , _headers = get_asset_with_http_info ( namespace , asset_type , asset_id , opts ) return data end | Get details of a given asset |
14,851 | def get_assets_in_node ( namespace , type , id , opts = { } ) data , _status_code , _headers = get_assets_in_node_with_http_info ( namespace , type , id , opts ) return data end | Get for assets in the relevant node |
14,852 | def remove_asset_from_node ( namespace , type , id , asset_type , asset_id , opts = { } ) remove_asset_from_node_with_http_info ( namespace , type , id , asset_type , asset_id , opts ) return nil end | Remove an asset from the relevant node |
14,853 | def compile ( source , destination ) erb = ERB . new ( source . read , nil , '-' ) begin destination . puts erb . result ( data . instance_binding ) rescue SyntaxError => e raise Exceptions :: ErbTemplateHasSyntaxErrors , e . message end end | Create erb generator |
14,854 | def solr_save return true if indexing_disabled? if evaluate_condition ( :if , self ) debug "solr_save: #{self.class.name} : #{record_id(self)}" solr_add to_solr_doc solr_commit if configuration [ :auto_commit ] true else solr_destroy end end | saves to the Solr index |
14,855 | def to_solr_doc debug "to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}" doc = Solr :: Document . new doc . boost = validate_boost ( configuration [ :boost ] ) if configuration [ :boost ] doc << { :id => solr_id , solr_configuration [ :type_field ] => self . class . name , solr_configurat... | convert instance to Solr document |
14,856 | def send_request ( text ) params = { 'text' => text . encode ( "cp1251" ) , } params [ 'xml' ] = @xml if @xml request = Net :: HTTP :: Post . new ( @url . path ) request . set_form_data ( params ) begin response = Net :: HTTP . new ( @url . host , @url . port ) . start do | http | http . request ( request ) end rescue ... | Process text with remote web - service |
14,857 | def acts_as_solr ( options = { } , solr_options = { } , & deferred_solr_configuration ) $solr_indexed_models << self extend ClassMethods include InstanceMethods include CommonMethods include ParserMethods define_solr_configuration_methods acts_as_taggable_on :tags if options [ :taggable ] has_many :dynamic_attributes ,... | declares a class as solr - searchable |
14,858 | def build_linked_resources_map ( data ) data [ "linked" ] . each_with_object ( { } ) do | ( type , resources ) , obj | obj [ type ] ||= { } resources . each do | linked_resource | obj [ type ] [ linked_resource [ "id" ] ] = linked_resource end end end | Builds a map to enable getting references by type and id |
14,859 | def build_link_type_map ( data ) data [ "links" ] . each_with_object ( { } ) do | ( key , value ) , obj | association = key . split ( "." ) . last obj [ association ] = value [ "type" ] . pluralize end end | Builds a map to translate references to types |
14,860 | def build_and_run_task ( task_class , params = nil ) task_run = TaskRun . new ( task_class , params ) @task_run_stack . last . runs << task_run @task_run_stack . push ( task_run ) task = super ( task_class , params ) @task_run_stack . pop task end | track all task runs |
14,861 | def run! begin ensure_path target_path setup_log log_info "Commit: #{@commit}" log_info "Cleaning..." clean log_info "Exporting..." ensure_path export_path export begin load_config rescue ConfigMissingError => e log_error e . message log_error 'Removing export...' clean return false end @builder ||= instantiate_builder... | Constructor allows injection of generic configuration params . |
14,862 | def instantiate_builder klass = TinyCI :: Builders . const_get ( @config [ :builder ] [ :class ] ) klass . new ( @config [ :builder ] [ :config ] . merge ( target : export_path ) , logger : @logger ) end | Instantiate the Builder object according to the class named in the config |
14,863 | def instantiate_hooker return nil unless @config [ :hooker ] . is_a? Hash klass = TinyCI :: Hookers . const_get ( @config [ :hooker ] [ :class ] ) klass . new ( @config [ :hooker ] [ :config ] . merge ( target : export_path ) , logger : @logger ) end | Instantiate the Hooker object according to the class named in the config |
14,864 | def load_songs @songs = [ ] playlist = @client . request ( 'getPlaylistByID' , playlistID : @id ) @songs = playlist [ 'songs' ] . map! do | s | Song . new ( s ) end if playlist . key? ( 'songs' ) @songs end | Fetch playlist songs |
14,865 | def create_wav_wrapped_mpeg ( mpeg_path , result_path , options = { } ) options . to_options! start_at = get_datetime_for_option ( options [ :start_at ] ) end_at = get_datetime_for_option ( options [ :end_at ] ) wav_wrapped_mpeg = NuWav :: WaveFile . from_mpeg ( mpeg_path ) cart = wav_wrapped_mpeg . chunks [ :cart ] ca... | need start_at ends_on |
14,866 | def run_command ( command , options = { } ) timeout = options [ :timeout ] || 7200 nice = if options . key? ( :nice ) ( options [ :nice ] == 'n' ) ? '' : "nice -n #{options[:nice]} " else 'nice -n 19 ' end echo_return = ( options . key? ( :echo_return ) && ! options [ :echo_return ] ) ? '' : '; echo $?' cmd = "#{nice}#... | Pass the command to run and a timeout |
14,867 | def key_for_primary @_key_for_primary ||= if options [ :as ] options [ :as ] else controller_name = controller . controller_name ( resource . respond_to? ( :each ) ? controller_name : controller_name . singularize ) . intern end end | The primary resource is keyed per the request . |
14,868 | def get ( field , filter = true ) if field . nil? or ! field . instance_of? ( String ) raise ArgumentError , "Field value must be a string" end resp = http . get ( "#{BASEPATH}?fields=#{field}" , headers ) data = resp . body [ RESP_PREFIX . length .. - 1 ] data = JSON . parse ( data ) if filter && data . has_key? ( fie... | Base method to send a request to Quora API . |
14,869 | def method_missing ( method_id , * arguments , & block ) if method_id . to_s =~ / \w / self . class . send :define_method , method_id do field = method_id . to_s [ 4 .. - 1 ] get ( field ) end self . send ( method_id ) else super end end | Override method_missing so any method that starts with get_ will be defined . |
14,870 | def log_controller_action_block ( options = { } ) if null? do_nothing_on_null ( :log_controller_action_block ) yield else build_full_controller_action_string ( options ) has_error = true begin_time = UnionStationHooks . now begin result = yield has_error = false result ensure log_controller_action ( options . merge ( :... | Logging controller - related information Logs that you are calling a web framework controller action . Of course you should only call this if your web framework has the concept of controller actions . For example Rails does but Sinatra and Grape don t . |
14,871 | def log_controller_action ( options ) return do_nothing_on_null ( :log_controller_action ) if null? Utils . require_key ( options , :begin_time ) Utils . require_key ( options , :end_time ) if options [ :controller_name ] build_full_controller_action_string ( options ) @transaction . message ( "Controller action: #{@co... | Logs that you are calling a web framework controller action . Of course you should only call this if your web framework has the concept of controller actions . For example Rails does but Sinatra and Grape don t . |
14,872 | def remove_vertex ( vertex ) raise "not a vertex" unless vertex . is_a? ( Vertex ) if ! vertex raise "Vertex does not exist" elsif ! vertex . connections . empty? raise "Vertex has edges. Break them first." else @vertices . delete ( vertex ) end end | Remove a vertex |
14,873 | def make_connection ( v1 , v2 ) raise "not a vertex" unless v1 . is_a? ( Vertex ) && v2 . is_a? ( Vertex ) raise "already connected" if is_connected? ( v1 , v2 ) edge = Edge . new ( v1 , v2 ) v1 . connect ( v2 , edge ) v2 . connect ( v1 , edge ) @edges << edge edge end | Make an edge between two vertices |
14,874 | def find_connection ( v1 , v2 ) raise "not a vertex" unless v1 . is_a? ( Vertex ) && v2 . is_a? ( Vertex ) raise "Vertices not connected" if ! is_connected? ( v1 , v2 ) connection = v1 . edges . select { | edge | edge . connection . include? ( v2 ) } raise "Error finding connection" if connection . length > 1 connectio... | Find the edge connecting two vertices |
14,875 | def is_connected? ( v1 , v2 ) raise "not a vertex" unless v1 . is_a? ( Vertex ) && v2 . is_a? ( Vertex ) v1 . connections . include? ( v2 ) end | Returns whether two vertices are connected |
14,876 | def find_by_solr ( query , options = { } ) data = parse_query ( query , options ) return parse_results ( data , options ) end | Finds instances of a model . Terms are ANDed by default can be overwritten by using OR between terms |
14,877 | def rebuild_solr_index ( batch_size = 300 , options = { } , & finder ) finder ||= lambda do | ar , sql_options | ar . all sql_options . merge! ( { :order => self . primary_key , :include => configuration [ :solr_includes ] . keys } ) end start_time = Time . now options [ :offset ] ||= 0 options [ :threads ] ||= 2 optio... | It s used to rebuild the Solr index for a specific model . Book . rebuild_solr_index |
14,878 | def delete_old_temp_folders path = File . join ( Dir . tmpdir , STAGING_AREA_PREFIX + '*' ) day = 24 * 60 * 60 dirs = Dir . glob ( path ) dirs . select! { | dir | Time . now . utc - File . ctime ( dir ) . utc > day } removed = dirs . each { | dir | FileUtils . rm_rf ( dir ) } log "Removed #{removed} old temp folder(s)"... | Sometimes SIGTERM causes Dir . mktmpdir to not properly delete the temp folder Remove 1 day old folders |
14,879 | def fetch_key ( key ) string_key = key . to_s keys . detect { | k | k . to_s . casecmp ( string_key ) == 0 } end | Returns a key that matches the parameter in a case - insensitive manner . |
14,880 | def ruby_to_sdb ( name , value ) return nil if value . nil? name = name . to_s att_meta = get_att_meta ( name ) if value . is_a? Array ret = value . collect { | x | ruby_to_string_val ( att_meta , x ) } else ret = ruby_to_string_val ( att_meta , value ) end unless value . blank? if att_meta . options if att_meta . opti... | Time to second precision |
14,881 | def sdb_to_ruby ( name , value ) return nil if value . nil? att_meta = get_att_meta ( name ) if att_meta . options if att_meta . options [ :encrypted ] value = Translations . decrypt ( value , att_meta . options [ :encrypted ] ) end if att_meta . options [ :hashed ] return PasswordHashed . new ( value ) end end if ! ha... | Convert value from SimpleDB String version to real ruby value . |
14,882 | def head ( template_values ) raise FamilySearch :: Error :: MethodNotAllowed unless allow . include? ( 'head' ) template_values = validate_values ( template_values ) t = Addressable :: Template . new ( @template ) url = t . expand ( template_values ) . to_s @client . head url end | Calls HTTP HEAD on the URL template . It takes the + template_values + hash and merges the values into the template . |
14,883 | def get_one_student ( params ) ps_dcid = params [ :dcid ] || params [ :dc_id ] || params [ :id ] api_path = "/ws/v1/student/#{ps_dcid.to_i}" options = { query : { "extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields" , "expansion... | retrieves all individual student s details - you must use the DCID !!! |
14,884 | def build_query ( params ) query = [ ] query << "school_enrollment.enroll_status_code==#{params[:status_code]}" if params . has_key? ( :status_code ) query << "school_enrollment.enroll_status==#{params[:enroll_status]}" if params . has_key? ( :enroll_status ) query << "student_username==#{params[:username]}" if params ... | build the api query - you can use splats to match any character |
14,885 | def directories_to_compact builds = Dir . entries builds_dir builds . select! { | e | File . directory? builds_dir ( e ) } builds . reject! { | e | %w{ . .. } . include? e } builds . sort! builds = builds [ 0 .. - ( @num_builds_to_leave + 1 ) ] builds . reject! { | e | @builds_to_leave . include? ( e ) || @builds_to_le... | Build the list of directories to compact according to the options |
14,886 | def compress_directory ( dir ) File . open archive_path ( dir ) , 'wb' do | oarchive_path | Zlib :: GzipWriter . wrap oarchive_path do | gz | Gem :: Package :: TarWriter . new gz do | tar | Find . find "#{builds_dir}/" + dir do | f | relative_path = f . sub "#{builds_dir}/" , "" mode = File . stat ( f ) . mode size = F... | Create a . tar . gz file from a directory Done in pure ruby to ensure portability |
14,887 | def execute ( * command , label : nil ) output , status = Open3 . capture2 ( * command . flatten ) log_debug caller [ 0 ] log_debug "CMD: #{command.join(' ')}" log_debug "OUT: #{output}" unless status . success? log_error output raise SubprocessError . new ( label , command . join ( ' ' ) , status ) end output . chomp ... | Synchronously execute a command as a subprocess and return the output . |
14,888 | def execute_pipe ( * commands , label : nil ) stdout , waiters = Open3 . pipeline_r ( * commands ) output = stdout . read waiters . each_with_index do | waiter , i | status = waiter . value unless status . success? log_error output raise SubprocessError . new ( label , commands [ i ] . join ( ' ' ) , status ) end end o... | Synchronously execute a chain multiple commands piped into each other as a subprocess and return the output . |
14,889 | def execute_stream ( * command , label : nil , pwd : nil ) opts = { } opts [ :chdir ] = pwd unless pwd . nil? Open3 . popen2e ( command . join ( ' ' ) , opts ) do | stdin , stdout_and_stderr , wait_thr | stdin . close until stdout_and_stderr . closed? || stdout_and_stderr . eof? line = stdout_and_stderr . gets log_info... | Synchronously execute a command as a subprocess and and stream the output to STDOUT |
14,890 | def property ( contractid , groupid , propertyid ) begin property_hash = @client . get_json_body ( "/papi/v0/properties/#{propertyid}" , { 'contractId' => contractid , 'groupId' => groupid , } , ) rescue puts "# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.messag... | fetch a single property |
14,891 | def properties properties = [ ] contract_group_pairs . each do | cg | begin properties_hash = @client . get_json_body ( "/papi/v0/properties/" , { 'contractId' => cg [ :contract ] , 'groupId' => cg [ :group ] , } ) if properties_hash && properties_hash [ 'properties' ] [ 'items' ] properties_hash [ 'properties' ] [ 'it... | takes a long time to complete! |
14,892 | def hostnames ( property , skip_update_dns_status = false , version = nil ) raise 'property must be a Borderlands::Property object' unless property . is_a? Property version ||= property . productionversion begin hostnames_hash = @client . get_json_body ( "/papi/v0/properties/#{property.id}/versions/#{version}/hostnames... | version defaults to the current production version which is pretty much always going to be the most meaningful thing to look at |
14,893 | def ruletree ( property , version = nil ) raise 'property must be a Borderlands::Property object' unless property . is_a? Property version ||= property . productionversion tree = nil begin rt = @client . get_json_body ( "/papi/v0/properties/#{property.id}/versions/#{version}/rules/" , { 'contractId' => property . contr... | version defaults to current production version here too |
14,894 | def find_passenger_config passenger_config = ENV [ 'PASSENGER_CONFIG' ] if passenger_config . nil? || passenger_config . empty? passenger_config = find_passenger_config_vendor || find_passenger_config_in_path end if passenger_config . nil? || passenger_config . empty? abort 'ERROR: The unit tests are to be run against ... | Lookup the passenger - config command either by respecting the PASSENGER_CONFIG environment variable or by looking it up in PATH . If the command cannot be found the current process aborts with an error message . |
14,895 | def undo_bundler clean_env = nil Bundler . with_clean_env do clean_env = ENV . to_hash end ENV . replace ( clean_env ) end | Unit tests must undo the Bundler environment so that the gem s own Gemfile doesn t affect subprocesses that may have their own Gemfile . |
14,896 | def write_file ( path , content ) dir = File . dirname ( path ) if ! File . exist? ( dir ) FileUtils . mkdir_p ( dir ) end File . open ( path , 'wb' ) do | f | f . write ( content ) end end | Writes the given content to the file at the given path . If or or more parent directories don t exist then they are created . |
14,897 | def debug_shell puts '------ Opening debug shell -----' @orig_dir = Dir . pwd begin if respond_to? ( :prepare_debug_shell ) prepare_debug_shell end system ( 'bash' ) ensure Dir . chdir ( @orig_dir ) end puts '------ Exiting debug shell -----' end | Opens a debug shell . By default the debug shell is opened in the current working directory . If the current module has the prepare_debug_shell method that method is called before opening the debug shell . The method could for example change the working directory . |
14,898 | def eventually ( deadline_duration = 3 , check_interval = 0.05 ) deadline = Time . now + deadline_duration while Time . now < deadline if yield return else sleep ( check_interval ) end end raise 'Time limit exceeded' end | Asserts that something should eventually happen . This is done by checking that the given block eventually returns true . The block is called once every check_interval msec . If the block does not return true within deadline_duration secs then an exception is raised . |
14,899 | def should_never_happen ( deadline_duration = 0.5 , check_interval = 0.05 ) deadline = Time . now + deadline_duration while Time . now < deadline if yield raise "That which shouldn't happen happened anyway" else sleep ( check_interval ) end end end | Asserts that something should never happen . This is done by checking that the given block never returns true . The block is called once every check_interval msec until deadline_duration seconds have passed . If the block ever returns true then an exception is raised . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.