idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
249,800 | def writeSentence ( self , cmd , * words ) : encoded = self . encodeSentence ( cmd , * words ) self . log ( '<---' , cmd , * words ) self . transport . write ( encoded ) | Write encoded sentence . | 48 | 4 |
249,801 | def read ( self , length ) : data = bytearray ( ) while len ( data ) != length : data += self . sock . recv ( ( length - len ( data ) ) ) if not data : raise ConnectionError ( 'Connection unexpectedly closed.' ) return data | Read as many bytes from socket as specified in length . Loop as long as every byte is read unless exception is raised . | 58 | 24 |
249,802 | def parseWord ( word ) : mapping = { 'yes' : True , 'true' : True , 'no' : False , 'false' : False } _ , key , value = word . split ( '=' , 2 ) try : value = int ( value ) except ValueError : value = mapping . get ( value , value ) return ( key , value ) | Split given attribute word to key value pair . | 77 | 9 |
249,803 | def composeWord ( key , value ) : mapping = { True : 'yes' , False : 'no' } # this is necesary because 1 == True, 0 == False if type ( value ) == int : value = str ( value ) else : value = mapping . get ( value , str ( value ) ) return '={}={}' . format ( key , value ) | Create a attribute word from key value pair . Values are casted to api equivalents . | 81 | 17 |
249,804 | def login_token ( api , username , password ) : sentence = api ( '/login' ) token = tuple ( sentence ) [ 0 ] [ 'ret' ] encoded = encode_password ( token , password ) tuple ( api ( '/login' , * * { 'name' : username , 'response' : encoded } ) ) | Login using pre routeros 6 . 43 authorization method . | 69 | 11 |
249,805 | def check_relations ( self , relations ) : for rel in relations : if not rel : continue fields = rel . split ( '.' , 1 ) local_field = fields [ 0 ] if local_field not in self . fields : raise ValueError ( 'Unknown field "{}"' . format ( local_field ) ) field = self . fields [ local_field ] if not isinstance ( field , BaseRelationship ) : raise ValueError ( 'Can only include relationships. "{}" is a "{}"' . format ( field . name , field . __class__ . __name__ ) ) field . include_data = True if len ( fields ) > 1 : field . schema . check_relations ( fields [ 1 : ] ) | Recursive function which checks if a relation is valid . | 153 | 11 |
249,806 | def format_json_api_response ( self , data , many ) : ret = self . format_items ( data , many ) ret = self . wrap_response ( ret , many ) ret = self . render_included_data ( ret ) ret = self . render_meta_document ( ret ) return ret | Post - dump hook that formats serialized data as a top - level JSON API object . | 67 | 18 |
249,807 | def _do_load ( self , data , many = None , * * kwargs ) : many = self . many if many is None else bool ( many ) # Store this on the instance so we have access to the included data # when processing relationships (``included`` is outside of the # ``data``). self . included_data = data . get ( 'included' , { } ) self . document_meta = data . get ( 'meta' , { } ) try : result = super ( Schema , self ) . _do_load ( data , many , * * kwargs ) except ValidationError as err : # strict mode error_messages = err . messages if '_schema' in error_messages : error_messages = error_messages [ '_schema' ] formatted_messages = self . format_errors ( error_messages , many = many ) err . messages = formatted_messages raise err else : # On marshmallow 2, _do_load returns a tuple (load_data, errors) if _MARSHMALLOW_VERSION_INFO [ 0 ] < 3 : data , error_messages = result if '_schema' in error_messages : error_messages = error_messages [ '_schema' ] formatted_messages = self . format_errors ( error_messages , many = many ) return data , formatted_messages return result | Override marshmallow . Schema . _do_load for custom JSON API handling . | 309 | 17 |
249,808 | def _extract_from_included ( self , data ) : return ( item for item in self . included_data if item [ 'type' ] == data [ 'type' ] and str ( item [ 'id' ] ) == str ( data [ 'id' ] ) ) | Extract included data matching the items in data . | 61 | 10 |
249,809 | def inflect ( self , text ) : return self . opts . inflect ( text ) if self . opts . inflect else text | Inflect text if the inflect class Meta option is defined otherwise do nothing . | 30 | 16 |
249,810 | def format_errors ( self , errors , many ) : if not errors : return { } if isinstance ( errors , ( list , tuple ) ) : return { 'errors' : errors } formatted_errors = [ ] if many : for index , errors in iteritems ( errors ) : for field_name , field_errors in iteritems ( errors ) : formatted_errors . extend ( [ self . format_error ( field_name , message , index = index ) for message in field_errors ] ) else : for field_name , field_errors in iteritems ( errors ) : formatted_errors . extend ( [ self . format_error ( field_name , message ) for message in field_errors ] ) return { 'errors' : formatted_errors } | Format validation errors as JSON Error objects . | 160 | 8 |
249,811 | def format_error ( self , field_name , message , index = None ) : pointer = [ '/data' ] if index is not None : pointer . append ( str ( index ) ) relationship = isinstance ( self . declared_fields . get ( field_name ) , BaseRelationship , ) if relationship : pointer . append ( 'relationships' ) elif field_name != 'id' : # JSONAPI identifier is a special field that exists above the attribute object. pointer . append ( 'attributes' ) pointer . append ( self . inflect ( field_name ) ) if relationship : pointer . append ( 'data' ) return { 'detail' : message , 'source' : { 'pointer' : '/' . join ( pointer ) , } , } | Override - able hook to format a single error message as an Error object . | 162 | 15 |
249,812 | def format_item ( self , item ) : # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identifier object, or null, for requests that target single resources if not item : return None ret = self . dict_class ( ) ret [ TYPE ] = self . opts . type_ # Get the schema attributes so we can confirm `dump-to` values exist attributes = { ( get_dump_key ( self . fields [ field ] ) or field ) : field for field in self . fields } for field_name , value in iteritems ( item ) : attribute = attributes [ field_name ] if attribute == ID : ret [ ID ] = value elif isinstance ( self . fields [ attribute ] , DocumentMeta ) : if not self . document_meta : self . document_meta = self . dict_class ( ) self . document_meta . update ( value ) elif isinstance ( self . fields [ attribute ] , ResourceMeta ) : if 'meta' not in ret : ret [ 'meta' ] = self . dict_class ( ) ret [ 'meta' ] . update ( value ) elif isinstance ( self . fields [ attribute ] , BaseRelationship ) : if value : if 'relationships' not in ret : ret [ 'relationships' ] = self . dict_class ( ) ret [ 'relationships' ] [ self . inflect ( field_name ) ] = value else : if 'attributes' not in ret : ret [ 'attributes' ] = self . dict_class ( ) ret [ 'attributes' ] [ self . inflect ( field_name ) ] = value links = self . get_resource_links ( item ) if links : ret [ 'links' ] = links return ret | Format a single datum as a Resource object . | 388 | 10 |
249,813 | def format_items ( self , data , many ) : if many : return [ self . format_item ( item ) for item in data ] else : return self . format_item ( data ) | Format data as a Resource object or list of Resource objects . | 41 | 12 |
249,814 | def get_top_level_links ( self , data , many ) : self_link = None if many : if self . opts . self_url_many : self_link = self . generate_url ( self . opts . self_url_many ) else : if self . opts . self_url : self_link = data . get ( 'links' , { } ) . get ( 'self' , None ) return { 'self' : self_link } | Hook for adding links to the root of the response data . | 103 | 13 |
249,815 | def get_resource_links ( self , item ) : if self . opts . self_url : ret = self . dict_class ( ) kwargs = resolve_params ( item , self . opts . self_url_kwargs or { } ) ret [ 'self' ] = self . generate_url ( self . opts . self_url , * * kwargs ) return ret return None | Hook for adding links to a resource object . | 88 | 10 |
249,816 | def wrap_response ( self , data , many ) : ret = { 'data' : data } # self_url_many is still valid when there isn't any data, but self_url # may only be included if there is data in the ret if many or data : top_level_links = self . get_top_level_links ( data , many ) if top_level_links [ 'self' ] : ret [ 'links' ] = top_level_links return ret | Wrap data and links according to the JSON API | 104 | 10 |
249,817 | def extract_value ( self , data ) : errors = [ ] if 'id' not in data : errors . append ( 'Must have an `id` field' ) if 'type' not in data : errors . append ( 'Must have a `type` field' ) elif data [ 'type' ] != self . type_ : errors . append ( 'Invalid `type` specified' ) if errors : raise ValidationError ( errors ) # If ``attributes`` is set, we've folded included data into this # relationship. Unserialize it if we have a schema set; otherwise we # fall back below to old behaviour of only IDs. if 'attributes' in data and self . __schema : result = self . schema . load ( { 'data' : data , 'included' : self . root . included_data } ) return result . data if _MARSHMALLOW_VERSION_INFO [ 0 ] < 3 else result id_value = data . get ( 'id' ) if self . __schema : id_value = self . schema . fields [ 'id' ] . deserialize ( id_value ) return id_value | Extract the id key and validate the request structure . | 248 | 11 |
249,818 | def fill_package_digests ( generated_project : Project ) -> Project : for package_version in chain ( generated_project . pipfile_lock . packages , generated_project . pipfile_lock . dev_packages ) : if package_version . hashes : # Already filled from the last run. continue if package_version . index : scanned_hashes = package_version . index . get_package_hashes ( package_version . name , package_version . locked_version ) else : for source in generated_project . pipfile . meta . sources . values ( ) : try : scanned_hashes = source . get_package_hashes ( package_version . name , package_version . locked_version ) break except Exception : continue else : raise ValueError ( "Unable to find package hashes" ) for entry in scanned_hashes : package_version . hashes . append ( "sha256:" + entry [ "sha256" ] ) return generated_project | Temporary fill package digests stated in Pipfile . lock . | 207 | 13 |
249,819 | def fetch_digests ( self , package_name : str , package_version : str ) -> dict : report = { } for source in self . _sources : try : report [ source . url ] = source . get_package_hashes ( package_name , package_version ) except NotFound as exc : _LOGGER . debug ( f"Package {package_name} in version {package_version} not " f"found on index {source.name}: {str(exc)}" ) return report | Fetch digests for the given package in specified version from the given package index . | 110 | 17 |
249,820 | def random_passphrase_from_wordlist ( phrase_length , wordlist ) : passphrase_words = [ ] numbytes_of_entropy = phrase_length * 2 entropy = list ( dev_random_entropy ( numbytes_of_entropy , fallback_to_urandom = True ) ) bytes_per_word = int ( ceil ( log ( len ( wordlist ) , 2 ) / 8 ) ) if ( phrase_length * bytes_per_word > 64 ) : raise Exception ( "Error! This operation requires too much entropy. \ Try a shorter phrase length or word list." ) for i in range ( phrase_length ) : current_entropy = entropy [ i * bytes_per_word : ( i + 1 ) * bytes_per_word ] index = int ( '' . join ( current_entropy ) . encode ( 'hex' ) , 16 ) % len ( wordlist ) word = wordlist [ index ] passphrase_words . append ( word ) return " " . join ( passphrase_words ) | An extremely entropy efficient passphrase generator . | 226 | 8 |
249,821 | def reverse_hash ( hash , hex_format = True ) : if not hex_format : hash = hexlify ( hash ) return "" . join ( reversed ( [ hash [ i : i + 2 ] for i in range ( 0 , len ( hash ) , 2 ) ] ) ) | hash is in hex or binary format | 61 | 7 |
249,822 | def get_num_words_with_entropy ( bits_of_entropy , wordlist ) : entropy_per_word = math . log ( len ( wordlist ) ) / math . log ( 2 ) num_words = int ( math . ceil ( bits_of_entropy / entropy_per_word ) ) return num_words | Gets the number of words randomly selected from a given wordlist that would result in the number of bits of entropy specified . | 75 | 25 |
249,823 | def create_passphrase ( bits_of_entropy = None , num_words = None , language = 'english' , word_source = 'wiktionary' ) : wordlist = get_wordlist ( language , word_source ) if not num_words : if not bits_of_entropy : bits_of_entropy = 80 num_words = get_num_words_with_entropy ( bits_of_entropy , wordlist ) return ' ' . join ( pick_random_words_from_wordlist ( wordlist , num_words ) ) | Creates a passphrase that has a certain number of bits of entropy OR a certain number of words . | 125 | 21 |
249,824 | def serialize_input ( input , signature_script_hex = '' ) : if not ( isinstance ( input , dict ) and 'transaction_hash' in input and 'output_index' in input ) : raise Exception ( 'Required parameters: transaction_hash, output_index' ) if is_hex ( str ( input [ 'transaction_hash' ] ) ) and len ( str ( input [ 'transaction_hash' ] ) ) != 64 : raise Exception ( "Transaction hash '%s' must be 32 bytes" % input [ 'transaction_hash' ] ) elif not is_hex ( str ( input [ 'transaction_hash' ] ) ) and len ( str ( input [ 'transaction_hash' ] ) ) != 32 : raise Exception ( "Transaction hash '%s' must be 32 bytes" % hexlify ( input [ 'transaction_hash' ] ) ) if not 'sequence' in input : input [ 'sequence' ] = UINT_MAX return '' . join ( [ flip_endian ( input [ 'transaction_hash' ] ) , hexlify ( struct . pack ( '<I' , input [ 'output_index' ] ) ) , hexlify ( variable_length_int ( len ( signature_script_hex ) / 2 ) ) , signature_script_hex , hexlify ( struct . pack ( '<I' , input [ 'sequence' ] ) ) ] ) | Serializes a transaction input . | 312 | 6 |
249,825 | def serialize_output ( output ) : if not ( 'value' in output and 'script_hex' in output ) : raise Exception ( 'Invalid output' ) return '' . join ( [ hexlify ( struct . pack ( '<Q' , output [ 'value' ] ) ) , # pack into 8 bites hexlify ( variable_length_int ( len ( output [ 'script_hex' ] ) / 2 ) ) , output [ 'script_hex' ] ] ) | Serializes a transaction output . | 104 | 6 |
249,826 | def serialize_transaction ( inputs , outputs , lock_time = 0 , version = 1 ) : # add in the inputs serialized_inputs = '' . join ( [ serialize_input ( input ) for input in inputs ] ) # add in the outputs serialized_outputs = '' . join ( [ serialize_output ( output ) for output in outputs ] ) return '' . join ( [ # add in the version number hexlify ( struct . pack ( '<I' , version ) ) , # add in the number of inputs hexlify ( variable_length_int ( len ( inputs ) ) ) , # add in the inputs serialized_inputs , # add in the number of outputs hexlify ( variable_length_int ( len ( outputs ) ) ) , # add in the outputs serialized_outputs , # add in the lock time hexlify ( struct . pack ( '<I' , lock_time ) ) , ] ) | Serializes a transaction . | 206 | 5 |
249,827 | def deserialize_transaction ( tx_hex ) : tx = bitcoin . deserialize ( str ( tx_hex ) ) inputs = tx [ "ins" ] outputs = tx [ "outs" ] ret_inputs = [ ] ret_outputs = [ ] for inp in inputs : ret_inp = { "transaction_hash" : inp [ "outpoint" ] [ "hash" ] , "output_index" : int ( inp [ "outpoint" ] [ "index" ] ) , } if "sequence" in inp : ret_inp [ "sequence" ] = int ( inp [ "sequence" ] ) if "script" in inp : ret_inp [ "script_sig" ] = inp [ "script" ] ret_inputs . append ( ret_inp ) for out in outputs : ret_out = { "value" : out [ "value" ] , "script_hex" : out [ "script" ] } ret_outputs . append ( ret_out ) return ret_inputs , ret_outputs , tx [ "locktime" ] , tx [ "version" ] | Given a serialized transaction return its inputs outputs locktime and version | 253 | 13 |
249,828 | def variable_length_int ( i ) : if not isinstance ( i , ( int , long ) ) : raise Exception ( 'i must be an integer' ) if i < ( 2 ** 8 - 3 ) : return chr ( i ) # pack the integer into one byte elif i < ( 2 ** 16 ) : return chr ( 253 ) + struct . pack ( '<H' , i ) # pack into 2 bytes elif i < ( 2 ** 32 ) : return chr ( 254 ) + struct . pack ( '<I' , i ) # pack into 4 bytes elif i < ( 2 ** 64 ) : return chr ( 255 ) + struct . pack ( '<Q' , i ) # pack into 8 bites else : raise Exception ( 'Integer cannot exceed 8 bytes in length.' ) | Encodes integers into variable length integers which are used in Bitcoin in order to save space . | 173 | 18 |
249,829 | def make_pay_to_address_script ( address ) : hash160 = hexlify ( b58check_decode ( address ) ) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex ( script_string ) | Takes in an address and returns the script | 75 | 9 |
249,830 | def make_op_return_script ( data , format = 'bin' ) : if format == 'hex' : assert ( is_hex ( data ) ) hex_data = data elif format == 'bin' : hex_data = hexlify ( data ) else : raise Exception ( "Format must be either 'hex' or 'bin'" ) num_bytes = count_bytes ( hex_data ) if num_bytes > MAX_BYTES_AFTER_OP_RETURN : raise Exception ( 'Data is %i bytes - must not exceed 40.' % num_bytes ) script_string = 'OP_RETURN %s' % hex_data return script_to_hex ( script_string ) | Takes in raw ascii data to be embedded and returns a script . | 153 | 16 |
249,831 | def create_bitcoind_service_proxy ( rpc_username , rpc_password , server = '127.0.0.1' , port = 8332 , use_https = False ) : protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % ( protocol , rpc_username , rpc_password , server , port ) return AuthServiceProxy ( uri ) | create a bitcoind service proxy | 103 | 7 |
249,832 | def get_unspents ( address , blockchain_client = BlockchainInfoClient ( ) ) : if isinstance ( blockchain_client , BlockcypherClient ) : return blockcypher . get_unspents ( address , blockchain_client ) elif isinstance ( blockchain_client , BlockchainInfoClient ) : return blockchain_info . get_unspents ( address , blockchain_client ) elif isinstance ( blockchain_client , ChainComClient ) : return chain_com . get_unspents ( address , blockchain_client ) elif isinstance ( blockchain_client , ( BitcoindClient , AuthServiceProxy ) ) : return bitcoind . get_unspents ( address , blockchain_client ) elif hasattr ( blockchain_client , "get_unspents" ) : return blockchain_client . get_unspents ( address ) elif isinstance ( blockchain_client , BlockchainClient ) : raise Exception ( 'That blockchain interface is not supported.' ) else : raise Exception ( 'A BlockchainClient object is required' ) | Gets the unspent outputs for a given address . | 221 | 12 |
249,833 | def broadcast_transaction ( hex_tx , blockchain_client ) : if isinstance ( blockchain_client , BlockcypherClient ) : return blockcypher . broadcast_transaction ( hex_tx , blockchain_client ) elif isinstance ( blockchain_client , BlockchainInfoClient ) : return blockchain_info . broadcast_transaction ( hex_tx , blockchain_client ) elif isinstance ( blockchain_client , ChainComClient ) : return chain_com . broadcast_transaction ( hex_tx , blockchain_client ) elif isinstance ( blockchain_client , ( BitcoindClient , AuthServiceProxy ) ) : return bitcoind . broadcast_transaction ( hex_tx , blockchain_client ) elif hasattr ( blockchain_client , "broadcast_transaction" ) : return blockchain_client . broadcast_transaction ( hex_tx ) elif isinstance ( blockchain_client , BlockchainClient ) : raise Exception ( 'That blockchain interface is not supported.' ) else : raise Exception ( 'A BlockchainClient object is required' ) | Dispatches a raw hex transaction to the network . | 221 | 11 |
249,834 | def make_send_to_address_tx ( recipient_address , amount , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = STANDARD_FEE , change_address = None ) : # get out the private key object, sending address, and inputs private_key_obj , from_address , inputs = analyze_private_key ( private_key , blockchain_client ) # get the change address if not change_address : change_address = from_address # create the outputs outputs = make_pay_to_address_outputs ( recipient_address , amount , inputs , change_address , fee = fee ) # serialize the transaction unsigned_tx = serialize_transaction ( inputs , outputs ) # generate a scriptSig for each input for i in xrange ( 0 , len ( inputs ) ) : signed_tx = sign_transaction ( unsigned_tx , i , private_key_obj . to_hex ( ) ) unsigned_tx = signed_tx # return the signed tx return signed_tx | Builds and signs a send to address transaction . | 221 | 10 |
249,835 | def make_op_return_tx ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : # get out the private key object, sending address, and inputs private_key_obj , from_address , inputs = analyze_private_key ( private_key , blockchain_client ) # get the change address if not change_address : change_address = from_address # create the outputs outputs = make_op_return_outputs ( data , inputs , change_address , fee = fee , format = format ) # serialize the transaction unsigned_tx = serialize_transaction ( inputs , outputs ) # generate a scriptSig for each input for i in xrange ( 0 , len ( inputs ) ) : signed_tx = sign_transaction ( unsigned_tx , i , private_key_obj . to_hex ( ) ) unsigned_tx = signed_tx # return the signed tx return signed_tx | Builds and signs an OP_RETURN transaction . | 221 | 11 |
249,836 | def send_to_address ( recipient_address , amount , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = STANDARD_FEE , change_address = None ) : # build and sign the tx signed_tx = make_send_to_address_tx ( recipient_address , amount , private_key , blockchain_client , fee = fee , change_address = change_address ) # dispatch the signed transction to the network response = broadcast_transaction ( signed_tx , blockchain_client ) # return the response return response | Builds signs and dispatches a send to address transaction . | 118 | 12 |
249,837 | def embed_data_in_blockchain ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : # build and sign the tx signed_tx = make_op_return_tx ( data , private_key , blockchain_client , fee = fee , change_address = change_address , format = format ) # dispatch the signed transction to the network response = broadcast_transaction ( signed_tx , blockchain_client ) # return the response return response | Builds signs and dispatches an OP_RETURN transaction . | 123 | 13 |
249,838 | def sign_all_unsigned_inputs ( hex_privkey , unsigned_tx_hex ) : inputs , outputs , locktime , version = deserialize_transaction ( unsigned_tx_hex ) tx_hex = unsigned_tx_hex for index in xrange ( 0 , len ( inputs ) ) : if len ( inputs [ index ] [ 'script_sig' ] ) == 0 : # tx with index i signed with privkey tx_hex = sign_transaction ( str ( unsigned_tx_hex ) , index , hex_privkey ) unsigned_tx_hex = tx_hex return tx_hex | Sign a serialized transaction s unsigned inputs | 133 | 8 |
249,839 | def calculate_merkle_root ( hashes , hash_function = bin_double_sha256 , hex_format = True ) : if hex_format : hashes = hex_to_bin_reversed_hashes ( hashes ) # keep moving up the merkle tree, constructing one row at a time while len ( hashes ) > 1 : hashes = calculate_merkle_pairs ( hashes , hash_function ) # get the merkle root merkle_root = hashes [ 0 ] # if the user wants the merkle root in hex format, convert it if hex_format : return bin_to_hex_reversed ( merkle_root ) # return the binary merkle root return merkle_root | takes in a list of binary hashes returns a binary hash | 161 | 12 |
249,840 | def b58check_encode ( bin_s , version_byte = 0 ) : # append the version byte to the beginning bin_s = chr ( int ( version_byte ) ) + bin_s # calculate the number of leading zeros num_leading_zeros = len ( re . match ( r'^\x00*' , bin_s ) . group ( 0 ) ) # add in the checksum add the end bin_s = bin_s + bin_checksum ( bin_s ) # convert from b2 to b16 hex_s = hexlify ( bin_s ) # convert from b16 to b58 b58_s = change_charset ( hex_s , HEX_KEYSPACE , B58_KEYSPACE ) return B58_KEYSPACE [ 0 ] * num_leading_zeros + b58_s | Takes in a binary string and converts it to a base 58 check string . | 190 | 16 |
249,841 | def make_pay_to_address_outputs ( to_address , send_amount , inputs , change_address , fee = STANDARD_FEE ) : return [ # main output { "script_hex" : make_pay_to_address_script ( to_address ) , "value" : send_amount } , # change output { "script_hex" : make_pay_to_address_script ( change_address ) , "value" : calculate_change_amount ( inputs , send_amount , fee ) } ] | Builds the outputs for a pay to address transaction . | 116 | 11 |
249,842 | def make_op_return_outputs ( data , inputs , change_address , fee = OP_RETURN_FEE , send_amount = 0 , format = 'bin' ) : return [ # main output { "script_hex" : make_op_return_script ( data , format = format ) , "value" : send_amount } , # change output { "script_hex" : make_pay_to_address_script ( change_address ) , "value" : calculate_change_amount ( inputs , send_amount , fee ) } ] | Builds the outputs for an OP_RETURN transaction . | 122 | 12 |
249,843 | def add_timezone ( value , tz = None ) : tz = tz or timezone . get_current_timezone ( ) try : if timezone . is_naive ( value ) : return timezone . make_aware ( value , tz ) except AttributeError : # 'datetime.date' object has no attribute 'tzinfo' dt = datetime . datetime . combine ( value , datetime . time ( ) ) return timezone . make_aware ( dt , tz ) return value | If the value is naive then the timezone is added to it . | 114 | 14 |
249,844 | def get_active_entry ( user , select_for_update = False ) : entries = apps . get_model ( 'entries' , 'Entry' ) . no_join if select_for_update : entries = entries . select_for_update ( ) entries = entries . filter ( user = user , end_time__isnull = True ) if not entries . exists ( ) : return None if entries . count ( ) > 1 : raise ActiveEntryError ( 'Only one active entry is allowed.' ) return entries [ 0 ] | Returns the user s currently - active entry or None . | 114 | 11 |
249,845 | def get_month_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( day = 1 ) | Returns the first day of the given month . | 39 | 9 |
249,846 | def get_setting ( name , * * kwargs ) : if hasattr ( settings , name ) : # Try user-defined settings first. return getattr ( settings , name ) if 'default' in kwargs : # Fall back to a specified default value. return kwargs [ 'default' ] if hasattr ( defaults , name ) : # If that's not given, look in defaults file. return getattr ( defaults , name ) msg = '{0} must be specified in your project settings.' . format ( name ) raise AttributeError ( msg ) | Returns the user - defined value for the setting or a default value . | 121 | 14 |
249,847 | def get_week_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) days_since_monday = day . weekday ( ) if days_since_monday != 0 : day = day - relativedelta ( days = days_since_monday ) return day | Returns the Monday of the given week . | 71 | 8 |
249,848 | def get_year_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( month = 1 ) . replace ( day = 1 ) | Returns January 1 of the given year . | 46 | 8 |
249,849 | def to_datetime ( date ) : return datetime . datetime ( date . year , date . month , date . day ) | Transforms a date or datetime object into a date object . | 28 | 13 |
249,850 | def report_estimation_accuracy ( request ) : contracts = ProjectContract . objects . filter ( status = ProjectContract . STATUS_COMPLETE , type = ProjectContract . PROJECT_FIXED ) data = [ ( 'Target (hrs)' , 'Actual (hrs)' , 'Point Label' ) ] for c in contracts : if c . contracted_hours ( ) == 0 : continue pt_label = "%s (%.2f%%)" % ( c . name , c . hours_worked / c . contracted_hours ( ) * 100 ) data . append ( ( c . contracted_hours ( ) , c . hours_worked , pt_label ) ) chart_max = max ( [ max ( x [ 0 ] , x [ 1 ] ) for x in data [ 1 : ] ] ) # max of all targets & actuals return render ( request , 'timepiece/reports/estimation_accuracy.html' , { 'data' : json . dumps ( data , cls = DecimalEncoder ) , 'chart_max' : chart_max , } ) | Idea from Software Estimation Demystifying the Black Art McConnel 2006 Fig 3 - 3 . | 233 | 22 |
249,851 | def get_context_data ( self , * * kwargs ) : context = super ( ReportMixin , self ) . get_context_data ( * * kwargs ) form = self . get_form ( ) if form . is_valid ( ) : data = form . cleaned_data start , end = form . save ( ) entryQ = self . get_entry_query ( start , end , data ) trunc = data [ 'trunc' ] if entryQ : vals = ( 'pk' , 'activity' , 'project' , 'project__name' , 'project__status' , 'project__type__label' ) entries = Entry . objects . date_trunc ( trunc , extra_values = vals ) . filter ( entryQ ) else : entries = Entry . objects . none ( ) end = end - relativedelta ( days = 1 ) date_headers = generate_dates ( start , end , by = trunc ) context . update ( { 'from_date' : start , 'to_date' : end , 'date_headers' : date_headers , 'entries' : entries , 'filter_form' : form , 'trunc' : trunc , } ) else : context . update ( { 'from_date' : None , 'to_date' : None , 'date_headers' : [ ] , 'entries' : Entry . objects . none ( ) , 'filter_form' : form , 'trunc' : '' , } ) return context | Processes form data to get relevant entries & date_headers . | 324 | 13 |
249,852 | def get_entry_query ( self , start , end , data ) : # Entry types. incl_billable = data . get ( 'billable' , True ) incl_nonbillable = data . get ( 'non_billable' , True ) incl_leave = data . get ( 'paid_leave' , True ) # If no types are selected, shortcut & return nothing. if not any ( ( incl_billable , incl_nonbillable , incl_leave ) ) : return None # All entries must meet time period requirements. basicQ = Q ( end_time__gte = start , end_time__lt = end ) # Filter by project for HourlyReport. projects = data . get ( 'projects' , None ) basicQ &= Q ( project__in = projects ) if projects else Q ( ) # Filter by user, activity, and project type for BillableReport. if 'users' in data : basicQ &= Q ( user__in = data . get ( 'users' ) ) if 'activities' in data : basicQ &= Q ( activity__in = data . get ( 'activities' ) ) if 'project_types' in data : basicQ &= Q ( project__type__in = data . get ( 'project_types' ) ) # If all types are selected, no further filtering is required. if all ( ( incl_billable , incl_nonbillable , incl_leave ) ) : return basicQ # Filter by whether a project is billable or non-billable. billableQ = None if incl_billable and not incl_nonbillable : billableQ = Q ( activity__billable = True , project__type__billable = True ) if incl_nonbillable and not incl_billable : billableQ = Q ( activity__billable = False ) | Q ( project__type__billable = False ) # Filter by whether the entry is paid leave. leave_ids = utils . get_setting ( 'TIMEPIECE_PAID_LEAVE_PROJECTS' ) . values ( ) leaveQ = Q ( project__in = leave_ids ) if incl_leave : extraQ = ( leaveQ | billableQ ) if billableQ else leaveQ else : extraQ = ( ~ leaveQ & billableQ ) if billableQ else ~ leaveQ return basicQ & extraQ | Builds Entry query from form data . | 518 | 8 |
249,853 | def get_headers ( self , date_headers , from_date , to_date , trunc ) : date_headers = list ( date_headers ) # Earliest date should be no earlier than from_date. if date_headers and date_headers [ 0 ] < from_date : date_headers [ 0 ] = from_date # When organizing by week or month, create a list of the range for # each date header. if date_headers and trunc != 'day' : count = len ( date_headers ) range_headers = [ 0 ] * count for i in range ( count - 1 ) : range_headers [ i ] = ( date_headers [ i ] , date_headers [ i + 1 ] - relativedelta ( days = 1 ) ) range_headers [ count - 1 ] = ( date_headers [ count - 1 ] , to_date ) else : range_headers = date_headers return date_headers , range_headers | Adjust date headers & get range headers . | 202 | 8 |
249,854 | def get_previous_month ( self ) : end = utils . get_month_start ( ) - relativedelta ( days = 1 ) end = utils . to_datetime ( end ) start = utils . get_month_start ( end ) return start , end | Returns date range for the previous full month . | 61 | 9 |
249,855 | def convert_context_to_csv ( self , context ) : content = [ ] date_headers = context [ 'date_headers' ] headers = [ 'Name' ] headers . extend ( [ date . strftime ( '%m/%d/%Y' ) for date in date_headers ] ) headers . append ( 'Total' ) content . append ( headers ) summaries = context [ 'summaries' ] summary = summaries . get ( self . export , [ ] ) for rows , totals in summary : for name , user_id , hours in rows : data = [ name ] data . extend ( hours ) content . append ( data ) total = [ 'Totals' ] total . extend ( totals ) content . append ( total ) return content | Convert the context dictionary into a CSV file . | 163 | 10 |
249,856 | def defaults ( self ) : # Set default date span to previous week. ( start , end ) = get_week_window ( timezone . now ( ) - relativedelta ( days = 7 ) ) return { 'from_date' : start , 'to_date' : end , 'billable' : True , 'non_billable' : False , 'paid_leave' : False , 'trunc' : 'day' , 'projects' : [ ] , } | Default filter form data when no GET data is provided . | 102 | 11 |
249,857 | def get_hours_data ( self , entries , date_headers ) : project_totals = get_project_totals ( entries , date_headers , total_column = False ) if entries else [ ] data_map = { } for rows , totals in project_totals : for user , user_id , periods in rows : for period in periods : day = period [ 'day' ] if day not in data_map : data_map [ day ] = { 'billable' : 0 , 'nonbillable' : 0 } data_map [ day ] [ 'billable' ] += period [ 'billable' ] data_map [ day ] [ 'nonbillable' ] += period [ 'nonbillable' ] return data_map | Sum billable and non - billable hours across all users . | 165 | 13 |
249,858 | def add_parameters ( url , parameters ) : if parameters : sep = '&' if '?' in url else '?' return '{0}{1}{2}' . format ( url , sep , urlencode ( parameters ) ) return url | Appends URL - encoded parameters to the base URL . It appends after & if ? is found in the URL ; otherwise it appends using ? . Keep in mind that this tag does not take into account the value of existing params ; it is therefore possible to add another value for a pre - existing parameter . | 53 | 63 |
249,859 | def get_max_hours ( context ) : progress = context [ 'project_progress' ] return max ( [ 0 ] + [ max ( p [ 'worked' ] , p [ 'assigned' ] ) for p in progress ] ) | Return the largest number of hours worked or assigned on any project . | 51 | 13 |
249,860 | def get_uninvoiced_hours ( entries , billable = None ) : statuses = ( 'invoiced' , 'not-invoiced' ) if billable is not None : billable = ( billable . lower ( ) == u'billable' ) entries = [ e for e in entries if e . activity . billable == billable ] hours = sum ( [ e . hours for e in entries if e . status not in statuses ] ) return '{0:.2f}' . format ( hours ) | Given an iterable of entries return the total hours that have not been invoiced . If billable is passed as billable or nonbillable limit to the corresponding entries . | 115 | 36 |
249,861 | def humanize_hours ( total_hours , frmt = '{hours:02d}:{minutes:02d}:{seconds:02d}' , negative_frmt = None ) : seconds = int ( float ( total_hours ) * 3600 ) return humanize_seconds ( seconds , frmt , negative_frmt ) | Given time in hours return a string representing the time . | 73 | 11 |
249,862 | def _timesheet_url ( url_name , pk , date = None ) : url = reverse ( url_name , args = ( pk , ) ) if date : params = { 'month' : date . month , 'year' : date . year } return '?' . join ( ( url , urlencode ( params ) ) ) return url | Utility to create a time sheet URL with optional date parameters . | 76 | 13 |
249,863 | def reject_user_timesheet ( request , user_id ) : form = YearMonthForm ( request . GET or request . POST ) user = User . objects . get ( pk = user_id ) if form . is_valid ( ) : from_date , to_date = form . save ( ) entries = Entry . no_join . filter ( status = Entry . VERIFIED , user = user , start_time__gte = from_date , end_time__lte = to_date ) if request . POST . get ( 'yes' ) : if entries . exists ( ) : count = entries . count ( ) Entry . no_join . filter ( pk__in = entries ) . update ( status = Entry . UNVERIFIED ) msg = 'You have rejected %d previously verified entries.' % count else : msg = 'There are no verified entries to reject.' messages . info ( request , msg ) else : return render ( request , 'timepiece/user/timesheet/reject.html' , { 'date' : from_date , 'timesheet_user' : user } ) else : msg = 'You must provide a month and year for entries to be rejected.' messages . error ( request , msg ) url = reverse ( 'view_user_timesheet' , args = ( user_id , ) ) return HttpResponseRedirect ( url ) | This allows admins to reject all entries instead of just one | 294 | 11 |
249,864 | def _is_requirement ( line ) : line = line . strip ( ) return line and not ( line . startswith ( "-r" ) or line . startswith ( "#" ) ) | Returns whether the line is a valid package requirement . | 43 | 10 |
249,865 | def render_to_response ( self , context ) : if self . redirect_if_one_result : if self . object_list . count ( ) == 1 and self . form . is_bound : return redirect ( self . object_list . get ( ) . get_absolute_url ( ) ) return super ( SearchMixin , self ) . render_to_response ( context ) | When the user makes a search and there is only one result redirect to the result s detail page rather than rendering the list . | 83 | 25 |
249,866 | def clean_start_time ( self ) : start = self . cleaned_data . get ( 'start_time' ) if not start : return start active_entries = self . user . timepiece_entries . filter ( start_time__gte = start , end_time__isnull = True ) for entry in active_entries : output = ( 'The start time is on or before the current entry: ' '%s - %s starting at %s' % ( entry . project , entry . activity , entry . start_time . strftime ( '%H:%M:%S' ) ) ) raise forms . ValidationError ( output ) return start | Make sure that the start time doesn t come before the active entry | 145 | 13 |
249,867 | def clean ( self ) : active = utils . get_active_entry ( self . user ) start_time = self . cleaned_data . get ( 'start_time' , None ) end_time = self . cleaned_data . get ( 'end_time' , None ) if active and active . pk != self . instance . pk : if ( start_time and start_time > active . start_time ) or ( end_time and end_time > active . start_time ) : raise forms . ValidationError ( 'The start time or end time conflict with the active ' 'entry: {activity} on {project} starting at ' '{start_time}.' . format ( project = active . project , activity = active . activity , start_time = active . start_time . strftime ( '%H:%M:%S' ) , ) ) month_start = utils . get_month_start ( start_time ) next_month = month_start + relativedelta ( months = 1 ) entries = self . instance . user . timepiece_entries . filter ( Q ( status = Entry . APPROVED ) | Q ( status = Entry . INVOICED ) , start_time__gte = month_start , end_time__lt = next_month ) entry = self . instance if not self . acting_user . is_superuser : if ( entries . exists ( ) and not entry . id or entry . id and entry . status == Entry . INVOICED ) : message = 'You cannot add/edit entries after a timesheet has been ' 'approved or invoiced. Please correct the start and end times.' raise forms . ValidationError ( message ) return self . cleaned_data | If we re not editing the active entry ensure that this entry doesn t conflict with or come after the active entry . | 376 | 23 |
249,868 | def clock_in ( request ) : user = request . user # Lock the active entry for the duration of this transaction, to prevent # creating multiple active entries. active_entry = utils . get_active_entry ( user , select_for_update = True ) initial = dict ( [ ( k , v ) for k , v in request . GET . items ( ) ] ) data = request . POST or None form = ClockInForm ( data , initial = initial , user = user , active = active_entry ) if form . is_valid ( ) : entry = form . save ( ) message = 'You have clocked into {0} on {1}.' . format ( entry . activity . name , entry . project ) messages . info ( request , message ) return HttpResponseRedirect ( reverse ( 'dashboard' ) ) return render ( request , 'timepiece/entry/clock_in.html' , { 'form' : form , 'active' : active_entry , } ) | For clocking the user into a project . | 212 | 9 |
249,869 | def toggle_pause ( request ) : entry = utils . get_active_entry ( request . user ) if not entry : raise Http404 # toggle the paused state entry . toggle_paused ( ) entry . save ( ) # create a message that can be displayed to the user action = 'paused' if entry . is_paused else 'resumed' message = 'Your entry, {0} on {1}, has been {2}.' . format ( entry . activity . name , entry . project , action ) messages . info ( request , message ) # redirect to the log entry list return HttpResponseRedirect ( reverse ( 'dashboard' ) ) | Allow the user to pause and unpause the active entry . | 142 | 12 |
249,870 | def reject_entry ( request , entry_id ) : return_url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) try : entry = Entry . no_join . get ( pk = entry_id ) except : message = 'No such log entry.' messages . error ( request , message ) return redirect ( return_url ) if entry . status == Entry . UNVERIFIED or entry . status == Entry . INVOICED : msg_text = 'This entry is unverified or is already invoiced.' messages . error ( request , msg_text ) return redirect ( return_url ) if request . POST . get ( 'Yes' ) : entry . status = Entry . UNVERIFIED entry . save ( ) msg_text = 'The entry\'s status was set to unverified.' messages . info ( request , msg_text ) return redirect ( return_url ) return render ( request , 'timepiece/entry/reject.html' , { 'entry' : entry , 'next' : request . GET . get ( 'next' ) , } ) | Admins can reject an entry that has been verified or approved but not invoiced to set its status to unverified for the user to fix . | 234 | 30 |
249,871 | def delete_entry ( request , entry_id ) : try : entry = Entry . no_join . get ( pk = entry_id , user = request . user ) except Entry . DoesNotExist : message = 'No such entry found.' messages . info ( request , message ) url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) return HttpResponseRedirect ( url ) if request . method == 'POST' : key = request . POST . get ( 'key' , None ) if key and key == entry . delete_key : entry . delete ( ) message = 'Deleted {0} for {1}.' . format ( entry . activity . name , entry . project ) messages . info ( request , message ) url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) return HttpResponseRedirect ( url ) else : message = 'You are not authorized to delete this entry!' messages . error ( request , message ) return render ( request , 'timepiece/entry/delete.html' , { 'entry' : entry , } ) | Give the user the ability to delete a log entry with a confirmation beforehand . If this method is invoked via a GET request a form asking for a confirmation of intent will be presented to the user . If this method is invoked via a POST request the entry will be deleted . | 239 | 54 |
249,872 | def get_hours_per_week ( self , user = None ) : try : profile = UserProfile . objects . get ( user = user or self . user ) except UserProfile . DoesNotExist : profile = None return profile . hours_per_week if profile else Decimal ( '40.00' ) | Retrieves the number of hours the user should work per week . | 67 | 14 |
249,873 | def get_hours_for_week ( self , week_start = None ) : week_start = week_start if week_start else self . week_start week_end = week_start + relativedelta ( days = 7 ) return ProjectHours . objects . filter ( week_start__gte = week_start , week_start__lt = week_end ) | Gets all ProjectHours entries in the 7 - day period beginning on week_start . | 80 | 18 |
249,874 | def get_users_from_project_hours ( self , project_hours ) : name = ( 'user__first_name' , 'user__last_name' ) users = project_hours . values_list ( 'user__id' , * name ) . distinct ( ) . order_by ( * name ) return users | Gets a list of the distinct users included in the project hours entries ordered by name . | 70 | 18 |
249,875 | def check_all ( self , all_entries , * args , * * kwargs ) : all_overlaps = 0 while True : try : user_entries = all_entries . next ( ) except StopIteration : return all_overlaps else : user_total_overlaps = self . check_entry ( user_entries , * args , * * kwargs ) all_overlaps += user_total_overlaps | Go through lists of entries find overlaps among each return the total | 101 | 13 |
249,876 | def check_entry ( self , entries , * args , * * kwargs ) : verbosity = kwargs . get ( 'verbosity' , 1 ) user_total_overlaps = 0 user = '' for index_a , entry_a in enumerate ( entries ) : # Show the name the first time through if index_a == 0 : if args and verbosity >= 1 or verbosity >= 2 : self . show_name ( entry_a . user ) user = entry_a . user for index_b in range ( index_a , len ( entries ) ) : entry_b = entries [ index_b ] if entry_a . check_overlap ( entry_b ) : user_total_overlaps += 1 self . show_overlap ( entry_a , entry_b , verbosity = verbosity ) if user_total_overlaps and user and verbosity >= 1 : overlap_data = { 'first' : user . first_name , 'last' : user . last_name , 'total' : user_total_overlaps , } self . stdout . write ( 'Total overlapping entries for user ' + '%(first)s %(last)s: %(total)d' % overlap_data ) return user_total_overlaps | With a list of entries check each entry against every other | 281 | 11 |
249,877 | def find_start ( self , * * kwargs ) : week = kwargs . get ( 'week' , False ) month = kwargs . get ( 'month' , False ) year = kwargs . get ( 'year' , False ) days = kwargs . get ( 'days' , 0 ) # If no flags are True, set to the beginning of last billing window # to assure we catch all recent violations start = timezone . now ( ) - relativedelta ( months = 1 , day = 1 ) # Set the start date based on arguments provided through options if week : start = utils . get_week_start ( ) if month : start = timezone . now ( ) - relativedelta ( day = 1 ) if year : start = timezone . now ( ) - relativedelta ( day = 1 , month = 1 ) if days : start = timezone . now ( ) - relativedelta ( days = days ) start -= relativedelta ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 ) return start | Determine the starting point of the query using CLI keyword arguments | 229 | 13 |
249,878 | def find_users ( self , * args ) : if args : names = reduce ( lambda query , arg : query | ( Q ( first_name__icontains = arg ) | Q ( last_name__icontains = arg ) ) , args , Q ( ) ) # noqa users = User . objects . filter ( names ) # If no args given, check every user else : users = User . objects . all ( ) # Display errors if no user was found if not users . count ( ) and args : if len ( args ) == 1 : raise CommandError ( 'No user was found with the name %s' % args [ 0 ] ) else : arg_list = ', ' . join ( args ) raise CommandError ( 'No users found with the names: %s' % arg_list ) return users | Returns the users to search given names as args . Return all users if there are no args provided . | 174 | 20 |
249,879 | def find_entries ( self , users , start , * args , * * kwargs ) : forever = kwargs . get ( 'all' , False ) for user in users : if forever : entries = Entry . objects . filter ( user = user ) . order_by ( 'start_time' ) else : entries = Entry . objects . filter ( user = user , start_time__gte = start ) . order_by ( 'start_time' ) yield entries | Find all entries for all users from a given starting point . If no starting point is provided all entries are returned . | 103 | 23 |
249,880 | def cbv_decorator ( function_decorator ) : def class_decorator ( View ) : View . dispatch = method_decorator ( function_decorator ) ( View . dispatch ) return View return class_decorator | Allows a function - based decorator to be used on a CBV . | 55 | 15 |
249,881 | def date_totals ( entries , by ) : date_dict = { } for date , date_entries in groupby ( entries , lambda x : x [ 'date' ] ) : if isinstance ( date , datetime . datetime ) : date = date . date ( ) d_entries = list ( date_entries ) if by == 'user' : name = ' ' . join ( ( d_entries [ 0 ] [ 'user__first_name' ] , d_entries [ 0 ] [ 'user__last_name' ] ) ) elif by == 'project' : name = d_entries [ 0 ] [ 'project__name' ] else : name = d_entries [ 0 ] [ by ] pk = d_entries [ 0 ] [ by ] hours = get_hours_summary ( d_entries ) date_dict [ date ] = hours return name , pk , date_dict | Yield a user s name and a dictionary of their hours | 205 | 12 |
249,882 | def get_project_totals ( entries , date_headers , hour_type = None , overtime = False , total_column = False , by = 'user' ) : totals = [ 0 for date in date_headers ] rows = [ ] for thing , thing_entries in groupby ( entries , lambda x : x [ by ] ) : name , thing_id , date_dict = date_totals ( thing_entries , by ) dates = [ ] for index , day in enumerate ( date_headers ) : if isinstance ( day , datetime . datetime ) : day = day . date ( ) if hour_type : total = date_dict . get ( day , { } ) . get ( hour_type , 0 ) dates . append ( total ) else : billable = date_dict . get ( day , { } ) . get ( 'billable' , 0 ) nonbillable = date_dict . get ( day , { } ) . get ( 'non_billable' , 0 ) total = billable + nonbillable dates . append ( { 'day' : day , 'billable' : billable , 'nonbillable' : nonbillable , 'total' : total } ) totals [ index ] += total if total_column : dates . append ( sum ( dates ) ) if overtime : dates . append ( find_overtime ( dates ) ) dates = [ date or '' for date in dates ] rows . append ( ( name , thing_id , dates ) ) if total_column : totals . append ( sum ( totals ) ) totals = [ t or '' for t in totals ] yield ( rows , totals ) | Yield hour totals grouped by user and date . Optionally including overtime . | 357 | 15 |
249,883 | def validate ( self , validation_instances , metrics , iteration = None ) : if not validation_instances or not metrics : return { } split_id = 'val%s' % iteration if iteration is not None else 'val' train_results = evaluate . evaluate ( self , validation_instances , metrics = metrics , split_id = split_id ) output . output_results ( train_results , split_id ) return train_results | Evaluate this model on validation_instances during training and output a report . | 95 | 17 |
249,884 | def predict_and_score ( self , eval_instances , random = False , verbosity = 0 ) : if hasattr ( self , '_using_default_separate' ) and self . _using_default_separate : raise NotImplementedError self . _using_default_combined = True return ( self . predict ( eval_instances , random = random , verbosity = verbosity ) , self . score ( eval_instances , verbosity = verbosity ) ) | Return most likely outputs and scores for the particular set of outputs given in eval_instances as a tuple . Return value should be equivalent to the default implementation of | 106 | 32 |
249,885 | def load ( self , infile ) : model = pickle . load ( infile ) self . __dict__ . update ( model . __dict__ ) | Deserialize a model from a stored file . | 33 | 10 |
249,886 | def iter_batches ( iterable , batch_size ) : # http://stackoverflow.com/a/8290514/4481448 sourceiter = iter ( iterable ) while True : batchiter = islice ( sourceiter , batch_size ) yield chain ( [ batchiter . next ( ) ] , batchiter ) | Given a sequence or iterable yield batches from that iterable until it runs out . Note that this function returns a generator and also each batch will be a generator . | 73 | 33 |
249,887 | def gen_batches ( iterable , batch_size ) : def batches_thunk ( ) : return iter_batches ( iterable , batch_size ) try : length = len ( iterable ) except TypeError : return batches_thunk ( ) num_batches = ( length - 1 ) // batch_size + 1 return SizedGenerator ( batches_thunk , length = num_batches ) | Returns a generator object that yields batches from iterable . See iter_batches for more details and caveats . | 89 | 22 |
249,888 | def inverted ( self ) : return Instance ( input = self . output , output = self . input , annotated_input = self . annotated_output , annotated_output = self . annotated_input , alt_inputs = self . alt_outputs , alt_outputs = self . alt_inputs , source = self . source ) | Return a version of this instance with inputs replaced by outputs and vice versa . | 76 | 15 |
249,889 | def get_data_or_download ( dir_name , file_name , url = '' , size = 'unknown' ) : dname = os . path . join ( stanza . DATA_DIR , dir_name ) fname = os . path . join ( dname , file_name ) if not os . path . isdir ( dname ) : assert url , 'Could not locate data {}, and url was not specified. Cannot retrieve data.' . format ( dname ) os . makedirs ( dname ) if not os . path . isfile ( fname ) : assert url , 'Could not locate data {}, and url was not specified. Cannot retrieve data.' . format ( fname ) logging . warn ( 'downloading from {}. This file could potentially be *very* large! Actual size ({})' . format ( url , size ) ) with open ( fname , 'wb' ) as f : f . write ( get_from_url ( url ) ) return fname | Returns the data . if the data hasn t been downloaded then first download the data . | 213 | 17 |
249,890 | def add ( self , word , count = 1 ) : if word not in self : super ( Vocab , self ) . __setitem__ ( word , len ( self ) ) self . _counts [ word ] += count return self [ word ] | Add a word to the vocabulary and return its index . | 53 | 11 |
249,891 | def subset ( self , words ) : v = self . __class__ ( unk = self . _unk ) unique = lambda seq : len ( set ( seq ) ) == len ( seq ) assert unique ( words ) for w in words : if w in self : v . add ( w , count = self . count ( w ) ) return v | Get a new Vocab containing only the specified subset of words . | 73 | 13 |
249,892 | def _index2word ( self ) : # TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable compute_index2word = lambda : self . keys ( ) # this works because self is an OrderedDict # create if it doesn't exist try : self . _index2word_cache except AttributeError : self . _index2word_cache = compute_index2word ( ) # update if it is out of date if len ( self . _index2word_cache ) != len ( self ) : self . _index2word_cache = compute_index2word ( ) return self . _index2word_cache | Mapping from indices to words . | 150 | 7 |
249,893 | def from_dict ( cls , word2index , unk , counts = None ) : try : if word2index [ unk ] != 0 : raise ValueError ( 'unk must be assigned index 0' ) except KeyError : raise ValueError ( 'word2index must have an entry for unk.' ) # check that word2index is a bijection vals = set ( word2index . values ( ) ) # unique indices n = len ( vals ) bijection = ( len ( word2index ) == n ) and ( vals == set ( range ( n ) ) ) if not bijection : raise ValueError ( 'word2index is not a bijection between N words and the integers 0 through N-1.' ) # reverse the dictionary index2word = { idx : word for word , idx in word2index . iteritems ( ) } vocab = cls ( unk = unk ) for i in xrange ( n ) : vocab . add ( index2word [ i ] ) if counts : matching_entries = set ( word2index . keys ( ) ) == set ( counts . keys ( ) ) if not matching_entries : raise ValueError ( 'entries of word2index do not match counts (did you include UNK?)' ) vocab . _counts = counts return vocab | Create Vocab from an existing string to integer dictionary . | 287 | 11 |
249,894 | def to_file ( self , f ) : for word in self . _index2word : count = self . _counts [ word ] f . write ( u'{}\t{}\n' . format ( word , count ) . encode ( 'utf-8' ) ) | Write vocab to a file . | 60 | 7 |
249,895 | def backfill_unk_emb ( self , E , filled_words ) : unk_emb = E [ self [ self . _unk ] ] for i , word in enumerate ( self ) : if word not in filled_words : E [ i ] = unk_emb | Backfills an embedding matrix with the embedding for the unknown token . | 60 | 16 |
249,896 | def best_gpu ( max_usage = USAGE_THRESHOLD , verbose = False ) : try : proc = subprocess . Popen ( "nvidia-smi" , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) output , error = proc . communicate ( ) if error : raise Exception ( error ) except Exception , e : sys . stderr . write ( "Couldn't run nvidia-smi to find best GPU, using CPU: %s\n" % str ( e ) ) sys . stderr . write ( "(This is normal if you have no GPU or haven't configured CUDA.)\n" ) return "cpu" usages = parse_output ( output ) pct_usage = [ max ( u . mem , cpu_backoff ( u ) ) for u in usages ] max_usage = min ( max_usage , min ( pct_usage ) ) open_gpus = [ index for index , usage in enumerate ( usages ) if max ( usage . mem , cpu_backoff ( usage ) ) <= max_usage ] if verbose : print ( 'Best GPUs:' ) for index in open_gpus : print ( '%d: %s fan, %s mem, %s cpu' % ( index , format_percent ( usages [ index ] . fan ) , format_percent ( usages [ index ] . mem ) , format_percent ( usages [ index ] . cpu ) ) ) if open_gpus : result = "gpu" + str ( random . choice ( open_gpus ) ) else : result = "cpu" if verbose : print ( 'Chosen: ' + result ) return result | Return the name of a device to use either cpu or gpu0 gpu1 ... The least - used GPU with usage under the constant threshold will be chosen ; ties are broken randomly . | 372 | 38 |
249,897 | def evaluate ( learner , eval_data , metrics , metric_names = None , split_id = None , write_data = False ) : if metric_names is None : metric_names = [ ( metric . __name__ if hasattr ( metric , '__name__' ) else ( 'm%d' % i ) ) for i , metric in enumerate ( metrics ) ] split_prefix = split_id + '.' if split_id else '' if write_data : config . dump ( [ inst . __dict__ for inst in eval_data ] , 'data.%sjsons' % split_prefix , default = json_default , lines = True ) results = { split_prefix + 'num_params' : learner . num_params } predictions , scores = learner . predict_and_score ( eval_data ) config . dump ( predictions , 'predictions.%sjsons' % split_prefix , lines = True ) config . dump ( scores , 'scores.%sjsons' % split_prefix , lines = True ) for metric , metric_name in zip ( metrics , metric_names ) : prefix = split_prefix + ( metric_name + '.' if metric_name else '' ) inst_outputs = metric ( eval_data , predictions , scores , learner ) if metric_name in [ 'data' , 'predictions' , 'scores' ] : warnings . warn ( 'not outputting metric scores for metric "%s" because it would shadow ' 'another results file' ) else : config . dump ( inst_outputs , '%s.%sjsons' % ( metric_name , split_prefix ) , lines = True ) mean = np . mean ( inst_outputs ) gmean = np . exp ( np . log ( inst_outputs ) . mean ( ) ) sum = np . sum ( inst_outputs ) std = np . std ( inst_outputs ) results . update ( { prefix + 'mean' : mean , prefix + 'gmean' : gmean , prefix + 'sum' : sum , prefix + 'std' : std , # prefix + 'ci_lower': ci_lower, # prefix + 'ci_upper': ci_upper, } ) config . dump_pretty ( results , 'results.%sjson' % split_prefix ) return results | Evaluate learner on the instances in eval_data according to each metric in metric and return a dictionary summarizing the values of the metrics . | 509 | 30 |
249,898 | def json2pb ( pb , js , useFieldNumber = False ) : for field in pb . DESCRIPTOR . fields : if useFieldNumber : key = field . number else : key = field . name if key not in js : continue if field . type == FD . TYPE_MESSAGE : pass elif field . type in _js2ftype : ftype = _js2ftype [ field . type ] else : raise ParseError ( "Field %s.%s of type '%d' is not supported" % ( pb . __class__ . __name__ , field . name , field . type , ) ) value = js [ key ] if field . label == FD . LABEL_REPEATED : pb_value = getattr ( pb , field . name , None ) for v in value : if field . type == FD . TYPE_MESSAGE : json2pb ( pb_value . add ( ) , v , useFieldNumber = useFieldNumber ) else : pb_value . append ( ftype ( v ) ) else : if field . type == FD . TYPE_MESSAGE : json2pb ( getattr ( pb , field . name , None ) , value , useFieldNumber = useFieldNumber ) else : setattr ( pb , field . name , ftype ( value ) ) return pb | convert JSON string to google . protobuf . descriptor instance | 299 | 13 |
249,899 | def annotate_json ( self , text , annotators = None ) : # WARN(chaganty): I'd like to deprecate this function -- we # should just use annotate().json #properties = { # 'annotators': ','.join(annotators or self.default_annotators), # 'outputFormat': 'json', #} #return self._request(text, properties).json(strict=False) doc = self . annotate ( text , annotators ) return doc . json | Return a JSON dict from the CoreNLP server containing annotations of the text . | 109 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.