idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
22,200
def totalPacketsSent ( ) joinThread ( ) v = MiniUPnP . UPNP_GetTotalPacketsSent ( @urls . controlURL_CIF , @data . servicetype_CIF ) ; if v < 0 then raise UPnPException . new , "Error while retriving total packets sent." end return v end
Total packets sent from the router to the external network .
22,201
def portMappings ( ) joinThread ( ) i , r = 0 , 0 mappings = Array . new while r == 0 rhost = getCString ( ) enabled = getCString ( ) duration = getCString ( ) description = getCString ( ) nport = getCString ( ) lport = getCString ( ) duration = getCString ( ) client = getCString ( ) protocol = getCString ( ) r = MiniU...
An array of mappings registered on the router
22,202
def portMapping ( nport , proto ) checkProto ( proto ) checkPort ( nport ) if nport . to_i == 0 then raise ArgumentError , "Port must be an int value and greater then 0." end joinThread ( ) client = getCString ( ) lport = getCString ( ) if MiniUPnP . UPNP_GetSpecificPortMappingEntry ( @urls . controlURL , @data . servi...
Get the mapping registered for a specific port and protocol
22,203
def deletePortMapping ( nport , proto ) checkProto ( proto ) checkPort ( nport ) joinThread ( ) r = MiniUPnP . UPNP_DeletePortMapping ( @urls . controlURL , @data . servicetype , nport . to_s , proto ) if r != 0 then raise UPnPException . new , "Failed delete mapping: #{code2error(r)}." end end
Delete the port mapping for specified network port and protocol
22,204
def checkProto ( proto ) if proto != Protocol :: UDP && proto != Protocol :: TCP then raise ArgumentError , "Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid." end end
Check that the protocol is a correct value
22,205
def register ( command , aggregate_class = nil , & block ) raise ArgumentError , 'Pass either aggregate class or block' if aggregate_class && block handler = aggregate_class || block @routes [ command ] = handler end
Registers a handler .
22,206
def route! ( command , aggregate_id , options = { } , ** data ) handler = @routes [ command ] case handler when Class transactor = options . fetch ( :transactor , default_transactor ) transactor . call ( handler , command , aggregate_id , options , ** data ) when handler . respond_to? ( :call ) handler . call ( command...
Routes a command to the registered target . Raises NotFoundError if no corresponding target can be found .
22,207
def attribute ( name , options = { } ) attributes << name unless attributes . include? ( name ) defaults [ name ] = options [ :default ] if options . has_key? ( :default ) if options . has_key? ( :accessors ) to_define = Array ( options [ :accessors ] ) & accessor_options else to_define = [ :reader , :writer ] end to_d...
Declares persisted attributes . All attributes are stored on the Riak hash .
22,208
def index ( name ) indices [ name ] = Index . new ( name ) unless indices . include? ( name ) end
Index any attribute on your model . Once you index an attribute you can use it in find statements .
22,209
def action_any_of? ( * actions ) actions . any? do | sub_ca | if sub_ca . present? sub_controller , sub_action = extract_controller_and_action ( sub_ca ) ( ( self . controller_path == sub_controller ) || ( sub_controller . blank? ) ) && ( self . action_name == sub_action || ( sub_action == '' || sub_action == '*' ) ) e...
Returns true if current controller and action names equals to any of passed . Asterik as action name matches all controller s action .
22,210
def extract_controller_and_action ( ca ) raise ArgumentError , "Pass the string" if ca . nil? slash_pos = ca . rindex ( '#' ) raise ArgumentError , "Invalid action: #{ca}" if slash_pos . nil? controller = ca [ 0 , slash_pos ] action = ca [ slash_pos + 1 .. - 1 ] || "" raise ArgumentError , "Invalid action or controller...
Extracts controller and action names from a string .
22,211
def call ( event_name , payload ) return unless data_present? ( payload ) self . fnord . event ( { :_type => event_name , :payload => payload } ) self . fnord . event ( { :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}" , :payload => payload . values . first . keys } ) end
I guess this is toooooo sloooow but anyhow let s play with it
22,212
def make_tmpname ( basename , n ) extension = File . extname ( basename ) sprintf ( "%s,%d,%d%s" , File . basename ( basename , extension ) , $$ , n . to_i , extension ) end
Replaces Tempfile s + make_tmpname + with one that honors file extensions . Copied from Paperclip
22,213
def get ( path , params = { } ) dont_parse_response = params . delete ( :dont_parse_response ) options = { :content_type => :json , :accept => :json , :params => params . merge ( :apikey => @api_key , :source => @source ) } RestClient . get ( "#{@litmosURL}/#{path}" , options ) do | response , request , result | case r...
Initialize with an API key and config options
22,214
def station_time ( station ) @station_code = station [ 'Code' ] if ! station [ 'StationTogether1' ] . empty? @station_code += ",#{station['StationTogether1']}" end if ! station [ 'StationTogether2' ] . empty? @station_code += ",#{station['StationTogether2']}" end @metro_time = RestClient . get "#{BASE_URL}/StationPredi...
This makes an api call to grab the train arrival and departure predictions . If more than one line is present at a station such is concatenated and the call is made on all lines .
22,215
def update! ( params ) response = @@soap . updateTemplate ( :apiKey => params [ :apiKey ] || CAMPAIGN_MONITOR_API_KEY , :templateID => @templateID , :templateName => params [ :templateName ] , :hTMLPageURL => params [ :htmlPageURL ] , :zipFileURL => params [ :zipFileURL ] , :screenshotURL => params [ :screenshotURL ] )...
Updates an existing template .
22,216
def force_encoding ( data , encoding = Encoding . default_external ) return data if data . respond_to? ( :rewind ) if data . respond_to? ( :force_encoding ) data . force_encoding ( encoding ) . encode! elsif data . respond_to? ( :each_value ) data . each_value { | v | force_encoding ( v , encoding ) } elsif data . resp...
stolen from sinatra Fixes encoding issues by casting params to Encoding . default_external
22,217
def install_codeqa_git_hook git_root = app_path . join ( '.git' ) pre_commit_path = git_root . join 'hooks' , 'pre-commit' return false unless File . exist? ( git_root ) return false if File . exist? ( pre_commit_path ) pre_commit_path . make_symlink ( '../../.codeqa/git_hook.rb' ) true end
return true if installation succeeded return false if either no git repo or hook already present
22,218
def list_amis ( distro ) amis = Hash . new Ubuntu . release ( distro ) . amis . each do | ami | amis [ build_type ( ami . region , ami . arch , ami . root_store , ami . virtualization_type ) ] = ami . name end amis end
Iterates over the AMIs available for the specified distro .
22,219
def exit_node ( tree_node ) parent = @stack . last if @delegate @delegate . exit_node ( tree_node ) if @delegate . respond_to? :exit_node else @on_exit_tree_node_blocks . each do | b | if b . arity == 1 b . call ( tree_node ) elsif b . arity == 2 b . call ( tree_node , parent ) end end end @stack . pop end
called on tree node at end of the visit i . e . oll subtree are visited
22,220
def visit_leaf ( leaf_node ) parent = @stack . last if @delegate @delegate . visit_leaf ( leaf_node ) if @delegate . respond_to? :visit_leaf else @on_visit_leaf_node_blocks . each do | b | if b . arity == 1 b . call ( leaf_node ) elsif b . arity == 2 b . call ( leaf_node , parent ) end end end end
called when visit leaf node
22,221
def to_md lines = @text . split ( "\n" , - 1 ) lines . collect do | line | result = line unless result =~ / \s / result . sub! ( / / ) { | s | "#" * s . length } unless result =~ / / result . gsub! ( / \A \\ \* \* \* \* \\ \* / , '\1**\2**' ) result . gsub! ( / \A \\ \+ \+ \+ / , '\1`\2`' ) result . gsub! ( / \A \s \S ...
The initializer takes an optional text which is the document to be converted from rdoc style to markdown . Convert the existing document to markdown . The result is returned as a String .
22,222
def templates response = @@soap . getClientTemplates ( :apiKey => @apiKey , :clientID => @clientID ) templates = handle_response response . client_GetTemplatesResult templates . collect { | template | Template . new ( template . templateID , template . name , template . previewURL , template . screenshotURL , :apiKey =...
Gets a list of all templates for a client .
22,223
def lists response = @@soap . getClientLists ( :apiKey => @apiKey , :clientID => @clientID ) lists = handle_response response . client_GetListsResult lists . collect { | list | List . new ( list . listID , list . name , :apiKey => @apiKey ) } end
Gets a list of all subscriber lists for a client .
22,224
def campaigns response = @@soap . getClientCampaigns ( :apiKey => @apiKey , :clientID => @clientID ) campaign_list = handle_response response . client_GetCampaignsResult campaign_list . collect do | campaign | Campaign . new ( campaign . campaignID , campaign . subject , campaign . name , campaign . sentDate , campaign...
Gets a list of all campaigns that have been sent for a client .
22,225
def update_access_and_billing! ( params ) response = @@soap . updateClientAccessAndBilling ( :apiKey => @apiKey , :clientID => @clientID , :accessLevel => params [ :accessLevel ] , :username => params . fetch ( :username , "" ) , :password => params . fetch ( :password , "" ) , :billingType => params . fetch ( :billing...
Update the access and billing settings of an existing client leaving the basic details untouched .
22,226
def update_basics! ( params ) response = @@soap . updateClientBasics ( :apiKey => @apiKey , :clientID => @clientID , :companyName => params [ :companyName ] , :contactName => params [ :contactName ] , :emailAddress => params [ :emailAddress ] , :country => params [ :country ] , :timezone => params [ :timezone ] ) handl...
Updates the basic details of an existing client . If you wish to change only some details the others must be included as they currently are . Please note that the client s existing access and billing details will remain unchanged by a call to this method .
22,227
def save_aggregate ( aggregate , concurrency : :none ) changeset = aggregate . changeset events = changeset . events . map { | event | event . with_metadata ( namespace : @namespace ) } revision = aggregate . revision if concurrency == :optimistic stream ( aggregate . class , changeset . aggregate_id ) . write_events (...
Saves an aggregate to the repository appending events to the corresponding stream .
22,228
def update_status ( unsent_reg_ids , all_results , multicast_result ) results = multicast_result . results raise RuntimeError , "Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}" unless results . size == unsent_reg_ids . size new_unsent_reg_ids = [ ] unsent_reg_ids . each_...
Updates the status of the messages sent to devices and the list of devices that should be retried .
22,229
def selections ( field , options = { } , html_options = { } ) SelectionTag . new ( self , object , field , options , html_options ) . select_tag end
Create a select list based on the field name finding items within Selection .
22,230
def radios ( field , options = { } ) html_options = options . clone html_options . delete_if { | key , value | key == :system_code } SelectionTag . new ( self , object , field , options , html_options ) . radio_tag end
Build a radio button list based field name finding items within Selection
22,231
def method_missing ( symbol , * args ) ( args . empty? and attrs . has_key? ( symbol ) ) ? attrs [ symbol ] : super end
Return + true + if the node is equal to + other + . Normally this means + other + is an instance of the same class or a subclass and has equal children and attributes .
22,232
def monitor_association_changes ( association ) define_method "#{association}=" do | value | attribute_will_change! ( association . to_s ) if _association_will_change? ( association , value ) super ( value ) end ids = "#{association.to_s.singularize}_ids" define_method "#{ids}=" do | value | attribute_will_change! ( as...
Creates methods that allows an + association + to be monitored .
22,233
def encode_with_ts ( value ) public_key = OpenSSL :: PKey :: RSA . new ( self . public_key_str ) payload = "#{value}|#{self.now_timestamp}" return Base64 . encode64 ( public_key . public_encrypt ( payload ) ) end
Will add on timestamp according to Relais protocol encrypt and Base64 - encode all per Relais protocol .
22,234
def moon_phase ( location ) response = get ( 'astronomy' , location ) { age : response [ 'moon_phase' ] [ 'ageOfMoon' ] . to_i , illumination : response [ 'moon_phase' ] [ 'percentIlluminated' ] . to_i } end
Gets the current moon phase of the location .
22,235
def sun_info ( location ) response = get ( 'astronomy' , location ) { rise : { hour : response [ 'moon_phase' ] [ 'sunrise' ] [ 'hour' ] . to_i , minute : response [ 'moon_phase' ] [ 'sunrise' ] [ 'minute' ] . to_i } , set : { hour : response [ 'moon_phase' ] [ 'sunset' ] [ 'hour' ] . to_i , minute : response [ 'moon_p...
Gets sunrise and sunset information for the current day at the current location .
22,236
def parse_simple_forecast ( response ) ret = { } response [ 'forecast' ] [ 'txt_forecast' ] [ 'forecastday' ] . each do | f | ret [ f [ 'period' ] ] = { weekday_name : f [ 'title' ] , text : f [ 'fcttext' ] , text_metric : f [ 'fcttext_metric' ] , image_url : f [ 'icon_url' ] } end ret end
Parses the simple forecast information .
22,237
def parse_complex_forecast ( response ) ret = { } response [ 'forecast' ] [ 'simpleforecast' ] [ 'forecastday' ] . each do | f | date = f [ 'date' ] ret [ f [ 'period' ] - 1 ] = { date : DateTime . new ( date [ 'year' ] , date [ 'month' ] , date [ 'day' ] , date [ 'hour' ] , date [ 'min' ] . to_i , date [ 'sec' ] , dat...
Parses the complex forecast information .
22,238
def reopen_io ( io , path , mode = nil ) begin if mode io . reopen ( path , mode ) else io . reopen ( path ) end io . binmode rescue :: Exception end end
Attempts to reopen an IO object .
22,239
def gxapi_get_variant ( identifier , ivar_name = :variant ) if params [ ivar_name ] val = Gxapi :: Ostruct . new ( value : { index : - 1 , experiment_id : nil , name : params [ ivar_name ] } ) else val = self . gxapi_base . get_variant ( identifier ) end return instance_variable_set ( "@#{ivar_name}" , val ) end
Get the variant and set it as an instance variable handling overriding by passing in the URL
22,240
def process ( request , body , status , headers , exception = nil ) request . env [ ENV_RUNTIME ] = Time . now . to_f - request . env [ ENV_RUNTIME_START ] request . env [ ENV_EXCEPTION ] = nil if ! exception . nil? request . env [ ENV_EXCEPTION ] = exception WebProfiler :: Engine . process_exception ( request ) . fini...
Process the request .
22,241
def search ( page = 0 ) url = Pirata . config [ :base_url ] + "/search/#{URI.escape(@query)}" + "/#{page.to_s}" + "/#{@sort_type}" + "/#{@category}" html = Pirata :: Search . parse_html ( url ) Pirata :: Search :: parse_search_page ( html , self ) end
Perform a search and return an array of Torrent objects
22,242
def search_page ( page ) raise "Search must be multipage to search pages" if ! multipage? raise "Page must be a valid, positive integer" if page . class != Fixnum || page < 0 raise "Invalid page range" if page > @pages self . search ( page ) end
Return the n page results of a search assuming it is multipage
22,243
def parse_html ( url ) response = open ( url , :allow_redirections => Pirata . config [ :redirect ] ) Nokogiri :: HTML ( response ) end
Parse HTML body of a supplied URL
22,244
def get_international ( parcel_params ) response = @connection . get INTERNATIONAL_URL , params : parcel_params options = response . parsed . tap do | so | so . delete ( 'success' ) so . delete ( 'message_id' ) end RecursiveOpenStruct . new ( options , recurse_over_arrays : true ) end
Search for International Shipping Options
22,245
def run ( dirname = nil , tree_node_visitor = nil , & block ) if dirname and dirname . respond_to? ( :enter_node ) tree_node_visitor = dirname dirname = nil end if @dirname . nil? and dirname . nil? raise 'missing starting directory' end @dirname = dirname if dirname if tree_node_visitor and block raise 'cannot use blo...
Run the visitor through the directory tree
22,246
def process_directory ( dirname , level = 1 ) begin entries = Dir . entries ( dirname ) . sort rescue Errno :: EACCES => e $stderr . puts e @visitor . cannot_enter_node ( dirname , e ) return rescue Errno :: EPERM => e $stderr . puts e @visitor . cannot_enter_node ( dirname , e ) return rescue Errno :: ENOENT => e $std...
recurse on other directories
22,247
def cxx_plugin ( & blk ) if blk . arity != @expected_arity return end case blk . arity when 0 blk . call ( ) when 3 blk . call ( @cxxproject2rake , @building_blocks , @log ) end end
method for plugins to get the cxxproject2rake building_blocks log
22,248
def node_healthy? ( hostname , services = [ ] , iterations = 60 ) print "Waiting for #{hostname} to become healthy" services = services . reject { | s | get_service_check ( s ) . empty? } . freeze iterations . times do print '.' checks = hostname_health_checks ( hostname ) has_services = ( services - checks . map { | c...
Wait for all health checks on the host to become healthy .
22,249
def available_services ( index = nil ) loop do begin resp , nindex = _service . get_all ( index : index ) return [ resp . keys - [ 'consul' ] , nindex ] if nindex != index rescue Diplomat :: Timeout end end end
Blocks forever waiting for updates to the list of available services .
22,250
def service_addresses ( service , index = nil ) loop do addresses , nindex = service_addresses! ( service , index ) return [ addresses , nindex ] if addresses && nindex end end
Blocks forever waiting for updates to service addresses .
22,251
def service_addresses! ( service , index = nil ) meta = { } resp = _service . get ( service , :all , { index : index , wait : '2s' } , meta ) if ( nindex = meta [ :index ] ) != index addresses = resp . map do | address | { id : address . ServiceID , ip : address . ServiceAddress , node : address . Node , port : address...
Non - blocking request for service_addresses .
22,252
def matches ( media_type ) type , subtype , params = parse_media_type ( media_type ) values . select { | v | if v == media_type || v == '*/*' true else t , s , p = parse_media_type ( v ) t == type && ( s == '*' || s == subtype ) && ( p == '' || params_match? ( params , p ) ) end } . sort_by { | v | v . length } . rever...
Returns an array of media types from this header that match the given + media_type + ordered by precedence .
22,253
def params_match? ( params , match ) return true if params == match parsed = parse_range_params ( params ) parsed == parsed . merge ( parse_range_params ( match ) ) end
Returns true if all parameters and values in + match + are also present in + params + .
22,254
def words ( pos_name ) pos . select { | w , c | c . include? ( pos_code_map . key ( pos_name ) ) } . keys end
Get words by pos name
22,255
def apply ( match_method_name ) start_pos = @scanner . pos if m = memo ( match_method_name , start_pos ) recall m , match_method_name else m = inject_fail match_method_name , start_pos save m , eval_rule ( match_method_name ) end end
Apply a rule by dispatching to the given match method . The result of applying the rule is memoized so that the match method is invoked at most once at a given parse position .
22,256
def from_array ( data ) n = data . length if data . reject { | l | Numeric === l } . size == 0 a = self . new ( n , 1 ) ( 0 ... data . length ) . each do | i | a [ i , 0 ] = data [ i ] end return a else begin lengths = data . collect { | v | v . length } rescue raise "All columns must be arrays" end raise "All columns ...
Create a new matrix . There are two ways to use this function
22,257
def each ( io ) if block_given? filter = BELParser :: ASTFilter . new ( BELParser :: ASTGenerator . new ( io ) , * TYPES ) filter . each do | results | yield results end else enum_for ( :each , io ) end end
Yields Term AST to the block argument or provides an enumerator of Term AST .
22,258
def request ( method , path , query = { } , body = nil , headers = { } ) AwsRequest . new ( aws_http_connection ) . tap do | aws_request | aws_request . credentials = credentials aws_request . path = path aws_request . region = region aws_request . service = service aws_request . method = method aws_request . query = q...
Give the region service and optionally the AwsCredentials .
22,259
def action ( action_name , path = "/" , options = { } ) retries = 0 begin options , path = path , "/" if path . is_a? ( Hash ) && options . empty? request ( :post , path , { } , options . merge ( "Action" => action_name ) ) . response . tap do | response | unless response . success? element = response . doc . xpath ( "...
Call an AWS API with the given name at the given path . An optional hash of options can be passed as arguments for the API call .
22,260
def is_authorized_for_action? action = params [ :action ] . to_sym self . class . authorizable_config ||= DefaultConfig . config if ! self . class . authorizable_config [ action ] action = Authorizable :: Controller . alias_action ( action ) end settings_for_action = self . class . authorizable_config [ action ] result...
check if the resource can perform the action
22,261
def is_authorized_for_action_with_config? ( action , config ) request_may_proceed = false return true unless config . present? defaults = { user : current_user , permission : action . to_s , message : I18n . t ( 'authorizable.not_authorized' ) , flash_type : Authorizable . configuration . flash_error } options = defaul...
check if the resource can perform the action and respond according to the specefied config
22,262
def evaluate_action_permission ( options ) if options [ :target ] object = instance_variable_get ( "@#{options[:target]}" ) return options [ :user ] . can? ( options [ :permission ] , object ) else return options [ :user ] . can? ( options [ :permission ] ) end end
run the permission
22,263
def get_drive_files_list ( folder ) ls = Hash . new page_token = nil begin ( files , page_token ) = folder . files ( "pageToken" => page_token ) files . each do | f | ls [ f . original_filename ] = f end end while page_token return ls end
Get all file from drive folder
22,264
def insert_sentence ( hash ) thrift_method = "mutateRow" thrift_table = hash [ :into ] thrift_calls = [ ] hash [ :values ] . each do | value_set | thrift_row = SecureRandom . uuid thrift_mutations = [ ] i = 0 hash [ :columns ] . each do | col | thrift_mutations << HBase :: Mutation . new ( column : col , value : value_...
When SQL sentence is an INSERT query generate the Thrift mutations according to the specified query values .
22,265
def select_sentence ( hash ) thrift_method = "getRowsByScanner" thrift_table = hash [ :from ] thrift_columns = hash [ :select ] thrift_filters = recurse_where ( hash [ :where ] || [ ] ) thrift_limit = hash [ :limit ] HipsterSqlToHbase :: ThriftCallGroup . new ( [ { :method => thrift_method , :arguments => [ thrift_tabl...
When SQL sentence is a SELECT query generate the Thrift filters according to the specified query values .
22,266
def filters_from_key_value_pair ( kvp ) kvp [ :qualifier ] = kvp [ :column ] . split ( ':' ) kvp [ :column ] = kvp [ :qualifier ] . shift if ( kvp [ :condition ] . to_s != "LIKE" ) "(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',#{kvp[:condition]},'binary:#{kvp[:value]}',true,true))" else kvp...
Generate a Thrift QualifierFilter and ValueFilter from key value pair .
22,267
def find_all_grouped_by_language all_files = Dir . glob ( File . join ( @base_path , '**/*' ) ) found_files = all_files . select { | file_path | file_path !~ @exclude_regex && ! File . directory? ( file_path ) } found_files = found_files . select { | file_path | content = File . open ( file_path , 'r' ) { | f | f . rea...
Initializes a file search object .
22,268
def build_url parts = [ ] uri = "" parts << "/#{@version}" if @version parts << "/#{@domain}" if @domain parts << "/#{@service}" if @service uri = parts . join ( "" ) parts << "?" parts << "format=#{@format}" parts << "&#{authentication_params(uri)}" parts << "#{format_parameters}" if @parameters @url = parts . join ( ...
build service url
22,269
def execute ( refresh = false ) return @response if @response && ! refresh validate build_url @done = true DomainTools . counter! require 'net/http' begin Net :: HTTP . start ( @host ) do | http | req = Net :: HTTP :: Get . new ( @url ) @http = http . request ( req ) @success = validate_http_status return finalize end ...
Connect to the server and execute the request
22,270
def trade ( currency_code , price , amount , action , limit = nil , counter_currency_code = "jpy" ) currency_pair = currency_code + "_" + counter_currency_code params = { :currency_pair => currency_pair , :action => action , :price => price , :amount => amount } params . store ( :limit , limit ) if limit json = post_ss...
Issue trade . Need api key .
22,271
def bid ( currency_code , price , amount , limit = nil , counter_currency_code = "jpy" ) return trade ( currency_code , price , amount , "bid" , limit , counter_currency_code ) end
Issue bid order . Need api key .
22,272
def ask ( currency_code , price , amount , limit = nil , counter_currency_code = "jpy" ) return trade ( currency_code , price , amount , "ask" , limit , counter_currency_code ) end
Issue ask order . Need api key .
22,273
def withdraw ( currency_code , address , amount , option = { } ) option [ "currency" ] = currency_code option [ "address" ] = address option [ "amount" ] = amount json = post_ssl ( @zaif_trade_url , "withdraw" , option ) return json end
Withdraw funds . Need api key .
22,274
def associations @associations ||= [ ] . tap do | fields | @model . reflect_on_all_associations . each do | association | fields << resolve ( association . macro , association . name ) end end end
Collects fields from model associations
22,275
def strict_merge_with_env ( default : , local : , prefix : ) hsh = { } default . each do | k , v | env = "#{prefix}_#{k}" if v . is_a? ( Hash ) l = local [ k ] || { } hsh [ k ] = strict_merge_with_env ( default : default [ k ] , local : l , prefix : env ) else hsh [ k ] = first_non_nil ( get_env ( env ) , local [ k ] ,...
Applies a deep merge while respecting the values from environment variables . A deep merge consists of a merge of all the nested elements of the two given hashes config and local . The config hash is supposed to contain all the accepted keys and the local hash is a subset of it .
22,276
def get_env ( key ) env = ENV [ key . upcase ] return nil if env . nil? return true if env . casecmp ( "true" ) . zero? return false if env . casecmp ( "false" ) . zero? begin Integer ( env ) rescue ArgumentError env end end
Get the typed value of the specified environment variable . If it doesn t exist it will return nil . Otherwise it will try to cast the fetched value into the proper type and return it .
22,277
def evaluate ( m ) return self . owner . instance_eval ( m ) if self . owner != nil && self . owner . respond_to? ( m ) return self . instance_eval ( m ) if self . respond_to? ( m ) nil end
this is the associated object
22,278
def validate_parent ( parent ) raise InvalidParent . create ( parent , self ) unless ( ! parent . nil? && is_valid_parent? ( parent ) ) parent . validate_child ( self ) end
determine whether the parent is valid for this object . See description of validate_child for more detail . This method calls validate_child to perform the actual validation .
22,279
def match_documents ( mind_results , database_results , key = 'id' ) return [ ] unless database_results mind_results . each_with_object ( [ ] ) do | result , arr | next unless ( doc = database_results . find { | s | s [ key ] . to_s == result [ 'document_id' ] . to_s } ) arr << doc . attributes . merge ( result ) end e...
Takes two result arrays and using the specified key merges the two
22,280
def generate_secret if defined? ( SecureRandom ) SecureRandom . urlsafe_base64 ( 32 ) else Base64 . encode64 ( Digest :: SHA256 . digest ( "#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}" ) ) . gsub ( '/' , '-' ) . gsub ( '+' , '_' ) . gsub ( '=' , '' ) . strip end end
Generate a unique cryptographically secure secret
22,281
def encrypt_password ( password , salt , hash ) case hash . to_s when 'sha256' Digest :: SHA256 . hexdigest ( "#{password}-#{salt}" ) else raise 'Unsupported hash algorithm' end end
Obfuscate a password using a salt and a cryptographic hash function
22,282
def decode_scopes ( scopes ) if scopes . is_a? ( Array ) scopes . map { | s | s . to_s . strip } else scopes . to_s . split ( ' ' ) . map { | s | s . strip } end end
Decode a space delimited string of security scopes and return an array
22,283
def check_method ( tab_ops , prefix , method_sym , do_call , * arguments , & block ) method_sym = method_sym . id2name verb = :get [ :post , :get , :delete , :put ] . each do | averb | if method_sym . start_with? averb . id2name verb = averb method_sym [ averb . id2name + '_' ] = '' break end end if tab_ops [ verb ] . ...
Dynamic check of methods tab_ops contain the list of allowed method and verbs prefix the prefix to add to the method
22,284
def handle_message ( metadata , payload ) @consumers . each do | consumer | action = metadata . routing_key . split ( '.' , 2 ) . first if ( action == "publish" ) exchange = metadata . attributes [ :headers ] [ "exchange_name" ] queue = metadata . routing_key . split ( '.' , 2 ) . last item = { :date => Time . now , :e...
Raised on receipt of a message from RabbitMq and uses the appropriate appender
22,285
def get_experiments @experiments ||= begin data = Gxapi . with_error_handling do self . list_experiments_from_cache end ( data || [ ] ) . collect { | data | Ostruct . new ( data ) } end end
return a list of all experiments
22,286
def get_variant ( identifier ) experiment = self . get_experiment ( identifier ) if self . run_experiment? ( experiment ) variant = self . select_variant ( experiment ) return variant if variant . present? end return Ostruct . new ( name : "default" , index : - 1 , experiment_id : nil ) end
get a variant for an experiment
22,287
def list_experiments response = self . client . execute ( { api_method : self . analytics_experiments . list , parameters : { accountId : self . config . account_id . to_s , profileId : self . config . profile_id . to_s , webPropertyId : self . config . web_property_id } } ) response . data . items . collect ( & :to_ha...
List all experiments for our account
22,288
def client @client ||= begin client = Google :: APIClient . new client . authorization = Signet :: OAuth2 :: Client . new ( token_credential_uri : 'https://accounts.google.com/o/oauth2/token' , audience : 'https://accounts.google.com/o/oauth2/token' , scope : 'https://www.googleapis.com/auth/analytics.readonly' , issue...
google api client
22,289
def select_variant ( experiment ) accum = 0.0 sample = Kernel . rand experiment . variations . each_with_index do | variation , i | variation . index = i variation . experiment_id = experiment . id accum += variation . weight if sample <= accum return variation end end return nil end
Select a variant from a given experiment
22,290
def merge ( subtree , prefix , name , options = { } ) register ( prefix , name , options ) subtree . calls . each do | key , command | next unless command calls [ "#{prefix}#{key}" ] = command end end
merge a subtree with a prefix and a name
22,291
def scm_dir dir , scm = SCM :: DIRS . find { | dir , scm | scm == @scm } return dir end
The control directory used by the SCM .
22,292
def locations ( parameters ) allowed_parameters = %w( query x y type ) query = create_query ( parameters , allowed_parameters ) locations = perform ( 'locations' , query ) locations [ 'stations' ] end
= > find locations
22,293
def connections ( parameters ) allowed_parameters = %w( from to via date time isArrivalTime transportations limit page direct sleeper couchette bike ) query = create_query ( parameters , allowed_parameters ) locations = perform ( 'connections' , query ) locations [ 'connections' ] end
= > find connections
22,294
def stationboard ( parameters ) allowed_parameters = %w( station id limit transportations datetime ) query = create_query ( parameters , allowed_parameters ) locations = perform ( 'stationboard' , query ) locations [ 'stationboard' ] end
= > find station boards
22,295
def method_missing ( method_name , * arguments , & block ) if method_name . to_s =~ / / self . cache . try ( :[] , method_name . to_s ) else super end end
Delegate the methods start with actor_ or target_ to cached result
22,296
def update ( options = { } ) response = ProfitBricks . request ( method : :patch , path : "/datacenters/#{datacenterId}/loadbalancers/#{id}" , expects : 202 , body : options . to_json ) if response self . requestId = response [ 'requestId' ] @properties = @properties . merge ( response [ 'properties' ] ) end self end
Update the loadbalancer .
22,297
def sign ( time ) unencrypted_signature = @api_key + @secret + time + @user . to_s to_digest = unencrypted_signature + unencrypted_signature . length . to_s return Digest :: MD5 . hexdigest ( to_digest ) end
Method for constructing a signature
22,298
def normalized_author ( author ) return "" if author . nil? || author . empty? author = author . downcase if author =~ / \A \s \s / author = $1 end author . gsub! ( / \A \s / , '' ) author . gsub! ( PUNCT_STRIP_REGEX , ' ' ) author . strip! author . gsub! ( / \s / , ' ' ) return author end
Lowercase and try to get just the last name out of something that looks like a cataloging authorized heading .
22,299
def sitemap_meta_keywords return controller . sitemap_meta_data [ :keywords ] . blank? ? nil : tag ( :meta , { name : :keywords , content : controller . sitemap_meta_data [ :keywords ] } , false , false ) end
Generates a keywords meta tag for use inside HTML header area .