idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
46,900 | def sign ( self , req , issuer_cert_key , validity_period , digest = "sha256" , extensions = None , serial = 0 ) : issuer_cert , issuer_key = issuer_cert_key not_before , not_after = validity_period cert = crypto . X509 ( ) cert . set_serial_number ( serial ) cert . gmtime_adj_notBefore ( not_before ) cert . gmtime_adj_notAfter ( not_after ) cert . set_issuer ( issuer_cert . get_subject ( ) ) cert . set_subject ( req . get_subject ( ) ) cert . set_pubkey ( req . get_pubkey ( ) ) if extensions : for ext in extensions : if callable ( ext ) : ext = ext ( cert ) cert . add_extensions ( [ ext ] ) cert . sign ( issuer_key , digest ) return cert | Generate a certificate given a certificate request . |
46,901 | def create_ca_bundle_for_names ( self , bundle_name , names ) : records = [ rec for name , rec in self . store . store . items ( ) if name in names ] return self . create_bundle ( bundle_name , names = [ r [ 'parent_ca' ] for r in records ] ) | Create a CA bundle to trust only certs defined in names |
46,902 | def create_bundle ( self , bundle_name , names = None , ca_only = True ) : if not names : if ca_only : names = [ ] for name , record in self . store . store . items ( ) : if record [ 'is_ca' ] : names . append ( name ) else : names = self . store . store . keys ( ) out_file_path = os . path . join ( self . store . containing_dir , bundle_name ) with open ( out_file_path , 'w' ) as fh : for name in names : bundle = self . store . get_files ( name ) bundle . cert . load ( ) fh . write ( str ( bundle . cert ) ) return out_file_path | Create a bundle of public certs for trust distribution |
46,903 | def trust_from_graph ( self , graph ) : def distinct_components ( graph ) : components = set ( graph . keys ( ) ) for trusts in graph . values ( ) : components |= set ( trusts ) return components for component in distinct_components ( graph ) : try : self . store . get_record ( component ) except CertNotFoundError : self . create_ca ( component ) trust_files = { } for component , trusts in graph . items ( ) : file_name = component + '_trust.crt' trust_files [ component ] = self . create_bundle ( file_name , names = trusts , ca_only = False ) return trust_files | Create a set of trust bundles from a relationship graph . |
46,904 | def create_ca ( self , name , ca_name = '' , cert_type = crypto . TYPE_RSA , bits = 2048 , alt_names = None , years = 5 , serial = 0 , pathlen = 0 , overwrite = False ) : cakey = self . create_key_pair ( cert_type , bits ) req = self . create_request ( cakey , CN = name ) signing_key = cakey signing_cert = req parent_ca = '' if ca_name : ca_bundle = self . store . get_files ( ca_name ) signing_key = ca_bundle . key . load ( ) signing_cert = ca_bundle . cert . load ( ) parent_ca = ca_bundle . cert . file_path basicConstraints = "CA:true" if pathlen >= 0 : basicConstraints += ', pathlen:' + str ( pathlen ) extensions = [ crypto . X509Extension ( b"basicConstraints" , True , basicConstraints . encode ( ) ) , crypto . X509Extension ( b"keyUsage" , True , b"keyCertSign, cRLSign" ) , crypto . X509Extension ( b"extendedKeyUsage" , True , b"serverAuth, clientAuth" ) , lambda cert : crypto . X509Extension ( b"subjectKeyIdentifier" , False , b"hash" , subject = cert ) , lambda cert : crypto . X509Extension ( b"authorityKeyIdentifier" , False , b"keyid:always" , issuer = cert ) , ] if alt_names : extensions . append ( crypto . X509Extension ( b"subjectAltName" , False , "," . join ( alt_names ) . encode ( ) ) ) cacert = self . sign ( req , ( signing_cert , signing_key ) , ( 0 , 60 * 60 * 24 * 365 * years ) , extensions = extensions ) x509s = { 'key' : cakey , 'cert' : cacert , 'ca' : cacert } self . store . add_files ( name , x509s , overwrite = overwrite , parent_ca = parent_ca , is_ca = True ) if ca_name : self . store . add_sign_link ( ca_name , name ) return self . store . get_record ( name ) | Create a certificate authority |
46,905 | def create_signed_pair ( self , name , ca_name , cert_type = crypto . TYPE_RSA , bits = 2048 , years = 5 , alt_names = None , serial = 0 , overwrite = False ) : key = self . create_key_pair ( cert_type , bits ) req = self . create_request ( key , CN = name ) extensions = [ crypto . X509Extension ( b"extendedKeyUsage" , True , b"serverAuth, clientAuth" ) , ] if alt_names : extensions . append ( crypto . X509Extension ( b"subjectAltName" , False , "," . join ( alt_names ) . encode ( ) ) ) ca_bundle = self . store . get_files ( ca_name ) cacert = ca_bundle . cert . load ( ) cakey = ca_bundle . key . load ( ) cert = self . sign ( req , ( cacert , cakey ) , ( 0 , 60 * 60 * 24 * 365 * years ) , extensions = extensions ) x509s = { 'key' : key , 'cert' : cert , 'ca' : None } self . store . add_files ( name , x509s , parent_ca = ca_name , overwrite = overwrite ) self . store . add_sign_link ( ca_name , name ) return self . store . get_record ( name ) | Create a key - cert pair |
46,906 | def send_change_notification ( hub , topic_url , updated_content = None ) : if updated_content : body = base64 . b64decode ( updated_content [ 'content' ] ) else : body , updated_content = get_new_content ( hub . config , topic_url ) b64_body = updated_content [ 'content' ] headers = updated_content [ 'headers' ] link_header = headers . get ( 'Link' , '' ) if 'rel="hub"' not in link_header or 'rel="self"' not in link_header : raise NotificationError ( INVALID_LINK ) for callback_url , secret in hub . storage . get_callbacks ( topic_url ) : schedule_request ( hub , topic_url , callback_url , secret , body , b64_body , headers ) | 7 . Content Distribution |
46,907 | def subscribe ( hub , callback_url , topic_url , lease_seconds , secret , endpoint_hook_data ) : for validate in hub . validators : error = validate ( callback_url , topic_url , lease_seconds , secret , endpoint_hook_data ) if error : send_denied ( hub , callback_url , topic_url , error ) return if intent_verified ( hub , callback_url , 'subscribe' , topic_url , lease_seconds ) : hub . storage [ topic_url , callback_url ] = { 'lease_seconds' : lease_seconds , 'secret' : secret , } | 5 . 2 Subscription Validation |
46,908 | def intent_verified ( hub , callback_url , mode , topic_url , lease_seconds ) : challenge = uuid4 ( ) params = { 'hub.mode' : mode , 'hub.topic' : topic_url , 'hub.challenge' : challenge , 'hub.lease_seconds' : lease_seconds , } try : response = request_url ( hub . config , 'GET' , callback_url , params = params ) assert response . status_code == 200 and response . text == challenge except requests . exceptions . RequestException as e : warn ( "Cannot verify subscriber intent" , e ) except AssertionError as e : warn ( INTENT_UNVERIFIED % ( response . status_code , response . content ) , e ) else : return True return False | 5 . 3 Hub Verifies Intent of the Subscriber |
46,909 | def init_celery ( self , celery ) : count = next ( self . counter ) def task_with_hub ( f , ** opts ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( self , * args , ** kwargs ) wrapper . __name__ = wrapper . __name__ + '_' + str ( count ) return celery . task ( ** opts ) ( wrapper ) self . subscribe = task_with_hub ( subscribe ) self . unsubscribe = task_with_hub ( unsubscribe ) max_attempts = self . config . get ( 'MAX_ATTEMPTS' , 10 ) make_req = task_with_hub ( make_request_retrying , bind = True , max_retries = max_attempts ) self . make_request_retrying = make_req self . send_change = task_with_hub ( send_change_notification ) @ task_with_hub def cleanup ( hub ) : self . storage . cleanup_expired_subscriptions ( ) self . cleanup = cleanup def schedule ( every_x_seconds = A_DAY ) : celery . add_periodic_task ( every_x_seconds , self . cleanup_expired_subscriptions . s ( ) ) self . schedule = schedule | Registers the celery tasks on the hub object . |
46,910 | def init_publisher ( app ) : @ app . context_processor def inject_links ( ) : return { 'websub_self_url' : stack . top . websub_self_url , 'websub_hub_url' : stack . top . websub_hub_url , 'websub_self_link' : stack . top . websub_self_link , 'websub_hub_link' : stack . top . websub_hub_link , } | Calling this with your flask app as argument is required for the publisher decorator to work . |
46,911 | def count_results ( cube , q ) : q = select ( columns = [ func . count ( True ) ] , from_obj = q . alias ( ) ) return cube . engine . execute ( q ) . scalar ( ) | Get the count of records matching the query . |
46,912 | def generate_results ( cube , q ) : if q . _limit is not None and q . _limit < 1 : return rp = cube . engine . execute ( q ) while True : row = rp . fetchone ( ) if row is None : return yield dict ( row . items ( ) ) | Generate the resulting records for this query applying pagination . Values will be returned by their reference . |
46,913 | def concatenate ( cls , * args ) : nargs = len ( args ) if nargs == 1 : return args [ 0 ] vs = [ a . v for a in args if a . v is not None ] vcs = [ a . vc for a in args if a . vc is not None ] fs = [ a . f for a in args if a . f is not None ] if vs and len ( vs ) != nargs : raise ValueError ( 'Expected `v` for all args or none.' ) if vcs and len ( vcs ) != nargs : raise ValueError ( 'Expected `vc` for all args or none.' ) if fs and len ( fs ) != nargs : raise ValueError ( 'Expected `f` for all args or none.' ) face_offsets = np . cumsum ( [ v . shape [ 0 ] for v in vs [ : - 1 ] ] ) for offset , f in zip ( face_offsets , fs [ 1 : ] ) : f += offset return Mesh ( v = np . vstack ( vs ) if vs else None , vc = np . vstack ( vcs ) if vcs else None , f = np . vstack ( fs ) if fs else None , ) | Concatenates an arbitrary number of meshes . |
46,914 | def getNewConnection ( * args , ** kargs ) : kargs = dict ( kargs ) if len ( args ) > 0 : if len ( args ) >= 1 : kargs [ 'host' ] = args [ 0 ] if len ( args ) >= 2 : kargs [ 'user' ] = args [ 1 ] if len ( args ) >= 3 : kargs [ 'passwd' ] = args [ 2 ] if len ( args ) >= 4 : kargs [ 'db' ] = args [ 3 ] if len ( args ) >= 5 : kargs [ 'port' ] = args [ 4 ] if len ( args ) >= 6 : kargs [ 'commitOnEnd' ] = args [ 5 ] return connection . Connection ( * args , ** kargs ) | Quickly Create a new PySQLConnection class |
46,915 | def getNewQuery ( connection = None , commitOnEnd = False , * args , ** kargs ) : if connection is None : return query . PySQLQuery ( getNewConnection ( * args , ** kargs ) , commitOnEnd = commitOnEnd ) else : return query . PySQLQuery ( connection , commitOnEnd = commitOnEnd ) | Create a new PySQLQuery Class |
46,916 | def cli ( username , repository , path , password , deploy , env , clipboard , env_file ) : key = retrieve_public_key ( '{}/{}' . format ( username , repository ) ) if env_file : if path : config = load_travis_configuration ( path ) for env_var , value in dotenv_values ( env_file ) . items ( ) : encrypted_env = encrypt_key ( key , value . encode ( ) ) config . setdefault ( 'env' , { } ) . setdefault ( 'global' , { } ) [ env_var ] = { 'secure' : encrypted_env } dump_travis_configuration ( config , path ) print ( 'Encrypted variables from {} added to {}' . format ( env_file , path ) ) else : print ( '\nPlease add the following to your .travis.yml:' ) for env_var , value in dotenv_values ( env_file ) . items ( ) : encrypted_env = encrypt_key ( key , value . encode ( ) ) print ( "{}:\n secure: {}" . format ( env_var , encrypted_env ) ) else : encrypted_password = encrypt_key ( key , password . encode ( ) ) if path : config = load_travis_configuration ( path ) if config is None : config = OrderedDict ( ) if deploy : config . setdefault ( 'deploy' , { } ) . setdefault ( 'password' , { } ) [ 'secure' ] = encrypted_password elif env : try : config . setdefault ( 'env' , { } ) . setdefault ( 'global' , { } ) [ 'secure' ] = encrypted_password except TypeError : for item in config [ 'env' ] [ 'global' ] : if isinstance ( item , dict ) and 'secure' in item : item [ 'secure' ] = encrypted_password else : config . setdefault ( 'password' , { } ) [ 'secure' ] = encrypted_password dump_travis_configuration ( config , path ) print ( 'Encrypted password added to {}' . format ( path ) ) elif clipboard : pyperclip . copy ( encrypted_password ) print ( '\nThe encrypted password has been copied to your clipboard.' ) else : print ( '\nPlease add the following to your .travis.yml:\nsecure: {}' . format ( encrypted_password ) ) | Encrypt passwords and environment variables for use with Travis CI . |
46,917 | def apply ( self , q , bindings , fields , distinct = False ) : info = [ ] group_by = None for field in self . parse ( fields ) : for concept in self . cube . model . match ( field ) : info . append ( concept . ref ) table , column = concept . bind ( self . cube ) bindings . append ( Binding ( table , concept . ref ) ) if distinct : if group_by is None : q = q . group_by ( column ) group_by = column else : min_column = func . max ( column ) min_column = min_column . label ( column . name ) column = min_column q = q . column ( column ) if not len ( self . results ) : for concept in list ( self . cube . model . attributes ) + list ( self . cube . model . measures ) : info . append ( concept . ref ) table , column = concept . bind ( self . cube ) bindings . append ( Binding ( table , concept . ref ) ) q = q . column ( column ) return info , q , bindings | Define a set of fields to return for a non - aggregated query . |
46,918 | def create_cell_volumes ( self ) : self . cell_volumes = numpy . array ( [ abs ( self . node_coords [ cell [ "nodes" ] ] [ 1 ] - self . node_coords [ cell [ "nodes" ] ] [ 0 ] ) for cell in self . cells ] ) return | Computes the volumes of the cells in the mesh . |
46,919 | def create_rectangular_prism ( origin , size ) : from lace . topology import quads_to_tris lower_base_plane = np . array ( [ origin , origin + np . array ( [ size [ 0 ] , 0 , 0 ] ) , origin + np . array ( [ size [ 0 ] , 0 , size [ 2 ] ] ) , origin + np . array ( [ 0 , 0 , size [ 2 ] ] ) , ] ) upper_base_plane = lower_base_plane + np . array ( [ 0 , size [ 1 ] , 0 ] ) vertices = np . vstack ( [ lower_base_plane , upper_base_plane ] ) faces = quads_to_tris ( np . array ( [ [ 0 , 1 , 2 , 3 ] , [ 7 , 6 , 5 , 4 ] , [ 4 , 5 , 1 , 0 ] , [ 5 , 6 , 2 , 1 ] , [ 6 , 7 , 3 , 2 ] , [ 3 , 7 , 4 , 0 ] , ] ) ) return Mesh ( v = vertices , f = faces ) | Return a Mesh which is an axis - aligned rectangular prism . One vertex is origin ; the diametrically opposite vertex is origin + size . |
46,920 | def create_triangular_prism ( p1 , p2 , p3 , height ) : from blmath . geometry import Plane base_plane = Plane . from_points ( p1 , p2 , p3 ) lower_base_to_upper_base = height * - base_plane . normal vertices = np . vstack ( ( [ p1 , p2 , p3 ] , [ p1 , p2 , p3 ] + lower_base_to_upper_base ) ) faces = np . array ( [ [ 0 , 1 , 2 ] , [ 0 , 3 , 4 ] , [ 0 , 4 , 1 ] , [ 1 , 4 , 5 ] , [ 1 , 5 , 2 ] , [ 2 , 5 , 3 ] , [ 2 , 3 , 0 ] , [ 5 , 4 , 3 ] , ] ) return Mesh ( v = vertices , f = faces ) | Return a Mesh which is a triangular prism whose base is the triangle p1 p2 p3 . If the vertices are oriented in a counterclockwise direction the prism extends from behind them . |
46,921 | def create_horizontal_plane ( ) : v = np . array ( [ [ 1. , 0. , 0. ] , [ - 1. , 0. , 0. ] , [ 0. , 0. , 1. ] , [ 0. , 0. , - 1. ] ] ) f = [ [ 0 , 1 , 2 ] , [ 3 , 1 , 0 ] ] return Mesh ( v = v , f = f ) | Creates a horizontal plane . |
46,922 | def match_ref ( self , ref ) : if ref in self . refs : self . _matched_ref = ref return True return False | Check if the ref matches one the concept s aliases . If so mark the matched ref so that we use it as the column label . |
46,923 | def bind ( self , cube ) : table , column = self . _physical_column ( cube , self . column_name ) column = column . label ( self . matched_ref ) column . quote = True return table , column | Map a model reference to an physical column in the database . |
46,924 | def update_from_stripe_data ( self , stripe_coupon , exclude_fields = None , commit = True ) : fields_to_update = self . STRIPE_FIELDS - set ( exclude_fields or [ ] ) update_data = { key : stripe_coupon [ key ] for key in fields_to_update } for field in [ "created" , "redeem_by" ] : if update_data . get ( field ) : update_data [ field ] = timestamp_to_timezone_aware_date ( update_data [ field ] ) if update_data . get ( "amount_off" ) : update_data [ "amount_off" ] = Decimal ( update_data [ "amount_off" ] ) / 100 for key , value in six . iteritems ( update_data ) : setattr ( self , key , value ) if commit : return StripeCoupon . objects . filter ( pk = self . pk ) . update ( ** update_data ) | Update StripeCoupon object with data from stripe . Coupon without calling stripe . Coupon . retrieve . |
46,925 | def save ( self , force_retrieve = False , * args , ** kwargs ) : stripe . api_key = stripe_settings . API_KEY if self . _previous_is_deleted != self . is_deleted and self . is_deleted : try : stripe_coupon = stripe . Coupon . retrieve ( self . coupon_id ) if self . created == timestamp_to_timezone_aware_date ( stripe_coupon [ "created" ] ) : stripe_coupon . delete ( ) except stripe . error . InvalidRequestError : pass return super ( StripeCoupon , self ) . save ( * args , ** kwargs ) if self . pk or force_retrieve : try : stripe_coupon = stripe . Coupon . retrieve ( self . coupon_id ) if not force_retrieve : stripe_coupon . metadata = self . metadata stripe_coupon . save ( ) if force_retrieve : coupon_qs = StripeCoupon . objects . filter ( coupon_id = self . coupon_id ) if coupon_qs . filter ( created = timestamp_to_timezone_aware_date ( stripe_coupon [ "created" ] ) ) . exists ( ) : raise StripeCouponAlreadyExists for coupon in coupon_qs : coupon . is_deleted = True super ( StripeCoupon , coupon ) . save ( ) self . update_from_stripe_data ( stripe_coupon , exclude_fields = [ "metadata" ] if not force_retrieve else [ ] ) self . stripe_response = stripe_coupon except stripe . error . InvalidRequestError : if force_retrieve : raise self . is_deleted = True else : self . stripe_response = stripe . Coupon . create ( id = self . coupon_id , duration = self . duration , amount_off = int ( self . amount_off * 100 ) if self . amount_off else None , currency = self . currency , duration_in_months = self . duration_in_months , max_redemptions = self . max_redemptions , metadata = self . metadata , percent_off = self . percent_off , redeem_by = int ( dateformat . format ( self . redeem_by , "U" ) ) if self . redeem_by else None ) if not self . coupon_id : self . coupon_id = self . stripe_response [ "id" ] self . created = timestamp_to_timezone_aware_date ( self . stripe_response [ "created" ] ) self . is_created_at_stripe = True return super ( StripeCoupon , self ) . save ( * args , ** kwargs ) | Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe |
46,926 | def get_signed_simplex_volumes ( cells , pts ) : n = pts . shape [ 1 ] assert cells . shape [ 1 ] == n + 1 p = pts [ cells ] p = numpy . concatenate ( [ p , numpy . ones ( list ( p . shape [ : 2 ] ) + [ 1 ] ) ] , axis = - 1 ) return numpy . linalg . det ( p ) / math . factorial ( n ) | Signed volume of a simplex in nD . Note that signing only makes sense for n - simplices in R^n . |
46,927 | def compute_triangle_circumcenters ( X , ei_dot_ei , ei_dot_ej ) : alpha = ei_dot_ei * ei_dot_ej alpha_sum = alpha [ 0 ] + alpha [ 1 ] + alpha [ 2 ] beta = alpha / alpha_sum [ None ] a = X * beta [ ... , None ] cc = a [ 0 ] + a [ 1 ] + a [ 2 ] return cc | Computes the circumcenters of all given triangles . |
46,928 | def ordered_dump ( data , stream = None , Dumper = yaml . SafeDumper , ** kwds ) : class OrderedDumper ( Dumper ) : pass def dict_representer ( dumper , data ) : return dumper . represent_mapping ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , data . items ( ) ) OrderedDumper . add_representer ( OrderedDict , dict_representer ) return yaml . dump ( data , stream , OrderedDumper , ** kwds ) | Dump a yaml configuration as an OrderedDict . |
46,929 | def _check_type ( self , ref , value ) : if isinstance ( value , list ) : return [ self . _check_type ( ref , val ) for val in value ] model_type = self . cube . model [ ref ] . datatype if model_type is None : return query_type = self . _api_type ( value ) if query_type == model_type : return else : raise QueryException ( "Invalid value %r parsed as type '%s' " "for cut %s of type '%s'" % ( value , query_type , ref , model_type ) ) | Checks whether the type of the cut value matches the type of the concept being cut and raises a QueryException if it doesn t match |
46,930 | def _api_type ( self , value ) : if isinstance ( value , six . string_types ) : return 'string' elif isinstance ( value , six . integer_types ) : return 'integer' elif type ( value ) is datetime . datetime : return 'date' | Returns the API type of the given value based on its python type . |
46,931 | def color_by_height ( self , axis = 1 , threshold = None , color = DEFAULT_COLORMAP ) : import numpy as np heights = self . v [ : , axis ] - self . floor_point [ axis ] if threshold : color_weights = np . minimum ( heights / threshold , 1. ) color_weights = color_weights * color_weights self . set_vertex_colors_from_weights ( color_weights , scale_to_range_1 = False ) else : self . set_vertex_colors_from_weights ( heights ) | Color each vertex by its height above the floor point . |
46,932 | def quads_to_tris ( quads ) : import numpy as np tris = np . empty ( ( 2 * len ( quads ) , 3 ) ) tris [ 0 : : 2 , : ] = quads [ : , [ 0 , 1 , 2 ] ] tris [ 1 : : 2 , : ] = quads [ : , [ 0 , 2 , 3 ] ] return tris | Convert quad faces to triangular faces . |
46,933 | def vertex_indices_in_segments ( self , segments , ret_face_indices = False ) : import numpy as np import warnings face_indices = np . array ( [ ] ) vertex_indices = np . array ( [ ] ) if self . segm is not None : try : segments = [ self . segm [ name ] for name in segments ] except KeyError as e : raise ValueError ( 'Unknown segments {}. Consier using Mesh.clean_segments on segments' . format ( e . args [ 0 ] ) ) face_indices = np . unique ( np . concatenate ( segments ) ) vertex_indices = np . unique ( np . ravel ( self . f [ face_indices ] ) ) else : warnings . warn ( 'self.segm is None, will return empty array' ) if ret_face_indices : return vertex_indices , face_indices else : return vertex_indices | Given a list of segment names return an array of vertex indices for all the vertices in those faces . |
46,934 | def keep_segments ( self , segments_to_keep , preserve_segmentation = True ) : v_ind , f_ind = self . vertex_indices_in_segments ( segments_to_keep , ret_face_indices = True ) self . segm = { name : self . segm [ name ] for name in segments_to_keep } if not preserve_segmentation : self . segm = None self . f = self . f [ f_ind ] if self . ft is not None : self . ft = self . ft [ f_ind ] self . keep_vertices ( v_ind ) | Keep the faces and vertices for given segments discarding all others . When preserve_segmentation is false self . segm is discarded for speed . |
46,935 | def remove_segments ( self , segments_to_remove ) : v_ind = self . vertex_indices_in_segments ( segments_to_remove ) self . segm = { name : faces for name , faces in self . segm . iteritems ( ) if name not in segments_to_remove } self . remove_vertices ( v_ind ) | Remove the faces and vertices for given segments keeping all others . |
46,936 | def verts_in_common ( self , segments ) : verts_by_segm = self . verts_by_segm return sorted ( reduce ( lambda s0 , s1 : s0 . intersection ( s1 ) , [ set ( verts_by_segm [ segm ] ) for segm in segments ] ) ) | returns array of all vertex indices common to each segment in segments |
46,937 | def uniquified_mesh ( self ) : import numpy as np from lace . mesh import Mesh new_mesh = Mesh ( v = self . v [ self . f . flatten ( ) ] , f = np . array ( range ( len ( self . f . flatten ( ) ) ) ) . reshape ( - 1 , 3 ) ) if self . vn is None : self . reset_normals ( ) new_mesh . vn = self . vn [ self . f . flatten ( ) ] if self . vt is not None : new_mesh . vt = self . vt [ self . ft . flatten ( ) ] new_mesh . ft = new_mesh . f . copy ( ) return new_mesh | This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face and hence has only one texture |
46,938 | def downsampled_mesh ( self , step ) : from lace . mesh import Mesh if self . f is not None : raise ValueError ( 'Function `downsampled_mesh` does not support faces.' ) low = Mesh ( ) if self . v is not None : low . v = self . v [ : : step ] if self . vc is not None : low . vc = self . vc [ : : step ] return low | Returns a downsampled copy of this mesh . |
46,939 | def keep_vertices ( self , indices_to_keep , ret_kept_faces = False ) : import numpy as np if self . v is None : return indices_to_keep = np . array ( indices_to_keep , dtype = np . uint32 ) initial_num_verts = self . v . shape [ 0 ] if self . f is not None : initial_num_faces = self . f . shape [ 0 ] f_indices_to_keep = self . all_faces_with_verts ( indices_to_keep , as_boolean = True ) vn_should_update = self . vn is not None and self . vn . shape [ 0 ] == initial_num_verts vc_should_update = self . vc is not None and self . vc . shape [ 0 ] == initial_num_verts self . v = self . v [ indices_to_keep ] if vn_should_update : self . vn = self . vn [ indices_to_keep ] if vc_should_update : self . vc = self . vc [ indices_to_keep ] if self . f is not None : v_old_to_new = np . zeros ( initial_num_verts , dtype = int ) f_old_to_new = np . zeros ( initial_num_faces , dtype = int ) v_old_to_new [ indices_to_keep ] = np . arange ( len ( indices_to_keep ) , dtype = int ) self . f = v_old_to_new [ self . f [ f_indices_to_keep ] ] f_old_to_new [ f_indices_to_keep ] = np . arange ( self . f . shape [ 0 ] , dtype = int ) else : f_indices_to_keep = [ ] if self . segm is not None : new_segm = { } for segm_name , segm_faces in self . segm . items ( ) : faces = np . array ( segm_faces , dtype = int ) valid_faces = faces [ f_indices_to_keep [ faces ] ] if len ( valid_faces ) : new_segm [ segm_name ] = f_old_to_new [ valid_faces ] self . segm = new_segm if new_segm else None if hasattr ( self , '_raw_landmarks' ) and self . _raw_landmarks is not None : self . recompute_landmarks ( ) return np . nonzero ( f_indices_to_keep ) [ 0 ] if ret_kept_faces else self | Keep the given vertices and discard the others and any faces to which they may belong . |
46,940 | def create_from_mesh_and_lines ( cls , mesh , lines ) : mesh_with_lines = mesh . copy ( ) mesh_with_lines . add_lines ( lines ) return mesh_with_lines | Return a copy of mesh with line vertices and edges added . |
46,941 | def add_lines ( self , lines ) : import numpy as np if not lines : return v_lines = np . vstack ( [ l . v for l in lines ] ) v_index_offset = np . cumsum ( [ 0 ] + [ len ( l . v ) for l in lines ] ) e_lines = np . vstack ( [ l . e + v_index_offset [ i ] for i , l in enumerate ( lines ) ] ) num_body_verts = self . v . shape [ 0 ] self . v = np . vstack ( [ self . v , v_lines ] ) self . e = e_lines + num_body_verts | Add line vertices and edges to the mesh . |
46,942 | def faces_per_edge ( self ) : import numpy as np import scipy . sparse as sp from blmath . numerics . matlab import col IS = np . repeat ( np . arange ( len ( self . f ) ) , 3 ) JS = self . f . ravel ( ) data = np . ones ( IS . size ) f2v = sp . csc_matrix ( ( data , ( IS , JS ) ) , shape = ( len ( self . f ) , np . max ( self . f . ravel ( ) ) + 1 ) ) f2f = f2v . dot ( f2v . T ) f2f = f2f . tocoo ( ) f2f = np . hstack ( ( col ( f2f . row ) , col ( f2f . col ) , col ( f2f . data ) ) ) which = ( f2f [ : , 0 ] < f2f [ : , 1 ] ) & ( f2f [ : , 2 ] >= 2 ) return np . asarray ( f2f [ which , : 2 ] , np . uint32 ) | Returns an Ex2 array of adjacencies between faces where each element in the array is a face index . Each edge is included only once . Edges that are not shared by 2 faces are not included . |
46,943 | def vertices_per_edge ( self ) : import numpy as np return np . asarray ( [ vertices_in_common ( e [ 0 ] , e [ 1 ] ) for e in self . f [ self . faces_per_edge ] ] ) | Returns an Ex2 array of adjacencies between vertices where each element in the array is a vertex index . Each edge is included only once . Edges that are not shared by 2 faces are not included . |
46,944 | def remove_redundant_verts ( self , eps = 1e-10 ) : import numpy as np from scipy . spatial import cKDTree fshape = self . f . shape tree = cKDTree ( self . v ) close_pairs = list ( tree . query_pairs ( eps ) ) if close_pairs : close_pairs = np . sort ( close_pairs , axis = 1 ) equivalent_verts = np . arange ( self . v . shape [ 0 ] ) for v1 , v2 in close_pairs : if equivalent_verts [ v2 ] > v1 : equivalent_verts [ v2 ] = v1 self . f = equivalent_verts [ self . f . flatten ( ) ] . reshape ( ( - 1 , 3 ) ) vertidxs_left = np . unique ( self . f ) repl = np . arange ( np . max ( self . f ) + 1 ) repl [ vertidxs_left ] = np . arange ( len ( vertidxs_left ) ) self . v = self . v [ vertidxs_left ] self . f = repl [ self . f ] . reshape ( ( - 1 , fshape [ 1 ] ) ) | Given verts and faces this remove colocated vertices |
46,945 | def signed_cell_areas ( self ) : assert ( self . node_coords . shape [ 1 ] == 2 ) , "Signed areas only make sense for triangles in 2D." if self . _signed_cell_areas is None : p = self . node_coords [ self . cells [ "nodes" ] ] . T self . _signed_cell_areas = ( + p [ 0 ] [ 2 ] * ( p [ 1 ] [ 0 ] - p [ 1 ] [ 1 ] ) + p [ 0 ] [ 0 ] * ( p [ 1 ] [ 1 ] - p [ 1 ] [ 2 ] ) + p [ 0 ] [ 1 ] * ( p [ 1 ] [ 2 ] - p [ 1 ] [ 0 ] ) ) / 2 return self . _signed_cell_areas | Signed area of a triangle in 2D . |
46,946 | def create_edges ( self ) : s = self . idx_hierarchy . shape a = numpy . sort ( self . idx_hierarchy . reshape ( s [ 0 ] , - 1 ) . T ) a_unique , inv , cts = unique_rows ( a ) assert numpy . all ( cts < 3 ) , "No edge has more than 2 cells. Are cells listed twice?" self . is_boundary_edge = ( cts [ inv ] == 1 ) . reshape ( s [ 1 : ] ) self . is_boundary_edge_individual = cts == 1 self . edges = { "nodes" : a_unique } self . cells [ "edges" ] = inv . reshape ( 3 , - 1 ) . T self . _edges_cells = None self . _edge_gid_to_edge_list = None self . _edge_to_edge_gid = [ [ ] , numpy . where ( self . is_boundary_edge_individual ) [ 0 ] , numpy . where ( ~ self . is_boundary_edge_individual ) [ 0 ] , ] return | Set up edge - node and edge - cell relations . |
46,947 | def _compute_edges_cells ( self ) : if self . edges is None : self . create_edges ( ) num_edges = len ( self . edges [ "nodes" ] ) counts = numpy . zeros ( num_edges , dtype = int ) fastfunc . add . at ( counts , self . cells [ "edges" ] , numpy . ones ( self . cells [ "edges" ] . shape , dtype = int ) , ) edges_flat = self . cells [ "edges" ] . flat idx_sort = numpy . argsort ( edges_flat ) idx_start , count = grp_start_len ( edges_flat [ idx_sort ] ) res1 = idx_sort [ idx_start [ count == 1 ] ] [ : , numpy . newaxis ] idx = idx_start [ count == 2 ] res2 = numpy . column_stack ( [ idx_sort [ idx ] , idx_sort [ idx + 1 ] ] ) self . _edges_cells = [ [ ] , res1 // 3 , res2 // 3 , ] self . _edge_gid_to_edge_list = numpy . empty ( ( num_edges , 2 ) , dtype = int ) self . _edge_gid_to_edge_list [ : , 0 ] = count c1 = count == 1 l1 = numpy . sum ( c1 ) self . _edge_gid_to_edge_list [ c1 , 1 ] = numpy . arange ( l1 ) c2 = count == 2 l2 = numpy . sum ( c2 ) self . _edge_gid_to_edge_list [ c2 , 1 ] = numpy . arange ( l2 ) assert l1 + l2 == len ( count ) return | This creates interior edge - > cells relations . While it s not necessary for many applications it sometimes does come in handy . |
46,948 | def _compute_integral_x ( self ) : right_triangle_vols = self . cell_partitions node_edges = self . idx_hierarchy corner = self . node_coords [ node_edges ] edge_midpoints = 0.5 * ( corner [ 0 ] + corner [ 1 ] ) cc = self . cell_circumcenters average = ( corner + edge_midpoints [ None ] + cc [ None , None ] ) / 3.0 contribs = right_triangle_vols [ None , : , : , None ] * average return node_edges , contribs | Computes the integral of x |
46,949 | def _compute_surface_areas ( self , cell_ids ) : cn = self . cells [ "nodes" ] [ cell_ids ] ids = numpy . stack ( [ cn , cn , cn ] , axis = 1 ) half_el = 0.5 * self . edge_lengths [ ... , cell_ids ] zero = numpy . zeros ( [ half_el . shape [ 1 ] ] ) vals = numpy . stack ( [ numpy . column_stack ( [ zero , half_el [ 0 ] , half_el [ 0 ] ] ) , numpy . column_stack ( [ half_el [ 1 ] , zero , half_el [ 1 ] ] ) , numpy . column_stack ( [ half_el [ 2 ] , half_el [ 2 ] , zero ] ) , ] , axis = 1 , ) return ids , vals | For each edge one half of the the edge goes to each of the end points . Used for Neumann boundary conditions if on the boundary of the mesh and transition conditions if in the interior . |
46,950 | def compute_curl ( self , vector_field ) : A = 0.5 * numpy . sum ( vector_field [ self . idx_hierarchy ] , axis = 0 ) sum_edge_dot_A = numpy . einsum ( "ijk, ijk->j" , self . half_edge_coords , A ) z = numpy . cross ( self . half_edge_coords [ 0 ] , self . half_edge_coords [ 1 ] ) curl = z * ( 0.5 * sum_edge_dot_A / self . cell_volumes ** 2 ) [ ... , None ] return curl | Computes the curl of a vector field over the mesh . While the vector field is point - based the curl will be cell - based . The approximation is based on |
46,951 | def show_vertex ( self , node_id , show_ce_ratio = True ) : from matplotlib import pyplot as plt fig = plt . figure ( ) ax = fig . gca ( ) plt . axis ( "equal" ) edge_gids = numpy . where ( ( self . edges [ "nodes" ] == node_id ) . any ( axis = 1 ) ) [ 0 ] for node_ids in self . edges [ "nodes" ] [ edge_gids ] : x = self . node_coords [ node_ids ] ax . plot ( x [ : , 0 ] , x [ : , 1 ] , "k" ) if show_ce_ratio : if self . cell_circumcenters is None : X = self . node_coords [ self . cells [ "nodes" ] ] self . cell_circumcenters = self . compute_triangle_circumcenters ( X , self . ei_dot_ei , self . ei_dot_ej ) cell_ids = numpy . where ( ( self . cells [ "nodes" ] == node_id ) . any ( axis = 1 ) ) [ 0 ] for cell_id in cell_ids : for edge_gid in self . cells [ "edges" ] [ cell_id ] : if node_id not in self . edges [ "nodes" ] [ edge_gid ] : continue node_ids = self . edges [ "nodes" ] [ edge_gid ] edge_midpoint = 0.5 * ( self . node_coords [ node_ids [ 0 ] ] + self . node_coords [ node_ids [ 1 ] ] ) p = _column_stack ( self . cell_circumcenters [ cell_id ] , edge_midpoint ) q = numpy . column_stack ( [ self . cell_circumcenters [ cell_id ] , edge_midpoint , self . node_coords [ node_id ] , ] ) ax . fill ( q [ 0 ] , q [ 1 ] , color = "0.5" ) ax . plot ( p [ 0 ] , p [ 1 ] , color = "0.7" ) return | Plot the vicinity of a node and its ce_ratio . |
46,952 | def _dump ( f , mesh ) : dae = mesh_to_collada ( mesh ) dae . write ( f . name ) | Writes a mesh to collada file format . |
46,953 | def dumps ( mesh ) : from lxml import etree dae = mesh_to_collada ( mesh ) dae . save ( ) return etree . tostring ( dae . xmlnode , encoding = 'UTF-8' ) | Generates a UTF - 8 XML string containing the mesh in collada format . |
46,954 | def mesh_to_collada ( mesh ) : import numpy as np try : from collada import Collada , scene except ImportError : raise ImportError ( "lace.serialization.dae.mesh_to_collade requires package pycollada." ) def create_material ( dae ) : from collada import material , scene effect = material . Effect ( "effect0" , [ ] , "phong" , diffuse = ( 1 , 1 , 1 ) , specular = ( 0 , 0 , 0 ) , double_sided = True ) mat = material . Material ( "material0" , "mymaterial" , effect ) dae . effects . append ( effect ) dae . materials . append ( mat ) return scene . MaterialNode ( "materialref" , mat , inputs = [ ] ) def geometry_from_mesh ( dae , mesh ) : from collada import source , geometry srcs = [ ] srcs . append ( source . FloatSource ( "verts-array" , mesh . v , ( 'X' , 'Y' , 'Z' ) ) ) input_list = source . InputList ( ) input_list . addInput ( 0 , 'VERTEX' , "#verts-array" ) if mesh . vc is not None : input_list . addInput ( len ( srcs ) , 'COLOR' , "#color-array" ) srcs . append ( source . FloatSource ( "color-array" , mesh . vc [ mesh . f . ravel ( ) ] , ( 'X' , 'Y' , 'Z' ) ) ) geom = geometry . Geometry ( str ( mesh ) , "geometry0" , "mymesh" , srcs ) indices = np . dstack ( [ mesh . f for _ in srcs ] ) . ravel ( ) triset = geom . createTriangleSet ( indices , input_list , "materialref" ) geom . primitives . append ( triset ) if mesh . e is not None : indices = np . dstack ( [ mesh . e for _ in srcs ] ) . ravel ( ) lineset = geom . createLineSet ( indices , input_list , "materialref" ) geom . primitives . append ( lineset ) dae . geometries . append ( geom ) return geom dae = Collada ( ) geom = geometry_from_mesh ( dae , mesh ) node = scene . Node ( "node0" , children = [ scene . GeometryNode ( geom , [ create_material ( dae ) ] ) ] ) myscene = scene . Scene ( "myscene" , [ node ] ) dae . scenes . append ( myscene ) dae . scene = myscene return dae | Supports per - vertex color but nothing else . |
46,955 | def convert_units ( self , from_units , to_units ) : from blmath import units factor = units . factor ( from_units = from_units , to_units = to_units , units_class = 'length' ) self . scale ( factor ) | Convert the mesh from one set of units to another . |
46,956 | def predict_body_units ( self ) : longest_dist = np . max ( np . max ( self . v , axis = 0 ) - np . min ( self . v , axis = 0 ) ) if round ( longest_dist / 1000 ) > 0 : return 'mm' if round ( longest_dist / 100 ) > 0 : return 'cm' if round ( longest_dist / 10 ) > 0 : return 'dm' return 'm' | There is no prediction for united states unit system . This may fail when a mesh is not axis - aligned |
46,957 | def reorient ( self , up , look ) : from blmath . geometry . transform import rotation_from_up_and_look from blmath . numerics import as_numeric_array up = as_numeric_array ( up , ( 3 , ) ) look = as_numeric_array ( look , ( 3 , ) ) if self . v is not None : self . v = np . dot ( rotation_from_up_and_look ( up , look ) , self . v . T ) . T | Reorient the mesh by specifying two vectors . |
46,958 | def centroid ( self ) : if self . v is None : raise ValueError ( 'Mesh has no vertices; centroid is not defined' ) return np . mean ( self . v , axis = 0 ) | Return the geometric center . |
46,959 | def floor_point ( self ) : floor_point = self . centroid floor_point [ 1 ] = self . v [ : , 1 ] . min ( ) return floor_point | Return the point on the floor that lies below the centroid . |
46,960 | def apex ( self , axis ) : from blmath . geometry . apex import apex return apex ( self . v , axis ) | Find the most extreme vertex in the direction of the axis provided . |
46,961 | def cut_across_axis ( self , dim , minval = None , maxval = None ) : vertex_mask = np . ones ( ( len ( self . v ) , ) , dtype = bool ) if minval is not None : predicate = self . v [ : , dim ] >= minval vertex_mask = np . logical_and ( vertex_mask , predicate ) if maxval is not None : predicate = self . v [ : , dim ] <= maxval vertex_mask = np . logical_and ( vertex_mask , predicate ) vertex_indices = np . flatnonzero ( vertex_mask ) self . keep_vertices ( vertex_indices ) return vertex_indices | Cut the mesh by a plane discarding vertices that lie behind that plane . Or cut the mesh by two parallel planes discarding vertices that lie outside them . |
46,962 | def surface_areas ( self ) : e_1 = self . v [ self . f [ : , 1 ] ] - self . v [ self . f [ : , 0 ] ] e_2 = self . v [ self . f [ : , 2 ] ] - self . v [ self . f [ : , 0 ] ] cross_products = np . array ( [ e_1 [ : , 1 ] * e_2 [ : , 2 ] - e_1 [ : , 2 ] * e_2 [ : , 1 ] , e_1 [ : , 2 ] * e_2 [ : , 0 ] - e_1 [ : , 0 ] * e_2 [ : , 2 ] , e_1 [ : , 0 ] * e_2 [ : , 1 ] - e_1 [ : , 1 ] * e_2 [ : , 0 ] ] ) . T return ( 0.5 ) * ( ( cross_products ** 2. ) . sum ( axis = 1 ) ** 0.5 ) | returns the surface area of each face |
46,963 | def purge_items ( app , env , docname ) : keys = list ( env . traceability_all_items . keys ( ) ) for key in keys : if env . traceability_all_items [ key ] [ 'docname' ] == docname : del env . traceability_all_items [ key ] | Clean if existing item entries in traceability_all_items environment variable for all the source docs being purged . |
46,964 | def process_item_nodes ( app , doctree , fromdocname ) : env = app . builder . env all_items = sorted ( env . traceability_all_items , key = naturalsortkey ) for node in doctree . traverse ( item_matrix ) : table = nodes . table ( ) tgroup = nodes . tgroup ( ) left_colspec = nodes . colspec ( colwidth = 5 ) right_colspec = nodes . colspec ( colwidth = 5 ) tgroup += [ left_colspec , right_colspec ] tgroup += nodes . thead ( '' , nodes . row ( '' , nodes . entry ( '' , nodes . paragraph ( '' , 'Source' ) ) , nodes . entry ( '' , nodes . paragraph ( '' , 'Target' ) ) ) ) tbody = nodes . tbody ( ) tgroup += tbody table += tgroup for source_item in all_items : if re . match ( node [ 'source' ] , source_item ) : row = nodes . row ( ) left = nodes . entry ( ) left += make_item_ref ( app , env , fromdocname , env . traceability_all_items [ source_item ] ) right = nodes . entry ( ) for target_item in all_items : if ( re . match ( node [ 'target' ] , target_item ) and are_related ( env , source_item , target_item , node [ 'type' ] ) ) : right += make_item_ref ( app , env , fromdocname , env . traceability_all_items [ target_item ] ) row += left row += right tbody += row node . replace_self ( table ) for node in doctree . traverse ( item_list ) : content = nodes . bullet_list ( ) for item in all_items : if re . match ( node [ 'filter' ] , item ) : bullet_list_item = nodes . list_item ( ) paragraph = nodes . paragraph ( ) paragraph . append ( make_item_ref ( app , env , fromdocname , env . traceability_all_items [ item ] ) ) bullet_list_item . append ( paragraph ) content . append ( bullet_list_item ) node . replace_self ( content ) for node in doctree . traverse ( pending_item_xref ) : new_node = make_refnode ( app . builder , fromdocname , fromdocname , 'ITEM_NOT_FOUND' , node [ 0 ] . deepcopy ( ) , node [ 'reftarget' ] + '??' ) if node [ 'reftarget' ] in env . traceability_all_items : item_info = env . traceability_all_items [ node [ 'reftarget' ] ] try : new_node = make_refnode ( app . builder , fromdocname , item_info [ 'docname' ] , item_info [ 'target' ] [ 'refid' ] , node [ 0 ] . deepcopy ( ) , node [ 'reftarget' ] ) except NoUri : pass else : env . warn_node ( 'Traceability: item %s not found' % node [ 'reftarget' ] , node ) node . replace_self ( new_node ) | This function should be triggered upon doctree - resolved event |
46,965 | def initialize_environment ( app ) : env = app . builder . env if not hasattr ( env , 'traceability_all_items' ) : env . traceability_all_items = { } update_available_item_relationships ( app ) | Perform initializations needed before the build process starts . |
46,966 | def make_item_ref ( app , env , fromdocname , item_info ) : id = item_info [ 'target' ] [ 'refid' ] if item_info [ 'caption' ] != '' : caption = ', ' + item_info [ 'caption' ] else : caption = '' para = nodes . paragraph ( ) newnode = nodes . reference ( '' , '' ) innernode = nodes . emphasis ( id + caption , id + caption ) newnode [ 'refdocname' ] = item_info [ 'docname' ] try : newnode [ 'refuri' ] = app . builder . get_relative_uri ( fromdocname , item_info [ 'docname' ] ) newnode [ 'refuri' ] += '#' + id except NoUri : pass newnode . append ( innernode ) para += newnode return para | Creates a reference node for an item embedded in a paragraph . Reference text adds also a caption if it exists . |
46,967 | def naturalsortkey ( s ) : return [ int ( part ) if part . isdigit ( ) else part for part in re . split ( '([0-9]+)' , s ) ] | Natural sort order |
46,968 | def are_related ( env , source , target , relationships ) : if not relationships : relationships = list ( env . relationships . keys ( ) ) for rel in relationships : if ( target in env . traceability_all_items [ source ] [ rel ] or source in env . traceability_all_items [ target ] [ env . relationships [ rel ] ] ) : return True return False | Returns True if source and target items are related according a list relationships of relationship types . False is returned otherwise |
46,969 | def MeshViewer ( titlebar = 'Mesh Viewer' , static_meshes = None , static_lines = None , uid = None , autorecenter = True , keepalive = False , window_width = 1280 , window_height = 960 , snapshot_camera = None ) : if not test_for_opengl ( ) : return Dummy ( ) mv = MeshViewerLocal ( shape = ( 1 , 1 ) , uid = uid , titlebar = titlebar , keepalive = keepalive , window_width = window_width , window_height = window_height ) result = mv . get_subwindows ( ) [ 0 ] [ 0 ] result . snapshot_camera = snapshot_camera if static_meshes : result . static_meshes = static_meshes if static_lines : result . static_lines = static_lines result . autorecenter = autorecenter return result | Allows visual inspection of geometric primitives . |
46,970 | def MeshViewers ( shape = ( 1 , 1 ) , titlebar = "Mesh Viewers" , keepalive = False , window_width = 1280 , window_height = 960 ) : if not test_for_opengl ( ) : return Dummy ( ) mv = MeshViewerLocal ( shape = shape , titlebar = titlebar , uid = None , keepalive = keepalive , window_width = window_width , window_height = window_height ) return mv . get_subwindows ( ) | Allows subplot - style inspection of primitives in multiple subwindows . |
46,971 | def on_click ( self , button , button_state , cursor_x , cursor_y ) : self . isdragging = False if button == glut . GLUT_LEFT_BUTTON and button_state == glut . GLUT_UP : self . lastrot = copy . copy ( self . thisrot ) elif button == glut . GLUT_LEFT_BUTTON and button_state == glut . GLUT_DOWN : self . lastrot = copy . copy ( self . thisrot ) self . isdragging = True mouse_pt = arcball . Point2fT ( cursor_x , cursor_y ) self . arcball . click ( mouse_pt ) elif button == glut . GLUT_RIGHT_BUTTON and button_state == glut . GLUT_DOWN : if hasattr ( self , 'event_port' ) : self . mouseclick_port = self . event_port del self . event_port if hasattr ( self , 'mouseclick_port' ) : self . send_mouseclick_to_caller ( cursor_x , cursor_y ) elif button == glut . GLUT_MIDDLE_BUTTON and button_state == glut . GLUT_DOWN : if hasattr ( self , 'event_port' ) : self . mouseclick_port = self . event_port del self . event_port if hasattr ( self , 'mouseclick_port' ) : self . send_mouseclick_to_caller ( cursor_x , cursor_y , button = 'middle' ) glut . glutPostRedisplay ( ) | Mouse button clicked . Glut calls this function when a mouse button is clicked or released . |
46,972 | def _compute_cell_circumcenters ( self ) : alpha = self . _zeta / numpy . sum ( self . _zeta , axis = 0 ) self . _circumcenters = numpy . sum ( alpha [ None ] . T * self . node_coords [ self . cells [ "nodes" ] ] , axis = 1 ) return | Computes the center of the circumsphere of each cell . |
46,973 | def show_edge ( self , edge_id ) : from mpl_toolkits . mplot3d import Axes3D from matplotlib import pyplot as plt if "faces" not in self . cells : self . create_cell_face_relationships ( ) if "edges" not in self . faces : self . create_face_edge_relationships ( ) fig = plt . figure ( ) ax = fig . gca ( projection = Axes3D . name ) plt . axis ( "equal" ) adj_face_ids = numpy . where ( ( self . faces [ "edges" ] == edge_id ) . any ( axis = 1 ) ) [ 0 ] adj_cell_ids = numpy . where ( numpy . in1d ( self . cells [ "faces" ] , adj_face_ids ) . reshape ( self . cells [ "faces" ] . shape ) . any ( axis = 1 ) ) [ 0 ] adj_edge_ids = numpy . unique ( [ adj_edge_id for adj_cell_id in adj_cell_ids for face_id in self . cells [ "faces" ] [ adj_cell_id ] for adj_edge_id in self . faces [ "edges" ] [ face_id ] ] ) col = "k" for adj_edge_id in adj_edge_ids : x = self . node_coords [ self . edges [ "nodes" ] [ adj_edge_id ] ] ax . plot ( x [ : , 0 ] , x [ : , 1 ] , x [ : , 2 ] , col ) x = self . node_coords [ self . edges [ "nodes" ] [ edge_id ] ] ax . plot ( x [ : , 0 ] , x [ : , 1 ] , x [ : , 2 ] , color = col , linewidth = 3.0 ) X = self . node_coords for cell_id in adj_cell_ids : cc = self . _circumcenters [ cell_id ] x = X [ self . node_face_cells [ ... , [ cell_id ] ] ] face_ccs = compute_triangle_circumcenters ( x , self . ei_dot_ei , self . ei_dot_ej ) ax . plot ( face_ccs [ ... , 0 ] . flatten ( ) , face_ccs [ ... , 1 ] . flatten ( ) , face_ccs [ ... , 2 ] . flatten ( ) , "go" , ) for face_cc in face_ccs : ax . plot ( [ cc [ ... , 0 ] , face_cc [ ... , 0 ] ] , [ cc [ ... , 1 ] , face_cc [ ... , 1 ] ] , [ cc [ ... , 2 ] , face_cc [ ... , 2 ] ] , "b-" , ) cc = self . _circumcenters [ adj_cell_ids ] ax . plot ( cc [ : , 0 ] , cc [ : , 1 ] , cc [ : , 2 ] , "ro" ) return | Displays edge with ce_ratio . |
46,974 | def parse_int ( text , fallback = None ) : try : if isinstance ( text , six . integer_types ) : return text elif isinstance ( text , six . string_types ) : return int ( text ) else : return fallback except ValueError : return fallback | Try to extract an integer from a string return the fallback if that s not possible . |
46,975 | def _load_table ( self , name ) : table = self . _tables . get ( name , None ) if table is not None : return table if not self . engine . has_table ( name ) : raise BindingException ( 'Table does not exist: %r' % name , table = name ) table = Table ( name , self . meta , autoload = True ) self . _tables [ name ] = table return table | Reflect a given table from the database . |
46,976 | def fact_pk ( self ) : keys = [ c for c in self . fact_table . columns if c . primary_key ] return keys [ 0 ] | Try to determine the primary key of the fact table for use in fact table counting . If more than one column exists return the first column of the pk . |
46,977 | def members ( self , ref , cuts = None , order = None , page = None , page_size = None ) : def prep ( cuts , ref , order , columns = None ) : q = select ( columns = columns ) bindings = [ ] cuts , q , bindings = Cuts ( self ) . apply ( q , bindings , cuts ) fields , q , bindings = Fields ( self ) . apply ( q , bindings , ref , distinct = True ) ordering , q , bindings = Ordering ( self ) . apply ( q , bindings , order , distinct = fields [ 0 ] ) q = self . restrict_joins ( q , bindings ) return q , bindings , cuts , fields , ordering count = count_results ( self , prep ( cuts , ref , order , [ 1 ] ) [ 0 ] ) q , bindings , cuts , fields , ordering = prep ( cuts , ref , order ) page , q = Pagination ( self ) . apply ( q , page , page_size ) q = self . restrict_joins ( q , bindings ) return { 'total_member_count' : count , 'data' : list ( generate_results ( self , q ) ) , 'cell' : cuts , 'fields' : fields , 'order' : ordering , 'page' : page [ 'page' ] , 'page_size' : page [ 'page_size' ] } | List all the distinct members of the given reference filtered and paginated . If the reference describes a dimension all attributes are returned . |
46,978 | def facts ( self , fields = None , cuts = None , order = None , page = None , page_size = None , page_max = None ) : def prep ( cuts , columns = None ) : q = select ( columns = columns ) . select_from ( self . fact_table ) bindings = [ ] _ , q , bindings = Cuts ( self ) . apply ( q , bindings , cuts ) q = self . restrict_joins ( q , bindings ) return q , bindings count = count_results ( self , prep ( cuts , [ 1 ] ) [ 0 ] ) q , bindings = prep ( cuts ) fields , q , bindings = Fields ( self ) . apply ( q , bindings , fields ) ordering , q , bindings = Ordering ( self ) . apply ( q , bindings , order ) page , q = Pagination ( self ) . apply ( q , page , page_size , page_max ) q = self . restrict_joins ( q , bindings ) return { 'total_fact_count' : count , 'data' : list ( generate_results ( self , q ) ) , 'cell' : cuts , 'fields' : fields , 'order' : ordering , 'page' : page [ 'page' ] , 'page_size' : page [ 'page_size' ] } | List all facts in the cube returning only the specified references if these are specified . |
46,979 | def compute_cardinalities ( self ) : for dimension in self . model . dimensions : result = self . members ( dimension . ref , page_size = 0 ) dimension . spec [ 'cardinality' ] = result . get ( 'total_member_count' ) | This will count the number of distinct values for each dimension in the dataset and add that count to the model so that it can be used as a hint by UI components . |
46,980 | def restrict_joins ( self , q , bindings ) : if len ( q . froms ) == 1 : return q else : for binding in bindings : if binding . table == self . fact_table : continue concept = self . model [ binding . ref ] if isinstance ( concept , Dimension ) : dimension = concept else : dimension = concept . dimension dimension_table , key_col = dimension . key_attribute . bind ( self ) if binding . table != dimension_table : raise BindingException ( 'Attributes must be of same table as ' 'as their dimension key' ) join_column_name = dimension . join_column_name if isinstance ( join_column_name , string_types ) : try : join_column = self . fact_table . columns [ join_column_name ] except KeyError : raise BindingException ( "Join column '%s' for %r not in fact table." % ( dimension . join_column_name , dimension ) ) else : if not isinstance ( join_column_name , list ) or len ( join_column_name ) != 2 : raise BindingException ( "Join column '%s' for %r should be either a string or a 2-tuple." % ( join_column_name , dimension ) ) try : join_column = self . fact_table . columns [ join_column_name [ 0 ] ] except KeyError : raise BindingException ( "Join column '%s' for %r not in fact table." % ( dimension . join_column_name [ 0 ] , dimension ) ) try : key_col = dimension_table . columns [ join_column_name [ 1 ] ] except KeyError : raise BindingException ( "Join column '%s' for %r not in dimension table." % ( dimension . join_column_name [ 1 ] , dimension ) ) q = q . where ( join_column == key_col ) return q | Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions . If a single table is used for the query no unnecessary joins are performed . If more than one table are referenced this ensures their returned rows are connected via the fact table . |
46,981 | def order_manually ( sub_commands ) : order = [ "start" , "projects" , ] ordered = [ ] commands = dict ( zip ( [ cmd for cmd in sub_commands ] , sub_commands ) ) for k in order : ordered . append ( commands . get ( k , "" ) ) if k in commands : del commands [ k ] for k in commands : ordered . append ( commands [ k ] ) return ordered | Order sub - commands for display |
46,982 | def concepts ( self ) : for measure in self . measures : yield measure for aggregate in self . aggregates : yield aggregate for dimension in self . dimensions : yield dimension for attribute in dimension . attributes : yield attribute | Return all existing concepts i . e . dimensions measures and attributes within the model . |
46,983 | def match ( self , ref ) : try : concept = self [ ref ] if not isinstance ( concept , Dimension ) : return [ concept ] return [ a for a in concept . attributes ] except KeyError : return [ ] | Get all concepts matching this ref . For a dimension that is all its attributes but not the dimension itself . |
46,984 | def add ( self , lineitem ) : if lineitem [ 'ProductName' ] : self . _lineitems . append ( lineitem ) if lineitem [ 'BlendedCost' ] : self . _blended_cost += lineitem [ 'BlendedCost' ] if lineitem [ 'UnBlendedCost' ] : self . _unblended_cost += lineitem [ 'UnBlendedCost' ] | Add a line item record to this Costs object . |
46,985 | def filter ( self , filters ) : subset = Costs ( self . _columns ) filters = [ ( col , re . compile ( regex ) ) for col , regex in filters ] for lineitem in self . _lineitems : for filter in filters : if filter [ 1 ] . search ( lineitem [ filter [ 0 ] ] ) is None : continue subset . add ( lineitem ) return subset | Pass in a list of tuples where each tuple represents one filter . The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against . If the regular expression matches the value in that column that lineitem will be included in the new Costs object returned . |
46,986 | def query ( self , query , args = None ) : self . affectedRows = None self . lastError = None cursor = None try : try : self . _GetConnection ( ) log . logger . debug ( 'Running query "%s" with args "%s"' , query , args ) self . conn . query = query cursor = self . conn . getCursor ( ) self . affectedRows = cursor . execute ( query , args ) self . lastInsertID = self . conn . connection . insert_id ( ) self . rowcount = cursor . rowcount log . logger . debug ( 'Query Resulted in %s affected rows, %s rows returned, %s last insert id' , self . affectedRows , self . lastInsertID , self . rowcount ) self . record = cursor . fetchall ( ) self . conn . updateCheckTime ( ) except Exception , e : self . lastError = e self . affectedRows = None finally : if cursor is not None : cursor . close ( ) self . _ReturnConnection ( ) if self . lastError is not None : raise self . lastError else : return self . affectedRows | Execute the passed in query against the database |
46,987 | def queryOne ( self , query , args = None ) : self . affectedRows = None self . lastError = None cursor = None try : try : self . _GetConnection ( ) self . conn . query = query cursor = self . conn . getCursor ( ) self . affectedRows = cursor . execute ( query , args ) self . conn . updateCheckTime ( ) while 1 : row = cursor . fetchone ( ) if row is None : break else : self . record = row yield row self . rowcount = cursor . rowcount except Exception , e : self . lastError = e self . affectedRows = None finally : if cursor is not None : cursor . close ( ) self . _ReturnConnection ( ) if self . lastError is not None : raise self . lastError else : raise StopIteration | Execute the passed in query against the database . Uses a Generator & fetchone to reduce your process memory size . |
46,988 | def queryMulti ( self , queries ) : self . lastError = None self . affectedRows = 0 self . rowcount = None self . record = None cursor = None try : try : self . _GetConnection ( ) cursor = self . conn . getCursor ( ) for query in queries : self . conn . query = query if query . __class__ == [ ] . __class__ : self . affectedRows += cursor . execute ( query [ 0 ] , query [ 1 ] ) else : self . affectedRows += cursor . execute ( query ) self . conn . updateCheckTime ( ) except Exception , e : self . lastError = e finally : if cursor is not None : cursor . close ( ) self . _ReturnConnection ( ) if self . lastError is not None : raise self . lastError else : return self . affectedRows | Execute a series of Deletes Inserts & Updates in the Queires List |
46,989 | def _GetConnection ( self ) : while self . conn is None : self . conn = Pool ( ) . GetConnection ( self . connInfo ) if self . conn is not None : break else : time . sleep ( 1 ) | Retieves a prelocked connection from the Pool |
46,990 | def _ReturnConnection ( self ) : if self . conn is not None : if self . connInfo . commitOnEnd is True or self . commitOnEnd is True : self . conn . Commit ( ) Pool ( ) . returnConnection ( self . conn ) self . conn = None | Returns a connection back to the pool |
46,991 | def bind ( self , cube ) : if self . measure : table , column = self . measure . bind ( cube ) else : table , column = cube . fact_table , cube . fact_pk column = getattr ( func , self . function ) ( column ) column = column . label ( self . ref ) column . quote = True return table , column | When one column needs to match use the key . |
46,992 | def retrieve_public_key ( user_repo ) : url = 'https://api.travis-ci.org/repos/{}/key' . format ( user_repo ) response = requests . get ( url ) try : return response . json ( ) [ 'key' ] . replace ( ' RSA ' , ' ' ) except KeyError : username , repository = user_repo . split ( '/' ) raise InvalidCredentialsError ( "Either the username: '{}' or the repository: '{}' does not exist. Please enter a valid username or repository name. The username and repository name are both case sensitive." . format ( username , repository ) ) | Retrieve the public key from the Travis API . |
46,993 | def encrypt_key ( key , password ) : public_key = load_pem_public_key ( key . encode ( ) , default_backend ( ) ) encrypted_password = public_key . encrypt ( password , PKCS1v15 ( ) ) return base64 . b64encode ( encrypted_password ) . decode ( 'ascii' ) | Encrypt the password with the public key and return an ASCII representation . |
46,994 | def dump_travis_configuration ( config , path ) : with open ( path , 'w' ) as config_file : ordered_dump ( config , config_file , default_flow_style = False ) | Dump the travis configuration settings to the travis . yml file . |
46,995 | def show_distribution_section ( config , title , section_name ) : payload = requests . get ( config . apps_url ) . json ( ) distributions = sorted ( payload . keys ( ) , reverse = True ) latest_distribution = payload [ distributions [ 0 ] ] click . echo ( "{} {}" . format ( "Release" . rjust ( 7 ) , title ) ) click . echo ( "------- ---------------" ) section = latest_distribution [ section_name ] names = sorted ( section . keys ( ) ) for name in names : click . echo ( "{} {}" . format ( section [ name ] . rjust ( 7 ) , name ) ) | Obtain distribution data and display latest distribution section i . e . demos or apps or themes . |
46,996 | def validate_django_compatible_with_python ( ) : python_version = sys . version [ : 5 ] django_version = django . get_version ( ) if sys . version_info == ( 2 , 7 ) and django_version >= "2" : click . BadArgumentUsage ( "Please install Django v1.11 for Python {}, or switch to Python >= v3.4" . format ( python_version ) ) | Verify Django 1 . 11 is present if Python 2 . 7 is active |
46,997 | def keep_vertices ( self , indices_to_keep , ret_kept_edges = False ) : if self . v is None : return initial_num_verts = self . v . shape [ 0 ] if self . e is not None : initial_num_edges = self . e . shape [ 0 ] e_indices_to_keep = self . all_edges_with_verts ( indices_to_keep , as_boolean = True ) self . v = self . v [ indices_to_keep ] if self . e is not None : v_old_to_new = np . zeros ( initial_num_verts , dtype = int ) e_old_to_new = np . zeros ( initial_num_edges , dtype = int ) v_old_to_new [ indices_to_keep ] = np . arange ( len ( indices_to_keep ) , dtype = int ) self . e = v_old_to_new [ self . e [ e_indices_to_keep ] ] e_old_to_new [ e_indices_to_keep ] = np . arange ( self . e . shape [ 0 ] , dtype = int ) else : e_indices_to_keep = [ ] return np . nonzero ( e_indices_to_keep ) [ 0 ] if ret_kept_edges else self | Keep the given vertices and discard the others and any edges to which they may belong . |
46,998 | def lock ( self , block = True ) : self . _locked = True return self . _lock . acquire ( block ) | Lock connection from being used else where |
46,999 | def release ( self ) : if self . _locked is True : self . _locked = False self . _lock . release ( ) | Release the connection lock |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.