idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
240,400 | def get_table_service_stats ( self , timeout = None ) : request = HTTPRequest ( ) request . method = 'GET' request . host_locations = self . _get_host_locations ( primary = False , secondary = True ) request . path = '/' request . query = { 'restype' : 'service' , 'comp' : 'stats' , 'timeout' : _int_to_str ( timeout ) ... | Retrieves statistics related to replication for the Table service . It is only available when read - access geo - redundant replication is enabled for the storage account . |
240,401 | def get_table_service_properties ( self , timeout = None ) : request = HTTPRequest ( ) request . method = 'GET' request . host_locations = self . _get_host_locations ( secondary = True ) request . path = '/' request . query = { 'restype' : 'service' , 'comp' : 'properties' , 'timeout' : _int_to_str ( timeout ) , } retu... | Gets the properties of a storage account s Table service including logging analytics and CORS rules . |
240,402 | def delete_table ( self , table_name , fail_not_exist = False , timeout = None ) : _validate_not_none ( 'table_name' , table_name ) request = HTTPRequest ( ) request . method = 'DELETE' request . host_locations = self . _get_host_locations ( ) request . path = '/Tables(\'' + _to_str ( table_name ) + '\')' request . que... | Deletes the specified table and any data it contains . |
240,403 | def query_entities ( self , table_name , filter = None , select = None , num_results = None , marker = None , accept = TablePayloadFormat . JSON_MINIMAL_METADATA , property_resolver = None , timeout = None ) : operation_context = _OperationContext ( location_lock = True ) if self . key_encryption_key is not None or sel... | Returns a generator to list the entities in the table specified . The generator will lazily follow the continuation tokens returned by the service and stop when all entities have been returned or num_results is reached . |
240,404 | def merge_entity ( self , table_name , entity , if_match = '*' , timeout = None ) : _validate_not_none ( 'table_name' , table_name ) request = _merge_entity ( entity , if_match , self . require_encryption , self . key_encryption_key ) request . host_locations = self . _get_host_locations ( ) request . query [ 'timeout'... | Updates an existing entity by merging the entity s properties . Throws if the entity does not exist . This operation does not replace the existing entity as the update_entity operation does . A property cannot be removed with merge_entity . Any properties with null values are ignored . All other properties will be upda... |
240,405 | def create_entity_class ( self ) : entity = Entity ( ) entity . PartitionKey = 'pk{}' . format ( str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) ) entity . RowKey = 'rk{}' . format ( str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) ) entity . age = 39 entity . large = 933311100 entity . sex = 'male' entity . married = T... | Creates a class - based entity with fixed values using all of the supported data types . |
240,406 | def create_entity_dict ( self ) : entity = { } entity [ 'PartitionKey' ] = 'pk{}' . format ( str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) ) entity [ 'RowKey' ] = 'rk{}' . format ( str ( uuid . uuid4 ( ) ) . replace ( '-' , '' ) ) entity [ 'age' ] = 39 entity [ 'large' ] = 933311100 entity [ 'sex' ] = 'male' entity [... | Creates a dict - based entity with fixed values using all of the supported data types . |
240,407 | def _convert_batch_to_json ( batch_requests ) : batch_boundary = b'batch_' + _new_boundary ( ) changeset_boundary = b'changeset_' + _new_boundary ( ) body = [ b'--' + batch_boundary + b'\n' , b'Content-Type: multipart/mixed; boundary=' , changeset_boundary + b'\n\n' ] content_id = 1 for _ , request in batch_requests : ... | Create json to send for an array of batch requests . |
240,408 | def _decrypt_entity ( entity , encrypted_properties_list , content_encryption_key , entityIV , isJavaV1 ) : _validate_not_none ( 'entity' , entity ) decrypted_entity = deepcopy ( entity ) try : for property in entity . keys ( ) : if property in encrypted_properties_list : value = entity [ property ] propertyIV = _gener... | Decrypts the specified entity using AES256 in CBC mode with 128 bit padding . Unwraps the CEK using either the specified KEK or the key returned by the key_resolver . Properties specified in the encrypted_properties_list will be decrypted and decoded to utf - 8 strings . |
240,409 | def _generate_property_iv ( entity_iv , pk , rk , property_name , isJavaV1 ) : digest = Hash ( SHA256 ( ) , default_backend ( ) ) if not isJavaV1 : digest . update ( entity_iv + ( rk + pk + property_name ) . encode ( 'utf-8' ) ) else : digest . update ( entity_iv + ( pk + rk + property_name ) . encode ( 'utf-8' ) ) pro... | Uses the entity_iv partition key and row key to generate and return the iv for the specified property . |
240,410 | def _get_default_mapping ( self , obj ) : mapping = { v : k for k , v in obj . TYPE_MAPPING . items ( ) } mapping . update ( { fields . Email : text_type , fields . Dict : dict , fields . Url : text_type , fields . List : list , fields . LocalDateTime : datetime . datetime , fields . Nested : '_from_nested_schema' , } ... | Return default mapping if there are no special needs . |
240,411 | def get_properties ( self , obj ) : properties = { } for field_name , field in sorted ( obj . fields . items ( ) ) : schema = self . _get_schema_for_field ( obj , field ) properties [ field . name ] = schema return properties | Fill out properties field . |
240,412 | def get_required ( self , obj ) : required = [ ] for field_name , field in sorted ( obj . fields . items ( ) ) : if field . required : required . append ( field . name ) return required or missing | Fill out required field . |
240,413 | def _from_python_type ( self , obj , field , pytype ) : json_schema = { 'title' : field . attribute or field . name , } for key , val in TYPE_MAP [ pytype ] . items ( ) : json_schema [ key ] = val if field . dump_only : json_schema [ 'readonly' ] = True if field . default is not missing : json_schema [ 'default' ] = fi... | Get schema definition from python type . |
240,414 | def _get_schema_for_field ( self , obj , field ) : mapping = self . _get_default_mapping ( obj ) if hasattr ( field , '_jsonschema_type_mapping' ) : schema = field . _jsonschema_type_mapping ( ) elif '_jsonschema_type_mapping' in field . metadata : schema = field . metadata [ '_jsonschema_type_mapping' ] elif field . _... | Get schema and validators for field . |
240,415 | def _from_nested_schema ( self , obj , field ) : if isinstance ( field . nested , basestring ) : nested = get_class ( field . nested ) else : nested = field . nested name = nested . __name__ outer_name = obj . __class__ . __name__ only = field . only exclude = field . exclude if name not in self . _nested_schema_classe... | Support nested field . |
240,416 | def wrap ( self , data ) : if self . nested : return data name = self . obj . __class__ . __name__ self . _nested_schema_classes [ name ] = data root = { 'definitions' : self . _nested_schema_classes , '$ref' : '#/definitions/{name}' . format ( name = name ) } return root | Wrap this with the root schema definitions . |
240,417 | def handle_length ( schema , field , validator , parent_schema ) : if isinstance ( field , fields . String ) : minKey = 'minLength' maxKey = 'maxLength' elif isinstance ( field , ( fields . List , fields . Nested ) ) : minKey = 'minItems' maxKey = 'maxItems' else : raise ValueError ( "In order to set the Length validat... | Adds validation logic for marshmallow . validate . Length setting the values appropriately for fields . List fields . Nested and fields . String . |
240,418 | def handle_one_of ( schema , field , validator , parent_schema ) : if validator . choices : schema [ 'enum' ] = list ( validator . choices ) schema [ 'enumNames' ] = list ( validator . labels ) return schema | Adds the validation logic for marshmallow . validate . OneOf by setting the JSONSchema enum property to the allowed choices in the validator . |
240,419 | def handle_range ( schema , field , validator , parent_schema ) : if not isinstance ( field , fields . Number ) : return schema if validator . min : schema [ 'minimum' ] = validator . min schema [ 'exclusiveMinimum' ] = True else : schema [ 'minimum' ] = 0 schema [ 'exclusiveMinimum' ] = False if validator . max : sche... | Adds validation logic for marshmallow . validate . Range setting the values appropriately fields . Number and it s subclasses . |
240,420 | def check_eigen_solver ( eigen_solver , solver_kwds , size = None , nvec = None ) : if eigen_solver in BAD_EIGEN_SOLVERS : raise ValueError ( BAD_EIGEN_SOLVERS [ eigen_solver ] ) elif eigen_solver not in EIGEN_SOLVERS : raise ValueError ( "Unrecognized eigen_solver: '{0}'." "Should be one of: {1}" . format ( eigen_solv... | Check that the selected eigensolver is valid |
240,421 | def precompute_optimzation_Y ( laplacian_matrix , n_samples , relaxation_kwds ) : relaxation_kwds . setdefault ( 'presave' , False ) relaxation_kwds . setdefault ( 'presave_name' , 'pre_comp_current.npy' ) relaxation_kwds . setdefault ( 'verbose' , False ) if relaxation_kwds [ 'verbose' ] : print ( 'Making Lk and nbhds... | compute Lk neighbors and subset to index map for projected == False |
240,422 | def compute_Lk ( laplacian_matrix , n_samples , subset ) : Lk_tensor = [ ] nbk = [ ] row , column = laplacian_matrix . T . nonzero ( ) nnz_val = np . squeeze ( np . asarray ( laplacian_matrix . T [ ( row , column ) ] ) ) sorted_col_args = np . argsort ( column ) sorted_col_vals = column [ sorted_col_args ] breaks_row =... | Compute sparse L matrix neighbors and subset to L matrix index map . |
240,423 | def precompute_optimzation_S ( laplacian_matrix , n_samples , relaxation_kwds ) : relaxation_kwds . setdefault ( 'presave' , False ) relaxation_kwds . setdefault ( 'presave_name' , 'pre_comp_current.npy' ) relaxation_kwds . setdefault ( 'verbose' , False ) if relaxation_kwds [ 'verbose' ] : print ( 'Pre-computing quant... | compute Rk A ATAinv neighbors and pairs for projected mode |
240,424 | def compute_Rk ( L , A , n_samples ) : laplacian_matrix = L . copy ( ) laplacian_matrix . setdiag ( 0 ) laplacian_matrix . eliminate_zeros ( ) n = n_samples Rk_tensor = [ ] nbk = [ ] row_A , column_A = A . T . nonzero ( ) row , column = laplacian_matrix . nonzero ( ) nnz_val = np . squeeze ( np . asarray ( laplacian_ma... | Compute sparse L matrix and neighbors . |
240,425 | def _mod_info ( modname , toskip = [ ] , onlylocals = True ) : hascls = hasfunc = False for localnm , fqnm , obj in zip ( * find_mod_objs ( modname , onlylocals = onlylocals ) ) : if localnm not in toskip : hascls = hascls or inspect . isclass ( obj ) hasfunc = hasfunc or inspect . isroutine ( obj ) if hascls and hasfu... | Determines if a module is a module or a package and whether or not it has classes or functions . |
240,426 | def compute_affinity_matrix ( adjacency_matrix , method = 'auto' , ** kwargs ) : if method == 'auto' : method = 'gaussian' return Affinity . init ( method , ** kwargs ) . affinity_matrix ( adjacency_matrix ) | Compute the affinity matrix with the given method |
240,427 | def barycenter_graph ( distance_matrix , X , reg = 1e-3 ) : ( N , d_in ) = X . shape ( rows , cols ) = distance_matrix . nonzero ( ) W = sparse . lil_matrix ( ( N , N ) ) for i in range ( N ) : nbrs_i = cols [ rows == i ] n_neighbors_i = len ( nbrs_i ) v = np . ones ( n_neighbors_i , dtype = X . dtype ) C = X [ nbrs_i ... | Computes the barycenter weighted graph for points in X |
240,428 | def locally_linear_embedding ( geom , n_components , reg = 1e-3 , eigen_solver = 'auto' , random_state = None , solver_kwds = None ) : if geom . X is None : raise ValueError ( "Must pass data matrix X to Geometry" ) if geom . adjacency_matrix is None : geom . compute_adjacency_matrix ( ) W = barycenter_graph ( geom . a... | Perform a Locally Linear Embedding analysis on the data . |
240,429 | def _num_samples ( x ) : if hasattr ( x , 'fit' ) : raise TypeError ( 'Expected sequence or array-like, got ' 'estimator %s' % x ) if not hasattr ( x , '__len__' ) and not hasattr ( x , 'shape' ) : if hasattr ( x , '__array__' ) : x = np . asarray ( x ) else : raise TypeError ( "Expected sequence or array-like, got %s"... | Return number of samples in array - like x . |
240,430 | def spectral_clustering ( geom , K , eigen_solver = 'dense' , random_state = None , solver_kwds = None , renormalize = True , stabalize = True , additional_vectors = 0 ) : if geom . affinity_matrix is None : S = geom . compute_affinity_matrix ( ) else : S = geom . affinity_matrix if eigen_solver in [ 'lobpcg' , 'amg' ]... | Spectral clustering for find K clusters by using the eigenvectors of a matrix which is derived from a set of similarities S . |
240,431 | def pathpatch_2d_to_3d ( pathpatch , z = 0 , normal = 'z' ) : if type ( normal ) is str : index = "xyz" . index ( normal ) normal = np . roll ( ( 1.0 , 0 , 0 ) , index ) normal /= np . linalg . norm ( normal ) path = pathpatch . get_path ( ) trans = pathpatch . get_patch_transform ( ) path = trans . transform_path ( pa... | Transforms a 2D Patch to a 3D patch using the given normal vector . |
240,432 | def calc_2d_ellipse_properties ( cov , nstd = 2 ) : def eigsorted ( cov ) : vals , vecs = np . linalg . eigh ( cov ) order = vals . argsort ( ) [ : : - 1 ] return vals [ order ] , vecs [ : , order ] vals , vecs = eigsorted ( cov ) width , height = 2 * nstd * np . sqrt ( vals [ : 2 ] ) normal = vecs [ : , 2 ] if vecs [ ... | Calculate the properties for 2d ellipse given the covariance matrix . |
240,433 | def rotation_matrix ( d ) : sin_angle = np . linalg . norm ( d ) if sin_angle == 0 : return np . identity ( 3 ) d /= sin_angle eye = np . eye ( 3 ) ddt = np . outer ( d , d ) skew = np . array ( [ [ 0 , d [ 2 ] , - d [ 1 ] ] , [ - d [ 2 ] , 0 , d [ 0 ] ] , [ d [ 1 ] , - d [ 0 ] , 0 ] ] , dtype = np . float64 ) M = ddt ... | Calculates a rotation matrix given a vector d . The direction of d corresponds to the rotation axis . The length of d corresponds to the sin of the angle of rotation . |
240,434 | def create_ellipse ( width , height , angle ) : angle = angle / 180.0 * np . pi thetas = np . linspace ( 0 , 2 * np . pi , 200 ) a = width / 2.0 b = height / 2.0 x = a * np . cos ( thetas ) * np . cos ( angle ) - b * np . sin ( thetas ) * np . sin ( angle ) y = a * np . cos ( thetas ) * np . sin ( angle ) + b * np . si... | Create parametric ellipse from 200 points . |
240,435 | def transform_to_3d ( points , normal , z = 0 ) : d = np . cross ( normal , ( 0 , 0 , 1 ) ) M = rotation_matrix ( d ) transformed_points = M . dot ( points . T ) . T + z return transformed_points | Project points into 3d from 2d points . |
240,436 | def create_ellipse_mesh ( points , ** kwargs ) : import plotly . graph_objs as go x , y , z = points . T return ( go . Mesh3d ( x = x , y = y , z = z , ** kwargs ) , go . Scatter3d ( x = x , y = y , z = z , marker = dict ( size = 0.01 ) , line = dict ( width = 2 , color = '#000000' ) , showlegend = False , hoverinfo = ... | Visualize the ellipse by using the mesh of the points . |
240,437 | def ltsa ( geom , n_components , eigen_solver = 'auto' , random_state = None , solver_kwds = None ) : if geom . X is None : raise ValueError ( "Must pass data matrix X to Geometry" ) ( N , d_in ) = geom . X . shape if n_components > d_in : raise ValueError ( "output dimension must be less than or equal " "to input dime... | Perform a Local Tangent Space Alignment analysis on the data . |
240,438 | def run_riemannian_relaxation ( laplacian , initial_guess , intrinsic_dim , relaxation_kwds ) : n , s = initial_guess . shape relaxation_kwds = initialize_kwds ( relaxation_kwds , n , s , intrinsic_dim ) if relaxation_kwds [ 'save_init' ] : directory = relaxation_kwds [ 'backup_dir' ] np . save ( os . path . join ( dir... | Helper function for creating a RiemannianRelaxation class . |
240,439 | def relax_isometry ( self ) : for ii in range ( self . relaxation_kwds [ 'niter' ] ) : self . H = self . compute_dual_rmetric ( ) self . loss = self . rieman_loss ( ) self . trace_var . update ( ii , self . H , self . Y , self . eta , self . loss ) self . trace_var . print_report ( ii ) self . trace_var . save_backup (... | Main function for doing riemannian relaxation . |
240,440 | def calc_loss ( self , embedding ) : Hnew = self . compute_dual_rmetric ( Ynew = embedding ) return self . rieman_loss ( Hnew = Hnew ) | Helper function to calculate rieman loss given new embedding |
240,441 | def compute_dual_rmetric ( self , Ynew = None ) : usedY = self . Y if Ynew is None else Ynew rieman_metric = RiemannMetric ( usedY , self . laplacian_matrix ) return rieman_metric . get_dual_rmetric ( ) | Helper function to calculate the |
240,442 | def automodsumm_to_autosummary_lines ( fn , app ) : fullfn = os . path . join ( app . builder . env . srcdir , fn ) with open ( fullfn ) as fr : if 'astropy_helpers.sphinx.ext.automodapi' in app . _extensions : from astropy_helpers . sphinx . ext . automodapi import automodapi_replace docname = os . path . splitext ( f... | Generates lines from a file with an automodsumm entry suitable for feeding into autosummary . |
240,443 | def compute_adjacency_matrix ( X , method = 'auto' , ** kwargs ) : if method == 'auto' : if X . shape [ 0 ] > 10000 : method = 'cyflann' else : method = 'kd_tree' return Adjacency . init ( method , ** kwargs ) . adjacency_graph ( X . astype ( 'float' ) ) | Compute an adjacency matrix with the given method |
240,444 | def split_kwargs ( relaxation_kwds ) : optimizer_keys_list = [ 'step_method' , 'linesearch' , 'eta_max' , 'eta' , 'm' , 'linesearch_first' ] optimizer_kwargs = { k : relaxation_kwds . pop ( k ) for k in optimizer_keys_list if k in relaxation_kwds } if 'm' in optimizer_kwargs : optimizer_kwargs [ 'momentum' ] = optimize... | Split relaxation keywords to keywords for optimizer and others |
240,445 | def initialize_kwds ( relaxation_kwds , n_samples , n_components , intrinsic_dim ) : new_relaxation_kwds = { 'weights' : np . array ( [ ] , dtype = np . float64 ) , 'step_method' : 'fixed' , 'linesearch' : True , 'verbose' : False , 'niter' : 2000 , 'niter_trace' : 0 , 'presave' : False , 'sqrd' : True , 'alpha' : 0 , ... | Initialize relaxation keywords . |
240,446 | def _graph_connected_component ( graph , node_id ) : connected_components = np . zeros ( shape = ( graph . shape [ 0 ] ) , dtype = np . bool ) connected_components [ node_id ] = True n_node = graph . shape [ 0 ] for i in range ( n_node ) : last_num_component = connected_components . sum ( ) _ , node_to_add = np . where... | Find the largest graph connected components the contains one given node |
240,447 | def predict ( self , X_test , y = None ) : if not hasattr ( self , 'geom_' ) : raise RuntimeError ( 'the .fit() function must be called before the .predict() function' ) if self . geom_ . X is None : raise NotImplementedError ( 'method only implemented when X passed as data' ) adjacency_kwds = self . geom_ . adjacency_... | Predict embedding on new data X_test given the existing embedding on training data |
240,448 | def compute_laplacian_matrix ( affinity_matrix , method = 'auto' , ** kwargs ) : if method == 'auto' : method = 'geometric' return Laplacian . init ( method , ** kwargs ) . laplacian_matrix ( affinity_matrix ) | Compute the laplacian matrix with the given method |
240,449 | def fit_geometry ( self , X = None , input_type = 'data' ) : if self . geom is None : self . geom_ = Geometry ( ) elif isinstance ( self . geom , Geometry ) : self . geom_ = self . geom else : try : kwds = dict ( ** self . geom ) except TypeError : raise ValueError ( "geom must be a Geometry instance or " "a mappable/d... | Inputs self . geom and produces the fitted geometry self . geom_ |
240,450 | def set_radius ( self , radius , override = True , X = None , n_components = 2 ) : if radius < 0 : raise ValueError ( "radius must be non-negative" ) if override or ( 'radius' not in self . adjacency_kwds and 'n_neighbors' not in self . adjacency_kwds ) : self . adjacency_kwds [ 'radius' ] = radius if override or ( 'ra... | Set the radius for the adjacency and affinity computation |
240,451 | def get_rmetric ( self , mode_inv = 'svd' , return_svd = False ) : if self . H is None : self . H , self . G , self . Hvv , self . Hsval = riemann_metric ( self . Y , self . L , self . mdimG , invert_h = True , mode_inv = mode_inv ) if self . G is None : self . G , self . Hvv , self . Hsvals , self . Gsvals = compute_G... | Compute the Reimannian Metric |
240,452 | def report_and_save_keywords ( self , relaxation_kwds , precomputed_kwds ) : report_name = os . path . join ( self . backup_dir , 'relaxation_keywords.txt' ) pretty_relax_kwds = pprint . pformat ( relaxation_kwds , indent = 4 ) with open ( report_name , 'w' ) as wf : wf . write ( pretty_relax_kwds ) wf . close ( ) orig... | Save relaxation keywords to . txt and . pyc file |
240,453 | def update ( self , iiter , H , Y , eta , loss ) : if iiter <= self . niter_trace + 1 : self . H [ iiter ] = H self . Y [ iiter ] = Y elif iiter > self . niter - self . niter_trace + 1 : self . H [ self . ltrace + iiter - self . niter - 1 ] = H self . Y [ self . ltrace + iiter - self . niter - 1 ] = Y self . etas [ iit... | Update the trace_var in new iteration |
240,454 | def save ( cls , instance , filename ) : filename = cls . correct_file_extension ( filename ) try : with open ( filename , 'wb' ) as f : pickle . dump ( instance , f , protocol = pickle . HIGHEST_PROTOCOL ) except MemoryError as e : print ( '{} occurred, will downsampled the saved file by 20.' . format ( type ( e ) . _... | Class method save for saving TracingVariable . |
240,455 | def load ( cls , filename ) : filename = cls . correct_file_extension ( filename ) with open ( filename , 'rb' ) as f : return pickle . load ( f ) | Load from stored files |
240,456 | def find_mod_objs ( modname , onlylocals = False ) : __import__ ( modname ) mod = sys . modules [ modname ] if hasattr ( mod , '__all__' ) : pkgitems = [ ( k , mod . __dict__ [ k ] ) for k in mod . __all__ ] else : pkgitems = [ ( k , mod . __dict__ [ k ] ) for k in dir ( mod ) if k [ 0 ] != '_' ] ismodule = inspect . i... | Returns all the public attributes of a module referenced by name . |
240,457 | def get_megaman_image ( factor = 1 ) : imfile = os . path . join ( os . path . dirname ( __file__ ) , 'megaman.png' ) data = ndimage . imread ( imfile ) / 255 if factor > 1 : data = data . repeat ( factor , axis = 0 ) . repeat ( factor , axis = 1 ) return data | Return an RGBA representation of the megaman icon |
240,458 | def generate_megaman_data ( sampling = 2 ) : data = get_megaman_image ( ) x = np . arange ( sampling * data . shape [ 1 ] ) / float ( sampling ) y = np . arange ( sampling * data . shape [ 0 ] ) / float ( sampling ) X , Y = map ( np . ravel , np . meshgrid ( x , y ) ) C = data [ np . floor ( Y . max ( ) - Y ) . astype ... | Generate 2D point data of the megaman image |
240,459 | def _make_S_curve ( x , range = ( - 0.75 , 0.75 ) ) : assert x . ndim == 1 x = x - x . min ( ) theta = 2 * np . pi * ( range [ 0 ] + ( range [ 1 ] - range [ 0 ] ) * x / x . max ( ) ) X = np . empty ( ( x . shape [ 0 ] , 2 ) , dtype = float ) X [ : , 0 ] = np . sign ( theta ) * ( 1 - np . cos ( theta ) ) X [ : , 1 ] = n... | Make a 2D S - curve from a 1D vector |
240,460 | def generate_megaman_manifold ( sampling = 2 , nfolds = 2 , rotate = True , random_state = None ) : X , c = generate_megaman_data ( sampling ) for i in range ( nfolds ) : X = np . hstack ( [ _make_S_curve ( x ) for x in X . T ] ) if rotate : rand = check_random_state ( random_state ) R = rand . randn ( X . shape [ 1 ] ... | Generate a manifold of the megaman data |
240,461 | def snapshots_to_send ( source_snaps , dest_snaps ) : if len ( source_snaps ) == 0 : raise AssertionError ( "No snapshots exist locally!" ) if len ( dest_snaps ) == 0 : return None , source_snaps [ - 1 ] last_remote = dest_snaps [ - 1 ] for snap in reversed ( source_snaps ) : if snap == last_remote : return last_remote... | return pair of snapshots |
240,462 | def get_chunk ( self ) : while not self . _eof_reached : read = self . input_stream . read ( self . chunk_size - len ( self . _partial_chunk ) ) if len ( read ) == 0 : self . _eof_reached = True self . _partial_chunk += read if len ( self . _partial_chunk ) == self . chunk_size or self . _eof_reached : chunk = self . _... | Return complete chunks or None if EOF reached |
240,463 | def _handle_result ( self ) : result = self . inbox . get ( ) if result . success : if self . _verbosity >= VERB_PROGRESS : sys . stderr . write ( "\nuploaded chunk {} \n" . format ( result . index ) ) self . results . append ( ( result . index , result . md5 ) ) self . _pending_chunks -= 1 else : raise result . traceb... | Process one result . Block untill one is available |
240,464 | def _send_chunk ( self , index , chunk ) : self . _pending_chunks += 1 self . outbox . put ( ( index , chunk ) ) | Send the current chunk to the workers for processing . Called when the _partial_chunk is complete . |
240,465 | def _get ( self , key , section = None , default = _onion_dict_guard ) : if section is not None : section_dict = self . __sections . get ( section , { } ) if key in section_dict : return section_dict [ key ] for d in self . __dictionaries : if key in d : return d [ key ] if default is _onion_dict_guard : raise KeyError... | Try to get the key from each dict in turn . If you specify the optional section it looks there first . |
240,466 | def _parse_snapshots ( self ) : try : snap = self . _list_snapshots ( ) except OSError as err : logging . error ( "unable to list local snapshots!" ) return { } vols = { } for line in snap . splitlines ( ) : if len ( line ) == 0 : continue name , used , refer , mountpoint , written = line . split ( '\t' ) vol_name , sn... | Returns all snapshots grouped by filesystem a dict of OrderedDict s The order of snapshots matters when determining parents for incremental send so it s preserved . Data is indexed by filesystem then for each filesystem we have an OrderedDict of snapshots . |
240,467 | def _compress ( self , cmd ) : compressor = COMPRESSORS . get ( self . compressor ) if compressor is None : return cmd compress_cmd = compressor [ 'compress' ] return "{} | {}" . format ( compress_cmd , cmd ) | Adds the appropriate command to compress the zfs stream |
240,468 | def _decompress ( self , cmd , s3_snap ) : compressor = COMPRESSORS . get ( s3_snap . compressor ) if compressor is None : return cmd decompress_cmd = compressor [ 'decompress' ] return "{} | {}" . format ( decompress_cmd , cmd ) | Adds the appropriate command to decompress the zfs stream This is determined from the metadata of the s3_snap . |
240,469 | def backup_full ( self , snap_name = None , dry_run = False ) : z_snap = self . _snapshot_to_backup ( snap_name ) estimated_size = self . _parse_estimated_size ( self . _cmd . shell ( "zfs send -nvP '{}'" . format ( z_snap . name ) , capture = True ) ) self . _cmd . pipe ( "zfs send '{}'" . format ( z_snap . name ) , s... | Do a full backup of a snapshot . By default latest local snapshot |
240,470 | def backup_incremental ( self , snap_name = None , dry_run = False ) : z_snap = self . _snapshot_to_backup ( snap_name ) to_upload = [ ] current = z_snap uploaded_meta = [ ] while True : s3_snap = self . s3_manager . get ( current . name ) if s3_snap is not None : if not s3_snap . is_healthy : raise IntegrityError ( "B... | Uploads named snapshot or latest along with any other snapshots required for an incremental backup . |
240,471 | def extrude ( self , uem , reference , collar = 0.0 , skip_overlap = False ) : if collar == 0. and not skip_overlap : return uem collars , overlap_regions = [ ] , [ ] if collar > 0. : for segment in reference . itersegments ( ) : t = segment . start collars . append ( Segment ( t - .5 * collar , t + .5 * collar ) ) t =... | Extrude reference boundary collars from uem |
240,472 | def common_timeline ( self , reference , hypothesis ) : timeline = reference . get_timeline ( copy = True ) timeline . update ( hypothesis . get_timeline ( copy = False ) ) return timeline . segmentation ( ) | Return timeline common to both reference and hypothesis |
240,473 | def project ( self , annotation , timeline ) : projection = annotation . empty ( ) timeline_ = annotation . get_timeline ( copy = False ) for segment_ , segment in timeline_ . co_iter ( timeline ) : for track_ in annotation . get_tracks ( segment_ ) : track = projection . new_track ( segment , candidate = track_ ) proj... | Project annotation onto timeline segments |
240,474 | def uemify ( self , reference , hypothesis , uem = None , collar = 0. , skip_overlap = False , returns_uem = False , returns_timeline = False ) : if uem is None : r_extent = reference . get_timeline ( ) . extent ( ) h_extent = hypothesis . get_timeline ( ) . extent ( ) extent = r_extent | h_extent uem = Timeline ( segm... | Crop reference and hypothesis to uem support |
240,475 | def get_hypothesis ( hypotheses , current_file ) : uri = current_file [ 'uri' ] if uri in hypotheses : return hypotheses [ uri ] tmp_uri = [ u for u in hypotheses if u in uri ] if len ( tmp_uri ) == 0 : msg = f'Could not find hypothesis for file "{uri}"; assuming empty file.' warnings . warn ( msg ) return Annotation (... | Get hypothesis for given file |
240,476 | def reindex ( report ) : index = list ( report . index ) i = index . index ( 'TOTAL' ) return report . reindex ( index [ : i ] + index [ i + 1 : ] + [ 'TOTAL' ] ) | Reindex report so that TOTAL is the last row |
240,477 | def precision_recall_curve ( y_true , scores , distances = False ) : if distances : scores = - scores precision , recall , thresholds = sklearn . metrics . precision_recall_curve ( y_true , scores , pos_label = True ) if distances : thresholds = - thresholds auc = sklearn . metrics . auc ( precision , recall , reorder ... | Precision - recall curve |
240,478 | def difference ( self , reference , hypothesis , uem = None , uemified = False ) : R , H , common_timeline = self . uemify ( reference , hypothesis , uem = uem , collar = self . collar , skip_overlap = self . skip_overlap , returns_timeline = True ) errors = Annotation ( uri = reference . uri , modality = reference . m... | Get error analysis as Annotation |
240,479 | def reset ( self ) : if self . parallel : from pyannote . metrics import manager_ self . accumulated_ = manager_ . dict ( ) self . results_ = manager_ . list ( ) self . uris_ = manager_ . dict ( ) else : self . accumulated_ = dict ( ) self . results_ = list ( ) self . uris_ = dict ( ) for value in self . components_ : ... | Reset accumulated components and metric values |
240,480 | def confidence_interval ( self , alpha = 0.9 ) : m , _ , _ = scipy . stats . bayes_mvs ( [ r [ self . metric_name_ ] for _ , r in self . results_ ] , alpha = alpha ) return m | Compute confidence interval on accumulated metric values |
240,481 | def compute_metric ( self , components ) : numerator = components [ PRECISION_RELEVANT_RETRIEVED ] denominator = components [ PRECISION_RETRIEVED ] if denominator == 0. : if numerator == 0 : return 1. else : raise ValueError ( '' ) else : return numerator / denominator | Compute precision from components |
240,482 | def compute_metric ( self , components ) : numerator = components [ RECALL_RELEVANT_RETRIEVED ] denominator = components [ RECALL_RELEVANT ] if denominator == 0. : if numerator == 0 : return 1. else : raise ValueError ( '' ) else : return numerator / denominator | Compute recall from components |
240,483 | def optimal_mapping ( self , reference , hypothesis , uem = None ) : if uem : reference , hypothesis = self . uemify ( reference , hypothesis , uem = uem ) mapping = self . mapper_ ( hypothesis , reference ) return mapping | Optimal label mapping |
240,484 | def greedy_mapping ( self , reference , hypothesis , uem = None ) : if uem : reference , hypothesis = self . uemify ( reference , hypothesis , uem = uem ) return self . mapper_ ( hypothesis , reference ) | Greedy label mapping |
240,485 | def default_absorbers ( Tatm , ozone_file = 'apeozone_cam3_5_54.nc' , verbose = True , ) : absorber_vmr = { } absorber_vmr [ 'CO2' ] = 348. / 1E6 absorber_vmr [ 'CH4' ] = 1650. / 1E9 absorber_vmr [ 'N2O' ] = 306. / 1E9 absorber_vmr [ 'O2' ] = 0.21 absorber_vmr [ 'CFC11' ] = 0. absorber_vmr [ 'CFC12' ] = 0. absorber_vmr... | Initialize a dictionary of well - mixed radiatively active gases All values are volumetric mixing ratios . |
240,486 | def init_interface ( field ) : interface_shape = np . array ( field . shape ) interface_shape [ - 1 ] += 1 interfaces = np . tile ( False , len ( interface_shape ) ) interfaces [ - 1 ] = True interface_zero = Field ( np . zeros ( interface_shape ) , domain = field . domain , interfaces = interfaces ) return interface_z... | Return a Field object defined at the vertical interfaces of the input Field object . |
240,487 | def convective_adjustment_direct ( p , T , c , lapserate = 6.5 ) : alpha = const . Rd / const . g * lapserate / 1.E3 L = p . size pextended = np . insert ( p , 0 , const . ps ) Pi = np . cumprod ( ( p / pextended [ : - 1 ] ) ** alpha ) beta = 1. / Pi theta = T * beta q = Pi * c n_k = np . zeros ( L , dtype = np . int8 ... | Convective Adjustment to a specified lapse rate . |
240,488 | def Akmaev_adjustment ( theta , q , beta , n_k , theta_k , s_k , t_k ) : L = q . size k = 1 n_k [ k - 1 ] = 1 theta_k [ k - 1 ] = theta [ k - 1 ] l = 2 while True : n = 1 thistheta = theta [ l - 1 ] while True : if theta_k [ k - 1 ] <= thistheta : k += 1 break else : if n <= 1 : s = q [ l - 1 ] t = s * thistheta if n_k... | Single column only . |
240,489 | def do_diagnostics ( self ) : self . OLR = self . subprocess [ 'LW' ] . flux_to_space self . LW_down_sfc = self . subprocess [ 'LW' ] . flux_to_sfc self . LW_up_sfc = self . subprocess [ 'LW' ] . flux_from_sfc self . LW_absorbed_sfc = self . LW_down_sfc - self . LW_up_sfc self . LW_absorbed_atm = self . subprocess [ 'L... | Set all the diagnostics from long and shortwave radiation . |
240,490 | def clausius_clapeyron ( T ) : Tcel = T - tempCtoK es = 6.112 * exp ( 17.67 * Tcel / ( Tcel + 243.5 ) ) return es | Compute saturation vapor pressure as function of temperature T . |
240,491 | def qsat ( T , p ) : es = clausius_clapeyron ( T ) q = eps * es / ( p - ( 1 - eps ) * es ) return q | Compute saturation specific humidity as function of temperature and pressure . |
240,492 | def pseudoadiabat ( T , p ) : esoverp = clausius_clapeyron ( T ) / p Tcel = T - tempCtoK L = ( 2.501 - 0.00237 * Tcel ) * 1.E6 ratio = L / T / Rv dTdp = ( T / p * kappa * ( 1 + esoverp * ratio ) / ( 1 + kappa * ( cpv / Rv + ( ratio - 1 ) * ratio ) * esoverp ) ) return dTdp | Compute the local slope of the pseudoadiabat at given temperature and pressure |
240,493 | def _solve_implicit_banded ( current , banded_matrix ) : J = banded_matrix . shape [ 0 ] diag = np . zeros ( ( 3 , J ) ) diag [ 1 , : ] = np . diag ( banded_matrix , k = 0 ) diag [ 0 , 1 : ] = np . diag ( banded_matrix , k = 1 ) diag [ 2 , : - 1 ] = np . diag ( banded_matrix , k = - 1 ) return solve_banded ( ( 1 , 1 ) ... | Uses a banded solver for matrix inversion of a tridiagonal matrix . |
240,494 | def _guess_diffusion_axis ( process_or_domain ) : axes = get_axes ( process_or_domain ) diff_ax = { } for axname , ax in axes . items ( ) : if ax . num_points > 1 : diff_ax . update ( { axname : ax } ) if len ( list ( diff_ax . keys ( ) ) ) == 1 : return list ( diff_ax . keys ( ) ) [ 0 ] else : raise ValueError ( 'More... | Scans given process domain or dictionary of domains for a diffusion axis and returns appropriate name . |
240,495 | def _implicit_solver ( self ) : newstate = { } for varname , value in self . state . items ( ) : if self . use_banded_solver : newvar = _solve_implicit_banded ( value , self . _diffTriDiag ) else : newvar = np . linalg . solve ( self . _diffTriDiag , value ) newstate [ varname ] = newvar return newstate | Invertes and solves the matrix problem for diffusion matrix and temperature T . |
240,496 | def _compute_fixed ( self ) : try : lon , lat = np . meshgrid ( self . lon , self . lat ) except : lat = self . lat phi = np . deg2rad ( lat ) try : albedo = self . a0 + self . a2 * P2 ( np . sin ( phi ) ) except : albedo = np . zeros_like ( phi ) dom = next ( iter ( self . domains . values ( ) ) ) self . albedo = Fiel... | Recompute any fixed quantities after a change in parameters |
240,497 | def find_icelines ( self ) : Tf = self . param [ 'Tf' ] Ts = self . state [ 'Ts' ] lat_bounds = self . domains [ 'Ts' ] . axes [ 'lat' ] . bounds self . noice = np . where ( Ts >= Tf , True , False ) self . ice = np . where ( Ts < Tf , True , False ) self . ice_area = global_mean ( self . ice * np . ones_like ( self . ... | Finds iceline according to the surface temperature . |
240,498 | def _get_current_albedo ( self ) : ice = self . subprocess [ 'iceline' ] . ice cold_albedo = self . subprocess [ 'cold_albedo' ] . albedo warm_albedo = self . subprocess [ 'warm_albedo' ] . albedo albedo = Field ( np . where ( ice , cold_albedo , warm_albedo ) , domain = self . domains [ 'Ts' ] ) return albedo | Simple step - function albedo based on ice line at temperature Tf . |
240,499 | def process_like ( proc ) : newproc = copy . deepcopy ( proc ) newproc . creation_date = time . strftime ( "%a, %d %b %Y %H:%M:%S %z" , time . localtime ( ) ) return newproc | Make an exact clone of a process including state and all subprocesses . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.