signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def distance_matrix ( coords_a , coords_b , cutoff , periodic = False , method = "simple" ) :
"""Calculate distances matrix the array of coordinates * coord _ a *
and * coord _ b * within a certain cutoff .
This function is a wrapper around different routines and data structures
for distance searches . It ret... | coords_a = np . array ( coords_a )
coords_b = np . array ( coords_b )
if method == "simple" :
if periodic is not False :
return distance_array ( coords_a , coords_b , cutoff = cutoff , period = periodic . astype ( np . double ) )
else :
dist = cdist ( coords_a , coords_b )
dist [ dist > ... |
def goBack ( self ) :
"""Moves the cursor to the end of the previous editor""" | index = self . indexOf ( self . currentEditor ( ) )
if index == - 1 :
return
previous = self . editorAt ( index - 1 )
if previous :
previous . setFocus ( )
previous . setCursorPosition ( self . sectionLength ( ) ) |
def update ( self , id ) :
"""PUT / datastores / id : Update an existing item .""" | # url ( ' DataStores ' , id = ID )
content = request . environ [ 'wsgi.input' ] . read ( int ( request . environ [ 'CONTENT_LENGTH' ] ) )
content = content . decode ( 'utf8' )
content = simplejson . loads ( content )
result = meta . Session . query ( DataStore ) . get ( id )
result . name = content [ 'name' ]
result . ... |
def wait_for_idle ( self ) :
"""Waits until the worker has nothing more to do . Very useful in tests""" | # Be mindful that this is being executed in a different greenlet than the work _ * methods .
while True :
time . sleep ( 0.01 )
with self . work_lock :
if self . status != "wait" :
continue
if len ( self . gevent_pool ) > 0 :
continue
# Force a refresh of the curr... |
def compute_statistics ( out_dir , gold_prefix , source_prefix , same_samples , use_sge , final_out_prefix ) :
"""Compute the statistics .""" | # Now , creating a temporary directory
if not os . path . isdir ( out_dir ) :
try :
os . mkdir ( out_dir )
except OSError :
msg = "{}: file exists" . format ( out_dir )
raise ProgramError ( msg )
# The out prefix
out_prefix = os . path . join ( out_dir , "tmp" )
# Subsetting the files
lo... |
def set_level ( self , val ) :
"""Set the device ON LEVEL .""" | if val == 0 :
self . off ( )
elif val == 255 :
self . on ( )
else :
setlevel = 255
if val < 1 :
setlevel = val * 255
elif val <= 0xff :
setlevel = val
change = setlevel - self . _value
increment = 255 / self . _steps
steps = round ( abs ( change ) / increment )
print ... |
def get_all_queues ( self ) :
"""Get information about all queues in the cluster .
Returns
queues : list of Queue
Examples
> > > client . get _ all _ queues ( )
[ Queue < name = ' default ' , percent _ used = 0.00 > ,
Queue < name = ' myqueue ' , percent _ used = 5.00 > ,
Queue < name = ' child1 ' , p... | resp = self . _call ( 'getAllQueues' , proto . Empty ( ) )
return [ Queue . from_protobuf ( q ) for q in resp . queues ] |
def _build_opr_data ( self , data , store ) :
"""Returns a well formatted OPR data""" | return { "invoice_data" : { "invoice" : { "total_amount" : data . get ( "total_amount" ) , "description" : data . get ( "description" ) } , "store" : store . info } , "opr_data" : { "account_alias" : data . get ( "account_alias" ) } } |
def _get_full_block ( grouped_dicoms ) :
"""Generate a full datablock containing all timepoints""" | # For each slice / mosaic create a data volume block
data_blocks = [ ]
for index in range ( 0 , len ( grouped_dicoms ) ) :
logger . info ( 'Creating block %s of %s' % ( index + 1 , len ( grouped_dicoms ) ) )
data_blocks . append ( _timepoint_to_block ( grouped_dicoms [ index ] ) )
# Add the data _ blocks togeth... |
def simplify ( self ) :
"""Return a new simplified expression in canonical form from this
expression .
For simplification of AND and OR fthe ollowing rules are used
recursively bottom up :
- Associativity ( output does not contain same operations nested )
- Annihilation
- Idempotence
- Identity
- Co... | # TODO : Refactor DualBase . simplify into different " sub - evals " .
# If self is already canonical do nothing .
if self . iscanonical :
return self
# Otherwise bring arguments into canonical form .
args = [ arg . simplify ( ) for arg in self . args ]
# Create new instance of own class with canonical args .
# TOD... |
def undefine ( self ) :
"""Undefine the Function .
Python equivalent of the CLIPS undeffunction command .
The object becomes unusable after this method has been called .""" | if lib . EnvUndeffunction ( self . _env , self . _fnc ) != 1 :
raise CLIPSError ( self . _env )
self . _env = None |
def get_events ( self ) -> List [ Event ] :
"""Get events associated with the scheduling object .
Returns :
list of Event objects""" | LOG . debug ( 'Getting events for %s' , self . key )
return get_events ( self . key ) |
def getChildren ( self , name = None , ns = None ) :
"""Get a list of children by ( optional ) name and / or ( optional ) namespace .
@ param name : The name of a child element ( may contain prefix ) .
@ type name : basestring
@ param ns : An optional namespace used to match the child .
@ type ns : ( I { pr... | if name is None :
matched = self . __root
else :
matched = self . getChild ( name , ns )
if matched is None :
return [ ]
else :
return [ matched , ] |
def decode_body ( cls , header , f ) :
"""Generates a ` MqttPingresp ` packet given a
` MqttFixedHeader ` . This method asserts that header . packet _ type
is ` pingresp ` .
Parameters
header : MqttFixedHeader
f : file
Object with a read method .
Raises
DecodeError
When there are extra bytes at th... | assert header . packet_type == MqttControlPacketType . pingresp
if header . remaining_len != 0 :
raise DecodeError ( 'Extra bytes at end of packet.' )
return 0 , MqttPingresp ( ) |
def axis_bounds ( self ) -> Dict [ str , Tuple [ float , float ] ] :
"""The ( minimum , maximum ) bounds for each axis .""" | return { ax : ( 0 , pos + 0.5 ) for ax , pos in _HOME_POSITION . items ( ) if ax not in 'BC' } |
def add_link ( self , ** kwgs ) :
"""Add additional link to the document . Links will be embeded only inside of this document .
> > > add _ link ( href = ' styles . css ' , rel = ' stylesheet ' , type = ' text / css ' )""" | self . links . append ( kwgs )
if kwgs . get ( 'type' ) == 'text/javascript' :
if 'scripted' not in self . properties :
self . properties . append ( 'scripted' ) |
def _select_best_smooth_at_each_point ( self ) :
"""Solve Eq ( 10 ) to find the best span for each observation .
Stores index so we can easily grab the best residual smooth , primary smooth , etc .""" | for residuals_i in zip ( * self . _residual_smooths ) :
index_of_best_span = residuals_i . index ( min ( residuals_i ) )
self . _best_span_at_each_point . append ( DEFAULT_SPANS [ index_of_best_span ] ) |
def get_points ( orig , dest , taillen ) :
"""Return a pair of lists of points for use making an arrow .
The first list is the beginning and end point of the trunk of the arrow .
The second list is the arrowhead .""" | # Adjust the start and end points so they ' re on the first non - transparent pixel .
# y = slope ( x - ox ) + oy
# x = ( y - oy ) / slope + ox
ox , oy = orig . center
ow , oh = orig . size
dx , dy = dest . center
dw , dh = dest . size
if ox < dx :
leftx = ox
rightx = dx
xco = 1
elif ox > dx :
leftx = o... |
def quick1D ( data , axis = 0 , at = { } , channel = 0 , * , local = False , autosave = False , save_directory = None , fname = None , verbose = True ) :
"""Quickly plot 1D slice ( s ) of data .
Parameters
data : WrightTools . Data object
Data to plot .
axis : string or integer ( optional )
Expression or ... | # channel index
channel_index = wt_kit . get_index ( data . channel_names , channel )
shape = data . channels [ channel_index ] . shape
collapse = [ i for i in range ( len ( shape ) ) if shape [ i ] == 1 ]
at = at . copy ( )
at . update ( { c : 0 for c in collapse } )
# prepare data
chopped = data . chop ( axis , at = ... |
def _find_benchmarks ( self ) :
"""Return a suite of all tests cases contained in testCaseClass""" | def is_bench_method ( attrname , prefix = "bench" ) :
return attrname . startswith ( prefix ) and hasattr ( getattr ( self . __class__ , attrname ) , '__call__' )
return list ( filter ( is_bench_method , dir ( self . __class__ ) ) ) |
def tx_min ( tasmax , freq = 'YS' ) :
r"""Lowest max temperature
The minimum of daily maximum temperature .
Parameters
tasmax : xarray . DataArray
Maximum daily temperature [ ° C ] or [ K ]
freq : str , optional
Resampling frequency
Returns
xarray . DataArray
Minimum of daily maximum temperature .... | return tasmax . resample ( time = freq ) . min ( dim = 'time' , keep_attrs = True ) |
def remove_file ( filename , recursive = False , force = False ) :
"""Removes a file or directory .""" | import os
try :
mode = os . stat ( filename ) [ 0 ]
if mode & 0x4000 != 0 : # directory
if recursive :
for file in os . listdir ( filename ) :
success = remove_file ( filename + '/' + file , recursive , force )
if not success and not force :
... |
def _make_entities_from_ids ( entity_cls , entity_objs_and_ids , server_config ) :
"""Given an iterable of entities and / or IDs , return a list of entities .
: param entity _ cls : An : class : ` Entity ` subclass .
: param entity _ obj _ or _ id : An iterable of
: class : ` nailgun . entity _ mixins . Entit... | return [ _make_entity_from_id ( entity_cls , entity_or_id , server_config ) for entity_or_id in entity_objs_and_ids ] |
def gpu_memory_info ( device_id = 0 ) :
"""Query CUDA for the free and total bytes of GPU global memory .
Parameters
device _ id : int , optional
The device id of the GPU device .
Raises
Will raise an exception on any CUDA error .
Returns
( free , total ) : ( int , int )
The number of GPUs .""" | free = ctypes . c_uint64 ( )
total = ctypes . c_uint64 ( )
dev_id = ctypes . c_int ( device_id )
check_call ( _LIB . MXGetGPUMemoryInformation64 ( dev_id , ctypes . byref ( free ) , ctypes . byref ( total ) ) )
return ( free . value , total . value ) |
def summarize ( requestContext , seriesList , intervalString , func = 'sum' , alignToFrom = False ) :
"""Summarize the data into interval buckets of a certain size .
By default , the contents of each interval bucket are summed together .
This is useful for counters where each increment represents a discrete
e... | results = [ ]
delta = parseTimeOffset ( intervalString )
interval = to_seconds ( delta )
for series in seriesList :
buckets = { }
timestamps = range ( int ( series . start ) , int ( series . end ) + 1 , int ( series . step ) )
datapoints = zip_longest ( timestamps , series )
for timestamp , value in dat... |
def get_scoped_variable_from_name ( self , name ) :
"""Get the scoped variable for a unique name
: param name : the unique name of the scoped variable
: return : the scoped variable specified by the name
: raises exceptions . AttributeError : if the name is not in the the scoped _ variables dictionary""" | for scoped_variable_id , scoped_variable in self . scoped_variables . items ( ) :
if scoped_variable . name == name :
return scoped_variable_id
raise AttributeError ( "Name %s is not in scoped_variables dictionary" , name ) |
def _bind_for_search ( anonymous = False , opts = None ) :
'''Bind with binddn and bindpw only for searching LDAP
: param anonymous : Try binding anonymously
: param opts : Pass in when _ _ opts _ _ is not available
: return : LDAPConnection object''' | # Get config params ; create connection dictionary
connargs = { }
# config params ( auth . ldap . * )
params = { 'mandatory' : [ 'uri' , 'server' , 'port' , 'starttls' , 'tls' , 'no_verify' , 'anonymous' , 'accountattributename' , 'activedirectory' ] , 'additional' : [ 'binddn' , 'bindpw' , 'filter' , 'groupclass' , 'a... |
def setup ( app ) :
"""Called at Sphinx initialization .""" | # Triggers sphinx - apidoc to generate API documentation .
app . connect ( 'builder-inited' , RunSphinxAPIDoc )
app . add_config_value ( 'recommonmark_config' , { 'enable_auto_doc_ref' : False } , True )
app . add_transform ( AutoStructify )
app . add_transform ( ProcessLink ) |
def valueFromString ( self , value , context = None ) :
"""Converts the inputted string text to a value that matches the type from
this column type .
: param value | < str >""" | if value == 'now' :
return datetime . datetime . now ( ) . time ( )
elif dateutil_parser :
return dateutil_parser . parse ( value ) . time ( )
else :
time_struct = time . strptime ( value , self . defaultFormat ( ) )
return datetime . time ( time_struct . tm_hour , time_struct . tm_min , time_struct . t... |
def get_prep_value ( self , value ) :
"""Returns field ' s value prepared for saving into a database .""" | if isinstance ( value , LocalizedValue ) :
prep_value = LocalizedValue ( )
for k , v in value . __dict__ . items ( ) :
if v is None :
prep_value . set ( k , '' )
else : # Need to convert File objects provided via a form to
# unicode for database insertion
prep_val... |
def _namedtupleload ( l : Loader , value : Dict [ str , Any ] , type_ ) -> Tuple :
"""This loads a Dict [ str , Any ] into a NamedTuple .""" | if not hasattr ( type_ , '__dataclass_fields__' ) :
fields = set ( type_ . _fields )
optional_fields = set ( getattr ( type_ , '_field_defaults' , { } ) . keys ( ) )
type_hints = type_ . _field_types
else : # dataclass
import dataclasses
fields = set ( type_ . __dataclass_fields__ . keys ( ) )
o... |
def delete ( self , msg , claim_id = None ) :
"""Deletes the specified message from its queue . If the message has been
claimed , the ID of that claim must be passed as the ' claim _ id '
parameter .""" | msg_id = utils . get_id ( msg )
if claim_id :
uri = "/%s/%s?claim_id=%s" % ( self . uri_base , msg_id , claim_id )
else :
uri = "/%s/%s" % ( self . uri_base , msg_id )
return self . _delete ( uri ) |
def fw_policy_delete ( self , data , fw_name = None ) :
"""Top level policy delete routine .""" | LOG . debug ( "FW Policy Debug" )
self . _fw_policy_delete ( fw_name , data ) |
def wait_all ( jobs , timeout = None ) :
"""Return when at all of the specified jobs have completed or timeout expires .
Args :
jobs : a Job or list of Jobs to wait on .
timeout : a timeout in seconds to wait for . None ( the default ) means no timeout .
Returns :
A list of the jobs that have now complete... | return Job . _wait ( jobs , timeout , concurrent . futures . ALL_COMPLETED ) |
def resolve_operation_info ( self , encoding_map , mips_op_info ) :
"""Adds the predefined operation info ( opcode , funct ) to the current encoding map .""" | encoding_map [ 'opcode' ] = mips_op_info . opcode
encoding_map [ 'funct' ] = mips_op_info . funct |
def parse_text_urls ( mesg ) :
"""Parse a block of text , splitting it into its url and non - url
components .""" | rval = [ ]
loc = 0
for match in URLRE . finditer ( mesg ) :
if loc < match . start ( ) :
rval . append ( Chunk ( mesg [ loc : match . start ( ) ] , None ) )
# Turn email addresses into mailto : links
email = match . group ( "email" )
if email and "mailto" not in email :
mailto = "mailto:... |
def step ( self , step_size : Timedelta = None ) :
"""Advance the simulation one step .
Parameters
step _ size
An optional size of step to take . Must be the same type as the
simulation clock ' s step size ( usually a pandas . Timedelta ) .""" | old_step_size = self . clock . step_size
if step_size is not None :
if not isinstance ( step_size , type ( self . clock . step_size ) ) :
raise ValueError ( f"Provided time must be an instance of {type(self.clock.step_size)}" )
self . clock . _step_size = step_size
super ( ) . step ( )
self . clock . _s... |
def convert_to_sympy_matrix ( expr , full_space = None ) :
"""Convert a QNET expression to an explicit ` ` n x n ` ` instance of
` sympy . Matrix ` , where ` ` n ` ` is the dimension of ` full _ space ` . The entries
of the matrix may contain symbols .
Parameters :
expr : a QNET expression
full _ space ( ... | if full_space is None :
full_space = expr . space
if not expr . space . is_tensor_factor_of ( full_space ) :
raise ValueError ( "expr must be in full_space" )
if expr is IdentityOperator :
return sympy . eye ( full_space . dimension )
elif expr is ZeroOperator :
return 0
elif isinstance ( expr , LocalOp... |
def __get_hooks_for_dll ( self , event ) :
"""Get the requested API hooks for the current DLL .
Used by L { _ _ hook _ dll } and L { _ _ unhook _ dll } .""" | result = [ ]
if self . __apiHooks :
path = event . get_module ( ) . get_filename ( )
if path :
lib_name = PathOperations . pathname_to_filename ( path ) . lower ( )
for hook_lib , hook_api_list in compat . iteritems ( self . __apiHooks ) :
if hook_lib == lib_name :
re... |
def delete_dispatch ( self , dispatch_id ) :
"""Deleting an existing dispatch
: param dispatch _ id : is the dispatch that the client wants to delete""" | self . _validate_uuid ( dispatch_id )
url = "/notification/v1/dispatch/{}" . format ( dispatch_id )
response = NWS_DAO ( ) . deleteURL ( url , self . _write_headers ( ) )
if response . status != 204 :
raise DataFailureException ( url , response . status , response . data )
return response . status |
def geocode ( self , query , lang = 'en' , exactly_one = True , timeout = DEFAULT_SENTINEL ) :
"""Return a location point for a ` 3 words ` query . If the ` 3 words ` address
doesn ' t exist , a : class : ` geopy . exc . GeocoderQueryError ` exception will be
thrown .
: param str query : The 3 - word address ... | if not self . _check_query ( query ) :
raise exc . GeocoderQueryError ( "Search string must be 'word.word.word'" )
params = { 'addr' : self . format_string % query , 'lang' : lang . lower ( ) , 'key' : self . api_key , }
url = "?" . join ( ( self . geocode_api , urlencode ( params ) ) )
logger . debug ( "%s.geocode... |
def get_user_info ( self , user_id , lang = "zh_CN" ) :
"""获取用户基本信息 。
: param user _ id : 用户 ID 。 就是你收到的 ` Message ` 的 source
: param lang : 返回国家地区语言版本 , zh _ CN 简体 , zh _ TW 繁体 , en 英语
: return : 返回的 JSON 数据包""" | return self . get ( url = "https://api.weixin.qq.com/cgi-bin/user/info" , params = { "access_token" : self . token , "openid" : user_id , "lang" : lang } ) |
def iter_widgets ( self , file = None , place = None ) :
'''Iterate registered widgets , optionally matching given criteria .
: param file : optional file object will be passed to widgets ' filter
functions .
: type file : browsepy . file . Node or None
: param place : optional template place hint .
: typ... | for filter , dynamic , cwidget in self . _widgets :
try :
if file and filter and not filter ( file ) :
continue
except BaseException as e : # Exception is handled as this method execution is deffered ,
# making hard to debug for plugin developers .
warnings . warn ( 'Plugin actio... |
def permutation_isc ( iscs , group_assignment = None , pairwise = False , # noqa : C901
summary_statistic = 'median' , n_permutations = 1000 , random_state = None ) :
"""Group - level permutation test for ISCs
For ISCs from one or more voxels or ROIs , permute group assignments to
construct a permutation distri... | # Standardize structure of input data
iscs , n_subjects , n_voxels = _check_isc_input ( iscs , pairwise = pairwise )
# Check for valid summary statistic
if summary_statistic not in ( 'mean' , 'median' ) :
raise ValueError ( "Summary statistic must be 'mean' or 'median'" )
# Check match between group labels and ISCs... |
def as_dates ( self ) :
"""Create a new DateRange with the datetimes converted to dates and changing to CLOSED / CLOSED .""" | new_start = self . start . date ( ) if self . start and isinstance ( self . start , datetime . datetime ) else self . start
new_end = self . end . date ( ) if self . end and isinstance ( self . end , datetime . datetime ) else self . end
return DateRange ( new_start , new_end , CLOSED_CLOSED ) |
def setCurrentMode ( self , mode ) :
"""Sets what mode this loader will be in .
: param mode | < XLoaderWidget . Mode >""" | if ( mode == self . _currentMode ) :
return
self . _currentMode = mode
ajax = mode == XLoaderWidget . Mode . Spinner
self . _movieLabel . setVisible ( ajax )
self . _primaryProgressBar . setVisible ( not ajax )
self . _subProgressBar . setVisible ( not ajax and self . _showSubProgress ) |
def post ( method , hmc , uri , uri_parms , body , logon_required , wait_for_completion ) :
"""Operation : Create Metrics Context .""" | assert wait_for_completion is True
# always synchronous
check_required_fields ( method , uri , body , [ 'anticipated-frequency-seconds' ] )
new_metrics_context = hmc . metrics_contexts . add ( body )
result = { 'metrics-context-uri' : new_metrics_context . uri , 'metric-group-infos' : new_metrics_context . get_metric_g... |
def read ( filename , mmap = False ) :
"""Return the sample rate ( in samples / sec ) and data from a WAV file
Parameters
filename : string or open file handle
Input wav file .
mmap : bool , optional
Whether to read data as memory mapped .
Only to be used on real files ( Default : False )
. . versiona... | if hasattr ( filename , 'read' ) :
fid = filename
mmap = False
else :
fid = open ( filename , 'rb' )
try :
fsize = _read_riff_chunk ( fid )
noc = 1
bits = 8
comp = WAVE_FORMAT_PCM
while ( fid . tell ( ) < fsize ) : # read the next chunk
chunk_id = fid . read ( 4 )
if chun... |
def get_public_url ( self , doc_id , branch = 'master' ) :
"""Returns a GitHub URL for the doc in question ( study , collection , . . . )""" | name , path_frag = self . get_repo_and_path_fragment ( doc_id )
return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag |
def create_instances_from_document ( doc_database , doc_idx , max_seq_length , short_seq_prob , masked_lm_prob , max_predictions_per_seq , vocab_list ) :
"""This code is mostly a duplicate of the equivalent function from Google BERT ' s repo .
However , we make some changes and improvements . Sampling is improved... | document = doc_database [ doc_idx ]
# Account for [ CLS ] , [ SEP ] , [ SEP ]
max_num_tokens = max_seq_length - 3
# We * usually * want to fill up the entire sequence since we are padding
# to ` max _ seq _ length ` anyways , so short sequences are generally wasted
# computation . However , we * sometimes *
# ( i . e .... |
def add_constants ( namespace , registry ) :
"""Adds the quantities from : mod : ` unyt . physical _ constants ` to a namespace
Parameters
namespace : dict
The dict to insert quantities into . The keys will be string names
and values will be the corresponding quantities .
registry : : class : ` unyt . uni... | from unyt . array import unyt_quantity
for constant_name in physical_constants :
value , unit_name , alternate_names = physical_constants [ constant_name ]
for name in alternate_names + [ constant_name ] :
quan = unyt_quantity ( value , unit_name , registry = registry )
try :
namespa... |
def gen_query ( self ) :
"""Generate an SQL query for the edge object .""" | return ( SQL . forwards_relation ( self . src , self . rel ) if self . dst is None else SQL . inverse_relation ( self . dst , self . rel ) ) |
def transform_form_error ( form , verbose = True ) :
"""transform form errors to list like
[ " field1 : error1 " , " field2 : error2 " ]""" | errors = [ ]
for field , err_msg in form . errors . items ( ) :
if field == '__all__' : # general errors
errors . append ( ', ' . join ( err_msg ) )
else : # field errors
field_name = field
if verbose and field in form . fields :
field_name = form . fields [ field ] . label o... |
def run ( self ) :
"""Process incoming HTTP connections .
Retrieves incoming connections from thread pool .""" | self . server . stats [ 'Worker Threads' ] [ self . getName ( ) ] = self . stats
try :
self . ready = True
while True :
conn = self . server . requests . get ( )
if conn is _SHUTDOWNREQUEST :
return
self . conn = conn
if self . server . stats [ 'Enabled' ] :
... |
def _send_packet ( self , data ) :
"Send to server ." | data = json . dumps ( data ) . encode ( 'utf-8' )
# Be sure that our socket is blocking , otherwise , the send ( ) call could
# raise ` BlockingIOError ` if the buffer is full .
self . socket . setblocking ( 1 )
self . socket . send ( data + b'\0' ) |
def last_modified ( self ) :
"""Gets the most recent modification time for all entries in the view""" | if self . entries :
latest = max ( self . entries , key = lambda x : x . last_modified )
return arrow . get ( latest . last_modified )
return arrow . get ( ) |
def reply_video ( self , video : str , quote : bool = None , caption : str = "" , parse_mode : str = "" , duration : int = 0 , width : int = 0 , height : int = 0 , thumb : str = None , supports_streaming : bool = True , disable_notification : bool = None , reply_to_message_id : int = None , reply_markup : Union [ "pyro... | if quote is None :
quote = self . chat . type != "private"
if reply_to_message_id is None and quote :
reply_to_message_id = self . message_id
return self . _client . send_video ( chat_id = self . chat . id , video = video , caption = caption , parse_mode = parse_mode , duration = duration , width = width , heig... |
def mv_normal_cov_like ( x , mu , C ) :
r"""Multivariate normal log - likelihood parameterized by a covariance
matrix .
. . math : :
f ( x \ mid \ pi , C ) = \ frac { 1 } { ( 2 \ pi | C | ) ^ { 1/2 } } \ exp \ left \ { - \ frac { 1 } { 2 } ( x - \ mu ) ^ { \ prime } C ^ { - 1 } ( x - \ mu ) \ right \ }
: Pa... | # TODO : Vectorize in Fortran
if len ( np . shape ( x ) ) > 1 :
return np . sum ( [ flib . cov_mvnorm ( r , mu , C ) for r in x ] )
else :
return flib . cov_mvnorm ( x , mu , C ) |
def all_node_style ( self , ** kwargs ) :
'''Modifies all node styles''' | for node in self . nodes :
self . node_style ( node , ** kwargs ) |
def _getFirmwareVersion ( self , device ) :
"""Get the firmware version .
: Parameters :
device : ` int `
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol .
: Returns :
An integer indicating the version number .""" | cmd = self . _COMMAND . get ( 'get-fw-version' )
self . _writeData ( cmd , device )
try :
result = self . _serial . read ( size = 1 )
result = int ( result )
except serial . SerialException as e :
self . _log and self . _log . error ( "Error: %s" , e , exc_info = True )
raise e
except ValueError as e :
... |
def check ( self , triggers , data_reader ) :
"""Look for a single detector trigger that passes the thresholds in
the current data .""" | if len ( triggers [ 'snr' ] ) == 0 :
return None
i = triggers [ 'snr' ] . argmax ( )
# This uses the pycbc live convention of chisq always meaning the
# reduced chisq .
rchisq = triggers [ 'chisq' ] [ i ]
nsnr = ranking . newsnr ( triggers [ 'snr' ] [ i ] , rchisq )
dur = triggers [ 'template_duration' ] [ i ]
if n... |
def UNas ( self , to = 'name_short' ) :
"""Return UN member states in the specified classification
Parameters
to : str , optional
Output classification ( valid str for an index of
country _ data file ) , default : name _ short
Returns
Pandas DataFrame""" | if isinstance ( to , str ) :
to = [ to ]
return self . data [ self . data . UNmember > 0 ] [ to ] |
def authAddress ( val ) :
"""# The C1 Tag
extracts the address of the authors as given by WOS . * * Warning * * the mapping of author to address is not very good and is given in multiple ways .
# Parameters
_ val _ : ` list [ str ] `
> The raw data from a WOS file
# Returns
` list [ str ] `
> A list o... | ret = [ ]
for a in val :
if a [ 0 ] == '[' :
ret . append ( '] ' . join ( a . split ( '] ' ) [ 1 : ] ) )
else :
ret . append ( a )
return ret |
def extract ( self , content , output ) :
"""Try to extract lines from the invoice""" | # First apply default options .
plugin_settings = DEFAULT_OPTIONS . copy ( )
plugin_settings . update ( self [ 'lines' ] )
self [ 'lines' ] = plugin_settings
# Validate settings
assert 'start' in self [ 'lines' ] , 'Lines start regex missing'
assert 'end' in self [ 'lines' ] , 'Lines end regex missing'
assert 'line' in... |
def bind ( self , * pos , ** kw ) :
"""Implements proxy connection for UDP sockets ,
which happens during the bind ( ) phase .""" | proxy_type , proxy_addr , proxy_port , rdns , username , password = self . proxy
if not proxy_type or self . type != socket . SOCK_DGRAM :
return _orig_socket . bind ( self , * pos , ** kw )
if self . _proxyconn :
raise socket . error ( EINVAL , "Socket already bound to an address" )
if proxy_type != SOCKS5 :
... |
def _resolve_folder ( project , parent_folder , folder_name ) :
""": param project : The project that the folder belongs to
: type project : string
: param parent _ folder : Full path to the parent folder that contains
folder _ name
: type parent _ folder : string
: param folder _ name : Name of the folde... | if '/' in folder_name : # Then there ' s no way it ' s supposed to be a folder
raise ResolutionError ( 'Object of name ' + str ( folder_name ) + ' could not be resolved in folder ' + str ( parent_folder ) + ' of project ID ' + str ( project ) )
possible_folder , _skip = clean_folder_path ( parent_folder + '/' + fol... |
def remove_node ( self , node ) :
"""Remove the node from the graph , removes also all connections .
: param androguard . decompiler . dad . node . Node node : the node to remove""" | preds = self . reverse_edges . get ( node , [ ] )
for pred in preds :
self . edges [ pred ] . remove ( node )
succs = self . edges . get ( node , [ ] )
for suc in succs :
self . reverse_edges [ suc ] . remove ( node )
exc_preds = self . reverse_catch_edges . pop ( node , [ ] )
for pred in exc_preds :
self .... |
def realpath ( path ) :
"""Create the real absolute path for the given path .
Add supports for userdir & / supports .
Args :
* path : pathname to use for realpath .
Returns :
Platform independent real absolute path .""" | if path == '~' :
return userdir
if path == '/' :
return sysroot
if path . startswith ( '/' ) :
return os . path . abspath ( path )
if path . startswith ( '~/' ) :
return os . path . expanduser ( path )
if path . startswith ( './' ) :
return os . path . abspath ( os . path . join ( os . path . curdir... |
def list_processed_parameter_group_histogram ( self , group = None , start = None , stop = None , merge_time = 20 ) :
"""Reads index records related to processed parameter groups between the
specified start and stop time .
Each iteration returns a chunk of chronologically - sorted records .
: param float merg... | params = { }
if group is not None :
params [ 'group' ] = group
if start is not None :
params [ 'start' ] = to_isostring ( start )
if stop is not None :
params [ 'stop' ] = to_isostring ( stop )
if merge_time is not None :
params [ 'mergeTime' ] = int ( merge_time * 1000 )
return pagination . Iterator ( ... |
def state ( self , time = None ) :
"""The most recently - created info of type State at the specfied time .
If time is None then it returns the most recent state as of now .""" | if time is None :
return max ( self . infos ( type = State ) , key = attrgetter ( 'creation_time' ) )
else :
states = [ s for s in self . infos ( type = State ) if s . creation_time < time ]
return max ( states , key = attrgetter ( 'creation_time' ) ) |
def set_voltage ( self , value , channel = 1 ) :
"""channel : 1 = OP1 , 2 = OP2 , AUX is not supported""" | cmd = "V%d %f" % ( channel , value )
self . write ( cmd ) |
def hash_data ( obj ) :
"""Generate a SHA1 from a complex object .""" | collect = sha1 ( )
for text in bytes_iter ( obj ) :
if isinstance ( text , six . text_type ) :
text = text . encode ( 'utf-8' )
collect . update ( text )
return collect . hexdigest ( ) |
def load_config ( filename = None ) :
"""Load a configuration from a file or stdin .
If ` filename ` is ` None ` or " - " , then configuration gets read from stdin .
Returns : A ` ConfigDict ` .
Raises : ConfigError : If there is an error loading the config .""" | try :
with _config_stream ( filename ) as handle :
filename = handle . name
return deserialize_config ( handle . read ( ) )
except ( OSError , toml . TomlDecodeError , UnicodeDecodeError ) as exc :
raise ConfigError ( 'Error loading configuration from {}' . format ( filename ) ) from exc |
def default_decode ( events , mode = 'full' ) :
"""Decode a XigtCorpus element .""" | event , elem = next ( events )
root = elem
# store root for later instantiation
while ( event , elem . tag ) not in [ ( 'start' , 'igt' ) , ( 'end' , 'xigt-corpus' ) ] :
event , elem = next ( events )
igts = None
if event == 'start' and elem . tag == 'igt' :
igts = ( decode_igt ( e ) for e in iter_elements ( 'i... |
def apply_caching ( response ) :
"""Applies the configuration ' s http headers to all responses""" | for k , v in config . get ( 'HTTP_HEADERS' ) . items ( ) :
response . headers [ k ] = v
return response |
def list_sinks ( self , project , page_size = 0 , page_token = None ) :
"""List sinks for the project associated with this client .
: type project : str
: param project : ID of the project whose sinks are to be listed .
: type page _ size : int
: param page _ size : maximum number of sinks to return , If no... | path = "projects/%s" % ( project , )
page_iter = self . _gapic_api . list_sinks ( path , page_size = page_size )
page_iter . client = self . _client
page_iter . next_page_token = page_token
page_iter . item_to_value = _item_to_sink
return page_iter |
def get_map_matrix ( inputfile , sheet_name ) :
"""Return the matrix representation of the genetic map .
: arg inputfile : the path to the input file from which to retrieve the
genetic map .
: arg sheet _ name : the excel sheet containing the data on which to
retrieve the genetic map .""" | matrix = read_excel_file ( inputfile , sheet_name )
output = [ [ 'Locus' , 'Group' , 'Position' ] ]
for row in matrix :
if row [ 0 ] and not re . match ( r'c\d+\.loc[\d\.]+' , row [ 0 ] ) :
output . append ( [ row [ 0 ] , row [ 1 ] , row [ 2 ] ] )
return output |
def pad_to_multiple ( self , factor ) :
"""Pad the pianoroll with zeros at the end along the time axis with the
minimum length that makes the resulting pianoroll length a multiple of
` factor ` .
Parameters
factor : int
The value which the length of the resulting pianoroll will be
a multiple of .""" | remainder = self . pianoroll . shape [ 0 ] % factor
if remainder :
pad_width = ( ( 0 , ( factor - remainder ) ) , ( 0 , 0 ) )
self . pianoroll = np . pad ( self . pianoroll , pad_width , 'constant' ) |
def execute_epoch ( self , epoch_info , learner ) :
"""Prepare the phase for learning""" | for param_group in epoch_info . optimizer . param_groups :
param_group [ 'lr' ] = self . lr
epoch_result = learner . run_epoch ( epoch_info , self . _source )
return epoch_result |
def exec_command ( self , command , sudo = False , ** kwargs ) :
"""Wrapper to paramiko . SSHClient . exec _ command""" | channel = self . client . get_transport ( ) . open_session ( )
# stdin = channel . makefile ( ' wb ' )
stdout = channel . makefile ( 'rb' )
stderr = channel . makefile_stderr ( 'rb' )
if sudo :
command = 'sudo -S bash -c \'%s\'' % command
else :
command = 'bash -c \'%s\'' % command
logger . debug ( "Running com... |
def gauss_warp_arb ( X , l1 , l2 , lw , x0 ) :
r"""Warps the ` X ` coordinate with a Gaussian - shaped divot .
. . math : :
l = l _ 1 - ( l _ 1 - l _ 2 ) \ exp \ left ( - 4 \ ln 2 \ frac { ( X - x _ 0 ) ^ 2 } { l _ { w } ^ { 2 } } \ right )
Parameters
X : : py : class : ` Array ` , ( ` M ` , ) or scalar flo... | if isinstance ( X , scipy . ndarray ) :
if isinstance ( X , scipy . matrix ) :
X = scipy . asarray ( X , dtype = float )
return l1 - ( l1 - l2 ) * scipy . exp ( - 4.0 * scipy . log ( 2.0 ) * ( X - x0 ) ** 2.0 / ( lw ** 2.0 ) )
else :
return l1 - ( l1 - l2 ) * mpmath . exp ( - 4.0 * mpmath . log ( 2.... |
def vertically ( value , num_blocks , val_min , color , args ) :
"""Prepare the vertical graph .
The whole graph is printed through the print _ vertical function .""" | global maxi , value_list
value_list . append ( str ( value ) )
# In case the number of blocks at the end of the normalization is less
# than the default number , use the maxi variable to escape .
if maxi < num_blocks :
maxi = num_blocks
if num_blocks > 0 :
vertical_list . append ( ( TICK * num_blocks ) )
else :... |
def read_cert_from_file ( cert_file , cert_type ) :
"""Reads a certificate from a file . The assumption is that there is
only one certificate in the file
: param cert _ file : The name of the file
: param cert _ type : The certificate type
: return : A base64 encoded certificate as a string or the empty str... | if not cert_file :
return ''
if cert_type == 'pem' :
_a = read_file ( cert_file , 'rb' ) . decode ( )
_b = _a . replace ( '\r\n' , '\n' )
lines = _b . split ( '\n' )
for pattern in ( '-----BEGIN CERTIFICATE-----' , '-----BEGIN PUBLIC KEY-----' ) :
if pattern in lines :
lines = li... |
def stop ( self , * args ) :
"""Stops the TendrilManager . Requires cooperation from the
listener implementation , which must watch the ` ` running ` `
attribute and ensure that it stops accepting connections
should that attribute become False . Note that some tendril
managers will not exit from the listeni... | # Remove ourself from the dictionary of running managers
try :
del self . _running_managers [ self . _manager_key ]
except KeyError :
pass
self . running = False
self . _local_addr = None
self . _local_addr_event . clear ( ) |
def new_process_number ( self , name ) :
"""Increment the counter for the process id number for a given consumer
configuration .
: param str name : Consumer name
: rtype : int""" | self . consumers [ name ] . last_proc_num += 1
return self . consumers [ name ] . last_proc_num |
def cli ( ctx , dname , site ) :
"""Launches a MySQL CLI session for the database of the specified IPS installation .""" | assert isinstance ( ctx , Context )
log = logging . getLogger ( 'ipsv.mysql' )
dname = domain_parse ( dname ) . hostname
domain = Session . query ( Domain ) . filter ( Domain . name == dname ) . first ( )
# No such domain
if not domain :
click . secho ( 'No such domain: {dn}' . format ( dn = dname ) , fg = 'red' , ... |
def assert_is_not ( self , actual_val , unexpected_type , failure_message = 'Expected type not to be "{1}," but was "{0}"' ) :
"""Calls smart _ assert , but creates its own assertion closure using
the expected and provided values with the ' is not ' operator""" | assertion = lambda : unexpected_type is not actual_val
self . webdriver_assert ( assertion , unicode ( failure_message ) . format ( actual_val , unexpected_type ) ) |
def IsPrimitiveType ( obj ) :
"""See if the passed in type is a Primitive Type""" | return ( isinstance ( obj , types . bool ) or isinstance ( obj , types . byte ) or isinstance ( obj , types . short ) or isinstance ( obj , six . integer_types ) or isinstance ( obj , types . double ) or isinstance ( obj , types . float ) or isinstance ( obj , six . string_types ) or isinstance ( obj , types . Property... |
def _on_del_route ( self , msg ) :
"""Stub : data : ` DEL _ ROUTE ` handler ; fires ' disconnect ' events on the
corresponding : attr : ` _ context _ by _ id ` member . This is replaced by
: class : ` mitogen . parent . RouteMonitor ` in an upgraded context .""" | LOG . error ( '%r._on_del_route() %r' , self , msg )
if msg . is_dead :
return
target_id_s , _ , name = bytes_partition ( msg . data , b ( ':' ) )
target_id = int ( target_id_s , 10 )
context = self . _context_by_id . get ( target_id )
if context :
fire ( context , 'disconnect' )
else :
LOG . debug ( 'DEL_R... |
def get_template_node_arguments ( cls , tokens ) :
"""Return the arguments taken from the templatetag that will be used to the
Node class .
Take a list of all tokens and return a list of real tokens . Here
should be done some validations ( number of tokens . . . ) and eventually
some parsing . . .""" | if len ( tokens ) < 3 :
raise template . TemplateSyntaxError ( "'%r' tag requires at least 2 arguments." % tokens [ 0 ] )
return tokens [ 1 ] , tokens [ 2 ] , tokens [ 3 : ] |
def write ( self , out ) :
"""Used in constructing an outgoing packet""" | out . write_string ( self . text , len ( self . text ) ) |
def add_transitions_to_closest_sibling_state_from_selected_state ( ) :
"""Generates the outcome transitions from outcomes with positive outcome _ id to the closest next state
: return :""" | task_string = "create transition"
sub_task_string = "to closest sibling state"
selected_state_m , msg = get_selected_single_state_model_and_check_for_its_parent ( )
if selected_state_m is None :
logger . warning ( "Can not {0} {1}: {2}" . format ( task_string , sub_task_string , msg ) )
return
logger . debug ( ... |
def wide ( self ) :
"""` ` True ` ` if this instruction needs to be prefixed by the WIDE
opcode .""" | if not opcode_table [ self . opcode ] . get ( 'can_be_wide' ) :
return False
if self . operands [ 0 ] . value >= 255 :
return True
if self . opcode == 0x84 :
if self . operands [ 1 ] . value >= 255 :
return True
return False |
def build ( self , field : Field ) -> Mapping [ str , Any ] :
"""Build a parameter .""" | return dict ( self . iter_parsed_values ( field ) ) |
def get_airports ( self , country ) :
"""Returns a list of all the airports
For a given country this returns a list of dicts , one for each airport , with information like the iata code of the airport etc
Args :
country ( str ) : The country for which the airports will be fetched
Example : :
from pyflight... | url = AIRPORT_BASE . format ( country . replace ( " " , "-" ) )
return self . _fr24 . get_airports_data ( url ) |
def time ( arg ) :
"""Converts the value into a unix time ( seconds since unix epoch ) .
For example :
convert . time ( datetime . now ( ) )
# ' 1409810596'
: param arg : The time .
: type arg : datetime . datetime or int""" | # handle datetime instances .
if _has_method ( arg , "timetuple" ) :
arg = _time . mktime ( arg . timetuple ( ) )
if isinstance ( arg , float ) :
arg = int ( arg )
return str ( arg ) |
def get_bug_log ( nr ) :
"""Get Buglogs .
A buglog is a dictionary with the following mappings :
* " header " = > string
* " body " = > string
* " attachments " = > list
* " msg _ num " = > int
* " message " = > email . message . Message
Parameters
nr : int
the bugnumber
Returns
buglogs : list... | reply = _soap_client_call ( 'get_bug_log' , nr )
items_el = reply ( 'soapenc:Array' )
buglogs = [ ]
for buglog_el in items_el . children ( ) :
buglog = { }
buglog [ "header" ] = _parse_string_el ( buglog_el ( "header" ) )
buglog [ "body" ] = _parse_string_el ( buglog_el ( "body" ) )
buglog [ "msg_num" ]... |
def compose ( im , y , fns ) :
"""Apply a collection of transformation functions : fns : to images""" | for fn in fns : # pdb . set _ trace ( )
im , y = fn ( im , y )
return im if y is None else ( im , y ) |
def connect ( self ) :
"""Sets up your Phabricator session , it ' s not necessary to call
this directly""" | if self . token :
self . phab_session = { 'token' : self . token }
return
req = self . req_session . post ( '%s/api/conduit.connect' % self . host , data = { 'params' : json . dumps ( self . connect_params ) , 'output' : 'json' , '__conduit__' : True , } )
# Parse out the response ( error handling ommitted )
re... |
def toList ( value ) :
"""Convert a value to a list , if possible .""" | if type ( value ) == list :
return value
elif type ( value ) in [ np . ndarray , tuple , xrange , array . array ] :
return list ( value )
elif isinstance ( value , Vector ) :
return list ( value . toArray ( ) )
else :
raise TypeError ( "Could not convert %s to list" % value ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.