idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
16,100 | def round_value ( val ) remainder = val % self . step_size unprecised = if ( remainder * 2 ) >= self . step_size ( val - remainder ) + self . step_size else val - remainder end if self . step_size < 1 precision = - Math . log10 ( self . step_size ) . floor ( unprecised * ( 10 ** precision ) ) . to_i . to_f / ( 10 ** pr... | round to nearest step size making sure we curtail precision to same order of magnitude as the step size to avoid 0 . 4 + 0 . 2 = 0 . 6000000000000001 |
16,101 | def _deserialize_value ( val , raw : false ) val = val . pack ( 'C*' ) val = @desc . post_process ( val ) if ! raw && @desc . read_processors? val end | Convert Arrays of bytes returned by DBus to Strings of bytes . |
16,102 | def css_class_options_merge ( options , css_classes = [ ] , & block ) options . symbolize_keys! css_classes += options [ :class ] . split ( ' ' ) if options . include? ( :class ) yield ( css_classes ) if block_given? options [ :class ] = css_classes . join ( ' ' ) unless css_classes . empty? unless css_classes == css_c... | This method merges the specified css_classes into the options hash |
16,103 | def filter ( uuids , rssi : nil , pathloss : nil , transport : :le ) unless [ :auto , :bredr , :le ] . include? ( transport ) raise ArgumentError , "transport must be one of :auto, :bredr, :le" end filter = { } unless uuids . nil? || uuids . empty? filter [ 'UUIDs' ] = DBus . variant ( 'as' , uuids ) end unless rssi . ... | This method sets the device discovery filter for the caller . When this method is called with + nil + or an empty list of UUIDs filter is removed . |
16,104 | def stub_with_file ( filename ) return if :: ServiceMock . disable_stubs yield self if block_given? content = File . open ( filename , 'rb' ) { | file | file . read } stub ( content ) end | Create a stub using the information in the provided filename . |
16,105 | def stub_with_erb ( filename , hsh = { } ) return if :: ServiceMock . disable_stubs yield self if block_given? template = File . open ( filename , 'rb' ) { | file | file . read } erb_content = ERB . new ( template ) . result ( data_binding ( hsh ) ) stub ( erb_content ) end | Create a stub using the erb template provided . The + Hash + second parameter contains the values to be inserted into the + ERB + . |
16,106 | def count ( request_criteria ) return if :: ServiceMock . disable_stubs yield self if block_given? JSON . parse ( http . post ( '/__admin/requests/count' , request_criteria ) . body ) [ 'count' ] end | Get the count for the request criteria |
16,107 | def count_with_file ( filename ) return if :: ServiceMock . disable_stubs yield self if block_given? content = File . open ( filename , 'rb' ) { | file | file . read } count ( content ) end | Get the count for the request criteria in the provided filename . |
16,108 | def count_with_erb ( filename , hsh = { } ) return if :: ServiceMock . disable_stubs yield self if block_given? template = File . open ( filename , 'rb' ) { | file | file . read } erb_content = ERB . new ( template ) . result ( data_binding ( hsh ) ) count ( erb_content ) end | Get the count for the request criteria using the erb template provided . The + Hash + second parameter contains the values to be inserted into the + ERB + . |
16,109 | def clear ( options = { } ) options = { color : [ 0.0 , 0.0 , 0.0 , 0.0 ] , } . merge! options color = options [ :color ] color = color . to_opengl if color . is_a? Gosu :: Color Gl . glBindFramebufferEXT Gl :: GL_FRAMEBUFFER_EXT , fbo_id unless rendering? Gl . glDisable Gl :: GL_BLEND Gl . glClearColor ( * color ) Gl ... | Clears the buffer optionally to a specific color . |
16,110 | def write ( data , fire_and_forget = true ) raise NotConnectedError , "no connection to server" unless connected? @socket . puts ( data ) @socket . flush return true if fire_and_forget read rescue Errno :: EPIPE disconnect raise BrokenConnectionError , "the connection to the server is lost" end | Writes data to the TCP server socket |
16,111 | def read ( timeout = nil ) timeout = read_timeout if timeout . nil? raw_data = nil Timeout . timeout ( timeout ) do raw_data = @socket . gets . chomp end if ( data = parse_raw_data ( raw_data ) ) data [ 1 ] else raise VLC :: ProtocolError , "could not interpret the playload: #{raw_data}" end rescue Timeout :: Error rai... | Reads data from the TCP server |
16,112 | def post_process ( * shaders ) raise ArgumentError , "Block required" unless block_given? raise TypeError , "Can only process with Shaders" unless shaders . all? { | s | s . is_a? Ashton :: Shader } unless shaders . size > 0 yield return end buffer1 = primary_buffer buffer1 . clear buffer1 . render do yield end if shad... | Full screen post - processing using a fragment shader . |
16,113 | def each_url ( & _block ) index = 0 while index < urls . count url = urls [ index ] next unless url yield url , handlers [ url ] . first , handlers [ url ] . last index += 1 end end | Override this for custom storage or prioritization of crawled URLs . Iterates through URL queue yielding the URL handler and default data . |
16,114 | def draw_as_points ( points , z , options = { } ) color = options [ :color ] || DEFAULT_DRAW_COLOR scale = options [ :scale ] || 1.0 shader = options [ :shader ] mode = options [ :mode ] || :default if shader shader . enable z $window . gl z do shader . image = self shader . color = color end end begin points . each do... | Draw a list of centred sprites by position . |
16,115 | def sample_distance ( x , y ) x = [ [ x , width - 1 ] . min , 0 ] . max y = [ [ y , height - 1 ] . min , 0 ] . max @field . red ( ( x / @scale ) . round , ( y / @scale ) . round ) - ZERO_DISTANCE end | If positive distance in pixels to the nearest opaque pixel . If negative distance in pixels to the nearest transparent pixel . |
16,116 | def sample_gradient ( x , y ) d0 = sample_distance x , y - 1 d1 = sample_distance x - 1 , y d2 = sample_distance x + 1 , y d3 = sample_distance x , y + 1 [ ( d2 - d1 ) / @scale , ( d3 - d0 ) / @scale ] end | Gets the gradient of the field at a given point . |
16,117 | def sample_normal ( x , y ) gradient_x , gradient_y = sample_gradient x , y length = Gosu :: distance 0 , 0 , gradient_x , gradient_y if length == 0 [ 0 , 0 ] else [ gradient_x / length , gradient_y / length ] end end | Get the normal at a given point . |
16,118 | def line_of_sight_blocked_at ( x1 , y1 , x2 , y2 ) distance_to_travel = Gosu :: distance x1 , y1 , x2 , y2 distance_x , distance_y = x2 - x1 , y2 - y1 distance_travelled = 0 x , y = x1 , y1 loop do distance = sample_distance x , y return [ x , y ] if distance <= 0 distance_travelled += distance return nil if distance_t... | Returns blocking position else nil if line of sight isn t blocked . |
16,119 | def render_field raise ArgumentError , "Block required" unless block_given? @mask . render do @mask . clear $window . scale 1.0 / @scale do yield self end end @shader . enable do @field . render do @mask . draw 0 , 0 , 0 end end nil end | Update the SDF should the image have changed . Draw the mask in the passed block . |
16,120 | def draw ( x , y , z , options = { } ) options = { mode : :add , } . merge! options $window . scale @scale do @field . draw x , y , z , options end nil end | Draw the field usually for debugging purposes . |
16,121 | def to_a width . times . map do | x | height . times . map do | y | sample_distance x , y end end end | Convert into a nested array of sample values . |
16,122 | def start ( detached = false ) return @pid if running? detached ? @deamon = true : setup_traps @pid = RUBY_VERSION >= '1.9' ? process_spawn ( detached ) : process_spawn_ruby_1_8 ( detached ) end | Starts a VLC instance in a subprocess |
16,123 | def process_spawn_ruby_1_8 ( detached ) rd , wr = IO . pipe if Process . fork wr . close pid = rd . read . to_i rd . close return pid else rd . close detach if detached wr . write ( Process . pid ) wr . close STDIN . reopen "/dev/null" STDOUT . reopen "/dev/null" , "a" STDERR . reopen "/dev/null" , "a" Kernel . exec "#... | For ruby 1 . 8 |
16,124 | def merge_config ( config ) defaults = { name : 'Ruby App' , version : '0.0.0' , release : 'Rookie' , ignore : 'pkg' , icons : { } , template_urls : { jar_app : JAR_APP_TEMPLATE_URL , } , validator : Furoshiki :: Validator , warbler_extensions : Furoshiki :: WarblerExtensions , working_dir : Dir . pwd , } @config = mer... | Overwrite defaults with supplied config |
16,125 | def capture Gl . glBindTexture Gl :: GL_TEXTURE_2D , id Gl . glCopyTexImage2D Gl :: GL_TEXTURE_2D , 0 , Gl :: GL_RGBA8 , 0 , 0 , width , height , 0 self end | Copy the window contents into the buffer . |
16,126 | def []= ( uniform , value ) uniform = uniform_name_from_symbol ( uniform ) if uniform . is_a? Symbol needs_use = ! current? enable if needs_use set_uniform uniform_location ( uniform ) , value disable if needs_use value end | Set the value of a uniform . |
16,127 | def set_uniform ( location , value ) raise ShaderUniformError , "Shader uniform #{location.inspect} could not be set, since shader is not current" unless current? return if location == INVALID_LOCATION case value when true , Gl :: GL_TRUE Gl . glUniform1i location , 1 when false , Gl :: GL_FALSE Gl . glUniform1i locati... | Set uniform without trying to force use of the program . |
16,128 | def process_source ( shader , extension ) source = if shader . is_a? Symbol file = File . expand_path "#{shader}#{extension}" , BUILT_IN_SHADER_PATH unless File . exist? file raise ShaderLoadError , "Failed to load built-in shader: #{shader.inspect}" end File . read file elsif File . exist? shader File . read shader el... | Symbol = > load a built - in Filename = > load file Source = > use directly . |
16,129 | def deep_set_symbol_key ( hash , key , value ) if value . kind_of? Hash hash [ key . to_sym ] = value . inject ( { } ) { | inner_hash , ( inner_key , inner_value ) | deep_set_symbol_key ( inner_hash , inner_key , inner_value ) } else hash [ key . to_sym ] = value end hash end | Ensure symbol keys even in nested hashes |
16,130 | def merge_with_symbolized_keys ( defaults , hash ) hash . inject ( defaults ) { | symbolized , ( k , v ) | deep_set_symbol_key ( symbolized , k , v ) } end | Assumes that defaults already has symbolized keys |
16,131 | def expect * patterns , & block @logger . debug ( "Expecting: #{patterns.inspect}" ) if @logger . debug? patterns = pattern_escape ( * patterns ) @end_time = 0 if ( @timeout != 0 ) @end_time = Time . now + @timeout end @before = '' matched_index = nil while ( @end_time == 0 || Time . now < @end_time ) raise ClosedError... | Wait until either the timeout occurs or one of the given patterns is seen in the input . Upon a match the property before is assigned all input in the accumulator before the match the matched string itself is assigned to the match property and an optional block is called |
16,132 | def pattern_escape * patterns escaped_patterns = [ ] patterns . each do | pattern | if ( pattern . is_a? ( String ) ) pattern = Regexp . new ( Regexp . escape ( pattern ) ) elsif ( ! pattern . is_a? ( Regexp ) ) raise "Don't know how to match on a #{pattern.class}" end escaped_patterns . push ( pattern ) end escaped_pa... | This method will convert any strings in the argument list to regular expressions that search for the literal string |
16,133 | def serialize_args ( args ) return { } if args . nil? args . each do | key , value | case value when DateTime , Time args [ key ] = value . strftime ( '%m/%d/%Y %H:%M:%S' ) when Date args [ key ] = value . strftime ( '%m/%d/%Y' ) else args [ key ] = value . to_s end end args end | { - db = > mydb - lay = > mylay email = > a |
16,134 | def match? ( arr , parser = nil ) arr = arr . to_a return false if arr . length != self . length each_with_index do | node , i | node . match? ( arr [ i ] , parser ) or return false end return true end | As defined in Node . |
16,135 | def assert_invariants ( testcase ) fields . each do | field | if val = send ( field . reader ) assert_same ( self , node . parent , "field.reader is #{field.reader}" ) if field . child? assert_same ( field , val . instance_variable_get ( :@parent_field ) , "field.reader is #{field.reader}" ) end end end end | Called by the test suite to ensure all invariants are true . |
16,136 | def each ( & blk ) fields . each do | field | if field . child? val = self . send ( field . reader ) yield val unless val . nil? end end return self end | Yield each child in field order . |
16,137 | def swap_with node return self if node . equal? self if self . attached? if node . attached? placeholder = Default . new my_parent = @parent my_parent . replace_node ( self , placeholder ) node . parent . replace_node ( node , self ) my_parent . replace_node ( placeholder , node ) else @parent . replace_node ( self , n... | Swap this node with node in their trees . If either node is detached the other will become detached as a result of calling this method . |
16,138 | def node_before ( node ) node . parent . equal? self or raise ArgumentError , "node is not a child" fields = self . fields i = node . instance_variable_get ( :@parent_field ) . index - 1 i . downto ( 0 ) do | i | f = fields [ i ] if f . child? && ( val = self . send ( f . reader ) ) return val end end return nil end | Return the Node that comes before the given Node in tree preorder . |
16,139 | def remove_node ( node ) node . parent . equal? self or raise ArgumentError , "node is not a child" field = node . instance_variable_get ( :@parent_field ) node . instance_variable_set ( :@parent , nil ) node . instance_variable_set ( :@parent_field , nil ) self . instance_variable_set ( field . var , nil ) return self... | Remove the given Node . |
16,140 | def replace_node ( node , newnode = nil ) node . parent . equal? self or raise ArgumentError , "node is not a child" field = node . instance_variable_get ( :@parent_field ) self . send ( field . writer , newnode ) return self end | Replace node with newnode . |
16,141 | def link_ ( a , nodes , b ) if nodes . empty? if a . nil? @first = b else a . instance_variable_set ( :@next , b ) end if b . nil? @last = a else b . instance_variable_set ( :@prev , a ) end else first = nodes . first if a . nil? @first = first else a . instance_variable_set ( :@next , first ) end last = nodes . last i... | Link up nodes between a and b . |
16,142 | def link2_ ( a , b ) if a . nil? @first = b else a . instance_variable_set ( :@next , b ) unless a . nil? end if b . nil? @last = a else b . instance_variable_set ( :@prev , a ) unless b . nil? end end | Special case for 2 |
16,143 | def get_ ( i ) if i < ( @length >> 1 ) node = @first i . times { node = node . next } else node = @last ( @length - 1 - i ) . times { node = node . prev } end return node end | Return the i th Node . Assume i is in 0 ... length . |
16,144 | def exec socket_fd = @socket . to_i ENV [ 'RESQUED_SOCKET' ] = socket_fd . to_s ENV [ 'RESQUED_CONFIG_PATH' ] = @config_paths . join ( ':' ) ENV [ 'RESQUED_STATE' ] = ( @old_workers . map { | r | "#{r[:pid]}|#{r[:queue]}" } . join ( '||' ) ) ENV [ 'RESQUED_LISTENER_ID' ] = @listener_id . to_s ENV [ 'RESQUED_MASTER_VERS... | Configure a new listener object . |
16,145 | def method_missing ( name , * arguments ) value = arguments [ 0 ] name = name . to_s if name [ - 1 , 1 ] == '=' key = name [ / \s / , 1 ] @data [ key . to_sym ] = value unless instance_variables . include? "@#{key}" . to_sym else @data [ name . to_sym ] end end | allow this object to be set with arbitrary key value data |
16,146 | def fetch! fields = POST_FIELDS . reject { | f | @options [ f ] . nil? } . map do | f | cgi_param = f . to_s . gsub ( / \_ / ) { | s | s . upcase } . gsub ( '_' , '' ) . sub ( / /i , 'URL' ) Curl :: PostField . content ( cgi_param , @options [ f ] ) end res = Curl :: Easy . http_post ( 'http://wherein.yahooapis.com/v1/... | Fetches the place information for input parameters from the Yahoo Placemaker service |
16,147 | def decorate ( templates , path_info , details , locals ) templates . each do | t | t . locals = locals end end | Ensures all the resolver information is set in the template . |
16,148 | def extract_handles_from_mentioner ( mentioner ) content = extract_mentioner_content ( mentioner ) handles = content . scan ( handle_regexp ) . map { | handle | handle . gsub ( "#{mention_prefix}" , "" ) } end | Extract handles from mentioner |
16,149 | def process_after_callbacks ( mentioner , mentionee ) result = true @callbacks [ :after ] . each do | callback | unless callback . call ( mentioner , mentionee ) result = false break end end result end | Process after callbacks |
16,150 | def headers { 'X-EBAY-API-COMPATIBILITY-LEVEL' => @compatability_level . to_s , 'X-EBAY-API-DEV-NAME' => dev_id . to_s , 'X-EBAY-API-APP-NAME' => app_id . to_s , 'X-EBAY-API-CERT-NAME' => cert_id . to_s , 'X-EBAY-API-CALL-NAME' => @command . to_s , 'X-EBAY-API-SITEID' => @site_id . to_s , 'Content-Type' => 'text/xml' }... | Gets the headers that will be sent with this request . |
16,151 | def http ( & block ) http = Net :: HTTP . new ( @uri . host , @uri . port ) if @uri . port == 443 http . use_ssl = true http . verify_mode = OpenSSL :: SSL :: VERIFY_NONE end return http . start ( & block ) if block_given? http end | Gets a HTTP connection for this request . If you pass in a block it will be run on that HTTP connection . |
16,152 | def retry_request ( is_read_only = false ) attempts = 0 begin yield rescue OpenSSL :: SSL :: SSLError => e raise e unless @enable_retry raise e if attempts >= @max_attempts attempts += 1 retry rescue Errno :: ECONNRESET , RestClient :: ServerBrokeConnection , RestClient :: RequestTimeout => e raise e unless @enable_ret... | Users shouldn t need to call the following methods directly |
16,153 | def do_get ( path , params = { } ) login if need_login? path = add_id_and_params_to_path ( path , params ) req , res , resource_type , body = nil begin retry_request ( true ) do resource_type , body = @rest_client [ path ] . get ( headers ) do | response , request , result , & block | req , res = request , response upd... | Generic get params are NOT read only |
16,154 | def re_login? ( e ) auth_error = ( e . response_code == 403 && e . message =~ %r( ) ) || e . response_code == 401 renewable_creds = ( @instance_token || ( @email && ( @password || @password_base64 ) ) || @refresh_token ) auth_error && renewable_creds end | Determine whether an exception can be fixed by logging in again . |
16,155 | def get_version_req ( dep ) req = get_key_or_sym ( dep , :version_requirement ) req = get_key_or_sym ( dep , :version_range ) unless req req end | At least puppet - extlib has malformed metadata |
16,156 | def do_layout ( payload , layouts ) info = { :filters => [ Jekyll :: Filters ] , :registers => { :site => site } } payload [ 'pygments_prefix' ] = converter . pygments_prefix payload [ 'pygments_suffix' ] = converter . pygments_suffix self . content = engine . render ( payload , content , info , data ) transform self .... | Overwrites the original method to use the configured rendering engine . |
16,157 | def monitor ( interests = :rw ) @monitor ||= begin raise @error if @error monitor = @ioloop . add_io_wait ( @io , interests ) { callback_on_waiting } ObjectSpace . define_finalizer ( self , self . class . finalizer ( monitor ) ) monitor end end | Create a io watcher |
16,158 | def wait_in_ioloop raise LightIO :: Error , "Watchers::IO can't cross threads" if @ioloop != LightIO :: Core :: IOloop . current raise EOFError , "can't wait closed IO watcher" if @monitor . closed? @ioloop . wait ( self ) end | Blocking until io interests is satisfied |
16,159 | def assign_confirmed_if_valid! return unless pending? self . state = EffectiveOrders :: CONFIRMED return true if valid? self . errors . clear self . state = EffectiveOrders :: PENDING false end | This lets us skip to the confirmed workflow for an admin ... |
16,160 | def create_stripe_token! return if stripe_token . blank? Rails . logger . info "[STRIPE] update source: #{stripe_token}" customer . stripe_customer . source = stripe_token customer . stripe_customer . save return if customer . stripe_customer . default_source . blank? card = customer . stripe_customer . sources . retri... | Update stripe customer card |
16,161 | def metadata { :user_id => user . id . to_s , :user => user . to_s . truncate ( 500 ) , ( subscription . subscribable_type . downcase + '_id' ) . to_sym => subscription . subscribable . id . to_s , subscription . subscribable_type . downcase . to_sym => subscription . subscribable . to_s } end | The stripe metadata limit is 500 characters |
16,162 | def to_snake_keys ( value = self ) case value when Array value . map { | v | to_snake_keys ( v ) } when Hash snake_hash ( value ) else value end end | Recursively converts CamelCase and camelBack JSON - style hash keys to Rubyish snake_case suitable for use during instantiation of Ruby model attributes . |
16,163 | def new @order ||= Effective :: Order . new ( view_context . current_cart ) EffectiveOrders . authorize! ( self , :new , @order ) unless @order . valid? flash [ :danger ] = "Unable to proceed: #{flash_errors(@order)}. Please try again." redirect_to ( effective_orders . cart_path ) return end end | If you want to use the Add to Cart - > Checkout flow Add one or more items however you do . redirect_to effective_orders . new_order_path which is here . This is the entry point for any Checkout button . It displayes an order based on the cart Always step1 |
16,164 | def create @order ||= Effective :: Order . new ( view_context . current_cart ) EffectiveOrders . authorize! ( self , :create , @order ) @order . assign_attributes ( checkout_params ) if ( @order . confirm! rescue false ) redirect_to ( effective_orders . order_path ( @order ) ) else flash . now [ :danger ] = "Unable to ... | Confirms an order from the cart . |
16,165 | def update @order ||= Effective :: Order . find ( params [ :id ] ) EffectiveOrders . authorize! ( self , :update , @order ) @order . assign_attributes ( checkout_params ) if ( @order . confirm! rescue false ) redirect_to ( effective_orders . order_path ( @order ) ) else flash . now [ :danger ] = "Unable to proceed: #{f... | Confirms the order from existing order |
16,166 | def index @orders = Effective :: Order . deep . purchased . where ( user : current_user ) @pending_orders = Effective :: Order . deep . pending . where ( user : current_user ) EffectiveOrders . authorize! ( self , :index , Effective :: Order . new ( user : current_user ) ) end | My Orders History |
16,167 | def purchased @order = if params [ :id ] . present? Effective :: Order . find ( params [ :id ] ) elsif current_user . present? Effective :: Order . sorted . purchased_by ( current_user ) . last end if @order . blank? redirect_to ( effective_orders . orders_path ) and return end EffectiveOrders . authorize! ( self , :sh... | Thank you for Purchasing this Order . This is where a successfully purchased order ends up |
16,168 | def add ( item , quantity : 1 , unique : true ) raise 'expecting an acts_as_purchasable object' unless item . kind_of? ( ActsAsPurchasable ) existing = ( if unique . kind_of? ( Proc ) cart_items . find { | cart_item | instance_exec ( item , cart_item . purchasable , & unique ) } elsif unique . kind_of? ( Symbol ) || ( ... | cart . add ( |
16,169 | def pending_order_invoice_to_buyer ( order_param ) return true unless EffectiveOrders . mailer [ :send_pending_order_invoice_to_buyer ] @order = ( order_param . kind_of? ( Effective :: Order ) ? order_param : Effective :: Order . find ( order_param ) ) @user = @order . user @subject = subject_for ( @order , :pending_or... | This is sent when someone chooses to Pay by Cheque |
16,170 | def subscription_payment_succeeded ( customer_param ) return true unless EffectiveOrders . mailer [ :send_subscription_payment_succeeded ] @customer = ( customer_param . kind_of? ( Effective :: Customer ) ? customer_param : Effective :: Customer . find ( customer_param ) ) @subscriptions = @customer . subscriptions @us... | Sent by the invoice . payment_succeeded webhook event |
16,171 | def get ( * titles , interwiki : nil , & processor ) return interwikis ( interwiki ) . get ( * titles , & processor ) if interwiki pages = get_h ( * titles , & processor ) . values . compact titles . count == 1 ? pages . first : Tree :: Nodes [ * pages ] end | Receive list of parsed MediaWiki pages for list of titles provided . All pages are received with single query to MediaWiki API . |
16,172 | def category ( title , limit : 'max' , & processor ) title = normalize_category_title ( title ) list ( @api . query . generator ( :categorymembers ) . title ( title ) , limit , & processor ) end | Receive list of parsed MediaWiki pages from specified category . |
16,173 | def join ( limit = nil ) if ! alive? || limit . nil? || limit <= 0 value return self end origin_parent = parent self . parent = Beam . current timer = LightIO :: Watchers :: Timer . new ( limit ) timer . set_callback do if alive? caller_beam = parent self . parent = origin_parent caller_beam . transfer end end ioloop .... | Block and wait beam dead |
16,174 | def raise ( error , message = nil , backtrace = nil ) unless error . is_a? ( BeamError ) message ||= error . respond_to? ( :message ) ? error . message : nil backtrace ||= error . respond_to? ( :backtrace ) ? error . backtrace : nil super ( error , message , backtrace ) end self . parent = error . parent if error . par... | Fiber not provide raise method so we have to simulate one |
16,175 | def wait_nonblock ( method , * args ) loop do result = __send__ ( method , * args , exception : false ) case result when :wait_readable io_watcher . wait_readable when :wait_writable io_watcher . wait_writable else return result end end end | wait io nonblock method |
16,176 | def process_array ( value ) value . split ( "\n" ) . map { | s | s . to_s . strip } . compact . select { | s | ! s . empty? } end | Process array of strings |
16,177 | def process ( data , type ) raise InvalidType , 'Type is invalid!' unless FORMATS . include? ( type ) send ( "process_#{type}" . to_sym , data . to_s ) end | Process data value for the format |
16,178 | def by_reference ( psp_reference ) code = Spree :: Store . joins ( orders : :payments ) . find_by ( spree_payments : { response_code : psp_reference } ) . try! ( :code ) by_store_code ( code ) end | Creates a new merchant account locator . |
16,179 | def close ( options = { } ) PostMessage ( handle , WM_SYSCOMMAND , SC_CLOSE , 0 ) wait_for_close ( options ) if ( options [ :wait_for_close ] == true ) end | PostMessage SC_CLOSE and optionally wait for the window to close |
16,180 | def wait_for_close ( options = { } ) seconds = options [ :timeout ] || 5 timeout ( seconds ) do begin yield if block_given? sleep 0.05 end until 0 == IsWindow ( handle ) end end | Wait for the window to close |
16,181 | def set_focus if is_window? keystroke ( VK_SHIFT ) ret = SetForegroundWindow ( handle ) logger . warn ( "SetForegroundWindow failed" ) if ret == 0 end end | Brings the window into the foreground and activates it . Keyboard input is directed to the window and various visual cues are changed for the user . |
16,182 | def combined_text return unless is_window? t = [ ] t << text unless text == '' children . each do | w | t << w . combined_text unless w . combined_text == '' end t . join ( "\n" ) end | The window text including all child windows joined together with newlines . Faciliates matching text . Text from any given window is limited to 2048 characters |
16,183 | def authorise3d payment = Spree :: Adyen :: RedirectResponse . find_by ( md : params [ :MD ] ) . payment payment . request_env = request . env payment_method = payment . payment_method @order = payment . order payment_method . authorize_3d_secure_payment ( payment , adyen_3d_params ) payment . capture! if payment_metho... | This is the entry point after returning from the 3DS page for credit cards that support it . MD is a unique payment session identifier returned by the card issuer . |
16,184 | def confirm_order_already_completed if psp_reference payment = @order . payments . find_by! ( response_code : psp_reference ) else payment = @order . payments . where ( source_type : "Spree::Adyen::HppSource" ) . last end payment . source . update ( source_params ) redirect_to_order end | If an authorization notification is received before the redirection the payment is created there . In this case we just need to assign the addition parameters received about the source . |
16,185 | def restore_session guest_token , payment_method_id = params . fetch ( :merchantReturnData ) . split ( "|" ) cookies . permanent . signed [ :guest_token ] = guest_token @payment_method = Spree :: PaymentMethod . find ( payment_method_id ) @order = Spree :: Order . find_by! ( number : order_number ) end | We pass the guest token and payment method id in pipe seperated in the merchantReturnData parameter so that we can recover the session . |
16,186 | def get_offset platform = ChromedriverScreenshot :: Platforms . platform offset_x = @x - platform . window_x offset_y = @y - platform . window_y [ offset_x , offset_y ] end | can t scroll past ends of page so sometimes position won t be accurate |
16,187 | def card ( header , sections ) payload = { cards : [ header : header , sections : sections ] } send_request ( payload ) end | Sends Card Message |
16,188 | def send_request ( payload ) response = @http . post payload raise APIError , response unless response . is_a? ( Net :: HTTPSuccess ) response end | Sends payload and check response |
16,189 | def ignore_columns ( * columns ) self . ignored_columns ||= [ ] self . ignored_columns += columns . map ( & :to_s ) reset_column_information descendants . each ( & :reset_column_information ) self . ignored_columns . tap ( & :uniq! ) end | Prevent Rails from loading a table column . Useful for legacy database schemas with problematic column names like class or attributes . |
16,190 | def keystroke ( * keys ) return if keys . empty? keybd_event keys . first , 0 , KEYBD_EVENT_KEYDOWN , 0 sleep KEYBD_KEYDELAY keystroke * keys [ 1 .. - 1 ] sleep KEYBD_KEYDELAY keybd_event keys . first , 0 , KEYBD_EVENT_KEYUP , 0 end | Send keystroke to the focused window keystrokes are virtual keycodes |
16,191 | def char_to_virtual_keycode ( char ) unless char . size == 1 raise "virtual keycode conversion is for single characters only" end code = char . unpack ( 'U' ) [ 0 ] case char when '0' .. '9' [ code - ?0 . ord + 0x30 ] when 'A' .. 'Z' [ VK_SHIFT , code ] when 'a' .. 'z' [ code - ?a . ord + ?A . ord ] when ' ' [ code ] w... | convert a single character to a virtual keycode |
16,192 | def all rules = [ ] raw . each do | type , details | Array ( details [ 'prefix' ] ) . each do | prefix | rules . push ( { prefix : prefix . to_s , length : details [ 'length' ] , type : type } ) end Array ( details [ 'countries' ] ) . each do | country , prefixes | Array ( prefixes ) . each do | prefix | rules . push (... | Change hash format to process rules |
16,193 | def filter ( filters = { } ) all . select do | rule | [ :country , :type ] . each do | condition | break false if filters [ condition ] && filters [ condition ] != rule [ condition ] true end end end | Returns rules according to given filters |
16,194 | def generate ( options = { } ) rule = find_rule ( options ) || return number = generate_from_rule ( rule ) { number : number , type : rule [ :type ] , country : rule [ :country ] } end | Generate a credit card number |
16,195 | def infos ( number ) rules = Rules . all . select do | rule | valid = true lengths = rule [ :length ] . is_a? ( Array ) ? rule [ :length ] : [ rule [ :length ] ] valid = false unless lengths . include? number . length valid = false unless ! ( number =~ Regexp . new ( "^#{rule[:prefix]}" ) ) . nil? valid end if rules ru... | Returns information about a number |
16,196 | def validate ( number ) criterii = { } criterii [ :luhn ] = Check . luhn number criterii [ :type ] = ! ! infos ( number ) valid = criterii . all? { | _ , v | v == true } { valid : valid , details : criterii } end | Validates a number |
16,197 | def text = ( str ) data = str . nil? ? "" : str . dup Win32 :: Clipboard . set_data ( data ) end | Clipboard text setter |
16,198 | def spam ( user_ip , user_agent , params = { } ) response = invoke_comment_method ( 'submit-spam' , user_ip , user_agent , params ) unless response . body == 'Thanks for making the web a better place.' raise_with_response response end end | Submits a comment that has been identified as spam . |
16,199 | def run original_directory = FileUtils . pwd box_name = '' rendered_template = template . render ( name : name , provider : provider , scripts : scripts ) File . open ( Boxes . config . working_dir + "#{build_name}.json" , 'w' ) do | f | f . puts rendered_template end Boxes . config . environment_vars . each do | e | e... | Initialise a new build . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.