idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
12,200 | def define_methods methods = [ ] pretty_name = @relationship [ :target ] [ :name ] methods << define_method ( @link_field ) methods << define_alias ( pretty_name , @link_field ) if pretty_name != @link_field methods end | Defines methods for accessing the association target on the owner class . If the link_field name includes the owner class name it is stripped before creating the method . If this occurs we also create an alias to the stripped method using the full link_field name . |
12,201 | def define_method ( link_field ) raise ArgumentError , "argument cannot be nil" if link_field . nil? if ( @owner . respond_to? link_field . to_sym ) && @owner . debug warn "Warning: Overriding method: #{@owner.class}##{link_field}" end @owner . class . module_eval %Q? def #{link_field} query_association... | Generates the association proxy method for related module |
12,202 | def cardinality_for ( * args ) args . inject ( [ ] ) { | results , arg | result = :many result = :one if arg . singularize == arg results << result } end | Determines if the provided string is plural or singular Plurality == Cardinality |
12,203 | def convert_reserved_characters ( string ) string . gsub! ( / / , '\"' ) string . gsub! ( / / , '\'' ) string . gsub! ( / / , '\&' ) string . gsub! ( / / , '\<' ) string . gsub! ( / / , '\>' ) string end | A tiny helper for converting reserved characters for html encoding |
12,204 | def fields return @fields if fields_registered? all_fields = @session . connection . get_fields ( @name ) @fields = all_fields [ "module_fields" ] . with_indifferent_access @link_fields = all_fields [ "link_fields" ] handle_empty_arrays @fields_registered = true @fields end | Returns the fields associated with the module |
12,205 | def required_fields required_fields = [ ] ignore_fields = [ :id , :date_entered , :date_modified ] self . fields . each_value do | field | next if ignore_fields . include? field [ "name" ] . to_sym required_fields << field [ "name" ] . to_sym if field [ "required" ] == 1 end required_fields end | Returns the required fields |
12,206 | def deregister return true unless registered? klass = self . klass @session . namespace_const . instance_eval { remove_const klass } true end | Deregisters the module |
12,207 | def serialize_attribute ( name , value ) attr_value = value attr_type = attr_type_for ( name ) case attr_type when :bool attr_value = 0 attr_value = 1 if value when :datetime , :datetimecombo begin attr_value = value . strftime ( "%Y-%m-%d %H:%M:%S" ) rescue attr_value = value end when :int attr_value = value . to_s en... | Un - typecasts the attribute - false becomes 0 5234 becomes 5234 etc . |
12,208 | def save ( opts = { } ) options = { :validate => true } . merge ( opts ) return false if ! ( new_record? || changed? ) if options [ :validate ] return false if ! valid? end begin save! ( options ) rescue return false end true end | Saves the current object checks that required fields are present . returns true or false |
12,209 | def valid? @errors = ( defined? ( HashWithIndifferentAccess ) ? HashWithIndifferentAccess : ActiveSupport :: HashWithIndifferentAccess ) . new self . class . _module . required_fields . each do | attribute | valid_attribute? ( attribute ) end def @errors . full_messages self . inject ( [ ] ) { | memo , obj | memo . con... | Checks to see if we have all the neccessary attributes |
12,210 | def validate_class_for ( attribute , class_array ) return true if class_array . include? @attributes [ attribute ] . class add_error ( attribute , "must be a #{class_array.join(" or ")} object (not #{@attributes[attribute].class})" ) false end | Compares the class of the attribute with the class or classes provided in the class array returns true if they match otherwise adds an entry to the |
12,211 | def add_error ( attribute , message ) @errors [ attribute ] ||= [ ] @errors [ attribute ] = @errors [ attribute ] << message unless @errors [ attribute ] . include? message @errors end | Add an error to the hash |
12,212 | def to_obj return @response unless @response && @response [ "entry_list" ] objects = [ ] @response [ "entry_list" ] . each do | object | attributes = [ ] _module = resolve_module ( object ) attributes = flatten_name_value_list ( object ) namespace = @session . namespace_const if namespace . const_get ( _module ) if att... | Tries to instantiate and return an object with the values populated from the response |
12,213 | def attr_type_for ( attribute ) fields = self . class . _module . fields field = fields [ attribute ] raise UninitializedModule , "#{self.class.session.namespace_const}Module #{self.class._module.name} was not initialized properly (fields.length == 0)" if fields . length == 0 raise InvalidAttribute , "#{self.class}._mo... | Returns the attribute type for a given attribute |
12,214 | def typecast_attributes @attributes . each_pair do | name , value | next if ( name == "id" ) or ( ! name . present? ) attr_type = attr_type_for ( name ) if [ :datetime , :datetimecombo , :int ] . include? attr_type && ( value . nil? || value == '' ) @attributes [ name ] = nil next end case attr_type when :bool @attribu... | Attempts to typecast each attribute based on the module field type |
12,215 | def make_nodes ( ids , opt ) result = [ ] ids . each do | id | id = id . tr ( '"' , '' ) selector = "//*[@capybara-ng-match='#{id}']" nodes = page . driver . find_xpath ( selector ) raise NotFound . new ( "Failed to match found id to node" ) if nodes . empty? result . concat ( nodes ) end page . evaluate_script ( "clea... | Find nodes matching capybara - ng - match attributes using ids |
12,216 | def ng_root_selector ( root_selector = nil ) opt = ng . page . ng_session_options if root_selector opt [ :root_selector ] = root_selector end opt [ :root_selector ] || :: Angular . root_selector end | Get or set selector to find ng - app for current capybara test session |
12,217 | def ng_binding ( binding , opt = { } ) opt [ :root_selector ] ||= ng_root_selector row = ng . row ( opt ) ng_bindings ( binding , opt ) [ row ] end | Node for nth binding match |
12,218 | def ng_bindings ( binding , opt = { } ) opt [ :root_selector ] ||= ng_root_selector ng . get_nodes_2 :findBindingsIds , [ binding , opt [ :exact ] == true ] , opt end | All nodes matching binding |
12,219 | def ng_model ( model , opt = { } ) opt [ :root_selector ] ||= ng_root_selector row = ng . row ( opt ) ng_models ( model , opt ) [ row ] end | Node for nth model match |
12,220 | def has_ng_options? ( options , opt = { } ) opt [ :root_selector ] ||= ng_root_selector ng_options ( options , opt ) true rescue NotFound false end | Does option exist |
12,221 | def ng_option ( options , opt = { } ) opt [ :root_selector ] ||= ng_root_selector row = ng . row ( opt ) ng_options ( options , opt ) [ row ] end | Node for nth option |
12,222 | def ng_repeater_row ( repeater , opt = { } ) opt [ :root_selector ] ||= ng_root_selector row = ng . row ( opt ) data = ng . get_nodes_2 ( :findRepeaterRowsIds , [ repeater , row ] , opt ) data . first end | Node for nth repeater row |
12,223 | def ng_repeater_column ( repeater , binding , opt = { } ) opt [ :root_selector ] ||= ng_root_selector row = ng . row ( opt ) ng_repeater_columns ( repeater , binding , opt ) [ row ] end | Node for column binding value in row |
12,224 | def ng_repeater_columns ( repeater , binding , opt = { } ) opt [ :root_selector ] ||= ng_root_selector ng . get_nodes_2 :findRepeaterColumnIds , [ repeater , binding ] , opt end | Node for column binding value in all rows |
12,225 | def set_data ( format , data , width = nil , height = nil ) ZBar . zbar_image_set_format ( @img , format ) new_buffer = FFI :: MemoryPointer . from_string ( data ) ZBar . zbar_image_set_data ( @img , new_buffer , data . size , nil ) @buffer = new_buffer if width && height ZBar . zbar_image_set_size ( @img , width . to_... | Load arbitrary data from a string into the Image object . |
12,226 | def convert ( format ) ptr = ZBar . zbar_image_convert ( @img , format ) if ptr . null? raise ArgumentError , "conversion failed" else Image . new ( ptr ) end end | Ask ZBar to convert this image to a new format returning a new Image . |
12,227 | def transform_hash ( hash , path = "" ) hash . each_with_object ( { } ) do | ( k , v ) , ret | key = path + k . to_s if v . is_a? ( Hash ) ret . merge! transform_hash ( v , "#{key}:" ) else ret [ key ] = v end end end | Transforms a nested hash into meta property keys . |
12,228 | def parse_json ( response ) json_response = JSON . parse ( response ) error = json_response [ 'error' ] if ! error . nil? then raise APIException . new ( error ) end return json_response end | convenience method that parses a response into json AND makes sure there are no errors |
12,229 | def stats ( filename , * args ) fn = OptArg . quote ( filename ) opt = OptArg . parse ( * args ) puts send_cmd "stats #{fn} #{opt}" end | This command prepares a statistical summary of the data in one or two columns of a file . |
12,230 | def parse_element ( ele ) if ele . is_a? Nokogiri :: XML :: Text return "#{ele.text}\n" else if ( children = ele . children ) . count > 0 return wrap_node ( ele , children . map { | ele | parse_element ( ele ) } . join ) else return wrap_node ( ele , ele . text ) end end end | a normal element maybe text maybe node |
12,231 | def wrap_node ( node , contents = nil ) result = '' contents . strip! unless contents == nil if respond_to? "parse_#{node.name}" return self . send ( "parse_#{node.name}" , node , contents ) end return '' if node [ 'style' ] and node [ 'style' ] =~ / \s / case node . name . downcase when 'i' when 'script' when 'style' ... | wrap node with markdown |
12,232 | def method_missing ( name , * args , & block ) self . class . send :define_method , "parse_#{name}" do | node , contents | block . call node , contents end end | define custom node processor |
12,233 | def convert_line ( line_num ) return '' unless @callouts . key? line_num @callouts [ line_num ] . map { | num | convert_callout ( num ) } . join ( ' ' ) end | Converts the extracted callout markers for the specified line . |
12,234 | def stream_lines ( tokens , line_num ) yield line_start ( line_num ) tokens . each do | token , value | yield @inner . span ( token , value ) end yield line_end ( line_num ) end | Formats tokens on the specified line into HTML . |
12,235 | def to_s rendered_rows = [ separator ] + text_table_rows . map ( & :to_s ) + [ separator ] rendered_rows . unshift [ separator , text_table_head . to_s ] if head rendered_rows << [ text_table_foot . to_s , separator ] if foot rendered_rows . join end | Renders a pretty plain - text table . |
12,236 | def align_column ( column_number , alignment ) set_alignment = Proc . new do | row , column_number_block , alignment_block | cell = row . find do | cell_row | row [ 0 ... row . index ( cell_row ) ] . map { | c | c . is_a? ( Hash ) ? c [ :colspan ] || 1 : 1 } . inject ( 0 , & :+ ) == column_number_block - 1 end row [ ro... | Aligns the cells and the footer of a column . |
12,237 | def restore ( text ) return text if @node . passthroughs . empty? text = text . gsub ( PASS_SLOT_RX , "#{PASS_START_MARK}\\1#{PASS_END_MARK}" ) @node . restore_passthroughs ( text ) end | Restores the extracted passthroughs by reinserting them into the placeholder positions . |
12,238 | def element! ( name , content = nil , attributes = nil ) build! do if content or block_given? @_crafted << "<#{name}#{Tools.format_attributes(attributes)}>" if block_given? value = yield content = value if ! @_appended or value . kind_of? String end content = content . to_s @_crafted << Tools . escape ( content ) if co... | Write an element with the given name content and attributes . If there is no content and no block is given a self - closing element is created . Provide an empty string as content to create an empty non - self - closing element . |
12,239 | def extract! ( force = false ) return if @options [ :dry_run ] && ! force if not package? return end FileUtils . mkdir_p ( @path ) Zip :: ZipFile :: foreach ( @package ) do | entry | entry_path = File . join ( @path , entry . name ) entry_dir = File . dirname ( entry_path ) FileUtils . mkdir_p ( entry_dir ) unless File... | Extracts the content of the package to the course repository . This will be done automatically when opening a package so this method will rarely be used . If the + dry_run + option was set to + true + when the package was opened nothing will happen . This behavior can be overridden with the + force + parameter . |
12,240 | def path_to ( relative_filename , relative = false ) if relative File . join ( @name , relative_filename ) else File . join ( @path , relative_filename ) end end | Computes the absolute path to a file in an extracted package given its relative path . The argument + relative + can be used to get the path relative to the course repository . |
12,241 | def make_resource resource = Module . new paths . each do | path | new_module = PathBuilder . build ( path : path , module_constant : resource ) path . operations . each do | operation | OperationBuilder . build ( operation : operation , module_constant : new_module , configuration : configuration ) end end Service . c... | Creates a new SwaggerBuilder |
12,242 | def define_models ( json ) return unless json models = { } model_definitions = json [ 'definitions' ] model_definitions . each do | model_name , parameters | attributes = parameters [ 'properties' ] . keys model = Class . new do attr_reader ( * attributes . map ( & :to_sym ) ) parameters [ 'properties' ] . each do | at... | Creates typed Ruby objects from JSON definitions . These definitions are found in the Swagger JSON spec as a top - level key definitions . |
12,243 | def server ( client_id , client_secret , redirect_uri ) Googl :: OAuth2 :: Server . new ( client_id , client_secret , redirect_uri ) end | OAuth 2 . 0 for server - side web applications |
12,244 | def decode ( string ) padding_size = string . bytesize % 4 padded_string = padding_size > 0 ? string + '=' * ( 4 - padding_size ) : string Base64 . urlsafe_decode64 ( padded_string ) end | Decode an unpadded URL - safe Base64 string |
12,245 | def operations validate_operations @operations ||= @raw_operations . map do | operation , properties | Operation . new ( verb : operation , properties : properties , path : self ) end end | Creates a new Path . |
12,246 | def create ( entity ) url = "#{DEFAULT_HOST}/#{entity.path}" uri = URI ( url ) response = http_response ( :post , uri , body : entity . to_hash ) entity . attributes = JSON . parse ( response . body ) entity end | Creates an entity in your Harvest account . |
12,247 | def delete ( entity ) url = "#{DEFAULT_HOST}/#{entity.path}" uri = URI ( url ) response = http_response ( :delete , uri ) raise UnprocessableRequest ( response . to_s ) unless response . code . to_i == 200 JSON . parse ( response . body ) end | It removes an entity from your Harvest account . |
12,248 | def get ( path , opts = { } ) url = "#{DEFAULT_HOST}/#{path}" url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts . any? uri = URI ( url ) response = http_response ( :get , uri ) JSON . parse ( response . body ) end | Performs a GET request and returned the parsed JSON as a Hash . |
12,249 | def knapsack ( items , capacity , algorithm = :dynamic ) if algorithm == :memoize knapsack_memoize ( items , capacity ) elsif algorithm == :dynamic knapsack_dynamic_programming ( items , capacity ) end end | Given a set of items each with a weight and a value determines the maximum profit you can have while keeping the overall weight smaller than the capacity of the knapsack . |
12,250 | def prev_sib ( ) if ( self . network . addr == 0 ) return nil end shift = 32 - self . netmask . prefix_len addr = ( ( self . network . addr >> shift ) - 1 ) << shift return IPv4Net . new ( IPv4 . new ( addr ) , self . netmask ) end | prev_sib returns the network immediately preceding this one or nil if this network is 0 . 0 . 0 . 0 . |
12,251 | def summ ( other ) if ( ! other . kind_of? ( IPv4Net ) ) raise ArgumentError , "Expected an IPv4Net object for 'other' but got a #{other.class}." end if ( self . netmask . prefix_len != other . netmask . prefix_len ) return nil end shift = 32 - self . netmask . prefix_len + 1 addr = self . network . addr >> shift other... | summ creates a summary address from this IPv4Net and another . It returns nil if the two networks are incapable of being summarized . |
12,252 | def contains ( ip ) if ( ! ip . kind_of? ( IPv6 ) ) raise ArgumentError , "Expected an IPv6 object for 'ip' but got a #{ip.class}." end if ( @base . addr == ip . addr & @m128 . mask ) return true end return false end | contains returns true if the IPv6Net contains the IPv6 |
12,253 | def bytes ( ) return [ ( @addr >> 56 & 0xff ) . to_s ( 16 ) . rjust ( 2 , "0" ) , ( @addr >> 48 & 0xff ) . to_s ( 16 ) . rjust ( 2 , "0" ) , ( @addr >> 40 & 0xff ) . to_s ( 16 ) . rjust ( 2 , "0" ) , ( @addr >> 32 & 0xff ) . to_s ( 16 ) . rjust ( 2 , "0" ) , ( @addr >> 24 & 0xff ) . to_s ( 16 ) . rjust ( 2 , "0" ) , ( ... | bytes returns a list containing each byte of the EUI64 as a String . |
12,254 | def set ( * keys , value : nil , & block ) assert_either_value_or_block ( value , block ) keys = convert_to_keys ( keys ) key = flatten_keys ( keys ) value_to_eval = block || value if validators . key? ( key ) if callable_without_params? ( value_to_eval ) value_to_eval = delay_validation ( key , value_to_eval ) else as... | Set a value for a composite key and overrides any existing keys . Keys are case - insensitive |
12,255 | def set_if_empty ( * keys , value : nil , & block ) return unless deep_find ( @settings , keys . last . to_s ) . nil? block ? set ( * keys , & block ) : set ( * keys , value : value ) end | Set a value for a composite key if not present already |
12,256 | def set_from_env ( * keys , & block ) assert_keys_with_block ( convert_to_keys ( keys ) , block ) key = flatten_keys ( keys ) env_key = block . nil? ? key : block . ( ) env_key = to_env_key ( env_key ) @envs [ key . to_s . downcase ] = env_key end | Bind a key to ENV variable |
12,257 | def fetch ( * keys , default : nil , & block ) real_key = @aliases [ flatten_keys ( keys ) ] keys = real_key . split ( key_delim ) if real_key keys = convert_to_keys ( keys ) env_key = autoload_env? ? to_env_key ( keys [ 0 ] ) : @envs [ flatten_keys ( keys ) ] value = deep_fetch ( @settings , * keys ) if value . nil? &... | Fetch value under a composite key |
12,258 | def append ( * values , to : nil ) keys = Array ( to ) set ( * keys , value : Array ( fetch ( * keys ) ) + values ) end | Append values to an already existing nested key |
12,259 | def remove ( * values , from : nil ) keys = Array ( from ) set ( * keys , value : Array ( fetch ( * keys ) ) - values ) end | Remove a set of values from a nested key |
12,260 | def alias_setting ( * keys , to : nil ) flat_setting = flatten_keys ( keys ) alias_keys = Array ( to ) alias_key = flatten_keys ( alias_keys ) if alias_key == flat_setting raise ArgumentError , 'Alias matches setting key' end if fetch ( alias_key ) raise ArgumentError , 'Setting already exists with an alias ' "'#{alias... | Define an alias to a nested key |
12,261 | def validate ( * keys , & validator ) key = flatten_keys ( keys ) values = validators [ key ] || [ ] values << validator validators [ key ] = values end | Register a validation rule for a nested key |
12,262 | def read ( file = find_file , format : :auto ) if file . nil? raise ReadError , 'No file found to read configuration from!' elsif ! :: File . exist? ( file ) raise ReadError , "Configuration file `#{file}` does not exist!" end merge ( unmarshal ( file , format : format ) ) end | Find and read a configuration file . |
12,263 | def write ( file = find_file , force : false , format : :auto ) if file && :: File . exist? ( file ) if ! force raise WriteError , "File `#{file}` already exists. " 'Use :force option to overwrite.' elsif ! :: File . writable? ( file ) raise WriteError , "Cannot write to #{file}." end end if file . nil? dir = @location... | Write current configuration to a file . |
12,264 | def assert_either_value_or_block ( value , block ) if value . nil? && block . nil? raise ArgumentError , 'Need to set either value or block' elsif ! ( value . nil? || block . nil? ) raise ArgumentError , "Can't set both value and block" end end | Ensure that value is set either through parameter or block |
12,265 | def assert_valid ( key , value ) validators [ key ] . each do | validator | validator . call ( key , value ) end end | Check if key passes all registered validations for a key |
12,266 | def deep_set ( settings , * keys ) return settings if keys . empty? key , * rest = * keys value = settings [ key ] if value . nil? && rest . empty? settings [ key ] = { } elsif value . nil? && ! rest . empty? settings [ key ] = { } deep_set ( settings [ key ] , * rest ) else settings [ key ] = value deep_set ( settings... | Set value under deeply nested keys |
12,267 | def deep_fetch ( settings , * keys ) key , * rest = keys value = settings . fetch ( key . to_s , settings [ key . to_sym ] ) if value . nil? || rest . empty? value else deep_fetch ( value , * rest ) end end | Fetch value under deeply nested keys with indiffernt key access |
12,268 | def marshal ( file , data , format : :auto ) file_ext = :: File . extname ( file ) ext = ( format == :auto ? file_ext : ".#{format}" ) self . extname = file_ext self . filename = :: File . basename ( file , file_ext ) case ext when * EXTENSIONS [ :yaml ] load_write_dep ( 'yaml' , ext ) YAML . dump ( self . class . norm... | Marshal data hash into a configuration file content |
12,269 | def save_certificate ( certificate ) return unless certificate return HerokuOutput . new ( common_domain_name , certificate ) . output unless ENV [ 'DYNO' ] . nil? output_dir = File . join ( Rails . root , @options [ :output_cert_dir ] ) return FileOutput . new ( common_domain_name , certificate , output_dir ) . output... | Save the certificate and key |
12,270 | def count * where sql , * binds = SQLHelper . count :table => name , :where => @query_where + where , :prepared => true pstmt = prepare :count , sql pstmt . query ( * binds ) . to_a [ 0 ] [ 0 ] . to_i end | Retrieves the count of the table |
12,271 | def insert_ignore data_hash = { } sql , * binds = SQLHelper . insert_ignore :table => name , :data => @query_default . merge ( data_hash ) , :prepared => true pstmt = prepare :insert , sql pstmt . set_fetch_size @fetch_size if @fetch_size pstmt . send @update_method , * binds end | Inserts a record into the table with the given hash . Skip insertion when duplicate record is found . |
12,272 | def replace data_hash = { } sql , * binds = SQLHelper . replace :table => name , :data => @query_default . merge ( data_hash ) , :prepared => true pstmt = prepare :insert , sql pstmt . send @update_method , * binds end | Replaces a record in the table with the new one with the same unique key . |
12,273 | def delete * where sql , * binds = SQLHelper . delete ( :table => name , :where => @query_where + where , :prepared => true ) pstmt = prepare :delete , sql pstmt . send @update_method , * binds end | Deletes records matching given condtion |
12,274 | def select * fields , & block obj = self . dup obj . instance_variable_set :@query_select , fields unless fields . empty? ret obj , & block end | Returns a new TableWrapper object which can be used to execute a select statement for the table selecting only the specified fields . If a block is given executes the select statement and yields each row to the block . |
12,275 | def where * conditions , & block raise ArgumentError . new ( "Wrong number of arguments" ) if conditions . empty? obj = self . dup obj . instance_variable_set :@query_where , @query_where + conditions ret obj , & block end | Returns a new TableWrapper object which can be used to execute a select statement for the table with the specified filter conditions . If a block is given executes the select statement and yields each row to the block . |
12,276 | def order * criteria , & block raise ArgumentError . new ( "Wrong number of arguments" ) if criteria . empty? obj = self . dup obj . instance_variable_set :@query_order , criteria ret obj , & block end | Returns a new TableWrapper object which can be used to execute a select statement for the table with the given sorting criteria . If a block is given executes the select statement and yields each row to the block . |
12,277 | def default data_hash , & block raise ArgumentError . new ( "Hash required" ) unless data_hash . kind_of? Hash obj = self . dup obj . instance_variable_set :@query_default , @query_default . merge ( data_hash ) ret obj , & block end | Returns a new TableWrapper object with default values which will be applied to the subsequent inserts and updates . |
12,278 | def fetch_size fsz , & block obj = self . dup obj . instance_variable_set :@fetch_size , fsz ret obj , & block end | Returns a new TableWrapper object with the given fetch size . If a block is given executes the select statement and yields each row to the block . |
12,279 | def each & block sql , * binds = SQLHelper . select ( :prepared => true , :table => name , :project => @query_select , :where => @query_where , :order => @query_order , :limit => @query_limit ) pstmt = prepare :select , sql pstmt . enumerate ( * binds , & block ) end | Executes a select SQL for the table and returns an Enumerable object or yields each row if block is given . |
12,280 | def clear_batch * types types = [ :insert , :update , :delete ] if types . empty? types . each do | type | raise ArgumentError . new ( "Invalid type: #{type}" ) unless @pstmts . has_key? ( type ) @pstmts [ type ] . values . each ( & :clear_batch ) end nil end | Clear batched operations . |
12,281 | def close @pstmts . each do | typ , hash | hash . each do | sql , pstmt | pstmt . close if pstmt end @pstmts [ typ ] = { } end end | Closes the prepared statements |
12,282 | def call ( * args ) pstmt = @connection . prepare ( "select #{name}(#{args.map{'?'}.join ','})#{@suffix}" ) begin pstmt . query ( * args ) . to_a [ 0 ] [ 0 ] ensure pstmt . close end end | Returns the result of the function call with the given parameters |
12,283 | def call ( * args ) params = build_params args cstmt = @connection . prepare_call "{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}" begin process_result ( args , cstmt . call ( * params ) ) ensure cstmt . close end end | Executes the procedure and returns the values of INOUT & OUT parameters in Hash |
12,284 | def unpack_int64_bigendian ( bytes ) bytes . each_byte . to_a . reverse . each_with_index . reduce ( 0 ) { | val , ( byte , index ) | val | ( byte << ( index * 8 ) ) } end | Internal - unpacks a string of big endian 64 bit integers |
12,285 | def transaction check_closed raise ArgumentError . new ( "Transaction block not given" ) unless block_given? tx = Transaction . send :new , @conn ac = @conn . get_auto_commit status = :unknown begin @conn . set_auto_commit false yield tx @conn . commit status = :committed rescue Transaction :: Commit status = :committe... | Executes the given code block as a transaction . Returns true if the transaction is committed . A transaction object is passed to the block which only has commit and rollback methods . The execution breaks out of the code block when either of the methods is called . |
12,286 | def execute ( qstr ) check_closed stmt = @spool . take begin if stmt . execute ( qstr ) ResultSet . send ( :new , stmt . getResultSet ) { @spool . give stmt } else rset = stmt . getUpdateCount @spool . give stmt rset end rescue Exception => e @spool . give stmt raise end end | Executes an SQL and returns the count of the update rows or a ResultSet object depending on the type of the given statement . If a ResultSet is returned it must be enumerated or closed . |
12,287 | def query ( qstr , & blk ) check_closed stmt = @spool . take begin rset = stmt . execute_query ( qstr ) rescue Exception => e @spool . give stmt raise end enum = ResultSet . send ( :new , rset ) { @spool . give stmt } if block_given? enum . each do | row | yield row end else enum end end | Executes a select query . When a code block is given each row of the result is passed to the block one by one . If not given ResultSet is returned which can be used to enumerate through the result set . ResultSet is closed automatically when all the rows in the result set is consumed . |
12,288 | def execute_batch check_closed cnt = 0 if @bstmt cnt += @bstmt . execute_batch . inject ( :+ ) || 0 @spool . give @bstmt @bstmt = nil end @pstmts . each do | pstmt | cnt += pstmt . execute_batch end cnt end | Executes batched statements including prepared statements . No effect when no statement is added |
12,289 | def table table_name table = JDBCHelper :: TableWrapper . new ( self , table_name ) table = table . fetch_size ( @fetch_size ) if @fetch_size @table_wrappers [ table_name ] ||= table end | Returns a table wrapper for the given table name |
12,290 | def save self . attributes . stringify_keys! self . attributes . delete ( 'customer' ) self . attributes . delete ( 'product' ) self . attributes . delete ( 'credit_card' ) self . attributes . delete ( 'bank_account' ) self . attributes . delete ( 'paypal_account' ) self . attributes , options = extract_uniqueness_toke... | Strip off nested attributes of associations before saving or type - mismatch errors will occur |
12,291 | def unpack ( filename ) @destination = Dir . mktmpdir Zip :: File . open ( filename ) { | zip_file | zip_file . each { | f | f_path = File . join ( @destination , f . name ) FileUtils . mkdir_p ( File . dirname ( f_path ) ) zip_file . extract ( f , f_path ) unless File . exists? ( f_path ) } } end | Unzips the excel file to a temporary directory . The directory will be removed at the end of the parsing stage when invoked by initialize otherwise at exit . |
12,292 | def parse ( options = { } ) @sheets . each do | x | if ! options [ :paginate ] . nil? lines = options [ :paginate ] [ 0 ] ; page = options [ :paginate ] [ 1 ] sheet = PagSheet . new ( lines , page ) elsif ! options [ :cellrange ] . nil? range = options [ :cellrange ] sheet = Cellrange . new ( range ) else sheet = Xlshe... | Parses sheet data by feeding the output of the Xlsheet SAX parser into the arrays representing the sheets . |
12,293 | def commentsrel unless Dir [ @destination + '/xl/worksheets/_rels' ] . empty? Find . find ( @destination + '/xl/worksheets/_rels' ) do | path | if File . basename ( path ) . split ( "." ) . last == 'rels' a = IO . read ( path ) f = Ox :: load ( a ) f . locate ( "Relationships/*" ) . each do | x | if x [ :Target ] . inc... | Build the relationship between sheets and the XML files storing the comments to the actual sheet . |
12,294 | def shstrings strings = Sharedstrings . new ( ) File . open ( @destination + '/xl/sharedStrings.xml' , 'r' ) do | f | Ox . sax_parse ( strings , f ) end @sharedstrings = strings . stringarray end | Invokes the Sharedstrings helper class |
12,295 | def mkcomments ( commentfile ) unless commentfile . nil? comms = Comments . new ( ) File . open ( @destination + '/xl/' + commentfile . gsub ( '../' , '' ) , 'r' ) do | f | Ox . sax_parse ( comms , f ) end return comms . commarray end end | Parses the comments related to the actual sheet . |
12,296 | def mergevalues ( m , col , row , valuecell ) if valuecell != nil valuecell . xlcoords = ( col . col_name ) + ( row + 1 ) . to_s m [ row , col ] = valuecell return m , valuecell else valuecell = Cell . new valuecell . xlcoords = ( col . col_name ) + ( row + 1 ) . to_s m [ row , col ] = valuecell return m , valuecell en... | Replace the empty values of the mergegroup with cell values or nil . |
12,297 | def datetime formatcode deminutified = formatcode . downcase . gsub ( / / , '\k<hrs>\k<div>i' ) . gsub ( / / , 'ii' ) . gsub ( / / , 'i\k<div>\k<secs>' ) . gsub ( / / , 'ii' ) return deminutified . gsub ( / / , Dtmap ) end | Convert excel - style date formats into ruby DateTime strftime format strings |
12,298 | def to_ru if ! @value . numeric? || Numformats :: Formatarray [ @numformat . to_i ] [ :xl ] == nil || Numformats :: Formatarray [ @numformat . to_i ] [ :xl ] . downcase == "general" return @value end if Numformats :: Formatarray [ @numformat . to_i ] [ :cls ] == 'date' return DateTime . new ( 1899 , 12 , 30 ) + ( eval ... | Get the cell s value and excel format string and return a string a ruby Numeric or a DateTime object accordingly |
12,299 | def to_fmt begin if Numformats :: Formatarray [ @numformat . to_i ] [ :cls ] == 'date' self . to_ru . strftime ( Numformats :: Formatarray [ @numformat ] [ :ostring ] ) rescue @value elsif Numformats :: Formatarray [ @numformat . to_i ] [ :cls ] == 'numeric' || Numformats :: Formatarray [ @numformat . to_i ] [ :cls ] =... | Get the cell s value convert it with to_ru and finally format it based on the value s type . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.