signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def dictionaries_walker ( dictionary , path = ( ) ) :
"""Defines a generator used to walk into nested dictionaries .
Usage : :
> > > nested _ dictionary = { " Level 1A " : { " Level 2A " : { " Level 3A " : " Higher Level " } } , " Level 1B " : " Lower level " }
> > > dictionaries _ walker ( nested _ dictionar... | for key in dictionary :
if not isinstance ( dictionary [ key ] , dict ) :
yield path , key , dictionary [ key ]
else :
for value in dictionaries_walker ( dictionary [ key ] , path + ( key , ) ) :
yield value |
def samples_multidimensional_uniform ( bounds , num_data ) :
'''Generates a multidimensional grid uniformly distributed .
: param bounds : tuple defining the box constraints .
: num _ data : number of data points to generate .''' | dim = len ( bounds )
Z_rand = np . zeros ( shape = ( num_data , dim ) )
for k in range ( 0 , dim ) :
Z_rand [ : , k ] = np . random . uniform ( low = bounds [ k ] [ 0 ] , high = bounds [ k ] [ 1 ] , size = num_data )
return Z_rand |
def get_interface ( dev , bInterfaceNumber ) :
r"""Get the current alternate setting of the interface .
dev is the Device object to which the request will be
sent to .""" | bmRequestType = util . build_request_type ( util . CTRL_IN , util . CTRL_TYPE_STANDARD , util . CTRL_RECIPIENT_INTERFACE )
return dev . ctrl_transfer ( bmRequestType = bmRequestType , bRequest = 0x0a , wIndex = bInterfaceNumber , data_or_wLength = 1 ) [ 0 ] |
def _ipopo_setup_field_callback ( cls , context ) : # type : ( type , FactoryContext ) - > None
"""Sets up the class _ field _ callback dictionary
: param cls : The class to handle
: param context : The factory class context""" | assert inspect . isclass ( cls )
assert isinstance ( context , FactoryContext )
if context . field_callbacks is not None :
callbacks = context . field_callbacks . copy ( )
else :
callbacks = { }
functions = inspect . getmembers ( cls , inspect . isroutine )
for name , func in functions :
if not hasattr ( fu... |
def handle_valid ( self , form = None , * args , ** kwargs ) :
"""Called after the form has validated .""" | # Take a chance and try save a subclass of a ModelForm .
if hasattr ( form , 'save' ) :
form . save ( )
# Also try and call handle _ valid method of the form itself .
if hasattr ( form , 'handle_valid' ) :
form . handle_valid ( * args , ** kwargs ) |
def bind_field ( self , form : DynamicForm , unbound_field : UnboundField , options : Dict [ Any , Any ] , ) -> Field :
"""Customize how fields are bound by stripping all whitespace .
: param form : The form
: param unbound _ field : The unbound field
: param options : The field options
: returns : The boun... | filters = unbound_field . kwargs . get ( 'filters' , [ ] )
filters . append ( lambda x : x . strip ( ) if isinstance ( x , str ) else x )
return unbound_field . bind ( form = form , filters = filters , ** options ) |
def run ( self ) :
"""Statistics logger job callback .""" | try :
proxy = config_ini . engine . open ( )
self . LOG . info ( "Stats for %s - up %s, %s" % ( config_ini . engine . engine_id , fmt . human_duration ( proxy . system . time ( ) - config_ini . engine . startup , 0 , 2 , True ) . strip ( ) , proxy ) )
except ( error . LoggableError , xmlrpc . ERRORS ) , exc :
... |
def from_ast_file ( cls , filename , index = None ) :
"""Create a TranslationUnit instance from a saved AST file .
A previously - saved AST file ( provided with - emit - ast or
TranslationUnit . save ( ) ) is loaded from the filename specified .
If the file cannot be loaded , a TranslationUnitLoadError will b... | if index is None :
index = Index . create ( )
ptr = conf . lib . clang_createTranslationUnit ( index , filename )
if not ptr :
raise TranslationUnitLoadError ( filename )
return cls ( ptr = ptr , index = index ) |
def _get_cached_response ( self ) :
"""Returns a file object of the cached response .""" | if not self . _is_cached ( ) :
response = self . _download_response ( )
self . cache . set_xml ( self . _get_cache_key ( ) , response )
return self . cache . get_xml ( self . _get_cache_key ( ) ) |
def flatten ( xs : Union [ List , Tuple ] ) -> List :
"""Flatten a nested list or tuple .""" | return ( sum ( map ( flatten , xs ) , [ ] ) if ( isinstance ( xs , list ) or isinstance ( xs , tuple ) ) else [ xs ] ) |
def getNetworkSummary ( self , suid , verbose = None ) :
"""Returns summary of collection containing the specified network .
: param suid : Cytoscape Collection / Subnetwork SUID
: param verbose : print more
: returns : 200 : successful operation""" | surl = self . ___url
sv = surl . split ( '/' ) [ - 1 ]
surl = surl . rstrip ( sv + '/' )
response = api ( url = surl + '/cyndex2/' + sv + '/networks/' + str ( suid ) + '' , method = "GET" , verbose = verbose , parse_params = False )
return response |
def Sample ( self , n ) :
"""Generates a random sample from this distribution .
n : int sample size""" | size = n ,
return numpy . random . beta ( self . alpha , self . beta , size ) |
def sample ( self , n_samples ) :
"""Generate specified ` n _ samples ` of new data from model . ` v ~ U [ 0,1 ] , v ~ C ^ - 1 ( u | v ) `
Args :
n _ samples : ` int ` , amount of samples to create .
Returns :
np . ndarray : Array of length ` n _ samples ` with generated data from the model .""" | if self . tau > 1 or self . tau < - 1 :
raise ValueError ( "The range for correlation measure is [-1,1]." )
v = np . random . uniform ( 0 , 1 , n_samples )
c = np . random . uniform ( 0 , 1 , n_samples )
u = self . percent_point ( c , v )
return np . column_stack ( ( u , v ) ) |
def _parse_thead_tbody_tfoot ( self , table_html ) :
"""Given a table , return parsed header , body , and foot .
Parameters
table _ html : node - like
Returns
tuple of ( header , body , footer ) , each a list of list - of - text rows .
Notes
Header and body are lists - of - lists . Top level list is a l... | header_rows = self . _parse_thead_tr ( table_html )
body_rows = self . _parse_tbody_tr ( table_html )
footer_rows = self . _parse_tfoot_tr ( table_html )
def row_is_all_th ( row ) :
return all ( self . _equals_tag ( t , 'th' ) for t in self . _parse_td ( row ) )
if not header_rows : # The table has no < thead > . M... |
def _set_user_password ( self , v , load = False ) :
"""Setter method for user _ password , mapped from YANG variable / username / user _ password ( user - passwd )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ user _ password is considered as a private
method . Bac... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'1..40' ] } ) , is_leaf = True , yang_name = "user-password" , rest_name = "password" , parent = self , path_helper = self . _path_helper , extmet... |
def get_tape ( self ) :
"""Get content of tape .""" | result = ''
for i in range ( min ( self . tape ) , max ( self . tape ) + 1 ) :
symbol = self . tape [ i ] if self . tape [ i ] != self . EMPTY_SYMBOL else ' '
result += symbol
# Remove unnecessary empty symbols on tape
return result . strip ( ) |
def perlin ( self , key , ** kwargs ) :
"""Return perlin noise seede with the specified key .
For parameters , check the PerlinNoise class .""" | if hasattr ( key , "encode" ) :
key = key . encode ( 'ascii' )
value = zlib . adler32 ( key , self . seed )
return PerlinNoise ( value , ** kwargs ) |
def blk_1d ( blk , shape ) :
"""Iterate through the slices that recover a line .
This function is used by : func : ` blk _ nd ` as a base 1d case .
The last slice is returned even if is lesser than blk .
: param blk : the size of the block
: param shape : the size of the array
: return : a generator that ... | maxpix , rem = blk_coverage_1d ( blk , shape )
for i in range ( 0 , maxpix , blk ) :
yield slice ( i , i + blk )
if rem != 0 :
yield slice ( maxpix , shape ) |
def flag ( self , key , env = None ) :
"""Feature flagging system
write flags to redis
$ dynaconf write redis - s DASHBOARD = 1 - e premiumuser
meaning : Any premium user has DASHBOARD feature enabled
In your program do : :
# premium user has access to dashboard ?
> > > if settings . flag ( ' dashboard ... | env = env or self . ENVVAR_PREFIX_FOR_DYNACONF or "DYNACONF"
with self . using_env ( env ) :
value = self . get_fresh ( key )
return value is True or value in true_values |
def face_angles_sparse ( mesh ) :
"""A sparse matrix representation of the face angles .
Returns
sparse : scipy . sparse . coo _ matrix with :
dtype : float
shape : ( len ( mesh . vertices ) , len ( mesh . faces ) )""" | matrix = coo_matrix ( ( mesh . face_angles . flatten ( ) , ( mesh . faces_sparse . row , mesh . faces_sparse . col ) ) , mesh . faces_sparse . shape )
return matrix |
def modifyPdpContextRequest ( ) :
"""MODIFY PDP CONTEXT REQUEST Section 9.5.6""" | a = TpPd ( pd = 0x8 )
b = MessageType ( mesType = 0x48 )
# 01001000
c = RadioPriorityAndSpareHalfOctets ( )
d = LlcServiceAccessPointIdentifier ( )
e = QualityOfService ( )
packet = a / b / c / d / e
return packet |
def parse_text ( infile , xpath = None , filter_words = None , attributes = None ) :
"""Filter text using XPath , regex keywords , and tag attributes .
Keyword arguments :
infile - - HTML or text content to parse ( list )
xpath - - an XPath expression ( str )
filter _ words - - regex keywords ( list )
att... | infiles = [ ]
text = [ ]
if xpath is not None :
infile = parse_html ( infile , xpath )
if isinstance ( infile , list ) :
if isinstance ( infile [ 0 ] , lh . HtmlElement ) :
infiles = list ( infile )
else :
text = [ line + '\n' for line in infile ]
elif isinstance ( in... |
def update ( self , jump ) :
"""Update the lattice state by accepting a specific jump
Args :
jump ( Jump ) : The jump that has been accepted .
Returns :
None .""" | atom = jump . initial_site . atom
dr = jump . dr ( self . cell_lengths )
# print ( " atom { } jumped from site { } to site { } " . format ( atom . number , jump . initial _ site . number , jump . final _ site . number ) )
jump . final_site . occupation = atom . number
jump . final_site . atom = atom
jump . final_site .... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : RatePlanContext for this RatePlanInstance
: rtype : twilio . rest . preview . wireless . rate _ plan . RatePlanContext""" | if self . _context is None :
self . _context = RatePlanContext ( self . _version , sid = self . _solution [ 'sid' ] , )
return self . _context |
def from_dict ( cls , d ) :
"""Create an instance from a dictionary .""" | instance = super ( Simulation , cls ) . from_dict ( d )
# The instance ' s input _ files and cmd _ line _ args members still point to data structures in the original
# dictionary . Copy them to avoid surprises if they are changed in the original dictionary .
instance . input_files = dict ( instance . input_files )
inst... |
def remove_term ( self , t ) :
"""Only removes top - level terms . Child terms can be removed at the parent .""" | try :
self . terms . remove ( t )
except ValueError :
pass
if t . section and t . parent_term_lc == 'root' :
t . section = self . add_section ( t . section )
t . section . remove_term ( t , remove_from_doc = False )
if t . parent :
try :
t . parent . remove_child ( t )
except ValueError ... |
def get_post_reference_section_keyword_patterns ( ) :
"""Return a list of compiled regex patterns used to search for various
keywords that can often be found after , and therefore suggest the end of ,
a reference section in a full - text document .
@ return : ( list ) of compiled regex patterns .""" | compiled_patterns = [ ]
patterns = [ u'(' + _create_regex_pattern_add_optional_spaces_to_word_characters ( u'prepared' ) + ur'|' + _create_regex_pattern_add_optional_spaces_to_word_characters ( u'created' ) + ur').*(AAS\s*)?\sLATEX' , ur'AAS\s+?LATEX\s+?' + _create_regex_pattern_add_optional_spaces_to_word_characters (... |
def xarray_derivative_wrap ( func ) :
"""Decorate the derivative functions to make them work nicely with DataArrays .
This will automatically determine if the coordinates can be pulled directly from the
DataArray , or if a call to lat _ lon _ grid _ deltas is needed .""" | @ functools . wraps ( func )
def wrapper ( f , ** kwargs ) :
if 'x' in kwargs or 'delta' in kwargs : # Use the usual DataArray to pint . Quantity preprocessing wrapper
return preprocess_xarray ( func ) ( f , ** kwargs )
elif isinstance ( f , xr . DataArray ) : # Get axis argument , defaulting to first d... |
def validate ( self , signature ) :
'''Check if ofiles and ifiles match signatures recorded in md5file''' | if not signature :
return 'Empty signature'
sig_files = self . input_files . _targets + self . output_files . _targets + self . dependent_files . _targets
for x in sig_files :
if not x . target_exists ( 'any' ) :
return f'Missing target {x}'
files_checked = { x . target_name ( ) : False for x in sig_fil... |
def process_additional_minidisks ( self , userid , disk_info ) :
'''Generate and punch the scripts used to process additional disk into
target vm ' s reader .''' | for idx , disk in enumerate ( disk_info ) :
vdev = disk . get ( 'vdev' ) or self . generate_disk_vdev ( offset = ( idx + 1 ) )
fmt = disk . get ( 'format' )
mount_dir = disk . get ( 'mntdir' ) or '' . join ( [ '/mnt/ephemeral' , str ( vdev ) ] )
disk_parms = self . _generate_disk_parmline ( vdev , fmt ,... |
def sample_labels ( self , n ) :
"""Returns a set of n labels sampled from the labels of the tree
: param n : Number of labels to sample
: return : set of randomly sampled labels""" | if n >= len ( self ) :
return self . labels
sample = random . sample ( self . labels , n )
return set ( sample ) |
def coarseMaximum ( arr , shape ) :
'''return an array of [ shape ]
where every cell equals the localised maximum of the given array [ arr ]
at the same ( scalled ) position''' | ss0 , ss1 = shape
s0 , s1 = arr . shape
pos0 = linspace2 ( 0 , s0 , ss0 , dtype = int )
pos1 = linspace2 ( 0 , s1 , ss1 , dtype = int )
k0 = pos0 [ 0 ]
k1 = pos1 [ 0 ]
out = np . empty ( shape , dtype = arr . dtype )
_calc ( arr , out , pos0 , pos1 , k0 , k1 , ss0 , ss1 )
return out |
def _mine ( self , load , skip_verify = False ) :
'''Return the mine data''' | if not skip_verify :
if 'id' not in load or 'data' not in load :
return False
if self . opts . get ( 'minion_data_cache' , False ) or self . opts . get ( 'enforce_mine_cache' , False ) :
cbank = 'minions/{0}' . format ( load [ 'id' ] )
ckey = 'mine'
if not load . get ( 'clear' , False ) :
... |
def chrome_tracing_object_transfer_dump ( self , filename = None ) :
"""Return a list of transfer events that can viewed as a timeline .
To view this information as a timeline , simply dump it as a json file
by passing in " filename " or using using json . dump , and then load go to
chrome : / / tracing in th... | client_id_to_address = { }
for client_info in ray . global_state . client_table ( ) :
client_id_to_address [ client_info [ "ClientID" ] ] = "{}:{}" . format ( client_info [ "NodeManagerAddress" ] , client_info [ "ObjectManagerPort" ] )
all_events = [ ]
for key , items in self . profile_table ( ) . items ( ) : # Onl... |
def add_colorbar ( self , * args , ** kwargs ) :
"""DEPRECATED , use ` Plot . colorbar ` instead""" | warnings . warn ( "{0}.add_colorbar was renamed {0}.colorbar, this warnings will " "result in an error in the future" . format ( type ( self ) . __name__ ) , DeprecationWarning )
return self . colorbar ( * args , ** kwargs ) |
def napi_and ( values , ** kwargs ) :
"""Perform element - wise logical * and * operation on arrays .
If * values * contains a non - array object with truth _ value * * False * * , the
outcome will be an array of * * False * * \ s with suitable shape without arrays
being evaluated . Non - array objects with t... | arrays = [ ]
result = None
shapes = set ( )
for value in values :
if isinstance ( value , ndarray ) and value . shape :
arrays . append ( value )
shapes . add ( value . shape )
elif not value :
result = value
if len ( shapes ) > 1 and kwargs . get ( 'sq' , kwargs . get ( 'squeeze' , Fals... |
def to_UNIXtime ( timeobject ) :
"""Returns the UNIXtime corresponding to the time value conveyed by the
specified object , which can be either a UNIXtime , a
` ` datetime . datetime ` ` object or an ISO8601 - formatted string in the format
` YYYY - MM - DD HH : MM : SS + 00 ` ` .
: param timeobject : the o... | if isinstance ( timeobject , int ) :
if timeobject < 0 :
raise ValueError ( "The time value is a negative number" )
return timeobject
elif isinstance ( timeobject , datetime ) :
return _datetime_to_UNIXtime ( timeobject )
elif isinstance ( timeobject , str ) :
return _ISO8601_to_UNIXtime ( timeo... |
def delNode ( self , address ) :
"""Delete a node from the NodeServer
: param node : Dictionary of node settings . Keys : address , name , node _ def _ id , primary , and drivers are required .""" | LOGGER . info ( 'Removing node {}' . format ( address ) )
message = { 'removenode' : { 'address' : address } }
self . send ( message ) |
def add ( self , tagname , tagvalue ) :
""": returns : numeric index associated to the tag""" | dic = getattr ( self , tagname + '_idx' )
try :
return dic [ tagvalue ]
except KeyError :
dic [ tagvalue ] = idx = len ( dic )
getattr ( self , tagname ) . append ( tagvalue )
if idx > TWO16 :
raise InvalidFile ( 'contains more then %d tags' % TWO16 )
return idx |
def L1 ( layer = "input" , constant = 0 , batch = None ) :
"""L1 norm of layer . Generally used as penalty .""" | if batch is None :
return lambda T : tf . reduce_sum ( tf . abs ( T ( layer ) - constant ) )
else :
return lambda T : tf . reduce_sum ( tf . abs ( T ( layer ) [ batch ] - constant ) ) |
def InitNornir ( config_file : str = "" , dry_run : bool = False , configure_logging : Optional [ bool ] = None , ** kwargs : Dict [ str , Any ] , ) -> Nornir :
"""Arguments :
config _ file ( str ) : Path to the configuration file ( optional )
dry _ run ( bool ) : Whether to simulate changes or not
configure ... | register_default_connection_plugins ( )
if callable ( kwargs . get ( "inventory" , { } ) . get ( "plugin" , "" ) ) :
kwargs [ "inventory" ] [ "plugin" ] = cls_to_string ( kwargs [ "inventory" ] [ "plugin" ] )
if callable ( kwargs . get ( "inventory" , { } ) . get ( "transform_function" , "" ) ) :
kwargs [ "inve... |
def validate_collxml ( * content_filepaths ) :
"""Validates the given COLLXML file against the collxml - jing . rng RNG .""" | content_filepaths = [ Path ( path ) . resolve ( ) for path in content_filepaths ]
return jing ( COLLXML_JING_RNG , * content_filepaths ) |
def destroy ( cls , * ids ) :
"""Delete the records with the given ids
: type ids : list
: param ids : primary key ids of records""" | for pk in ids :
cls . find ( pk ) . delete ( )
cls . session . flush ( ) |
def nation ( self , nation_name , password = None , autologin = None ) :
"""Setup access to the Nation API with the Nation object
: param nation _ name : Name of the nation
: param password : ( Optional ) password for this nation
: param autologin ( Optional ) autologin for this nation
: type nation _ name ... | return Nation ( nation_name , self , password = password , autologin = autologin ) |
def getAutoServiceLevelEnabled ( self ) :
"""Returns True if enabled , False if disabled""" | command = '$GE'
settings = self . sendCommand ( command )
flags = int ( settings [ 2 ] , 16 )
return not ( flags & 0x0020 ) |
def parse ( ) :
"""Parse command line options""" | parser = argparse . ArgumentParser ( description = 'Dynamic DynamoDB - Auto provisioning AWS DynamoDB' )
parser . add_argument ( '-c' , '--config' , help = 'Read configuration from a configuration file' )
parser . add_argument ( '--dry-run' , action = 'store_true' , help = 'Run without making any changes to your Dynamo... |
def rename_dupe_cols ( cols ) :
"""Takes a list of strings and appends 2,3,4 etc to duplicates . Never
appends a 0 or 1 . Appended # s are not always in order . . . but if you wrap
this in a dataframe . to _ sql function you ' re guaranteed to not have dupe
column name errors importing data to SQL . . . you '... | counts = { }
positions = { pos : fld for pos , fld in enumerate ( cols ) }
for c in cols :
if c in counts . keys ( ) :
counts [ c ] += 1
else :
counts [ c ] = 1
fixed_cols = { }
for pos , col in positions . items ( ) :
if counts [ col ] > 1 :
fix_cols = { pos : fld for pos , fld in p... |
def remove_task ( cls , task ) :
""": param Task | callable task : Remove ' task ' from the list of tasks to run periodically""" | with cls . _lock :
if not isinstance ( task , Task ) :
task = cls . resolved_task ( task )
if task :
cls . tasks . remove ( task )
cls . tasks . sort ( ) |
def _set_ldp_fec_vcs ( self , v , load = False ) :
"""Setter method for ldp _ fec _ vcs , mapped from YANG variable / mpls _ state / ldp / fec / ldp _ fec _ vcs ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ldp _ fec _ vcs is considered as a private
me... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = ldp_fec_vcs . ldp_fec_vcs , is_container = 'container' , presence = False , yang_name = "ldp-fec-vcs" , rest_name = "ldp-fec-vcs" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , registe... |
def OnPasteAs ( self , event ) :
"""Clipboard paste as event handler""" | data = self . main_window . clipboard . get_clipboard ( )
key = self . main_window . grid . actions . cursor
with undo . group ( _ ( "Paste As..." ) ) :
self . main_window . actions . paste_as ( key , data )
self . main_window . grid . ForceRefresh ( )
event . Skip ( ) |
def cardinal_direction ( self ) :
"""Returns the cardinal direction of the
wind as a string . Possible returned values are N , E , S , W , and None .
315 degrees to 45 degrees exclusive - > N
45 degrees to 135 degrees exclusive - > E
135 degrees to 225 degrees exclusive - > S
225 degrees to 315 degrees ex... | if self . direction is None :
return None
if self . direction > 360 or self . direction < 0 :
raise Exception ( 'Direction out of range' )
if ( 315 <= self . direction ) <= 360 or 0 <= ( self . direction ) < 45 :
return 'N'
elif 45 <= self . direction < 135 :
return 'E'
elif 135 <= self . direction < 22... |
def _gorg ( cls ) :
"""This function exists for compatibility with old typing versions .""" | assert isinstance ( cls , GenericMeta )
if hasattr ( cls , '_gorg' ) :
return cls . _gorg
while cls . __origin__ is not None :
cls = cls . __origin__
return cls |
def summarize ( self , text , length = 5 , binary_matrix = True ) :
"""Implements the method of summarization by relevance score , as described by Gong and Liu in the paper :
Y . Gong and X . Liu ( 2001 ) . Generic text summarization using relevance measure and latent semantic analysis .
Proceedings of the 24th... | text = self . _parse_input ( text )
sentences , unprocessed_sentences = self . _tokenizer . tokenize_sentences ( text )
length = self . _parse_summary_length ( length , len ( sentences ) )
if length == len ( sentences ) :
return unprocessed_sentences
matrix = self . _compute_matrix ( sentences , weighting = 'freque... |
def graphql_query ( self , query_hash : str , variables : Dict [ str , Any ] , referer : Optional [ str ] = None , rhx_gis : Optional [ str ] = None ) -> Dict [ str , Any ] :
"""Do a GraphQL Query .
: param query _ hash : Query identifying hash .
: param variables : Variables for the Query .
: param referer :... | with copy_session ( self . _session ) as tmpsession :
tmpsession . headers . update ( self . _default_http_header ( empty_session_only = True ) )
del tmpsession . headers [ 'Connection' ]
del tmpsession . headers [ 'Content-Length' ]
tmpsession . headers [ 'authority' ] = 'www.instagram.com'
tmpsess... |
def get_version_requested ( path ) :
"""Return string listing requested Terraform version .""" | tf_version_path = os . path . join ( path , TF_VERSION_FILENAME )
if not os . path . isfile ( tf_version_path ) :
LOGGER . error ( "Terraform install attempted and no %s file present to " "dictate the version. Please create it (e.g. write " "\"0.11.13\" (without quotes) to the file and try again" , TF_VERSION_FILE... |
def reindex_sortable_title ( portal ) :
"""Reindex sortable _ title from some catalogs""" | catalogs = [ "bika_catalog" , "bika_setup_catalog" , "portal_catalog" , ]
for catalog_name in catalogs :
logger . info ( "Reindexing sortable_title for {} ..." . format ( catalog_name ) )
handler = ZLogHandler ( steps = 100 )
catalog = api . get_tool ( catalog_name )
catalog . reindexIndex ( "sortable_t... |
def delete_report ( server , report_number , timeout = HQ_DEFAULT_TIMEOUT ) :
"""Delete a specific crash report from the server .
: param report _ number : Report Number
: return : server response""" | try :
r = requests . post ( server + "/reports/delete/%d" % report_number , timeout = timeout )
except Exception as e :
logging . error ( e )
return False
return r |
def request ( self , method , url , params = None , headers = None ) :
"""Return a deferred .""" | if params is None :
params = self . _retrieve_params
return make_request ( self , method , url , stripe_account = self . stripe_account , params = params , headers = headers ) |
def read_raid ( self , raid_config = None ) :
"""Read the logical drives from the system
: param raid _ config : None or a dictionary containing target raid
configuration data . This data stucture should be as
follows :
raid _ config = { ' logical _ disks ' : [ { ' raid _ level ' : 1,
' size _ gb ' : 100 ... | self . check_smart_storage_config_ids ( )
if raid_config : # When read called after create raid , user can pass raid config
# as a input
result = self . _post_create_read_raid ( raid_config = raid_config )
else : # When read called after delete raid , there will be no input
# passed by user then
result = self .... |
def peek_stack_dwords ( self , count , offset = 0 ) :
"""Tries to read DWORDs from the top of the stack .
@ type count : int
@ param count : Number of DWORDs to read .
@ type offset : int
@ param offset : Offset from the stack pointer to begin reading .
@ rtype : tuple ( int . . . )
@ return : Tuple of ... | stackData = self . peek_stack_data ( count * 4 , offset )
if len ( stackData ) & 3 :
stackData = stackData [ : - len ( stackData ) & 3 ]
if not stackData :
return ( )
return struct . unpack ( '<' + ( 'L' * count ) , stackData ) |
def shell_out ( cmd , timeout = 30 , chroot = None , runat = None ) :
"""Shell out to an external command and return the output or the empty
string in case of error .""" | return sos_get_command_output ( cmd , timeout = timeout , chroot = chroot , chdir = runat ) [ 'output' ] |
def qbe_tree ( graph , nodes , root = None ) :
"""Given a graph , nodes to explore and an optinal root , do a breadth - first
search in order to return the tree .""" | if root :
start = root
else :
index = random . randint ( 0 , len ( nodes ) - 1 )
start = nodes [ index ]
# A queue to BFS instead DFS
to_visit = deque ( )
cnodes = copy ( nodes )
visited = set ( )
# Format is ( parent , parent _ edge , neighbor , neighbor _ field )
to_visit . append ( ( None , None , start ... |
def get_cert_contents ( kwargs ) :
"""Builds parameters with server cert file contents .
Args :
kwargs ( dict ) : The keyword args passed to ensure _ server _ cert _ exists ,
optionally containing the paths to the cert , key and chain files .
Returns :
dict : A dictionary containing the appropriate parame... | paths = { "certificate" : kwargs . get ( "path_to_certificate" ) , "private_key" : kwargs . get ( "path_to_private_key" ) , "chain" : kwargs . get ( "path_to_chain" ) , }
for key , value in paths . items ( ) :
if value is not None :
continue
path = input ( "Path to %s (skip): " % ( key , ) )
if path... |
def create ( self , name , passphrase = None , wallet_data = None ) :
"""Create a new Wallet object and add it to this Wallets collection .
This is only available in this library for Application wallets . Users
must add additional wallets in their User Console
Args :
name ( str ) : wallet name
passphrase ... | if not self . application :
raise RoundError ( "User accounts are limited to one wallet. Make an " "account or shoot us an email <dev@gem.co> if you " "have a compelling use case for more." )
if not passphrase and not wallet_data :
raise ValueError ( "Usage: wallets.create(name, passphrase [, " "wallet_data])" ... |
def oauth_flow ( s , oauth_url , username = None , password = None , sandbox = False ) :
"""s should be a requests session""" | r = s . get ( oauth_url )
if r . status_code >= 300 :
raise RuntimeError ( r . text )
params = urlparse . parse_qs ( urlparse . urlparse ( r . url ) . query )
data = { "un" : username , "width" : 2560 , "height" : 1440 , "hasRememberUn" : True , "startURL" : params [ 'startURL' ] , "loginURL" : "" , "loginType" : 6... |
def before_render ( self ) :
"""Before template render hook""" | # Render the Add button if the user has the AddClient permission
if check_permission ( AddClient , self . context ) :
self . context_actions [ _ ( "Add" ) ] = { "url" : "createObject?type_name=Client" , "icon" : "++resource++bika.lims.images/add.png" }
# Display a checkbox next to each client in the list if the use... |
def run_nested_error_groups ( ) :
"""Run nested groups example where an error occurs in nested main phase .
In this example , the first main phase in the nested PhaseGroup errors out .
The other inner main phase is skipped , as is the outer main phase . Both
PhaseGroups were entered , so both teardown phases ... | test = htf . Test ( htf . PhaseGroup ( main = [ htf . PhaseGroup . with_teardown ( inner_teardown_phase ) ( error_main_phase , main_phase ) , main_phase , ] , teardown = [ teardown_phase ] , ) )
test . execute ( ) |
def transform ( func , data ) :
"""Apply < func > on each element in < data > and return the list
consisting of the return values from < func > .
> > > data = [ [ 10,20 ] , [ 30,40 ] , [ 50,60 ] ]
. . . chart _ data . transform ( lambda x : [ x [ 0 ] , x [ 1 ] + 1 ] , data )
[ [ 10 , 21 ] , [ 30 , 41 ] , [ ... | out = [ ]
for r in data :
out . append ( func ( r ) )
return out |
def adjust_ages ( AgesIn ) :
"""Function to adjust ages to a common age _ unit""" | # get a list of age _ units first
age_units , AgesOut , factors , factor , maxunit , age_unit = [ ] , [ ] , [ ] , 1 , 1 , "Ma"
for agerec in AgesIn :
if agerec [ 1 ] not in age_units :
age_units . append ( agerec [ 1 ] )
if agerec [ 1 ] == "Ga" :
factors . append ( 1e9 )
maxu... |
def round ( col , scale = 0 ) :
"""Round the given value to ` scale ` decimal places using HALF _ UP rounding mode if ` scale ` > = 0
or at integral part when ` scale ` < 0.
> > > spark . createDataFrame ( [ ( 2.5 , ) ] , [ ' a ' ] ) . select ( round ( ' a ' , 0 ) . alias ( ' r ' ) ) . collect ( )
[ Row ( r =... | sc = SparkContext . _active_spark_context
return Column ( sc . _jvm . functions . round ( _to_java_column ( col ) , scale ) ) |
def compute ( datetimes , to_np = None ) : # @ NoSelf
"""Computes the provided date / time components into CDF epoch value ( s ) .
For CDF _ EPOCH :
For computing into CDF _ EPOCH value , each date / time elements should
have exactly seven ( 7 ) components , as year , month , day , hour , minute ,
second an... | if not isinstance ( datetimes , ( list , tuple , np . ndarray ) ) :
raise TypeError ( 'datetime must be in list form' )
if isinstance ( datetimes [ 0 ] , numbers . Number ) :
items = len ( datetimes )
elif isinstance ( datetimes [ 0 ] , ( list , tuple , np . ndarray ) ) :
items = len ( datetimes [ 0 ] )
els... |
def find_stream ( self , ** kwargs ) :
"""Finds a single stream with the given meta data values . Useful for debugging purposes .
: param kwargs : The meta data as keyword arguments
: return : The stream found""" | found = list ( self . find_streams ( ** kwargs ) . values ( ) )
if not found :
raise StreamNotFoundError ( kwargs )
if len ( found ) > 1 :
raise MultipleStreamsFoundError ( kwargs )
return found [ 0 ] |
def splitDataset ( dataset , groupby ) :
"""Split the given dataset into multiple datasets grouped by the given groupby
function . For example : :
# Split mnist dataset into 10 datasets , one dataset for each label
splitDataset ( mnist , groupby = lambda x : x [ 1 ] )
# Split mnist dataset into 5 datasets ,... | # Split dataset based on the group by function and keep track of indices
indicesByGroup = collections . defaultdict ( list )
for k , g in itertools . groupby ( enumerate ( dataset ) , key = lambda x : groupby ( x [ 1 ] ) ) :
indicesByGroup [ k ] . extend ( [ i [ 0 ] for i in g ] )
# Sort by group and create a Subse... |
def filterAcceptsRow ( self , row_num , parent ) :
"""Qt override .
Reimplemented from base class to allow the use of custom filtering .""" | model = self . sourceModel ( )
name = model . row ( row_num ) . name
r = re . search ( self . pattern , name )
if r is None :
return False
else :
return True |
def result_str ( self ) :
"""Return a string representing the totals contained herein .
: return : str counts / types string""" | return '{}, {}, {}' . format ( LocalOnlyCounter . plural_fmt ( 'project' , self . projects ) , LocalOnlyCounter . plural_fmt ( 'folder' , self . folders ) , LocalOnlyCounter . plural_fmt ( 'file' , self . files ) ) |
def npoints_between ( lon1 , lat1 , depth1 , lon2 , lat2 , depth2 , npoints ) :
"""Find a list of specified number of points between two given ones that are
equally spaced along the great circle arc connecting given points .
: param float lon1 , lat1 , depth1:
Coordinates of a point to start from . The first ... | hdist = geodetic_distance ( lon1 , lat1 , lon2 , lat2 )
vdist = depth2 - depth1
rlons , rlats , rdepths = npoints_towards ( lon1 , lat1 , depth1 , azimuth ( lon1 , lat1 , lon2 , lat2 ) , hdist , vdist , npoints )
# the last point should be left intact
rlons [ - 1 ] = lon2
rlats [ - 1 ] = lat2
rdepths [ - 1 ] = depth2
r... |
def unbounded ( self ) :
"""Returns a list of key dimensions that are unbounded , excluding
stream parameters . If any of theses key dimensions are
unbounded , the DynamicMap as a whole is also unbounded .""" | unbounded_dims = [ ]
# Dimensioned streams do not need to be bounded
stream_params = set ( util . stream_parameters ( self . streams ) )
for kdim in self . kdims :
if str ( kdim ) in stream_params :
continue
if kdim . values :
continue
if None in kdim . range :
unbounded_dims . appen... |
def Write ( self , output_writer ) :
"""Writes the table to output writer .
Args :
output _ writer ( CLIOutputWriter ) : output writer .""" | # Round up the column sizes to the nearest tab .
for column_index , column_size in enumerate ( self . _column_sizes ) :
column_size , _ = divmod ( column_size , self . _NUMBER_OF_SPACES_IN_TAB )
column_size = ( column_size + 1 ) * self . _NUMBER_OF_SPACES_IN_TAB
self . _column_sizes [ column_index ] = colum... |
def update_current_tags ( self , tags ) :
"""Set a new set of tags for this executable .
Update the set of tags that this job will use . This updated default
file naming and shared options . It will * not * update the pegasus
profile , which belong to the executable and cannot be different for
different nod... | if tags is None :
tags = [ ]
tags = [ tag . upper ( ) for tag in tags ]
self . tags = tags
if len ( tags ) > 6 :
warn_msg = "This job has way too many tags. "
warn_msg += "Current tags are {}. " . format ( ' ' . join ( tags ) )
warn_msg += "Current executable {}." . format ( self . name )
logging . ... |
def xpatherror ( self , file , line , no ) :
"""Formats an error message .""" | libxml2mod . xmlXPatherror ( self . _o , file , line , no ) |
def _check_connection ( self ) :
"""Check if connection is alive every reconnect _ timeout seconds .""" | if ( ( self . tcp_disconnect_timer + 2 * self . reconnect_timeout ) < time . time ( ) ) :
self . tcp_disconnect_timer = time . time ( )
raise OSError ( 'No response from {}. Disconnecting' . format ( self . server_address ) )
if ( self . tcp_check_timer + self . reconnect_timeout ) >= time . time ( ) :
retu... |
def save_bin ( self , bin_form , * args , ** kwargs ) :
"""Pass through to provider BinAdminSession . update _ bin""" | # Implemented from kitosid template for -
# osid . resource . BinAdminSession . update _ bin
if bin_form . is_for_update ( ) :
return self . update_bin ( bin_form , * args , ** kwargs )
else :
return self . create_bin ( bin_form , * args , ** kwargs ) |
def parse_line_headers ( self , line ) :
"""We must build headers carefully : there are multiple blank values
in the header row , and the instrument may just add more for all
we know .""" | headers = line . split ( "," )
for i , v in enumerate ( headers ) :
if v :
headers [ i ] = v
else :
headers [ i ] = str ( i )
self . headers = headers |
def drawLognormal ( N , mu = 0.0 , sigma = 1.0 , seed = 0 ) :
'''Generate arrays of mean one lognormal draws . The sigma input can be a number
or list - like . If a number , output is a length N array of draws from the
lognormal distribution with standard deviation sigma . If a list , output is
a length T lis... | # Set up the RNG
RNG = np . random . RandomState ( seed )
if isinstance ( sigma , float ) : # Return a single array of length N
if sigma == 0 :
draws = np . exp ( mu ) * np . ones ( N )
else :
draws = RNG . lognormal ( mean = mu , sigma = sigma , size = N )
else : # Set up empty list to populate... |
async def create_student_container ( self , job_id , parent_container_id , sockets_path , student_path , systemfiles_path , course_common_student_path , socket_id , environment_name , memory_limit , time_limit , hard_time_limit , share_network , write_stream ) :
"""Creates a new student container .
: param write ... | try :
self . _logger . debug ( "Starting new student container... %s %s %s %s" , environment_name , memory_limit , time_limit , hard_time_limit )
if environment_name not in self . _containers :
self . _logger . warning ( "Student container asked for an unknown environment %s (not in aliases)" , environm... |
def _check_package ( pkg_xml , zipfilename , zf ) :
"""Helper for ` ` build _ index ( ) ` ` : Perform some checks to make sure that
the given package is consistent .""" | # The filename must patch the id given in the XML file .
uid = os . path . splitext ( os . path . split ( zipfilename ) [ 1 ] ) [ 0 ]
if pkg_xml . get ( 'id' ) != uid :
raise ValueError ( 'package identifier mismatch (%s vs %s)' % ( pkg_xml . get ( 'id' ) , uid ) )
# Zip file must expand to a subdir whose name matc... |
def jacobi ( A , x , b , iterations = 1 , omega = 1.0 ) :
"""Perform Jacobi iteration on the linear system Ax = b .
Parameters
A : csr _ matrix
Sparse NxN matrix
x : ndarray
Approximate solution ( length N )
b : ndarray
Right - hand side ( length N )
iterations : int
Number of iterations to perfor... | A , x , b = make_system ( A , x , b , formats = [ 'csr' , 'bsr' ] )
sweep = slice ( None )
( row_start , row_stop , row_step ) = sweep . indices ( A . shape [ 0 ] )
if ( row_stop - row_start ) * row_step <= 0 : # no work to do
return
temp = np . empty_like ( x )
# Create uniform type , convert possibly complex scal... |
def exam_reliability ( x_axis , x_axis_new , reliable_distance , precision = 0.0001 ) :
"""When we do linear interpolation on x _ axis and derive value for
x _ axis _ new , we also evaluate how can we trust those interpolated
data points . This is how it works :
For each new x _ axis point in x _ axis new , l... | x_axis = x_axis [ : : - 1 ]
x_axis . append ( - 2 ** 32 )
distance_to_closest_point = list ( )
for t in x_axis_new :
while 1 :
try :
x = x_axis . pop ( )
if x <= t :
left = x
else :
right = x
x_axis . append ( right )
... |
def _print_trainings_long ( trainings : Iterable [ Tuple [ str , dict , TrainingTrace ] ] ) -> None :
"""Print a plain table with the details of the given trainings .
: param trainings : iterable of tuples ( train _ dir , configuration dict , trace )""" | long_table = [ ]
for train_dir , config , trace in trainings :
start_datetime , end_datetime = trace [ TrainingTraceKeys . TRAIN_BEGIN ] , trace [ TrainingTraceKeys . TRAIN_END ]
if start_datetime :
age = format_timedelta ( datetime . now ( ) - start_datetime ) + ' ago'
if end_datetime :
... |
def _make_expr_empty_dict ( toplevel , stack_builders ) :
"""This should only be hit for empty dicts . Anything else should hit the
STORE _ MAP handler instead .""" | if toplevel . arg :
raise DecompilationError ( "make_expr() called with nonzero BUILD_MAP arg %d" % toplevel . arg )
if stack_builders :
raise DecompilationError ( "Unexpected stack_builders for BUILD_MAP(0): %s" % stack_builders )
return ast . Dict ( keys = [ ] , values = [ ] ) |
def hacking_no_old_style_class ( logical_line , noqa ) :
r"""Check for old style classes .
Examples :
Okay : class Foo ( object ) : \ n pass
Okay : class Foo ( Bar , Baz ) : \ n pass
Okay : class Foo ( object , Baz ) : \ n pass
Okay : class Foo ( somefunc ( ) ) : \ n pass
H238 : class Bar : \ n pass
H... | if noqa :
return
line = core . import_normalize ( logical_line . strip ( ) )
if line . startswith ( "class " ) and not RE_NEW_STYLE_CLASS . match ( line ) :
yield ( 0 , "H238: old style class declaration, " "use new style (inherit from `object`)" ) |
def check_backends ( self , service_id , version_number ) :
"""Performs a health check against each backend in version . If the backend has a specific type of healthcheck , that one is performed , otherwise a HEAD request to / is performed . The first item is the details on the Backend itself . The second item is d... | content = self . _fetch ( "/service/%s/version/%d/backend/check_all" % ( service_id , version_number ) )
# TODO : Use a strong - typed class for output ?
return content |
def add_detection_pattern ( self , m ) :
"""This method add the detection patterns to the QR code . This lets
the scanner orient the pattern . It is required for all QR codes .
The detection pattern consists of three boxes located at the upper
left , upper right , and lower left corners of the matrix . Also ,... | # Draw outer black box
for i in range ( 7 ) :
inv = - ( i + 1 )
for j in [ 0 , 6 , - 1 , - 7 ] :
m [ j ] [ i ] = 1
m [ i ] [ j ] = 1
m [ inv ] [ j ] = 1
m [ j ] [ inv ] = 1
# Draw inner white box
for i in range ( 1 , 6 ) :
inv = - ( i + 1 )
for j in [ 1 , 5 , - 2 , - 6 ] ... |
def dump_collection ( cfg , f , indent = 0 ) :
'''Save a collection of attributes''' | for i , value in enumerate ( cfg ) :
dump_value ( None , value , f , indent )
if i < len ( cfg ) - 1 :
f . write ( u',\n' ) |
def getProjectAreaIDs ( self , projectarea_name = None , archived = False ) :
"""Get all : class : ` rtcclient . project _ area . ProjectArea ` id ( s )
by project area name
If ` projectarea _ name ` is ` None ` , all the
: class : ` rtcclient . project _ area . ProjectArea ` id ( s ) will be returned .
: p... | projectarea_ids = list ( )
if projectarea_name and isinstance ( projectarea_name , six . string_types ) :
projectarea_id = self . getProjectAreaID ( projectarea_name , archived = archived )
projectarea_ids . append ( projectarea_id )
elif projectarea_name is None :
projectareas = self . getProjectAreas ( ar... |
def print_request ( request ) :
"""Prints a prepared request to give the user info as to what they ' re sending
: param request . PreparedRequest request : PreparedRequest object to be printed
: return : Nothing""" | print ( '{}\n{}\n{}\n\n{}' . format ( '-----------START-----------' , request . method + ' ' + request . url , '\n' . join ( '{}: {}' . format ( k , v ) for k , v in request . headers . items ( ) ) , request . body , ) ) |
def list_team_members ( team_name , profile = "github" , ignore_cache = False ) :
'''Gets the names of team members in lower case .
team _ name
The name of the team from which to list members .
profile
The name of the profile configuration to use . Defaults to ` ` github ` ` .
ignore _ cache
Bypasses th... | cached_team = get_team ( team_name , profile = profile )
if not cached_team :
log . error ( 'Team %s does not exist.' , team_name )
return False
# Return from cache if available
if cached_team . get ( 'members' ) and not ignore_cache :
return cached_team . get ( 'members' )
try :
client = _get_client ( ... |
def enable_parallel_lz4 ( mode ) :
"""Set the global multithread compression mode
Parameters
mode : ` bool `
True : Use parallel compression . False : Use sequential compression""" | global ENABLE_PARALLEL
ENABLE_PARALLEL = bool ( mode )
logger . info ( "Setting parallelisation mode to {}" . format ( "multi-threaded" if mode else "single-threaded" ) ) |
def disconnectMsToNet ( Facility_presence = 0 , UserUser_presence = 0 , SsVersionIndicator_presence = 0 ) :
"""Disconnect Section 9.3.7.2""" | a = TpPd ( pd = 0x3 )
b = MessageType ( mesType = 0x25 )
# 00100101
c = Cause ( )
packet = a / b / c
if Facility_presence is 1 :
d = FacilityHdr ( ieiF = 0x1C , eightBitF = 0x0 )
packet = packet / d
if UserUser_presence is 1 :
e = UserUserHdr ( ieiUU = 0x7E , eightBitUU = 0x0 )
packet = packet / e
if Ss... |
def close ( self ) :
"""Stop serving the : attr : ` . Server . sockets ` and close all
concurrent connections .""" | transports , self . transports = self . transports , [ ]
for transport in transports :
transport . close ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.