idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
24,800
def find_prefix ( doc ) return config [ 'prefix' ] if config && config [ 'prefix' ] ns_prefix_attribute = doc . namespaces . find do | prefix , ns | ns . to_s == namespace . to_s && prefix != 'xmlns' end ns_prefix_attribute ? ns_prefix_attribute [ 0 ] . split ( ':' ) . last : "Unknown" end
Find the namespace prefix by searching through the namespaces for the TNS
24,801
def each return to_enum unless block_given? each_explicit_key do | * key | next if default? ( * key ) yield key , get ( * key ) end end
Expensive . Use only for debug
24,802
def include? date result = false walk { | elements | break result = true if elements . include? date } return result if ! result || date . class == Date || times . nil? times . include? date end
Returns true if the Date or DateTime passed is included in the parsed Dates or DateTimes
24,803
def define desc "Generate rokko documentation" task @name do if @options [ :generate_index ] readme_source = @sources . detect { | f | File . basename ( f ) =~ / \. /i } readme = readme_source ? File . read ( @sources . delete ( readme_source ) ) : '' end @sources . each do | filename | rokko = Rokko . new ( filename , @sources , @options ) out_dest = File . join ( @dest , filename . sub ( Regexp . new ( "#{File.extname(filename)}$" ) , ".html" ) ) puts "rokko: #{filename} -> #{out_dest}" FileUtils . mkdir_p File . dirname ( out_dest ) File . open ( out_dest , 'wb' ) { | fd | fd . write ( rokko . to_html ) } end if @options [ :generate_index ] require 'rokko/index_layout' out_dest = File . join ( @dest , 'index.html' ) puts "rokko: #{out_dest}" File . open ( out_dest , 'wb' ) { | fd | fd . write ( IndexLayout . new ( @sources , readme , @options ) . render ) } end if @options [ :index ] && source_index = @sources . find { | s | s == @options [ :index ] } rokko = Rokko . new ( source_index , @sources , @options . merge ( preserve_urls : true ) ) out_dest = File . join ( @dest , 'index.html' ) puts "rokko: #{source_index} -> index.html" File . open ( out_dest , 'wb' ) { | fd | fd . write ( rokko . to_html ) } end end end
Actually setup the task
24,804
def new ( item , total ) data = read_file data [ item ] = { 'total' => total . to_i , 'min' => options [ :minimum ] . to_i , 'url' => options [ :url ] || read_config [ 'url' ] , 'checked' => Time . now } write_file ( data ) end
Creates a new item in the inventory
24,805
def delete ( item ) data = read_file match_name ( item ) data . delete ( @@item ) write_file ( data ) end
Deletes an item from the inventory . Stocker will attempt a fuzzy match of the item name .
24,806
def check links = [ ] read_file . each do | key , value | value [ "checked" ] = Time . now if value [ "total" ] < value [ "min" ] puts "You're running low on #{key}!" links << key end end links . uniq! links . each { | link | buy ( link ) } end
Checks the total number of items on hand against their acceptable minimum values and opens the URLs of any items running low in stock .
24,807
def total ( item , total ) data = read_file match_name ( item ) data [ @@item ] [ "total" ] = total . to_i time ( item ) write_file ( data ) end
Set total of existing item in Stocker s inventory
24,808
def url ( item , url ) data = read_file match_name ( item ) data [ @@item ] [ "url" ] = url time ( item ) write_file ( data ) end
Set URL of existing item in Stocker s inventory
24,809
def min ( item , min ) data = read_file match_name ( item ) data [ @@item ] [ "min" ] = min . to_i write_file ( data ) end
Set minimum acceptable amount of existing inventory item
24,810
def list begin @header = [ [ "" , "" ] ] @green = [ ] @yellow = [ ] @yellow2 = [ ] @green2 = [ ] @red = [ ] @red2 = [ ] read_file . each do | key , value | if value [ 'total' ] > value [ 'min' ] @green += [ [ key . titlecase , value [ 'total' ] , value [ 'total' ] - value [ 'min' ] ] ] elsif value [ 'total' ] == value [ 'min' ] @yellow += [ [ key . titlecase , value [ 'total' ] , value [ 'total' ] - value [ 'min' ] ] ] else @red += [ [ key . titlecase , value [ 'total' ] , value [ 'total' ] - value [ 'min' ] ] ] end end @green . sort_by! { | a , b , c | c } @yellow . sort_by! { | a , b , c | c } @red . sort_by! { | a , b , c | c } @green . reverse! @yellow . reverse! @red . reverse! @green . each { | a , b | @green2 += [ [ set_color ( a , :green ) , set_color ( b , :green ) ] ] } @yellow . each { | a , b | @yellow2 += [ [ set_color ( a , :yellow ) , set_color ( b , :yellow ) ] ] } @red . each { | a , b | @red2 += [ [ set_color ( a , :red ) , set_color ( b , :red ) ] ] } print_table ( @header + @green2 + @yellow2 + @red2 , { indent : 2 } ) rescue Exception => e puts "Inventory empty" end end
Print a list of all inventory items . Green items are well stocked . Yellow items are at minimum acceptable total . Red items are below minimum acceptable total .
24,811
def parse_file ( path , target_ext = nil ) return nil if path . nil? return nil if File . directory? path _load_from_file path , target_ext end
Not used internally but useful for external usage
24,812
def build_pointer_array ( array , type ) buffer = FFI :: MemoryPointer . new type , array . length buffer . send ( "write_array_of_#{type}" . to_sym , array ) buffer end
Shortcut to build a C array from a Ruby array
24,813
def has_default_association * names , & default_proc opts = names . extract_options! opts . assert_valid_keys ( :eager ) names . each do | name | create_default_association ( name , default_proc ) add_default_association_callback ( name ) if opts [ :eager ] end end
Declare default associations for ActiveRecord models .
24,814
def status ( commit , ignore : [ ] ) tree = get_object ( commit . tree ) unless commit . nil? Utils :: Status . compare_tree_and_store tree , staging_area , object_store , ignore : ignore end
Return new changed and deleted files compared to a specific commit and the staging area .
24,815
def commit_status ( base_commit , new_commit , ignore : [ ] ) base_tree = get_object ( base_commit . tree ) unless base_commit . nil? new_tree = get_object ( new_commit . tree ) unless new_commit . nil? Utils :: Status . compare_trees base_tree , new_tree , object_store , ignore : ignore end
Return new changed and deleted files by comparing two commits .
24,816
def merge ( commit_one , commit_two ) common_ancestor = commit_one . common_ancestor ( commit_two , object_store ) commit_one_files = Hash [ get_object ( commit_one . tree ) . all_files ( object_store ) . to_a ] commit_two_files = Hash [ get_object ( commit_two . tree ) . all_files ( object_store ) . to_a ] if common_ancestor . nil? ancestor_files = { } else ancestor_files = Hash [ get_object ( common_ancestor . tree ) . all_files ( object_store ) . to_a ] end all_files = commit_one_files . keys | commit_two_files . keys | ancestor_files . keys merged = [ ] conflicted = [ ] all_files . each do | file | ancestor = ancestor_files . key? ( file ) ? get_object ( ancestor_files [ file ] ) . content . lines : [ ] file_one = commit_one_files . key? ( file ) ? get_object ( commit_one_files [ file ] ) . content . lines : [ ] file_two = commit_two_files . key? ( file ) ? get_object ( commit_two_files [ file ] ) . content . lines : [ ] diff = VCSToolkit :: Merge . three_way ancestor , file_one , file_two if diff . has_conflicts? conflicted << file elsif diff . has_changes? merged << file end content = diff . new_content ( "<<<<< #{commit_one.id}\n" , ">>>>> #{commit_two.id}\n" , "=====\n" ) if content . empty? staging_area . delete_file file if staging_area . file? file else staging_area . store file , content . join ( '' ) end end { merged : merged , conflicted : conflicted } end
Merge two commits and save the changes to the staging area .
24,817
def file_difference ( file_path , commit ) if staging_area . file? file_path file_lines = staging_area . fetch ( file_path ) . lines file_lines . last << "\n" unless file_lines . last . nil? or file_lines . last . end_with? "\n" else file_lines = [ ] end tree = get_object commit . tree blob_name_and_id = tree . all_files ( object_store ) . find { | file , _ | file_path == file } if blob_name_and_id . nil? blob_lines = [ ] else blob = get_object blob_name_and_id . last blob_lines = blob . content . lines blob_lines . last << "\n" unless blob_lines . last . nil? or blob_lines . last . end_with? "\n" end Diff . from_sequences blob_lines , file_lines end
Return a list of changes between a file in the staging area and a specific commit .
24,818
def me_url ( provider , params = nil ) connection . build_url ( options [ :me_url ] . sub ( / / , provider ) , params ) . to_s end
Instantiate a new OAuth 2 . 0 client using the Client ID and Client Secret registered to your application .
24,819
def included ( plugin_receiver ) return if plugin_receiver . include? ( self . much_plugin_included_detector ) plugin_receiver . send ( :include , self . much_plugin_included_detector ) self . much_plugin_included_hooks . each do | hook | plugin_receiver . class_eval ( & hook ) end end
install an included hook that first checks if this plugin s receiver mixin has already been included . If it has not been include the receiver mixin and run all of the plugin_included hooks
24,820
def to_hash _copy = { } @table . each { | key , value | _copy [ key ] = value . is_a? ( HashStruct ) ? value . to_hash : value } _copy end
Generates a nested Hash object which is a copy of existing configuration
24,821
def check_hash_for_conflicts ( hash ) raise HashArgumentError , 'It must be a hash' unless hash . is_a? ( Hash ) unless ( conflicts = self . public_methods & hash . keys . map ( & :to_sym ) ) . empty? raise HashArgumentError , "Rename keys in order to avoid conflicts with internal calls: #{conflicts.join(', ')}" end end
Checks if provided option is a hash and if the keys are not in confict with OpenStruct public methods .
24,822
def get_resource ( url , resource_class , params = { } ) resource_class . from_hash ( get ( url , params ) , client : self ) end
If an API endpoint returns a single resource not an Array of resources we want to use this .
24,823
def get_resources ( url , resource_class , params = { } ) get ( url , params ) . map do | result | resource_class . from_hash ( result , client : self ) end end
If an API endpoint returns an Array of resources we want to use this .
24,824
def audit_relationship_enabled ( opts = { } ) include InstanceMethods class_attribute :audit_enabled_models class_attribute :field_names self . audit_enabled_models = gather_models ( opts ) self . field_names = gather_assoc_fields_for_auditing ( opts [ :fields ] ) after_create :audit_relationship_create before_update :audit_relationship_update before_destroy :audit_relationship_destroy end
AuditRelationship creates audits for a has_many relationship .
24,825
def delegate ( method , & convproc ) convproc ||= lambda { | v , t | v . send ( method ) } upon ( lambda { | v , t | v . respond_to? ( method ) } , convproc ) end
Adds an upon rule that works by delegation if the value responds to method .
24,826
def coercion ( source , target = main_target_domain , converter = nil , & convproc ) @rules . send ( @appender , [ source , target , converter || convproc ] ) self end
Adds a coercion rule from a source to a target domain .
24,827
def coerce ( value , target_domain = main_target_domain ) return value if belongs_to? ( value , target_domain ) error = nil each_rule do | from , to , converter | next unless from . nil? or belongs_to? ( value , from , target_domain ) begin catch ( :nextrule ) do if to . nil? or subdomain? ( to , target_domain ) got = convert ( value , target_domain , converter ) return got elsif subdomain? ( target_domain , to ) got = convert ( value , target_domain , converter ) return got if belongs_to? ( got , target_domain ) end end rescue => ex error = ex unless error end end error_handler . call ( value , target_domain , error ) end
Coerces value to an element of target_domain
24,828
def belongs_to? ( value , domain , target_domain = domain ) if domain . is_a? ( Proc ) and domain . arity == 2 domain . call ( value , target_domain ) else domain . respond_to? ( :=== ) && ( domain === value ) end end
Returns true if value can be considered as a valid element of the domain domain false otherwise .
24,829
def endpoint ( type , opts = { } ) options = { :extname => @name , :extdesc => "" , :extauthor => @user . name , :force_build => 'N' , :contents => "compiled" , :format => 'json' , :env => 'prod' } case type . to_s when 'bookmarklet' options [ :runtime ] = "init.kobj.net/js/shared/kobj-static.js" when 'info_card' options [ :image_url ] = image_url ( 'icard' ) options [ :datasets ] = "" when 'ie' options [ :appguid ] = @guid end options . merge! ( opts ) puts "ENDPOINT PARAMS: (#{type}): #{options.inspect}" if $DEBUG return @api . post_app_generate ( @application_id , type . to_s , options ) end
Returns an endpoint
24,830
def handcart_show_path ( handcart ) if Handcart . handcart_show_path . present? "/#{Handcart.handcart_show_path}/#{handcart.to_param}" else if Rails . application . routes . url_helpers . respond_to? ( "#{Handcart.handcart_class.model_name.singular}_path" . to_sym ) Rails . application . routes . url_helpers . send ( "#{Handcart.handcart_class.model_name.singular}_path" , handcart . to_param ) else "/#{Handcart.handcart_class.model_name.route_key}/#{handcart.to_param}" end end end
Try to formulate a path to view the handcart show page
24,831
def destroy_relay_field child_field = LatoBlog :: PostField . find_by ( id : params [ :id ] ) @post_field = child_field . post_field unless @post_field @error = true respond_to { | r | r . js } end unless child_field . destroy @error = true respond_to { | r | r . js } end @error = false respond_to { | r | r . js } end
This function destroy a post for the field .
24,832
def start if File . exist? 'config.yml' Notifier . notify "Watching for changes to Shopify Theme" else data = <<-EOF EOF File . open ( './config.yml' , "w" ) { | file | file . write data } Notifier . notify "Created config.yml. Remember to add your Shopify details to it." end end
VERSION = 0 . 0 . 1 Called once when Guard starts . Please override initialize method to init stuff .
24,833
def create ( global_options , options ) status , body = project_create ( global_options , options ) if status == 201 save_message ( create_success_message ( body ) ) true else parse_message ( body ) false end end
Creates a new project on fenton server by sending a post request with json from the command line to create the project
24,834
def project_json ( options ) { project : { name : options [ :name ] , description : options [ :description ] , passphrase : options [ :passphrase ] , key : options [ :key ] , organization : options [ :organization ] } } . to_json end
Formulates the project json for the post request
24,835
def reload ( url = nil , parameters = { } ) httparty = self . class . get ( url || self [ :@url ] , StorageRoom . request_options . merge ( parameters ) ) hash = httparty . parsed_response . first [ 1 ] reset! set_from_response_data ( hash ) true end
Reload an object from the API . Optionally pass an URL .
24,836
def debug raise ArgumentError , "RDO::Connection#debug requires a block" unless block_given? reset , logger . level = logger . level , Logger :: DEBUG yield ensure logger . level = reset end
Use debug log level in the context of a block .
24,837
def normalize_options ( options ) case options when Hash Hash [ options . map { | k , v | [ k . respond_to? ( :to_sym ) ? k . to_sym : k , v ] } ] . tap do | opts | opts [ :driver ] = opts [ :driver ] . to_s if opts [ :driver ] end when String , URI parse_connection_uri ( options ) else raise RDO :: Exception , "Unsupported connection argument format: #{options.class.name}" end end
Normalizes the given options String or Hash into a Symbol - keyed Hash .
24,838
def create_migrations Dir [ "#{self.class.source_root}/migrations/*.rb" ] . sort . each do | filepath | name = File . basename ( filepath ) template "migrations/#{name}" , "db/migrate/#{name}" sleep 1 end end
Generator Code . Remember this is just suped - up Thor so methods are executed in order
24,839
def to_native ( query , ctx ) return 0 if query . nil? flat_query = [ query ] . flatten flat_query . inject ( 0 ) do | val , o | case o when Symbol v = @kv_map [ o ] raise ArgumentError , "invalid bitmask value, #{o.inspect}" unless v val |= v when Integer val |= o when -> ( obj ) { obj . respond_to? ( :to_int ) } val |= o . to_int else raise ArgumentError , "invalid bitmask value, #{o.inspect}" end end end
Get the native value of a bitmask
24,840
def render results , column_widths = [ ] , get_column_widths rows . times { | row_index | results << render_row ( row_index , column_widths ) } @page_data . clear results end
Render the page as an array of strings .
24,841
def add_a_row new_rows = rows + 1 pool , @page_data = @page_data . flatten , [ ] until pool . empty? @page_data << pool . shift ( new_rows ) end end
Add a row to the page moving items as needed .
24,842
def call ( env ) return receive ( env ) if env [ "PATH_INFO" ] == RECEIVE_PATH return retrieve ( env ) if env [ "PATH_INFO" ] == RETRIEVE_PATH @app . call ( env ) end
Create a new instance of the middleware .
24,843
def store_iou ( pgt_iou , pgt ) pstore = open_pstore pstore . transaction do pstore [ pgt_iou ] = pgt end end
Associates the given PGTIOU and PGT .
24,844
def resolve_iou ( pgt_iou ) pstore = open_pstore pgt = nil pstore . transaction do pgt = pstore [ pgt_iou ] pstore . delete ( pgt_iou ) if pgt end pgt end
Finds the PGT for the given PGTIOU . If there isn t one it returns nil . If there is one it deletes it from the store before returning it .
24,845
def withdraw ( coin , params = { } ) raise ConfigurationError . new ( 'No coin type specified' ) unless coin raise ConfigurationError . new ( 'Invalid coin type specified' ) unless Coin . valid? ( coin ) request ( :post , "/#{coin}_withdrawal" , params ) end
Withdrawal of the specified coin type .
24,846
def user_transactions ( params = { } ) request ( :post , '/user_transactions' , params ) . each { | t | t . id = t . id . to_s } end
Return a list of user transactions .
24,847
def label_width if ! @label_width then @label_width = @samples . find_all { | s | Sample === s } . max { | a , b | a . label . length <=> b . label . length } . label . length + 1 @label_width = 40 if @label_width < 40 end return @label_width end
Calculate the label padding taking all labels into account
24,848
def delete ( filename ) within_source_root do FileUtils . mkdir_p File . dirname ( filename ) FileUtils . touch filename end generate { expect ( File ) . not_to exist ( filename ) } end
Makes sure that the generator deletes the named file . This is done by first ensuring that the file exists in the first place and then ensuring that it does not exist after the generator completes its run .
24,849
def get_client init_opts = { client_id : @CLIENT_ID , client_secret : @CLIENT_SECRET } if username? and password? init_opts [ :username ] = @USERNAME init_opts [ :password ] = @PASSWORD end Soundcloud . new ( init_opts ) end
Defines a Soundcloud client object
24,850
def get_drop ( url ) sc_track = client . get ( '/resolve' , url : url ) SoundDrop :: Drop . new ( client : client , track : sc_track ) end
Returns a Drop object that contains useful track information .
24,851
def format_backtrace ( backtrace ) backtrace ||= [ ] backtrace [ 0 .. BACKTRACE_LINES ] . collect do | line | "#{line.gsub(/\n|\`|\'/, '')}" . split ( / / ) . last ( MAX_LINE_LENGTH ) . join end end
remove backticks single quotes \ n and ensure each line is reasonably small
24,852
def validate ( expected_digest ) if not bundle_exists? then raise BundleNotFound . new ( "repo = #{@repo}; bundle = #{@bundle}" ) end if not command_exists? then raise CommandNotFound . new ( "repo = #{@repo}; bundle = #{@bundle}; command = #{@command}" ) end if self . digest != expected_digest then raise BundleNotFound , "digest does not match ('#{self.digest}' != '#{expected_digest}')" , caller end return true end
Create new CommandSpec
24,853
def manifest if File . exists? ( manifest_file ) && File . readable? ( manifest_file ) then MultiJson . load ( File . read ( manifest_file ) ) else { } end end
Retrieve the command s Manifest loading it from disk if necessary If no Manifest is available returns an empty hash
24,854
def to_s s = [ ] s << "CommandSpec:#{self.object_id}" s << " digest: #{self.digest}" s << " repo: #{self.repo}" s << " bundle: #{self.bundle}" s << " command: #{self.command}" s << " args: #{self.args}" s << " user: #{self.user}" s << " group: #{self.group}" s << " env: " + ( self . env . nil? ( ) ? "" : MultiJson . dump ( self . env ) ) s << " stdin: " + Debug . pretty_str ( stdin ) s . join ( "\n" ) end
Convert object to String useful for debugging
24,855
def check_category_father_circular_dependency return unless self . lato_blog_category_id all_children = self . get_all_category_children same_children = all_children . select { | child | child . id === self . lato_blog_category_id } if same_children . length > 0 errors . add ( 'Category father' , 'can not be a children of the category' ) throw :abort end end
This function check the category parent of the category do not create a circular dependency .
24,856
def check_lato_blog_category_parent category_parent = LatoBlog :: CategoryParent . find_by ( id : lato_blog_category_parent_id ) if ! category_parent errors . add ( 'Category parent' , 'not exist for the category' ) throw :abort return end same_language_category = category_parent . categories . find_by ( meta_language : meta_language ) if same_language_category && same_language_category . id != id errors . add ( 'Category parent' , 'has another category for the same language' ) throw :abort return end end
This function check that the category parent exist and has not others categories for the same language .
24,857
def start_server ( port = 9886 ) @thread = Thread . new do Server . prepare Server . run! :port => port end sleep ( 1 ) self end
Start the nsi . videogranulate fake server
24,858
def links rows . map do | row | attributes = Link :: ATTRS . dup - [ :url ] Link . new ( row . shift , Hash [ row . map { | v | [ attributes . shift , v ] } ] ) end end
Links returned as Link objects
24,859
def to_app Rack :: Builder . new . tap do | app | app . use Middleware :: Static , machined . output_path app . use Middleware :: RootIndex app . run Rack :: URLMap . new ( sprockets_map ) end end
Creates a Rack app with the current Machined environment configuration .
24,860
def twitter_hashtag_streams ( campaign_id , options = { } ) response = connection . get do | req | req . url "campaigns/#{campaign_id}/twitter_hashtag_streams" , options end return_error_or_body ( response ) end
Retrieve Twitter Hashtag Streams for a campaign
24,861
def twitter_hashtag_stream ( campaign_id , id , options = { } ) response = connection . get do | req | req . url "campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}" , options end return_error_or_body ( response ) end
Retrieve Single Twitter Hashtag Stream for a campaign
24,862
def root ( options = { } ) if options . is_a? ( Symbol ) if source_route = @set . named_routes . routes [ options ] options = source_route . defaults . merge ( { :conditions => source_route . conditions } ) end end named_route ( "root" , '' , options ) end
Creates a named route called root for matching the root level request .
24,863
def index core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :categories ] ) @categories = LatoBlog :: Category . where ( meta_language : cookies [ :lato_blog__current_language ] ) . order ( 'title ASC' ) @widget_index_categories = core__widgets_index ( @categories , search : 'title' , pagination : 10 ) end
This function shows the list of possible categories .
24,864
def new core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :categories_new ] ) @category = LatoBlog :: Category . new if params [ :language ] set_current_language params [ :language ] end if params [ :parent ] @category_parent = LatoBlog :: CategoryParent . find_by ( id : params [ :parent ] ) end fetch_external_objects end
This function shows the view to create a new category .
24,865
def create @category = LatoBlog :: Category . new ( new_category_params ) if ! @category . save flash [ :danger ] = @category . errors . full_messages . to_sentence redirect_to lato_blog . new_category_path return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :category_create_success ] redirect_to lato_blog . category_path ( @category . id ) end
This function creates a new category .
24,866
def edit core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :categories_edit ] ) @category = LatoBlog :: Category . find_by ( id : params [ :id ] ) return unless check_category_presence if @category . meta_language != cookies [ :lato_blog__current_language ] set_current_language @category . meta_language end fetch_external_objects end
This function show the view to edit a category .
24,867
def update @category = LatoBlog :: Category . find_by ( id : params [ :id ] ) return unless check_category_presence if ! @category . update ( edit_category_params ) flash [ :danger ] = @category . errors . full_messages . to_sentence redirect_to lato_blog . edit_category_path ( @category . id ) return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :category_update_success ] redirect_to lato_blog . category_path ( @category . id ) end
This function updates a category .
24,868
def destroy @category = LatoBlog :: Category . find_by ( id : params [ :id ] ) return unless check_category_presence if ! @category . destroy flash [ :danger ] = @category . category_parent . errors . full_messages . to_sentence redirect_to lato_blog . edit_category_path ( @category . id ) return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :category_destroy_success ] redirect_to lato_blog . categories_path ( status : 'deleted' ) end
This function destroyes a category .
24,869
def encode ( object , options = { } ) object = object . to_a if defined? ( ActiveRecord :: Relation ) && object . is_a? ( ActiveRecord :: Relation ) fields_to_hash ( options ) if object . is_a? ( Array ) if options [ :fields ] encode_partial_array ( object , options ) else encode_array ( object , options ) end elsif options [ :fields ] encode_partial_single ( object , options ) else encode_single ( object , options ) end end
Creates a new XML - encoder with a root tag named after + root_name + .
24,870
def extend_off_air ( programs , program , stop ) prev = programs . pop + program program = prev . program occurrence = prev . occurrence remainder = time_left ( occurrence . start_time , occurrence . end_time , stop ) [ program , occurrence , remainder ] end
Extends the previous Off Air schedule
24,871
def outgoing ( message , callback ) return callback . call ( message ) if %r{ } =~ message [ 'channel' ] message [ 'ext' ] ||= { } signature = OpenSSL :: HMAC . digest ( 'sha256' , @key , message [ 'data' ] ) message [ 'ext' ] [ 'signature' ] = Base64 . encode64 ( signature ) return callback . call ( message ) end
Initializes the signer with a secret key .
24,872
def extract ( path ) files = files_in_path ( path ) supported_files = filter_files ( files ) parse_files ( supported_files ) end
Extract strings from files in the given path .
24,873
def validate ( input ) ( check_exists ( required_inputs , input ) && check_format ( input_formats , input ) ) || ( raise Errors :: InvalidInput , "Invalid input for #{self.class.name}" ) end
Checks for required inputs and input formats that the adapter will need to process the search .
24,874
def check_exists ( required , input ) required . inject ( true ) do | result , key | input [ key ] && result end end
Required keys must exist in the input hash and must have a non - nil non - empty value .
24,875
def get_files return @dir . values . map do | dir | next get_files_recursively_from dir end . reject { | x | ! x } . flatten end
Returns all necessary filepaths .
24,876
def deserialize_object ( definition , hash ) return nil if hash . nil? result = definition . new result . __fields . each do | field | name = field . key_json || name_to_json ( field . sym ) if field . options [ :as ] == :list value = deserialize_list ( hash [ name ] , field ) elsif field . options [ :as ] == :dto value = deserialize_object ( field . options [ :of ] , hash [ name ] ) else value = hash [ name ] end next if value . nil? result . send ( "#{field.key_ruby}=" , value ) end result end
IF engine contains deserialization logic we can no more unit test the converters . Seems like the conversion logic must be outsourced to its respective converter
24,877
def reduce! @reduced_characteristics = if @reduced_characteristics . keys . length < 2 { } else most_restrictive_characteristic = @reduced_characteristics . keys . max_by do | key | conditions = CohortScope . conditions_for @reduced_characteristics . except ( key ) @active_record_relation . where ( conditions ) . count end @reduced_characteristics . except most_restrictive_characteristic end end
Reduce characteristics by removing them one by one and counting the results .
24,878
def pull name , source , dest , kwargs = { } packages = kwargs . arg :packages , [ ] deps = kwargs . arg :deps , true remove = kwargs . arg :remove , true if packages . length == 0 raise AptlyError . new "1 or more package names are required" end cmd = 'aptly snapshot pull' cmd += ' -no-deps' if ! deps cmd += ' -no-remove' if ! remove cmd += " #{name.quote} #{source.quote} #{dest.quote}" if ! packages . empty? packages . each { | p | cmd += " #{p.quote}" } end Aptly :: runcmd cmd Aptly :: Snapshot . new dest end
Pull packages from a snapshot into another creating a new snapshot .
24,879
def pull_from source , dest , kwargs = { } packages = kwargs . arg :packages , [ ] deps = kwargs . arg :deps , true remove = kwargs . arg :remove , true pull @name , source , dest , :packages => packages , :deps => deps , :remove => remove end
Shortcut method to pull packages to the current snapshot
24,880
def exists? ( vm_name = nil ) return ( vm_names . count > 0 ) if vm_name . nil? vm_names . include? vm_name . to_sym end
Determines if a particular virtual machine exists in the output
24,881
def state ( vm_name ) unless states . include? vm_name . to_sym raise Derelict :: VirtualMachine :: NotFound . new vm_name end states [ vm_name . to_sym ] end
Determines the state of a particular virtual machine
24,882
def vm_lines output . match ( PARSE_LIST_FROM_OUTPUT ) . tap { | list | logger . debug "Parsing VM list from output using #{description}" raise InvalidFormat . new "Couldn't find VM list" if list . nil? } . captures [ 0 ] . lines end
Retrieves the virtual machine list section of the output
24,883
def get_opts ( db_uri ) uri = URI . parse ( db_uri ) { :host => uri . host , :port => uri . port , :user => uri . user , :password => uri . password , :db => uri . path . gsub ( '/' , '' ) } end
Initialize a ne DB object .
24,884
def dump ( db , path ) Mongolicious . logger . info ( "Dumping database #{db[:db]}" ) cmd = "mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}" cmd << " -u '#{db[:user]}' -p '#{db[:password]}'" unless ( db [ :user ] . nil? || db [ :user ] . empty? ) cmd << " > /dev/null" system ( cmd ) raise "Error while backuing up #{db[:db]}" if $? . to_i != 0 end
Dump database using mongodump .
24,885
def run ( * args ) optparse ( * args ) options = { :env => :production , :host => @host , :port => @port } options . merge! ( :server => @handler ) if @handler App . run! ( options ) end
Runs the runner .
24,886
def messages ( which = "ALL" ) cmd ( 'AT+CPMS="MT"' ) sms = cmd ( 'AT+CMGL="%s"' % which ) msgs = sms . scan ( / \+ \: \s \d \, \, \" \" \, \, \" \" \n / ) return nil unless msgs msgs . collect! { | msg | Biju :: Sms . new ( :id => msg [ 0 ] , :phone_number => msg [ 1 ] , :datetime => msg [ 2 ] , :message => msg [ 3 ] . chomp ) } end
Return an Array of Sms if there is messages nad return nil if not .
24,887
def send_smtp ( mail ) smtp = Net :: SMTP . new ( SMTP_SERVER , SMTP_PORT ) smtp . enable_starttls_auto secret = { :consumer_key => SMTP_CONSUMER_KEY , :consumer_secret => SMTP_CONSUMER_SECRET , :token => @email_credentials [ :smtp_oauth_token ] , :token_secret => @email_credentials [ :smtp_oauth_token_secret ] } smtp . start ( SMTP_HOST , @email_credentials [ :email ] , secret , :xoauth ) do | session | print "Sending message..." session . send_message ( mail . encoded , mail . from_addrs . first , mail . destinations ) puts ".sent!" end end
Use gmail_xoauth to send email
24,888
def render_404_public_file! ( file_name ) four_oh_four_path = File . expand_path ( "#{file_name}.html" , settings . public_dir ) return unless File . file? ( four_oh_four_path ) send_file four_oh_four_path , status : 404 end
Given a file name attempts to send an public 404 file if it exists and halt
24,889
def render_404_template! ( template_name ) VIEW_TEMPLATE_ENGINES . each do | engine , extension | @preferred_extension = extension . to_s find_template ( settings . views , template_name , engine ) do | file | next unless File . file? ( file ) halt send ( extension , template_name . to_sym , layout : false ) end end end
Given a template name and with a prioritized list of template engines attempts to render a 404 template if one exists and halt .
24,890
def render_javascript_template! ( uri_path ) javascript_match = File . join ( settings . javascripts , "*" ) javascript_path = File . expand_path ( uri_path , settings . javascripts ) return unless File . fnmatch ( javascript_match , javascript_path ) JAVASCRIPT_TEMPLATE_ENGINES . each do | engine , extension | @preferred_extension = extension . to_s find_template ( settings . javascripts , uri_path , engine ) do | file | next unless File . file? ( file ) halt send ( extension , uri_path . to_sym , views : settings . javascripts ) end end end
Given a URI path attempts to render a JavaScript template if it exists and halt
24,891
def render_stylesheet_template! ( uri_path ) stylesheet_match = File . join ( settings . stylesheets , "*" ) stylesheet_path = File . expand_path ( uri_path , settings . stylesheets ) return unless File . fnmatch ( stylesheet_match , stylesheet_path ) STYLESHEET_TEMPLATE_ENGINES . each do | engine , extension | @preferred_extension = extension . to_s find_template ( settings . stylesheets , uri_path , engine ) do | file | next unless File . file? ( file ) halt send ( extension , uri_path . to_sym , views : settings . stylesheets ) end end end
Given a URI path attempts to render a stylesheet template if it exists and halt
24,892
def render_index_file! ( uri_path ) return unless URI . directory? ( uri_path ) index_match = File . join ( settings . public_dir , "*" ) index_file_path = File . expand_path ( uri_path + "index.html" , settings . public_dir ) return unless File . fnmatch ( index_match , index_file_path ) return unless File . file? ( index_file_path ) send_file index_file_path end
Given a URI path attempts to send an index . html file if it exists and halt
24,893
def render_content_page! ( uri_path ) uri_path += "index" if URI . directory? ( uri_path ) content_match = File . join ( settings . content , "*" ) content_page_path = File . expand_path ( uri_path , settings . content ) return unless File . fnmatch ( content_match , content_page_path ) begin content_page = find_content_page ( uri_path ) rescue ContentPageNotFound return end view_template_path = File . expand_path ( content_page . view , settings . views ) begin engine = VIEW_TEMPLATE_ENGINES . fetch ( Tilt [ content_page . view ] ) rescue KeyError message = "Cannot find registered engine for view template file -- #{view_template_path}" raise RegisteredEngineNotFound , message end begin halt send ( engine , content_page . view . to_s . templatize , locals : { page : content_page } ) rescue Errno :: ENOENT message = "Cannot find view template file -- #{view_template_path}" raise ViewTemplateNotFound , message end end
Given a URI path attempts to render a content page if it exists and halt
24,894
def find_content_page ( uri_path ) ContentPage :: TEMPLATE_ENGINES . each do | engine , extension | @preferred_extension = extension . to_s find_template ( settings . content , uri_path , engine ) do | file | next unless File . file? ( file ) return ContentPage . new ( data : File . read ( file ) , engine : engine ) end end raise ContentPageNotFound , "Cannot find content page for path -- #{uri_path}" end
Given a URI path creates a new ContentPage instance by searching for and reading a content file from disk . Content files are searched consecutively until a page with a supported content page template engine is found .
24,895
def factory_build_for_store ( atts_hash , identifier_conditions = { } , full_data_object = { } , & blk ) if identifier_conditions . empty? record = self . new else record = self . where ( identifier_conditions ) . first_or_initialize end record . assign_attributes ( atts_hash , :without_protection => true ) if block_given? yield record , full_data_object end return record end
atts_hash are the attributes to assign to the Record identifier_conditions is what the scope for first_or_initialize is called upon so that an existing object is updated full_data_object is passed in to be saved as a blob
24,896
def add_child ( * names ) names . flatten! return unless name = names . shift node = children . find { | c | c . name == name } node ? node . add_child ( names ) : ( children << TreeNode . new ( name , names ) ) end
Initialize a tree node setting name and adding a child if one was passed Add one or more children to the tree
24,897
def parse_a_bookmark line line = line . strip if line =~ / / @h3_tags << h3_tags ( line ) elsif line =~ / \/ / @h3_tags . pop elsif line =~ / / @bookmarks << NetscapeBookmark . from_string ( line ) if ( not @h3_tags . empty? ) && ( not @bookmarks . last . nil? ) @bookmarks . last . add_tags @h3_tags end elsif line =~ / / @bookmarks . last . description = line [ 4 .. - 1 ] . chomp end end
Parse a single line from a bookmarks file .
24,898
def save body = { version : to_hash } body [ :version ] . delete ( :providers ) begin response = Atlas . client . put ( url_builder . box_version_url , body : body ) rescue Atlas :: Errors :: NotFoundError response = Atlas . client . post ( "#{url_builder.box_url}/versions" , body : body ) end providers . each ( & :save ) if providers update_with_response ( response , [ :providers ] ) end
Save the version .
24,899
def textRectForBounds ( bounds , limitedToNumberOfLines : num_of_lines ) required_rect = rect_fitting_text_for_container_size ( bounds . size , for_number_of_line : num_of_lines ) text_container . size = required_rect . size required_rect end
Override UILabel Methods