signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _parseDataDirectoryImport ( self , dataDirectoryEntry , importSection ) : """Parses the ImportDataDirectory and returns a list of ImportDescriptorData"""
if not importSection : return raw_bytes = ( c_ubyte * dataDirectoryEntry . Size ) . from_buffer ( importSection . raw , to_offset ( dataDirectoryEntry . VirtualAddress , importSection ) ) offset = 0 import_descriptors = [ ] while True : import_descriptor = IMAGE_IMPORT_DESCRIPTOR . from_buffer ( raw_bytes , off...
def _on_del_route ( self , msg ) : """Respond to : data : ` mitogen . core . DEL _ ROUTE ` by validating the source of the message , updating the local table , propagating the message upwards , and downwards towards any stream that every had a message forwarded from it towards the disconnecting context ."""
if msg . is_dead : return target_id = int ( msg . data ) registered_stream = self . router . stream_by_id ( target_id ) if registered_stream is None : return stream = self . router . stream_by_id ( msg . auth_id ) if registered_stream != stream : LOG . error ( '%r: received DEL_ROUTE for %d from %r, expecte...
def _EccZmaxRperiRap ( self , * args , ** kwargs ) : """NAME : _ EccZmaxRperiRap PURPOSE : evaluate the eccentricity , maximum height above the plane , peri - and apocenter for an isochrone potential INPUT : Either : a ) R , vR , vT , z , vz [ , phi ] : 1 ) floats : phase - space value for single obje...
if len ( args ) == 5 : # R , vR . vT , z , vz pragma : no cover R , vR , vT , z , vz = args elif len ( args ) == 6 : # R , vR . vT , z , vz , phi R , vR , vT , z , vz , phi = args else : self . _parse_eval_args ( * args ) R = self . _eval_R vR = self . _eval_vR vT = self . _eval_vT z = self ...
def makeCubiccFunc ( self , mNrm , cNrm ) : '''Makes a cubic spline interpolation of the unconstrained consumption function for this period . Parameters mNrm : np . array Corresponding market resource points for interpolation . cNrm : np . array Consumption points for interpolation . Returns cFuncUn...
EndOfPrdvPP = self . DiscFacEff * self . Rfree * self . Rfree * self . PermGroFac ** ( - self . CRRA - 1.0 ) * np . sum ( self . PermShkVals_temp ** ( - self . CRRA - 1.0 ) * self . vPPfuncNext ( self . mNrmNext ) * self . ShkPrbs_temp , axis = 0 ) dcda = EndOfPrdvPP / self . uPP ( np . array ( cNrm [ 1 : ] ) ) MPC = d...
def get_widths_mean_var ( self , estimation ) : """Get estimation on the variance of widths ' mean Parameters estimation : 1D arrary Either prior of posterior estimation Returns widths _ mean _ var : 2D array , in shape [ K , 1] Estimation on variance of widths ' mean"""
widths_mean_var = estimation [ self . map_offset [ 3 ] : ] . reshape ( self . K , 1 ) return widths_mean_var
def int_global_to_local ( self , index , axis = 0 ) : """Calculate local index from global index for integer input : param index : global index as integer : param axis : current axis to process : return :"""
# Warum > = an dieser Stelle . Eigentlich sollte > ausreichend sein ! Test ! if index >= self . __mask [ axis ] . stop - self . __halos [ 1 ] [ axis ] : return None if index < self . __mask [ axis ] . start + self . __halos [ 0 ] [ axis ] : return None return index - self . __mask [ axis ] . start
def addCallbacks ( self , callback , errback = None , callbackArgs = None , callbackKeywords = None , errbackArgs = None , errbackKeywords = None ) : """Add a pair of callbacks that will be run in the context of an eliot action . @ return : C { self } @ rtype : L { DeferredContext } @ raises AlreadyFinished...
if self . _finishAdded : raise AlreadyFinished ( ) if errback is None : errback = _passthrough def callbackWithContext ( * args , ** kwargs ) : return self . _action . run ( callback , * args , ** kwargs ) def errbackWithContext ( * args , ** kwargs ) : return self . _action . run ( errback , * args , *...
def from_payload ( type_code , payload , connection ) : """Generator function to create lob from payload . Depending on lob type a BLOB , CLOB , or NCLOB instance will be returned . This function is usually called from types . * LobType . from _ resultset ( )"""
lob_header = ReadLobHeader ( payload ) if lob_header . isnull ( ) : lob = None else : data = payload . read ( lob_header . chunk_length ) _LobClass = LOB_TYPE_CODE_MAP [ type_code ] lob = _LobClass . from_payload ( data , lob_header , connection ) logger . debug ( 'Lob Header %r' % lob ) return lob
def full_clean ( self , * args , ** kwargs ) : """Apply fixups that need to happen before per - field validation occurs . Sets the page ' s title ."""
name = getattr ( self , 'name' , self . slugName . title ( ) ) self . title = "{} for {}" . format ( name , dateFormat ( self . except_date ) ) self . slug = "{}-{}" . format ( self . except_date , self . slugName ) super ( ) . full_clean ( * args , ** kwargs )
def parseruninfo ( self ) : """Extracts the flowcell ID , as well as the instrument name from RunInfo . xml . If this file is not provided , NA values are substituted"""
# Check if the RunInfo . xml file is provided , otherwise , yield N / A try : runinfo = ElementTree . ElementTree ( file = self . runinfo ) # Get the run id from the for elem in runinfo . iter ( ) : for run in elem : try : self . runid = run . attrib [ 'Id' ] ...
def populate ( self , struct ) : """Generates the list tree . struct : if a list / set / tuple is given , a flat list is generated < * l > < li > v1 < / li > < li > v2 < / li > . . . < / * l > If the list type is ' Dl ' a flat list without definitions is generated < * l > < dt > v1 < / dt > < dt > v2 < / dt...
if struct is None : # Maybe raise ? Empty the list ? return self if isinstance ( struct , ( list , set , tuple ) ) : struct = dict ( zip_longest ( struct , [ None ] ) ) if not isinstance ( struct , dict ) : raise WidgetDataError ( self , "List Input not managed, expected (dict, list), got %s" % type ( struc...
def QA_data_futuremin_resample ( min_data , type_ = '5min' ) : """期货分钟线采样成大周期 分钟线采样成子级别的分钟线 future : vol = = > trade amount X"""
min_data . tradeime = pd . to_datetime ( min_data . tradetime ) CONVERSION = { 'code' : 'first' , 'open' : 'first' , 'high' : 'max' , 'low' : 'min' , 'close' : 'last' , 'trade' : 'sum' , 'tradetime' : 'last' , 'date' : 'last' } resx = min_data . resample ( type_ , closed = 'right' , loffset = type_ ) . apply ( CONVERSI...
def start ( ** kwargs : Any ) -> None : """Start web server . Run until ` ` Ctrl - c ` ` pressed , or if auto - shutdown is enabled , until when all browser windows are closed . This function accepts keyword areguments same as : func : ` start _ server ` and all arguments passed to it ."""
start_server ( ** kwargs ) try : asyncio . get_event_loop ( ) . run_forever ( ) except KeyboardInterrupt : stop_server ( )
def adjust_name_for_printing ( name ) : """Make sure a name can be printed , alongside used as a variable name ."""
if name is not None : name2 = name name = name . replace ( " " , "_" ) . replace ( "." , "_" ) . replace ( "-" , "_m_" ) name = name . replace ( "+" , "_p_" ) . replace ( "!" , "_I_" ) name = name . replace ( "**" , "_xx_" ) . replace ( "*" , "_x_" ) name = name . replace ( "/" , "_l_" ) . replace (...
def prepare_list_of_files ( kernel_name , kernel_file_list , params , grid , threads , block_size_names ) : """prepare the kernel string along with any additional files The first file in the list is allowed to include or read in the others The files beyond the first are considered additional files that may also...
temp_files = dict ( ) kernel_string = get_kernel_string ( kernel_file_list [ 0 ] , params ) name , kernel_string = prepare_kernel_string ( kernel_name , kernel_string , params , grid , threads , block_size_names ) if len ( kernel_file_list ) > 1 : for f in kernel_file_list [ 1 : ] : # generate temp filename with th...
def pool_memcached_connections ( func ) : """Function decorator to pool memcached connections . Use this to wrap functions that might make multiple calls to memcached . This will cause a single memcached client to be shared for all connections ."""
if isgeneratorfunction ( func ) : def wrapper ( * nargs , ** kwargs ) : with memcached_client ( ) : for result in func ( * nargs , ** kwargs ) : yield result else : def wrapper ( * nargs , ** kwargs ) : with memcached_client ( ) : return func ( * nargs , *...
def bellman_ford ( G , seeds , maxiter = None ) : """Bellman - Ford iteration . Parameters G : sparse matrix Returns distances : array nearest _ seed : array References CLR"""
G = asgraph ( G ) N = G . shape [ 0 ] if maxiter is not None and maxiter < 0 : raise ValueError ( 'maxiter must be positive' ) if G . dtype == complex : raise ValueError ( 'Bellman-Ford algorithm only defined for real\ weights' ) seeds = np . asarray ( seeds , dtype = 'intc' ) distance...
def _deleteObject ( self , xref ) : """Delete an object given its xref ."""
if self . isClosed : raise ValueError ( "operation illegal for closed doc" ) return _fitz . Document__deleteObject ( self , xref )
def _sd_decode ( self , msg ) : """SD : Description text ."""
desc_ch1 = msg [ 9 ] show_on_keypad = ord ( desc_ch1 ) >= 0x80 if show_on_keypad : desc_ch1 = chr ( ord ( desc_ch1 ) & 0x7f ) return { 'desc_type' : int ( msg [ 4 : 6 ] ) , 'unit' : int ( msg [ 6 : 9 ] ) - 1 , 'desc' : ( desc_ch1 + msg [ 10 : 25 ] ) . rstrip ( ) , 'show_on_keypad' : show_on_keypad }
def failMeasurement ( self , measurementId , deviceName , failureReason = None ) : """Fails the measurement session . : param deviceName : the device name . : param measurementId : the measurement name . : param failureReason : why it failed . : return : true if it was completed ."""
am , handler = self . getDataHandler ( measurementId , deviceName ) if handler is not None : am . updateDeviceStatus ( deviceName , RecordStatus . FAILED , reason = failureReason ) handler . stop ( measurementId ) return True else : return False
def _getMonitorInfo ( self ) : """Returns info about the attached monitors , in device order [0 ] is always the primary monitor"""
monitors = [ ] CCHDEVICENAME = 32 def _MonitorEnumProcCallback ( hMonitor , hdcMonitor , lprcMonitor , dwData ) : class MONITORINFOEX ( ctypes . Structure ) : _fields_ = [ ( "cbSize" , ctypes . wintypes . DWORD ) , ( "rcMonitor" , ctypes . wintypes . RECT ) , ( "rcWork" , ctypes . wintypes . RECT ) , ( "dwF...
def _parse_dependencies ( string ) : """This function actually parses the dependencies are sorts them into the buildable and given dependencies"""
contents = _get_contents_between ( string , '(' , ')' ) unsorted_dependencies = contents . split ( ',' ) _check_parameters ( unsorted_dependencies , ( '?' , ) ) buildable_dependencies = [ ] given_dependencies = [ ] for dependency in unsorted_dependencies : if dependency [ 0 ] == '?' : given_dependencies . a...
def read ( cls , dstore ) : """: param dstore : a DataStore instance : returns : a : class : ` CompositeRiskModel ` instance"""
oqparam = dstore [ 'oqparam' ] tmap = ( dstore [ 'taxonomy_mapping' ] if 'taxonomy_mapping' in dstore else { } ) crm = dstore . getitem ( 'risk_model' ) # building dictionaries riskid - > loss _ type - > risk _ func fragdict , vulndict , consdict , retrodict = ( AccumDict ( ) , AccumDict ( ) , AccumDict ( ) , AccumDict...
def route ( self , uri , methods = frozenset ( { "GET" } ) , host = None , strict_slashes = None , stream = False , version = None , name = None , ) : """Decorate a function to be registered as a route : param uri : path of the URL : param methods : list or tuple of methods allowed : param host : : param st...
# Fix case where the user did not prefix the URL with a / # and will probably get confused as to why it ' s not working if not uri . startswith ( "/" ) : uri = "/" + uri if stream : self . is_request_stream = True if strict_slashes is None : strict_slashes = self . strict_slashes def response ( handler ) : ...
def distinct ( self , field = None ) : """If field is None , then it means that it ' ll create : select distinct * and if field is not None , for example : ' name ' , it ' ll create : select distinc ( name ) ,"""
if field is None : self . funcs . append ( ( 'distinct' , ( ) , { } ) ) else : self . distinct_field = field return self
def list_path_traversal ( path ) : '''Returns a full list of directories leading up to , and including , a path . So list _ path _ traversal ( ' / path / to / salt ' ) would return : [ ' / ' , ' / path ' , ' / path / to ' , ' / path / to / salt ' ] in that order . This routine has been tested on Windows sys...
out = [ path ] ( head , tail ) = os . path . split ( path ) if tail == '' : # paths with trailing separators will return an empty string out = [ head ] ( head , tail ) = os . path . split ( head ) while head != out [ 0 ] : # loop until head is the same two consecutive times out . insert ( 0 , head ) ( h...
def main ( ) : """fetches hek data and makes thematic maps as requested"""
args = get_args ( ) config = Config ( args . config ) # Load dates if os . path . isfile ( args . dates ) : with open ( args . dates ) as f : dates = [ dateparser . parse ( line . split ( " " ) [ 0 ] ) for line in f . readlines ( ) ] else : # assume it ' s a date dates = [ dateparser . parse ( args . da...
def raw_sensor_count ( self ) : """Returns the raw integer ADC count from the sensor Note : Must be divided depending on the max . sensor resolution to get floating point celsius : returns : the raw value from the sensor ADC : rtype : int : raises NoSensorFoundError : if the sensor could not be found : ...
# two complement bytes , MSB comes after LSB ! bytes = self . raw_sensor_strings [ 1 ] . split ( ) # Convert from 16 bit hex string into int int16 = int ( bytes [ 1 ] + bytes [ 0 ] , 16 ) # check first signing bit if int16 >> 15 == 0 : return int16 # positive values need no processing else : return int16 - ...
def p_UnionType ( p ) : """UnionType : " ( " UnionMemberType or UnionMemberType UnionMemberTypes " ) " """
t = [ p [ 2 ] ] + [ p [ 4 ] ] + p [ 5 ] p [ 0 ] = model . UnionType ( t = t )
def map_dataarray ( self , func , x , y , ** kwargs ) : """Apply a plotting function to a 2d facet ' s subset of the data . This is more convenient and less general than ` ` FacetGrid . map ` ` Parameters func : callable A plotting function with the same signature as a 2d xarray plotting method such as ` ...
if kwargs . get ( 'cbar_ax' , None ) is not None : raise ValueError ( 'cbar_ax not supported by FacetGrid.' ) cmap_params , cbar_kwargs = _process_cmap_cbar_kwargs ( func , kwargs , self . data . values ) self . _cmap_extend = cmap_params . get ( 'extend' ) # Order is important func_kwargs = kwargs . copy ( ) func_...
def _activate ( self ) : """Activates the stream ."""
if six . callable ( self . streamer ) : # If it ' s a function , create the stream . self . stream_ = self . streamer ( * ( self . args ) , ** ( self . kwargs ) ) else : # If it ' s iterable , use it directly . self . stream_ = iter ( self . streamer )
def svalue ( self , value ) : """Change of serialized value . Nonify this value as well . : param str value : serialized value to use ."""
if value is not None : # if value is not None self . _value = None self . _error = None self . _svalue = value
def count ( self ) : """Explicit count of the number of items . For lazy or distributed data , will force a computation ."""
if self . mode == 'spark' : return self . tordd ( ) . count ( ) if self . mode == 'local' : return prod ( self . values . values . shape )
def process_account ( account_info ) : """Scan all buckets in an account and schedule processing"""
log = logging . getLogger ( 'salactus.bucket-iterator' ) log . info ( "processing account %s" , account_info ) session = get_session ( account_info ) client = session . client ( 's3' , config = s3config ) buckets = client . list_buckets ( ) [ 'Buckets' ] connection . hset ( 'bucket-accounts' , account_info [ 'name' ] ,...
def client_cookie_jar ( self ) : """Return internal cookie jar that must be used as HTTP - request cookies see : class : ` . WHTTPCookieJar ` : return : WHTTPCookieJar"""
cookie_jar = WHTTPCookieJar ( ) cookie_header = self . get_headers ( 'Cookie' ) for cookie_string in ( cookie_header if cookie_header is not None else tuple ( ) ) : for single_cookie in WHTTPCookieJar . import_header_text ( cookie_string ) : cookie_jar . add_cookie ( single_cookie ) return cookie_jar . ro (...
def cnst_A ( self , X , Xf = None ) : r"""Compute : math : ` A \ mathbf { x } ` component of ADMM problem constraint . In this case : math : ` A \ mathbf { x } = ( G _ r ^ T \ ; \ ; G _ c ^ T \ ; \ ; H ) ^ T \ mathbf { x } ` ."""
if Xf is None : Xf = sl . rfftn ( X , axes = self . axes ) return sl . irfftn ( self . GAf * Xf [ ... , np . newaxis ] , self . axsz , axes = self . axes )
def bethe_lattice ( energy , hopping ) : """Bethe lattice in inf dim density of states"""
energy = np . asarray ( energy ) . clip ( - 2 * hopping , 2 * hopping ) return np . sqrt ( 4 * hopping ** 2 - energy ** 2 ) / ( 2 * np . pi * hopping ** 2 )
def to_naf ( self ) : """Converts the object to NAF"""
if self . type == 'KAF' : self . type = 'NAF' for node in self . __get_wf_nodes ( ) : node . set ( 'id' , node . get ( 'wid' ) ) del node . attrib [ 'wid' ]
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'text' ) and self . text is not None : _dict [ 'text' ] = self . text if hasattr ( self , 'score' ) and self . score is not None : _dict [ 'score' ] = self . score return _dict
def trocar_codigo_de_ativacao ( self , novo_codigo_ativacao , opcao = constantes . CODIGO_ATIVACAO_REGULAR , codigo_emergencia = None ) : """Função ` ` TrocarCodigoDeAtivacao ` ` conforme ER SAT , item 6.1.15. Troca do código de ativação do equipamento SAT . : param str novo _ codigo _ ativacao : O novo co...
if not novo_codigo_ativacao : raise ValueError ( 'Novo codigo de ativacao invalido: {!r}' . format ( novo_codigo_ativacao ) ) codigo_ativacao = self . _codigo_ativacao if opcao == constantes . CODIGO_ATIVACAO_EMERGENCIA : if codigo_emergencia : codigo_ativacao = codigo_emergencia else : rais...
def actualize_source_type ( self , sources , prop_set ) : """Helper for ' actualize _ sources ' . For each passed source , actualizes it with the appropriate scanner . Returns the actualized virtual targets ."""
assert is_iterable_typed ( sources , VirtualTarget ) assert isinstance ( prop_set , property_set . PropertySet ) result = [ ] for i in sources : scanner = None # FIXME : what ' s this ? # if isinstance ( i , str ) : # i = self . manager _ . get _ object ( i ) if i . type ( ) : scanner = b2 ....
def next_block ( self ) : """This could probably be improved ; at the moment it starts by trying to overshoot the desired compressed block size , then it reduces the input bytes one by one until it has met the required block size"""
assert self . pos <= self . input_len if self . pos == self . input_len : return None # Overshoot i = self . START_OVERSHOOT while True : try_size = int ( self . bs * i ) size = self . check_request_size ( try_size ) c , d = self . compress_next_chunk ( size ) if size != try_size : break ...
def bitwise_xor ( bs0 : str , bs1 : str ) -> str : """A helper to calculate the bitwise XOR of two bit string : param bs0 : String of 0 ' s and 1 ' s representing a number in binary representations : param bs1 : String of 0 ' s and 1 ' s representing a number in binary representations : return : String of 0 '...
if len ( bs0 ) != len ( bs1 ) : raise ValueError ( "Bit strings are not of equal length" ) n_bits = len ( bs0 ) return PADDED_BINARY_BIT_STRING . format ( xor ( int ( bs0 , 2 ) , int ( bs1 , 2 ) ) , n_bits )
def saxon6 ( self , elem , ** params ) : """Use Saxon6 to process the element . If the XSLT has a filename ( fn ) , use that . Otherwise , make temp ."""
java = os . environ . get ( 'java' ) or 'java' saxon6path = os . path . join ( JARS , 'saxon.jar' ) # saxon 6.5.5 , included with jing and trang with tempfile . TemporaryDirectory ( ) as tempdir : if self . fn is None : xslfn = os . path . join ( tempdir , "xslt.xsl" ) self . write ( fn = xslfn ) ...
def unixjoin ( * args ) : """Like os . path . join , but uses forward slashes on win32"""
isabs_list = list ( map ( isabs , args ) ) if any ( isabs_list ) : poslist = [ count for count , flag in enumerate ( isabs_list ) if flag ] pos = poslist [ - 1 ] return '/' . join ( args [ pos : ] ) else : return '/' . join ( args )
async def serviceViewChanger ( self , limit ) -> int : """Service the view _ changer ' s inBox , outBox and action queues . : return : the number of messages successfully serviced"""
if not self . isReady ( ) : return 0 o = self . serviceViewChangerOutBox ( limit ) i = await self . serviceViewChangerInbox ( limit ) return o + i
def compute_avg_of_tuples ( input_tuples ) : """This function calculates the average value of the numbers in a specified tuple of tuples . Parameters : input _ tuples : A collection of tuples containing numerical data . Returns : A list with the average values calculated across each position in the nested t...
averages = [ sum ( data ) / len ( data ) for data in zip ( * input_tuples ) ] return averages
def set_number_of_annotation_signals ( self , number_of_annotations ) : """Sets the number of annotation signals . The default value is 1 This function is optional and can be called only after opening a file in writemode and before the first sample write action Normally you don ' t need to change the default ...
number_of_annotations = max ( ( min ( ( int ( number_of_annotations ) , 64 ) ) , 1 ) ) self . number_of_annotations = number_of_annotations self . update_header ( )
def unzip ( self , overwrite : bool = False ) : """Flattens a MIZ file into the temp dir Args : overwrite : allow overwriting exiting files"""
if self . zip_content and not overwrite : raise FileExistsError ( str ( self . temp_dir ) ) LOGGER . debug ( 'unzipping miz to temp dir' ) try : with ZipFile ( str ( self . miz_path ) ) as zip_file : LOGGER . debug ( 'reading infolist' ) self . zip_content = [ f . filename for f in zip_file . in...
def assertDateTimesFuture ( self , sequence , strict = True , msg = None ) : '''Fail if any elements in ` ` sequence ` ` are not in the future . If the min element is a datetime , " future " is defined as anything after ` ` datetime . now ( ) ` ` ; if the min element is a date , " future " is defined as anyth...
if not isinstance ( sequence , collections . Iterable ) : raise TypeError ( 'First argument is not iterable' ) # Cannot compare datetime to date , so if dates are provided use # date . today ( ) , if datetimes are provided use datetime . today ( ) if isinstance ( min ( sequence ) , datetime ) : target = datetim...
def add_data ( self , * args ) : """Add data to signer"""
for data in args : self . _data . append ( to_binary ( data ) )
def _clean_record ( rec ) : """Remove secondary files from record fields , which are currently not supported . To be removed later when secondaryFiles added to records ."""
if workflow . is_cwl_record ( rec ) : def _clean_fields ( d ) : if isinstance ( d , dict ) : if "fields" in d : out = [ ] for f in d [ "fields" ] : f = utils . deepish_copy ( f ) f . pop ( "secondaryFiles" , None ) ...
def merge_result ( res ) : """Merge all items in ` res ` into a list . This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list ."""
if not isinstance ( res , dict ) : raise ValueError ( 'Value should be of dict type' ) result = set ( [ ] ) for _ , v in res . items ( ) : for value in v : result . add ( value ) return list ( result )
def breadcrumb_raw ( context , label , viewname , * args , ** kwargs ) : """Same as breadcrumb but label is not translated ."""
append_breadcrumb ( context , escape ( label ) , viewname , args , kwargs ) return ''
def _get_ansible_playbook ( self , playbook , ** kwargs ) : """Get an instance of AnsiblePlaybook and returns it . : param playbook : A string containing an absolute path to a provisioner ' s playbook . : param kwargs : An optional keyword arguments . : return : object"""
return ansible_playbook . AnsiblePlaybook ( playbook , self . _config , ** kwargs )
def maximum ( lhs , rhs ) : """Returns element - wise maximum of the input arrays with broadcasting . Equivalent to ` ` mx . nd . broadcast _ maximum ( lhs , rhs ) ` ` . . . note : : If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable...
# pylint : disable = no - member , protected - access return _ufunc_helper ( lhs , rhs , op . broadcast_maximum , lambda x , y : x if x > y else y , _internal . _maximum_scalar , None )
def create ( self , edgeList = None , excludeEdges = None , networkName = None , nodeList = None , source = None , verbose = False ) : """Create a new network from a list of nodes and edges in an existing source network . The SUID of the network and view are returned . : param edgeList ( string , optional ) : S...
network = check_network ( self , source , verbose = verbose ) PARAMS = set_param ( [ "edgeList" , "excludeEdges" , "networkName" , "nodeList" , "source" ] , [ edgeList , excludeEdges , networkName , nodeList , network ] ) response = api ( url = self . __url + "/create" , PARAMS = PARAMS , method = "POST" , verbose = ve...
def reqs_txt ( self ) : """Export a requirements file in txt format ."""
role_lines = "" for role in sorted ( self . report [ "roles" ] ) : name = utils . normalize_role ( role , self . config ) galaxy_name = "{0}.{1}" . format ( self . config [ "scm_user" ] , name ) version_path = os . path . join ( self . roles_path , role , "VERSION" ) version = utils . get_version ( vers...
def _get_function_matches ( attributes_a , attributes_b , filter_set_a = None , filter_set_b = None ) : """: param attributes _ a : A dict of functions to their attributes : param attributes _ b : A dict of functions to their attributes The following parameters are optional . : param filter _ set _ a : A set ...
# get the attributes that are in the sets if filter_set_a is None : filtered_attributes_a = { k : v for k , v in attributes_a . items ( ) } else : filtered_attributes_a = { k : v for k , v in attributes_a . items ( ) if k in filter_set_a } if filter_set_b is None : filtered_attributes_b = { k : v for k , v ...
def DecryptPrivateKey ( self , encrypted_private_key ) : """Decrypt the provided ciphertext with the initialized private key . Args : encrypted _ private _ key ( byte string ) : the ciphertext to be decrypted . Returns : bytes : the ciphertext ."""
aes = AES . new ( self . _master_key , AES . MODE_CBC , self . _iv ) return aes . decrypt ( encrypted_private_key )
def _enqueue_fs_event ( self , event ) : """Watchman filesystem event handler for BUILD / requirements . txt updates . Called via a thread ."""
self . _logger . info ( 'enqueuing {} changes for subscription {}' . format ( len ( event [ 'files' ] ) , event [ 'subscription' ] ) ) self . _event_queue . put ( event )
def autodoc_tuple2doc ( module ) : """Include tuples as ` CLASSES ` of ` ControlParameters ` and ` RUN _ METHODS ` of ` Models ` into the respective docstring ."""
modulename = module . __name__ for membername , member in inspect . getmembers ( module ) : for tuplename , descr in _name2descr . items ( ) : tuple_ = getattr ( member , tuplename , None ) if tuple_ : logstring = f'{modulename}.{membername}.{tuplename}' if logstring not in _...
def _request_commit ( self , three_pc_key : Tuple [ int , int ] , recipients : List [ str ] = None ) -> bool : """Request commit"""
return self . _request_three_phase_msg ( three_pc_key , self . requested_commits , COMMIT , recipients )
def heatmaps_to_keypoints ( maps , rois ) : """Extract predicted keypoint locations from heatmaps . Output has shape ( # rois , 4 , # keypoints ) with the 4 rows corresponding to ( x , y , logit , prob ) for each keypoint ."""
# This function converts a discrete image coordinate in a HEATMAP _ SIZE x # HEATMAP _ SIZE image to a continuous keypoint coordinate . We maintain # consistency with keypoints _ to _ heatmap _ labels by using the conversion from # Heckbert 1990 : c = d + 0.5 , where d is a discrete coordinate and c is a # continuous c...
def replace_payment_token_by_id ( cls , payment_token_id , payment_token , ** kwargs ) : """Replace PaymentToken Replace all attributes of PaymentToken This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . replace _ pay...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _replace_payment_token_by_id_with_http_info ( payment_token_id , payment_token , ** kwargs ) else : ( data ) = cls . _replace_payment_token_by_id_with_http_info ( payment_token_id , payment_token , ** kwargs ) return data
def launch_server ( ) : """Launches the django server at 127.0.0.1:8000"""
print ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) cur_dir = os . getcwd ( ) path = os . path . dirname ( os . path . abspath ( __file__ ) ) run = True os . chdir ( path ) os . system ( 'python manage.py runserver --nostatic' ) os . chdir ( cur_dir )
def read ( filename ) : """Reads an unstructured mesh with added data . : param filenames : The files to read from . : type filenames : str : returns mesh { 2,3 } d : The mesh data . : returns point _ data : Point data read from file . : type point _ data : dict : returns field _ data : Field data read ...
mesh = meshio . read ( filename ) # make sure to include the used nodes only if "tetra" in mesh . cells : points , cells = _sanitize ( mesh . points , mesh . cells [ "tetra" ] ) return ( MeshTetra ( points , cells ) , mesh . point_data , mesh . cell_data , mesh . field_data , ) elif "triangle" in mesh . cells :...
def contains_python_files_or_subdirs ( folder ) : """Checks ( recursively ) if the directory contains . py or . pyc files"""
for root , dirs , files in os . walk ( folder ) : if [ filename for filename in files if filename . endswith ( '.py' ) or filename . endswith ( '.pyc' ) ] : return True for d in dirs : for _ , subdirs , subfiles in os . walk ( d ) : if [ filename for filename in subfiles if filename ...
def image_update ( call = None , kwargs = None ) : '''Replaces the image template contents . . . versionadded : : 2016.3.0 image _ id The ID of the image to update . Can be used instead of ` ` image _ name ` ` . image _ name The name of the image to update . Can be used instead of ` ` image _ id ` ` . p...
if call != 'function' : raise SaltCloudSystemExit ( 'The image_allocate function must be called with -f or --function.' ) if kwargs is None : kwargs = { } image_id = kwargs . get ( 'image_id' , None ) image_name = kwargs . get ( 'image_name' , None ) path = kwargs . get ( 'path' , None ) data = kwargs . get ( '...
def __EncodedAttribute_generic_encode_rgb24 ( self , rgb24 , width = 0 , height = 0 , quality = 0 , format = _ImageFormat . RawImage ) : """Internal usage only"""
if not is_seq ( rgb24 ) : raise TypeError ( "Expected sequence (str, numpy.ndarray, list, tuple " "or bytearray) as first argument" ) is_str = is_pure_str ( rgb24 ) if is_str : if not width or not height : raise ValueError ( "When giving a string as data, you must also " "supply width and height" ) if n...
async def iter_chunks ( self , chunk_size = _DEFAULT_CHUNK_SIZE ) : """Return an iterator to yield chunks of chunk _ size bytes from the raw stream ."""
while True : current_chunk = await self . read ( chunk_size ) if current_chunk == b"" : break await yield_ ( current_chunk )
def _set_ldp_ecmp ( self , v , load = False ) : """Setter method for ldp _ ecmp , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / ldp / ldp _ holder / ldp _ ecmp ( uint32) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ ldp _ ecmp is c...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'1..16' ] } ) , default = RestrictedClassTy...
def valid_ips ( self ) : """: return : A list of unicode strings of valid IP addresses for the certificate"""
if self . _valid_ips is None : self . _valid_ips = [ ] if self . subject_alt_name_value : for general_name in self . subject_alt_name_value : if general_name . name == 'ip_address' : self . _valid_ips . append ( general_name . native ) return self . _valid_ips
def _formatOntologyTerm ( self , element , element_type ) : """Formats the ontology terms for query"""
elementClause = None if isinstance ( element , dict ) and element . get ( 'terms' ) : elements = [ ] for _term in element [ 'terms' ] : if _term . get ( 'id' ) : elements . append ( '?{} = <{}> ' . format ( element_type , _term [ 'id' ] ) ) else : elements . append ( '?{}...
def kls_name ( self ) : """Determine python name for group"""
# Determine kls for group if not self . parent or not self . parent . name : return 'Test{0}' . format ( self . name ) else : use = self . parent . kls_name if use . startswith ( 'Test' ) : use = use [ 4 : ] return 'Test{0}_{1}' . format ( use , self . name )
def flush ( self ) : """Write self to . pyftpsync - meta . json ."""
# We DO write meta files even on read - only targets , but not in dry - run mode # if self . target . readonly : # write ( " DirMetadata . flush ( % s ) : read - only ; nothing to do " % self . target ) # return assert self . path == self . target . cur_dir if self . target . dry_run : # write ( " DirMetadata . flush (...
def setRules ( self , rules ) : """Sets all the rules for this builder . : param rules | [ < XQueryRule > , . . ]"""
if ( type ( rules ) in ( list , tuple ) ) : self . _rules = dict ( [ ( x . term ( ) , x ) for x in rules ] ) self . updateRules ( ) return True elif ( type ( rules ) == dict ) : self . _rules = rules . copy ( ) self . updateRules ( ) return True else : return False
def combine_neb_plots ( neb_analyses , arranged_neb_analyses = False , reverse_plot = False ) : """neb _ analyses : a list of NEBAnalysis objects arranged _ neb _ analyses : The code connects two end points with the smallest - energy difference . If all end points have very close energies , it ' s likely to r...
x = StructureMatcher ( ) for neb_index in range ( len ( neb_analyses ) ) : if neb_index == 0 : neb1 = neb_analyses [ neb_index ] neb1_energies = list ( neb1 . energies ) neb1_structures = neb1 . structures neb1_forces = neb1 . forces neb1_r = neb1 . r continue neb...
def with_params ( self , params ) : """Create a new request with added query parameters Parameters params : Mapping the query parameters to add"""
return self . replace ( params = _merge_maps ( self . params , params ) )
def _structmap ( self ) : """Returns structMap element for all files ."""
structmap = etree . Element ( utils . lxmlns ( "mets" ) + "structMap" , TYPE = "physical" , # TODO Add ability for multiple structMaps ID = "structMap_1" , # TODO don ' t hardcode this LABEL = "Archivematica default" , ) for item in self . _root_elements : child = item . serialize_structmap ( recurse = True ) i...
def _getOutputElegant ( self , ** kws ) : """get results from elegant output according to the given keywords , input parameter format : key = sdds field name tuple , e . g . : available keywords are : - ' file ' : sdds fielname , file = test . sig - ' data ' : data array , data = ( ' s ' , ' Sx ' ) - ' du...
datascript = "sddsprintdata.sh" datapath = self . sim_path trajparam_list = kws [ 'data' ] sddsfile = os . path . expanduser ( os . path . join ( self . sim_path , kws [ 'file' ] ) ) dh = datautils . DataExtracter ( sddsfile , * trajparam_list ) dh . setDataScript ( datascript ) dh . setDataPath ( datapath ) if 'dump' ...
def load_config ( ) : """Load a config file . This function looks for a config ( * . ini ) file in the following order : : (1 ) . / * . ini (2 ) ~ / . config / hydra / (3 ) / etc / hydra (4 ) / path / to / hydra _ base / * . ini (1 ) will override ( 2 ) will override ( 3 ) will override ( 4 ) . Paramete...
global localfiles global localfile global repofile global repofiles global userfile global userfiles global sysfile global sysfiles global CONFIG logging . basicConfig ( level = 'INFO' ) config = ConfigParser . ConfigParser ( allow_no_value = True ) modulepath = os . path . dirname ( os . path . abspath ( __file__ ) ) ...
def get_gen_info ( network , level = 'mvlv' , fluctuating = False ) : """Gets all the installed generators with some additional information . Parameters network : : class : ` ~ . grid . network . Network ` Network object holding the grid data . level : : obj : ` str ` Defines which generators are returned...
gens_w_id = [ ] if 'mv' in level : gens = network . mv_grid . generators gens_voltage_level = [ 'mv' ] * len ( gens ) gens_type = [ gen . type for gen in gens ] gens_rating = [ gen . nominal_capacity for gen in gens ] for gen in gens : try : gens_w_id . append ( gen . weather_cel...
async def listTaskGroup ( self , * args , ** kwargs ) : """List Task Group List tasks sharing the same ` taskGroupId ` . As a task - group may contain an unbounded number of tasks , this end - point may return a ` continuationToken ` . To continue listing tasks you must call the ` listTaskGroup ` again with...
return await self . _makeApiCall ( self . funcinfo [ "listTaskGroup" ] , * args , ** kwargs )
def runCommandSplits ( splits , silent = False , shell = False ) : """Run a shell command given the command ' s parsed command line"""
try : if silent : with open ( os . devnull , 'w' ) as devnull : subprocess . check_call ( splits , stdout = devnull , stderr = devnull , shell = shell ) else : subprocess . check_call ( splits , shell = shell ) except OSError as exception : if exception . errno == 2 : # cmd not f...
def date_range ( start_date , end_date , increment , period ) : """Generate ` date ` objects between ` start _ date ` and ` end _ date ` in ` increment ` ` period ` intervals ."""
next = start_date delta = relativedelta . relativedelta ( ** { period : increment } ) while next <= end_date : yield next next += delta
def asin ( x , context = None ) : """Return the inverse sine of ` ` x ` ` . The mathematically exact result lies in the range [ - π / 2 , π / 2 ] . However , note that as a result of rounding to the current context , it ' s possible for the actual value to lie just outside this range ."""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_asin , ( BigFloat . _implicit_convert ( x ) , ) , context , )
def close ( self ) : """Close the underlying connection ."""
self . _closed = True if self . receive_task : self . receive_task . cancel ( ) if self . connection : self . connection . close ( )
def remove_alt_text_language ( self , language_type ) : """Removes the specified alt _ text . raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` is ` ` true ` ` or ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` ` * compliance : mandatory - - This method must be implemented . *"""
if self . get_alt_texts_metadata ( ) . is_read_only ( ) : raise NoAccess ( ) self . remove_field_by_language ( 'altTexts' , language_type )
def _compute_p_value ( self , term_i ) : """compute the p - value of the desired feature Arguments term _ i : int term to select from the data Returns p _ value : float Notes Wood 2006 , section 4.8.5: The p - values , calculated in this manner , behave correctly for un - penalized models , or mod...
if not self . _is_fitted : raise AttributeError ( 'GAM has not been fitted. Call fit first.' ) idxs = self . terms . get_coef_indices ( term_i ) cov = self . statistics_ [ 'cov' ] [ idxs ] [ : , idxs ] coef = self . coef_ [ idxs ] # center non - intercept term functions if isinstance ( self . terms [ term_i ] , Spl...
def get_hashes_from_search ( self , query , page = None ) : """Get the scan results for a file . Even if you do not have a Private Mass API key that you can use , you can still automate VirusTotal Intelligence searches pretty much in the same way that the searching for files api call works . : param query : a...
params = { 'query' : query , 'apikey' : self . api_key , 'page' : page } try : response = requests . get ( self . base + 'search/programmatic/' , params = params , proxies = self . proxies ) except requests . RequestException as e : return dict ( error = e . message ) return response . json ( ) [ 'next_page' ] ...
def list_packages ( self , ** kwargs ) : """List active packages . : returns : List of active packages ."""
get_kwargs = { } get_kwargs [ 'mask' ] = kwargs . get ( 'mask' , PACKAGE_MASK ) if 'filter' in kwargs : get_kwargs [ 'filter' ] = kwargs [ 'filter' ] packages = self . package_svc . getAllObjects ( ** get_kwargs ) return [ package for package in packages if package [ 'isActive' ] ]
def add_async_sender ( self , partition = None , operation = None , send_timeout = 60 , keep_alive = 30 , auto_reconnect = True , loop = None ) : """Add an async sender to the client to send ~ azure . eventhub . common . EventData object to an EventHub . : param partition : Optionally specify a particular parti...
target = "amqps://{}{}" . format ( self . address . hostname , self . address . path ) if operation : target = target + operation handler = AsyncSender ( self , target , partition = partition , send_timeout = send_timeout , keep_alive = keep_alive , auto_reconnect = auto_reconnect , loop = loop ) self . clients . a...
def _counts_at_position ( positions , orig_reader , cmp_reader ) : """Combine orignal and new qualities at each position , generating counts ."""
pos_counts = collections . defaultdict ( lambda : collections . defaultdict ( lambda : collections . defaultdict ( int ) ) ) for orig_parts in orig_reader : cmp_parts = next ( cmp_reader ) for pos in positions : try : pos_counts [ pos ] [ int ( orig_parts [ pos + 1 ] ) ] [ int ( cmp_parts [ ...
def interpolate ( dataset , points , sharpness = 2 , radius = 1.0 , dimensions = ( 101 , 101 , 101 ) , pass_cell_arrays = True , pass_point_arrays = True ) : """Interpolate values onto this mesh from the point data of a given : class : ` vtki . PolyData ` object ( typically a point cloud ) . This uses a guassia...
bounds = np . array ( dataset . bounds ) dimensions = np . array ( dimensions ) box = vtki . UniformGrid ( ) box . dimensions = dimensions box . spacing = ( bounds [ 1 : : 2 ] - bounds [ : - 1 : 2 ] ) / ( dimensions - 1 ) box . origin = bounds [ : : 2 ] gaussian_kernel = vtk . vtkGaussianKernel ( ) gaussian_kernel . Se...
def xstep ( self ) : r"""Minimise Augmented Lagrangian with respect to : math : ` \ mathbf { x } ` ."""
self . cgit = None self . YU [ : ] = self . Y - self . U b = self . ZSf + self . rho * sl . rfftn ( self . YU , None , self . cri . axisN ) self . Xf [ : ] , cgit = sl . solvemdbi_cg ( self . Zf , self . rho , b , self . cri . axisM , self . cri . axisK , self . opt [ 'CG' , 'StopTol' ] , self . opt [ 'CG' , 'MaxIter' ...
def _before_cursor_execute ( conn , cursor , statement , parameters , context , executemany ) : """Intercept low - level cursor execute ( ) events before execution . If executemany is True , this is an executemany call , else an execute call . Note : If enabled tracing both SQLAlchemy and the database it connec...
# Find out the func name if executemany : query_func = 'executemany' else : query_func = 'execute' _tracer = execution_context . get_opencensus_tracer ( ) _span = _tracer . start_span ( ) _span . name = '{}.query' . format ( MODULE_NAME ) _span . span_kind = span_module . SpanKind . CLIENT # Set query statement...
def make_ring_filelist ( self , sourcekeys , rings , galprop_run ) : """Make a list of all the template files for a merged component Parameters sourcekeys : list - like of str The names of the componenents to merge rings : list - like of int The indices of the rings to merge galprop _ run : str String...
flist = [ ] for sourcekey in sourcekeys : for ring in rings : flist += [ self . make_ring_filename ( sourcekey , ring , galprop_run ) ] return flist
def find_module ( self , fullname , path = None ) : """Return self when fullname starts with root _ name and the target module is one vendored through this importer ."""
root , base , target = fullname . partition ( self . root_name + '.' ) if root : return if not any ( map ( target . startswith , self . vendored_names ) ) : return return self
def run_inline_script ( host , name = None , port = 22 , timeout = 900 , username = 'root' , key_filename = None , inline_script = None , ssh_timeout = 15 , display_ssh_output = True , parallel = False , sudo_password = None , sudo = False , password = None , tty = None , opts = None , tmp_dir = '/tmp/.saltcloud-inline...
gateway = None if 'gateway' in kwargs : gateway = kwargs [ 'gateway' ] starttime = time . mktime ( time . localtime ( ) ) log . debug ( 'Deploying %s at %s' , host , starttime ) known_hosts_file = kwargs . get ( 'known_hosts_file' , '/dev/null' ) if wait_for_port ( host = host , port = port , gateway = gateway ) : ...