signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def read ( file_name = None , is_encoding = True , ignore_raises = False ) :
"""Read file""" | if file_name is None :
raise Exception ( "File name not provided" )
if ignore_raises :
try :
return read_file ( is_encoding = is_encoding , file_path = path_format ( file_path = CURR_PATH , file_name = file_name , ignore_raises = ignore_raises ) )
except Exception : # TODO : not silence like this ,
... |
def fit ( self , x , y ) :
""": param x : 2D np . ndarray ( n _ instances , n _ features ) should be categorical data , must be of type int
: param y : 1D np . ndarray ( n _ instances , ) labels
: return :""" | verbose = self . verbose
# Create temporary files
data_file = tempfile . NamedTemporaryFile ( "w+b" , delete = False )
label_file = tempfile . NamedTemporaryFile ( "w+b" , delete = False )
start = time . time ( )
raw_rules = categorical2pysbrl_data ( x , y , data_file . name , label_file . name , supp = self . min_supp... |
def paga_path ( adata , nodes , keys , use_raw = True , annotations = [ 'dpt_pseudotime' ] , color_map = None , color_maps_annotations = { 'dpt_pseudotime' : 'Greys' } , palette_groups = None , n_avg = 1 , groups_key = None , xlim = [ None , None ] , title = None , left_margin = None , ytick_fontsize = None , title_fon... | ax_was_none = ax is None
if groups_key is None :
if 'groups' not in adata . uns [ 'paga' ] :
raise KeyError ( 'Pass the key of the grouping with which you ran PAGA, ' 'using the parameter `groups_key`.' )
groups_key = adata . uns [ 'paga' ] [ 'groups' ]
groups_names = adata . obs [ groups_key ] . cat . ... |
def ontologyClassTree ( self ) :
"""Returns a dict representing the ontology tree
Top level = { 0 : [ top classes ] }
Multi inheritance is represented explicitly""" | treedict = { }
if self . all_classes :
treedict [ 0 ] = self . toplayer_classes
for element in self . all_classes :
if element . children ( ) :
treedict [ element ] = element . children ( )
return treedict
return treedict |
def setExpressCheckout ( self , params ) :
"""Initiates an Express Checkout transaction .
Optionally , the SetExpressCheckout API operation can set up billing agreements for
reference transactions and recurring payments .
Returns a NVP instance - check for token and payerid to continue !""" | if self . _is_recurring ( params ) :
params = self . _recurring_setExpressCheckout_adapter ( params )
defaults = { "method" : "SetExpressCheckout" , "noshipping" : 1 }
required = [ "returnurl" , "cancelurl" , "paymentrequest_0_amt" ]
nvp_obj = self . _fetch ( params , required , defaults )
if nvp_obj . flag :
r... |
def _cartesian_to_spherical ( cls , coord , center ) :
"""Cartesian to Spherical conversion
. . warning : : The spherical form is equatorial , not zenithal""" | x , y , z , vx , vy , vz = coord
r = np . linalg . norm ( coord [ : 3 ] )
phi = arcsin ( z / r )
theta = arctan2 ( y , x )
r_dot = ( x * vx + y * vy + z * vz ) / r
phi_dot = ( vz * ( x ** 2 + y ** 2 ) - z * ( x * vx + y * vy ) ) / ( r ** 2 * sqrt ( x ** 2 + y ** 2 ) )
theta_dot = ( x * vy - y * vx ) / ( x ** 2 + y ** 2... |
def get_filter ( cls , mimetype ) :
"""Returns a filter string for the file dialog . The filter is based
on the mime type .
: param mimetype : path from which the filter must be derived .
: return : Filter string""" | filters = ' ' . join ( [ '*%s' % ext for ext in mimetypes . guess_all_extensions ( mimetype ) ] )
return '%s (%s)' % ( mimetype , filters ) |
def _post_document_batch ( self , batch ) :
"""Send a batch to Cloudsearch endpoint
See : http : / / docs . aws . amazon . com / cloudsearch / latest / developerguide / submitting - doc - requests . html""" | # noqa
target_batch = '/2013-01-01/documents/batch'
url = self . endpoint_url + target_batch
return requests . post ( url , data = batch , headers = { 'Content-type' : 'application/json' } ) |
def _check_fill_title_row ( self , row_index ) :
'''Checks the given row to see if it is all titles and fills any blanks cells if that is the
case .''' | table_row = self . table [ row_index ]
# Determine if the whole row is titles
prior_row = self . table [ row_index - 1 ] if row_index > 0 else table_row
for column_index in range ( self . start [ 1 ] , self . end [ 1 ] ) :
if is_num_cell ( table_row [ column_index ] ) or is_num_cell ( prior_row [ column_index ] ) :... |
def getFileAuthor ( self , fileInfo ) :
"""Function to get the file ' s author for file info , note that we are pretending that multiple authors do not exist here""" | author = fileInfo [ fileInfo . find ( "Author" ) : ]
author = author [ author . find ( "<FONT " ) + 47 : ]
author = author [ author . find ( '<B>' ) + 3 : ]
authormail = author [ author . find ( "mailto:" ) + 7 : ]
authormail = authormail [ : authormail . find ( '"' ) ]
author = author [ : author . find ( "</B></A>" ) ... |
def replicate_methods ( srcObj , dstObj ) :
"""Replicate callable methods from a ` srcObj ` to ` dstObj ` ( generally a wrapper object ) .
@ param srcObj : source object
@ param dstObj : destination object of the same type .
@ return : none
Implementer notes :
1 . Once the methods are mapped from the ` sr... | # prevent methods that we intend to specialize from being mapped . The specialized
# ( overridden ) methods are methods with the same name as the corresponding method in
# the source ZOS API COM object written for each ZOS API COM object in an associated
# python script such as i _ analyses _ methods . py for I _ Analy... |
def diff ( self , ** kwargs ) :
"""Generate the commit diff .
Args :
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenticationError : If authentication is not correct
GitlabGetError : If the diff could not be retrieved
Returns :
list : The changes done in this com... | path = '%s/%s/diff' % ( self . manager . path , self . get_id ( ) )
return self . manager . gitlab . http_get ( path , ** kwargs ) |
def write_all ( self , data ) :
""": param list [ int ] data :""" | self . _set_cursor_x ( 0 )
self . _set_cursor_y ( 0 )
self . DC . on ( )
self . _write ( data ) |
def is_fifo ( self ) :
"""Whether this path is a FIFO .""" | try :
return S_ISFIFO ( self . stat ( ) . st_mode )
except OSError as e :
if e . errno not in ( ENOENT , ENOTDIR ) :
raise
# Path doesn ' t exist or is a broken symlink
# ( see https : / / bitbucket . org / pitrou / pathlib / issue / 12 / )
return False |
def parse_release_id ( release_id ) :
"""Parse release _ id to parts :
{ short , version , type }
or
{ short , version , type , bp _ short , bp _ version , bp _ type }
: param release _ id : Release ID string
: type release _ id : str
: rtype : dict""" | if "@" in release_id :
release , base_product = release_id . split ( "@" )
else :
release = release_id
base_product = None
result = _parse_release_id_part ( release )
if base_product is not None :
result . update ( _parse_release_id_part ( base_product , prefix = "bp_" ) )
return result |
def get_vectors_loss ( ops , docs , prediction , objective = "L2" ) :
"""Compute a mean - squared error loss between the documents ' vectors and
the prediction .
Note that this is ripe for customization ! We could compute the vectors
in some other word , e . g . with an LSTM language model , or use some other... | # The simplest way to implement this would be to vstack the
# token . vector values , but that ' s a bit inefficient , especially on GPU .
# Instead we fetch the index into the vectors table for each of our tokens ,
# and look them up all at once . This prevents data copying .
ids = ops . flatten ( [ doc . to_array ( I... |
def inverse ( self ) :
"""Return the inverse of the graph .
@ rtype : graph
@ return : Complement graph for the graph .""" | inv = self . __class__ ( )
inv . add_nodes ( self . nodes ( ) )
inv . complete ( )
for each in self . edges ( ) :
if ( inv . has_edge ( each ) ) :
inv . del_edge ( each )
return inv |
def search_channels ( self , ** kwargs ) :
"""Search for all channels by parameters""" | params = [ ( key , kwargs [ key ] ) for key in sorted ( kwargs . keys ( ) ) ]
url = "/notification/v1/channel?{}" . format ( urlencode ( params , doseq = True ) )
response = NWS_DAO ( ) . getURL ( url , self . _read_headers )
if response . status != 200 :
raise DataFailureException ( url , response . status , respo... |
def _deserialize ( self , value , attr , data , ** kwargs ) :
"""Deserialize an ISO8601 - formatted time to a : class : ` datetime . time ` object .""" | if not value : # falsy values are invalid
self . fail ( 'invalid' )
try :
return utils . from_iso_time ( value )
except ( AttributeError , TypeError , ValueError ) :
self . fail ( 'invalid' ) |
def _ctypes_assign ( parameter ) :
"""Returns the Fortran code lines to allocate and assign values to the * original *
parameter ValueElement that exists now only as a local variable so that the
signatures match for the compiler .""" | # If the array is set to only have intent ( out ) , we don ' t want to allocate or assign
# a value to it ; otherwise we do .
if ( parameter . direction != "(out)" and ( "allocate" in parameter . modifiers or "pointer" in parameter . modifiers or "target" in parameter . modifiers ) ) :
if "in" in parameter . direct... |
def _register_device ( self , device_description , permitted_ips ) :
""": type device _ description : str
: type permitted _ ips : list [ ]
: rtype : None""" | from bunq . sdk . model . device_server_internal import DeviceServerInternal
DeviceServerInternal . create ( device_description , self . api_key , permitted_ips , api_context = self ) |
def setStoragePath ( self , location , path ) :
"""Returns the path associated with this application and user for the
given location .
: param location | < QtGui . QDesktopServices . StandardLocation >
path | < str > | | None
: return < str >""" | if not path :
self . _storagePaths . pop ( location , None )
else :
self . _storagePaths [ location ] = path |
def dot ( desc , color , title = "Trump's ORM" ) :
"""Generate dot file
: param desc : result of sadisplay . describe function
Return string""" | classes , relations , inherits = desc
CLASS_TEMPLATE = """
%(name)s [label=<
<TABLE BGCOLOR="{ncolor}" BORDER="0"
CELLBORDER="0" CELLSPACING="0">
<TR><TD COLSPAN="2" CELLPADDING="4"
ALIGN="CENTER" BGCOLOR="{ncolor}"
><FONT FACE="Helveti... |
def submit ( self , call , * args , ** kwargs ) :
"""Submit a call for future execution
: return : future for the call execution
: rtype : StoredFuture""" | future = StoredFuture ( call , * args , ** kwargs )
self . _queue . put ( future )
self . _ensure_worker ( )
return future |
def percent_pareto_interactions ( records , percentage = 0.8 ) :
"""The percentage of user ' s contacts that account for 80 % of its interactions .""" | if len ( records ) == 0 :
return None
user_count = Counter ( r . correspondent_id for r in records )
target = int ( math . ceil ( sum ( user_count . values ( ) ) * percentage ) )
user_sort = sorted ( user_count . keys ( ) , key = lambda x : user_count [ x ] )
while target > 0 and len ( user_sort ) > 0 :
user_id... |
def values ( self , * keys ) :
"""Return the values of the record , optionally filtering to
include only certain values by index or key .
: param keys : indexes or keys of the items to include ; if none
are provided , all values will be included
: return : list of values""" | if keys :
d = [ ]
for key in keys :
try :
i = self . index ( key )
except KeyError :
d . append ( None )
else :
d . append ( self [ i ] )
return d
return list ( self ) |
def add_package_dependency ( self , package_name , version ) :
"""Add a package to the list of dependencies .
: param package _ name : The name of the package dependency
: type package _ name : str
: param version : The ( minimum ) version of the package
: type version : str""" | if not PEP440_VERSION_PATTERN . match ( version ) :
raise ValueError ( 'Invalid Version: "{}"' . format ( version ) )
self . dependencies . add ( PackageDependency ( package_name , version ) ) |
def from_dict ( cls , d : dict , force_snake_case : bool = True , force_cast : bool = False , restrict : bool = True ) -> T :
"""From dict to instance
: param d : Dict
: param force _ snake _ case : Keys are transformed to snake case in order to compliant PEP8 if True
: param force _ cast : Cast forcibly if T... | if isinstance ( d , cls ) :
return d
instance : T = cls ( )
d = util . replace_keys ( d , { "self" : "_self" } , force_snake_case )
properties = cls . __annotations__ . items ( )
if restrict :
assert_extra ( properties , d , cls )
for n , t in properties :
f = cls . _methods_dict . get ( f'_{cls.__name__}__... |
def setup_logging ( logfile , print_log_location = True , debug = False ) :
'''Set up logging using the built - in ` ` logging ` ` package .
A stream handler is added to all logs , so that logs at or above
` ` logging . INFO ` ` level are printed to screen as well as written
to the log file .
Arguments :
... | log_dir = os . path . dirname ( logfile )
make_dir ( log_dir )
fmt = '[%(levelname)s] %(name)s %(asctime)s %(message)s'
if debug :
logging . basicConfig ( filename = logfile , filemode = 'w' , format = fmt , level = logging . DEBUG )
else :
logging . basicConfig ( filename = logfile , filemode = 'w' , format = ... |
def is_all_field_none ( self ) :
""": rtype : bool""" | if self . _billing_date is not None :
return False
if self . _type_description is not None :
return False
if self . _type_description_translated is not None :
return False
if self . _unit_vat_exclusive is not None :
return False
if self . _unit_vat_inclusive is not None :
return False
if self . _vat... |
def get_global_dist_packages_dir ( ) :
"""Attempts to work around virtualenvs and find the system dist _ pacakges .
Essentially this is implmenented as a lookuptable""" | import utool as ut
if not ut . in_virtual_env ( ) : # Non venv case
return get_site_packages_dir ( )
else :
candidates = [ ]
if ut . LINUX :
import sys
candidates += [ '/usr/lib/python%s/dist-packages' % ( sys . version [ 0 : 3 ] , ) , '/usr/lib/python%s/dist-packages' % ( sys . version [ 0 ... |
async def popen_xboard ( command : Union [ str , List [ str ] ] , * , setpgrp : bool = False , ** popen_args : Any ) -> Tuple [ asyncio . SubprocessTransport , XBoardProtocol ] :
"""Spawns and initializes an XBoard engine .
: param command : Path of the engine executable , or a list including the
path and argum... | transport , protocol = await XBoardProtocol . popen ( command , setpgrp = setpgrp , ** popen_args )
try :
await protocol . initialize ( )
except :
transport . close ( )
raise
return transport , protocol |
def _create_variables ( self , n_features , W_ = None , bh_ = None , bv_ = None ) :
"""Create the TensorFlow variables for the model .
: return : self""" | if W_ :
self . W_ = tf . Variable ( W_ , name = 'enc-w' )
else :
self . W_ = tf . Variable ( tf . truncated_normal ( shape = [ n_features , self . n_components ] , stddev = 0.1 ) , name = 'enc-w' )
if bh_ :
self . bh_ = tf . Variable ( bh_ , name = 'hidden-bias' )
else :
self . bh_ = tf . Variable ( tf ... |
def parse_block ( lines , header = False ) : # type : ( List [ str ] , bool ) - > List [ str ]
"""Parse and return a single block , popping off the start of ` lines ` .
If parsing a header block , we stop after we reach a line that is not a
comment . Otherwise , we stop after reaching an empty line .
: param ... | block_lines = [ ]
while lines and lines [ 0 ] and ( not header or lines [ 0 ] . startswith ( '#' ) ) :
block_lines . append ( lines . pop ( 0 ) )
return block_lines |
def delete ( self , doc_id : str ) -> bool :
"""Delete a document with id .""" | try :
self . instance . delete ( self . index , self . doc_type , doc_id )
except RequestError as ex :
logging . error ( ex )
return False
else :
return True |
def find_unconserved_metabolites ( model ) :
"""Detect unconserved metabolites .
Parameters
model : cobra . Model
The metabolic model under investigation .
Notes
See [ 1 ] _ section 3.2 for a complete description of the algorithm .
. . [ 1 ] Gevorgyan , A . , M . G Poolman , and D . A Fell .
" Detecti... | problem = model . problem
stoich_trans = problem . Model ( )
internal_rxns = con_helpers . get_internals ( model )
metabolites = set ( met for rxn in internal_rxns for met in rxn . metabolites )
# The binary variables k [ i ] in the paper .
k_vars = list ( )
for met in metabolites : # The element m [ i ] of the mass ve... |
def _print_figures ( figures , arguments = '' , file_format = 'pdf' , target_width = 8.5 , target_height = 11.0 , target_pad = 0.5 ) :
"""figure printing loop designed to be launched in a separate thread .""" | for fig in figures : # get the temp path
temp_path = _os . path . join ( _settings . path_home , "temp" )
# make the temp folder
_settings . MakeDir ( temp_path )
# output the figure to postscript
path = _os . path . join ( temp_path , "graph." + file_format )
# get the dimensions of the figure ... |
def log ( message , type ) :
"""Log notices to stdout and errors to stderr""" | ( sys . stdout if type == 'notice' else sys . stderr ) . write ( message + "\n" ) |
def remove_in_progress_check ( self , check ) :
"""Remove check from check in progress
: param check : Check to remove
: type check : alignak . objects . check . Check
: return : None""" | # The check is consumed , update the in _ checking properties
if check in self . checks_in_progress :
self . checks_in_progress . remove ( check )
self . update_in_checking ( ) |
def _prepare_vcf_rec ( rec , pops , known , impact_info ) :
"""Parse a vcfanno output into a dictionary of useful attributes .""" | out = { }
for k in pops + known :
out [ k ] = rec . INFO . get ( k )
if impact_info :
cur_info = rec . INFO . get ( impact_info . id )
if cur_info :
cur_impacts = [ impact_info . gclass ( e , impact_info . header ) for e in _from_bytes ( cur_info ) . split ( "," ) ]
top = geneimpacts . Effec... |
def xray ( im , direction = 'X' ) :
r"""Simulates an X - ray radiograph looking through the porouls material in the
specfied direction . The resulting image is colored according to the amount
of attenuation an X - ray would experience , so regions with more solid will
appear darker .
Parameters
im : array... | im = sp . array ( ~ im , dtype = int )
if direction in [ 'Y' , 'y' ] :
im = sp . transpose ( im , axes = [ 1 , 0 , 2 ] )
if direction in [ 'Z' , 'z' ] :
im = sp . transpose ( im , axes = [ 2 , 1 , 0 ] )
im = sp . sum ( im , axis = 0 )
return im |
def list_nic ( self , instance_id ) :
"""List all Network Interface Controller""" | output = self . client . describe_instances ( InstanceIds = [ instance_id ] )
output = output . get ( "Reservations" ) [ 0 ] . get ( "Instances" ) [ 0 ]
return output . get ( "NetworkInterfaces" ) |
def create_sandbox ( name = 'healthybox' ) :
"""Create a temporary sandbox directory
: param name : name of the directory to create
: return : The directory created""" | sandbox = tempfile . mkdtemp ( prefix = name )
if not os . path . isdir ( sandbox ) :
os . mkdir ( sandbox )
return sandbox |
def LE64 ( value , min_value = None , max_value = None , fuzzable = True , name = None , full_range = False ) :
'''64 - bit field , Little endian encoded''' | return UInt64 ( value , min_value = min_value , max_value = max_value , encoder = ENC_INT_LE , fuzzable = fuzzable , name = name , full_range = full_range ) |
def _get_page_with_optional_heading ( self , page_file_path : str ) -> str or Dict :
'''Get the content of first heading of source Markdown file , if the file
contains any headings . Return a data element of ` ` pages ` ` section
of ` ` mkdocs . yml ` ` file .
: param page _ file _ path : path to source Markd... | self . logger . debug ( f'Looking for the first heading in {page_file_path}' )
if page_file_path . endswith ( '.md' ) :
page_file_full_path = self . project_path / self . config [ 'src_dir' ] / page_file_path
with open ( page_file_full_path , encoding = 'utf8' ) as page_file :
content = page_file . read... |
def halted ( self ) :
"""Returns whether the CPU core was halted .
Args :
self ( JLink ) : the ` ` JLink ` ` instance
Returns :
` ` True ` ` if the CPU core is halted , otherwise ` ` False ` ` .
Raises :
JLinkException : on device errors .""" | result = int ( self . _dll . JLINKARM_IsHalted ( ) )
if result < 0 :
raise errors . JLinkException ( result )
return ( result > 0 ) |
def set_python ( self , value ) :
"""Set field internal value from the python representation of field value""" | # hook exists to stringify before validation
# set to string if not string or unicode
if value is not None and not isinstance ( value , self . supported_types ) or isinstance ( value , int ) :
value = str ( value )
return super ( TextField , self ) . set_python ( value ) |
def bytes2unicode ( x , encoding = 'utf-8' , errors = 'strict' ) :
"""Convert a C { bytes } to a unicode string .
@ param x : a unicode string , of type C { unicode } on Python 2,
or C { str } on Python 3.
@ param encoding : an optional codec , default : ' utf - 8'
@ param errors : error handling scheme , d... | if isinstance ( x , ( text_type , type ( None ) ) ) :
return x
return text_type ( x , encoding , errors ) |
def remove ( self , * terminals ) : # type : ( Iterable [ Any ] ) - > None
"""Remove terminals from the set .
Removes also rules using this terminal .
: param terminals : Terminals to remove .
: raise KeyError if the object is not in the set .""" | for term in set ( terminals ) :
if term not in self :
raise KeyError ( 'Terminal ' + str ( term ) + ' is not inside' )
self . _grammar . rules . remove ( * self . _assign_map [ term ] , _validate = False )
del self . _assign_map [ term ]
super ( ) . remove ( term ) |
def _load_zp_mappings ( self , file ) :
"""Given a file that defines the mapping between
ZFIN - specific EQ definitions and the automatically derived ZP ids ,
create a mapping here .
This may be deprecated in the future
: return :""" | zp_map = { }
LOG . info ( "Loading ZP-to-EQ mappings" )
line_counter = 0
with open ( file , 'r' , encoding = "utf-8" ) as csvfile :
filereader = csv . reader ( csvfile , delimiter = '\t' , quotechar = '\"' )
for row in filereader :
line_counter += 1
( zp_id , zp_label , superterm1_id , subterm1_... |
def create_output_directory ( cls , outdir ) :
"""Tries to create base output directory""" | cls . PATH = outdir
try :
os . mkdir ( outdir )
except FileExistsError :
pass |
def _find_v1_settings ( self , settings ) :
"""Parse a v1 module _ settings . json file .
V1 is the older file format that requires a modules dictionary with a
module _ name and modules key that could in theory hold information on
multiple modules in a single directory .""" | if 'module_name' in settings :
modname = settings [ 'module_name' ]
if 'modules' not in settings or len ( settings [ 'modules' ] ) == 0 :
raise DataError ( "No modules defined in module_settings.json file" )
elif len ( settings [ 'modules' ] ) > 1 :
raise DataError ( "Multiple modules defined in module_sett... |
def createEditor ( self , delegate , parent , option ) :
"""Creates a ChoiceCtiEditor .
For the parameters see the AbstractCti constructor documentation .""" | return FontChoiceCtiEditor ( self , delegate , parent = parent ) |
def _get_random_id ( ) :
"""Get a random ( i . e . , unique ) string identifier""" | symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits
return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) ) |
def replace_project ( self , owner , id , ** kwargs ) :
"""Create / Replace a project
Create a project with a given id or completely rewrite the project , including any previously added files or linked datasets , if one already exists with the given id .
This method makes a synchronous HTTP request by default .... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . replace_project_with_http_info ( owner , id , ** kwargs )
else :
( data ) = self . replace_project_with_http_info ( owner , id , ** kwargs )
return data |
def extra_symlinked_files ( self , potential_symlinks ) :
"""Find any symlinkd folders and yield SymlinkdPath objects for each file
that is found under the symlink .""" | for key in list ( potential_symlinks ) :
location = os . path . join ( self . root_folder , key . path )
real_location = os . path . realpath ( location )
if os . path . islink ( location ) and os . path . isdir ( real_location ) :
for root , dirs , files in os . walk ( real_location , followlinks =... |
def validate_reference_links ( reference_links ) :
"""Vaidate reference links data structure
Expected data structure :
" links " : {
id _ type1 : url1,
id _ type2 : url2
" redirect _ id _ type " : id _ type1 | id1 _ type2
where links is an optional key but must be a dictionary with id types to
URLs if... | allowed_keys = [ 'links' , 'redirect_id_type' ]
if not isinstance ( reference_links , dict ) :
raise Invalid ( 'Expected reference_links to be an object' )
if 'links' in reference_links and not isinstance ( reference_links [ 'links' ] , dict ) :
raise Invalid ( 'Expected links in reference_links to be an object... |
def engagements ( self ) :
"""Access the engagements
: returns : twilio . rest . studio . v1 . flow . engagement . EngagementList
: rtype : twilio . rest . studio . v1 . flow . engagement . EngagementList""" | if self . _engagements is None :
self . _engagements = EngagementList ( self . _version , flow_sid = self . _solution [ 'sid' ] , )
return self . _engagements |
def _repr_pretty_ ( self , p : Any , cycle : bool ) -> None :
"""Print ASCII diagram in Jupyter .""" | if cycle : # There should never be a cycle . This is just in case .
p . text ( 'Circuit(...)' )
else :
p . text ( self . to_text_diagram ( ) ) |
def filter ( self , table , idps , filter_string ) :
"""Naive case - insensitive search .""" | q = filter_string . lower ( )
return [ idp for idp in idps if q in idp . ud . lower ( ) ] |
def ParseFloat ( text ) :
"""Parse a floating point number .
Args :
text : Text to parse .
Returns :
The number parsed .
Raises :
ValueError : If a floating point number couldn ' t be parsed .""" | try : # Assume Python compatible syntax .
return float ( text )
except ValueError : # Check alternative spellings .
if _FLOAT_INFINITY . match ( text ) :
if text [ 0 ] == '-' :
return float ( '-inf' )
else :
return float ( 'inf' )
elif _FLOAT_NAN . match ( text ) :
... |
def checkArgs ( args ) :
"""Checks the arguments and options .
: param args : an object containing the options of the program .
: type args : argparse . Namespace
: returns : ` ` True ` ` if everything was OK .
If there is a problem with an option , an exception is raised using the
: py : class : ` Progra... | # Checking the input file
for file_name in [ args . tfile + i for i in { ".tfam" , ".tped" } ] :
if not os . path . isfile ( file_name ) :
msg = "{}: no such file" . format ( file_name )
raise ProgramError ( msg )
# Checking the xlimit
if args . xlim is not None :
if args . xlim [ 0 ] >= args . ... |
def check_type_and_values_of_alt_name_dict ( alt_name_dict , alt_id_col , df ) :
"""Ensures that ` alt _ name _ dict ` is a dictionary and that its keys are in the
alternative id column of ` df ` . Raises helpful errors if either condition
is not met .
Parameters
alt _ name _ dict : dict .
A dictionary wh... | if not isinstance ( alt_name_dict , dict ) :
msg = "alt_name_dict should be a dictionary. Passed value was a {}"
raise TypeError ( msg . format ( type ( alt_name_dict ) ) )
if not all ( [ x in df [ alt_id_col ] . values for x in alt_name_dict . keys ( ) ] ) :
msg = "One or more of alt_name_dict's keys are n... |
def setEnable ( self , status , lanInterfaceId = 1 , timeout = 1 ) :
"""Set enable status for a LAN interface , be careful you don ' t cut yourself off .
: param bool status : enable or disable the interface
: param int lanInterfaceId : the id of the LAN interface
: param float timeout : the timeout to wait f... | namespace = Lan . getServiceType ( "setEnable" ) + str ( lanInterfaceId )
uri = self . getControlURL ( namespace )
if status :
setStatus = 1
else :
setStatus = 0
self . execute ( uri , namespace , "SetEnable" , timeout = timeout , NewEnable = setStatus ) |
def __step4 ( self ) :
"""Find a noncovered zero and prime it . If there is no starred zero
in the row containing this primed zero , Go to Step 5 . Otherwise ,
cover this row and uncover the column containing the starred
zero . Continue in this manner until there are no uncovered zeros
left . Save the small... | step = 0
done = False
row = - 1
col = - 1
star_col = - 1
while not done :
( row , col ) = self . __find_a_zero ( )
if row < 0 :
done = True
step = 6
else :
self . marked [ row ] [ col ] = 2
star_col = self . __find_star_in_row ( row )
if star_col >= 0 :
co... |
def help ( self ) :
"""Display command usage information .""" | if self . params :
command = self . params . pop ( ) . lstrip ( '-' )
if command in self . command . documentation :
( aliases , doc ) = self . command . documentation [ command ]
( synopsis , body ) = self . _split_docstring ( doc )
print ( synopsis )
if body :
print... |
def move_application ( self , app_id , queue ) :
"""Move an application to a different queue .
Parameters
app _ id : str
The id of the application to move .
queue : str
The queue to move the application to .""" | self . _call ( 'moveApplication' , proto . MoveRequest ( id = app_id , queue = queue ) ) |
def doc ( * args ) :
'''Return the docstrings for all modules . Optionally , specify a module or a
function to narrow the selection .
The strings are aggregated into a single document on the master for easy
reading .
Multiple modules / functions can be specified .
CLI Example :
. . code - block : : bash... | docs = { }
if not args :
for fun in __salt__ :
docs [ fun ] = __salt__ [ fun ] . __doc__
return _strip_rst ( docs )
for module in args :
_use_fnmatch = False
if '*' in module :
target_mod = module
_use_fnmatch = True
elif module : # allow both " sys " and " sys . " to match s... |
def scatter_plot ( data , x , y , by = None , ax = None , figsize = None , grid = False , ** kwargs ) :
"""Make a scatter plot from two DataFrame columns
Parameters
data : DataFrame
x : Column name for the x - axis values
y : Column name for the y - axis values
ax : Matplotlib axis object
figsize : A tu... | import matplotlib . pyplot as plt
kwargs . setdefault ( 'edgecolors' , 'none' )
def plot_group ( group , ax ) :
xvals = group [ x ] . values
yvals = group [ y ] . values
ax . scatter ( xvals , yvals , ** kwargs )
ax . grid ( grid )
if by is not None :
fig = _grouped_plot ( plot_group , data , by = b... |
def upsert ( self , events ) :
"""Inserts / updates the given events into MySQL""" | existing = self . get_existing_keys ( events )
inserts = [ e for e in events if not e [ self . key ] in existing ]
updates = [ e for e in events if e [ self . key ] in existing ]
self . insert ( inserts )
self . update ( updates ) |
def generate_voxel_image ( network , pore_shape = "sphere" , throat_shape = "cylinder" , max_dim = None , verbose = 1 , rtol = 0.1 ) :
r"""Generates voxel image from an OpenPNM network object .
Parameters
network : OpenPNM GenericNetwork
Network from which voxel image is to be generated
pore _ shape : str
... | print ( "\n" + "-" * 44 , flush = True )
print ( "| Generating voxel image from pore network |" , flush = True )
print ( "-" * 44 , flush = True )
# If max _ dim is provided , generate voxel image using max _ dim
if max_dim is not None :
return _generate_voxel_image ( network , pore_shape , throat_shape , max_dim =... |
def _rename_objects_pretty ( self ) :
"""Rename all objects like " name _ 1 " to avoid conflicts . Objects are
only renamed if necessary .
This method produces more readable GLSL , but is rather slow .""" | # 1 . For each object , add its static names to the global namespace
# and make a list of the shaders used by the object .
# { name : obj } mapping for finding unique names
# initialize with reserved keywords .
self . _global_ns = dict ( [ ( kwd , None ) for kwd in gloo . util . KEYWORDS ] )
# functions are local per -... |
def certify_enum ( value , kind = None , required = True ) :
"""Certifier for enum .
: param value :
The value to be certified .
: param kind :
The enum type that value should be an instance of .
: param bool required :
Whether the value can be ` None ` . Defaults to True .
: raises CertifierTypeError... | if certify_required ( value = value , required = required , ) :
return
if not isinstance ( value , kind ) :
raise CertifierTypeError ( message = "expected {expected!r}, but value is of type {actual!r}" . format ( expected = kind . __name__ , actual = value . __class__ . __name__ ) , value = value , required = r... |
def check_namespace ( namespace_id ) :
"""Verify that a namespace ID is well - formed
> > > check _ namespace ( 123)
False
> > > check _ namespace ( None )
False
> > > check _ namespace ( ' ' )
False
> > > check _ namespace ( ' abcd ' )
True
> > > check _ namespace ( ' Abcd ' )
False
> > > che... | if type ( namespace_id ) not in [ str , unicode ] :
return False
if not is_namespace_valid ( namespace_id ) :
return False
return True |
def getWinnersBruteForce ( self , profile ) :
"""Returns a list of all winning candidates when we use brute force to compute Bayesian
utilities for an election profile . This function assumes that
getCandScoresMapBruteForce ( profile ) is implemented for the child MechanismMcmc class .
: ivar Profile profile ... | candScoresMapBruteForce = self . getCandScoresMapBruteForce ( profile )
# Check whether the winning candidate is the candidate that maximizes the score or
# minimizes it .
if self . maximizeCandScore == True :
bestScore = max ( candScoresMapBruteForce . values ( ) )
else :
bestScore = min ( candScoresMapBruteFo... |
def closestsites ( struct_blk , struct_def , pos ) :
"""Returns closest site to the input position
for both bulk and defect structures
Args :
struct _ blk : Bulk structure
struct _ def : Defect structure
pos : Position
Return : ( site object , dist , index )""" | blk_close_sites = struct_blk . get_sites_in_sphere ( pos , 5 , include_index = True )
blk_close_sites . sort ( key = lambda x : x [ 1 ] )
def_close_sites = struct_def . get_sites_in_sphere ( pos , 5 , include_index = True )
def_close_sites . sort ( key = lambda x : x [ 1 ] )
return blk_close_sites [ 0 ] , def_close_sit... |
def get_layout_active_label ( self , resources , name , title , identity , shortcut ) :
"""Returns a layout * * Active _ QLabel * * widget .
: param resources : Icons resources ( Default / Hover / Active ) .
: type resources : tuple
: param name : Ui object name .
: type name : unicode
: param title : Lay... | default_icon , hover_icon , active_icon = resources
layout_active_label = Active_QLabel ( self , QPixmap ( umbra . ui . common . get_resource_path ( default_icon ) ) , QPixmap ( umbra . ui . common . get_resource_path ( hover_icon ) ) , QPixmap ( umbra . ui . common . get_resource_path ( active_icon ) ) , True )
self .... |
def create_response ( self , payload ) :
"""Create a signed bitjws response using the supplied payload .
The response content - type will be ' application / jose ' .
: param payload : The response content . Must be json - serializable .
: return : The signed Response with headers .
: rtype : flask . Respons... | signedmess = bitjws . sign_serialize ( self . _privkey , requrl = '/response' , iat = time . time ( ) , data = payload )
return Response ( signedmess , mimetype = 'application/jose' ) |
def macro_attachments ( self , macro_id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / macros # list - macro - attachments" | api_path = "/api/v2/macros/{macro_id}/attachments.json"
api_path = api_path . format ( macro_id = macro_id )
return self . call ( api_path , ** kwargs ) |
def ApplyPluginToTypedCollection ( plugin , type_names , fetch_fn ) :
"""Applies instant output plugin to a collection of results .
Args :
plugin : InstantOutputPlugin instance .
type _ names : List of type names ( strings ) to be processed .
fetch _ fn : Function that takes a type name as an argument and r... | for chunk in plugin . Start ( ) :
yield chunk
def GetValues ( tn ) :
for v in fetch_fn ( tn ) :
yield v
for type_name in sorted ( type_names ) :
stored_cls = rdfvalue . RDFValue . classes [ type_name ]
for chunk in plugin . ProcessValues ( stored_cls , functools . partial ( GetValues , type_name... |
def cpuset ( self , name , cpus = None , mems = None ) :
"""Set / Get cpuset cgroup specification / limitation
the call to this method will always GET the current set values for both cpus and mems
If cpus , or mems is NOT NONE value it will be set as the spec for that attribute
: param cpus : Set cpus affinit... | args = { 'name' : name , 'cpus' : cpus , 'mems' : mems , }
self . _cpuset_spec . check ( args )
return self . _client . json ( 'cgroup.cpuset.spec' , args ) |
def symmetrize_force_constants ( force_constants , level = 1 ) :
"""Symmetry force constants by translational and permutation symmetries
Note
Schemes of symmetrization are slightly different between C and
python implementations . If these give very different results , the
original force constants are not re... | try :
import phonopy . _phonopy as phonoc
phonoc . perm_trans_symmetrize_fc ( force_constants , level )
except ImportError :
for i in range ( level ) :
set_translational_invariance ( force_constants )
set_permutation_symmetry ( force_constants )
set_translational_invariance ( force_const... |
def get_error ( self , startingPercentage = 0.0 , endPercentage = 100.0 , startDate = None , endDate = None ) :
"""Calculates the error for the given interval ( startingPercentage , endPercentage ) between the TimeSeries
given during : py : meth : ` BaseErrorMeasure . initialize ` .
: param float startingPercen... | # not initialized :
if len ( self . _errorValues ) == 0 :
raise StandardError ( "The last call of initialize(...) was not successfull." )
# check for wrong parameters
if not ( 0.0 <= startingPercentage <= 100.0 ) :
raise ValueError ( "startingPercentage has to be in [0.0, 100.0]." )
if not ( 0.0 <= endPercentag... |
def account_weight ( self , account ) :
"""Returns the voting weight for * * account * *
: param account : Account to get voting weight for
: type account : str
: raises : : py : exc : ` nano . rpc . RPCException `
> > > rpc . account _ weight (
. . . account = " xrb _ 3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5... | account = self . _process_value ( account , 'account' )
payload = { "account" : account }
resp = self . call ( 'account_weight' , payload )
return int ( resp [ 'weight' ] ) |
def _find_error_evaluator ( self , synd , sigma , k = None ) :
'''Compute the error ( or erasures if you supply sigma = erasures locator polynomial ) evaluator polynomial Omega from the syndrome and the error / erasures / errata locator Sigma . Omega is already computed at the same time as Sigma inside the Berlekam... | n = self . n
if not k :
k = self . k
# Omega ( x ) = [ ( 1 + Synd ( x ) ) * Error _ loc ( x ) ] mod x ^ ( n - k + 1)
# NOTE : I don ' t know why we do 1 + Synd ( x ) here , from docs it seems just Synd ( x ) is enough ( and in practice if you remove the " ONE + " it will still decode correcty ) as advised by Blahut... |
def cyntenator ( args ) :
"""% prog cyntenator athaliana . athaliana . last athaliana . bed
Prepare input for Cyntenator .""" | p = OptionParser ( cyntenator . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) < 2 :
sys . exit ( not p . print_help ( ) )
lastfile = args [ 0 ]
fp = open ( lastfile )
filteredlastfile = lastfile + ".blast"
fw = open ( filteredlastfile , "w" )
for row in fp :
b = BlastLine ( row )
if b . qu... |
def read_choice ( self ) :
"""Return choice""" | commands = { "r" : "README" , "R" : "README" , "s" : "{0}.SlackBuild" . format ( self . name ) , "S" : "{0}.SlackBuild" . format ( self . name ) , "f" : "{0}.info" . format ( self . name ) , "F" : "{0}.info" . format ( self . name ) , "o" : "doinst.sh" , "O" : "doinst.sh" , "d" : "download" , "D" : "download" , "downlo... |
def get_or_create_author ( self , api_author ) :
"""Find or create an Author object given API data .
: param api _ author : the API data for the Author
: return : a tuple of an Author instance and a boolean indicating whether the author was created or not""" | return Author . objects . get_or_create ( site_id = self . site_id , wp_id = api_author [ "ID" ] , defaults = self . api_object_data ( "author" , api_author ) ) |
def populate ( self ) :
"""Sync changes from the API to the local object .
Note : syncs ip _ addresses and storage _ devices too ( / server / uuid endpoint )""" | server , IPAddresses , storages = self . cloud_manager . get_server_data ( self . uuid )
self . _reset ( server , ip_addresses = IPAddresses , storage_devices = storages , populated = True )
return self |
def _forward_iterator ( self ) :
"Returns a forward iterator over the trie" | path = [ ( self , 0 , Bits ( ) ) ]
while path :
node , idx , prefix = path . pop ( )
if idx == 0 and node . value is not None and not node . prune_value :
yield ( self . _unpickle_key ( prefix ) , self . _unpickle_value ( node . value ) )
if idx < len ( node . children ) :
path . append ( ( ... |
def _sync_writes ( self ) :
'''Flushes the write queue''' | for key in self . _wqueue :
val = self . _cache [ key ]
self . _database [ key ] = val
del self . _wqueue
self . _wqueue = set ( )
self . _database . sync ( ) |
def positive_int ( integer_string : str , strict : bool = False , cutoff : Optional [ int ] = None ) -> int :
"""Cast a string to a strictly positive integer .""" | ret = int ( integer_string )
if ret < 0 or ( ret == 0 and strict ) :
raise ValueError ( )
if cutoff :
ret = min ( ret , cutoff )
return ret |
def create_volume ( DryRun = None , Size = None , SnapshotId = None , AvailabilityZone = None , VolumeType = None , Iops = None , Encrypted = None , KmsKeyId = None , TagSpecifications = None ) :
"""Creates an EBS volume that can be attached to an instance in the same Availability Zone . The volume is created in th... | pass |
def merge ( self , values , lists_only = False ) :
"""Merges list - based attributes into one list including unique elements from both lists . When ` ` lists _ only ` ` is
set to ` ` False ` ` , updates dictionaries and overwrites single - value attributes . The resulting configuration
is ' clean ' , i . e . in... | if isinstance ( values , self . __class__ ) :
self . merge_from_obj ( values , lists_only = lists_only )
elif isinstance ( values , dict ) :
self . merge_from_dict ( values , lists_only = lists_only )
else :
raise ValueError ( "{0} or dictionary expected; found '{1}'." . format ( self . __class__ . __name__... |
def infer_x ( self , y ) :
"""Infer probable x from input y
@ param y the desired output for infered x .
@ return a list of probable x""" | OptimizedInverseModel . infer_x ( self , y )
if self . fmodel . size ( ) == 0 :
return self . _random_x ( )
x_guesses = [ self . _guess_x_simple ( y ) [ 0 ] ]
result = [ ]
for xg in x_guesses :
res = cma . fmin ( self . _error , xg , self . cmaes_sigma , options = { 'bounds' : [ self . lower , self . upper ] , ... |
def most_populated ( adf ) :
"""Looks at each column , using the one with the most values
Honours the Trump override / failsafe logic .""" | # just look at the feeds , ignore overrides and failsafes :
feeds_only = adf [ adf . columns [ 1 : - 1 ] ]
# find the most populated feed
cnt_df = feeds_only . count ( )
cnt = cnt_df . max ( )
selected_feeds = cnt_df [ cnt_df == cnt ]
# if there aren ' t any feeds , the first feed will work . . .
if len ( selected_feed... |
def anonymous_login ( self ) :
"""Login as anonymous user
: return : logon result , see ` CMsgClientLogonResponse . eresult < https : / / github . com / ValvePython / steam / blob / 513c68ca081dc9409df932ad86c66100164380a6 / protobufs / steammessages _ clientserver . proto # L95 - L118 > ` _
: rtype : : class :... | self . _LOG . debug ( "Attempting Anonymous login" )
self . _pre_login ( )
self . username = None
self . login_key = None
message = MsgProto ( EMsg . ClientLogon )
message . header . steamid = SteamID ( type = 'AnonUser' , universe = 'Public' )
message . body . protocol_version = 65579
self . send ( message )
resp = se... |
def _exponent_handler_factory ( ion_type , exp_chars , parse_func , first_char = None ) :
"""Generates a handler co - routine which tokenizes an numeric exponent .
Args :
ion _ type ( IonType ) : The type of the value with this exponent .
exp _ chars ( sequence ) : The set of ordinals of the legal exponent ch... | def transition ( prev , c , ctx , trans ) :
if c in _SIGN and prev in exp_chars :
ctx . value . append ( c )
else :
_illegal_character ( c , ctx )
return trans
illegal = exp_chars + _SIGN
return _numeric_handler_factory ( _DIGITS , transition , lambda c , ctx : c in exp_chars , illegal , par... |
def _first_word_not_cmd ( self , first_word : str , command : str , args : tuple , kwargs : dict ) -> None :
"""check to see if this is an author or service .
This method does high level control handling""" | if self . service_interface . is_service ( first_word ) :
self . _logger . debug ( ' first word is a service' )
kwargs = self . service_interface . get_metadata ( first_word , kwargs )
self . _logger . debug ( ' service transform kwargs: %s' , kwargs )
elif self . author_interface . is_author ( first_word )... |
def _setMaxRecords ( self , maxRec ) :
"""Specifies the maximum number of records you want returned ( number or constant ' all ' )""" | if type ( maxRec ) == int :
self . _maxRecords = maxRec
elif type ( maxRec ) == str and ( maxRec . lower == 'all' or maxRec . isdigit ( ) ) :
self . _maxRecords = maxRec . lower
else :
raise FMError , 'Unsupported -max value (not a number or "all").' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.