idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
11,300
def composition root_terms . reduce ( SignedMultiset . new ) do | s , t | s . increment ( t . atom . dim , t . exponent ) if t . atom s end end
A representation of a unit based on the atoms it s derived from .
11,301
def composition_string composition . sort . map do | k , v | v == 1 ? k . to_s : "#{k}#{v}" end . join ( '.' ) end
A string representation of a unit based on the atoms it s derived from
11,302
def terms unless frozen? unless @terms decomposer = Expression . decompose ( @expression ) @mode = decomposer . mode @terms = decomposer . terms end freeze end @terms end
Create a new unit . You can send an expression or a collection of terms
11,303
def expression ( mode = nil ) if @expression && ( mode . nil? || mode == self . mode ) @expression else Expression . compose ( terms , mode || self . mode ) end end
Build a string representation of this unit by it s terms .
11,304
def scalar ( magnitude = 1 ) terms . reduce ( 1 ) do | prod , term | prod * term . scalar ( magnitude ) end end
Get a scalar value for this unit .
11,305
def ** ( other ) if other . is_a? ( Numeric ) self . class . new ( terms . map { | t | t ** other } ) else fail TypeError , "Can't raise #{self} to #{other}." end end
Raise this unit to a numeric power .
11,306
def operate ( operator , other ) exp = operator == '/' ? - 1 : 1 if other . respond_to? ( :terms ) self . class . new ( terms + other . terms . map { | t | t ** exp } ) elsif other . respond_to? ( :atom ) self . class . new ( terms << other ** exp ) elsif other . is_a? ( Numeric ) self . class . new ( terms . map { | t...
Multiply or divide units
11,307
def convert_to ( other_unit ) other_unit = Unit . new ( other_unit ) if compatible_with? ( other_unit ) new ( converted_value ( other_unit ) , other_unit ) else fail ConversionError , "Can't convert #{self} to #{other_unit}." end end
Create a new Measurement
11,308
def ** ( other ) if other . is_a? ( Numeric ) new ( value ** other , unit ** other ) else fail TypeError , "Can't raise #{self} to #{other} power." end end
Raise a measurement to a numeric power .
11,309
def round ( digits = nil ) rounded_value = digits ? value . round ( digits ) : value . round self . class . new ( rounded_value , unit ) end
Round the measurement value . Delegates to the value s class .
11,310
def method_missing ( meth , * args , & block ) if args . empty? && ! block_given? && ( match = / \A \w \Z / . match ( meth . to_s ) ) begin convert_to ( match [ 1 ] ) rescue ExpressionError super ( meth , * args , & block ) end else super ( meth , * args , & block ) end end
Will attempt to convert to a unit by method name .
11,311
def converted_value ( other_unit ) if other_unit . special? other_unit . magnitude scalar else scalar / other_unit . scalar end end
Determine value of the unit after conversion to another unit
11,312
def combine ( operator , other ) if other . respond_to? ( :composition ) && compatible_with? ( other ) new ( value . send ( operator , other . convert_to ( unit ) . value ) , unit ) end end
Add or subtract other unit
11,313
def operate ( operator , other ) if other . is_a? ( Numeric ) new ( value . send ( operator , other ) , unit ) elsif other . respond_to? ( :composition ) if compatible_with? ( other ) converted = other . convert_to ( unit ) new ( value . send ( operator , converted . value ) , unit . send ( operator , converted . unit ...
Multiply or divide other unit
11,314
def scalar ( magnitude = value ) if special? unit . scalar ( magnitude ) else Number . rationalize ( value ) * Number . rationalize ( unit . scalar ) end end
Get a scalar value for this scale .
11,315
def magnitude ( scalar = scalar ( ) ) if special? unit . magnitude ( scalar ) else value * unit . magnitude end end
Get a magnitude based on a linear scale value . Only used by scales with special atoms in it s hierarchy .
11,316
def to_s ( mode = nil ) unit_string = unit . to_s ( mode ) if unit_string && unit_string != '1' "#{simplified_value} #{unit_string}" else simplified_value . to_s end end
Convert to a simple string representing the scale .
11,317
def evaluate ( str , file = '<in QML::Engine#evaluate>' , lineno = 1 ) evaluate_impl ( str , file , lineno ) . tap do | result | raise result . to_error if result . is_a? ( JSObject ) && result . error? end end
Evaluates an JavaScript expression
11,318
def load_path ( path ) path = path . to_s check_error_string do @path = Pathname . new ( path ) load_path_impl ( path ) end self end
Creates an component . Either data or path must be specified .
11,319
def emit ( * args ) if args . size != @arity fail :: ArgumentError , "wrong number of arguments for signal (#{args.size} for #{@arity})" end @listeners . each do | listener | listener . call ( * args ) end end
Initializes the Signal .
11,320
def moving ( range , destination ) return if range . count == 0 @access . begin_move ( range . min , range . max , destination ) ret = yield @access . end_move ret end
Notifies the list views that items are about to be and were moved .
11,321
def inserting ( range , & block ) return if range . count == 0 @access . begin_insert ( range . min , range . max ) ret = yield @access . end_insert ret end
Notifies the list views that items are about to be and were inserted .
11,322
def removing ( range , & block ) return if range . count == 0 @access . begin_remove ( range . min , range . max ) ret = yield @access . end_remove ret end
Notifies the list views that items are about to be and were removed .
11,323
def insert ( index , * items ) inserting ( index ... index + items . size ) do @array . insert ( index , * items ) end self end
Inserts items .
11,324
def method_missing ( method , * args , & block ) if method [ - 1 ] == '=' key = method . slice ( 0 ... - 1 ) . to_sym unless has_key? ( key ) super end self [ key ] = args [ 0 ] else unless has_key? ( method ) super end prop = self [ method ] if prop . is_a? JSFunction prop . call_with_instance ( self , * args , & bloc...
Gets or sets a JS property or call it as a method if it is a function .
11,325
def convert_coords x , y if y % 2 == 1 [ x , y / 2 + @pass_starts [ 7 ] ] elsif x % 2 == 1 && y % 2 == 0 [ x / 2 , y / 2 + @pass_starts [ 6 ] ] elsif x % 8 == 0 && y % 8 == 0 [ x / 8 , y / 8 ] elsif x % 8 == 4 && y % 8 == 0 [ x / 8 , y / 8 + @pass_starts [ 2 ] ] elsif x % 4 == 0 && y % 8 == 4 [ x / 4 , y / 8 + @pass_st...
convert flat coords in scanline number & pos in scanline
11,326
def save fname , options = { } File . open ( fname , "wb" ) { | f | f << export ( options ) } end
save image to file
11,327
def _safe_inflate data zi = Zlib :: Inflate . new pos = 0 ; r = '' begin r << zi . inflate ( pos == 0 ? data : data [ pos .. - 1 ] ) if zi . total_in < data . size @extradata << data [ zi . total_in .. - 1 ] puts "[?] #{@extradata.last.size} bytes of extra data after zlib stream" . red if @verbose >= 1 end rescue Zlib ...
unpack zlib on errors keep going and try to return maximum possible data
11,328
def crop! params decode_all_scanlines x , y , h , w = ( params [ :x ] || 0 ) , ( params [ :y ] || 0 ) , params [ :height ] , params [ :width ] raise ArgumentError , "negative params not allowed" if [ x , y , h , w ] . any? { | x | x < 0 } h = self . height - y if ( y + h ) > self . height w = self . width - x if ( x + ...
modifies this image
11,329
def deinterlace return self unless interlaced? h = Hash [ * %w' width height depth color compression filter ' . map { | k | [ k . to_sym , hdr . send ( k ) ] } . flatten ] h [ :palette ] = nil new_img = self . class . new h chunks . each do | chunk | next if chunk . is_a? ( Chunk :: IHDR ) next if chunk . is_a? ( Chunk...
returns new deinterlaced image if deinterlaced OR returns self if no need to deinterlace
11,330
def to_ansi return to_depth ( 8 ) . to_ansi if depth != 8 a = ANSI_COLORS . map { | c | self . class . const_get ( c . to_s . upcase ) } a . map! { | c | self . euclidian ( c ) } ANSI_COLORS [ a . index ( a . min ) ] end
convert to ANSI color name
11,331
def to_depth new_depth return self if depth == new_depth color = Color . new :depth => new_depth if new_depth > self . depth %w' r g b a ' . each do | part | color . send ( "#{part}=" , ( 2 ** new_depth - 1 ) / ( 2 ** depth - 1 ) * self . send ( part ) ) end else %w' r g b a ' . each do | part | color . send ( "#{part}...
change bit depth return new Color
11,332
def op op , c = nil max = 2 ** depth - 1 if c c = c . to_depth ( depth ) Color . new ( @r . send ( op , c . r ) & max , @g . send ( op , c . g ) & max , @b . send ( op , c . b ) & max , :depth => self . depth ) else Color . new ( @r . send ( op ) & max , @g . send ( op ) & max , @b . send ( op ) & max , :depth => self ...
Op! op! op! Op!! Oppan Gangnam Style!!
11,333
def handle_response ( response ) check_response_fail ( response ) return nil if blank? ( response . body ) begin response . body = JSON . parse ( response . body , max_nesting : false ) response . body = if response . body . is_a? Array response . body . map { | r | Hashie :: Mash . new ( r ) } else Hashie :: Mash . ne...
Returns a response with a parsed body
11,334
def underscore_string ( str ) str . to_s . strip . gsub ( ' ' , '_' ) . gsub ( / / , '/' ) . gsub ( / / , '\1_\2' ) . gsub ( / \d / , '\1_\2' ) . tr ( "-" , "_" ) . squeeze ( "_" ) . downcase end
converts a camel_cased string to a underscore string subs spaces with underscores strips whitespace Same way ActiveSupport does string . underscore
11,335
def discover ( * card_types ) card_types . inject ( [ ] ) do | tags , card_type | raise NFC :: Error . new ( 'Wrong card type' ) unless card_type . respond_to? :discover tags += card_type . discover ( connect ) end end
Returns list of tags applied to reader
11,336
def search data = Job . search ( params ) respond_with data . flatten! ( 1 ) do | format | format . json { render :json => Quorum :: JobSerializer . as_json ( data ) } format . gff { render :text => Quorum :: JobSerializer . as_gff ( data ) } format . txt { render :text => Quorum :: JobSerializer . as_txt ( data ) } en...
Returns Quorum s search results .
11,337
def build_blast_jobs @job ||= Job . new @job . build_blastn_job if @job . blastn_job . nil? @job . build_blastx_job if @job . blastx_job . nil? @job . build_tblastn_job if @job . tblastn_job . nil? @job . build_blastp_job if @job . blastp_job . nil? end
Create new Job and build associations .
11,338
def create_file_name ( file , base_dir ) file_name = file . split ( "/" ) . delete_if { | f | f . include? ( "." ) } . first unless File . exists? ( File . join ( base_dir , file_name ) ) Dir . mkdir ( File . join ( base_dir , file_name ) ) end file_name end
Create directories per tarball and return tarball file name minus the file extension .
11,339
def extract_files ( src , file , flag , path ) extract_data_error = File . join ( @log_dir , "extract_data_error.log" ) cmd = "tar -x#{flag}Of #{src} #{file} >> #{path} 2>> " << "#{extract_data_error}" system ( cmd ) if $? . exitstatus > 0 raise "Data extraction error. " << "See #{extract_data_error} for details." end ...
Extracts and concatenates files from tarballs .
11,340
def execute_makeblastdb ( type , title , input ) @output . puts "Executing makeblastdb for #{title} dbtype #{type}..." makeblast_log = File . join ( @log_dir , "makeblastdb.log" ) output = File . dirname ( input ) cmd = "makeblastdb " << "-dbtype #{type} " << "-title #{title} " << "-in #{input} " << "-out #{output} " <...
Execute makeblastdb on an extracted dataset .
11,341
def build_blast_db ( blastdb ) Dir . glob ( File . expand_path ( blastdb ) + "/*" ) . each do | d | if File . directory? ( d ) contigs = File . join ( d , "contigs.fa" ) peptides = File . join ( d , "peptides.fa" ) found = false if File . exists? ( contigs ) && File . readable? ( contigs ) execute_makeblastdb ( "nucl" ...
Builds a Blast database from parse_blast_db_data .
11,342
def log ( program , message , exit_status = nil , files = nil ) File . open ( File . join ( @log_directory , @log_file ) , "a" ) do | log | log . puts "" log . puts Time . now . to_s + " " + program log . puts message log . puts "" end if exit_status remove_files ( files ) unless files . nil? exit exit_status . to_i en...
Write to log file and exit if exit_status is present .
11,343
def algorithm_selected in_queue = false if ( self . blastn_job && self . blastn_job . queue ) || ( self . blastx_job && self . blastx_job . queue ) || ( self . tblastn_job && self . tblastn_job . queue ) || ( self . blastp_job && self . blastp_job . queue ) in_queue = true end unless in_queue errors . add ( :algorithm ...
Make sure an algorithm is selected .
11,344
def start_mongrel ( suite_name = { } ) pid_file = File . join ( RAILS_ROOT , "tmp" , "pids" , "mongrel_selenium.pid" ) port = suite_name [ :port ] rescue @selenium_config . application_port say "Starting mongrel at #{pid_file}, port #{port}" system "mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --enviro...
parameters required when invoked by test_unit
11,345
def create_hash ( sequence ) Digest :: MD5 . hexdigest ( sequence ) . to_s + "-" + Time . now . to_f . to_s end
Create a unique hash plus timestamp .
11,346
def write_input_sequence_to_file ( tmp_dir , hash , sequence ) seq = File . join ( tmp_dir , hash + ".seq" ) File . open ( seq , "w" ) do | f | f << sequence end fasta = File . join ( tmp_dir , hash + ".fa" ) cmd = "seqret -filter -sformat pearson -osformat fasta < #{seq} " << "> #{fasta} 2> /dev/null" system ( cmd ) i...
Write input sequence to file . Pass the raw input data through seqret to ensure FASTA format .
11,347
def set_flash_message ( key , kind , options = { } ) options [ :scope ] = "quorum.#{controller_name}" options [ :scope ] << ".errors" if key . to_s == "error" options [ :scope ] << ".notices" if key . to_s == "notice" options [ :scope ] << ".alerts" if key . to_s == "alert" message = I18n . t ( "#{kind}" , options ) fl...
I18n flash helper . Set flash message based on key .
11,348
def gap_opening_extension = ( value ) v = value . split ( ',' ) self . gap_opening_penalty = v . first self . gap_extension_penalty = v . last end
Virtual attribute setter .
11,349
def deep_transform_keys! ( object , & block ) case object when Hash object . keys . each do | key | value = object . delete ( key ) object [ yield ( key ) ] = deep_transform_keys! ( value ) { | key | yield ( key ) } end object when Array object . map! { | e | deep_transform_keys! ( e ) { | key | yield ( key ) } } else ...
Inspired by ActiveSupport s implementation
11,350
def execute ( sql , args = nil , bulk_args = nil , http_options = { } ) @logger . debug sql req = Net :: HTTP :: Post . new ( '/_sql' , headers ) body = { 'stmt' => sql } body [ 'args' ] = args if args body [ 'bulk_args' ] = bulk_args if bulk_args req . body = body . to_json response = request ( req , http_options ) @l...
Executes a SQL statement against the Crate HTTP REST endpoint .
11,351
def blob_put ( table , digest , data ) uri = blob_path ( table , digest ) @logger . debug ( "BLOB PUT #{uri}" ) req = Net :: HTTP :: Put . new ( blob_path ( table , digest ) , headers ) req . body = data response = request ( req ) case response . code when '201' true else @logger . info ( "Response #{response.code}: " ...
Upload a File to a blob table
11,352
def start_transaction_admin ( options = { } ) transaction = Janus :: Transactions :: Admin . new ( options ) transaction . connect { yield ( transaction ) } rescue raise Errors :: RRJAdmin :: StartTransactionAdmin , options end
Create a transaction between apps and Janus for request without handle
11,353
def generate_output ( inputs , output ) inputs . each do | input | begin output . write CoffeeScript . compile ( input , options ) rescue ExecJS :: Error => error raise error , "Error compiling #{input.path}. #{error.message}" end end end
By default the CoffeeScriptFilter converts inputs with the extension + . coffee + to + . js + .
11,354
def start_transaction ( exclusive = true , options = { } ) session = @option . use_current_session? ( options ) transaction = Janus :: Transactions :: Session . new ( exclusive , session ) transaction . connect { yield ( transaction ) } rescue raise Errors :: RRJ :: StartTransaction . new ( exclusive , options ) end
Return a new instance of RubyRabbitmqJanus .
11,355
def generate_output ( inputs , output ) inputs . each do | input | begin body = input . read if input . respond_to? ( :read ) local_opts = { } if @module_id_generator local_opts [ :moduleName ] = @module_id_generator . call ( input ) end opts = @options . merge ( local_opts ) opts . delete ( :module_id_generator ) outp...
Create an instance of this filter .
11,356
def start_transaction_handle ( exclusive = true , options = { } ) janus = session_instance ( options ) handle = 0 transaction = Janus :: Transactions :: Handle . new ( exclusive , janus . session , handle , janus . instance ) transaction . connect { yield ( transaction ) } rescue raise Errors :: RRJTask :: StartTransac...
Create a transaction between apps and janus with a handle
11,357
def actions lambda do | reason , data | Rails . logger . debug "Execute block code with reason : #{reason}" case reason when event then case_events ( data . to_hash ) end end end
Default method using for sending a block of code
11,358
def response ( options = { } ) elements = options . slice ( :error ) render do response_for options [ :href ] do | dav | elements . each do | name , value | status_for options [ :status ] dav . __send__ name , value end end end end
Render a WebDAV multistatus response with a single response element . This is primarily intended vor responding to single resource errors .
11,359
def duplicate_self new_self new_self . translations = translations . map ( & :dup ) new_self . translations . each { | t | t . globalized_model = new_self } children . each do | child | new_self . children << child . dup end end
A block dups all it s children and the translations
11,360
def has_set_coerce_argument_value ( enum_class , argument_value ) invalid_set_elements = [ ] set_elements = if String === argument_value argument_value . split ( ',' ) . map ( & :strip ) else Array ( argument_value ) end . map do | set_element | if result = enum_class [ set_element ] result else invalid_set_elements <<...
Understands the arguments as the list of enum values The argument value can be - a string of enum values joined by a comma - an enum constant - a symbol which resolves to the enum constant - an integer as the index of the enum class If you have just 1 value you do not need to enclose it in an Array
11,361
def unresponsive_dbhost_count ( db_host ) begin count = $hijacker_redis . hget ( redis_keys ( :unresponsive_dbhosts ) , db_host ) unless db_host . nil? ( count or 0 ) . to_i rescue 0 end end
Get the current count for the number of times requests were not able to connect to a given database host
11,362
def to_a current = @first array = [ ] while ! current . nil? array << current . data current = current . next end array end
Returns an array containing the data from the nodes in the list
11,363
def delete ( statements ) raise ( TriplestoreAdapter :: TriplestoreException , "delete received invalid array of statements" ) unless statements . any? writer = RDF :: Writer . for ( :jsonld ) uri = URI . parse ( "#{@uri}?delete" ) request = Net :: HTTP :: Post . new ( uri ) request [ 'Content-Type' ] = 'application/ld...
Delete the provided statements from the triplestore
11,364
def get_statements ( subject : nil ) raise ( TriplestoreAdapter :: TriplestoreException , "get_statements received blank subject" ) if subject . empty? subject = URI . escape ( subject . to_s ) uri = URI . parse ( format ( "%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false" , { uri : @uri , subject : subject } ) ) r...
Returns statements matching the subject
11,365
def build_namespace ( namespace ) raise ( TriplestoreAdapter :: TriplestoreException , "build_namespace received blank namespace" ) if namespace . empty? request = Net :: HTTP :: Post . new ( "#{build_url}/blazegraph/namespace" ) request [ 'Content-Type' ] = 'text/plain' request . body = "com.bigdata.rdf.sail.namespace...
Create a new namespace on the triplestore
11,366
def store ( graph ) begin statements = graph . each_statement . to_a @client . insert ( statements ) graph rescue => e raise TriplestoreAdapter :: TriplestoreException , "store graph in triplestore cache failed with exception: #{e.message}" end end
Store the graph in the triplestore cache
11,367
def delete ( rdf_url ) begin graph = fetch_cached_graph ( rdf_url ) puts "[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache" if graph . nil? return true if graph . nil? statements = graph . each_statement . to_a @client . delete ( statements ) return true rescue => e raise TriplestoreAdapter :...
Delete the graph from the triplestore cache
11,368
def fetch_cached_graph ( rdf_url ) statements = @client . get_statements ( subject : rdf_url . to_s ) if statements . count == 0 puts "[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})" return nil end RDF :: Graph . new . insert ( * statements ) end
Fetch the graph from the triplestore cache
11,369
def fetch_and_cache_graph ( rdf_url ) begin graph = RDF :: Graph . load ( rdf_url ) store ( graph ) graph rescue TriplestoreAdapter :: TriplestoreException => tse puts "[ERROR] *****\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\n[ERROR] *****\n#{tse.message}" graph rescue =>...
Fetch the graph from the source URL and cache it for future use
11,370
def get_statements ( subject : nil ) raise TriplestoreAdapter :: TriplestoreException . new ( "#{@provider.class.name} missing get_statements method." ) unless @provider . respond_to? ( :get_statements ) @provider . get_statements ( subject : subject ) end
Get statements from the server
11,371
def raise_unless_all_named_parsers_exist! config . columns_with_named_parsers . each do | name , options | parser = options [ :parser ] next if named_parsers . include? parser raise UnknownParserError . new ( name , parser , named_parsers ) end end
This error has to be raised at runtime because when the class body is being executed the parser methods won t be available unless they are defined above the column definitions in the class body
11,372
def which ( cmd , paths : search_paths ) if file_with_path? ( cmd ) return cmd if executable_file? ( cmd ) extensions . each do | ext | exe = :: File . join ( cmd , ext ) return :: File . absolute_path ( exe ) if executable_file? ( exe ) end return nil end paths . each do | path | if file_with_exec_ext? ( cmd ) exe = :...
Find an executable in a platform independent way
11,373
def search_paths ( path = ENV [ 'PATH' ] ) paths = if path && ! path . empty? path . split ( :: File :: PATH_SEPARATOR ) else %w( /usr/local/bin /usr/ucb /usr/bin /bin ) end paths . select ( & Dir . method ( :exist? ) ) end
Find default system paths
11,374
def extensions ( path_ext = ENV [ 'PATHEXT' ] ) return [ '' ] unless path_ext path_ext . split ( :: File :: PATH_SEPARATOR ) . select { | part | part . include? ( '.' ) } end
All possible file extensions
11,375
def executable_file? ( filename , dir = nil ) path = :: File . join ( dir , filename ) if dir path ||= filename :: File . file? ( path ) && :: File . executable? ( path ) end
Determines if filename is an executable file
11,376
def file_with_exec_ext? ( filename ) extension = :: File . extname ( filename ) return false if extension . empty? extensions . any? { | ext | extension . casecmp ( ext ) . zero? } end
Check if command itself has executable extension
11,377
def found_now_through_following_dayname @constructs << DateSpanConstruct . new ( start_date : @curdate , end_date : @curdate . this ( @day_index ) , comp_start : @pos , comp_end : @pos += 3 , found_in : __method__ ) end
redundant!! preprocess this out of here!
11,378
def correct_case orig = @query . split latest = @message . split orig . each_with_index do | original_word , j | if i = latest . index ( original_word . downcase ) latest [ i ] = original_word end end @message = latest . join ( ' ' ) end
returns any words in the query that appeared as input to their original case
11,379
def ordinal_dayindex ( num , day_index ) first_occ_date = ZDate . new ( ZDate . format_date ( year_str , month_str ) ) . this ( day_index ) if num <= 4 d = first_occ_date . add_weeks ( num - 1 ) else d = first_occ_date . add_weeks ( 4 ) if d . month != month d = d . sub_weeks ( 1 ) end end d end
for example 1st friday uses self as the reference month
11,380
def x_weeks_from_day ( weeks_away , day2index ) day1index = dayindex if day1index > day2index days_away = 7 * ( weeks_away + 1 ) - ( day1index - day2index ) elsif day1index < day2index days_away = ( weeks_away * 7 ) + ( day2index - day1index ) elsif day1index == day2index days_away = 7 * weeks_away end add_days ( days_...
returns a new date object
11,381
def add_days ( number ) if number < 0 return sub_days ( number . abs ) end o = dup while number > 0 if o . days_left_in_month >= number o . date = ZDate . format_date ( o . year_str , o . month_str , o . day + number ) number = 0 else number = number - 1 - o . days_left_in_month o . increment_month! end end o end
add_ methods return new ZDate object they DO NOT modify self
11,382
def sub_days ( number ) o = dup while number > 0 if ( o . day - 1 ) >= number o . date = ZDate . format_date ( o . year_str , o . month_str , o . day - number ) number = 0 else number -= o . day o . decrement_month! end end o end
sub_ methods return new ZDate object they do not modify self .
11,383
def diff_in_days ( date_to_compare ) if date_to_compare > self d1 , d2 = dup , date_to_compare . dup elsif self > date_to_compare d1 , d2 = date_to_compare . dup , dup else return 0 end total = 0 while d1 . year != d2 . year total += d1 . days_left_in_year + 1 d1 = ZDate . new ( ZDate . format_date ( d1 . year + 1 ) ) ...
Gets the absolute difference in days between self and date_to_compare order is not important .
11,384
def diff_in_months ( date2 ) if date2 > self ZDate . diff_in_months ( month , year , date2 . month , date2 . year ) else ZDate . diff_in_months ( date2 . month , date2 . year , month , year ) * - 1 end end
difference in months FROM self TO date2 for instance if self is oct 1 and date2 is nov 14 will return 1 if self is nov 14 and date2 is oct 1 will return - 1
11,385
def increment_month! if month != 12 self . date = ZDate . format_date ( year_str , month + 1 ) else self . date = ZDate . format_date ( year + 1 ) end end
Modifies self . bumps self to first day of next month
11,386
def modify_such_that_is_before ( time2 ) fail 'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set' if @firm fail 'ZTime#modify_such_that_is_before says: time2 does not have @firm set' unless time2 . firm if self > time2 if hour == 12 && time2 . hour == 0 else hour == 12 ? change_hour_to ( 0...
this can very easily be cleaned up
11,387
def send_zip ( active_storages , filename : 'my.zip' ) require 'zip' files = SendZipHelper . save_files_on_server active_storages zip_data = SendZipHelper . create_temporary_zip_file files send_data ( zip_data , type : 'application/zip' , filename : filename ) end
Zip all given files into a zip and send it with send_data
11,388
def check @nwo , @sha = parse_commit_url @commit_url begin @commit = @client . commit @nwo , @sha rescue ArgumentError raise ContributionChecker :: InvalidCommitUrlError rescue Octokit :: NotFound raise ContributionChecker :: InvalidCommitUrlError rescue Octokit :: Unauthorized raise ContributionChecker :: InvalidAcces...
Initialise a new Checker instance with an API access token and commit URL .
11,389
def parse_commit_url ( url ) begin parts = URI . parse ( @commit_url ) . path . split ( "/" ) nwo = "#{parts[1]}/#{parts[2]}" sha = parts [ 4 ] return nwo , sha rescue raise ContributionChecker :: InvalidCommitUrlError end end
Parses the commit URL provided .
11,390
def user_has_fork_of_repo? return false if @repo [ :forks_count ] == 0 if @repo [ :forks_count ] <= 100 repo_forks = @client . forks @repo [ :full_name ] , :per_page => 100 repo_forks . each do | f | return true if f [ :owner ] [ :login ] == @user [ :login ] end end potential_fork_nwo = "#{@user[:login]}/#{@repo[:name]...
Checks whether the authenticated user has forked the repository in which the commit exists .
11,391
def on_input_change ( obj = nil , & block ) @on_input_change_obj = obj @on_input_change = Proc . new { | device , obj_ptr , index , state | yield self , @inputs [ index ] , ( state == 0 ? false : true ) , object_for ( obj_ptr ) } Klass . set_OnInputChange_Handler ( @handle , @on_input_change , pointer_for ( obj ) ) end
Sets an input change handler callback function . This is called when a digital input on the PhidgetEncoder board has changed .
11,392
def crop_geometry ( ratio_vector ) crop_size = ratio_vector . fit ( size ) . round center = crop_gravity - crop_start start = center - ( crop_size / 2 ) . floor start = clamp ( start , crop_size , size ) [ crop_size , ( start + crop_start ) ] end
Calculates crop geometry . The given vector is scaled to match the image size since DynamicImage performs cropping before resizing .
11,393
def fit ( fit_size , options = { } ) fit_size = parse_vector ( fit_size ) require_dimensions! ( fit_size ) if options [ :crop ] fit_size = size . fit ( fit_size ) unless options [ :crop ] fit_size = size . contain ( fit_size ) unless options [ :upscale ] fit_size end
Adjusts + fit_size + to fit the image dimensions . Any dimension set to zero will be ignored .
11,394
def clamp ( start , size , max_size ) start += shift_vector ( start ) start -= shift_vector ( max_size - ( start + size ) ) start end
Clamps the rectangle defined by + start + and + size + to fit inside 0 0 and + max_size + . It is assumed that + size + will always be smaller than + max_size + .
11,395
def on_count ( obj = nil , & block ) @on_count_obj = obj @on_count = Proc . new { | device , obj_ptr , index , time , counts | yield self , @inputs [ index ] , time , counts , object_for ( obj_ptr ) } Klass . set_OnCount_Handler ( @handle , @on_count , pointer_for ( obj ) ) end
Sets an count handler callback function . This is called when ticks are counted on an frequency counter input or when the timeout expires
11,396
def create ptr = :: FFI :: MemoryPointer . new ( :pointer , 1 ) self . class :: Klass . create ( ptr ) @handle = ptr . get_pointer ( 0 ) true end
Create a pointer for this Device handle .. must be called before open or anything else . Called automatically when objects are instantiated in block form .
11,397
def close remove_common_event_handlers remove_specific_event_handlers sleep 0.2 Phidgets :: FFI :: Common . close ( @handle ) delete true end
Closes and frees a Phidget . This should be called before closing your application or things may not shut down cleanly .
11,398
def on_attach ( obj = nil , & block ) @on_attach_obj = obj @on_attach = Proc . new { | handle , obj_ptr | load_device_attributes yield self , object_for ( obj_ptr ) } Phidgets :: FFI :: Common . set_OnAttach_Handler ( @handle , @on_attach , pointer_for ( obj ) ) true end
Sets an attach handler callback function . This is called when the Phidget is plugged into the system and is ready for use .
11,399
def on_detach ( obj = nil , & block ) @on_detach_obj = obj @on_detach = Proc . new { | handle , obj_ptr | yield self , object_for ( obj_ptr ) } Phidgets :: FFI :: Common . set_OnDetach_Handler ( @handle , @on_detach , pointer_for ( obj ) ) true end
Sets a detach handler callback function . This is called when the Phidget is physically detached from the system and is no longer available .