idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
21,300 | def environment_list_command ( environment_command ) environment_command . desc 'List the remote environments in the project' environment_command . command :list do | environment_list_command | environment_list_command . action do | global_options , options , args | environments = Bebox :: Environment . list ( project_root ) title _ ( 'cli.environment.list.current_envs' ) environments . map { | environment | msg ( environment ) } warn ( _ ( 'cli.environment.list.no_envs' ) ) if environments . empty? end end end | Environment list command |
21,301 | def hash_to_styles ( hash , separator = '; ' ) unless hash . empty? return hash . map { | e | "#{e[0]}: #{e[1].join(' ')}" } . join ( separator ) else return nil end end | make a CSS style - let from a Hash of CSS settings |
21,302 | def lex! r = Array . new @buffer . gsub! ( / \r \n \n \r / , "\n" ) while @code_start_re =~ @buffer r << [ :string , $` ] unless $` . empty? if CODE_EQUIVALENT . has_key? ( $& ) CODE_EQUIVALENT [ $& ] . each do | c | r << [ :code , c ] end @buffer = $' else csi = $& residual = $' if PARAMETER_AND_LETTER =~ residual r << [ :code , $& ] @buffer = $' else @buffer = csi + residual return r end end end r << [ :string , @buffer ] unless @buffer . empty? @buffer = '' return r end | returns array of tokens while deleting the tokenized part from buffer |
21,303 | def echo_on ( screen , cursor ) each_char do | c | w = width ( c ) cursor . fit! ( w ) screen . write ( c , w , cursor . cur_col , cursor . cur_row , @sgr . dup ) cursor . advance! ( w ) end return self end | Select Graphic Rendition associated with the text echo the string onto the _screen_ with initial cursor as _cursor_ _cursor_ position will be changed as the string is echoed |
21,304 | def apply_code! ( letter , * pars ) case letter when 'A' @cur_row -= pars [ 0 ] ? pars [ 0 ] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'B' @cur_row += pars [ 0 ] ? pars [ 0 ] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'C' @cur_col += pars [ 0 ] ? pars [ 0 ] : 1 when 'D' @cur_col -= pars [ 0 ] ? pars [ 0 ] : 1 when 'E' @cur_row += pars [ 0 ] ? pars [ 0 ] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'F' @cur_row -= pars [ 0 ] ? pars [ 0 ] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'G' @cur_col = pars [ 0 ] ? pars [ 0 ] : 1 when 'H' @cur_row = pars [ 0 ] ? pars [ 0 ] : 1 @cur_col = pars [ 1 ] ? pars [ 1 ] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'f' @cur_row = pars [ 0 ] ? pars [ 0 ] : 1 @cur_col = pars [ 1 ] ? pars [ 1 ] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row end if @cur_row < 1 @cur_row = 1 end if @cur_col < 1 @cur_col = 1 elsif @cur_col > @max_col @cur_col = @max_col end return self end | maximum row number applies self an escape sequence code that ends with _letter_ as String and with some _pars_ as Integers |
21,305 | def css_styles ( colors = Screen . default_css_colors ) r = Hash . new { | h , k | h [ k ] = Array . new } r [ 'font-style' ] << 'italic' if @italic == :on r [ 'text-decoration' ] << 'underline' unless @underline == :none r [ 'text-decoration' ] << 'blink' unless @blink == :off case @image when :positive fg = @foreground bg = @background when :negative fg = @background bg = @foreground end fg = bg if @conceal == :on r [ 'color' ] << colors [ @intensity ] [ fg ] unless fg == :white r [ 'background-color' ] << colors [ @intensity ] [ bg ] unless bg == :black return r end | a Hash of CSS stylelet |
21,306 | def write ( char , char_width , col , row , sgr ) @lines [ Integer ( row ) ] [ Integer ( col ) ] = [ char , char_width , sgr . dup ] end | register the _char_ at a specific location on Screen |
21,307 | def anchor name , anchor_mark = @data . split ( / \s /o , 2 ) anchor_mark = "_" if ( anchor_mark . nil? or anchor_mark . empty? ) HtmlElement . create ( "a" , anchor_mark , "name" => name , "href" => "#" + name ) end | def inline lines = HtmlElement . decode ( |
21,308 | def params idx = 0 @param_types . collect do | param_type | args = GCCType . new ( param_type ) . identifiers . collect do arg = GCCValue . new self , "param#{idx}" idx += 1 arg end param_type . construct * args end end | Retrieve all parameters |
21,309 | def tag ( name , attributes = { } , & block ) open = sjoin name , attrs ( attributes ) body = block . call if block_given? if VOID_ELEMENTS . include? ( name . to_sym ) raise BuilderError , "Void elements cannot have content" if body "<#{open}>" else "<#{open}>#{body}</#{name}>" end end | Generate an HTML Tag |
21,310 | def process_forget ( object , quiet : ) reference = convert_object_to_reference ( object , build : false ) raise UnexposedObjectError unless reference reference . local_forget_request ( quiet : quiet ) end | Process a request from the local application to forget an exposed object . |
21,311 | def process_forget_message ( message , quiet : ) reference = convert_properties_to_reference ( message . object , build : false ) reference . remote_forget_request ( quiet : quiet ) end | Processes a request from the remote endpoint to forget an exposed object . Called when a forget message has been received by the messenger . |
21,312 | def memorise if memory contiguous_strides = ( 0 ... dimension ) . collect do | i | shape [ 0 ... i ] . inject 1 , :* end if strides == contiguous_strides self else dup end else dup end end | Duplicate array expression if it is not in row - major format |
21,313 | def to_a if dimension == 0 force else n = shape . last ( 0 ... n ) . collect { | i | element ( i ) . to_a } end end | Convert to Ruby array of objects |
21,314 | def inspect ( indent = nil , lines = nil ) if variables . empty? if dimension == 0 and not indent "#{typecode.inspect}(#{force.inspect})" else if indent prepend = '' else prepend = "#{Hornetseye::MultiArray(typecode, dimension).inspect}:\n" indent = 0 lines = 0 end if empty? retval = '[]' else retval = '[ ' for i in 0 ... shape . last x = element i if x . dimension > 0 if i > 0 retval += ",\n " lines += 1 if lines >= 10 retval += '...' if indent == 0 break end retval += ' ' * indent end str = x . inspect indent + 1 , lines lines += str . count "\n" retval += str if lines >= 10 retval += '...' if indent == 0 break end else retval += ', ' if i > 0 str = x . force . inspect if retval . size + str . size >= 74 - '...' . size - '[ ]' . size * indent . succ retval += '...' break else retval += str end end end retval += ' ]' unless lines >= 10 end prepend + retval end else to_s end end | Display information about this object |
21,315 | def check_shape ( * args ) _shape = shape args . each do | arg | _arg_shape = arg . shape if _shape . size < _arg_shape . size raise "#{arg.inspect} has #{arg.dimension} dimension(s) " + "but should not have more than #{dimension}" end if ( _shape + _arg_shape ) . all? { | s | s . is_a? Integer } if _shape . last ( _arg_shape . size ) != _arg_shape raise "#{arg.inspect} has shape #{arg.shape.inspect} " + "(does not match last value(s) of #{shape.inspect})" end end end end | Check arguments for compatible shape |
21,316 | def force if finalised? get elsif ( dimension > 0 and Thread . current [ :lazy ] ) or not variables . empty? self elsif compilable? retval = allocate GCCFunction . run Store . new ( retval , self ) retval . demand . get else retval = allocate Store . new ( retval , self ) . demand retval . demand . get end end | Force delayed computation unless in lazy mode |
21,317 | def yield ( dt , clock = nil ) clock ||= $shreduler . clock $shreduler . shredule ( Shred . current , clock . now + dt , clock ) Shred . current . pause end | yields the given amount of time on the global Shreduler using the provided Clock if given |
21,318 | def wait_on ( event ) $shreduler . shredule ( Shred . current , event , $shreduler . event_clock ) Shred . current . pause end | sleeps waiting on the given event on the default EventClock of the global Shreduler |
21,319 | def run_one shred , relative_time = @clock . unschedule_next return nil unless shred fast_forward ( relative_time ) if relative_time > 0 invoke_shred ( shred ) end | runs the next scheduled Shred if one exists returning that Shred |
21,320 | def run_until ( target_time ) return if target_time < now loop do shred , relative_time = next_shred break unless shred break unless now + relative_time <= target_time run_one end fast_forward ( target_time - now ) end | runs shreds until the given target time then fast - forwards to that time |
21,321 | def validate_syntax update_native validator = Bitcoin :: Validation :: Tx . new ( @native , nil ) valid = validator . validate :rules => [ :syntax ] { :valid => valid , :error => validator . error } end | Validate that the transaction is plausibly signable . |
21,322 | def validate_script_sigs bad_inputs = [ ] valid = true @inputs . each_with_index do | input , index | unless self . native . verify_input_signature ( index , input . output . transaction . native ) valid = false bad_inputs << index end end { :valid => valid , :inputs => bad_inputs } end | Verify that the script_sigs for all inputs are valid . |
21,323 | def add_input ( input , network : @network ) input = Input . new ( input . merge ( transaction : self , index : @inputs . size , network : network ) ) unless input . is_a? ( Input ) @inputs << input self . update_native do | native | native . add_in input . native end input end | Takes one of |
21,324 | def add_output ( output , network : @network ) if output . is_a? ( Output ) output . set_transaction ( self , @outputs . size ) else output = Output . new ( output . merge ( transaction : self , index : @outputs . size ) , network : network ) end @outputs << output self . update_native do | native | native . add_out ( output . native ) end end | Takes either an Output or a Hash describing an output . |
21,325 | def set_script_sigs ( * input_args , & block ) report = validate_syntax unless report [ :valid ] == true raise "Invalid syntax: #{report[:errors].to_json}" end self . inputs . zip ( * input_args ) do | input , * input_arg | input . script_sig = yield input , * input_arg end end | A convenience method for authorizing inputs in a generic manner . Rather than iterating over the inputs manually the user can provide this method with an array of values and a block that knows what to do with the values . |
21,326 | def input_value_for ( addresses ) own = inputs . select { | input | addresses . include? ( input . output . address ) } own . inject ( 0 ) { | sum , input | input . output . value } end | Takes a set of Bitcoin addresses and returns the value expressed in the inputs for this transaction . |
21,327 | def output_value_for ( addresses ) own = outputs . select { | output | addresses . include? ( output . address ) } own . inject ( 0 ) { | sum , output | output . value } end | Takes a set of Bitcoin addresses and returns the value expressed in the outputs for this transaction . |
21,328 | def add_change ( address , metadata = { } ) add_output ( value : change_value , address : address , metadata : { memo : "change" } . merge ( metadata ) ) end | Add an output to receive change for this transaction . Takes a bitcoin address and optional metadata Hash . |
21,329 | def path temporary = [ ] actual_route = nil router do | route | actual_route = extract_and_format_route ( route ) temporary . push ( actual_route ) unless temporary . include? ( actual_route ) actual_route end temporary end | Extract path to routes and change format to parameter path |
21,330 | def assert_raises ( expected = StandardError ) begin yield rescue => actual return actual if actual . kind_of? ( expected ) raise Failure . new ( "Failure: Unexpected Exception" , expected , actual ) end raise Failure . new ( "Failure: No Exception" , expected , "Nothing raised." ) end | Succeeds if it catches an error AND that error is a kind_of? the expected error . Fails otherwise . |
21,331 | def tst ( name , & block ) start = Time . now block . call status = SUCCEEDED rescue Failure => exception status = FAILED rescue StandardError => exception status = RAISED ensure elapsed = Time . now - start __record ( name , status , elapsed , exception ) end | The tst methods itself . Takes a name and a block . Runs the block . Records the result . |
21,332 | def add_attribute ( attribute , type , * flags ) prop = create_nonjava_property ( attribute , type , * flags ) add_property ( prop ) prop end | Adds the given attribute to this Class . |
21,333 | def init_property_classifiers @local_std_prop_hash = { } @alias_std_prop_map = append_ancestor_enum ( @local_std_prop_hash ) { | par | par . alias_standard_attribute_hash } @local_prop_hash = { } @prop_hash = append_ancestor_enum ( @local_prop_hash ) { | par | par . property_hash } @attributes = Enumerable :: Enumerator . new ( @prop_hash , :each_key ) @local_mndty_attrs = Set . new @local_defaults = { } @defaults = append_ancestor_enum ( @local_defaults ) { | par | par . defaults } end | Initializes the property meta - data structures . |
21,334 | def compose_property ( property , other ) if other . inverse . nil? then raise ArgumentError . new ( "Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}" ) end sir , siw = property . accessors itr , itw = other . accessors tir = other . inverse define_method ( itr ) do ref = send ( sir ) ref . send ( itr ) if ref end define_method ( itw ) do | tgt | if tgt then ref = block_given? ? yield ( tgt ) : tgt . send ( tir ) raise ArgumentError . new ( "#{tgt} does not reference a #{other.inverse}" ) if ref . nil? end send ( siw , ref ) end prop = add_attribute ( itr , other . type ) logger . debug { "Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}." } prop . qualify ( :collection ) if other . collection? prop end | Creates a new convenience property in this source class which composes the given property and the other property . The new property symbol is the same as the other property symbol . The new property reader and writer methods delegate to the respective composed property reader and writer methods . |
21,335 | def most_specific_domain_attribute ( klass , attributes = nil ) attributes ||= domain_attributes candidates = attributes . properties best = candidates . inject ( nil ) do | better , prop | klass <= prop . type ? ( better && better . type <= prop . type ? better : prop ) : better end if best then logger . debug { "Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}." } best . to_sym end end | Returns the most specific attribute which references the given target type or nil if none . If the given class can be returned by more than on of the attributes then the attribute is chosen whose return type most closely matches the given class . |
21,336 | def set_attribute_type ( attribute , klass ) prop = property ( attribute ) return if klass == prop . type if prop . declarer == self then prop . type = klass logger . debug { "Set #{qp}.#{attribute} type to #{klass.qp}." } elsif prop . type . nil? or klass < prop . type then prop . restrict ( self , :type => klass ) logger . debug { "Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}." } else raise ArgumentError . new ( "Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}" ) end end | Sets the given attribute type to klass . If attribute is defined in a superclass then klass must be a subclass of the superclass attribute type . |
21,337 | def remove_attribute ( attribute ) sa = standard_attribute ( attribute ) sp = @local_prop_hash . delete ( sa ) if sp then clear_inverse ( sp ) @local_mndty_attrs . delete ( sa ) @local_std_prop_hash . delete_if { | aliaz , pa | pa == sa } else anc_prop_hash = @prop_hash . components [ 1 ] @prop_hash . components [ 1 ] = anc_prop_hash . filter_on_key { | pa | pa != attribute } anc_alias_hash = @alias_std_prop_map . components [ 1 ] @alias_std_prop_map . components [ 1 ] = anc_alias_hash . filter_on_key { | pa | pa != attribute } end logger . debug { "Removed the #{qp} #{attribute} property." } end | Removes the given attribute from this Resource . An attribute declared in a superclass Resource is hidden from this Resource but retained in the declaring Resource . |
21,338 | def register_property_alias ( aliaz , attribute ) std = standard_attribute ( attribute ) raise ArgumentError . new ( "#{self} attribute not found: #{attribute}" ) if std . nil? @local_std_prop_hash [ aliaz . to_sym ] = std end | Registers an alias to an attribute . |
21,339 | def strip_color! ( string ) [ @@mirc_color , @@rgb_color , @@ecma48_color ] . each do | pattern | string . gsub! ( pattern , '' ) end string . gsub! ( @@normal ) if ! has_color? ( string ) return string end | Strip IRC color codes from a string modifying it in place . |
21,340 | def generate_binding ( a_binding = binding ) a_binding . local_variables do | local_var | a_binding . local_variable_set local_var , nil end @bound_procs . each_with_index do | bound_proc , index | a_binding . local_variable_set "proc_#{index}" , bound_proc end @bound_constants . each_with_index do | bound_const , index | a_binding . local_variable_set "const_#{index}" , bound_const end a_binding end | Generate a binding containing the locally bound procs and constants |
21,341 | def save_as_new_record new_attributes = attributes . reject { | k , _v | k . to_s =~ / / } self . class . create ( new_attributes ) end | Save this record to the EVVNT API as a new record using the + create + action . |
21,342 | def save_as_persisted_record new_attributes = attributes . reject { | k , _v | k . to_s =~ / / } self . class . update ( id , new_attributes ) end | Save this record to the EVVNT API as an existing record using the + update + action . |
21,343 | def request_raw_hero_data return unless authenticated? response = RestClient . get ( "https://godvillegame.com/fbh/feed?a=#{@hero_guid}" , cookies : @cookies , content_type : :json , accept : :json ) JSON . parse ( response ) end | Request the raw hero data from godville |
21,344 | def compare_and_set_state ( next_state , expected_current ) mutex . lock if @state == expected_current @state = next_state true else false end ensure mutex . unlock end | Atomic compare and set operation . State is set to next_state only if current state == expected_current . |
21,345 | def if_state ( * expected_states ) mutex . lock raise ArgumentError , 'no block given' unless block_given? if expected_states . include? @state yield else false end ensure mutex . unlock end | executes the block within mutex if current state is included in expected_states |
21,346 | def method_missing ( name , * args , & block ) super unless respond_to_missing? ( name ) @__delegated_object__ . __send__ ( name , self , * args , & block ) end | Create a wrapper around a delegated object |
21,347 | def delete ( observer ) old_size = @stack . size @stack . delete_if do | o | o [ :observer ] == observer end old_size == @stack . size ? nil : observer end | Remove an observer from the stack . |
21,348 | def push ( observer , priority = nil ) raise ArgumentError , 'Observer is not callable' unless observer . respond_to? ( :call ) raise ArgumentError , 'Priority must be Fixnum' unless priority . nil? || priority . is_a? ( Fixnum ) @stack . push ( { :observer => observer , :priority => ( priority || default_priority ) } ) sort_by_priority observer end | Add an element to the stack with an optional priority . |
21,349 | def validate_each ( record , attribute , value ) unless value . blank? unless value =~ VALID_MASK if value =~ / \A /i record . errors [ attribute ] << ( options [ :message ] || 'must start with a letter' ) elsif value =~ / \z / record . errors [ attribute ] << ( options [ :message ] || 'must not end with an underscore' ) else record . errors [ attribute ] << ( options [ :message ] || 'must contain only letters, numbers, and underscore' ) end end end end | Validates attributes to determine if the values match the requirements of a safe name . |
21,350 | def validate_command ( cmd = ARGV ) fail 'Specify one action.' unless cmd . count == 1 cmd = cmd . shift fail 'Invalid action.' unless SUB_COMMANDS . include? ( cmd ) cmd end | Validate the given command . |
21,351 | def validate_options if @opts [ :daemonize ] fail 'Must specify PID file.' unless @opts [ :pid_given ] end @opts [ :pid ] = File . expand_path ( @opts [ :pid ] ) if @opts [ :pid_given ] @opts [ :log ] = File . expand_path ( @opts [ :log ] ) if @opts [ :log_given ] @opts [ :error ] = File . expand_path ( @opts [ :error ] ) if @opts [ :error_given ] @opts [ :config ] = File . expand_path ( @opts [ :config ] ) if @opts [ :config_given ] end | Validate the options ; otherwise fails . |
21,352 | def start ( & block ) fail 'No start block given.' if block . nil? check_existing_pid puts "Starting process..." Process . daemon if @opts [ :daemonize ] change_privileges if @opts [ :auto_default_actions ] redirect_outputs if @opts [ :auto_default_actions ] write_pid trap_default_signals if @opts [ :auto_default_actions ] block . call ( 'start' ) end | Start the process with the given block . |
21,353 | def stop ( & block ) block . call ( 'stop' ) unless block . nil? pid = read_pid fail 'No valid PID file.' unless pid && pid > 0 Process . kill ( 'TERM' , pid ) delete_pid puts 'Process terminated.' end | Stop the process . |
21,354 | def local ( tag ) first , second = tag . split ':' return first if second . nil? @namespaces . include? ( first ) ? second : tag end | Split off the local name portion of an XML tag . |
21,355 | def to_csv data attributes = data . first &. keys || [ ] CSV . generate ( headers : true ) do | csv | csv << attributes data . each do | row | csv << attributes . map do | att | row [ att ] end end end end | Array of hash data to csv format |
21,356 | def standardize_cell_val v v = ( ( float = Float ( v ) ) && ( float % 1.0 == 0 ) ? float . to_i : float ) rescue v v = v . force_encoding ( "UTF-8" ) if v . is_a? ( String ) v end | Convert number string to number |
21,357 | def raw_filter raw_data , opts = { } raw_header = raw_data [ header_row ] . map . with_index do | h , idx | is_valid = valid_header? ( h ) { idx : idx , is_remove : ! is_valid , is_required : require_header? ( h ) , name : is_valid && h . gsub ( / \s / , '' ) . gsub ( / / , '' ) . downcase } end rows = raw_data [ ( header_row + 1 ) .. - 1 ] . map . with_index do | raw , rdx | row = { } . with_indifferent_access raw_header . each do | h | val = raw [ h [ :idx ] ] next if h [ :is_remove ] if h [ :is_required ] && val . blank? row = { } break end row [ h [ :name ] ] = standardize_cell_val val end next if row . values . all? ( & :blank? ) row [ :id ] = rdx + 1 if find_columns . include? ( :id ) && row [ :id ] . blank? row end . compact . reject ( & :blank? ) rows = rows . select do | row | if required_columns . present? required_columns . all? { | col | row [ col ] . present? } else true end end rows end | Remove uncessary columns and invalid rows from csv format data |
21,358 | def friendly_details ( * args , & block ) klass = args . shift options = args . extract_options! attributes = args . extract_options! if attributes . empty? attributes = options options = { } end DetailsDelegator . new ( klass , self , attributes , options , & block ) . tap do | dd | dd . setup_delegated_attributes dd . instance_eval ( & block ) if block_given? end end | Configure a Friendly Base model associated with an ActiveRecord model . |
21,359 | def inside_project? project_found = false cwd = Pathname ( Dir . pwd ) home_directory = File . expand_path ( '~' ) cwd . ascend do | current_path | project_found = File . file? ( "#{current_path.to_s}/.bebox" ) self . project_root = current_path . to_s if project_found break if project_found || ( current_path . to_s == home_directory ) end project_found end | Search recursively for . bebox file to see if current directory is a bebox project or not |
21,360 | def get_post ( user_name , intra_hash ) response = @conn . get @url_post . expand ( { :user_name => user_name , :intra_hash => intra_hash , :format => @format } ) if @parse attributes = JSON . parse ( response . body ) return Post . new ( attributes [ "post" ] ) end return response . body end | Initializes the client with the given credentials . |
21,361 | def get_posts_for_user ( user_name , resource_type , tags = nil , start = 0 , endc = $MAX_POSTS_PER_REQUEST ) return get_posts ( "user" , user_name , resource_type , tags , start , endc ) end | Get posts owned by a user optionally filtered by tags . |
21,362 | def get_posts_for_group ( group_name , resource_type , tags = nil , start = 0 , endc = $MAX_POSTS_PER_REQUEST ) return get_posts ( "group" , group_name , resource_type , tags , start , endc ) end | Get the posts of the users of a group optionally filtered by tags . |
21,363 | def get_posts ( grouping , name , resource_type , tags = nil , start = 0 , endc = $MAX_POSTS_PER_REQUEST ) url = @url_posts . partial_expand ( { :format => @format , :resourcetype => get_resource_type ( resource_type ) , :start => start , :end => endc } ) if grouping == "user" url = url . partial_expand ( { :user => name } ) elsif grouping == "group" url = url . partial_expand ( { :group => name } ) end if tags != nil url = url . partial_expand ( { :tags => tags . join ( " " ) } ) end response = @conn . get url . expand ( { } ) if @parse posts = JSON . parse ( response . body ) [ "posts" ] [ "post" ] return posts . map { | attributes | Post . new ( attributes ) } end return response . body end | Get posts for a user or group optionally filtered by tags . |
21,364 | def get_document ( user_name , intra_hash , file_name ) response = @conn . get get_document_href ( user_name , intra_hash , file_name ) if response . status == 200 return [ response . body , response . headers [ 'content-type' ] ] end return nil , nil end | Get a document belonging to a post . |
21,365 | def get_document_preview ( user_name , intra_hash , file_name , size ) response = @conn . get get_document_href ( user_name , intra_hash , file_name ) , { :preview => size } if response . status == 200 return [ response . body , 'image/jpeg' ] end return nil , nil end | Get the preview for a document belonging to a post . |
21,366 | def get_resource_type ( resource_type ) if $resource_types_bookmark . include? resource_type . downcase ( ) return "bookmark" end if $resource_types_bibtex . include? resource_type . downcase ( ) return "bibtex" end raise ArgumentError . new ( "Unknown resource type: #{resource_type}. Supported resource types are " ) end | Convenience method to allow sloppy specification of the resource type . |
21,367 | def get_current_table_name [ self . old_name , self . new_name ] . each do | name | return name . to_s if self . table_exists? ( name ) end self . raise_no_table_error end | Constructor - sets up the record and tries to connect to the correct database |
21,368 | def set_table_name [ self . old_name , self . new_name ] . each do | name | if self . table_exists? ( name ) return true if self . klass . table_name == name . to_s self . klass . table_name = name return true end end self . raise_no_table_error end | Set the correct table name for the Class we are controlling |
21,369 | def set ( options ) json_body = options . to_json request_uri = "#{base_request_uri}/state" HTTParty . put ( request_uri , :body => json_body ) end | change the state of a light note that colormode will automagically update |
21,370 | def rename ( new_name ) json_body = { :name => new_name } . to_json HTTParty . put ( base_request_uri , :body => json_body ) @name = new_name end | change the name of the light |
21,371 | def to_s pretty_name = @name . to_s . split ( / / ) . map ( & :capitalize ) . join ( " " ) on_or_off = on? ? "on" : "off" reachable = reachable? ? "reachable" : "unreachable" "#{pretty_name} is #{on_or_off} and #{reachable}" end | pretty - print the light s status |
21,372 | def edit @edit = true @record = Post . find ( params [ :id ] ) add_breadcrumb I18n . t ( "controllers.admin.pages.edit.breadcrumb" ) set_title ( I18n . t ( "controllers.admin.pages.edit.title" , post_title : @record . post_title ) ) @action = 'update' end | gets and displays the post object with the necessary dependencies |
21,373 | def destroy Post . disable_post ( params [ :id ] ) respond_to do | format | format . html { redirect_to admin_pages_path , notice : I18n . t ( "controllers.admin.pages.destroy.flash.success" ) } end end | deletes the post |
21,374 | def results ActiveRecord :: Base . connection . tables . each do | table | model = table . classify . constantize rescue next model . columns . each do | column | present = model . respond_to? ( :nillify_attributes ) && model . nillify_attributes . include? ( column . name . to_sym ) @results << [ present , model . name , column . name ] if include_column ( column ) end end @results end | A nested array with one row for each column suitable for nillification . |
21,375 | def load_json ( key ) path = if yaml [ key ] =~ %r{ } yaml [ key ] else dirname = File . dirname ( options [ :config ] ) "#{dirname}/#{yaml[key]}" end if File . exist? ( path ) Mash . from_hash ( JSON . parse ( IO . read ( path ) ) ) else puts "ERROR: #{key}.json config does not exist at: #{path}" exit 1 end end | the chap . json and node . json is assumed to be in th same folder as chap . yml if a relative path is given |
21,376 | def load ( manifest_filename , opts = { } ) opts = self . class . module_options . deep_merge ( opts ) manifest_filename = Pathname . new ( manifest_filename ) . expand_path load_manifest ( manifest_filename , opts ) load_params ( opts ) if opts [ :raise_on_missing_params ] && ! missing_params . empty? raise "Missing required configurable parameters: #{missing_params.join(', ')}" end self end | Creates a Config object . |
21,377 | def missing_params required_params = manifest . select { | p | p [ :required ] } . map { | p | p [ :name ] } required_params - @params . keys end | Returns list of missing required params |
21,378 | def manifest @manifest . map do | k , v | { name : k , desc : v [ :desc ] , required : ! v . key? ( :default ) , const : v [ :const ] , default : v [ :default ] } end end | Returns annotated manifest |
21,379 | def load_params ( opts = { } ) Dotenv . load if opts [ :use_dotenv ] manifest . each do | p | env_name = p [ :name ] . to_s if p [ :const ] @params [ p [ :name ] ] = p [ :default ] elsif p [ :required ] @params [ p [ :name ] ] = ENV [ env_name ] if ENV . key? ( env_name ) else @params [ p [ :name ] ] = ENV . key? ( env_name ) ? ENV [ env_name ] : p [ :default ] end end @params end | Reads parameters from the ENV according to the current manifest |
21,380 | def run @done = false @manager_running = false reaper = nil while @queue . size > 0 if @threads . size <= @max_threads @threads << Thread . new ( @queue . pop ) do | proc | Thread . current [ :thread_state ] = "running" @klass . new . instance_exec ( proc [ :params ] , & proc [ :block ] ) Thread . current [ :thread_state ] = "done" end else unless @manager_running reaper = manage_threads @manager_running = true end sleep 1 end end reaper = manage_threads unless @manager_running reaper . join end | Runs while there are jobs in the queue Waits for a second and checks for available threads Exits when all jobs are allocated in threads |
21,381 | def manage_threads Thread . new do while ( @threads . size > 0 ) done = [ ] @threads . each do | t | done << t if t [ :thread_state ] == "done" || ! t . status end done . each { | d | @threads . delete ( d ) } if done? @done = true else puts "Sleeping for 2" sleep 2 end end end end | Clears dead threads frees thread pool for more jobs Exits when no more threads are left |
21,382 | def print_debug ( stck_lvls , * vars ) @mutex ||= Mutex . new referers = caller [ 0 ... stck_lvls ] if stck_lvls > 0 @mutex . synchronize do referers . each { | r | puts "#{r}:" } vars . each { | v | pp v } if vars end end | outputs a debug message and details of each one of the + vars + if included . + stck_lvls + is the number of stack levels to be showed + vars + is a list of vars to be pretty printed . It is convenient to make the first to be a String with an informative message . |
21,383 | def friendly_instance_for_attribute ( attr ) klass = friendly_attributes_configuration . model_for_attribute ( attr ) send DetailsDelegator . friendly_model_reader ( klass ) end | Returns the Friendly instance corresponding to the specified attribute |
21,384 | def friendly_instance_present? ( friendly_model ) friendly_model_ivar = DetailsDelegator . friendly_model_ivar ( friendly_model ) val = instance_variable_get ( friendly_model_ivar ) val . present? end | Returns true if the FriendlyAttributes specified instance is loaded . |
21,385 | def load_session unless logged_in? session [ Shibbolite . pid ] = request . env [ Shibbolite . pid . to_s ] current_user . update ( get_attributes ) if registered_user? end end | loads the session data created by shibboleth ensures that the user s id is set in session and updates the user s shibboleth attributes |
21,386 | def create_node ( doc , node_name , content = nil ) node = Nokogiri :: XML :: Node . new ( node_name , doc ) node . content = content if content node end | a convenience method for quickly creating a new HTML element |
21,387 | def run begin @process . start rescue ChildProcess :: LaunchError => e raise StandardError . new ( e . message ) end begin @process . poll_for_exit ( @timeout ) rescue ChildProcess :: TimeoutError @timedout = true @process . stop ( @timeout ) end end | Initialize a new process |
21,388 | def rewrite_theme_helper if File . exists? ( "#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb" ) file = File . open ( "#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb" , "rb" ) contents = file . read parts = contents . split ( / \r \n / ) if parts [ 0 ] != 'module ThemeHelper' contents = "module ThemeHelper\n\n" + contents + "\n\nend" end File . open ( "#{Rails.root}/app/helpers/theme_helper.rb" , 'w' ) { | file | file . write ( contents ) } else contents = "module ThemeHelper\n\nend" File . open ( "#{Rails.root}/app/helpers/theme_helper.rb" , 'w' ) { | file | file . write ( contents ) } end load ( "#{Rails.root}/app/helpers/theme_helper.rb" ) end | rewrite the theme helper to use the themes function file |
21,389 | def address_to_pubkey ( addr ) return unless addr . size == 52 prefix = ADDRESS_PREFIX [ addr [ 0 , 2 ] ] return unless prefix v = Bitcoin . decode_base58 ( addr ) return if v [ 0 , 4 ] != prefix bytes = [ v [ 0 , 68 ] ] . pack ( 'H*' ) return if v [ 68 , 8 ] != sha256d ( bytes ) [ 0 , 8 ] v [ 4 , 64 ] end | to pubkey in hex 32 bytes |
21,390 | def prepare_vagrant ( node ) project_name = Bebox :: Project . name_from_file ( node . project_root ) vagrant_box_base = Bebox :: Project . vagrant_box_base_from_file ( node . project_root ) configure_local_hosts ( project_name , node ) add_vagrant_node ( project_name , vagrant_box_base , node ) end | Prepare the vagrant nodes |
21,391 | def prop atom val , format , nitems = prop_raw atom case format when 32 ; val . unpack ( "l!#{nitems}" ) when 16 ; val . unpack ( "s#{nitems}" ) when 8 ; val [ 0 , nitems ] when 0 ; nil end end | window property getter with easy way for XGetWindowProperty which return nil if the specified property name does not exist a String or a Array of Number |
21,392 | def validate_input ( dest , args ) return true unless should_validate ( dest ) @input . each do | p | val = args [ p [ :symbol ] ] next unless ! val || val == '*' || val == '' opts = p [ :opts ] unless opts [ :optional ] raise ArgumentError , "You must specify the required input #{p[:symbol]}" end end return true end | Validates that the specified parameters are valid for this input description . |
21,393 | def process_input ( dest , args ) dest . parent = args [ :parent ] dest . test = args [ :test ] return unless validate_input ( dest , args ) @input . each do | param | sym = param [ :symbol ] if args . key? sym sym_assign = "#{sym}=" . to_sym dest . send ( sym_assign , args [ sym ] ) end end end | Goes through and assigns the value for each declared parameter to an accessor with the same name validating that required parameters are not missing |
21,394 | def process_output ( dest , result ) return unless result . ok? && should_validate ( dest ) @output . each do | param | sym = param [ :symbol ] unless result . key? ( sym ) opts = param [ :opts ] raise ArgumentError , "Missing required value #{sym} in output" unless opts [ :optional ] end end end | Goes through and makes sure that required output parameters exist |
21,395 | def rake_input ( rake_arg ) params = { } rake_arg . each do | key , val | params [ key ] = val end params [ :logger ] = Logger . new ( STDOUT ) unless params . key? ( :logger ) params [ :log_format ] = :human unless params . key? ( :log_format ) return params end | convert rake task arguments to a standard hash . |
21,396 | def refresh_until_present ( timeout = 30 ) message = "waiting for #{@selector.inspect} to become present" Watir :: WaitWithRefresh . refresh_until ( browser , timeout , message ) { present? } end | Refresh the page until the element is present . |
21,397 | def refresh_while_present ( timeout = 30 ) message = "waiting for #{@selector.inspect} to disappear" Watir :: WaitWithRefresh . refresh_while ( browser , timeout , message ) { present? } end | Refresh the page while the element is present . |
21,398 | def when_present_after_refresh ( timeout = 30 ) message = "waiting for #{@selector.inspect} to become present" if block_given? Watir :: WaitWithRefresh . refresh_until ( browser , timeout , message ) { present? } yield self else WhenPresentAfterRefreshDecorator . new ( self , timeout , message ) end end | Refreshes the page until the element is present . |
21,399 | def locked? return false unless File . exists? ( lockfile ) result = false open ( lockfile , 'w' ) do | f | result = ! lock ( f , File :: LOCK_EX | File :: LOCK_NB ) end result end | Create a new LockFile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.