signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def meta_retrieve ( self , meta_lookahead = None ) :
"""Get metadata from the query itself . This is guaranteed to only
return a Python dictionary .
Note that if the query failed , the metadata might not be in JSON
format , in which case there may be additional , non - JSON data
which can be retrieved using... | if not self . __meta_received :
if meta_lookahead or self . meta_lookahead :
self . buffered_remainder = list ( self )
else :
raise RuntimeError ( 'This property only valid once all rows are received!' )
if isinstance ( self . raw . value , dict ) :
return self . raw . value
return { } |
def chunks ( l : List [ Any ] , n : int ) -> Iterable [ List [ Any ] ] :
"""Yield successive ` ` n ` ` - sized chunks from ` ` l ` ` .
Args :
l : input list
n : chunk size
Yields :
successive chunks of size ` ` n ` `""" | for i in range ( 0 , len ( l ) , n ) :
yield l [ i : i + n ] |
def encode ( message , encoding_type = 'default' , letter_sep = ' ' * 3 , strip = True ) :
"""Converts a string of message into morse
Two types of marks are there . One is short mark , dot ( . ) or " dit " and
other is long mark , dash ( - ) or " dah " . After every dit or dah , there is
a one dot duration or... | if strip :
message = message . strip ( )
# No trailing or leading spaces
encoding_type = encoding_type . lower ( )
allowed_encoding_type = [ 'default' , 'binary' ]
if encoding_type == 'default' :
return _encode_to_morse_string ( message , letter_sep )
elif encoding_type == 'binary' :
return _encode_to_binar... |
def nla_put_u64 ( msg , attrtype , value ) :
"""Add 64 bit integer attribute to Netlink message .
https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / attr . c # L638
Positional arguments :
msg - - Netlink message ( nl _ msg class instance ) .
attrtype - - attribute type ( integer ) .
v... | data = bytearray ( value if isinstance ( value , c_uint64 ) else c_uint64 ( value ) )
return nla_put ( msg , attrtype , SIZEOF_U64 , data ) |
def hwaddr_interfaces ( ) :
'''Provide a dict of the connected interfaces and their
hw addresses ( Mac Address )''' | # Provides :
# hwaddr _ interfaces
ret = { }
ifaces = _get_interfaces ( )
for face in ifaces :
if 'hwaddr' in ifaces [ face ] :
ret [ face ] = ifaces [ face ] [ 'hwaddr' ]
return { 'hwaddr_interfaces' : ret } |
def DOM_describeNode ( self , ** kwargs ) :
"""Function path : DOM . describeNode
Domain : DOM
Method name : describeNode
Parameters :
Optional arguments :
' nodeId ' ( type : NodeId ) - > Identifier of the node .
' backendNodeId ' ( type : BackendNodeId ) - > Identifier of the backend node .
' object... | if 'depth' in kwargs :
assert isinstance ( kwargs [ 'depth' ] , ( int , ) ) , "Optional argument 'depth' must be of type '['int']'. Received type: '%s'" % type ( kwargs [ 'depth' ] )
if 'pierce' in kwargs :
assert isinstance ( kwargs [ 'pierce' ] , ( bool , ) ) , "Optional argument 'pierce' must be of type '['b... |
def __set_hard_hard_constraints ( self , tdata1 , tdata2 , seeds ) :
"""it works with seed labels :
0 : nothing
1 : object 1 - full seeds
2 : object 2 - full seeds
3 : object 1 - not a training seeds
4 : object 2 - not a training seeds""" | seeds_mask = ( seeds == 1 ) | ( seeds == 3 )
tdata2 [ seeds_mask ] = np . max ( tdata2 ) + 1
tdata1 [ seeds_mask ] = 0
seeds_mask = ( seeds == 2 ) | ( seeds == 4 )
tdata1 [ seeds_mask ] = np . max ( tdata1 ) + 1
tdata2 [ seeds_mask ] = 0
return tdata1 , tdata2 |
def _get_data ( self , id_list , format = 'MLDataset' ) :
"""Returns the data , from all modalities , for a given list of IDs""" | format = format . lower ( )
features = list ( )
# returning a dict would be better if AutoMKL ( ) can handle it
for modality , data in self . _modalities . items ( ) :
if format in ( 'ndarray' , 'data_matrix' ) : # turning dict of arrays into a data matrix
# this is arguably worse , as labels are difficult to p... |
def save ( self , inplace = True ) :
"""Saves all modification to the task on the server .
: param inplace Apply edits on the current instance or get a new one .
: return : Task instance .""" | modified_data = self . _modified_data ( )
if bool ( modified_data ) :
task_request_data = { }
inputs = modified_data . pop ( 'inputs' , None )
execution_settings = modified_data . pop ( 'execution_settings' , None )
task_request_data . update ( modified_data )
if inputs :
task_request_data [... |
def number_text_lines ( text ) :
r"""Args :
text ( str ) :
Returns :
str : text _ with _ lineno - string with numbered lines""" | numbered_linelist = [ '' . join ( ( ( '%2d' % ( count + 1 ) ) , ' >>> ' , line ) ) for count , line in enumerate ( text . splitlines ( ) ) ]
text_with_lineno = '\n' . join ( numbered_linelist )
return text_with_lineno |
def flush ( self ) :
"""Flush all streams .""" | if self . __logFileStream is not None :
try :
self . __logFileStream . flush ( )
except :
pass
try :
os . fsync ( self . __logFileStream . fileno ( ) )
except :
pass
if self . __stdout is not None :
try :
self . __stdout . flush ( )
except :
pass
... |
def maybe_convert_ix ( * args ) :
"""We likely want to take the cross - product""" | ixify = True
for arg in args :
if not isinstance ( arg , ( np . ndarray , list , ABCSeries , Index ) ) :
ixify = False
if ixify :
return np . ix_ ( * args )
else :
return args |
def _retrieve_device_cache ( proxy = None ) :
'''Loads the network device details if not cached already .''' | global DEVICE_CACHE
if not DEVICE_CACHE :
if proxy and salt . utils . napalm . is_proxy ( __opts__ ) : # if proxy var passed and is NAPALM - type proxy minion
if 'napalm.get_device' in proxy :
DEVICE_CACHE = proxy [ 'napalm.get_device' ] ( )
elif not proxy and salt . utils . napalm . is_mini... |
def sample_distinct ( self , n_to_sample , ** kwargs ) :
"""Sample a sequence of items from the pool until a minimum number of
distinct items are queried
Parameters
n _ to _ sample : int
number of distinct items to sample . If sampling with replacement ,
this number is not necessarily the same as the numb... | # Record how many distinct items have not yet been sampled
n_notsampled = np . sum ( np . isnan ( self . cached_labels_ ) )
if n_notsampled == 0 :
raise Exception ( "All distinct items have already been sampled." )
if n_to_sample > n_notsampled :
warnings . warn ( "Only {} distinct item(s) have not yet been sam... |
def _begin_validation ( session : UpdateSession , loop : asyncio . AbstractEventLoop , downloaded_update_path : str , robot_name : str ) -> asyncio . futures . Future :
"""Start the validation process .""" | session . set_stage ( Stages . VALIDATING )
validation_future = asyncio . ensure_future ( loop . run_in_executor ( None , validate_update , downloaded_update_path , session . set_progress ) )
def validation_done ( fut ) :
exc = fut . exception ( )
if exc :
session . set_error ( getattr ( exc , 'short' ,... |
def get_epit_vintage_matrix ( self , mnemonic , date_from = '1951-01-01' , date_to = None ) :
"""Construct the vintage matrix for a given economic series .
Requires subscription to Thomson Reuters Economic Point - in - Time ( EPiT ) .
Vintage matrix represents a DataFrame where columns correspond to a
particu... | # Get first available date from the REL1 series
rel1 = self . fetch ( mnemonic , 'REL1' , date_from = date_from , date_to = date_to )
date_0 = rel1 . dropna ( ) . index [ 0 ]
# All release dates
reld123 = self . fetch ( mnemonic , [ 'RELD1' , 'RELD2' , 'RELD3' ] , date_from = date_0 , date_to = date_to ) . dropna ( how... |
def _logger ( self ) :
"""Create a logger to be used between processes .
: returns : Logging instance .""" | logger = logging . getLogger ( self . NAME )
logger . setLevel ( self . LOG_LEVEL )
shandler = logging . StreamHandler ( sys . stdout )
fmt = '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():'
fmt += '%(lineno)d %(asctime)s\033[0m| %(message)s'
shandler . setFormatter ( logging . Formatter ( fmt ) )
logger . addHan... |
def abspath ( path , ref = None ) :
"""Create an absolute path .
Parameters
path : str
absolute or relative path with respect to ` ref `
ref : str or None
reference path if ` path ` is relative
Returns
path : str
absolute path
Raises
ValueError
if an absolute path cannot be constructed""" | if ref :
path = os . path . join ( ref , path )
if not os . path . isabs ( path ) :
raise ValueError ( "expected an absolute path but got '%s'" % path )
return path |
def _delete_os_nwk ( self , tenant_id , tenant_name , direc , is_fw_virt = False ) :
"""Delete the network created in Openstack .
Function to delete Openstack network , It also releases the associated
segmentation , VLAN and subnets .""" | serv_obj = self . get_service_obj ( tenant_id )
fw_dict = serv_obj . get_fw_dict ( )
fw_id = fw_dict . get ( 'fw_id' )
fw_data , fw_data_dict = self . get_fw ( fw_id )
if fw_data is None :
LOG . error ( "Unable to get fw_data for tenant %s" , tenant_name )
return False
if direc == 'in' :
net_id = fw_data . ... |
def format ( self , result ) :
"""Generate plain text report .
: return : Report body
: rtype : str""" | m = self . meta
lines = [ '-' * len ( self . TITLE ) , self . TITLE , '-' * len ( self . TITLE ) , "Compared: {db1} <-> {db2}" . format ( ** m ) , "Filter: {filter}" . format ( ** m ) , "Run time: {start_time} -- {end_time} ({elapsed:.1f} sec)" . format ( ** m ) , "" ]
for section in result . keys ( ) :
lines . app... |
def format_table ( table , align = '<' , format = '{:.3g}' , colwidth = None , maxwidth = None , spacing = 2 , truncate = 0 , suffix = "..." ) :
"""Formats a table represented as an iterable of iterable into a nice big string
suitable for printing .
Parameters :
align : string or list of strings
Alignment o... | table = list ( deepcopy ( table ) )
if not isinstance ( align , list ) :
align = [ align ]
if not isinstance ( format , list ) :
format = [ format ]
if not isinstance ( format [ 0 ] , list ) :
format = [ format ]
num_cols = len ( table [ 0 ] )
if len ( set ( [ len ( row ) for row in table ] ) ) > 1 :
ra... |
def delegate_to_method ( mtd ) :
"""Create a simplification rule that delegates the instantiation to the
method ` mtd ` of the operand ( if defined )""" | def _delegate_to_method ( cls , ops , kwargs ) :
assert len ( ops ) == 1
op , = ops
if hasattr ( op , mtd ) :
return getattr ( op , mtd ) ( )
else :
return ops , kwargs
return _delegate_to_method |
def get_context ( self , context ) :
"""Return a tag or a list of tags context encoded .""" | # forward pass
i = 0
while i < len ( self . tagList ) :
tag = self . tagList [ i ]
# skip application stuff
if tag . tagClass == Tag . applicationTagClass :
pass
# check for context encoded atomic value
elif tag . tagClass == Tag . contextTagClass :
if tag . tagNumber == context :
... |
def disco_loop ( opc , version , queue , real_out , dup_lines = False , show_bytes = False ) :
"""Disassembles a queue of code objects . If we discover
another code object which will be found in co _ consts , we add
the new code to the list . Note that the order of code discovery
is in the order of first enco... | while len ( queue ) > 0 :
co = queue . popleft ( )
if co . co_name not in ( '<module>' , '?' ) :
real_out . write ( "\n" + format_code_info ( co , version ) + "\n" )
bytecode = Bytecode ( co , opc , dup_lines = dup_lines )
real_out . write ( bytecode . dis ( show_bytes = show_bytes ) + "\n" )
... |
def standardize ( self , x ) :
"""Apply the normalization configuration to a batch of inputs .
# Arguments
x : batch of inputs to be normalized .
# Returns
The inputs , normalized .""" | if self . preprocessing_function :
x = self . preprocessing_function ( x )
if self . rescale :
x *= self . rescale
if self . samplewise_center :
x -= np . mean ( x , keepdims = True )
if self . samplewise_std_normalization :
x /= np . std ( x , keepdims = True ) + 1e-7
if self . featurewise_center :
... |
def _import_matplotlib ( ) :
"""Import matplotlib safely .""" | # make sure that the Agg backend is set before importing any
# matplotlib
import matplotlib
matplotlib . use ( 'agg' )
matplotlib_backend = matplotlib . get_backend ( ) . lower ( )
if matplotlib_backend != 'agg' :
raise ValueError ( "Sphinx-Gallery relies on the matplotlib 'agg' backend to " "render figures and wri... |
def to_string ( self ) :
"""Convert SitemapIndex into a string .""" | root = etree . Element ( 'sitemapindex' , nsmap = { None : SITEMAP_NS } )
for sitemap in self . sitemaps :
sm = etree . SubElement ( root , 'sitemap' )
etree . SubElement ( sm , 'loc' ) . text = sitemap . url
if hasattr ( sitemap . lastmod , 'strftime' ) :
etree . SubElement ( sm , 'lastmod' ) . tex... |
def is_singlesig ( privkey_info , blockchain = 'bitcoin' , ** blockchain_opts ) :
"""Is the given private key bundle a single - sig key bundle ?""" | if blockchain == 'bitcoin' :
return btc_is_singlesig ( privkey_info , ** blockchain_opts )
else :
raise ValueError ( 'Unknown blockchain "{}"' . format ( blockchain ) ) |
def map_over_glob ( fn , path , pattern ) :
"""map a function over a glob pattern , relative to a directory""" | return [ fn ( x ) for x in glob . glob ( os . path . join ( path , pattern ) ) ] |
def get_default_candidate ( self , component ) :
"""Gets the default local candidate for the specified component .""" | for candidate in sorted ( self . _local_candidates , key = lambda x : x . priority ) :
if candidate . component == component :
return candidate |
def _check_cmdline ( data ) :
'''In some cases where there are an insane number of processes being created
on a system a PID can get recycled or assigned to a non - Salt process .
On Linux this fn checks to make sure the PID we are checking on is actually
a Salt process .
For non - Linux systems we punt and... | if not salt . utils . platform . is_linux ( ) :
return True
pid = data . get ( 'pid' )
if not pid :
return False
if not os . path . isdir ( '/proc' ) :
return True
path = os . path . join ( '/proc/{0}/cmdline' . format ( pid ) )
if not os . path . isfile ( path ) :
return False
try :
with salt . uti... |
def cleanup_defenses ( self ) :
"""Cleans up all data about defense work in current round .""" | print_header ( 'CLEANING UP DEFENSES DATA' )
work_ancestor_key = self . datastore_client . key ( 'WorkType' , 'AllDefenses' )
keys_to_delete = [ e . key for e in self . datastore_client . query_fetch ( kind = u'ClassificationBatch' ) ] + [ e . key for e in self . datastore_client . query_fetch ( kind = u'Work' , ancest... |
def build_play ( self , pbp_row ) :
"""Parses table row from RTSS . These are the rows tagged with ` ` < tr class = ' evenColor ' . . . > ` ` . Result set
contains : py : class : ` nhlscrapi . games . playbyplay . Strength ` and : py : class : ` nhlscrapi . games . events . EventType `
objects . Returned play d... | d = pbp_row . findall ( './td' )
c = PlayParser . ColMap ( self . season )
p = { }
to_dig = lambda t : int ( t ) if t . isdigit ( ) else 0
p [ 'play_num' ] = to_int ( d [ c [ "play_num" ] ] . text , 0 )
p [ 'period' ] = to_int ( d [ c [ "per" ] ] . text , 0 )
p [ 'strength' ] = self . __strength ( d [ c [ "str" ] ] . t... |
def _get_max_size ( parts , size = 1 ) :
"""Given a list of parts , find the maximum number of commands
contained in it .""" | max_group_size = 0
for part in parts :
if isinstance ( part , list ) :
group_size = 0
for input_group in part :
group_size += 1
if group_size > max_group_size :
max_group_size = group_size
magic_size = _get_magic_size ( parts )
return max_group_size * magic_size |
def input_files ( self ) :
"""List the input files""" | return self . workspace . mets . find_files ( fileGrp = self . input_file_grp , pageId = self . page_id ) |
def set_connection ( self , service_name , to_cache ) :
"""Sets a connection class within the cache .
: param service _ name : The service a given ` ` Connection ` ` talks to . Ex .
` ` sqs ` ` , ` ` sns ` ` , ` ` dynamodb ` ` , etc .
: type service _ name : string
: param to _ cache : The class to be cache... | self . services . setdefault ( service_name , { } )
self . services [ service_name ] [ 'connection' ] = to_cache |
def convert_python_regex_to_ecma ( value , flags = [ ] ) :
"""Convert Python regex to ECMA 262 regex .
If given value is already ECMA regex it will be returned unchanged .
: param string value : Python regex .
: param list flags : List of flags ( allowed flags : ` re . I ` , ` re . M ` )
: return : ECMA 262... | if is_ecma_regex ( value ) :
return value
result_flags = [ PYTHON_TO_ECMA_FLAGS [ f ] for f in flags ]
result_flags = '' . join ( result_flags )
return '/{value}/{flags}' . format ( value = value , flags = result_flags ) |
def relation_to_intermediary ( fk ) :
"""Transform an SQLAlchemy ForeignKey object to it ' s intermediary representation .""" | return Relation ( right_col = format_name ( fk . parent . table . fullname ) , left_col = format_name ( fk . _column_tokens [ 1 ] ) , right_cardinality = '?' , left_cardinality = '*' , ) |
async def get_or_create ( cls , lang : str , * , client_token : str = None , mounts : Iterable [ str ] = None , envs : Mapping [ str , str ] = None , resources : Mapping [ str , int ] = None , cluster_size : int = 1 , tag : str = None , owner_access_key : str = None ) -> 'Kernel' :
'''Get - or - creates a compute s... | if client_token :
assert 4 <= len ( client_token ) <= 64 , 'Client session token should be 4 to 64 characters long.'
else :
client_token = uuid . uuid4 ( ) . hex
if mounts is None :
mounts = [ ]
if resources is None :
resources = { }
mounts . extend ( cls . session . config . vfolder_mounts )
rqst = Req... |
def _cursor ( self ) :
"""Asserts that the connection is open and returns a cursor""" | if self . _conn is None :
self . _conn = sqlite3 . connect ( self . filename , check_same_thread = False )
return self . _conn . cursor ( ) |
def on_message ( self , event ) :
'''Runs when a message event is received
Args :
event : RTM API event .
Returns :
Legobot . messge''' | metadata = self . _parse_metadata ( event )
message = Message ( text = metadata [ 'text' ] , metadata = metadata ) . __dict__
if message . get ( 'text' ) :
message [ 'text' ] = self . find_and_replace_userids ( message [ 'text' ] )
message [ 'text' ] = self . find_and_replace_channel_refs ( message [ 'text' ] )... |
def tokenize_akkadian_signs ( word ) :
"""Takes tuple ( word , language ) and splits the word up into individual
sign tuples ( sign , language ) in a list .
input : ( " { gisz } isz - pur - ram " , " akkadian " )
output : [ ( " gisz " , " determinative " ) , ( " isz " , " akkadian " ) ,
( " pur " , " akkadi... | word_signs = [ ]
sign = ''
language = word [ 1 ]
determinative = False
for char in word [ 0 ] :
if determinative is True :
if char == '}' :
determinative = False
if len ( sign ) > 0 : # pylint : disable = len - as - condition
word_signs . append ( ( sign , 'determinat... |
def get_credentials ( self ) :
"""Return a set of credentials that may be used to access the Upload Area folder in the S3 bucket
: return : a dict containing AWS credentials in a format suitable for passing to Boto3
or if capitalized , used as environment variables""" | creds_mgr = CredentialsManager ( self )
creds = creds_mgr . get_credentials_from_upload_api ( )
return { 'aws_access_key_id' : creds [ 'access_key' ] , 'aws_secret_access_key' : creds [ 'secret_key' ] , 'aws_session_token' : creds [ 'token' ] , 'expiry_time' : creds [ 'expiry_time' ] } |
def dissolve ( inlist ) :
"""list and tuple flattening
Parameters
inlist : list
the list with sub - lists or tuples to be flattened
Returns
list
the flattened result
Examples
> > > dissolve ( [ [ 1 , 2 ] , [ 3 , 4 ] ] )
[1 , 2 , 3 , 4]
> > > dissolve ( [ ( 1 , 2 , ( 3 , 4 ) ) , [ 5 , ( 6 , 7 ) ]... | out = [ ]
for i in inlist :
i = list ( i ) if isinstance ( i , tuple ) else i
out . extend ( dissolve ( i ) ) if isinstance ( i , list ) else out . append ( i )
return out |
def get_handler ( self , handler_input , exception ) : # type : ( Input , Exception ) - > Union [ AbstractExceptionHandler , None ]
"""Get the exception handler that can handle the input and
exception .
: param handler _ input : Generic input passed to the
dispatcher .
: type handler _ input : Input
: par... | for handler in self . exception_handlers :
if handler . can_handle ( handler_input = handler_input , exception = exception ) :
return handler
return None |
def get_html_tag_lang_params ( index_page ) :
"""Parse lang and xml : lang parameters in the ` ` < html > ` ` tag .
See
https : / / www . w3 . org / International / questions / qa - html - language - declarations
for details .
Args :
index _ page ( str ) : HTML content of the page you wisht to analyze .
... | dom = dhtmlparser . parseString ( index_page )
html_tag = dom . find ( "html" )
if not html_tag :
return [ ]
html_tag = html_tag [ 0 ]
# parse parameters
lang = html_tag . params . get ( "lang" )
xml_lang = html_tag . params . get ( "xml:lang" )
if lang and lang == xml_lang :
return [ SourceString ( lang , sour... |
def removeSettingsGroup ( groupName , settings = None ) :
"""Removes a group from the persistent settings""" | logger . debug ( "Removing settings group: {}" . format ( groupName ) )
settings = QtCore . QSettings ( ) if settings is None else settings
settings . remove ( groupName ) |
def get_value_ddist ( self , attr_name , attr_value ) :
"""Returns the class value probability distribution of the given
attribute value .""" | assert not self . tree . data . is_continuous_class , "Discrete distributions are only maintained for " + "discrete class types."
ddist = DDist ( )
cls_counts = self . _attr_class_value_counts [ attr_name ] [ attr_value ]
for cls_value , cls_count in iteritems ( cls_counts ) :
ddist . add ( cls_value , count = cls_... |
def continuousSetsGenerator ( self , request ) :
"""Returns a generator over the ( continuousSet , nextPageToken ) pairs
defined by the specified request .""" | dataset = self . getDataRepository ( ) . getDataset ( request . dataset_id )
return self . _topLevelObjectGenerator ( request , dataset . getNumContinuousSets ( ) , dataset . getContinuousSetByIndex ) |
def get_object ( self ) :
"""Return the object of this TimeMachine""" | return self . content_type . model_class ( ) . objects . get ( uid = self . uid ) |
def _add_users ( self , db , mongo_version ) :
"""Add given user , and extra x509 user if necessary .""" | if self . x509_extra_user : # Build dict of kwargs to pass to add _ user .
auth_dict = { 'name' : DEFAULT_SUBJECT , 'roles' : self . _user_roles ( db . client ) }
db . add_user ( ** auth_dict )
# Fix kwargs to MongoClient .
self . kwargs [ 'ssl_certfile' ] = DEFAULT_CLIENT_CERT
# Add secondary user give... |
def provision ( self , conf ) :
"""Provision this metaconfig ' s config with what we gathered .
Since Config has native support for ini files , we just need to
let this metaconfig ' s config know about the ini file we found .
In future scenarios , this is where we would implement logic
specific to a metacon... | if self . ini and self . ini not in conf . _ini_paths :
conf . _ini_paths . insert ( 0 , self . ini ) |
def get_document_summary ( self , N = None , cite_sort = True , refresh = True ) :
"""Return a summary string of documents .
Parameters
N : int or None ( optional , default = None )
Maximum number of documents to include in the summary .
If None , return all documents .
cite _ sort : bool ( optional , def... | abstracts = self . get_abstracts ( refresh = refresh )
if cite_sort :
counts = [ ( a , int ( a . citedby_count ) ) for a in abstracts ]
counts . sort ( reverse = True , key = itemgetter ( 1 ) )
abstracts = [ a [ 0 ] for a in counts ]
if N is None :
N = len ( abstracts )
s = [ u'{0} of {1} documents' . f... |
def read_hdf5_dict ( h5f , names = None , group = None , ** kwargs ) :
"""Read a ` TimeSeriesDict ` from HDF5""" | # find group from which to read
if group :
h5g = h5f [ group ]
else :
h5g = h5f
# find list of names to read
if names is None :
names = [ key for key in h5g if _is_timeseries_dataset ( h5g [ key ] ) ]
# read names
out = kwargs . pop ( 'dict_type' , TimeSeriesDict ) ( )
kwargs . setdefault ( 'array_type' , o... |
def softplus ( attrs , inputs , proto_obj ) :
"""Applies the sofplus activation function element - wise to the input .""" | new_attrs = translation_utils . _add_extra_attributes ( attrs , { 'act_type' : 'softrelu' } )
return 'Activation' , new_attrs , inputs |
def _check_channel_state_for_update ( self , channel_identifier : ChannelID , closer : Address , update_nonce : Nonce , block_identifier : BlockSpecification , ) -> Optional [ str ] :
"""Check the channel state on chain to see if it has been updated .
Compare the nonce , we are about to update the contract with ,... | msg = None
closer_details = self . _detail_participant ( channel_identifier = channel_identifier , participant = closer , partner = self . node_address , block_identifier = block_identifier , )
if closer_details . nonce == update_nonce :
msg = ( 'updateNonClosingBalanceProof transaction has already ' 'been mined an... |
def get_file ( self , name , filename ) :
"""Saves the content of file named ` ` name ` ` to ` ` filename ` ` .
Works like : meth : ` get _ stream ` , but ` ` filename ` ` is the name of
a file which will be created ( or overwritten ) .
Returns the full versioned name of the retrieved file .""" | stream , vname = self . get_stream ( name )
path , version = split_name ( vname )
dir_path = os . path . dirname ( filename )
if dir_path :
mkdir ( dir_path )
with open ( filename , 'wb' ) as f :
shutil . copyfileobj ( stream , f )
return vname |
def clustering_coef_wu ( W ) :
'''The weighted clustering coefficient is the average " intensity " of
triangles around a node .
Parameters
W : NxN np . ndarray
weighted undirected connection matrix
Returns
C : Nx1 np . ndarray
clustering coefficient vector''' | K = np . array ( np . sum ( np . logical_not ( W == 0 ) , axis = 1 ) , dtype = float )
ws = cuberoot ( W )
cyc3 = np . diag ( np . dot ( ws , np . dot ( ws , ws ) ) )
K [ np . where ( cyc3 == 0 ) ] = np . inf
# if no 3 - cycles exist , set C = 0
C = cyc3 / ( K * ( K - 1 ) )
return C |
def _get_pdi ( cls , df , windows ) :
"""+ DI , positive directional moving index
: param df : data
: param windows : range
: return :""" | window = cls . get_only_one_positive_int ( windows )
pdm_column = 'pdm_{}' . format ( window )
tr_column = 'atr_{}' . format ( window )
pdi_column = 'pdi_{}' . format ( window )
df [ pdi_column ] = df [ pdm_column ] / df [ tr_column ] * 100
return df [ pdi_column ] |
def computePCsPlink ( plink_path , k , out_dir , bfile , ffile ) :
"""computing the covariance matrix via plink""" | print ( "Using plink to compute principal components" )
cmd = '%s --bfile %s --pca %d ' % ( plink_path , bfile , k )
cmd += '--out %s' % ( os . path . join ( out_dir , 'plink' ) )
subprocess . call ( cmd , shell = True )
plink_fn = os . path . join ( out_dir , 'plink.eigenvec' )
M = sp . loadtxt ( plink_fn , dtype = st... |
def _upload_resumable_all ( self , upload_info , bitmap , number_of_units , unit_size ) :
"""Prepare and upload all resumable units and return upload _ key
upload _ info - - UploadInfo object
bitmap - - bitmap node of upload / check
number _ of _ units - - number of units requested
unit _ size - - size of a... | fd = upload_info . fd
upload_key = None
for unit_id in range ( number_of_units ) :
upload_status = decode_resumable_upload_bitmap ( bitmap , number_of_units )
if upload_status [ unit_id ] :
logger . debug ( "Skipping unit %d/%d - already uploaded" , unit_id + 1 , number_of_units )
continue
l... |
def confirm ( self , batch_id = None , filename = None ) :
"""Flags the batch as confirmed by updating
confirmation _ datetime on the history model for this batch .""" | if batch_id or filename :
export_history = self . history_model . objects . using ( self . using ) . filter ( Q ( batch_id = batch_id ) | Q ( filename = filename ) , sent = True , confirmation_code__isnull = True , )
else :
export_history = self . history_model . objects . using ( self . using ) . filter ( sent... |
def get_content ( request , page_id , content_id ) :
"""Get the content for a particular page""" | content = Content . objects . get ( pk = content_id )
return HttpResponse ( content . body ) |
def item_enclosure_length ( self , item ) :
"""Try to obtain the size of the enclosure if it ' s present on the FS ,
otherwise returns an hardcoded value .
Note : this method is only called if item _ enclosure _ url
has returned something .""" | try :
return str ( item . image . size )
except ( AttributeError , ValueError , os . error ) :
pass
return '100000' |
def _extended_lookup ( datastore_api , project , key_pbs , missing = None , deferred = None , eventual = False , transaction_id = None , ) :
"""Repeat lookup until all keys found ( unless stop requested ) .
Helper function for : meth : ` Client . get _ multi ` .
: type datastore _ api :
: class : ` google . c... | if missing is not None and missing != [ ] :
raise ValueError ( "missing must be None or an empty list" )
if deferred is not None and deferred != [ ] :
raise ValueError ( "deferred must be None or an empty list" )
results = [ ]
loop_num = 0
read_options = helpers . get_read_options ( eventual , transaction_id )
... |
def recv ( request_context = None , non_blocking = False ) :
"""Receives data from websocket .
: param request _ context :
: param bool non _ blocking :
: rtype : bytes | str
: raises IOError : If unable to receive a message .""" | if non_blocking :
result = uwsgi . websocket_recv_nb ( request_context )
else :
result = uwsgi . websocket_recv ( request_context )
return result |
def _distance_covariance_sqr_naive ( x , y , exponent = 1 ) :
"""Naive biased estimator for distance covariance .
Computes the unbiased estimator for distance covariance between two
matrices , using an : math : ` O ( N ^ 2 ) ` algorithm .""" | a = _distance_matrix ( x , exponent = exponent )
b = _distance_matrix ( y , exponent = exponent )
return mean_product ( a , b ) |
def relaxNGValidateFullElement ( self , doc , elem ) :
"""Validate a full subtree when
xmlRelaxNGValidatePushElement ( ) returned 0 and the content
of the node has been expanded .""" | if doc is None :
doc__o = None
else :
doc__o = doc . _o
if elem is None :
elem__o = None
else :
elem__o = elem . _o
ret = libxml2mod . xmlRelaxNGValidateFullElement ( self . _o , doc__o , elem__o )
return ret |
def export ( self , nidm_version , export_dir ) :
"""Create prov entities and activities .""" | if nidm_version [ 'major' ] < 1 or ( nidm_version [ 'major' ] == 1 and nidm_version [ 'minor' ] < 3 ) :
self . type = NIDM_DATA_SCALING
# Create " Data " entity
# FIXME : grand mean scaling ?
# FIXME : medianIntensity
self . add_attributes ( ( ( PROV [ 'type' ] , self . type ) , ( PROV [ 'type' ] , PROV [ 'Collecti... |
def remove ( self , force = False ) :
"""Remove this volume .
Args :
force ( bool ) : Force removal of volumes that were already removed
out of band by the volume driver plugin .
Raises :
: py : class : ` docker . errors . APIError `
If volume failed to remove .""" | return self . client . api . remove_volume ( self . id , force = force ) |
def _split_line ( s , parts ) :
"""Parameters
s : string
Fixed - length string to split
parts : list of ( name , length ) pairs
Used to break up string , name ' _ ' will be filtered from output .
Returns
Dict of name : contents of string at given location .""" | out = { }
start = 0
for name , length in parts :
out [ name ] = s [ start : start + length ] . strip ( )
start += length
del out [ '_' ]
return out |
def announce ( version ) :
"""Generates a new release announcement entry in the docs .""" | # Get our list of authors
stdout = check_output ( [ "git" , "describe" , "--abbrev=0" , "--tags" ] )
stdout = stdout . decode ( "utf-8" )
last_version = stdout . strip ( )
stdout = check_output ( [ "git" , "log" , "{}..HEAD" . format ( last_version ) , "--format=%aN" ] )
stdout = stdout . decode ( "utf-8" )
contributor... |
def hour ( self , value = None ) :
"""Corresponds to IDD Field ` hour `
Args :
value ( int ) : value for IDD Field ` hour `
value > = 1
value < = 24
if ` value ` is None it will not be checked against the
specification and is assumed to be a missing value
Raises :
ValueError : if ` value ` is not a ... | if value is not None :
try :
value = int ( value )
except ValueError :
raise ValueError ( 'value {} need to be of type int ' 'for field `hour`' . format ( value ) )
if value < 1 :
raise ValueError ( 'value need to be greater or equal 1 ' 'for field `hour`' )
if value > 24 :
... |
def get_users ( self ) :
"""Get number of users .""" | no_users = Token . query . filter_by ( client_id = self . client_id , is_personal = False , is_internal = False ) . count ( )
return no_users |
def dest_fpath ( self , source_fpath : str ) -> str :
"""Calculates full path for end json - api file from source file full
path .""" | relative_fpath = os . path . join ( * source_fpath . split ( os . sep ) [ 1 : ] )
relative_dirpath = os . path . dirname ( relative_fpath )
source_fname = relative_fpath . split ( os . sep ) [ - 1 ]
base_fname = source_fname . split ( '.' ) [ 0 ]
dest_fname = f'{base_fname}.json'
return os . path . join ( self . dest_d... |
def clean ( self , * args , ** kwargs ) :
"""Call self . synchronizer . clean method""" | if self . synchronizer_path != 'None' and self . config : # call synchronizer custom clean
try :
self . synchronizer . load_config ( self . config )
self . synchronizer . clean ( )
except ImproperlyConfigured as e :
raise ValidationError ( e . message ) |
def pid ( self ) :
"""Get PID object for the Release record .""" | if self . model . status == ReleaseStatus . PUBLISHED and self . record :
fetcher = current_pidstore . fetchers [ current_app . config . get ( 'GITHUB_PID_FETCHER' ) ]
return fetcher ( self . record . id , self . record ) |
def pause ( self , unique_id , configs = None ) :
"""Issues a sigstop for the specified process
: Parameter unique _ id : the name of the process""" | pids = self . get_pid ( unique_id , configs )
if pids != constants . PROCESS_NOT_RUNNING_PID :
pid_str = ' ' . join ( str ( pid ) for pid in pids )
hostname = self . processes [ unique_id ] . hostname
with get_ssh_client ( hostname , username = runtime . get_username ( ) , password = runtime . get_password ... |
def check_type_compatibility ( type_1_id , type_2_id ) :
"""When applying a type to a resource , it may be the case that the resource already
has an attribute specified in the new type , but the template which defines this
pre - existing attribute has a different unit specification to the new template .
This ... | errors = [ ]
type_1 = db . DBSession . query ( TemplateType ) . filter ( TemplateType . id == type_1_id ) . options ( joinedload_all ( 'typeattrs' ) ) . one ( )
type_2 = db . DBSession . query ( TemplateType ) . filter ( TemplateType . id == type_2_id ) . options ( joinedload_all ( 'typeattrs' ) ) . one ( )
template_1_... |
def plot ( data , headers = None , pconfig = None ) :
"""Helper HTML for a beeswarm plot .
: param data : A list of data dicts
: param headers : A list of Dicts / OrderedDicts with information
for the series , such as colour scales , min and
max values etc .
: return : HTML string""" | if headers is None :
headers = [ ]
if pconfig is None :
pconfig = { }
# Allow user to overwrite any given config for this plot
if 'id' in pconfig and pconfig [ 'id' ] and pconfig [ 'id' ] in config . custom_plot_config :
for k , v in config . custom_plot_config [ pconfig [ 'id' ] ] . items ( ) :
pco... |
def get ( self , session , fields = [ ] , ** kwargs ) :
'''taobao . items . get 搜索商品信息
根据传入的搜索条件 , 获取商品列表 ( 类似于淘宝页面上的商品搜索功能 , 但是只有搜索到的商品列表 , 不包含商品的ItemCategory列表 ) 只能获得商品的部分信息 , 商品的详细信息请通过taobao . item . get获取 如果只输入fields其他条件都不输入 , 系统会因为搜索条件不足而报错 。 不能通过设置cid = 0来查询 。''' | request = TOPRequest ( 'taobao.items.get' )
if not fields :
item = Item ( )
fields = item . fields
request [ 'fields' ] = fields
for k , v in kwargs . iteritems ( ) :
if k not in ( 'q' , 'nicks' , 'cid' , 'props' , 'product_id' , 'page_no' , 'order_by' , 'ww_status' , 'post_free' , 'location_state' , 'locat... |
def delete ( context , force , yes , analysis_id ) :
"""Delete an analysis log from the database .""" | analysis_obj = context . obj [ 'store' ] . analysis ( analysis_id )
if analysis_obj is None :
print ( click . style ( 'analysis log not found' , fg = 'red' ) )
context . abort ( )
print ( click . style ( f"{analysis_obj.family}: {analysis_obj.status}" ) )
if analysis_obj . is_temp :
if yes or click . confir... |
def decline ( self , lemma , flatten = False , collatinus_dict = False ) :
"""Decline a lemma
. . warning : : POS are incomplete as we do not detect the type outside of verbs , participle and adjective .
: raise UnknownLemma : When the lemma is unknown to our data
: param lemma : Lemma ( Canonical form ) to d... | if lemma not in self . __lemmas__ :
raise UnknownLemma ( "%s is unknown" % lemma )
# Get data information
lemma_entry = self . __lemmas__ [ lemma ]
model = self . __models__ [ lemma_entry [ "model" ] ]
# Get the roots
roots = self . __getRoots ( lemma , model = model )
# Get the known forms in order
keys = sorted (... |
def get_direct_band_gap_dict ( self ) :
"""Returns a dictionary of information about the direct
band gap
Returns :
a dictionary of the band gaps indexed by spin
along with their band indices and k - point index""" | if self . is_metal ( ) :
raise ValueError ( "get_direct_band_gap_dict should" "only be used with non-metals" )
direct_gap_dict = { }
for spin , v in self . bands . items ( ) :
above = v [ np . all ( v > self . efermi , axis = 1 ) ]
min_above = np . min ( above , axis = 0 )
below = v [ np . all ( v < sel... |
def _set_isns_vrf_instance ( self , v , load = False ) :
"""Setter method for isns _ vrf _ instance , mapped from YANG variable / isns / isns _ vrf / isns _ vrf _ instance ( isns - vrf - type )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ isns _ vrf _ instance is con... | parent = getattr ( self , "_parent" , None )
if parent is not None and load is False :
raise AttributeError ( "Cannot set keys directly when" + " within an instantiated list" )
if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = Restricted... |
def load_phonopy ( filename , structure , dim , symprec = 0.01 , primitive_matrix = None , factor = VaspToTHz , symmetrise = True , born = None , write_fc = False ) :
"""Load phonopy output and return an ` ` phonopy . Phonopy ` ` object .
Args :
filename ( str ) : Path to phonopy output . Can be any of ` ` FORC... | unitcell = get_phonopy_structure ( structure )
num_atom = unitcell . get_number_of_atoms ( )
num_satom = determinant ( dim ) * num_atom
phonon = Phonopy ( unitcell , dim , primitive_matrix = primitive_matrix , factor = factor , symprec = symprec )
if 'FORCE_CONSTANTS' == filename or '.hdf5' in filename : # if force con... |
def getObjectByPid ( self , pid ) :
"""Args :
pid : str
Returns :
str : URIRef of the entry identified by ` ` pid ` ` .""" | self . _check_initialized ( )
opid = rdflib . term . Literal ( pid )
res = [ o for o in self . subjects ( predicate = DCTERMS . identifier , object = opid ) ]
return res [ 0 ] |
async def pack_message ( wallet_handle : int , message : str , recipient_verkeys : list , sender_verkey : Optional [ str ] ) -> bytes :
"""Packs a message by encrypting the message and serializes it in a JWE - like format ( Experimental )
Note to use DID keys with this function you can call did . key _ for _ did ... | logger = logging . getLogger ( __name__ )
logger . debug ( "pack_message: >>> wallet_handle: %r, message: %r, recipient_verkeys: %r, sender_verkey: %r" , wallet_handle , message , recipient_verkeys , sender_verkey )
def transform_cb ( arr_ptr : POINTER ( c_uint8 ) , arr_len : c_uint32 ) :
return bytes ( arr_ptr [ :... |
def tasks_all_replaced_predicate ( service_name , old_task_ids , task_predicate = None ) :
"""Returns whether ALL of old _ task _ ids have been replaced with new tasks
: param service _ name : the service name
: type service _ name : str
: param old _ task _ ids : list of original task ids as returned by get ... | try :
task_ids = get_service_task_ids ( service_name , task_predicate )
except DCOSHTTPException :
print ( 'failed to get task ids for service {}' . format ( service_name ) )
task_ids = [ ]
print ( 'waiting for all task ids in "{}" to change:\n- old tasks: {}\n- current tasks: {}' . format ( service_name , ... |
def run ( self ) -> None :
"""Execute function calls on a separate thread .""" | while self . _running :
try :
future , function = self . _tx . get ( timeout = 0.1 )
except Empty :
continue
try :
LOG . debug ( "executing %s" , function )
result = function ( )
LOG . debug ( "returning %s" , result )
self . _loop . call_soon_threadsafe ( fut... |
def from_stream ( cls , stream ) :
"""Return a | Tiff | instance containing the properties of the TIFF image
in * stream * .""" | parser = _TiffParser . parse ( stream )
px_width = parser . px_width
px_height = parser . px_height
horz_dpi = parser . horz_dpi
vert_dpi = parser . vert_dpi
return cls ( px_width , px_height , horz_dpi , vert_dpi ) |
def dirsWavFeatureExtraction ( dirNames , mt_win , mt_step , st_win , st_step , compute_beat = False ) :
'''Same as dirWavFeatureExtraction , but instead of a single dir it
takes a list of paths as input and returns a list of feature matrices .
EXAMPLE :
[ features , classNames ] =
a . dirsWavFeatureExtract... | # feature extraction for each class :
features = [ ]
classNames = [ ]
fileNames = [ ]
for i , d in enumerate ( dirNames ) :
[ f , fn , feature_names ] = dirWavFeatureExtraction ( d , mt_win , mt_step , st_win , st_step , compute_beat = compute_beat )
if f . shape [ 0 ] > 0 : # if at least one audio file has bee... |
def fai_from_bam ( ref_file , bam_file , out_file , data ) :
"""Create a fai index with only contigs in the input BAM file .""" | contigs = set ( [ x . contig for x in idxstats ( bam_file , data ) ] )
if not utils . file_uptodate ( out_file , bam_file ) :
with open ( ref . fasta_idx ( ref_file , data [ "config" ] ) ) as in_handle :
with file_transaction ( data , out_file ) as tx_out_file :
with open ( tx_out_file , "w" ) a... |
def install_programmer ( programmer_id , programmer_options , replace_existing = False ) :
"""install programmer in programmers . txt .
: param programmer _ id : string identifier
: param programmer _ options : dict like
: param replace _ existing : bool
: rtype : None""" | doaction = 0
if programmer_id in programmers ( ) . keys ( ) :
log . debug ( 'programmer already exists: %s' , programmer_id )
if replace_existing :
log . debug ( 'remove programmer: %s' , programmer_id )
remove_programmer ( programmer_id )
doaction = 1
else :
doaction = 1
if doaction... |
def python_2_nonzero_compatible ( klass ) :
"""Adds a ` _ _ nonzero _ _ ( ) ` method to classes that define a ` _ _ bool _ _ ( ) ` method ,
so boolean conversion works in Python 2 . Has no effect in Python 3.
: param klass : The class to modify . Must define ` _ _ bool _ _ ( ) ` .
: return : The possibly patc... | if six . PY2 :
if '__bool__' not in klass . __dict__ :
raise ValueError ( '@python_2_nonzero_compatible cannot be applied to {0} because ' 'it doesn\'t define __bool__().' . format ( klass . __name__ ) )
klass . __nonzero__ = klass . __bool__
return klass |
def _GetDirectory ( self ) :
"""Retrieves a directory .
Returns :
APFSDirectory : directory or None if not available .""" | if self . _fsapfs_file_entry . number_of_sub_file_entries <= 0 :
return None
return APFSDirectory ( self . _file_system , self . path_spec ) |
def STORE_SLICE_3 ( self , instr ) :
'obj [ lower : upper ] = expr' | upper = self . ast_stack . pop ( )
lower = self . ast_stack . pop ( )
value = self . ast_stack . pop ( )
expr = self . ast_stack . pop ( )
kw = dict ( lineno = instr . lineno , col_offset = 0 )
slice = _ast . Slice ( lower = lower , step = None , upper = upper , ** kw )
subscr = _ast . Subscript ( value = value , slice... |
def watch_variable ( self , tid , address , size , action = None ) :
"""Sets a hardware breakpoint at the given thread , address and size .
@ see : L { dont _ watch _ variable }
@ type tid : int
@ param tid : Thread global ID .
@ type address : int
@ param address : Memory address of variable to watch .
... | bp = self . __set_variable_watch ( tid , address , size , action )
if not bp . is_enabled ( ) :
self . enable_hardware_breakpoint ( tid , address ) |
def run_worker ( worker_class , * args , ** kwargs ) :
'''Bridge function to run a worker under : mod : ` multiprocessing ` .
The : mod : ` multiprocessing ` module cannot
: meth : ` ~ multiprocessing . Pool . apply _ async ` to a class constructor ,
even if the ` ` _ _ init _ _ ` ` calls ` ` . run ( ) ` ` , ... | try :
worker = worker_class ( * args , ** kwargs )
except Exception :
logger . critical ( 'failed to create worker {0!r}' . format ( worker_class ) , exc_info = True )
raise
# A note on style here :
# If this runs ForkWorker , ForkWorker will os . fork ( ) LoopWorker
# ( or SingleWorker ) children , and the... |
def find_declaration ( declarations , decl_type = None , name = None , parent = None , recursive = True , fullname = None ) :
"""Returns single declaration that match criteria , defined by developer .
If more the one declaration was found None will be returned .
For more information about arguments see : class ... | decl = find_all_declarations ( declarations , decl_type = decl_type , name = name , parent = parent , recursive = recursive , fullname = fullname )
if len ( decl ) == 1 :
return decl [ 0 ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.