idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
31,000
def visit_Module ( self , node , ** kwargs ) : containingNodes = kwargs . get ( 'containingNodes' , [ ] ) if self . options . debug : stderr . write ( "# Module {0}{1}" . format ( self . options . fullPathNamespace , linesep ) ) if get_docstring ( node ) : if self . options . topLevelNamespace : fullPathNamespace = sel...
Handles the module - level docstring .
31,001
def visit_Assign ( self , node , ** kwargs ) : lineNum = node . lineno - 1 match = AstWalker . __attributeRE . match ( self . lines [ lineNum ] ) if match : self . lines [ lineNum ] = '{0}## @property {1}{2}{0}# {3}{2}' '{0}# @hideinitializer{2}{4}{2}' . format ( match . group ( 1 ) , match . group ( 2 ) , linesep , ma...
Handles assignments within code .
31,002
def visit_Call ( self , node , ** kwargs ) : lineNum = node . lineno - 1 match = AstWalker . __implementsRE . match ( self . lines [ lineNum ] ) if match : self . lines [ lineNum ] = '{0}## @implements {1}{2}{0}{3}{2}' . format ( match . group ( 1 ) , match . group ( 2 ) , linesep , self . lines [ lineNum ] . rstrip ( ...
Handles function calls within code .
31,003
def visit_FunctionDef ( self , node , ** kwargs ) : if self . options . debug : stderr . write ( "# Function {0.name}{1}" . format ( node , linesep ) ) containingNodes = kwargs . get ( 'containingNodes' ) or [ ] containingNodes . append ( ( node . name , 'function' ) ) if self . options . topLevelNamespace : fullPathNa...
Handles function definitions within code .
31,004
def visit_ClassDef ( self , node , ** kwargs ) : lineNum = node . lineno - 1 containingNodes = kwargs . get ( 'containingNodes' ) or [ ] if not self . options . object_respect : line = self . lines [ lineNum ] match = AstWalker . __classRE . match ( line ) if match : if match . group ( 2 ) == 'object' : self . lines [ ...
Handles class definitions within code .
31,005
def parseLines ( self ) : inAst = parse ( '' . join ( self . lines ) , self . inFilename ) self . visit ( inAst )
Form an AST for the code and produce a new version of the source .
31,006
def lambda_handler ( event , context = None , settings_name = "zappa_settings" ) : time_start = datetime . datetime . now ( ) if settings . DEBUG : logger . info ( 'Zappa Event: {}' . format ( event ) ) if event . get ( 'method' , None ) : environ = create_wsgi_request ( event , script_name = settings . SCRIPT_NAME ) e...
An AWS Lambda function which parses specific API Gateway input into a WSGI request .
31,007
def require_settings ( self , args , options ) : if not options . has_key ( 'environment' ) : print ( "You must call deploy with an environment name. \n python manage.py deploy <environment>" ) raise ImproperlyConfigured from django . conf import settings if not 'ZAPPA_SETTINGS' in dir ( settings ) : print ( "Please de...
Load the ZAPPA_SETTINGS as we expect it .
31,008
def clean_account ( self ) : account = self . cleaned_data [ 'account' ] if not account : return if account . type != Account . TYPES . income : raise ValidationError ( 'Account must be an income account' ) try : account . housemate except Housemate . DoesNotExist : pass else : raise ValidationError ( 'Account already ...
Ensure this is an income account
31,009
def get_amount_normal ( self , billing_cycle ) : if self . is_one_off ( ) : billing_cycle_number = self . _get_billing_cycle_number ( billing_cycle ) if billing_cycle_number > self . total_billing_cycles : return Decimal ( '0' ) else : splits = ratio_split ( amount = self . fixed_amount , ratios = [ Decimal ( '1' ) ] *...
Get the amount due on the given billing cycle
31,010
def get_amount_arrears_balance ( self , billing_cycle ) : return self . to_account . balance ( transaction__date__lt = billing_cycle . date_range . lower , )
Get the balance of to_account at the end of billing_cycle
31,011
def get_amount_arrears_transactions ( self , billing_cycle ) : previous_billing_cycle = billing_cycle . get_previous ( ) if not previous_billing_cycle : return Decimal ( 0 ) return self . to_account . balance ( transaction__date__lt = previous_billing_cycle . date_range . upper , transaction__date__gte = previous_billi...
Get the sum of all transaction legs in to_account during given billing cycle
31,012
def enact ( self , billing_cycle , disable_if_done = True ) : as_of = billing_cycle . date_range . lower if not self . is_enactable ( as_of ) : raise CannotEnactUnenactableRecurringCostError ( "RecurringCost {} is unenactable." . format ( self . uuid ) ) if self . has_enacted ( billing_cycle ) : raise RecurringCostAlre...
Enact this RecurringCost for the given billing cycle
31,013
def disable_if_done ( self , commit = True ) : if self . _is_billing_complete ( ) and not self . disabled : self . disabled = True if commit : self . save ( )
Set disabled = True if we have billed all we need to
31,014
def is_enactable ( self , as_of ) : return not self . disabled and not self . archived and not self . _is_finished ( as_of ) and self . _is_ready ( as_of ) and not self . _is_billing_complete ( )
Can this RecurringCost be enacted
31,015
def has_enacted ( self , billing_cycle ) : return RecurredCost . objects . filter ( recurring_cost = self , billing_cycle = billing_cycle , ) . exists ( )
Has this recurring cost already enacted transactions for given billing cycle?
31,016
def _is_ready ( self , as_of ) : if self . is_one_off ( ) : return self . initial_billing_cycle . date_range . lower <= as_of else : return True
Is the RecurringCost ready to be enacted as of the date as_of
31,017
def _is_finished ( self , as_of ) : if self . is_one_off ( ) : last_billing_cycle = self . get_billing_cycles ( ) [ self . total_billing_cycles - 1 ] return last_billing_cycle . date_range . upper <= as_of else : return False
Have the specified number of billing cycles been completed?
31,018
def _is_billing_complete ( self ) : if self . is_one_off ( ) : return self . get_billed_amount ( ) >= Balance ( self . fixed_amount , self . currency ) else : return False
Has the specified fixed_amount been billed?
31,019
def _get_billing_cycle_number ( self , billing_cycle ) : begins_before_initial_date = billing_cycle . date_range . lower < self . initial_billing_cycle . date_range . lower if begins_before_initial_date : raise ProvidedBillingCycleBeginsBeforeInitialBillingCycle ( '{} precedes initial cycle {}' . format ( billing_cycle...
Gets the 1 - indexed number of the billing cycle relative to the provided billing cycle
31,020
def split ( self , amount ) : split_objs = list ( self . all ( ) ) if not split_objs : raise NoSplitsFoundForRecurringCost ( ) portions = [ split_obj . portion for split_obj in split_objs ] split_amounts = ratio_split ( amount , portions ) return [ ( split_objs [ i ] , split_amount ) for i , split_amount in enumerate (...
Split the value given by amount according to the RecurringCostSplit s portions
31,021
def make_transaction ( self ) : if self . pk : raise CannotRecreateTransactionOnRecurredCost ( 'The transaction for this recurred cost has already been created. You cannot create it again.' ) amount = self . recurring_cost . get_amount ( self . billing_cycle ) if not amount : return None self . transaction = Transactio...
Create the transaction for this RecurredCost
31,022
def populate ( cls , as_of = None ) : return cls . _populate ( as_of = as_of or date . today ( ) , delete = True )
Ensure the next X years of billing cycles exist
31,023
def _populate ( cls , as_of = None , delete = False ) : billing_cycle_helper = get_billing_cycle ( ) billing_cycles_exist = BillingCycle . objects . exists ( ) try : current_billing_cycle = BillingCycle . objects . as_of ( date = as_of ) except BillingCycle . DoesNotExist : current_billing_cycle = None if not billing_c...
Populate the table with billing cycles starting from as_of
31,024
def get_next ( self ) : return BillingCycle . objects . filter ( date_range__gt = self . date_range ) . order_by ( 'date_range' ) . first ( )
Get the billing cycle after this one . May return None
31,025
def get_previous ( self ) : return BillingCycle . objects . filter ( date_range__lt = self . date_range ) . order_by ( 'date_range' ) . last ( )
Get the billing cycle prior to this one . May return None
31,026
def is_reconciled ( self ) : from hordak . models import StatementImport , StatementLine since = datetime ( self . date_range . lower . year , self . date_range . lower . month , self . date_range . lower . day , tzinfo = UTC ) if not StatementImport . objects . filter ( timestamp__gte = since ) . exists ( ) : return F...
Have transactions been imported and reconciled for this billing cycle?
31,027
def hash ( filename , algorithm = 'sha256' ) : if incompatible : raise Incompatible if algorithm not in [ 'sha256' , 'sha384' , 'sha512' ] : raise InvalidArguments ( 'Algorithm {} not supported' . format ( algorithm ) ) result = call ( 'hash' , '--algorithm' , algorithm , filename ) return result . strip ( ) . split ( ...
Hash the given filename . Unavailable in pip<8 . 0 . 0
31,028
def partition ( list_ , columns = 2 ) : iter_ = iter ( list_ ) columns = int ( columns ) rows = [ ] while True : row = [ ] for column_number in range ( 1 , columns + 1 ) : try : value = six . next ( iter_ ) except StopIteration : pass else : row . append ( value ) if not row : return rows rows . append ( row )
Break a list into columns number of columns .
31,029
def get_balance_context ( self ) : bank_account = Account . objects . get ( name = 'Bank' ) return dict ( bank = bank_account , retained_earnings_accounts = Account . objects . filter ( parent__name = 'Retained Earnings' ) , )
Get the high level balances
31,030
def get_accounts_context ( self ) : income_parent = Account . objects . get ( name = 'Income' ) housemate_parent = Account . objects . get ( name = 'Housemate Income' ) expense_parent = Account . objects . get ( name = 'Expenses' ) current_liabilities_parent = Account . objects . get ( name = 'Current Liabilities' ) lo...
Get the accounts we may want to display
31,031
def _build_syl ( vowels , tone_numbers = False ) : consonant_end = '(?![{a}{e}{i}{o}{u}{v}]|u:)' . format ( a = _a , e = _e , i = _i , o = _o , u = _u , v = _v ) _vowels = vowels . copy ( ) for v , s in _vowels . items ( ) : if len ( s ) > 1 : _vowels [ v ] = '[{}]' . format ( s ) return ( '(?:\u00B7|\u2027)?' '(?:' '(...
Builds a Pinyin syllable re pattern .
31,032
def _build_word ( syl , vowels ) : return "(?:{syl}(?:-(?={syl})|'(?=[{a}{e}{o}])(?={syl}))?)+" . format ( syl = syl , a = vowels [ 'a' ] , e = vowels [ 'e' ] , o = vowels [ 'o' ] )
Builds a Pinyin word re pattern from a Pinyin syllable re pattern .
31,033
def _build_sentence ( word ) : return ( "(?:{word}|[{non_stops}]|(?<![{stops} ]) )+" "[{stops}]['\"\]\}}\)]*" ) . format ( word = word , non_stops = non_stops . replace ( '-' , '\-' ) , stops = stops )
Builds a Pinyin sentence re pattern from a Pinyin word re pattern .
31,034
def read_file ( filename ) : infile = open ( filename , 'r' ) lines = infile . readlines ( ) infile . close ( ) return lines
Read contents of the specified file .
31,035
def _computeWeights ( self , logform = False , include_nonzero = False , recalc_denom = True , return_f_k = False ) : if ( include_nonzero ) : f_k = self . f_k K = self . K else : f_k = self . f_k [ self . states_with_samples ] K = len ( self . states_with_samples ) Warray_nk = np . zeros ( [ self . N , K ] , dtype = n...
Compute the normalized weights corresponding to samples for the given reduced potential .
31,036
def _pseudoinverse ( self , A , tol = 1.0e-10 ) : [ M , N ] = A . shape if N != M : raise DataError ( "pseudoinverse can only be computed for square matrices: dimensions were %d x %d" % ( M , N ) ) if ( np . any ( np . isnan ( A ) ) ) : print ( "attempted to compute pseudoinverse of A =" ) print ( A ) raise ParameterEr...
Compute the Moore - Penrose pseudoinverse .
31,037
def _zerosamestates ( self , A ) : for pair in self . samestates : A [ pair [ 0 ] , pair [ 1 ] ] = 0 A [ pair [ 1 ] , pair [ 0 ] ] = 0
zeros out states that should be identical
31,038
def _initializeFreeEnergies ( self , verbose = False , method = 'zeros' ) : if ( method == 'zeros' ) : if verbose : print ( "Initializing free energies to zero." ) self . f_k [ : ] = 0.0 elif ( method == 'mean-reduced-potential' ) : if verbose : print ( "Initializing free energies with mean reduced potential for each s...
Compute an initial guess at the relative free energies .
31,039
def _amIdoneIterating ( self , f_k_new , relative_tolerance , iteration , maximum_iterations , print_warning , verbose ) : yesIam = False Delta_f_k = f_k_new - self . f_k [ self . states_with_samples ] max_delta = np . max ( np . abs ( Delta_f_k ) / np . max ( np . abs ( f_k_new ) ) ) f_k = f_k_new . copy ( ) self . f_...
Convenience function to test whether we are done iterating same for all iteration types
31,040
def _selfConsistentIteration ( self , relative_tolerance = 1.0e-6 , maximum_iterations = 1000 , verbose = True , print_warning = False ) : if verbose : print ( "MBAR: Computing dimensionless free energies by iteration. This may take from seconds to minutes, depending on the quantity of data..." ) for iteration in rang...
Determine free energies by self - consistent iteration .
31,041
def _pseudoinverse ( self , A , tol = 1.0e-10 ) : return np . linalg . pinv ( A , rcond = tol )
Compute the Moore - Penrose pseudoinverse wraps np . linalg . pinv
31,042
def validate_inputs ( u_kn , N_k , f_k ) : n_states , n_samples = u_kn . shape u_kn = ensure_type ( u_kn , 'float' , 2 , "u_kn or Q_kn" , shape = ( n_states , n_samples ) ) N_k = ensure_type ( N_k , 'float' , 1 , "N_k" , shape = ( n_states , ) , warn_on_cast = False ) f_k = ensure_type ( f_k , 'float' , 1 , "f_k" , sha...
Check types and return inputs for MBAR calculations .
31,043
def self_consistent_update ( u_kn , N_k , f_k ) : u_kn , N_k , f_k = validate_inputs ( u_kn , N_k , f_k ) states_with_samples = ( N_k > 0 ) log_denominator_n = logsumexp ( f_k [ states_with_samples ] - u_kn [ states_with_samples ] . T , b = N_k [ states_with_samples ] , axis = 1 ) return - 1. * logsumexp ( - log_denomi...
Return an improved guess for the dimensionless free energies
31,044
def mbar_gradient ( u_kn , N_k , f_k ) : u_kn , N_k , f_k = validate_inputs ( u_kn , N_k , f_k ) log_denominator_n = logsumexp ( f_k - u_kn . T , b = N_k , axis = 1 ) log_numerator_k = logsumexp ( - log_denominator_n - u_kn , axis = 1 ) return - 1 * N_k * ( 1.0 - np . exp ( f_k + log_numerator_k ) )
Gradient of MBAR objective function .
31,045
def mbar_objective_and_gradient ( u_kn , N_k , f_k ) : u_kn , N_k , f_k = validate_inputs ( u_kn , N_k , f_k ) log_denominator_n = logsumexp ( f_k - u_kn . T , b = N_k , axis = 1 ) log_numerator_k = logsumexp ( - log_denominator_n - u_kn , axis = 1 ) grad = - 1 * N_k * ( 1.0 - np . exp ( f_k + log_numerator_k ) ) obj =...
Calculates both objective function and gradient for MBAR .
31,046
def mbar_hessian ( u_kn , N_k , f_k ) : u_kn , N_k , f_k = validate_inputs ( u_kn , N_k , f_k ) W = mbar_W_nk ( u_kn , N_k , f_k ) H = W . T . dot ( W ) H *= N_k H *= N_k [ : , np . newaxis ] H -= np . diag ( W . sum ( 0 ) * N_k ) return - 1.0 * H
Hessian of MBAR objective function .
31,047
def mbar_log_W_nk ( u_kn , N_k , f_k ) : u_kn , N_k , f_k = validate_inputs ( u_kn , N_k , f_k ) log_denominator_n = logsumexp ( f_k - u_kn . T , b = N_k , axis = 1 ) logW = f_k - u_kn . T - log_denominator_n [ : , np . newaxis ] return logW
Calculate the log weight matrix .
31,048
def mbar_W_nk ( u_kn , N_k , f_k ) : return np . exp ( mbar_log_W_nk ( u_kn , N_k , f_k ) )
Calculate the weight matrix .
31,049
def precondition_u_kn ( u_kn , N_k , f_k ) : u_kn , N_k , f_k = validate_inputs ( u_kn , N_k , f_k ) u_kn = u_kn - u_kn . min ( 0 ) u_kn += ( logsumexp ( f_k - u_kn . T , b = N_k , axis = 1 ) ) - N_k . dot ( f_k ) / float ( N_k . sum ( ) ) return u_kn
Subtract a sample - dependent constant from u_kn to improve precision
31,050
def solve_mbar_once ( u_kn_nonzero , N_k_nonzero , f_k_nonzero , method = "hybr" , tol = 1E-12 , options = None ) : u_kn_nonzero , N_k_nonzero , f_k_nonzero = validate_inputs ( u_kn_nonzero , N_k_nonzero , f_k_nonzero ) f_k_nonzero = f_k_nonzero - f_k_nonzero [ 0 ] u_kn_nonzero = precondition_u_kn ( u_kn_nonzero , N_k_...
Solve MBAR self - consistent equations using some form of equation solver .
31,051
def solve_mbar ( u_kn_nonzero , N_k_nonzero , f_k_nonzero , solver_protocol = None ) : if solver_protocol is None : solver_protocol = DEFAULT_SOLVER_PROTOCOL for protocol in solver_protocol : if protocol [ 'method' ] is None : protocol [ 'method' ] = DEFAULT_SOLVER_METHOD all_results = [ ] for k , options in enumerate ...
Solve MBAR self - consistent equations using some sequence of equation solvers .
31,052
def solve_mbar_for_all_states ( u_kn , N_k , f_k , solver_protocol ) : states_with_samples = np . where ( N_k > 0 ) [ 0 ] if len ( states_with_samples ) == 1 : f_k_nonzero = np . array ( [ 0.0 ] ) else : f_k_nonzero , all_results = solve_mbar ( u_kn [ states_with_samples ] , N_k [ states_with_samples ] , f_k [ states_w...
Solve for free energies of states with samples then calculate for empty states .
31,053
def construct_nonuniform_bins ( x_n , nbins ) : N = x_n . size sorted_indices = x_n . argsort ( ) bin_left_boundary_i = zeros ( [ nbins + 1 ] , float64 ) bin_right_boundary_i = zeros ( [ nbins + 1 ] , float64 ) bin_center_i = zeros ( [ nbins ] , float64 ) bin_width_i = zeros ( [ nbins ] , float64 ) bin_n = zeros ( [ N ...
Construct histogram using bins of unequal size to ensure approximately equal population in each bin .
31,054
def integratedAutocorrelationTime ( A_n , B_n = None , fast = False , mintime = 3 ) : g = statisticalInefficiency ( A_n , B_n , fast , mintime ) tau = ( g - 1.0 ) / 2.0 return tau
Estimate the integrated autocorrelation time .
31,055
def integratedAutocorrelationTimeMultiple ( A_kn , fast = False ) : g = statisticalInefficiencyMultiple ( A_kn , fast , False ) tau = ( g - 1.0 ) / 2.0 return tau
Estimate the integrated autocorrelation time from multiple timeseries .
31,056
def subsampleCorrelatedData ( A_t , g = None , fast = False , conservative = False , verbose = False ) : A_t = np . array ( A_t ) T = A_t . size if not g : if verbose : print ( "Computing statistical inefficiency..." ) g = statisticalInefficiency ( A_t , A_t , fast = fast ) if verbose : print ( "g = %f" % g ) if conser...
Determine the indices of an uncorrelated subsample of the data .
31,057
def BARzero ( w_F , w_R , DeltaF ) : np . seterr ( over = 'raise' ) w_F = np . array ( w_F , np . float64 ) w_R = np . array ( w_R , np . float64 ) DeltaF = float ( DeltaF ) T_F = float ( w_F . size ) T_R = float ( w_R . size ) M = np . log ( T_F / T_R ) exp_arg_F = ( M + w_F - DeltaF ) max_arg_F = np . choose ( np . l...
A function that when zeroed is equivalent to the solution of the Bennett acceptance ratio .
31,058
def kln_to_kn ( kln , N_k = None , cleanup = False ) : [ K , L , N_max ] = np . shape ( kln ) if N_k is None : N_k = N_max * np . ones ( [ L ] , dtype = np . int64 ) N = np . sum ( N_k ) kn = np . zeros ( [ L , N ] , dtype = np . float64 ) i = 0 for k in range ( K ) : for ik in range ( N_k [ k ] ) : kn [ : , i ] = kln ...
Convert KxKxN_max array to KxN max array
31,059
def kn_to_n ( kn , N_k = None , cleanup = False ) : [ K , N_max ] = np . shape ( kn ) if N_k is None : N_k = N_max * np . ones ( [ K ] , dtype = np . int64 ) N = np . sum ( N_k ) n = np . zeros ( [ N ] , dtype = np . float64 ) i = 0 for k in range ( K ) : for ik in range ( N_k [ k ] ) : n [ i ] = kn [ k , ik ] i += 1 i...
Convert KxN_max array to N array
31,060
def ensure_type ( val , dtype , ndim , name , length = None , can_be_none = False , shape = None , warn_on_cast = True , add_newaxis_on_deficient_ndim = False ) : if can_be_none and val is None : return None if not isinstance ( val , np . ndarray ) : if add_newaxis_on_deficient_ndim and ndim == 1 and np . isscalar ( va...
Typecheck the size shape and dtype of a numpy array with optional casting .
31,061
def logsumexp ( a , axis = None , b = None , use_numexpr = True ) : a = np . asarray ( a ) a_max = np . amax ( a , axis = axis , keepdims = True ) if a_max . ndim > 0 : a_max [ ~ np . isfinite ( a_max ) ] = 0 elif not np . isfinite ( a_max ) : a_max = 0 if b is not None : b = np . asarray ( b ) if use_numexpr and HAVE_...
Compute the log of the sum of exponentials of input elements .
31,062
def check_w_normalized ( W , N_k , tolerance = 1.0e-4 ) : [ N , K ] = W . shape column_sums = np . sum ( W , axis = 0 ) badcolumns = ( np . abs ( column_sums - 1 ) > tolerance ) if np . any ( badcolumns ) : which_badcolumns = np . arange ( K ) [ badcolumns ] firstbad = which_badcolumns [ 0 ] raise ParameterError ( 'War...
Check the weight matrix W is properly normalized . The sum over N should be 1 and the sum over k by N_k should aslo be 1
31,063
def configuration_callback ( cmd_name , option_name , config_file_name , saved_callback , provider , implicit , ctx , param , value ) : ctx . default_map = ctx . default_map or { } cmd_name = cmd_name or ctx . info_name if implicit : default_value = os . path . join ( click . get_app_dir ( cmd_name ) , config_file_name...
Callback for reading the config file .
31,064
def configuration_option ( * param_decls , ** attrs ) : param_decls = param_decls or ( '--config' , ) option_name = param_decls [ 0 ] def decorator ( f ) : attrs . setdefault ( 'is_eager' , True ) attrs . setdefault ( 'help' , 'Read configuration from FILE.' ) attrs . setdefault ( 'expose_value' , False ) implicit = at...
Adds configuration file support to a click application .
31,065
def decode_value ( stream ) : length = decode_length ( stream ) ( value , ) = unpack_value ( ">{:d}s" . format ( length ) , stream ) return value
Decode the contents of a value from a serialized stream .
31,066
def decode_tag ( stream ) : ( reserved , tag ) = unpack_value ( ">cc" , stream ) if reserved != b"\x00" : raise DeserializationError ( "Invalid tag: reserved byte is not null" ) return tag
Decode a tag value from a serialized stream .
31,067
def read ( * args ) : return io . open ( os . path . join ( HERE , * args ) , encoding = "utf-8" ) . read ( )
Reads complete file contents .
31,068
def sign_item ( encrypted_item , signing_key , crypto_config ) : signature = signing_key . sign ( algorithm = signing_key . algorithm , data = _string_to_sign ( item = encrypted_item , table_name = crypto_config . encryption_context . table_name , attribute_actions = crypto_config . attribute_actions , ) , ) return { T...
Generate the signature DynamoDB atttribute .
31,069
def verify_item_signature ( signature_attribute , encrypted_item , verification_key , crypto_config ) : signature = signature_attribute [ Tag . BINARY . dynamodb_tag ] verification_key . verify ( algorithm = verification_key . algorithm , signature = signature , data = _string_to_sign ( item = encrypted_item , table_na...
Verify the item signature .
31,070
def _string_to_sign ( item , table_name , attribute_actions ) : hasher = hashes . Hash ( hashes . SHA256 ( ) , backend = default_backend ( ) ) data_to_sign = bytearray ( ) data_to_sign . extend ( _hash_data ( hasher = hasher , data = "TABLE>{}<TABLE" . format ( table_name ) . encode ( TEXT_ENCODING ) ) ) for key in sor...
Generate the string to sign from an encrypted item and configuration .
31,071
def _hash_data ( hasher , data ) : _hasher = hasher . copy ( ) _hasher . update ( data ) return _hasher . finalize ( )
Generate hash of data using provided hash type .
31,072
def serialize ( material_description ) : material_description_bytes = bytearray ( _MATERIAL_DESCRIPTION_VERSION ) for name , value in sorted ( material_description . items ( ) , key = lambda x : x [ 0 ] ) : try : material_description_bytes . extend ( encode_value ( to_bytes ( name ) ) ) material_description_bytes . ext...
Serialize a material description dictionary into a DynamodDB attribute .
31,073
def deserialize ( serialized_material_description ) : try : _raw_material_description = serialized_material_description [ Tag . BINARY . dynamodb_tag ] material_description_bytes = io . BytesIO ( _raw_material_description ) total_bytes = len ( _raw_material_description ) except ( TypeError , KeyError ) : message = "Inv...
Deserialize a serialized material description attribute into a material description dictionary .
31,074
def _read_version ( material_description_bytes ) : try : ( version , ) = unpack_value ( ">4s" , material_description_bytes ) except struct . error : message = "Malformed material description version" _LOGGER . exception ( message ) raise InvalidMaterialDescriptionError ( message ) if version != _MATERIAL_DESCRIPTION_VE...
Read the version from the serialized material description and raise an error if it is unknown .
31,075
def encrypt_dynamodb_item ( item , crypto_config ) : if crypto_config . attribute_actions . take_no_actions : return item . copy ( ) for reserved_name in ReservedAttributes : if reserved_name . value in item : raise EncryptionError ( 'Reserved attribute name "{}" is not allowed in plaintext item.' . format ( reserved_n...
Encrypt a DynamoDB item .
31,076
def encrypt_python_item ( item , crypto_config ) : ddb_item = dict_to_ddb ( item ) encrypted_ddb_item = encrypt_dynamodb_item ( ddb_item , crypto_config ) return ddb_to_dict ( encrypted_ddb_item )
Encrypt a dictionary for DynamoDB .
31,077
def decrypt_dynamodb_item ( item , crypto_config ) : unique_actions = set ( [ crypto_config . attribute_actions . default_action . name ] ) unique_actions . update ( set ( [ action . name for action in crypto_config . attribute_actions . attribute_actions . values ( ) ] ) ) if crypto_config . attribute_actions . take_n...
Decrypt a DynamoDB item .
31,078
def decrypt_python_item ( item , crypto_config ) : ddb_item = dict_to_ddb ( item ) decrypted_ddb_item = decrypt_dynamodb_item ( ddb_item , crypto_config ) return ddb_to_dict ( decrypted_ddb_item )
Decrypt a dictionary for DynamoDB .
31,079
def dict_to_ddb ( item ) : serializer = TypeSerializer ( ) return { key : serializer . serialize ( value ) for key , value in item . items ( ) }
Converts a native Python dictionary to a raw DynamoDB item .
31,080
def ddb_to_dict ( item ) : deserializer = TypeDeserializer ( ) return { key : deserializer . deserialize ( value ) for key , value in item . items ( ) }
Converts a raw DynamoDB item to a native Python dictionary .
31,081
def dictionary_validator ( key_type , value_type ) : def _validate_dictionary ( instance , attribute , value ) : if not isinstance ( value , dict ) : raise TypeError ( '"{}" must be a dictionary' . format ( attribute . name ) ) for key , data in value . items ( ) : if not isinstance ( key , key_type ) : raise TypeError...
Validator for attrs that performs deep type checking of dictionaries .
31,082
def iterable_validator ( iterable_type , member_type ) : def _validate_tuple ( instance , attribute , value ) : if not isinstance ( value , iterable_type ) : raise TypeError ( '"{name}" must be a {type}' . format ( name = attribute . name , type = iterable_type ) ) for member in value : if not isinstance ( member , mem...
Validator for attrs that performs deep type checking of iterables .
31,083
def callable_validator ( instance , attribute , value ) : if not callable ( value ) : raise TypeError ( '"{name}" value "{value}" must be callable' . format ( name = attribute . name , value = value ) )
Validate that an attribute value is callable .
31,084
def encrypt_attribute ( attribute_name , attribute , encryption_key , algorithm ) : serialized_attribute = serialize_attribute ( attribute ) encrypted_attribute = encryption_key . encrypt ( algorithm = algorithm , name = attribute_name , plaintext = serialized_attribute ) return { Tag . BINARY . dynamodb_tag : encrypte...
Encrypt a single DynamoDB attribute .
31,085
def decrypt_attribute ( attribute_name , attribute , decryption_key , algorithm ) : encrypted_attribute = attribute [ Tag . BINARY . dynamodb_tag ] decrypted_attribute = decryption_key . decrypt ( algorithm = algorithm , name = attribute_name , ciphertext = encrypted_attribute ) return deserialize_attribute ( decrypted...
Decrypt a single DynamoDB attribute .
31,086
def _generate_rsa_key ( key_length ) : private_key = rsa . generate_private_key ( public_exponent = 65537 , key_size = key_length , backend = default_backend ( ) ) key_bytes = private_key . private_bytes ( encoding = serialization . Encoding . DER , format = serialization . PrivateFormat . PKCS8 , encryption_algorithm ...
Generate a new RSA private key .
31,087
def encode_value ( value ) : return struct . pack ( ">I{attr_len:d}s" . format ( attr_len = len ( value ) ) , len ( value ) , value )
Encodes the value in Length - Value format .
31,088
def encrypt_item ( table_name , aws_cmk_id ) : index_key = { "partition_attribute" : { "S" : "is this" } , "sort_attribute" : { "N" : "55" } } plaintext_item = { "example" : { "S" : "data" } , "some numbers" : { "N" : "99" } , "and some binary" : { "B" : b"\x00\x01\x02" } , "leave me" : { "S" : "alone" } , } encrypted_...
Demonstrate use of EncryptedClient to transparently encrypt an item .
31,089
def encrypt_batch_items ( table_name , aws_cmk_id ) : index_keys = [ { "partition_attribute" : { "S" : "is this" } , "sort_attribute" : { "N" : "55" } } , { "partition_attribute" : { "S" : "is this" } , "sort_attribute" : { "N" : "56" } } , { "partition_attribute" : { "S" : "is this" } , "sort_attribute" : { "N" : "57"...
Demonstrate use of EncryptedClient to transparently encrypt multiple items in a batch request .
31,090
def load_rsa_key ( key , key_type , key_encoding ) : try : loader = _RSA_KEY_LOADING [ key_type ] [ key_encoding ] except KeyError : raise ValueError ( "Invalid key type and encoding: {} and {}" . format ( key_type , key_encoding ) ) kwargs = dict ( data = key , backend = default_backend ( ) ) if key_type is Encryption...
Load an RSA key object from the provided raw key bytes .
31,091
def _disable_encryption ( self ) : self . encrypt = self . _disabled_encrypt self . decrypt = self . _disabled_decrypt
Enable encryption methods for ciphers that support them .
31,092
def wrap ( self , wrapping_key , key_to_wrap ) : if self . java_name not in ( "AES" , "AESWrap" ) : raise NotImplementedError ( '"wrap" is not supported by the "{}" cipher' . format ( self . java_name ) ) try : return keywrap . aes_key_wrap ( wrapping_key = wrapping_key , key_to_wrap = key_to_wrap , backend = default_b...
Wrap key using AES keywrap .
31,093
def unwrap ( self , wrapping_key , wrapped_key ) : if self . java_name not in ( "AES" , "AESWrap" ) : raise NotImplementedError ( '"unwrap" is not supported by this cipher' ) try : return keywrap . aes_key_unwrap ( wrapping_key = wrapping_key , wrapped_key = wrapped_key , backend = default_backend ( ) ) except Exceptio...
Unwrap key using AES keywrap .
31,094
def _validate_attribute_values_are_ddb_items ( instance , attribute , value ) : for data in value . values ( ) : if len ( list ( data . values ( ) ) ) != 1 : raise TypeError ( '"{}" values do not look like DynamoDB items' . format ( attribute . name ) )
Validate that dictionary values in value match the structure of DynamoDB JSON items .
31,095
def validate_get_arguments ( kwargs ) : for arg in ( "AttributesToGet" , "ProjectionExpression" ) : if arg in kwargs : raise InvalidArgumentError ( '"{}" is not supported for this operation' . format ( arg ) ) if kwargs . get ( "Select" , None ) in ( "SPECIFIC_ATTRIBUTES" , "ALL_PROJECTED_ATTRIBUTES" ) : raise InvalidA...
Verify that attribute filtering parameters are not found in the request .
31,096
def crypto_config_from_kwargs ( fallback , ** kwargs ) : try : crypto_config = kwargs . pop ( "crypto_config" ) except KeyError : try : fallback_kwargs = { "table_name" : kwargs [ "TableName" ] } except KeyError : fallback_kwargs = { } crypto_config = fallback ( ** fallback_kwargs ) return crypto_config , kwargs
Pull all encryption - specific parameters from the request and use them to build a crypto config .
31,097
def crypto_config_from_table_info ( materials_provider , attribute_actions , table_info ) : ec_kwargs = table_info . encryption_context_values if table_info . primary_index is not None : ec_kwargs . update ( { "partition_key_name" : table_info . primary_index . partition , "sort_key_name" : table_info . primary_index ....
Build a crypto config from the provided values and table info .
31,098
def crypto_config_from_cache ( materials_provider , attribute_actions , table_info_cache , table_name ) : table_info = table_info_cache . table_info ( table_name ) attribute_actions = attribute_actions . copy ( ) attribute_actions . set_index_keys ( * table_info . protected_index_keys ( ) ) return crypto_config_from_ta...
Build a crypto config from the provided values loading the table info from the provided cache .
31,099
def decrypt_multi_get ( decrypt_method , crypto_config_method , read_method , ** kwargs ) : validate_get_arguments ( kwargs ) crypto_config , ddb_kwargs = crypto_config_method ( ** kwargs ) response = read_method ( ** ddb_kwargs ) for pos in range ( len ( response [ "Items" ] ) ) : response [ "Items" ] [ pos ] = decryp...
Transparently decrypt multiple items after getting them from the table with a scan or query method .