idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
7,900
def checksum ( entropy ) b = Bitcoin . sha256 ( [ entropy ] . pack ( 'B*' ) ) . unpack ( 'B*' ) . first b . slice ( 0 , ( entropy . length / 32 ) ) end
calculate entropy checksum
7,901
def to_wif version = Bitcoin . chain_params . privkey_version hex = version + priv_key hex += '01' if compressed? hex += Bitcoin . calc_checksum ( hex ) Base58 . encode ( hex ) end
export private key with wif format
7,902
def sign ( data , low_r = true , extra_entropy = nil ) sig = secp256k1_module . sign_data ( data , priv_key , extra_entropy ) if low_r && ! sig_has_low_r? ( sig ) counter = 1 until sig_has_low_r? ( sig ) extra_entropy = [ counter ] . pack ( 'I*' ) . bth . ljust ( 64 , '0' ) . htb sig = secp256k1_module . sign_data ( da...
sign + data + with private key
7,903
def verify ( sig , origin ) return false unless valid_pubkey? begin sig = ecdsa_signature_parse_der_lax ( sig ) secp256k1_module . verify_sig ( origin , sig , pubkey ) rescue Exception false end end
verify signature using public key
7,904
def to_point p = pubkey p ||= generate_pubkey ( priv_key , compressed : compressed ) ECDSA :: Format :: PointOctetString . decode ( p . htb , Bitcoin :: Secp256k1 :: GROUP ) end
generate pubkey ec point
7,905
def ecdsa_signature_parse_der_lax ( sig ) sig_array = sig . unpack ( 'C*' ) len_r = sig_array [ 3 ] r = sig_array [ 4 ... ( len_r + 4 ) ] . pack ( 'C*' ) . bth len_s = sig_array [ len_r + 5 ] s = sig_array [ ( len_r + 6 ) ... ( len_r + 6 + len_s ) ] . pack ( 'C*' ) . bth ECDSA :: Signature . new ( r . to_i ( 16 ) , s ....
Supported violations include negative integers excessive padding garbage at the end and overly long length descriptors . This is safe to use in Bitcoin because since the activation of BIP66 signatures are verified to be strict DER before being passed to this module and we know it supports all violations present in the ...
7,906
def encode ( hex ) leading_zero_bytes = ( hex . match ( / / ) ? $1 : '' ) . size / 2 int_val = hex . to_i ( 16 ) base58_val = '' while int_val > 0 int_val , remainder = int_val . divmod ( SIZE ) base58_val = ALPHABET [ remainder ] + base58_val end ( '1' * leading_zero_bytes ) + base58_val end
encode hex value to base58 string .
7,907
def decode ( base58_val ) int_val = 0 base58_val . reverse . split ( / / ) . each_with_index do | char , index | raise ArgumentError , 'Value passed not a valid Base58 String.' if ( char_index = ALPHABET . index ( char ) ) . nil? int_val += char_index * ( SIZE ** index ) end s = int_val . to_even_length_hex s = '' if s...
decode base58 string to hex value .
7,908
def calculate_witness_commitment witness_hashes = [ COINBASE_WTXID ] witness_hashes += ( transactions [ 1 .. - 1 ] . map ( & :witness_hash ) ) reserved_value = transactions [ 0 ] . inputs [ 0 ] . script_witness . stack . map ( & :bth ) . join root_hash = Bitcoin :: MerkleTree . build_from_leaf ( witness_hashes ) . merk...
calculate witness commitment from tx list .
7,909
def height return nil if header . version < 2 coinbase_tx = transactions [ 0 ] return nil unless coinbase_tx . coinbase_tx? buf = StringIO . new ( coinbase_tx . inputs [ 0 ] . script_sig . to_payload ) len = Bitcoin . unpack_var_int_from_io ( buf ) buf . read ( len ) . reverse . bth . to_i ( 16 ) end
return this block height . block height is included in coinbase . if block version under 1 height does not include in coinbase so return nil .
7,910
def to_payload payload = String . new payload << MARKER payload << VERSION payload << Bitcoin . pack_var_int ( quantities . size ) << quantities . map { | q | LEB128 . encode_unsigned ( q ) . read } . join payload << Bitcoin . pack_var_int ( metadata . length ) << metadata . bytes . map { | b | sprintf ( "%02x" , b ) }...
generate binary payload
7,911
def hash160 ( hex ) Digest :: RMD160 . hexdigest ( Digest :: SHA256 . digest ( hex . htb ) ) end
generate sha256 - ripemd160 hash for value
7,912
def encode_base58_address ( hex , addr_version ) base = addr_version + hex Base58 . encode ( base + calc_checksum ( base ) ) end
encode Base58 check address .
7,913
def decode_base58_address ( addr ) hex = Base58 . decode ( addr ) if hex . size == 50 && calc_checksum ( hex [ 0 ... - 8 ] ) == hex [ - 8 .. - 1 ] raise 'Invalid version bytes.' unless [ Bitcoin . chain_params . address_version , Bitcoin . chain_params . p2sh_version ] . include? ( hex [ 0 .. 1 ] ) [ hex [ 2 ... - 8 ] ...
decode Base58 check encoding address .
7,914
def check_tx ( tx , state ) if tx . inputs . empty? return state . DoS ( 10 , reject_code : Message :: Reject :: CODE_INVALID , reject_reason : 'bad-txns-vin-empty' ) end if tx . outputs . empty? return state . DoS ( 100 , reject_code : Message :: Reject :: CODE_INVALID , reject_reason : 'bad-txns-vout-empty' ) end if ...
check transaction validation
7,915
def verify_script ( script_sig , script_pubkey , witness = ScriptWitness . new ) return set_error ( SCRIPT_ERR_SIG_PUSHONLY ) if flag? ( SCRIPT_VERIFY_SIGPUSHONLY ) && ! script_sig . push_only? stack_copy = nil had_witness = false return false unless eval_script ( script_sig , :base ) stack_copy = stack . dup if flag? ...
initialize runner eval script
7,916
def pop_int ( count = 1 ) i = stack . pop ( count ) . map { | s | cast_to_int ( s ) } count == 1 ? i . first : i end
pop the item with the int value for the number specified by + count + from the stack .
7,917
def cast_to_int ( s , max_num_size = DEFAULT_MAX_NUM_SIZE ) data = s . htb raise '"script number overflow"' if data . bytesize > max_num_size if require_minimal && data . bytesize > 0 if data . bytes [ - 1 ] & 0x7f == 0 && ( data . bytesize <= 1 || data . bytes [ data . bytesize - 2 ] & 0x80 == 0 ) raise 'non-minimally...
cast item to int value .
7,918
def contains? ( data ) return true if full? hash_funcs . times do | i | hash = to_hash ( data , i ) return false unless check_bit ( hash ) end true end
Returns true if the given data matches the filter
7,919
def hash_to_range ( element ) hash = SipHash . digest ( key , element ) map_into_range ( hash , f ) end
Hash a data element to an integer in the range [ 0 F ) .
7,920
def match_internal? ( hashes , size ) n , payload = Bitcoin . unpack_var_int ( encoded . htb ) bit_reader = Bitcoin :: BitStreamReader . new ( payload ) value = 0 hashes_index = 0 n . times do delta = golomb_rice_decode ( bit_reader , p ) value += delta loop do return false if hashes_index == size return true if hashes...
Checks if the elements may be in the set .
7,921
def golomb_rice_encode ( bit_writer , p , x ) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer . write ( - 1 , nbits ) q -= nbits end bit_writer . write ( 0 , 1 ) bit_writer . write ( x , p ) end
encode golomb rice
7,922
def golomb_rice_decode ( bit_reader , p ) q = 0 while bit_reader . read ( 1 ) == 1 q += 1 end r = bit_reader . read ( p ) ( q << p ) + r end
decode golomb rice
7,923
def remote_file_content_same_as? ( full_path , content ) Digest :: MD5 . hexdigest ( content ) == top . capture ( "md5sum #{full_path} | awk '{ print $1 }'" ) . strip end
Returns Boolean value indicating whether the file at + full_path + matches + content + . Checks if file is equivalent to content by checking whether or not the MD5 of the remote content is the same as the MD5 of the String in + content + .
7,924
def remote_file_differs? ( full_path , content ) ! remote_file_exists? ( full_path ) || remote_file_exists? ( full_path ) && ! remote_file_content_same_as? ( full_path , content ) end
Returns Boolean indicating whether the remote file is present and has the same contents as the String in + content + .
7,925
def adapt_tag! ( parsed_tag ) parsed_tag [ 'cuke_modeler_parsing_data' ] = Marshal :: load ( Marshal . dump ( parsed_tag ) ) parsed_tag [ 'name' ] = parsed_tag . delete ( :name ) parsed_tag [ 'line' ] = parsed_tag . delete ( :location ) [ :line ] end
Adapts the AST sub - tree that is rooted at the given tag node .
7,926
def adapt_comment! ( parsed_comment ) parsed_comment [ 'cuke_modeler_parsing_data' ] = Marshal :: load ( Marshal . dump ( parsed_comment ) ) parsed_comment [ 'text' ] = parsed_comment . delete ( :text ) parsed_comment [ 'line' ] = parsed_comment . delete ( :location ) [ :line ] end
Adapts the AST sub - tree that is rooted at the given comment node .
7,927
def to_s text = '' text << tag_output_string + "\n" unless tags . empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless ( description . nil? || description . empty? ) text << "\n\n" + background_output_string if background text << "\n\n" + tests_output_string unless tests . ...
Returns a string representation of this model . For a feature model this will be Gherkin text that is equivalent to the feature being modeled .
7,928
def to_s text = "#{keyword} #{self.text}" text << "\n" + block . to_s . split ( "\n" ) . collect { | line | " #{line}" } . join ( "\n" ) if block text end
Returns a string representation of this model . For a step model this will be Gherkin text that is equivalent to the step being modeled .
7,929
def adapt_doc_string! ( parsed_doc_string ) parsed_doc_string [ 'cuke_modeler_parsing_data' ] = Marshal :: load ( Marshal . dump ( parsed_doc_string ) ) parsed_doc_string [ 'value' ] = parsed_doc_string . delete ( :content ) parsed_doc_string [ 'content_type' ] = parsed_doc_string . delete ( :contentType ) parsed_doc_s...
Adapts the AST sub - tree that is rooted at the given doc string node .
7,930
def to_s text = '' text << tag_output_string + "\n" unless tags . empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless ( description . nil? || description . empty? ) text << "\n" unless ( steps . empty? || description . nil? || description . empty? ) text << "\n" + steps_ou...
Returns a string representation of this model . For an outline model this will be Gherkin text that is equivalent to the outline being modeled .
7,931
def each_descendant ( & block ) children . each do | child_model | block . call ( child_model ) child_model . each_descendant ( & block ) if child_model . respond_to? ( :each_descendant ) end end
Executes the given code block with every model that is a child of this model .
7,932
def get_ancestor ( ancestor_type ) target_type = { :directory => [ Directory ] , :feature_file => [ FeatureFile ] , :feature => [ Feature ] , :test => [ Scenario , Outline , Background ] , :background => [ Background ] , :scenario => [ Scenario ] , :outline => [ Outline ] , :step => [ Step ] , :table => [ Table ] , :ex...
Returns the ancestor model of this model that matches the given type .
7,933
def to_s text = '' text << tag_output_string + "\n" unless tags . empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless ( description . nil? || description . empty? ) text << "\n" unless ( rows . empty? || description . nil? || description . empty? ) text << "\n" + parameter...
Returns a string representation of this model . For an example model this will be Gherkin text that is equivalent to the example being modeled .
7,934
def broadcast ( recipients ) @node [ FROM ] = stream . user . jid . to_s recipients . each do | recipient | @node [ TO ] = recipient . user . jid . to_s recipient . write ( @node ) end end
Send the stanza to all recipients stamping it with from and to addresses first .
7,935
def local? return true unless ROUTABLE_STANZAS . include? ( @node . name ) to = JID . new ( @node [ TO ] ) to . empty? || local_jid? ( to ) end
Returns true if this stanza should be processed locally . Returns false if it s destined for a remote domain or external component .
7,936
def send_unavailable ( from , to ) available = router . available_resources ( from , to ) stanzas = available . map { | stream | unavailable ( stream . user . jid ) } broadcast_to_available_resources ( stanzas , to ) end
Broadcast unavailable presence from the user s available resources to the recipient s available resources . Route the stanza to a remote server if the recipient isn t hosted locally .
7,937
def unavailable ( from ) doc = Document . new doc . create_element ( 'presence' , 'from' => from . to_s , 'id' => Kit . uuid , 'type' => 'unavailable' ) end
Return an unavailable presence stanza addressed from the given JID .
7,938
def send_to_remote ( stanzas , to ) return false if local_jid? ( to ) to = JID . new ( to ) stanzas . each do | el | el [ TO ] = to . bare . to_s router . route ( el ) end true end
Route the stanzas to a remote server stamping a bare JID as the to address . Bare JIDs are required for presence subscription stanzas sent to the remote contact s server . Return true if the stanzas were routed false if they must be delivered locally .
7,939
def send_to_recipients ( stanzas , recipients ) recipients . each do | recipient | stanzas . each do | el | el [ TO ] = recipient . user . jid . to_s recipient . write ( el ) end end end
Send the stanzas to the local recipient streams stamping a full JID as the to address . It s important to use full JIDs even when sending to local clients because the stanzas may be routed to other cluster nodes for delivery . We need the receiving cluster node to send the stanza just to this full JID not to lookup all...
7,940
def update_from ( user ) @name = user . name @password = user . password @roster = user . roster . map { | c | c . clone } end
Update this user s information from the given user object .
7,941
def contact ( jid ) bare = JID . new ( jid ) . bare @roster . find { | c | c . jid . bare == bare } end
Returns the contact with this jid or nil if not found .
7,942
def remove_contact ( jid ) bare = JID . new ( jid ) . bare @roster . reject! { | c | c . jid . bare == bare } end
Removes the contact with this jid from the user s roster .
7,943
def request_subscription ( jid ) unless contact = contact ( jid ) contact = Contact . new ( :jid => jid ) @roster << contact end contact . ask = 'subscribe' if %w[ none from ] . include? ( contact . subscription ) end
Update the contact s jid on this user s roster to signal that this user has requested the contact s permission to receive their presence updates .
7,944
def add_subscription_from ( jid ) unless contact = contact ( jid ) contact = Contact . new ( :jid => jid ) @roster << contact end contact . subscribe_from end
Add the user s jid to this contact s roster with a subscription state of from . This signals that this contact has approved a user s subscription .
7,945
def to_roster_xml ( id ) doc = Nokogiri :: XML :: Document . new doc . create_element ( 'iq' , 'id' => id , 'type' => 'result' ) do | el | el << doc . create_element ( 'query' , 'xmlns' => 'jabber:iq:roster' ) do | query | @roster . sort! . each do | contact | query << contact . to_roster_xml end end end end
Returns this user s roster contacts as an iq query element .
7,946
def send_roster_push ( recipient ) doc = Nokogiri :: XML :: Document . new node = doc . create_element ( 'iq' , 'id' => Kit . uuid , 'to' => recipient . user . jid . to_s , 'type' => 'set' ) node << doc . create_element ( 'query' , 'xmlns' => NAMESPACES [ :roster ] ) do | query | query << to_roster_xml end recipient . ...
Write an iq stanza to the recipient stream representing this contact s current roster item state .
7,947
def start register_storage opts = parse ( ARGV ) check_config ( opts ) command = Command . const_get ( opts [ :command ] . capitalize ) . new begin command . run ( opts ) rescue SystemExit rescue Exception => e puts e . message exit ( 1 ) end end
Run the command line application to parse arguments and run sub - commands . Exits the process with a non - zero return code to indicate failure .
7,948
def check_config ( opts ) return if %w[ bcrypt init ] . include? ( opts [ :command ] ) unless File . exists? ( opts [ :config ] ) puts "No config file found at #{opts[:config]}" exit ( 1 ) end end
Many commands must be run in the context of a vines server directory created with vines init . If the command can t find the server s config file print an error message and exit .
7,949
def pubsub ( domain ) host = @vhosts . values . find { | host | host . pubsub? ( domain ) } host . pubsubs [ domain . to_s ] if host end
Returns the PubSub system for the domain or nil if pubsub is not enabled for this domain .
7,950
def component? ( * jids ) ! jids . flatten . index do | jid | ! component_password ( JID . new ( jid ) . domain ) end end
Return true if all JIDs belong to components hosted by this server .
7,951
def component_password ( domain ) host = @vhosts . values . find { | host | host . component? ( domain ) } host . password ( domain ) if host end
Return the password for the component or nil if it s not hosted here .
7,952
def local_jid? ( * jids ) ! jids . flatten . index do | jid | ! vhost? ( JID . new ( jid ) . domain ) end end
Return true if all of the JIDs are hosted by this server .
7,953
def allowed? ( to , from ) to , from = JID . new ( to ) , JID . new ( from ) return false if to . empty? || from . empty? return true if to . domain == from . domain return cross_domain? ( to , from ) if local_jid? ( to , from ) return check_subdomains ( to , from ) if subdomain? ( to , from ) return check_subdomain ( ...
Return true if the two JIDs are allowed to send messages to each other . Both domains must have enabled cross_domain_messages in their config files .
7,954
def strip_domain ( jid ) domain = jid . domain . split ( '.' ) . drop ( 1 ) . join ( '.' ) JID . new ( domain ) end
Return the third - level JID s domain with the first subdomain stripped off to create a second - level domain . For example alice
7,955
def cross_domain? ( * jids ) ! jids . flatten . index do | jid | ! vhost ( jid . domain ) . cross_domain_messages? end end
Return true if all JIDs are allowed to exchange cross domain messages .
7,956
def start @connection . connect @publisher . broadcast ( :online ) @subscriber . subscribe EM . add_periodic_timer ( 1 ) { heartbeat } at_exit do @publisher . broadcast ( :offline ) @sessions . delete_all ( @id ) end end
Join this node to the cluster by broadcasting its state to the other nodes subscribing to redis channels and scheduling periodic heartbeat broadcasts . This method must be called after initialize or this node will not be a cluster member .
7,957
def query ( name , * args ) fiber , yielding = Fiber . current , true req = connection . send ( name , * args ) req . errback { fiber . resume rescue yielding = false } req . callback { | response | fiber . resume ( response ) } Fiber . yield if yielding end
Turn an asynchronous redis query into a blocking call by pausing the fiber in which this code is running . Return the result of the query from this method rather than passing it to a callback block .
7,958
def authenticate ( username , password ) user = find_user ( username ) hash = BCrypt :: Password . new ( user . password ) rescue nil ( hash && hash == password ) ? user : nil end
Validate the username and password pair .
7,959
def authenticate_with_ldap ( username , password , & block ) op = operation { ldap . authenticate ( username , password ) } cb = proc { | user | save_ldap_user ( user , & block ) } EM . defer ( op , cb ) end
Bind to the LDAP server using the provided username and password . If authentication succeeds but the user is not yet stored in our database save the user to the database .
7,960
def save_ldap_user ( user , & block ) Fiber . new do if user . nil? block . call elsif found = find_user ( user . jid ) block . call ( found ) else save_user ( user ) block . call ( user ) end end . resume end
Save missing users to the storage database after they re authenticated with LDAP . This allows admins to define users once in LDAP and have them sync to the chat database the first time they successfully sign in .
7,961
def connected_resources ( jid , from , proxies = true ) jid , from = JID . new ( jid ) , JID . new ( from ) return [ ] unless @config . allowed? ( jid , from ) local = @clients [ jid . bare ] || EMPTY local = local . select { | stream | stream . user . jid == jid } unless jid . bare? remote = proxies ? proxies ( jid ) ...
Returns streams for all connected resources for this JID . A resource is considered connected after it has completed authentication and resource binding .
7,962
def delete ( stream ) case stream_type ( stream ) when :client then return unless stream . connected? jid = stream . user . jid . bare streams = @clients [ jid ] || [ ] streams . delete ( stream ) @clients . delete ( jid ) if streams . empty? when :server then @servers . delete ( stream ) when :component then @componen...
Remove the connection from the routing table .
7,963
def route ( stanza ) to , from = %w[ to from ] . map { | attr | JID . new ( stanza [ attr ] ) } return unless @config . allowed? ( to , from ) key = [ to . domain , from . domain ] if stream = connection_to ( to , from ) stream . write ( stanza ) elsif @pending . key? ( key ) @pending [ key ] << stanza elsif @config . ...
Send the stanza to the appropriate remote server - to - server stream or an external component stream .
7,964
def size clients = @clients . values . inject ( 0 ) { | sum , arr | sum + arr . size } clients + @servers . size + @components . size end
Returns the total number of streams connected to the server .
7,965
def return_pending ( key ) @pending [ key ] . each do | stanza | to , from = JID . new ( stanza [ 'to' ] ) , JID . new ( stanza [ 'from' ] ) xml = StanzaErrors :: RemoteServerNotFound . new ( stanza , 'cancel' ) . to_xml if @config . component? ( from ) connection_to ( from , to ) . write ( xml ) rescue nil else connec...
Return all pending stanzas to their senders as remote - server - not - found errors . Called after a s2s stream has failed to connect .
7,966
def clients ( jids , from , & filter ) jids = filter_allowed ( jids , from ) local = @clients . values_at ( * jids ) . compact . flatten . select ( & filter ) proxies = proxies ( * jids ) . select ( & filter ) [ local , proxies ] . flatten end
Return the client streams to which the from address is allowed to contact . Apply the filter block to each stream to narrow the results before returning the streams .
7,967
def filter_allowed ( jids , from ) from = JID . new ( from ) jids . flatten . map { | jid | JID . new ( jid ) . bare } . select { | jid | @config . allowed? ( jid , from ) } end
Return the bare JIDs from the list that are allowed to talk to the + from + JID .
7,968
def running? begin pid && Process . kill ( 0 , pid ) rescue Errno :: ESRCH delete_pid false rescue Errno :: EPERM true end end
Returns true if the process is running as determined by the numeric pid stored in the pid file created by a previous call to start .
7,969
def domain? ( pem , domain ) if cert = OpenSSL :: X509 :: Certificate . new ( pem ) rescue nil OpenSSL :: SSL . verify_certificate_identity ( cert , domain ) rescue false end end
Return true if the domain name matches one of the names in the certificate . In other words is the certificate provided to us really for the domain to which we think we re connected?
7,970
def files_for_domain ( domain ) crt = File . expand_path ( "#{domain}.crt" , @dir ) key = File . expand_path ( "#{domain}.key" , @dir ) return [ crt , key ] if File . exists? ( crt ) && File . exists? ( key ) @@sources . each do | file , certs | certs . each do | cert | if OpenSSL :: SSL . verify_certificate_identity (...
Returns a pair of file names containing the public key certificate and matching private key for the given domain . This supports using wildcard certificate files to serve several subdomains .
7,971
def post_init @remote_addr , @local_addr = addresses @user , @closed , @stanza_size = nil , false , 0 @bucket = TokenBucket . new ( 100 , 10 ) @store = Store . new ( @config . certs ) @nodes = EM :: Queue . new process_node_queue create_parser log . info { "%s %21s -> %s" % [ 'Stream connected:' . ljust ( PAD ) , @remo...
Initialize the stream after its connection to the server has completed . EventMachine calls this method when an incoming connection is accepted into the event loop .
7,972
def receive_data ( data ) return if @closed @stanza_size += data . bytesize if @stanza_size < max_stanza_size @parser << data rescue error ( StreamErrors :: NotWellFormed . new ) else error ( StreamErrors :: PolicyViolation . new ( 'max stanza size reached' ) ) end end
Read bytes off the stream and feed them into the XML parser . EventMachine is responsible for calling this method on its event loop as connections become readable .
7,973
def write ( data ) log_node ( data , :out ) if data . respond_to? ( :to_xml ) data = data . to_xml ( :indent => 0 ) end send_data ( data ) end
Send the data over the wire to this client .
7,974
def error ( e ) case e when SaslError , StanzaError write ( e . to_xml ) when StreamError send_stream_error ( e ) close_stream else log . error ( e ) send_stream_error ( StreamErrors :: InternalServerError . new ) close_stream end end
Stream level errors close the stream while stanza and SASL errors are written to the client and leave the stream open . All exceptions should pass through this method for consistent handling .
7,975
def addresses [ get_peername , get_sockname ] . map do | addr | addr ? Socket . unpack_sockaddr_in ( addr ) [ 0 , 2 ] . reverse . join ( ':' ) : 'unknown' end end
Determine the remote and local socket addresses used by this connection .
7,976
def to_xml ( options = { } ) xml = options [ :builder ] ||= Builder :: XmlMarkup . new xml . instruct! unless options [ :skip_instruct ] xml . member ( :type => type , :ref => ref , :role => role ) end
Create a new Member object . Type can be one of node way or relation . Ref is the ID of the corresponding Node Way or Relation . Role is a freeform string and can be empty . Return XML for this way . This method uses the Builder library . The only parameter ist the builder object .
7,977
def destroy ( element , changeset ) element . changeset = changeset . id response = delete ( "/#{element.type.downcase}/#{element.id}" , :body => element . to_xml ) unless element . id . nil? response . to_i end
Deletes the given element using API write access .
7,978
def save ( element , changeset ) response = if element . id . nil? create ( element , changeset ) else update ( element , changeset ) end end
Creates or updates an element depending on the current state of persistance .
7,979
def create ( element , changeset ) element . changeset = changeset . id put ( "/#{element.type.downcase}/create" , :body => element . to_xml ) end
Create a new element using API write access .
7,980
def update ( element , changeset ) element . changeset = changeset . id response = put ( "/#{element.type.downcase}/#{element.id}" , :body => element . to_xml ) response . to_i end
Update an existing element using API write access .
7,981
def create_changeset ( comment = nil , tags = { } ) tags . merge! ( :comment => comment ) { | key , v1 , v2 | v1 } changeset = Changeset . new ( :tags => tags ) changeset_id = put ( "/changeset/create" , :body => changeset . to_xml ) . to_i find_changeset ( changeset_id ) unless changeset_id == 0 end
Create a new changeset with an optional comment
7,982
def do_request ( method , url , options = { } ) begin response = self . class . send ( method , api_url ( url ) , options ) check_response_codes ( response ) response . parsed_response rescue Timeout :: Error raise Unavailable . new ( 'Service Unavailable' ) end end
Do a API request without authentication
7,983
def do_authenticated_request ( method , url , options = { } ) begin response = case client when BasicAuthClient self . class . send ( method , api_url ( url ) , options . merge ( :basic_auth => client . credentials ) ) when OauthClient result = client . send ( method , api_url ( url ) , options ) content_type = Parser ...
Do a API request with authentication using the given client
7,984
def << ( stuff ) case stuff when Array stuff . each do | item | self << item end when Rosemary :: Node nodes << stuff . id when String nodes << stuff . to_i when Integer nodes << stuff else tags . merge! ( stuff ) end self end
Add one or more tags or nodes to this way .
7,985
def to_xml ( options = { } ) xml = options [ :builder ] ||= Builder :: XmlMarkup . new xml . instruct! unless options [ :skip_instruct ] each do | key , value | xml . tag ( :k => key , :v => coder . decode ( value . strip ) ) unless value . blank? end unless empty? end
Return XML for these tags . This method uses the Builder library . The only parameter ist the builder object .
7,986
def to_xml ( options = { } ) xml = options [ :builder ] ||= Builder :: XmlMarkup . new xml . instruct! unless options [ :skip_instruct ] xml . osm do xml . changeset ( attributes ) do tags . each do | k , v | xml . tag ( :k => k , :v => v ) end unless tags . empty? end end end
Renders the object as an xml representation compatible to the OSM API
7,987
def to_xml ( options = { } ) xml = options [ :builder ] ||= Builder :: XmlMarkup . new xml . instruct! unless options [ :skip_instruct ] xml . osm ( :generator => "rosemary v#{Rosemary::VERSION}" , :version => Rosemary :: Api :: API_VERSION ) do xml . relation ( attributes ) do members . each do | member | member . to_...
Return XML for this relation . This method uses the Builder library . The only parameter ist the builder object .
7,988
def add_tags ( new_tags ) case new_tags when Array new_tags . each do | tag_hash | add_tags ( tag_hash ) end when Hash if ( new_tags . size == 2 && new_tags . keys . include? ( 'k' ) && new_tags . keys . include? ( 'v' ) ) add_tags ( { new_tags [ 'k' ] => new_tags [ 'v' ] } ) else new_tags . each do | k , v | self . ta...
Add one or more tags to this object .
7,989
def get_relations_from_api ( api = Rosemary :: API . new ) api . get_relations_referring_to_object ( type , self . id . to_i ) end
Get all relations from the API that have his object as members .
7,990
def get_history_from_api ( api = Rosemary :: API . new ) api . get_history ( type , self . id . to_i ) end
Get the history of this object from the API .
7,991
def dig ( key , * args ) value = send ( key ) args . empty? ? value : value &. dig ( * args ) end
Extracts the nested value specified by the sequence of idx objects by calling dig at each step returning nil if any intermediate step is nil .
7,992
def map! __copy_on_write__ return enum_for ( :map! ) unless block_given? __getobj__ . each . with_index do | _ , i | self [ i ] = yield ( self [ i ] ) end end
Invokes the given block once for each element of self replacing the element with the value returned by the block .
7,993
def tick_deltas unless @delta . empty? merge_to_db ( @delta ) @tick_delta . concat ( @delta . values ) if accumulate_tick_deltas @delta . clear end unless @new_delta . empty? @new_delta . reject! { | key , val | self [ key ] == val } @delta = @new_delta @new_delta = { } end return ! ( @delta . empty? ) end
move deltas to on - disk storage and new_deltas to deltas
7,994
def tick deleted = nil @to_delete . each do | tuple | k = get_key_vals ( tuple ) k_str = MessagePack . pack ( k ) cols_str = @dbm [ k_str ] unless cols_str . nil? db_cols = MessagePack . unpack ( cols_str ) delete_cols = val_cols . map { | c | tuple [ cols . index ( c ) ] } if db_cols == delete_cols deleted ||= @dbm . ...
Remove to_delete and then move pending = > delta .
7,995
def start_watchers @child_watcher = Zookeeper :: Callbacks :: WatcherCallback . new do while true break if @zk . closed? if @zk_mutex . try_lock get_and_watch unless @zk . closed? @zk_mutex . unlock break end end end @stat_watcher = Zookeeper :: Callbacks :: WatcherCallback . new do while true break if @zk . closed? if...
Since the watcher callbacks might invoke EventMachine we wait until after EM startup to start watching for Zk events .
7,996
def payloads ( & blk ) return self . pro ( & blk ) if @is_loopback if @payload_struct . nil? payload_cols = cols . dup payload_cols . delete_at ( @locspec_idx ) @payload_struct = Bud :: TupleStruct . new ( * payload_cols ) @payload_colnums = payload_cols . map { | k | cols . index ( k ) } end retval = self . pro do | t...
project to the non - address fields
7,997
def camelize ( str ) call_or_yield str do str . to_s . sub ( / \d / ) { $& . capitalize } . gsub ( / \/ \d / ) { "#{$1}#{$2.capitalize}" } . gsub ( '/' , '::' ) end end
Converts strings to UpperCamelCase .
7,998
def call_or_yield ( object ) caller_method = caller_locations ( 1 , 1 ) [ 0 ] . label if object . respond_to? ( caller_method ) object . public_send ( caller_method ) else yield end end
Calls caller method on object if defined otherwise yields to block
7,999
def described_class klass = super return klass if klass this_metadata = metadata while this_metadata do candidate = this_metadata [ :description_args ] . first begin return candidate . constantize if String === candidate rescue NameError , NoMethodError end this_metadata = this_metadata [ :parent_example_group ] end en...
lazy - load described_class if it s a string