idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
23,100
def implementation ( * selectors ) selectors << :auto if selectors . empty? Implementation :: Registry :: Finder . new ( @implementations , selectors ) end
Used to find a suitable implementation
23,101
def clean_up @doc . css ( ".ess-separator" ) . remove @doc . css ( "@title" ) . remove @doc . css ( "@onclick" ) . remove @doc . css ( "@tabindex" ) . remove @doc . css ( ".ess-label-hits" ) . remove @doc . css ( ".ess-clear" ) . remove end
Cleanup some crap
23,102
def possible_namespaces namespaces = [ ] key = @key . to_s while ( index = key . rindex ( '_' ) ) key = key [ 0 , index ] namespaces << key . to_sym end namespaces end
Returns an array of possible namespaces based on splitting the key at every underscore .
23,103
def rest_of_key ( namespace ) return nil if @key == namespace key = @key . to_s index = key . index ( namespace . to_s ) && ( namespace . to_s . length + 1 ) key [ index , key . length ] . to_sym if index end
Returns the rest of the key for a given namespace
23,104
def update ( value ) @list . callbacks [ :update ] . inject ( value ) { | a , e | e . call ( self , a ) } end
Initialize the attribute .
23,105
def loop_eval ( input ) if ( @buffer . nil? && input =~ PATTERN ) command = input [ 1 .. - 1 ] name , arguments = ShellCommands . parse ( command ) unless BLACKLIST . include? ( name ) if BUILTIN . include? ( name ) arguments ||= [ ] return ShellCommands . send ( name , * arguments ) elsif EXECUTABLES [ name ] return ShellCommands . exec ( name , * arguments ) end end end super ( input ) end
Dynamically execute shell commands instead of Ruby .
23,106
def section ( section_changes , header , entry_style , header_style = nil ) return "" unless section_changes . size > 0 str = "" unless header . empty? if header_style str << header_style . call ( header ) else str << header end end section_changes . each_with_index do | e , i | str << entry_style . call ( e , i ) end str end
Format a specific section .
23,107
def to_slack str = "" str << tag_info { | t | t } str << commit_info { | ci | ci . empty? ? "" : "(_#{ci}_)\n" } str << sections ( changes , -> ( header ) { "*#{header.capitalize}*\n" } , -> ( field , _index ) { "\t- #{field}\n" } ) str end
Render the Changelog with Slack Formatting
23,108
def grow @lock . synchronize do prune logger . debug { "jobs: #{num_jobs}; busy: #{num_working}; idle: #{num_idle}" } if @size == 0 || ( @size < @max_size && num_jobs > 0 && num_jobs > num_idle ) then space = @max_size - @size jobs = num_jobs - num_idle needed = space < jobs ? space : jobs needed = 1 if needed <= 0 expand ( needed ) else logger . debug "NOT growing the pool!" end end nil end
Grow the pool by one if we have more jobs than idle workers
23,109
def method_missing ( method_symbol , * method_args ) if method_args . length > 0 _set ( method_symbol , method_args . first ) end _get ( method_symbol ) end
Handles method calls for our configuration keys .
23,110
def write_file ( filename = 'foo' , string = nil ) raise ExportError , 'Nothing to export for #{filename}.' if string . nil? || string == "" f = File . new ( File . expand_path ( File . join ( export_path , filename ) ) , 'w+' ) f . puts string f . close end
Write the string to a file in the export path .
23,111
def new_page @pdf . start_new_page set_pos_y print_section :page unless @sections [ :page ] . nil? set_pos_y ( @sections [ :body ] [ :settings ] [ :posY ] || 0 ) @current_groups . each do | field , value | print_section field . to_sym , @record , true end draw_columns end
Creates a new page restarting the vertical position of the pointer . Print the whole header for the current groups and the columns of the report .
23,112
def symbolize! hash hash . symbolize_keys! hash . values . select { | v | v . is_a? Hash } . each { | h | symbolize! ( h ) } end
Convert to symbol all hash keys recursively .
23,113
def get_sections symbolize! @rules raise "[body] section on YAML file is needed to generate the report." if @rules [ :body ] . nil? @sections = { :page => @rules [ :page ] , :body => @rules [ :body ] , :defaults => @rules [ :defaults ] , :groups => { } } @sections [ :body ] [ :settings ] [ :groups ] . each { | group | @sections [ :groups ] [ group . to_sym ] = @rules [ group . to_sym ] } if has_groups? end
Convert the structure of the rules to facilitate the generating proccess .
23,114
def initialize_footer_values @sections [ :body ] [ :settings ] [ :groups ] . each do | group | current_footer = { } @sections [ :groups ] [ group . to_sym ] [ :footer ] . each { | field , settings | current_footer [ field ] = nil } unless @sections [ :groups ] [ group . to_sym ] [ :footer ] . nil? @footers [ group . to_sym ] = current_footer unless current_footer . empty? end if has_groups? raise "The report must have at least a footer on body section" if @sections [ :body ] [ :footer ] . nil? current_footer = { } @sections [ :body ] [ :footer ] . each { | field , settings | current_footer [ field ] = nil } @footers [ :body ] = current_footer unless current_footer . empty? end
Create a structure to calculate the footer values for all groups . Appends the footer body to total values too .
23,115
def draw_footer footers_to_print , source footers_to_print . reverse_each do | group | draw_line ( @posY + @sections [ :body ] [ :settings ] [ :height ] / 2 ) source [ group ] [ :footer ] . each do | field , settings | settings = [ settings [ 0 ] , @posY , ( @defaults . merge ( settings [ 1 ] || { } ) . symbolize_keys! ) ] settings [ 2 ] [ :style ] = settings [ 2 ] [ :style ] . to_sym set_options settings [ 2 ] draw_text @footers [ group ] [ field ] , settings end draw_line ( @posY - @sections [ :body ] [ :settings ] [ :height ] / 4 ) set_pos_y @sections [ :body ] [ :settings ] [ :height ] reset_footer group end end
Print the footers according to the groups and source specified
23,116
def release_p p while p2 = p . merged_shift release_p p2 end p . reset! ( @pool [ p . class ] ||= [ ] ) << p end
releases the given Particle
23,117
def require_p p_kls l = @pool [ p_kls ] return p_kls . new if l . nil? p = l . pop return p_kls . new if p . nil? p end
requires a Particle of the given Class
23,118
def process_sys_p p if p . action == Edoors :: SYS_ACT_HIBERNATE stop! hibernate! p [ FIELD_HIBERNATE_PATH ] else super p end end
process the given particle
23,119
def spin! start! @run = true @hibernation = false while @run and ( @sys_fifo . length > 0 or @app_fifo . length > 0 ) while @run and @sys_fifo . length > 0 p = @sys_fifo . shift p . dst . process_sys_p p end while @run and @app_fifo . length > 0 p = @app_fifo . shift p . dst . process_p p break end end stop! end
starts the system mainloop
23,120
def hibernate! path = nil @hibernation = true File . open ( path || @hibernate_path , 'w' ) do | f | f << JSON . pretty_generate ( self ) end end
sends the system into hibernation
23,121
def collapse ( types ) return types . first if types . size == 1 return nil if types . empty? return String if string? ( types ) return Float if float? ( types ) String end
collapses all types encountered in a file s column into a single type
23,122
def remote_a return unless @page_a_tags remote_a = [ ] @page_a_tags . uniq . each do | link | uri = URI ( link [ 0 ] . to_ascii ) if uri && @site_domain remote_a << link [ 0 ] unless uri . host == @site_domain end end remote_a end
get all remote link on page
23,123
def fill_data_field! @all_titles = titles @meta_data = collect_metadates @title_h1_h2 = all_titles_h1_h2 @page_text_size = text_size @page_a_tags = all_a_tags @meta_desc_content = all_meta_description_content @h2_text = h2 @hlu = bad_url @title_good = title_good? @title_and_h1_good = title_and_h1_good? @meta_description_good = metadescription_good? @meta_keywords = keywords_good? @code_less = code_less? @meta_title_duplicates = metadates_good? @have_h2 = h2? end
fill Page instant with data for report
23,124
def get_page ( url ) timeout ( 30 ) do page = open ( url ) @site_domain = page . base_uri . host @page_path = page . base_uri . request_uri @page = Nokogiri :: HTML ( page ) end rescue Timeout :: Error , EOFError , OpenURI :: HTTPError , Errno :: ENOENT , TypeError return nil end
get page with open - uri then parse it with Nokogiri . Get site domain and path from URI
23,125
def title_and_h1_good? return unless @page arr = [ ] @page . css ( 'h1' ) . each { | node | arr << node . text } @page . css ( 'title' ) . size == 1 && arr . uniq . size == arr . size end
true if title and h1 have no duplicates
23,126
def metadescription_good? return unless @page tags = @page . css ( "meta[name='description']" ) return false if tags . size == 0 tags . each do | t | unless t [ 'value' ] . nil? return false if t [ 'content' ] . size == 0 || t [ 'content' ] . size > 200 end end true end
true if metadescription less then 200 symbols
23,127
def code_less? return unless @page sum = 0 page_text = @page . text . size @page . css ( 'script' ) . each do | tag | sum += tag . text . size end sum < page_text / 2 end
true if code of page less then text on it
23,128
def metadates_good? return unless @page return false if @all_titles . size > 1 || @meta_data . empty? node_names = [ ] @meta_data . each { | node | node_names << node [ 'name' ] } node_names . compact! node_names . uniq . size == node_names . size unless node_names . nil? || node_names . size < 1 end
check meta and title tags duplicates
23,129
def all_titles_h1_h2 return unless @page out = [ ] out << @page . css ( 'title' ) . text << { @page_url => @page . css ( 'h1' ) . text } out << { @page_url => @page . css ( 'h2' ) . text } out end
return hash with all titles h1 and h2
23,130
def all_a_tags return unless @page tags = [ ] @page . css ( 'a' ) . each do | node | tags << [ node [ 'href' ] , node [ 'target' ] , node [ 'rel' ] ] end tags . compact end
get all a tags
23,131
def default_params @params ||= { :api_key => session . api_key } @params . merge! ( :session_id => session . id ) if ( session . id ) @params = Smile :: ParamConverter . clean_hash_keys ( @params ) end
This will be included in every request once you have logged in
23,132
def base_web_method_call ( web_options , options = { } , url ) options = Smile :: ParamConverter . clean_hash_keys ( options ) web_options = Smile :: ParamConverter . clean_hash_keys ( web_options ) params = default_params . merge ( web_options ) params . merge! ( options ) if ( options ) logger . info ( params . inspect ) json = RestClient . post ( url , params ) . body upper_hash_to_lower_hash ( Smile :: Json . parse ( json ) ) end
Call either the secure or the base web url
23,133
def upper_hash_to_lower_hash ( upper ) case upper when Hash upper . inject ( { } ) do | lower , array | key , value = array lower [ key . downcase ] = upper_hash_to_lower_hash ( value ) lower end else upper end end
This converts a hash that has mixed case into all lower case
23,134
def relevant? ( action , subject , context = nil ) subject = subject . values . first if subject . class == Hash @match_all || ( matches_action? ( action ) && matches_subject? ( subject ) && matches_context ( context ) ) end
Matches both the subject and action not necessarily the conditions
23,135
def build_report builder = Nokogiri :: XML :: Builder . new do | xml | xml . testsuites { testsuite = xml . testsuite { @cases . each do | tc | testcase = xml . testcase { if tc . result_has_message? result_type = xml . send ( tc . result ) result_type [ :message ] = tc . message if tc . message . present? end if tc . system_out . size > 0 xml . send ( 'system-out' ) { xml . text tc . system_out . to_s } end if tc . system_err . size > 0 xml . send ( 'system-err' ) { xml . text tc . system_err . to_s } end } testcase [ :name ] = tc . name if tc . name . present? testcase [ :time ] = tc . time if tc . time . present? testcase [ :classname ] = package if package . present? if tc . classname . present? if testcase [ :classname ] . present? testcase [ :classname ] = "#{testcase[:classname]}.#{tc.classname}" else testcase [ :classname ] = tc . classname end end end } testsuite [ :name ] = name if name . present? testsuite [ :package ] = package if package . present? } end builder . parent . root . to_xml end
In short this is the XML string that makes the report .
23,136
def write_report_file raise FileNotFoundException . new 'There is no report file path specified' if report_path . blank? report = build_report if append_report . present? && File . exist? ( report_path ) f = File . open ( report_path ) existing_xml = Nokogiri :: XML ( f ) f . close report = existing_xml . root << Nokogiri :: XML ( report ) . at ( 'testsuite' ) report = format_xml report . to_xml end File . write report_path , report report end
Writes the report to the specified file also returns the new XML report content
23,137
def return_error_or_body ( response ) if response . status / 100 == 2 response . body else raise Checkdin :: APIError . new ( response . status , response . body ) end end
Helper method to return errors or desired response data as appropriate .
23,138
def set_variable_bounds ( var_index , lb , ub , force = false ) return unless force Cbc . Cbc_setColLower @ptr , var_index , lb Cbc . Cbc_setColUpper @ptr , var_index , ub end
Set the bounds of a variable in the model
23,139
def new_model ptr = FFI :: AutoPointer . new Cbc . Cbc_newModel , Cbc . method ( :Cbc_deleteModel ) Cbc . Cbc_setParameter ptr , 'logLevel' , '0' if Cbc . respond_to? ( :Cbc_setParameter ) ptr end
Construct a new model object
23,140
def build_constraint_matrix ( constrs ) store_constraint_indexes constrs start = [ ] index = [ ] value = [ ] col_start = 0 @variables . each do | var | start << col_start var . constraints . each do | constr | col_start += 1 index << constr . index value << constr . expression . terms [ var ] end end start << col_start [ start , index , value ] end
Build a constraint matrix for the currently existing variables
23,141
def store_model ( constrs , vars ) constrs . each do | constr | store_constraint constr @constraints << constr end vars . each_with_index do | var , i | var . index = i var . model = self store_variable var end end
Store all data for the model
23,142
def store_constraint_bounds ( index , sense , rhs ) case sense when :== lb = ub = rhs when :>= lb = rhs ub = Float :: INFINITY when :<= lb = - Float :: INFINITY ub = rhs end Cbc . Cbc_setRowLower @ptr , index , lb Cbc . Cbc_setRowUpper @ptr , index , ub end
Store the bounds for a given constraint
23,143
def store_variable ( var ) if var . type == :binary var . instance_variable_set ( :@lower_bound , 0 ) var . instance_variable_set ( :@upper_bound , 1 ) end set_variable_bounds var . index , var . lower_bound , var . upper_bound , true Cbc . Cbc_setObjCoeff @ptr , var . index , var . coefficient Cbc . Cbc_setColName ( @ptr , var . index , var . name ) unless var . name . nil? set_variable_type var . index , var . type end
Set the properties of a variable in the model
23,144
def month_calendar ( date = Time . zone . now . to_date , elements = [ ] , options = { } ) options . reverse_merge! :date_method => :start_at , :display_method => :to_s , :link_elements => true , :start_day => :sunday , start_date_method : nil , end_date_method : nil display_method = options . delete ( :display_method ) link_elements = options . delete ( :link_elements ) start_date_method = options . delete ( :start_date_method ) end_date_method = options . delete ( :end_date_method ) beginning_of_month = date . beginning_of_month . to_date end_of_month = date . end_of_month . to_date localized_day_names = I18n . t ( 'date.abbr_day_names' ) . dup english_day_names = [ :sunday , :monday , :tuesday , :wednesday , :thursday , :friday , :saturday ] raise ":start_day option for month_calendar must be in: #{english_day_names.join(', ')}, but you passed: #{options[:start_day].to_s} (class: #{options[:start_day].class.to_s})" unless english_day_names . include? ( options [ :start_day ] ) offset = english_day_names . index ( options [ :start_day ] ) last_day_of_week = Time . zone . now . end_of_week . wday offset . times do localized_day_names . push ( localized_day_names . shift ) end days_by_week = { } first_day = beginning_of_month . beginning_of_week last_day = end_of_month . end_of_week days = ( first_day .. last_day ) . each_with_object ( { } ) . with_index do | ( day , memo ) , index | memo [ day . to_date ] = elements . find_all do | e | if start_date_method . present? && end_date_method . present? day . to_date . between? ( e . send ( start_date_method ) , e . send ( end_date_method ) ) else e . send ( options [ :date_method ] ) . to_date == day . to_date end end || { } end days_by_week = days . each_with_object ( { } ) { | ( k , v ) , m | ( m [ k . cweek ] ||= { } ) [ k ] = v } render partial : 'ecm/calendar_helper/month_calendar' , locals : { localized_day_names : localized_day_names , days_by_week : days_by_week , display_method : display_method , link_elements : link_elements } end
renders a calendar table
23,145
def command ( * parts ) parts [ 0 ] [ 0 , 0 ] = '/' unless parts [ 0 ] [ 0 .. 0 ] == '/' line = parts . join ( " " ) Weechat . exec ( line , self ) line end
Send a command to the current buffer .
23,146
def send ( * text ) text [ 0 ] [ 0 , 0 ] = '/' if text [ 0 ] [ 0 .. 0 ] == '/' line = text . join ( " " ) Weechat . exec ( line ) line end
Send a text to the buffer . If the buffer represents a channel the text will be send as a message to the channel .
23,147
def lines ( strip_colors = false ) lines = [ ] Weechat :: Infolist . parse ( "buffer_lines" , @ptr ) . each do | line | line = Weechat :: Line . from_hash ( line ) if strip_colors line . prefix . strip_colors! line . message . strip_colors! end lines << line end lines end
Returns an array with all lines of the buffer .
23,148
def bind_keys ( * args ) keys = args [ 0 .. - 2 ] command = args [ - 1 ] keychain = keys . join ( "-" ) if command . is_a? Command command = command . command end set ( "key_bind_#{keychain}" , command ) @keybinds [ keys ] = command keychain end
Bind keys to a command .
23,149
def request ( method , url = nil , options = { } ) options [ :headers ] = { 'Content-Type' => 'application/json' } . merge ( options [ :headers ] || { } ) options [ :body ] = options [ :body ] . to_json if options [ :body ] . is_a? ( Hash ) attempt = 0 max_attempts = GoogleAPI . development_mode ? 1 : 5 while attempt < max_attempts response = access_token . send ( method . to_sym , url , options ) seconds_to_wait = [ ( ( 2 ** attempt ) + rand ) , response . headers [ 'Retry-After' ] . to_i ] . max attempt += 1 break if response . status < 400 || attempt == max_attempts GoogleAPI . logger . error "Request attempt ##{attempt} to #{url} failed for. Trying again in #{seconds_to_wait} seconds..." sleep seconds_to_wait end response . parsed || response end
A really important part of this class . The headers are injected here and the body is transformed into a JSON d string when necessary . We do exponential back - off for error responses and return a parsed response body if present the full Response object if not .
23,150
def upload ( api_method , url , options = { } ) mime_type = :: MIME :: Types . type_for ( options [ :media ] ) . first . to_s file = File . read ( options . delete ( :media ) ) options [ :body ] [ :mimeType ] = mime_type options [ :headers ] = ( options [ :headers ] || { } ) . merge ( { 'X-Upload-Content-Type' => mime_type } ) response = request ( api_method , url , options ) options [ :body ] = file options [ :headers ] . delete ( 'X-Upload-Content-Type' ) options [ :headers ] . merge! ( { 'Content-Type' => mime_type , 'Content-Length' => file . bytesize . to_s } ) request ( :put , response . headers [ 'Location' ] , options ) end
Build a resumable upload request that then makes POST and PUT requests with the correct headers for each request .
23,151
def build_url ( api_method , options = { } ) if api_method [ 'mediaUpload' ] && options [ :media ] url = GoogleAPI . discovered_apis [ api ] [ 'rootUrl' ] + api_method [ 'mediaUpload' ] [ 'protocols' ] [ 'resumable' ] [ 'path' ] [ 1 .. - 1 ] else url = GoogleAPI . discovered_apis [ api ] [ 'baseUrl' ] + api_method [ 'path' ] query_params = [ ] api_method [ 'parameters' ] . each_with_index do | ( param , settings ) , index | param = param . to_sym case settings [ 'location' ] when 'path' raise ArgumentError , ":#{param} was not passed" if settings [ 'required' ] && ! options [ param ] url . sub! ( "{#{param}}" , options . delete ( param ) . to_s ) when 'query' query_params << "#{param}=#{options.delete(param)}" if options [ param ] end end if api_method [ 'parameters' ] url += "?#{query_params.join('&')}" if query_params . length > 0 end [ url , options ] end
Put together the full URL we will send a request to . First we join the API s base URL with the current method s path forming the main URL .
23,152
def language_code_select ( priority_languages , options , html_options ) selected = object . send ( @method_name ) if object . respond_to? ( @method_name ) languages = "" if options . present? and options [ :include_blank ] option = options [ :include_blank ] == true ? "" : options [ :include_blank ] languages += "<option>#{option}</option>\n" end if priority_languages languages += options_for_select ( priority_languages , selected ) languages += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" end languages = languages + options_for_select ( language_translations , selected ) html_options = html_options . stringify_keys add_default_name_and_id ( html_options ) content_tag ( :select , languages . html_safe , html_options ) end
Adapted from Rails language_select . Just uses language codes instead of full names .
23,153
def send_file_blob ( proxy , options = { } ) if request . get_header ( HTTP_IF_NONE_MATCH ) == proxy . blob_id head :not_modified else response . headers [ ETAG ] = proxy . blob_id send_options = { type : proxy . mime_type , filename : proxy . original_name } send_options . merge! options send_data proxy . data , send_options end end
Sends a file blob to the browser .
23,154
def validate_configuration! unless @host . is_a? ( String ) && @host . length > 0 raise ( Error :: ConfigurationError , "Invalid host specified: Host must contain the host to redirect to." ) end if @host . end_with? ( '/' ) raise ( Error :: ConfigurationError , "Invalid host specified: #{@host} should not end with a trailing slash." ) end unless @path . is_a? ( String ) && @path . length > 0 raise ( Error :: ConfigurationError , "Invalid path specified: Path must contain a path to redirect to." ) end unless @path . end_with? ( '/' ) raise ( Error :: ConfigurationError , "Invalid path specified: #{@path} should end with a trailing slash." ) end unless @port . is_a? ( Integer ) && @port > 0 raise ( Error :: ConfigurationError , "Invalid port specified: #{@port} must be an integer and non-zero." ) end if ! @sign_key . nil? && ! @sign_key . is_a? ( String ) raise ( Error :: ConfigurationError , "Invalid sign_key specified: #{@sign_key} must be a String." ) end unless @sign_length . is_a? ( Integer ) && @sign_length . between? ( 0 , Signing :: MAX_SIGN_LENGTH ) raise ( Error :: ConfigurationError , "Invalid sign_length specified: #{@sign_length} must be an integer between 0-#{Signing::MAX_SIGN_LENGTH}." ) end unless @encode_uris . is_a? ( Array ) && @encode_uris . count > 0 raise ( Error :: ConfigurationError , "Invalid encode_uris specified: #{@encode_uris} must be an array with at least one URI scheme." ) end unless @url_encoding . is_a? ( Module ) && Encode :: ENCODERS . include? ( @url_encoding ) raise ( Error :: ConfigurationError , "Invalid url_encoding specified: #{@url_encoding} must be a valid encoder module." ) end unless @url_decoding . is_a? ( Module ) && Decode :: DECODERS . include? ( @url_decoding ) raise ( Error :: ConfigurationError , "Invalid url_decoding specified: #{@url_decoding} must be a valid decoder module." ) end end
Ensures that all configuration parameters are of an expected type .
23,155
def barcode ( opts = { } ) data = format_for_subset_c_if_applicable send ( barcodable ) if ( subset = opts [ :subset ] ) case subset when 'A' ; Barby :: Code128A . new data when 'B' ; Barby :: Code128B . new data when 'C' ; Barby :: Code128C . new data end else most_efficient_barcode_for data end end
Returns a Code128 barcode instance .
23,156
def create_barcode ( opts = { } ) path = barcode_path FileUtils . mkdir_p File . dirname ( path ) File . open ( path , 'wb' ) do | f | f . write barcode ( opts ) . to_png ( self . class . options . merge ( opts ) ) end FileUtils . chmod ( 0666 & ~ File . umask , path ) end
Writes a barcode PNG image .
23,157
def classification_leaderboard ( campaign_id ) response = connection . get do | req | req . url "campaigns/#{campaign_id}/classification_leaderboard" end return_error_or_body ( response ) end
Get the classification leaderboard for a given campaign
23,158
def character ( count , template ) out_of_order ( "c" , count , template ) raw Character . new . render ( count , template ) end
select count characters
23,159
def word ( count , template ) out_of_order ( "w" , count , template ) raw Word . new . render ( count , template ) end
select count words
23,160
def paragraph ( count , template ) out_of_order ( "p" , count , template ) i = 0 result = "" data = Paragraph . new . render ( template ) while i < count result += "<p>#{data[i]}</p>" i += 1 end raw result end
select count paragraphs wrap in p - tags
23,161
def open ( user = nil , password = nil ) raise ArgumentError . new ( "Database open requires an execution block" ) unless block_given? raise DatabaseError . new ( "The caRuby application database is already in use." ) if open? persistence_services . each { | svc | svc . timer . reset } start_session ( user , password ) yield ( self ) ensure close end
Calls the block given to this method with this database as an argument and closes the database when done .
23,162
def close return if @session . nil? begin @session . terminate_session rescue Exception => e logger . error ( "Session termination unsuccessful - #{e.message}" ) end clear logger . info ( "Disconnected from application server." ) @session = nil end
Releases database resources . This method should be called when database interaction is completed .
23,163
def perform ( op , obj , opts = nil , & block ) op_s = op . to_s . capitalize_first pa = Options . get ( :attribute , opts ) attr_s = " #{pa}" if pa ag_s = " autogenerated" if Options . get ( :autogenerated , opts ) ctxt_s = " in context #{print_operations}" unless @operations . empty? logger . info ( ">> #{op_s}#{ag_s} #{obj.pp_s(:single_line)}#{attr_s}#{ctxt_s}..." ) @error = nil @operations . push ( Operation . new ( op , obj , opts ) ) begin result = perform_operation ( & block ) rescue Exception => e if @error . nil? then msg = "Error performing #{op} on #{obj}:\n#{e.message}\n#{obj.dump}\n#{e.backtrace.qp}" logger . error ( msg ) @error = e end raise e ensure @operations . pop if @operations . empty? then @transients . clear end end logger . info ( "<< Completed #{obj.qp}#{attr_s} #{op}." ) result end
Performs the operation given by the given op symbol on obj by calling the block given to this method . Lazy loading is suspended during the operation .
23,164
def start_session ( user = nil , password = nil ) user ||= @user password ||= @password if user . nil? then raise DatabaseError . new ( 'The caRuby application is missing the login user' ) end if password . nil? then raise DatabaseError . new ( 'The caRuby application is missing the login password' ) end @session = ClientSession . instance connect ( user , password ) end
Initializes the default application service .
23,165
def print_operations ops = @operations . reverse . map do | op | attr_s = " #{op.attribute}" if op . attribute "#{op.type.to_s.capitalize_first} #{op.subject.qp}#{attr_s}" end ops . qp end
Returns the current database operation stack as a String .
23,166
def connect ( user , password ) logger . debug { "Connecting to application server with login id #{user}..." } begin @session . start_session ( user , password ) rescue Exception => e logger . error ( "Login of #{user} with password #{password} was unsuccessful - #{e.message}" ) raise e end logger . info ( "Connected to application server." ) end
Connects to the database .
23,167
def retrieve_data ( key = '' ) key = key . to_s unless key . is_a? String data_array = @db . execute 'SELECT value FROM data WHERE key = ?' , key Marshal . load ( data_array [ 0 ] [ 0 ] ) unless data_array [ 0 ] . nil? end
Retrieve whatever data is stored in at key and return it!
23,168
def setup_client ( token ) client = Octokit :: Client . new ( access_token : token ) client . auto_paginate = true client end
setup an oktokit client with auto_pagination turned on so we get all the repos returned even in large organizations
23,169
def plugins raise NeedsReinstall , output if needs_reinstall? plugin_lines . map { | l | parse_line l . match ( PARSE_PLUGIN ) } . to_set end
Retrieves a Set containing all the plugins from the output
23,170
def parse_line ( match ) raise InvalidFormat . new "Couldn't parse plugin" if match . nil? Derelict :: Plugin . new * match . captures [ 0 .. 1 ] end
Parses a single line of the output into a Plugin object
23,171
def sospa ( location ) string = location [ 1 .. - 1 ] col = location [ 0 ] . to_i row = ( string . length . to_f / col ) . floor remainder = string . length % col address = [ [ nil ] * col ] * ( row + 1 ) sizes = [ row + 1 ] * remainder + [ row ] * ( col - remainder ) pos = 0 sizes . each_with_index { | size , i | size . times { | index | address [ col * index + i ] = string [ pos + index ] } pos += size } address = CGI :: unescape ( address . join ) . gsub ( '^' , '0' ) rescue raise location end
Rewrite the algorithm much much more better .
23,172
def _post_json ( path , object_to_post ) resp = @rawclient . post ( url ( path ) , JSON . dump ( object_to_post ) , { 'Content-type' => 'application/json' } ) JSON . parse ( resp . content ) end
post JSON data .
23,173
def get ( path , args = { } , response_type = nil ) response_type = SimpleSolrClient :: Response :: GenericResponse if response_type . nil? response_type . new ( _get ( path , args ) ) end
Get from solr and return a Response object of some sort
23,174
def post_json ( path , object_to_post , response_type = nil ) response_type = SimpleSolrClient :: Response :: GenericResponse if response_type . nil? response_type . new ( _post_json ( path , object_to_post ) ) end
Post an object as JSON and return a Response object
23,175
def core ( corename ) raise "Core #{corename} not found" unless cores . include? corename . to_s SimpleSolrClient :: Core . new ( @base_url , corename . to_s ) end
Get a client specific to the given core2
23,176
def new_core ( corename ) dir = temp_core_dir_setup ( corename ) args = { :wt => 'json' , :action => 'CREATE' , :name => corename , :instanceDir => dir } get ( 'admin/cores' , args ) core ( corename ) end
Create a new temporary core noinspection RubyWrongHash
23,177
def temp_core_dir_setup ( corename ) dest = Dir . mktmpdir ( "simple_solr_#{corename}_#{SecureRandom.uuid}" ) src = SAMPLE_CORE_DIR FileUtils . cp_r File . join ( src , '.' ) , dest dest end
Set up files for a temp core
23,178
def send_single_request ( method , args ) post_data = { 'jsonrpc' => JSON_RPC_VERSION , 'method' => method , 'params' => args , 'id' => self . class . make_id } . to_json resp = RestClient . post ( @url , post_data , content_type : 'application/json' , user_agent : "syncano-ruby-#{Syncano::VERSION}" ) if resp . nil? || resp . body . nil? || resp . body . empty? raise Jimson :: ClientError :: InvalidResponse . new end return resp . body rescue Exception , StandardError raise Jimson :: ClientError :: InternalError . new ( $! ) end
Overwritten send_single_request method so it now adds header with the user agent
23,179
def send_batch_request ( batch ) post_data = batch . to_json resp = RestClient . post ( @url , post_data , content_type : 'application/json' , user_agent : "syncano-ruby-#{Syncano::VERSION}" ) if resp . nil? || resp . body . nil? || resp . body . empty? raise Jimson :: ClientError :: InvalidResponse . new end return resp . body end
Overwritten send_batch_request method so it now adds header with the user agent
23,180
def send_batch batch = @batch . map ( & :first ) response = send_batch_request ( batch ) begin responses = JSON . parse ( response ) rescue raise Jimson :: ClientError :: InvalidJSON . new ( json ) end process_batch_response ( responses ) responses = @batch @batch = [ ] responses end
Overwritten send_batch method so it now returns collection of responses
23,181
def camelcase_keys ( options ) options = options . clone if options [ :destination_address ] options [ :destinationAddress ] = options [ :destination_address ] options . delete ( :destination_address ) end if options [ :notify_url ] options [ :notifyURL ] = options [ :notify_url ] options . delete ( :notify_url ) end if options [ :client_correlator ] options [ :clientCorrelator ] = options [ :client_correlator ] options . delete ( :client_correlator ) end if options [ :callback_data ] options [ :callbackData ] = options [ :callback_data ] options . delete ( :callback_data ) end options end
Camelcases the options
23,182
def build_query_string ( options ) options = camelcase_keys ( options ) query = '' options . each do | k , v | if k == :address if RUBY_VERSION . to_f >= 1.9 if v . instance_of? ( String ) v . each_line { | address | query += "#{ '&' if query != '' }address=#{CGI.escape address}" } else v . each { | address | query += "#{ '&' if query != '' }address=#{CGI.escape address}" } end else v . each { | address | query += "#{ '&' if query != '' }address=#{CGI.escape address}" } end else query += "#{ '&' if query != '' }#{k.to_s}=#{CGI.escape v}" end end query end
Builds the necessary query string
23,183
def to ( options = { } ) format = options [ :format ] . to_s mime_type = options [ :mime_type ] && options [ :mime_type ] . to_s type_uri = options [ :type_uri ] && options [ :type_uri ] . to_s base_uri = options [ :base_uri ] && options [ :base_uri ] . to_s rdf_serializer = Redland . librdf_new_serializer ( Redlander . rdf_world , format , mime_type , type_uri ) raise RedlandError , "Failed to create a new serializer" if rdf_serializer . null? begin if options [ :file ] Redland . librdf_serializer_serialize_model_to_file ( rdf_serializer , options [ :file ] , base_uri , @rdf_model ) . zero? else Redland . librdf_serializer_serialize_model_to_string ( rdf_serializer , base_uri , @rdf_model ) end ensure Redland . librdf_free_serializer ( rdf_serializer ) end end
Serialize model into a string
23,184
def start config = { } , & block @config . update ( config ) . update ( load_config ) log "Starting #{name} in the background.." logfile = get_logfile ( config ) daemonize ( logfile , get_pidfile ( config ) ) do yield ( self ) if block_given? trap ( 'TERM' ) { handle_exit } trap ( 'INT' ) { handle_exit } ( respond_to? ( :__start! ) ) ? __start! : perform ( @config ) handle_exit end end
Starts the Djinn in the background .
23,185
def run config = { } , & block @config . update ( config ) . update ( load_config ) log "Starting #{name} in the foreground.." trap ( 'TERM' ) { handle_exit } trap ( 'INT' ) { handle_exit } yield ( self ) if block_given? ( respond_to? ( :__start! ) ) ? __start! : perform ( @config ) handle_exit end
Starts the Djinn in the foreground which is often useful for testing or other noble pursuits .
23,186
def read_bits ( * args ) { } . tap do | m | args . each { | bit | m [ bit ] = @value [ bit ] } end end
Initialize the BitField with an optional value . Default is 0
23,187
def read_field ( * args ) m = 0 args . flatten . each_with_index do | bit , i | if bit . is_a? ( Integer ) m |= ( ( @value [ bit ] || 0 ) << i ) end end m end
Read the specified bit indices as a group in the order given
23,188
def parse_params ( params , key_word ) body = params . has_key? ( :path ) ? load_file ( params [ :path ] , key_word ) : params body = { key_word => body } unless body . has_key? ( key_word . to_sym ) body end
Parses given params or file and returns Hash including the given key .
23,189
def load_file ( path , key_word ) begin data = MultiJson . load ( IO . read ( File . expand_path ( path ) ) , symbolize_keys : true ) rescue RuntimeError , Errno :: ENOENT => e raise e . message rescue MultiJson :: LoadError => e raise e . message end if data . has_key? ( key_word ) data [ key_word ] . map { | k , v | data [ key_word ] [ k ] = v } if data [ key_word ] . is_a? Hash end data end
Loads a specified file and returns Hash including the given key .
23,190
def bundle_url ( name ) bundle = Bundle [ name ] raise "No such bundle: #{name}" unless bundle return bundle . paths . map { | p | asset_url ( p ) } unless Pinion . environment == "production" [ "#{@mount_point}/#{bundle.name}-#{bundle.checksum}.#{bundle.extension}" ] end
Return the bundle url . In production the single bundled result is produced ; otherwise each individual asset_url is returned .
23,191
def set_tags ( tag_list , options = { } ) options . reverse_merge! :context => nil , :tagger => nil , :downcase => true , :delimiter => ',' if block_given? tags = yield ( klass ) else tags = EasyTag :: Tag . compact_tag_list ( tag_list , options . slice ( :downcase , :delimiter ) ) end context = compact_context ( options [ :context ] ) tagger = compact_tagger ( options [ :tagger ] ) self . taggings . where ( :tag_context_id => context . try ( :id ) , :tagger_id => tagger . try ( :id ) ) . destroy_all if tags tags . each do | t | tag = EasyTag :: Tag . where ( :name => t ) . first_or_create raise SimgleTag :: InvalidTag if tag . nil? self . taggings . where ( :tagger_id => tagger . try ( :id ) , :tag_context_id => context . try ( :id ) , :tag_id => tag . id ) . first_or_create end end end
end of class methods
23,192
def external = ( externals_list ) @external = [ ] externals_list . each { | external_id | @external << Rlocu2 :: ExternalID . new ( id : external_id [ 'id' ] , url : external_id [ 'url' ] , mobile_url : external_id [ 'mobile_url' ] ) } end
BUILD sub structures
23,193
def forward_lines ( size = 10 ) file = @file result = "" while result . scan ( / \r \n \r \n / ) . size < size && ! file . eof? result += file . gets end result end
get forward lines
23,194
def ensure_valid_role_for_commentable allowed_roles = commentable . class . commentable_options [ :roles ] if allowed_roles . any? errors . add ( :role , :invalid ) unless allowed_roles . include? ( self . role ) else errors . add ( :role , :invalid ) unless self . role . blank? end end
Make sure that the value of the role attribute is a valid role for the commentable .
23,195
def route ( activity ) raise "Activity must be stored before routing: #{activity.inspect}" if ! activity . stored? result = 0 activity . run_callbacks ( :route ) do Activr . registry . timelines . values . each do | timeline_class | next unless timeline_class . should_route_activity? ( activity ) self . recipients_for_timeline ( timeline_class , activity ) . each do | recipient , route | result += 1 timeline = timeline_class . new ( recipient ) if timeline . should_handle_activity? ( activity , route ) Activr :: Async . hook ( :timeline_handle , timeline , activity , route ) end end end end result end
Route an activity
23,196
def recipients_for_timeline ( timeline_class , activity ) result = { } routes = timeline_class . routes_for_activity ( activity . class ) routes . each do | route | route . resolve ( activity ) . each do | recipient | recipient_id = timeline_class . recipient_id ( recipient ) if result [ recipient_id ] . nil? result [ recipient_id ] = { :rcpt => recipient , :route => route } end end end result . inject ( { } ) do | memo , ( recipient_id , infos ) | memo [ infos [ :rcpt ] ] = infos [ :route ] memo end end
Find recipients for given activity in given timeline
23,197
def get_and_merge_dojo_props! add_dojo_options_to_dojo_props if object . id . present? add_dojo_compliant_id else input_html_options [ "id" ] = nil end input_html_options [ :' ' ] = SimpleFormDojo :: FormBuilder . encode_as_dojo_props ( @dojo_props ) if ! @dojo_props . blank? end
Retrieves and merges all dojo_props
23,198
def store ( data ) request_data = { :value => data } request_data [ :expire ] = @expire if @expire request = prepare_request :POST , request_data . to_json Response . new ( execute_request ( request ) ) end
Initialize a client to a SAM node hosted at a specific url
23,199
def store_file ( file_content , filename , type = :file ) store ( type => Base64 . encode64 ( file_content ) , :filename => filename ) end
Store a file in SAM . If the file will be used by other NSI s service you should pass an additional type parameter .