signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def bdd ( * keywords ) : """Run tests matching keywords ."""
settings = _personal_settings ( ) . data _storybook ( ) . with_params ( ** { "python version" : settings [ "params" ] [ "python version" ] } ) . only_uninherited ( ) . shortcut ( * keywords ) . play ( )
def _GetSerializedAttributeContainerList ( self , container_type ) : """Retrieves a serialized attribute container list . Args : container _ type ( str ) : attribute container type . Returns : SerializedAttributeContainerList : serialized attribute container list ."""
container_list = self . _serialized_attribute_containers . get ( container_type , None ) if not container_list : container_list = SerializedAttributeContainerList ( ) self . _serialized_attribute_containers [ container_type ] = container_list return container_list
def method_already_there ( object_type , method_name , this_class_only = False ) : """Returns True if method ` method _ name ` is already implemented by object _ type , that is , its implementation differs from the one in ` object ` . : param object _ type : : param method _ name : : param this _ class _ on...
if this_class_only : return method_name in vars ( object_type ) # or object _ type . _ _ dict _ _ else : try : method = getattr ( object_type , method_name ) except AttributeError : return False else : return method is not None and method is not getattr ( object , method_name...
def get_many ( self , type : Type [ T ] , query : Mapping [ str , Any ] , streaming : bool = False ) -> Iterable [ T ] : """Gets a query from the data pipeline , which contains a request for multiple objects . 1 ) Extracts the query the sequence of data sources . 2 ) Inserts the results into the data sinks ( if...
LOGGER . info ( "Getting SourceHandlers for \"{type}\"" . format ( type = type . __name__ ) ) try : handlers = self . _get_types [ type ] except KeyError : try : LOGGER . info ( "Building new SourceHandlers for \"{type}\"" . format ( type = type . __name__ ) ) handlers = self . _get_handlers ( t...
def process_response ( self , request , response ) : """Disconnects the signal receiver to prevent it from staying active ."""
if hasattr ( threadlocal , 'auditlog' ) : pre_save . disconnect ( sender = LogEntry , dispatch_uid = threadlocal . auditlog [ 'signal_duid' ] ) return response
def attr_list ( label = None , kwargs = None , attributes = None ) : """Return assembled DOT attribute list string . Sorts ` ` kwargs ` ` and ` ` attributes ` ` if they are plain dicts ( to avoid unpredictable order from hash randomization in Python 3 versions ) . > > > attr _ list ( ) > > > attr _ list ( '...
content = a_list ( label , kwargs , attributes ) if not content : return '' return ' [%s]' % content
def isMethodAllowed ( self , method ) : """Checks if the analysis can follow the method specified , either if the method was assigned directly ( by using " Allows manual entry of results " ) or indirectly via Instrument ( " Allows instrument entry of results " ) in Analysis Service Edit view . Param method ...
if isinstance ( method , str ) : uid = method else : uid = method . UID ( ) return uid in self . getAllowedMethodUIDs ( )
def space_exists ( args ) : """Determine if the named space exists in the given project ( namespace )"""
# The return value is the INVERSE of UNIX exit status semantics , ( where # 0 = good / true , 1 = bad / false ) , so to check existence in UNIX one would do # if ! fissfc space _ exists blah ; then # fi try : r = fapi . get_workspace ( args . project , args . workspace ) fapi . _check_response_code ( r , 200 ) ...
def get_file ( self , key , file ) : """Write contents of key to file Like : meth : ` . KeyValueStore . put _ file ` , this method allows backends to implement a specialized function if data needs to be written to disk or streamed . If * file * is a string , contents of * key * are written to a newly crea...
self . _check_valid_key ( key ) if isinstance ( file , str ) : return self . _get_filename ( key , file ) else : return self . _get_file ( key , file )
def parsePropertyValue ( self ) : """Called when " [ " encountered ( but not consumed ) , ends when the next property , node , or variation encountered . Parses and returns a list of property values . Raises ' PropertyValueParseError ' if there is a problem ."""
pvlist = [ ] while self . index < self . datalen : match = self . rePropertyStart . match ( self . data , self . index ) if match : self . index = match . end ( ) v = "" # value # scan for escaped characters ( using ' \ ' ) , unescape them ( remove linebreaks ) mend = sel...
def getnodefieldname ( idfobject , endswith , fluid = None , startswith = None ) : """return the field name of the node fluid is only needed if there are air and water nodes fluid is Air or Water or ' ' . if the fluid is Steam , use Water"""
if startswith is None : startswith = '' if fluid is None : fluid = '' nodenames = getfieldnamesendswith ( idfobject , endswith ) nodenames = [ name for name in nodenames if name . startswith ( startswith ) ] fnodenames = [ nd for nd in nodenames if nd . find ( fluid ) != - 1 ] fnodenames = [ name for name in fn...
def logpdf ( self , mu ) : """Log PDF for Normal prior Parameters mu : float Latent variable for which the prior is being formed over Returns - log ( p ( mu ) )"""
if self . transform is not None : mu = self . transform ( mu ) return - np . log ( float ( self . sigma0 ) ) - ( 0.5 * ( mu - self . mu0 ) ** 2 ) / float ( self . sigma0 ** 2 )
def publish ( self , topic , message = None , qos = 0 , retain = False ) : """Publish a message to a topic with specified qos and retained flag . It is required that a connection has been established using ` Connect ` keyword before using this keyword . ` topic ` topic to which the message will be published ...
logger . info ( 'Publish topic: %s, message: %s, qos: %s, retain: %s' % ( topic , message , qos , retain ) ) self . _mid = - 1 self . _mqttc . on_publish = self . _on_publish result , mid = self . _mqttc . publish ( topic , message , int ( qos ) , retain ) if result != 0 : raise RuntimeError ( 'Error publishing: %s...
def list_feeds ( self ) : """Output a list of all feed names"""
feeds = configparser . ConfigParser ( ) feeds . read ( self . data_filename ) return feeds . sections ( )
def get_bytes ( self , * args , ** kwargs ) : """no string decoding performed"""
return super ( XClient , self ) . get ( * args , ** kwargs )
def log_results ( ) : """This is the callback that is run once the Async task is finished . It takes the output from grep and logs it ."""
from furious . context import get_current_async # Get the recently finished Async object . async = get_current_async ( ) # Pull out the result data and log it . for result in async . result : logging . info ( result )
def parse_definition ( self , definition ) : """Parse the basic structure of both provided and requested entities : param definition : string encoding an entity : return : tuple of entity type , alias and attributes"""
type = definition [ 0 ] alias = None attributes = { } for part in definition [ 1 : ] : if '=' in part : key , value = part . split ( '=' , 1 ) attributes [ key ] = set ( value . split ( ',' ) ) elif alias is None : alias = part else : raise ValueError ( 'entity name already d...
def delete_fastqs ( job , patient_dict ) : """Delete the fastqs from the job Store once their purpose has been achieved ( i . e . after all mapping steps ) : param dict patient _ dict : Dict of list of input fastqs"""
for key in patient_dict . keys ( ) : if 'fastq' not in key : continue job . fileStore . logToMaster ( 'Deleting "%s:%s" ' % ( patient_dict [ 'patient_id' ] , key ) + 'from the filestore.' ) job . fileStore . deleteGlobalFile ( patient_dict [ key ] ) return None
def add_star ( G , nodes , t , ** attr ) : """Add a star at time t . The first node in nodes is the middle of the star . It is connected to all other nodes . Parameters G : graph A DyNetx graph nodes : iterable container A container of nodes . t : snapshot id ( default = None ) snapshot id See A...
nlist = iter ( nodes ) v = next ( nlist ) edges = ( ( v , n ) for n in nlist ) G . add_interactions_from ( edges , t , ** attr )
def hamiltonian ( Ep , epsilonp , detuning_knob , rm , omega_level , omega_laser , xi , RWA = True , RF = True ) : r"""Return symbolic Hamiltonian . > > > from sympy import zeros , pi , pprint , symbols > > > Ne = 3 > > > Nl = 2 > > > Ep , omega _ laser = define _ laser _ variables ( Nl ) > > > epsilonp =...
# We check what RF is . if type ( RF ) == list : theta = RF [ : ] RF = True elif type ( RF ) == Matrix : theta = [ RF [ i , 0 ] for i in range ( RF . shape [ 0 ] ) ] RF = True elif RF : # theta should be calculate here ! s = "We are still missing automatic calculation of phase " s += "transforma...
def validate_current_versions ( self ) : # type : ( ) - > bool """Can a version be found ? Are all versions currently the same ? Are they valid sem ver ? : return :"""
versions = self . all_current_versions ( ) for _ , version in versions . items ( ) : if "Invalid Semantic Version" in version : logger . error ( "Invalid versions, can't compare them, can't determine if in sync" ) return False if not versions : logger . warning ( "Found no versions, will use def...
def get_object_by_natural_key ( self , app_label , model_name , object_id ) : """Return a model based on a natural key . This is a utility function for : func : ` get _ edited _ object ` ."""
try : model_type = ContentType . objects . get_by_natural_key ( app_label , model_name ) except ContentType . DoesNotExist : return None # Pointless to fetch the object , if there is no URL to generate # Avoid another database query . ModelClass = model_type . model_class ( ) if not hasattr ( ModelClass , 'get_...
def get_from_ipfs_and_checkhash ( ipfs_client , ipfs_hash_base58 , validate = True ) : """Get file from ipfs We must check the hash becasue we cannot believe that ipfs _ client wasn ' t been compromise"""
if validate : from snet_cli . resources . proto . unixfs_pb2 import Data from snet_cli . resources . proto . merckledag_pb2 import MerkleNode # No nice Python library to parse ipfs blocks , so do it ourselves . block_data = ipfs_client . block_get ( ipfs_hash_base58 ) mn = MerkleNode ( ) mn . Pa...
def _synchronize_node ( configfile , node ) : """Performs the Synchronize step of a Chef run : Uploads all cookbooks , all roles and all databags to a node and add the patch for data bags Returns the node object of the node which is about to be configured , or None if this node object cannot be found ."""
msg = "Synchronizing nodes, environments, roles, cookbooks and data bags..." if env . parallel : msg = "[{0}]: {1}" . format ( env . host_string , msg ) print ( msg ) # First upload node . json remote_file = '/etc/chef/node.json' put ( configfile , remote_file , use_sudo = True , mode = 400 ) with hide ( 'stdout' )...
def cvxEDA ( eda , sampling_rate = 1000 , tau0 = 2. , tau1 = 0.7 , delta_knot = 10. , alpha = 8e-4 , gamma = 1e-2 , solver = None , verbose = False , options = { 'reltol' : 1e-9 } ) : """A convex optimization approach to electrodermal activity processing ( CVXEDA ) . This function implements the cvxEDA algorithm ...
frequency = 1 / sampling_rate # Normalizing signal eda = z_score ( eda ) eda = np . array ( eda ) [ : , 0 ] n = len ( eda ) eda = eda . astype ( 'double' ) eda = cv . matrix ( eda ) # bateman ARMA model a1 = 1. / min ( tau1 , tau0 ) # a1 > a0 a0 = 1. / max ( tau1 , tau0 ) ar = np . array ( [ ( a1 * frequency + 2. ) * (...
def _add_gainloss_to_output ( out , data ) : """Add gainloss based on genes , helpful for identifying changes in smaller genes ."""
out_file = "%s-gainloss.txt" % os . path . splitext ( out [ "cns" ] ) [ 0 ] if not utils . file_exists ( out_file ) : with file_transaction ( data , out_file ) as tx_out_file : cmd = [ os . path . join ( os . path . dirname ( sys . executable ) , "cnvkit.py" ) , "gainloss" , "-s" , out [ "cns" ] , "-o" , tx...
def get ( self ) : """Get a JSON - ready representation of this SubscriptionTracking . : returns : This SubscriptionTracking , ready for use in a request body . : rtype : dict"""
subscription_tracking = { } if self . enable is not None : subscription_tracking [ "enable" ] = self . enable if self . text is not None : subscription_tracking [ "text" ] = self . text . get ( ) if self . html is not None : subscription_tracking [ "html" ] = self . html . get ( ) if self . substitution_tag...
def unpack_bitstring ( length , is_float , is_signed , bits ) : # type : ( int , bool , bool , typing . Any ) - > typing . Union [ float , int ] """returns a value calculated from bits : param length : length of signal in bits : param is _ float : value is float : param bits : value as bits ( array / iterable...
if is_float : types = { 32 : '>f' , 64 : '>d' } float_type = types [ length ] value , = struct . unpack ( float_type , bytearray ( int ( '' . join ( b ) , 2 ) for b in grouper ( bits , 8 ) ) ) else : value = int ( bits , 2 ) if is_signed and bits [ 0 ] == '1' : value -= ( 1 << len ( bits ) )...
def _async_raise ( tid , exctype ) : """raises the exception , performs cleanup if needed 参考 : https : / / www . oschina . net / question / 172446_2159505"""
tid = ctypes . c_long ( tid ) if not inspect . isclass ( exctype ) : exctype = type ( exctype ) res = ctypes . pythonapi . PyThreadState_SetAsyncExc ( tid , ctypes . py_object ( exctype ) ) if res == 0 : raise ValueError ( "invalid thread id" ) elif res != 1 : # " " " if it returns a number greater than one , y...
def from_disk ( self , path , ** kwargs ) : """Load the entity ruler from a file . Expects a file containing newline - delimited JSON ( JSONL ) with one entry per line . path ( unicode / Path ) : The JSONL file to load . * * kwargs : Other config paramters , mostly for consistency . RETURNS ( EntityRuler ) ...
path = ensure_path ( path ) path = path . with_suffix ( ".jsonl" ) patterns = srsly . read_jsonl ( path ) self . add_patterns ( patterns ) return self
def plot_by_correct ( self , y , is_correct ) : """Plots the images which correspond to the selected class ( y ) and to the specific case ( prediction is correct - is _ true = True , prediction is wrong - is _ true = False ) Arguments : y ( int ) : the selected class is _ correct ( boolean ) : a boolean flag ...
return self . plot_val_with_title ( self . most_by_correct ( y , is_correct ) , y )
def create_node ( self , network , participant ) : """Make a new node for participants ."""
if network . role == "practice" or network . role == "catch" : return RogersAgentFounder ( network = network , participant = participant ) elif network . size ( type = Agent ) < network . generation_size : return RogersAgentFounder ( network = network , participant = participant ) else : return RogersAgent ...
def cublasDspr ( handle , uplo , n , alpha , x , incx , AP ) : """Rank - 1 operation on real symmetric - packed matrix ."""
status = _libcublas . cublasDspr_v2 ( handle , _CUBLAS_FILL_MODE [ uplo ] , n , ctypes . byref ( ctypes . c_double ( alpha ) ) , int ( x ) , incx , int ( AP ) ) cublasCheckStatus ( status )
def _build_paths ( ) : """Prepare paths for distlib . wheel . Wheel to install into ."""
paths = sysconfig . get_paths ( ) return { "prefix" : sys . prefix , "data" : paths [ "data" ] , "scripts" : paths [ "scripts" ] , "headers" : paths [ "include" ] , "purelib" : paths [ "purelib" ] , "platlib" : paths [ "platlib" ] , }
def get_one ( self , request , ** kwargs ) : """Load a resource ."""
resource = request . match_info . get ( self . name ) if not resource : return None try : return self . collection . where ( self . meta . model_pk == resource ) . get ( ) except Exception : raise RESTNotFound ( reason = 'Resource not found.' )
def PushState ( self , ** _ ) : """Push the current state on the state stack ."""
if self . verbose : logging . debug ( "Storing state %r" , self . state ) self . state_stack . append ( self . state )
def shift_and_scale ( matrix , shift , scale ) : """Shift and scale matrix so its minimum value is placed at ` shift ` and its maximum value is scaled to ` scale `"""
zeroed = matrix - matrix . min ( ) scaled = ( scale - shift ) * ( zeroed / zeroed . max ( ) ) return scaled + shift
def fixup_simple_stmt ( parent , i , stmt_node ) : """if there is a semi - colon all the parts count as part of the same simple _ stmt . We just want the _ _ metaclass _ _ part so we move everything efter the semi - colon into its own simple _ stmt node"""
for semi_ind , node in enumerate ( stmt_node . children ) : if node . type == token . SEMI : # * sigh * break else : return node . remove ( ) # kill the semicolon new_expr = Node ( syms . expr_stmt , [ ] ) new_stmt = Node ( syms . simple_stmt , [ new_expr ] ) while stmt_node . children [ semi_ind : ] : ...
def call_sphinx ( out_type , build_dir = "build" ) : """Call the ` ` sphinx - build ` ` for the given output type and the ` ` make ` ` when the target has this possibility . Parameters out _ type : A builder name for ` ` sphinx - build ` ` . See the full list at ` < http : / / sphinx - doc . org / invocat...
sphinx_string = sphinx_template . format ( build_dir = build_dir , out_type = out_type ) if sphinx . main ( shlex . split ( sphinx_string ) ) != 0 : raise RuntimeError ( "Something went wrong while building '{0}'" . format ( out_type ) ) if out_type in make_target : make_string = make_template . format ( build_...
def _reload_version ( self ) : """Packages installed by distutils ( e . g . numpy or scipy ) , which uses an old safe _ version , and so their version numbers can get mangled when converted to filenames ( e . g . , 1.11.0 . dev0 + 2329eae to 1.11.0 . dev0_2329eae ) . These distributions will not be parsed...
md_version = self . _get_version ( ) if md_version : self . _version = md_version return self
def meryl ( args ) : """% prog meryl folder Run meryl on Illumina reads ."""
p = OptionParser ( meryl . __doc__ ) p . add_option ( "-k" , default = 19 , type = "int" , help = "Kmer size" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) folder , = args K = opts . k cpus = opts . cpus mm = MakeManager ( ) for p , pf in iter_...
def _shock_create ( self , h , shock_type , shock_index , shock_value , shock_dir , irf_intervals ) : """Function creates shocks based on desired specification Parameters h : int How many steps ahead to forecast shock _ type : None or str Type of shock ; options include None , ' Cov ' ( simulate from cova...
if shock_type is None : random = [ np . zeros ( self . ylen ) for i in range ( 0 , h ) ] elif shock_type == 'IRF' : if self . use_ols_covariance is False : cov = self . custom_covariance ( self . latent_variables . get_z_values ( ) ) else : cov = self . ols_covariance ( ) post = ss . mul...
def ComputeLightTravelTime ( Det1Pos , Det2Pos ) : """ComputeLightTravelTime - function to compute light travel time between two GW detectors at positions Det1Pos and Det2Pos . Det1Pos - ( 3 , ) array . Position vector of detector 1. Det2Pos - ( 3 , ) array . Position vector of detector 2. Returns travelTim...
# Get relative position vector Det21Pos = Det2Pos - Det1Pos # Dot difference vector into itself to get magnitude of detector separation dist = np . sqrt ( np . dot ( Det21Pos , Det21Pos ) ) # Normalise with speed of light travelTime = dist / c return travelTime
def boolean_add ( self , mesh , inplace = False ) : """Add a mesh to the current mesh . Does not attempt to " join " the meshes . Parameters mesh : vtki . PolyData The mesh to add . inplace : bool , optional Updates mesh in - place while returning nothing . Returns joinedmesh : vtki . PolyData Ini...
vtkappend = vtk . vtkAppendPolyData ( ) vtkappend . AddInputData ( self ) vtkappend . AddInputData ( mesh ) vtkappend . Update ( ) mesh = _get_output ( vtkappend ) if inplace : self . overwrite ( mesh ) else : return mesh
def quote ( string , safe = '/' , encoding = None , errors = None ) : """quote ( ' abc def ' ) - > ' abc % 20def ' Each part of a URL , e . g . the path info , the query , etc . , has a different set of reserved characters that must be quoted . RFC 2396 Uniform Resource Identifiers ( URI ) : Generic Syntax li...
if isinstance ( string , str ) : if not string : return string if encoding is None : encoding = 'utf-8' if errors is None : errors = 'strict' string = string . encode ( encoding , errors ) else : if encoding is not None : raise TypeError ( "quote() doesn't support 'en...
def get_email_regex ( self ) : """Return a regex pattern matching valid email addresses . Uses the same logic as the django validator , with the folowing exceptions : - Internationalized domain names not supported - IP addresses not supported - Strips lookbehinds ( not supported in javascript regular expres...
validator = self . default_validators [ 0 ] user_regex = validator . user_regex . pattern . replace ( '\Z' , '@' ) domain_patterns = ( [ re . escape ( domain ) + '$' for domain in validator . domain_whitelist ] + [ validator . domain_regex . pattern . replace ( '\Z' , '$' ) ] ) domain_regex = '({0})' . format ( '|' . j...
def get_domain_connect_template_sync_url ( self , domain , provider_id , service_id , redirect_uri = None , params = None , state = None , group_ids = None ) : """Makes full Domain Connect discovery of a domain and returns full url to request sync consent . : param domain : str : param provider _ id : str : p...
# TODO : support for signatures # TODO : support for provider _ name ( for shared templates ) if params is None : params = { } config = self . get_domain_config ( domain ) self . check_template_supported ( config , provider_id , service_id ) if config . urlSyncUX is None : raise InvalidDomainConnectSettingsExce...
def get_result ( self ) : """Get the result of this transfer ."""
while self . _result is None : if len ( self . daplink . _commands_to_read ) > 0 : self . daplink . _read_packet ( ) else : assert not self . daplink . _crnt_cmd . get_empty ( ) self . daplink . flush ( ) if self . _error is not None : # Pylint is confused and thinks self . _ error is No...
def fetchmany ( self , * args , ** kwargs ) : """Analogous to : any : ` sqlite3 . Cursor . fetchmany `"""
with self : return self . _cursor . fetchmany ( * args , ** kwargs )
def create_script_acl ( self , id_vlan , network_type ) : '''Generate the script acl : param id _ vlan : Vlan Id : param network _ type : v4 or v6 : raise InvalidValueError : Attrs invalids . : raise XMLError : Networkapi failed to generate the XML response . : raise VlanACLDuplicatedError : ACL name dupl...
vlan_map = dict ( ) vlan_map [ 'id_vlan' ] = id_vlan vlan_map [ 'network_type' ] = network_type url = 'vlan/create/script/acl/' code , xml = self . submit ( { 'vlan' : vlan_map } , 'POST' , url ) return self . response ( code , xml )
def upload_large_items ( self ) : """Upload files that were too large ."""
for local_file , parent in self . large_items : if local_file . need_to_send : self . process_large_file ( local_file , parent )
def doc ( obj , of_class = None ) : """Get parsed documentation for an object as a dict . This includes arguments spec , as well as the parsed data from the docstring . ` ` ` python from exdoc import doc The ` doc ( ) ` function simply fetches documentation for an object , which can be * Module * Class ...
# Special care about properties if isinstance ( obj , property ) : docstr = doc ( obj . fget ) # Some hacks for properties docstr . signature = docstr . qsignature = obj . fget . __name__ docstr . args = docstr . args [ 1 : ] return docstr # Module module = inspect . getmodule ( obj ) if module : ...
def _call_pyfftw ( self , x , out , ** kwargs ) : """Implement ` ` self ( x [ , out , * * kwargs ] ) ` ` using pyfftw . Parameters x : ` domain ` element Input element to be transformed . out : ` range ` element Output element storing the result . flags : sequence of strings , optional Flags for the t...
kwargs . pop ( 'normalise_idft' , None ) # Using ` True ` here kwargs . pop ( 'axes' , None ) kwargs . pop ( 'halfcomplex' , None ) flags = list ( _pyfftw_to_local ( flag ) for flag in kwargs . pop ( 'flags' , ( 'FFTW_MEASURE' , ) ) ) try : flags . remove ( 'unaligned' ) except ValueError : pass try : flags...
def add_schema_spec ( self , spec : Dict [ str , Any ] , fully_qualified_parent_name : str = None ) -> Optional [ str ] : """Add a schema dictionary to the schema loader . The given schema is stored against fully _ qualified _ parent _ name + ITEM _ SEPARATOR ( ' . ' ) + schema . name . : param spec : Schema sp...
if not isinstance ( spec , dict ) or ATTRIBUTE_NAME not in spec : return None name = spec [ ATTRIBUTE_NAME ] fully_qualified_name = name if fully_qualified_parent_name is None else self . get_fully_qualified_name ( fully_qualified_parent_name , name ) # Ensure that basic validation for each spec part is done before...
def fetch ( self ) : """Fetch the data from hddtemp daemon ."""
# Taking care of sudden deaths / stops of hddtemp daemon try : sck = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sck . connect ( ( self . host , self . port ) ) data = b'' while True : received = sck . recv ( 4096 ) if not received : break data += rece...
def define_from_header ( cls , image_header ) : """Define class members directly from FITS header . Parameters image _ header : instance of hdulist . header Header content from a FITS file ."""
self = CsuConfiguration ( ) # declare lists to store configuration of CSU bars self . _csu_bar_left = [ ] self . _csu_bar_right = [ ] self . _csu_bar_slit_center = [ ] self . _csu_bar_slit_width = [ ] for i in range ( EMIR_NBARS ) : ibar = i + 1 keyword = 'CSUP{}' . format ( ibar ) if keyword in image_heade...
def get_analyzer_for ( language_code , default = 'snowball' ) : """Get the available language analyzer for the given language code or else the default . : param language _ code : Django language code : param default : The analyzer to return if no language analyzer has been found . Defaults to ' snowball ' . ...
languages = { 'ar' : 'arabic' , # ' ' : ' armenian ' , 'eu' : 'basque' , 'pt-br' : 'brazilian' , 'bg' : 'bulgarian' , 'ca' : 'catalan' , 'zh-hans' : 'chinese' , 'zh-hant' : 'chinese' , # ' cjk ' , 'cs' : 'czech' , 'da' : 'danish' , 'nl' : 'dutch' , 'en' : 'english' , 'fi' : 'finnish' , 'fr' : 'french' , 'gl' : 'galicia...
def set_context ( pid_file , context_info ) : """Set context of running notebook . : param context _ info : dict of extra context parameters , see comm . py comments"""
assert type ( context_info ) == dict port_file = get_context_file_name ( pid_file ) with open ( port_file , "wt" ) as f : f . write ( json . dumps ( context_info ) )
def delete_os_in_nwk ( self , tenant_id , fw_dict , is_fw_virt = False ) : """Deletes the Openstack In network and update the DB ."""
ret = True tenant_name = fw_dict . get ( 'tenant_name' ) try : ret = self . _delete_os_nwk ( tenant_id , tenant_name , "in" , is_fw_virt = is_fw_virt ) except Exception as exc : LOG . error ( "Deletion of In Openstack Network failed tenant " "%(tenant)s Exception %(exc)s" , { 'tenant' : tenant_id , 'exc' : str ...
def predict ( self , u = 0 ) : """Predict next position . Parameters u : ndarray Optional control vector . If non - zero , it is multiplied by ` B ` to create the control input into the system ."""
# x = Fx + Bu self . x = dot ( self . F , self . x ) + dot ( self . B , u )
def url_is_from_any_domain ( url , domains ) : """Return True if the url belongs to any of the given domains"""
host = parse_url ( url ) . netloc . lower ( ) if host : return any ( ( ( host == d . lower ( ) ) or ( host . endswith ( '.%s' % d . lower ( ) ) ) for d in domains ) ) else : return False
def purity ( rho : Density ) -> bk . BKTensor : """Calculate the purity of a mixed quantum state . Purity , defined as tr ( rho ^ 2 ) , has an upper bound of 1 for a pure state , and a lower bound of 1 / D ( where D is the Hilbert space dimension ) for a competently mixed state . Two closely related measure...
tensor = rho . tensor N = rho . qubit_nb matrix = bk . reshape ( tensor , [ 2 ** N , 2 ** N ] ) return bk . trace ( bk . matmul ( matrix , matrix ) )
def from_dynacRepr ( cls , pynacRepr ) : """Construct a ` ` AccGap ` ` instance from the Pynac lattice element"""
pynacList = pynacRepr [ 1 ] [ 0 ] L = float ( pynacList [ 3 ] ) TTF = float ( pynacList [ 4 ] ) TTFprime = float ( pynacList [ 5 ] ) TTFprimeprime = float ( pynacList [ 13 ] ) EField = float ( pynacList [ 10 ] ) phase = float ( pynacList [ 11 ] ) F = float ( pynacList [ 14 ] ) atten = float ( pynacList [ 15 ] ) gap = c...
def OnSelectAll ( self , event ) : """Select all cells event handler"""
entry_line = self . main_window . entry_line_panel . entry_line_panel . entry_line if wx . Window . FindFocus ( ) != entry_line : self . main_window . grid . SelectAll ( ) else : entry_line . SelectAll ( )
def commands ( self , event ) : """Lists all available commands ."""
commands = sorted ( self . commands_dict ( ) . keys ( ) ) return "Available commands: %s" % " " . join ( commands )
def make_relative_timing_fn ( ) : """Make a function that logs the duration since it was made ."""
start_time = time . time ( ) def format_relative_time ( ) : time_delta = time . time ( ) - start_time return str ( datetime . timedelta ( seconds = time_delta ) ) def log_relative_time ( ) : tf . logging . info ( "Timing: %s" , format_relative_time ( ) ) return log_relative_time
def __configure_annotations ( mapper , cls ) : """Run through attributes of the class looking for annotations from : func : ` annotation _ wrapper ` and add them to : attr : ` cls . _ _ annotations _ _ ` and : attr : ` cls . _ _ annotations _ by _ attr _ _ `"""
annotations = { } annotations_by_attr = { } # An attribute may be defined more than once in base classes . Only handle the first processed = set ( ) # Loop through all attributes in the class and its base classes , looking for annotations for base in cls . __mro__ : for name , attr in base . __dict__ . items ( ) : ...
def cc ( self , cc ) : ''': param cc : Email addresses for the ' Cc ' API field . : type cc : : keyword : ` list ` or ` str `'''
if isinstance ( cc , basestring ) : cc = cc . split ( ',' ) self . _cc = cc
def WritePathStatHistory ( self , client_path , stat_entries ) : """Writes a collection of ` StatEntry ` observed for particular path . Args : client _ path : A ` ClientPath ` instance . stat _ entries : A dictionary with timestamps as keys and ` StatEntry ` instances as values ."""
client_path_history = ClientPathHistory ( ) for timestamp , stat_entry in iteritems ( stat_entries ) : client_path_history . AddStatEntry ( timestamp , stat_entry ) self . MultiWritePathHistory ( { client_path : client_path_history } )
def stop ( self , io_loop ) : """Asynchronously stop the application . : param tornado . ioloop . IOLoop io _ loop : loop to run until all callbacks , timeouts , and queued calls are complete Call this method to start the application shutdown process . The IOLoop will be stopped once the application is comp...
running_async = False shutdown = _ShutdownHandler ( io_loop ) for callback in self . on_shutdown_callbacks : try : maybe_future = callback ( self . tornado_application ) if asyncio . iscoroutine ( maybe_future ) : maybe_future = asyncio . create_task ( maybe_future ) if concurren...
async def vcx_messages_update_status ( msg_json : str ) : """Update the status of messages from the specified connection : param msg _ json : : return :"""
logger = logging . getLogger ( __name__ ) if not hasattr ( vcx_messages_update_status , "cb" ) : logger . debug ( "vcx_messages_update_status: Creating callback" ) vcx_messages_update_status . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 ) ) c_msg_json = c_char_p ( msg_json . encode ( 'utf-8' ) ) c_s...
def add_subtrack ( self , subtrack ) : """Add a child : class : ` Track ` ."""
self . add_child ( subtrack ) self . subtracks . append ( subtrack )
def filter_catalog ( catalog , ** kwargs ) : """Create a new catalog selected from input based on photometry . Parameters bright _ limit : float Fraction of catalog based on brightness that should be retained . Value of 1.00 means full catalog . max _ bright : int Maximum number of sources to keep regar...
# interpret input pars bright_limit = kwargs . get ( 'bright_limit' , 1.00 ) max_bright = kwargs . get ( 'max_bright' , None ) min_bright = kwargs . get ( 'min_bright' , 20 ) colname = kwargs . get ( 'colname' , 'vegamag' ) # sort by magnitude phot_column = catalog [ colname ] num_sources = len ( phot_column ) sort_ind...
def insert_after ( sequence , offset , new_residues ) : """Mutate the given sequence by inserting the string ` new _ residues ` after ` offset ` . Parameters sequence : sequence String of amino acids or DNA bases offset : int Base 0 offset from start of sequence , after which we should insert ` new _ ...
assert 0 <= offset < len ( sequence ) , "Invalid position %d for sequence of length %d" % ( offset , len ( sequence ) ) prefix = sequence [ : offset + 1 ] suffix = sequence [ offset + 1 : ] return prefix + new_residues + suffix
def tree_entries_from_data ( data ) : """Reads the binary representation of a tree and returns tuples of Tree items : param data : data block with tree data ( as bytes ) : return : list ( tuple ( binsha , mode , tree _ relative _ path ) , . . . )"""
ord_zero = ord ( '0' ) space_ord = ord ( ' ' ) len_data = len ( data ) i = 0 out = [ ] while i < len_data : mode = 0 # read mode # Some git versions truncate the leading 0 , some don ' t # The type will be extracted from the mode later while byte_ord ( data [ i ] ) != space_ord : # move existing mod...
def _cached_pages ( self , target_page = - 1 ) : """Get a page or all pages from page generator , caching results . This is necessary because PDFMiner searches recursively for pages , so we won ' t know how many there are until we parse the whole document , which we don ' t want to do until we need to ."""
try : # pdfminer < 20131022 self . _pages_iter = self . _pages_iter or self . doc . get_pages ( ) except AttributeError : # pdfminer > = 20131022 self . _pages_iter = self . _pages_iter or PDFPage . create_pages ( self . doc ) if target_page >= 0 : while len ( self . _pages ) <= target_page : next_p...
def delegate_method ( other , method , name = None ) : """Add a method to the current class that delegates to another method . The * other * argument must be a property that returns the instance to delegate to . Due to an implementation detail , the property must be defined in the current class . The * method...
frame = sys . _getframe ( 1 ) classdict = frame . f_locals @ functools . wraps ( method ) def delegate ( self , * args , ** kwargs ) : other_self = other . __get__ ( self ) return method ( other_self , * args , ** kwargs ) if getattr ( method , '__switchpoint__' , False ) : delegate . __switchpoint__ = True...
def adapter_remove_nio_binding ( self , adapter_number ) : """Removes an adapter NIO binding . : param adapter _ number : adapter number : returns : NIO instance"""
try : adapter = self . _ethernet_adapters [ adapter_number ] except KeyError : raise VirtualBoxError ( "Adapter {adapter_number} doesn't exist on VirtualBox VM '{name}'" . format ( name = self . name , adapter_number = adapter_number ) ) if self . is_running ( ) : yield from self . _ubridge_send ( "bridge d...
def is_reassignment_pending ( self ) : """Return True if there are reassignment tasks pending ."""
in_progress_plan = self . zk . get_pending_plan ( ) if in_progress_plan : in_progress_partitions = in_progress_plan [ 'partitions' ] self . log . info ( 'Previous re-assignment in progress for {count} partitions.' ' Current partitions in re-assignment queue: {partitions}' . format ( count = len ( in_progress_pa...
def p2sh_input_and_witness ( outpoint , stack_script , redeem_script , sequence = None ) : '''OutPoint , str , str , int - > ( TxIn , InputWitness ) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts'''
if sequence is None : sequence = guess_sequence ( redeem_script ) stack_script = script_ser . serialize ( stack_script ) redeem_script = script_ser . hex_serialize ( redeem_script ) redeem_script = script_ser . serialize ( redeem_script ) return tb . make_legacy_input_and_empty_witness ( outpoint = outpoint , stack...
def update_qualification_score ( self , qualification_type_id , worker_id , value ) : """TODO : Document ."""
params = { 'QualificationTypeId' : qualification_type_id , 'SubjectId' : worker_id , 'IntegerValue' : value } return self . _process_request ( 'UpdateQualificationScore' , params )
def fixminimized ( self , alphabet ) : """After pyfst minimization , all unused arcs are removed , and all sink states are removed . However this may break compatibility . Args : alphabet ( list ) : The input alphabet Returns : None"""
insymbols = fst . SymbolTable ( ) outsymbols = fst . SymbolTable ( ) num = 1 for char in self . alphabet : self . isyms . __setitem__ ( char , num ) self . osyms . __setitem__ ( char , num ) insymbols . add_symbol ( char , num ) outsymbols . add_symbol ( char , num ) num = num + 1 self . automaton ....
def _gill_king ( mat , beta , delta ) : """Backend function for the Gill - King algorithm ."""
size = mat . shape [ 0 ] # initialize d _ vec and lowtri if scipy . sparse . issparse ( mat ) : lowtri = scipy . sparse . eye ( * mat . shape ) else : lowtri = numpy . eye ( size ) d_vec = numpy . zeros ( size , dtype = float ) # there are no inner for loops , everything implemented with # vector operations for...
def _get_queue_lock ( self , queue , log ) : """Get queue lock for max worker queues . For max worker queues it returns a Lock if acquired and whether it failed to acquire the lock ."""
max_workers = self . max_workers_per_queue # Check if this is single worker queue for part in dotted_parts ( queue ) : if part in self . single_worker_queues : log . debug ( 'single worker queue' ) max_workers = 1 break # Max worker queues require us to get a queue lock before # moving tasks...
def generate_templates ( self , exercise_questions = False ) : """Create empty . csv files with the right headers and place them in the Will place files as siblings of directory ` channeldir ` ."""
self . generate_template ( channeldir = self . channeldir , filename = self . channelinfo , header = CHANNEL_INFO_HEADER ) self . generate_template ( channeldir = self . channeldir , filename = self . contentinfo , header = CONTENT_INFO_HEADER ) if exercise_questions : self . generate_template ( channeldir = self ....
def _onShortcutPasteLine ( self ) : """Paste lines from the clipboard"""
lines = self . lines [ self . _selectedLinesSlice ( ) ] text = QApplication . clipboard ( ) . text ( ) if text : with self : if self . textCursor ( ) . hasSelection ( ) : startBlockNumber , endBlockNumber = self . _selectedBlockNumbers ( ) del self . lines [ self . _selectedLinesSlic...
def _mantissa ( dval ) : """Extract the _ mantissa bits from a double - precision floating point value ."""
bb = _double_as_bytes ( dval ) mantissa = bb [ 1 ] & 0x0f << 48 mantissa += bb [ 2 ] << 40 mantissa += bb [ 3 ] << 32 mantissa += bb [ 4 ] return mantissa
def get_form_class ( self ) : """Returns the form class to use in this view . Makes sure that the form _ field _ callback is set to use the ` formfield _ for _ dbfield ` method and that any custom form classes are prepared by the ` customize _ form _ widgets ` method ."""
if self . fieldsets : fields = flatten_fieldsets ( self . get_fieldsets ( ) ) else : if ( self . form_class and getattr ( self . form_class , 'Meta' , None ) and getattr ( self . form_class . Meta , 'fields' , None ) ) : fields = self . form_class . Meta . fields else : fields = [ ] exclude ...
def show_progress ( self , message = None ) : """If we are in a progress scope , and no log messages have been shown , write out another ' . '"""
if self . in_progress_hanging : if message is None : sys . stdout . write ( '.' ) sys . stdout . flush ( ) else : if self . last_message : padding = ' ' * max ( 0 , len ( self . last_message ) - len ( message ) ) else : padding = '' sys . stdout . ...
def _canViewChange ( self , proposedViewNo : int ) -> ( bool , str ) : """Return whether there ' s quorum for view change for the proposed view number and its view is less than or equal to the proposed view"""
msg = None quorum = self . quorums . view_change . value if not self . instance_changes . has_quorum ( proposedViewNo , quorum ) : msg = '{} has no quorum for view {}' . format ( self , proposedViewNo ) elif not proposedViewNo > self . view_no : msg = '{} is in higher view more than {}' . format ( self , propos...
def collapse ( cls , holomap , ranges = None , mode = 'data' ) : """Given a map of Overlays , apply all applicable compositors ."""
# No potential compositors if cls . definitions == [ ] : return holomap # Apply compositors clone = holomap . clone ( shared_data = False ) data = zip ( ranges [ 1 ] , holomap . data . values ( ) ) if ranges else holomap . data . items ( ) for key , overlay in data : clone [ key ] = cls . collapse_element ( ove...
def literal_array ( cls , elems ) : """Construct a literal array constant made of the given members ."""
tys = [ el . type for el in elems ] if len ( tys ) == 0 : raise ValueError ( "need at least one element" ) ty = tys [ 0 ] for other in tys : if ty != other : raise TypeError ( "all elements must have the same type" ) return cls ( types . ArrayType ( ty , len ( elems ) ) , elems )
def from_legacy_urlsafe ( cls , urlsafe ) : """Convert urlsafe string to : class : ` ~ google . cloud . datastore . key . Key ` . This is intended to work with the " legacy " representation of a datastore " Key " used within Google App Engine ( a so - called " Reference " ) . This assumes that ` ` urlsafe ` `...
urlsafe = _to_bytes ( urlsafe , encoding = "ascii" ) padding = b"=" * ( - len ( urlsafe ) % 4 ) urlsafe += padding raw_bytes = base64 . urlsafe_b64decode ( urlsafe ) reference = _app_engine_key_pb2 . Reference ( ) reference . ParseFromString ( raw_bytes ) project = _clean_app ( reference . app ) namespace = _get_empty ...
def epsilon_rules_restore ( root ) : # type : ( Nonterminal ) - > Nonterminal """Transform parsed tree to contain epsilon rules originally removed from the grammar . : param root : Root of the parsed tree . : return : Modified tree including epsilon rules ."""
items = Traversing . post_order ( root ) items = filter ( lambda x : isinstance ( x , EpsilonRemovedRule ) , items ) for rule in items : # create original rule created_rule = rule . from_rule ( ) # type : Rule # attach parrents parents for s in rule . from_symbols : # type : Nonterminal s . _set...
def clear ( self ) : """Remove all sources from this configuration ."""
super ( LazyConfig , self ) . clear ( ) self . _lazy_suffix = [ ] self . _lazy_prefix = [ ]
def _schema_line ( args ) : """Implements the BigQuery schema magic used to display table / view schemas . Args : args : the arguments following ' % bigquery schema ' . Returns : The HTML rendering for the schema ."""
# TODO ( gram ) : surely we could just return the schema itself ? name = args [ 'table' ] if args [ 'table' ] else args [ 'view' ] if name is None : raise Exception ( 'No table or view specified; cannot show schema' ) schema = _get_schema ( name ) if schema : html = _repr_html_table_schema ( schema ) return...
def create ( backbone : ModelFactory , input_block : typing . Optional [ ModelFactory ] = None ) : """Vel factory function"""
if input_block is None : input_block = IdentityFactory ( ) return StochasticPolicyModelFactory ( input_block = input_block , backbone = backbone )
def group_remove ( name , ** kwargs ) : """Remove routing group from the storage ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'group:remove' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } )
def enable_save_reply_handlers ( self , delay = 120 , filename = "./.handler-saves/reply.save" ) : """Enable saving reply handlers ( by default saving disable ) : param delay : Delay between changes in handlers and saving : param filename : Filename of save file"""
self . reply_saver = Saver ( self . reply_handlers , filename , delay )
def create_node_rating_counts_settings ( sender , ** kwargs ) : """create node rating count and settings"""
created = kwargs [ 'created' ] node = kwargs [ 'instance' ] if created : # create node _ rating _ count and settings # task will be executed in background unless settings . CELERY _ ALWAYS _ EAGER is True # if CELERY _ ALWAYS _ EAGER is False celery worker must be running otherwise task won ' t be executed create_r...