signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def output_sizes ( self ) :
"""Returns a tuple of all output sizes of all the layers .""" | return tuple ( [ l ( ) if callable ( l ) else l for l in self . _output_sizes ] ) |
def send ( self , data , opcode = ABNF . OPCODE_TEXT ) :
"""send message .
data : message to send . If you set opcode to OPCODE _ TEXT ,
data must be utf - 8 string or unicode .
opcode : operation code of data . default is OPCODE _ TEXT .""" | if not self . sock or self . sock . send ( data , opcode ) == 0 :
raise WebSocketConnectionClosedException ( "Connection is already closed." ) |
def _validate_read_indexer ( self , key , indexer , axis , raise_missing = False ) :
"""Check that indexer can be used to return a result ( e . g . at least one
element was found , unless the list of keys was actually empty ) .
Parameters
key : list - like
Target labels ( only used to show correct error mes... | ax = self . obj . _get_axis ( axis )
if len ( key ) == 0 :
return
# Count missing values :
missing = ( indexer < 0 ) . sum ( )
if missing :
if missing == len ( indexer ) :
raise KeyError ( "None of [{key}] are in the [{axis}]" . format ( key = key , axis = self . obj . _get_axis_name ( axis ) ) )
# ... |
def find_primitive ( cell , symprec = 1e-5 , angle_tolerance = - 1.0 ) :
"""Primitive cell is searched in the input cell .
The primitive cell is returned by a tuple of ( lattice , positions , numbers ) .
If it fails , None is returned .""" | _set_no_error ( )
lattice , positions , numbers , _ = _expand_cell ( cell )
if lattice is None :
return None
num_atom_prim = spg . primitive ( lattice , positions , numbers , symprec , angle_tolerance )
_set_error_message ( )
if num_atom_prim > 0 :
return ( np . array ( lattice . T , dtype = 'double' , order = ... |
def is_frameshift_len ( mut_df ) :
"""Simply returns a series indicating whether each corresponding mutation
is a frameshift .
This is based on the length of the indel . Thus may be fooled by frameshifts
at exon - intron boundaries or other odd cases .
Parameters
mut _ df : pd . DataFrame
mutation input... | # calculate length , 0 - based coordinates
# indel _ len = mut _ df [ ' End _ Position ' ] - mut _ df [ ' Start _ Position ' ]
if 'indel len' in mut_df . columns :
indel_len = mut_df [ 'indel len' ]
else :
indel_len = compute_indel_length ( mut_df )
# only non multiples of 3 are frameshifts
is_fs = ( indel_len ... |
def rest_call ( self , url , method , data = None , sensitive = False , timeout = None , content_json = True , retry = None , max_retry = None , retry_sleep = None ) :
"""Generic REST call worker function
* * Parameters : * *
- * * url : * * URL for the REST call
- * * method : * * METHOD for the REST call
... | # pull retry related items from Constructor if not specified .
if timeout is None :
timeout = self . rest_call_timeout
if retry is not None : # Someone using deprecated retry code . Notify .
sys . stderr . write ( "WARNING: 'retry' option of rest_call() has been deprecated. " "Please use 'API.modify_rest_retry(... |
def _ha_return_method ( func ) :
'''Method decorator for ' return type ' methods''' | def wrapped ( self , * args , ** kw ) :
self . _reset_retries ( )
while ( True ) : # switch between all namenodes
try :
return func ( self , * args , ** kw )
except RequestError as e :
self . __handle_request_error ( e )
except socket . error as e :
se... |
def _realize ( self , master , element ) :
"""Builds a widget from xml element using master as parent .""" | data = data_xmlnode_to_dict ( element , self . translator )
cname = data [ 'class' ]
uniqueid = data [ 'id' ]
if cname not in CLASS_MAP :
self . _import_class ( cname )
if cname in CLASS_MAP :
self . _pre_process_data ( data )
parent = CLASS_MAP [ cname ] . builder . factory ( self , data )
widget = par... |
def load_signing_key ( signing_key , crypto_backend = default_backend ( ) ) :
"""Optional : crypto backend object from the " cryptography " python library""" | if isinstance ( signing_key , EllipticCurvePrivateKey ) :
return signing_key
elif isinstance ( signing_key , ( str , unicode ) ) :
invalid_strings = [ b'-----BEGIN PUBLIC KEY-----' ]
invalid_string_matches = [ string_value in signing_key for string_value in invalid_strings ]
if any ( invalid_string_matc... |
def merge_parts ( self , version_id = None , ** kwargs ) :
"""Merge parts into object version .""" | self . file . update_checksum ( ** kwargs )
with db . session . begin_nested ( ) :
obj = ObjectVersion . create ( self . bucket , self . key , _file_id = self . file_id , version_id = version_id )
self . delete ( )
return obj |
def get_file_systems ( self ) :
"""Creates a map of mounted filesystems on the machine .
iostat ( 1 ) : Each sector has size of 512 bytes .
Returns :
st _ dev - > FileSystem ( device , mount _ point )""" | result = { }
if os . access ( '/proc/mounts' , os . R_OK ) :
file = open ( '/proc/mounts' )
for line in file :
try :
mount = line . split ( )
device = mount [ 0 ]
mount_point = mount [ 1 ]
fs_type = mount [ 2 ]
except ( IndexError , ValueError ) :
... |
def slice_upload ( cookie , data ) :
'''分片上传一个大文件
分片上传完成后 , 会返回这个分片的MD5 , 用于最终的文件合并 .
如果上传失败 , 需要重新上传 .
不需要指定上传路径 , 上传后的数据会被存储在服务器的临时目录里 .
data - 这个文件分片的数据 .''' | url = '' . join ( [ const . PCS_URL_C , 'file?method=upload&type=tmpfile&app_id=250528' , '&' , cookie . sub_output ( 'BDUSS' ) , ] )
fields = [ ]
files = [ ( 'file' , ' ' , data ) ]
headers = { 'Accept' : const . ACCEPT_HTML , 'Origin' : const . PAN_URL }
req = net . post_multipart ( url , headers , fields , files )
i... |
def iter_labels ( self , number = - 1 , etag = None ) :
"""Iterate over the labels for every issue associated with this
milestone .
. . versionchanged : : 0.9
Add etag parameter .
: param int number : ( optional ) , number of labels to return . Default : - 1
returns all available labels .
: param str et... | url = self . _build_url ( 'labels' , base_url = self . _api )
return self . _iter ( int ( number ) , url , Label , etag = etag ) |
def network_running ( name , bridge , forward , vport = None , tag = None , autostart = True , connection = None , username = None , password = None ) :
'''Defines and starts a new network with specified arguments .
: param connection : libvirt connection URI , overriding defaults
. . versionadded : : 2019.2.0 ... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
try :
info = __salt__ [ 'virt.network_info' ] ( name , connection = connection , username = username , password = password )
if info :
if info [ 'active' ] :
ret [ 'comment' ] = 'Network {0} exists and is running' .... |
def truncate ( num , precision = 0 ) :
"""Deprecated , use decimal _ to _ precision instead""" | if precision > 0 :
decimal_precision = math . pow ( 10 , precision )
return math . trunc ( num * decimal_precision ) / decimal_precision
return int ( Exchange . truncate_to_string ( num , precision ) ) |
def sset_loop ( args ) :
'''Loop over all sample sets in a workspace , performing a func''' | # Ensure that the requested action is a valid fiss _ cmd
fiss_func = __cmd_to_func ( args . action )
if not fiss_func :
eprint ( "invalid FISS cmd '" + args . action + "'" )
return 1
# First get the sample set names
r = fapi . get_entities ( args . project , args . workspace , "sample_set" )
fapi . _check_respo... |
def match_abstract_str ( cls ) :
"""For a given abstract or match rule meta - class returns a nice string
representation for the body .""" | def r ( s ) :
if s . root :
if s in visited or s . rule_name in ALL_TYPE_NAMES or ( hasattr ( s , '_tx_class' ) and s . _tx_class . _tx_type is not RULE_MATCH ) :
return s . rule_name
visited . add ( s )
if isinstance ( s , Match ) :
result = text ( s )
elif isinstance ( s , ... |
def _send_broker_unaware_request ( self , payloads , encoder_fn , decoder_fn ) :
"""Attempt to send a broker - agnostic request to one of the available
brokers . Keep trying until you succeed .""" | hosts = set ( )
for broker in self . brokers . values ( ) :
host , port , afi = get_ip_port_afi ( broker . host )
hosts . add ( ( host , broker . port , afi ) )
hosts . update ( self . hosts )
hosts = list ( hosts )
random . shuffle ( hosts )
for ( host , port , afi ) in hosts :
try :
conn = self . ... |
def register_sub_command ( self , sub_command , additional_ids = [ ] ) :
"""Register a command as a subcommand .
It will have it ' s CommandDesc . command string used as id . Additional ids can be provided .
Args :
sub _ command ( CommandBase ) : Subcommand to register .
additional _ ids ( List [ str ] ) : ... | self . __register_sub_command ( sub_command , sub_command . command_desc ( ) . command )
self . __additional_ids . update ( additional_ids )
for id in additional_ids :
self . __register_sub_command ( sub_command , id ) |
def close_alert ( name = None , api_key = None , reason = "Conditions are met." , action_type = "Close" ) :
'''Close an alert in OpsGenie . It ' s a wrapper function for create _ alert .
Example usage with Salt ' s requisites and other global state arguments
could be found above .
Required Parameters :
name... | if name is None :
raise salt . exceptions . SaltInvocationError ( 'Name cannot be None.' )
return create_alert ( name , api_key , reason , action_type ) |
def unregister_language ( self , name ) :
"""Unregisters language with given name from the : obj : ` LanguagesModel . languages ` class property .
: param name : Language to unregister .
: type name : unicode
: return : Method success .
: rtype : bool""" | if not self . get_language ( name ) :
raise foundations . exceptions . ProgrammingError ( "{0} | '{1}' language isn't registered!" . format ( self . __class__ . __name__ , name ) )
LOGGER . debug ( "> Unregistering '{0}' language." . format ( name ) )
for i , language in enumerate ( self . __languages ) :
if no... |
def evolvets ( rng , pop , params , simplification_interval , recorder = None , suppress_table_indexing = False , record_gvalue_matrix = False , stopping_criterion = None , track_mutation_counts = False , remove_extinct_variants = True ) :
"""Evolve a population with tree sequence recording
: param rng : random n... | import warnings
# Currently , we do not support simulating neutral mutations
# during tree sequence simulations , so we make sure that there
# are no neutral regions / rates :
if len ( params . nregions ) != 0 :
raise ValueError ( "Simulation of neutral mutations on tree sequences not supported (yet)." )
# Test par... |
def setlist ( self , key , values ) :
"""Sets < key > ' s list of values to < values > . Existing items with key < key >
are first replaced with new values from < values > . Any remaining old
items that haven ' t been replaced with new values are deleted , and any
new values from < values > that don ' t have ... | if not values and key in self :
self . pop ( key )
else :
it = zip_longest ( list ( self . _map . get ( key , [ ] ) ) , values , fillvalue = _absent )
for node , value in it :
if node is not _absent and value is not _absent :
node . value = value
elif node is _absent :
... |
def search_complete ( self , completed ) :
"""Current search thread has finished""" | self . result_browser . set_sorting ( ON )
self . find_options . ok_button . setEnabled ( True )
self . find_options . stop_button . setEnabled ( False )
self . status_bar . hide ( )
self . result_browser . expandAll ( )
if self . search_thread is None :
return
self . sig_finished . emit ( )
found = self . search_t... |
def setLocked ( self , state , force = False ) :
"""Sets the locked state for this panel to the inputed state .
: param state | < bool >""" | if not force and state == self . _locked :
return
self . _locked = state
tabbar = self . tabBar ( )
tabbar . setLocked ( state )
if self . hideTabsWhenLocked ( ) :
tabbar . setVisible ( self . count ( ) > 1 or not state )
else :
tabbar . setVisible ( True )
if tabbar . isVisible ( ) :
self . setContents... |
def fetch_releases ( self , package_name ) :
"""Fetch package and index _ url for a package _ name .""" | package_name = self . source . normalize_package_name ( package_name )
releases = self . source . get_package_versions ( package_name )
releases_with_index_url = [ ( item , self . index_url ) for item in releases ]
return package_name , releases_with_index_url |
def disallow ( self , foreign , permission = "active" , account = None , threshold = None , ** kwargs ) :
"""Remove additional access to an account by some other public
key or account .
: param str foreign : The foreign account that will obtain access
: param str permission : ( optional ) The actual permissio... | if not account :
if "default_account" in self . config :
account = self . config [ "default_account" ]
if not account :
raise ValueError ( "You need to provide an account" )
if permission not in [ "owner" , "active" ] :
raise ValueError ( "Permission needs to be either 'owner', or 'active" )
account... |
def uniqueID ( size = 6 , chars = string . ascii_uppercase + string . digits ) :
"""A quick and dirty way to get a unique string""" | return '' . join ( random . choice ( chars ) for x in xrange ( size ) ) |
def youtube_id ( self ) :
"""Extract and return Youtube video id""" | if not self . video_embed :
return ''
m = re . search ( r'/embed/([A-Za-z0-9\-=_]*)' , self . video_embed )
if m :
return m . group ( 1 )
return '' |
def _get_replication_metrics ( self , key , db ) :
"""Use either REPLICATION _ METRICS _ 10 , REPLICATION _ METRICS _ 9_1 , or
REPLICATION _ METRICS _ 9_1 + REPLICATION _ METRICS _ 9_2 , depending on the
postgres version .
Uses a dictionnary to save the result for each instance""" | metrics = self . replication_metrics . get ( key )
if self . _is_10_or_above ( key , db ) and metrics is None :
self . replication_metrics [ key ] = dict ( self . REPLICATION_METRICS_10 )
metrics = self . replication_metrics . get ( key )
elif self . _is_9_1_or_above ( key , db ) and metrics is None :
self ... |
def query_random ( num = 6 , kind = '1' ) :
'''Query wikis randomly .''' | return TabWiki . select ( ) . where ( TabWiki . kind == kind ) . order_by ( peewee . fn . Random ( ) ) . limit ( num ) |
def get_ip ( request ) :
"""Retrieves the remote IP address from the request data . If the user is
behind a proxy , they may have a comma - separated list of IP addresses , so
we need to account for that . In such a case , only the first IP in the
list will be retrieved . Also , some hosts that use a proxy wi... | # if neither header contain a value , just use local loopback
ip_address = request . META . get ( 'HTTP_X_FORWARDED_FOR' , request . META . get ( 'REMOTE_ADDR' , '127.0.0.1' ) )
if ip_address : # make sure we have one and only one IP
try :
ip_address = IP_RE . match ( ip_address )
if ip_address :
... |
def update_field_forward_refs ( field : 'Field' , globalns : Any , localns : Any ) -> None :
"""Try to update ForwardRefs on fields based on this Field , globalns and localns .""" | if type ( field . type_ ) == ForwardRef :
field . type_ = field . type_ . _evaluate ( globalns , localns or None )
# type : ignore
field . prepare ( )
if field . sub_fields :
for sub_f in field . sub_fields :
update_field_forward_refs ( sub_f , globalns = globalns , localns = localns ) |
def _logins ( users , user_attrs = None ) :
'''FIXME : DOCS . . .''' | # FIXME : check for support attrs
# Supported attrs :
# login # DEFAULT , no auth required
# email
# bio
# company
# created _ at
# hireable
# location
# updated _ at
# url
# ' login ' will be the dict index key ; remove it from user _ attr columns
if 'login' in user_attrs :
if user_attrs . index ( 'login' ) >= 0 :... |
def _apply_flat ( cls , f , acts ) :
"""Utility for applying f to inner dimension of acts .
Flattens acts into a 2D tensor , applies f , then unflattens so that all
dimesnions except innermost are unchanged .""" | orig_shape = acts . shape
acts_flat = acts . reshape ( [ - 1 , acts . shape [ - 1 ] ] )
new_flat = f ( acts_flat )
if not isinstance ( new_flat , np . ndarray ) :
return new_flat
shape = list ( orig_shape [ : - 1 ] ) + [ - 1 ]
return new_flat . reshape ( shape ) |
def end_request ( req , collector_addr = 'tcp://127.0.0.2:2345' , prefix = 'my_app' ) :
"""registers the end of a request
registers the end of a request , computes elapsed time , sends it to the collector
: param req : request , can be mostly any hash - able object
: param collector _ addr : collector address... | req_end = time ( )
hreq = hash ( req )
if hreq in requests :
req_time = req_end - requests [ hreq ]
req_time *= 1000
del requests [ hreq ]
collector = get_context ( ) . socket ( zmq . PUSH )
collector . connect ( collector_addr )
collector . send_multipart ( [ prefix , str ( req_time ) ] )
c... |
def setup_icons ( self , ) :
"""Set all icons on buttons
: returns : None
: rtype : None
: raises : None""" | plus_icon = get_icon ( 'glyphicons_433_plus_bright.png' , asicon = True )
self . addnew_tb . setIcon ( plus_icon ) |
def remove_port ( uri ) :
"""Remove the port number from a URI
: param uri : full URI that Twilio requested on your server
: returns : full URI without a port number
: rtype : str""" | new_netloc = uri . netloc . split ( ':' ) [ 0 ]
new_uri = uri . _replace ( netloc = new_netloc )
return new_uri . geturl ( ) |
def install_update_deps ( self ) :
"""todo : Docstring for install _ update _ deps
: return :
: rtype :""" | logger . debug ( "" )
self . _ctx . installed ( self . name )
# are there any dependencies ?
depfile = os . path . join ( self . repo_dir , '_upkg' , 'depends' )
logger . debug ( "depfile? %s" , depfile )
if os . path . exists ( depfile ) :
logger . debug ( "Found depends file at %s" , depfile )
deps = open ( d... |
def write ( self , file_name ) :
"""Writes the chapter object to an xhtml file .
Args :
file _ name ( str ) : The full name of the xhtml file to save to .""" | try :
assert file_name [ - 6 : ] == '.xhtml'
except ( AssertionError , IndexError ) :
raise ValueError ( 'filename must end with .xhtml' )
with open ( file_name , 'wb' ) as f :
f . write ( self . content . encode ( 'utf-8' ) ) |
def do ( self , params ) :
"""Perform the underlying experiment and summarise its results .
Our results are the summary statistics extracted from the results of
the instances of the underlying experiment that we performed .
We drop from the calculations any experiments whose completion status
was False , in... | # perform the underlying experiment
rc = self . experiment ( ) . run ( )
# extract the result dicts as a list
results = rc [ Experiment . RESULTS ]
if not isinstance ( results , list ) : # force to list
results = [ rc ]
# extract only the successful runs
sresults = [ res for res in results if res [ Experiment . MET... |
def coerce ( value ) :
"""Turns value into a string""" | if isinstance ( value , StringCell ) :
return value
elif isinstance ( value , ( str , unicode ) ) :
return StringCell ( value )
else :
raise CoercionFailure ( "Cannot coerce %s to StringCell" % ( value ) ) |
def find_files ( ) :
"""Search for the directory containing jsonld and csv files . chdir and then quit .
: return none :""" | _dir = os . getcwd ( )
_files = os . listdir ( )
# Look for a jsonld file
for _file in _files :
if _file . endswith ( ".jsonld" ) :
return os . getcwd ( )
# No jsonld file found , try to chdir into " bag " ( LiPD v1.3)
if "bag" in _files :
os . chdir ( "bag" )
_dir = find_files ( )
# No " bag " dir ... |
def reftrack_status_data ( rt , role ) :
"""Return the data for the status
: param rt : the : class : ` jukeboxcore . reftrack . Reftrack ` holds the data
: type rt : : class : ` jukeboxcore . reftrack . Reftrack `
: param role : item data role
: type role : QtCore . Qt . ItemDataRole
: returns : data for... | status = rt . status ( )
if role == QtCore . Qt . DisplayRole or role == QtCore . Qt . EditRole :
if status :
return status
else :
return "Not in scene!" |
def sharpe ( self ) :
"""夏普比率""" | return round ( float ( self . calc_sharpe ( self . annualize_return , self . volatility , 0.05 ) ) , 2 ) |
def GetAttributeNs ( self , localName , namespaceURI ) :
"""Provides the value of the specified attribute""" | ret = libxml2mod . xmlTextReaderGetAttributeNs ( self . _o , localName , namespaceURI )
return ret |
def _parse_current_network_settings ( ) :
'''Parse / etc / default / networking and return current configuration''' | opts = salt . utils . odict . OrderedDict ( )
opts [ 'networking' ] = ''
if os . path . isfile ( _DEB_NETWORKING_FILE ) :
with salt . utils . files . fopen ( _DEB_NETWORKING_FILE ) as contents :
for line in contents :
salt . utils . stringutils . to_unicode ( line )
if line . startsw... |
def select_mask ( cls , dataset , selection ) :
"""Given a Dataset object and a dictionary with dimension keys and
selection keys ( i . e tuple ranges , slices , sets , lists or literals )
return a boolean mask over the rows in the Dataset object that
have been selected .""" | select_mask = None
for dim , k in selection . items ( ) :
if isinstance ( k , tuple ) :
k = slice ( * k )
masks = [ ]
alias = dataset . get_dimension ( dim ) . name
series = dataset . data [ alias ]
if isinstance ( k , slice ) :
if k . start is not None : # Workaround for dask issue ... |
def get ( self , pos ) :
"""Get the closest dataset .""" | latitude = int ( round ( pos [ 'latitude' ] ) )
search_set = self . bins [ latitude ]
i = 1
if latitude - i >= - 90 :
search_set += self . bins [ latitude - i ]
if latitude + i <= 90 :
search_set += self . bins [ latitude + i ]
while len ( search_set ) == 0 and i <= 200 :
if latitude - i >= - 90 :
s... |
def set_double_stack ( socket_obj , double_stack = True ) : # type : ( socket . socket , bool ) - > None
"""Sets up the IPv6 double stack according to the operating system
: param socket _ obj : A socket object
: param double _ stack : If True , use the double stack , else only support IPv6
: raise AttributeE... | try : # Use existing value
opt_ipv6_only = socket . IPV6_V6ONLY
except AttributeError : # Use " known " value
if os . name == "nt" : # Windows : see ws2ipdef . h
opt_ipv6_only = 27
elif platform . system ( ) == "Linux" : # Linux : see linux / in6 . h ( in recent kernels )
opt_ipv6_only = 26
... |
def typeof_rave_data ( value ) :
"""Function to duck - type values , not relying on standard Python functions because , for example ,
a string of ' 1 ' should be typed as an integer and not as a string or float
since we ' re trying to replace like with like when scrambling .""" | # Test if value is a date
for format in [ '%d %b %Y' , '%b %Y' , '%Y' , '%d %m %Y' , '%m %Y' , '%d/%b/%Y' , '%b/%Y' , '%d/%m/%Y' , '%m/%Y' ] :
try :
datetime . datetime . strptime ( value , format )
if len ( value ) == 4 and ( int ( value ) < 1900 or int ( value ) > 2030 ) :
break
... |
def slicenet_middle ( inputs_encoded , targets , target_space_emb , mask , hparams ) :
"""Middle part of slicenet , connecting encoder and decoder .""" | def norm_fn ( x , name ) :
with tf . variable_scope ( name , default_name = "norm" ) :
return common_layers . apply_norm ( x , hparams . norm_type , hparams . hidden_size , hparams . norm_epsilon )
# Flatten targets and embed target _ space _ id .
targets_flat = tf . expand_dims ( common_layers . flatten4d3... |
def parse ( self , body ) :
"""Parse JSON request , storing content in object attributes .
Args :
body : str . HTTP request body .
Returns :
self""" | if isinstance ( body , six . string_types ) :
body = json . loads ( body )
# version
version = body [ 'version' ]
self . version = version
# session
session = body [ 'session' ]
self . session . new = session [ 'new' ]
self . session . session_id = session [ 'sessionId' ]
application_id = session [ 'application' ] ... |
def loads ( self , value ) :
'''Returns deserialized ` value ` .''' | for serializer in reversed ( self ) :
value = serializer . loads ( value )
return value |
def itemat ( iterable , index ) :
"""Try to get the item at index position in iterable after iterate on
iterable items .
: param iterable : object which provides the method _ _ getitem _ _ or _ _ iter _ _ .
: param int index : item position to get .""" | result = None
handleindex = True
if isinstance ( iterable , dict ) :
handleindex = False
else :
try :
result = iterable [ index ]
except TypeError :
handleindex = False
if not handleindex :
iterator = iter ( iterable )
if index < 0 : # ensure index is positive
index += len ( ... |
def deleteoutputfile ( project , filename , credentials = None ) :
"""Delete an output file""" | user , oauth_access_token = parsecredentials ( credentials )
# pylint : disable = unused - variable
if filename :
filename = filename . replace ( ".." , "" )
# Simple security
if not filename or len ( filename ) == 0 : # Deleting all output files and resetting
Project . reset ( project , user )
msg = "Delet... |
def get_item2 ( self , tablename , key , attributes = None , alias = None , consistent = False , return_capacity = None ) :
"""Fetch a single item from a table
Parameters
tablename : str
Name of the table to fetch from
key : dict
Primary key dict specifying the hash key and , if applicable , the
range k... | kwargs = { 'TableName' : tablename , 'Key' : self . dynamizer . encode_keys ( key ) , 'ConsistentRead' : consistent , 'ReturnConsumedCapacity' : self . _default_capacity ( return_capacity ) , }
if attributes is not None :
if not isinstance ( attributes , six . string_types ) :
attributes = ', ' . join ( att... |
def device_radio_str ( self , resp , indent = " " ) :
"""Convenience to string method .""" | signal = resp . signal
tx = resp . tx
rx = resp . rx
s = "Wifi Signal Strength (mW): {}\n" . format ( signal )
s += indent + "Wifi TX (bytes): {}\n" . format ( tx )
s += indent + "Wifi RX (bytes): {}\n" . format ( rx )
return s |
def _get_nodes ( network_id , template_id = None ) :
"""Get all the nodes in a network""" | extras = { 'types' : [ ] , 'attributes' : [ ] }
node_qry = db . DBSession . query ( Node ) . filter ( Node . network_id == network_id , Node . status == 'A' ) . options ( noload ( 'network' ) )
if template_id is not None :
node_qry = node_qry . filter ( ResourceType . node_id == Node . id , TemplateType . id == Res... |
def set_variables ( self , data ) :
"""Set variables for the network .
Parameters
data : dict
dict for variable in the form of example as shown .
Examples
> > > from pgmpy . readwrite . XMLBeliefNetwork import XBNWriter
> > > writer = XBNWriter ( )
> > > writer . set _ variables ( { ' a ' : { ' TYPE '... | variables = etree . SubElement ( self . bnmodel , "VARIABLES" )
for var in sorted ( data ) :
variable = etree . SubElement ( variables , 'VAR' , attrib = { 'NAME' : var , 'TYPE' : data [ var ] [ 'TYPE' ] , 'XPOS' : data [ var ] [ 'XPOS' ] , 'YPOS' : data [ var ] [ 'YPOS' ] } )
etree . SubElement ( variable , 'D... |
def get_module ( mod_name ) :
"""Load and return a module based on C { mod _ name } .""" | if mod_name is '' :
raise ImportError ( 'Unable to import empty module' )
mod = __import__ ( mod_name )
components = mod_name . split ( '.' )
for comp in components [ 1 : ] :
mod = getattr ( mod , comp )
return mod |
def add_cylinder ( self , name , position , sizes , mass , precision = [ 10 , 10 ] ) :
"""Add Cylinder""" | self . _create_pure_shape ( 2 , 239 , sizes , mass , precision )
self . set_object_position ( "Cylinder" , position )
self . change_object_name ( "Cylinder" , name ) |
def update ( self , frame_no ) :
"""Process the animation effect for the specified frame number .
: param frame _ no : The index of the frame being generated .""" | if ( frame_no >= self . _start_frame and ( self . _stop_frame == 0 or frame_no < self . _stop_frame ) ) :
self . _update ( frame_no ) |
def add_milestone ( self , milestone , codelistoid = "MILESTONES" ) :
"""Add a milestone
: param codelistoid : specify the CodeListOID ( defaults to MILESTONES )
: param str milestone : Milestone to add""" | if milestone not in self . milestones . get ( codelistoid , [ ] ) :
self . _milestones . setdefault ( codelistoid , [ ] ) . append ( milestone ) |
def find_all_matching_parsers ( self , strict : bool , desired_type : Type [ Any ] = JOKER , required_ext : str = JOKER ) -> Tuple [ Tuple [ List [ Parser ] , List [ Parser ] , List [ Parser ] ] , List [ Parser ] , List [ Parser ] , List [ Parser ] ] :
"""Implementation of the parent method by lookin into the regis... | # if desired _ type is JOKER and required _ ext is JOKER :
# # Easy : return everything ( GENERIC first , SPECIFIC then ) in order ( make a copy first : ) )
# matching _ parsers _ generic = self . _ generic _ parsers . copy ( )
# matching _ parsers _ approx = [ ]
# matching _ parsers _ exact = self . _ specific _ parse... |
def deserialize ( cls , value ) :
"""Generates a Peer instance via a JSON string of the sort generated
by ` Peer . deserialize ` .
The ` name ` and ` ip ` keys are required to be present in the JSON map ,
if the ` port ` key is not present the default is used .""" | parsed = json . loads ( value )
if "name" not in parsed :
raise ValueError ( "No peer name." )
if "ip" not in parsed :
raise ValueError ( "No peer IP." )
if "port" not in parsed :
parsed [ "port" ] = DEFAULT_PEER_PORT
return cls ( parsed [ "name" ] , parsed [ "ip" ] , parsed [ "port" ] ) |
def set_guest_property ( self , property_p , value , flags ) :
"""Sets , changes or deletes an entry in the machine ' s guest property
store .
in property _ p of type str
The name of the property to set , change or delete .
in value of type str
The new value of the property to set , change or delete . If ... | if not isinstance ( property_p , basestring ) :
raise TypeError ( "property_p can only be an instance of type basestring" )
if not isinstance ( value , basestring ) :
raise TypeError ( "value can only be an instance of type basestring" )
if not isinstance ( flags , basestring ) :
raise TypeError ( "flags ca... |
def _find_best_positions ( self , G ) :
"""Finds best positions for the given graph ( given as adjacency matrix )
nodes by minimizing a network potential .""" | initpos = None
holddim = None
if self . xpos is not None :
y = _np . random . random ( len ( self . xpos ) )
initpos = _np . vstack ( ( self . xpos , y ) ) . T
holddim = 0
elif self . ypos is not None :
x = _np . zeros_like ( self . xpos )
initpos = _np . vstack ( ( x , self . ypos ) ) . T
holdd... |
def greenlet ( func , args = ( ) , kwargs = None ) :
"""create a new greenlet from a function and arguments
: param func : the function the new greenlet should run
: type func : function
: param args : any positional arguments for the function
: type args : tuple
: param kwargs : any keyword arguments for... | if args or kwargs :
def target ( ) :
return func ( * args , ** ( kwargs or { } ) )
else :
target = func
return compat . greenlet ( target , state . mainloop ) |
def add_text_content_type ( application , content_type , default_encoding , dumps , loads ) :
"""Add handler for a text content type .
: param tornado . web . Application application : the application to modify
: param str content _ type : the content type to add
: param str default _ encoding : encoding to u... | parsed = headers . parse_content_type ( content_type )
parsed . parameters . pop ( 'charset' , None )
normalized = str ( parsed )
add_transcoder ( application , handlers . TextContentHandler ( normalized , dumps , loads , default_encoding ) ) |
def prepare_environment ( default_settings = _default_settings , ** kwargs ) : # pylint : disable = unused - argument
'''Prepare ENV for web - application
: param default _ settings : minimal needed settings for run app
: type default _ settings : dict
: param kwargs : other overrided settings
: rtype : Non... | for key , value in default_settings . items ( ) :
os . environ . setdefault ( key , value )
os . environ . update ( kwargs )
if six . PY2 : # nocv
warnings . warn ( 'Python 2.7 is deprecated and will dropped in 2.0, use Python >3.5' , DeprecationWarning ) |
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 : CompositionSettingsContext for this CompositionSettingsInstance
: rtype : twilio . rest . video . v1 . composition _ setti... | if self . _context is None :
self . _context = CompositionSettingsContext ( self . _version , )
return self . _context |
def _not_in ( x , y ) :
"""Compute the vectorized membership of ` ` x not in y ` ` if possible ,
otherwise use Python .""" | try :
return ~ x . isin ( y )
except AttributeError :
if is_list_like ( x ) :
try :
return ~ y . isin ( x )
except AttributeError :
pass
return x not in y |
def fail_run_group ( group , session ) :
"""End the run _ group unsuccessfully .
Args :
group : The run _ group we want to complete .
session : The database transaction we will finish .""" | from datetime import datetime
group . end = datetime . now ( )
group . status = 'failed'
session . commit ( ) |
def handle ( self , * args , ** options ) :
"""Create new app""" | quickstart = Quickstart ( )
try :
quickstart . create_app ( os . path . join ( settings . BASE_DIR , 'apps' ) , options . get ( 'name' ) )
self . stdout . write ( self . style . SUCCESS ( "Successfully created app ({name}), don't forget to add 'apps.{name}' to INSTALLED_APPS" . format ( name = options . get ( '... |
async def insert ( ** data ) :
"""RPC method for inserting data to the table
: return : None""" | table = data . get ( 'table' )
try :
clickhouse_queries . insert_into_table ( table , data )
return 'Data was successfully inserted into table'
except ServerException as e :
exception_code = int ( str ( e ) [ 5 : 8 ] . strip ( ) )
if exception_code == 60 :
return 'Table does not exists'
elif... |
def from_int ( self , integer ) :
"""Set the Note corresponding to the integer .
0 is a C on octave 0 , 12 is a C on octave 1 , etc .
Example :
> > > Note ( ) . from _ int ( 12)
' C - 1'""" | self . name = notes . int_to_note ( integer % 12 )
self . octave = integer // 12
return self |
def search ( self , CorpNum , JobID , Type , TaxType , PurposeType , TaxRegIDType , TaxRegIDYN , TaxRegID , Page , PerPage , Order , UserID = None ) :
"""수집 결과 조회
args
CorpNum : 팝빌회원 사업자번호
JobID : 작업아이디
Type : 문서형태 배열 , N - 일반전자세금계산서 , M - 수정전자세금ᄀ... | if JobID == None or len ( JobID ) != 18 :
raise PopbillException ( - 99999999 , "작업아이디(jobID)가 올바르지 않습니다." )
uri = '/HomeTax/Taxinvoice/' + JobID
uri += '?Type=' + ',' . join ( Type )
uri += '&TaxType=' + ',' . join ( TaxType )
uri += '&PurposeType=' + ',' . join ( PurposeType )
uri += '&TaxRegIDType=' + TaxRegIDTy... |
def create_row_to_some_id_col_mapping ( id_array ) :
"""Parameters
id _ array : 1D ndarray .
All elements of the array should be ints representing some id related
to the corresponding row .
Returns
rows _ to _ ids : 2D scipy sparse array .
Will map each row of id _ array to the unique values of ` id _ a... | # Get the unique ids , in their original order of appearance
original_order_unique_ids = get_original_order_unique_ids ( id_array )
# Create a matrix with the same number of rows as id _ array but a single
# column for each of the unique IDs . This matrix will associate each row
# as belonging to a particular observati... |
def Target_setRemoteLocations ( self , locations ) :
"""Function path : Target . setRemoteLocations
Domain : Target
Method name : setRemoteLocations
Parameters :
Required arguments :
' locations ' ( type : array ) - > List of remote locations .
No return value .
Description : Enables target discovery ... | assert isinstance ( locations , ( list , tuple ) ) , "Argument 'locations' must be of type '['list', 'tuple']'. Received type: '%s'" % type ( locations )
subdom_funcs = self . synchronous_command ( 'Target.setRemoteLocations' , locations = locations )
return subdom_funcs |
def disable_contactgroup_svc_notifications ( self , contactgroup ) :
"""Disable service notifications for a contactgroup
Format of the line that triggers function call : :
DISABLE _ CONTACTGROUP _ SVC _ NOTIFICATIONS ; < contactgroup _ name >
: param contactgroup : contactgroup to disable
: type contactgrou... | for contact_id in contactgroup . get_contacts ( ) :
self . disable_contact_svc_notifications ( self . daemon . contacts [ contact_id ] ) |
def _getCampaignDict ( ) :
"""Returns a dictionary specifying the details of all campaigns .""" | global _campaign_dict_cache
if _campaign_dict_cache is None : # All pointing parameters and dates are stored in a JSON file
fn = os . path . join ( PACKAGEDIR , "data" , "k2-campaign-parameters.json" )
_campaign_dict_cache = json . load ( open ( fn ) )
return _campaign_dict_cache |
def help ( module = None , * args ) :
'''Display help on Ansible standard module .
: param module :
: return :''' | if not module :
raise CommandExecutionError ( 'Please tell me what module you want to have helped with. ' 'Or call "ansible.list" to know what is available.' )
try :
module = _resolver . load_module ( module )
except ( ImportError , LoaderError ) as err :
raise CommandExecutionError ( 'Module "{0}" is curre... |
def build_where_stmt ( self , ident , filters , q_filters = None , source_class = None ) :
"""construct a where statement from some filters""" | if q_filters is not None :
stmts = self . _parse_q_filters ( ident , q_filters , source_class )
if stmts :
self . _ast [ 'where' ] . append ( stmts )
else :
stmts = [ ]
for row in filters :
negate = False
# pre - process NOT cases as they are nested dicts
if '__NOT__' in ... |
def build_plan ( description , graph , targets = None , reverse = False ) :
"""Builds a plan from a list of steps .
Args :
description ( str ) : an arbitrary string to
describe the plan .
graph ( : class : ` Graph ` ) : a list of : class : ` Graph ` to execute .
targets ( list ) : an optional list of step... | # If we want to execute the plan in reverse ( e . g . Destroy ) , transpose the
# graph .
if reverse :
graph = graph . transposed ( )
# If we only want to build a specific target , filter the graph .
if targets :
nodes = [ ]
for target in targets :
for k , step in graph . steps . items ( ) :
... |
def parse ( self , file_obj ) :
"""Read an OpenSSH config from the given file object .
: param file _ obj : a file - like object to read the config file from""" | host = { "host" : [ "*" ] , "config" : { } }
for line in file_obj : # Strip any leading or trailing whitespace from the line .
# Refer to https : / / github . com / paramiko / paramiko / issues / 499
line = line . strip ( )
if not line or line . startswith ( "#" ) :
continue
match = re . match ( sel... |
def get_agents_by_search ( self , agent_query , agent_search ) :
"""Pass through to provider AgentSearchSession . get _ agents _ by _ search""" | # Implemented from azosid template for -
# osid . resource . ResourceSearchSession . get _ resources _ by _ search _ template
if not self . _can ( 'search' ) :
raise PermissionDenied ( )
return self . _provider_session . get_agents_by_search ( agent_query , agent_search ) |
def add_subparsers ( self , * args , ** kwargs ) :
"""Add subparsers to this parser
Parameters
` ` * args , * * kwargs ` `
As specified by the original
: meth : ` argparse . ArgumentParser . add _ subparsers ` method
chain : bool
Default : False . If True , It is enabled to chain subparsers""" | chain = kwargs . pop ( 'chain' , None )
ret = super ( FuncArgParser , self ) . add_subparsers ( * args , ** kwargs )
if chain :
self . _chain_subparsers = True
self . _subparsers_action = ret
return ret |
def default ( self ) :
"""Return last changes in truncated unified diff format""" | output = ensure_unicode ( self . git . log ( '-1' , '-p' , '--no-color' , '--format=%s' , ) . stdout )
lines = output . splitlines ( )
return u'\n' . join ( itertools . chain ( lines [ : 1 ] , itertools . islice ( itertools . dropwhile ( lambda x : not x . startswith ( '+++' ) , lines [ 1 : ] , ) , 1 , None , ) , ) ) |
def do_handshake ( self , timeout ) :
'perform a SSL / TLS handshake' | tout = _timeout ( timeout )
if not self . _blocking :
return self . _sslobj . do_handshake ( )
while 1 :
try :
return self . _sslobj . do_handshake ( )
except ssl . SSLError , exc :
if exc . args [ 0 ] == ssl . SSL_ERROR_WANT_READ :
self . _wait_event ( tout . now )
c... |
def update ( self , value = None , force = False , ** kwargs ) :
'Updates the ProgressBar to a new value .' | if self . start_time is None :
self . start ( )
return self . update ( value , force = force , ** kwargs )
if value is not None and value is not base . UnknownLength :
if self . max_value is base . UnknownLength : # Can ' t compare against unknown lengths so just update
pass
elif self . min_valu... |
def set_model ( self , model ) :
"""Set the model the item belongs to
A TreeItem can only belong to one model .
: param model : the model the item belongs to
: type model : : class : ` Treemodel `
: returns : None
: rtype : None
: raises : None""" | self . _model = model
for c in self . childItems :
c . set_model ( model ) |
def optspace ( edm_missing , rank , niter = 500 , tol = 1e-6 , print_out = False ) :
"""Complete and denoise EDM using OptSpace algorithm .
Uses OptSpace algorithm to complete and denoise EDM . The problem being solved is
X , S , Y = argmin _ ( X , S , Y ) | | W ° ( D - XSY ' ) | | _ F ^ 2
: param edm _ missi... | from . opt_space import opt_space
N = edm_missing . shape [ 0 ]
X , S , Y , __ = opt_space ( edm_missing , r = rank , niter = niter , tol = tol , print_out = print_out )
edm_complete = X . dot ( S . dot ( Y . T ) )
edm_complete [ range ( N ) , range ( N ) ] = 0.0
return edm_complete |
def _tags_present ( name , tags , vpc_id = None , vpc_name = None , region = None , key = None , keyid = None , profile = None ) :
'''helper function to validate tags are correct''' | ret = { 'result' : True , 'comment' : '' , 'changes' : { } }
if tags :
sg = __salt__ [ 'boto_secgroup.get_config' ] ( name = name , group_id = None , region = region , key = key , keyid = keyid , profile = profile , vpc_id = vpc_id , vpc_name = vpc_name )
if not sg :
ret [ 'comment' ] = '{0} security gr... |
def fold ( self ) :
"""Folds the region .""" | start , end = self . get_range ( )
TextBlockHelper . set_collapsed ( self . _trigger , True )
block = self . _trigger . next ( )
while block . blockNumber ( ) <= end and block . isValid ( ) :
block . setVisible ( False )
block = block . next ( ) |
def parameter ( self , name = None , value = None , ** kwargs ) :
"""Create a < Parameter > element
: param name : The name of the custom parameter
: param value : The value of the custom parameter
: param kwargs : additional attributes
: returns : < Parameter > element""" | return self . nest ( Parameter ( name = name , value = value , ** kwargs ) ) |
def activated ( self , include_extras = True , extra_dists = None ) :
"""Helper context manager to activate the environment .
This context manager will set the following variables for the duration
of its activation :
* sys . prefix
* sys . path
* os . environ [ " VIRTUAL _ ENV " ]
* os . environ [ " PAT... | if not extra_dists :
extra_dists = [ ]
original_path = sys . path
original_prefix = sys . prefix
parent_path = vistir . compat . Path ( __file__ ) . absolute ( ) . parent
vendor_dir = parent_path . joinpath ( "vendor" ) . as_posix ( )
patched_dir = parent_path . joinpath ( "patched" ) . as_posix ( )
parent_path = p... |
def log_message ( self , format , * args ) :
"""Log an arbitrary message .
This is used by all other logging functions . Override
it if you have specific logging wishes .
The first argument , FORMAT , is a format string for the
message to be logged . If the format string contains
any % escapes requiring p... | sys . stderr . write ( "%s - - [%s] %s\n" % ( self . address_string ( ) , self . log_date_time_string ( ) , format % args ) ) |
def determine_endpoint_type ( features ) :
"""Determines the type of an endpoint
: param features : pandas . DataFrame
A dataset in a panda ' s data frame
: returns string
string with a name of a dataset""" | counter = { k . name : v for k , v in features . columns . to_series ( ) . groupby ( features . dtypes ) . groups . items ( ) }
if ( len ( features . groupby ( 'class' ) . apply ( list ) ) == 2 ) :
return ( 'binary' )
if ( 'float64' in counter ) :
return ( 'float' )
return ( 'integer' ) |
def getContextsForTerm ( self , retina_name , term , get_fingerprint = None , start_index = 0 , max_results = 5 ) :
"""Get the contexts for a given term
Args :
retina _ name , str : The retina name ( required )
term , str : A term in the retina ( required )
get _ fingerprint , bool : Configure if the finger... | resourcePath = '/terms/contexts'
method = 'GET'
queryParams = { }
headerParams = { 'Accept' : 'Application/json' , 'Content-Type' : 'application/json' }
postData = None
queryParams [ 'retina_name' ] = retina_name
queryParams [ 'term' ] = term
queryParams [ 'start_index' ] = start_index
queryParams [ 'max_results' ] = m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.