signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def view ( self , start , end , max_items = None , * args , ** kwargs ) :
"""Implements the CalendarView option to FindItem . The difference between filter ( ) and view ( ) is that filter ( )
only returns the master CalendarItem for recurring items , while view ( ) unfolds recurring items and returns all
Calend... | qs = QuerySet ( self ) . filter ( * args , ** kwargs )
qs . calendar_view = CalendarView ( start = start , end = end , max_items = max_items )
return qs |
def load_from_file ( path , fmt = None , is_training = True ) :
'''load data from file''' | if fmt is None :
fmt = 'squad'
assert fmt in [ 'squad' , 'csv' ] , 'input format must be squad or csv'
qp_pairs = [ ]
if fmt == 'squad' :
with open ( path ) as data_file :
data = json . load ( data_file ) [ 'data' ]
for doc in data :
for paragraph in doc [ 'paragraphs' ] :
... |
def _enumerate_directions ( x ) :
"""For an n - dimensional tensor , returns tensors to enumerate each axis .
> > > x = np . zeros ( [ 2 , 3 , 4 ] ) # or any other tensor
> > > i , j , k = _ enumerate _ directions ( x )
> > > result = i + 2 * j + 3 * k
result [ i , j , k ] = i + 2 * j + 3 * k , and also has... | backend = get_backend ( x )
shape = backend . shape ( x )
result = [ ]
for axis_id , axis_length in enumerate ( shape ) :
shape = [ 1 ] * len ( shape )
shape [ axis_id ] = axis_length
result . append ( backend . reshape ( backend . arange ( 0 , axis_length ) , shape ) )
return result |
def get_trans_reg ( self , name : Text , default : Any = None ) -> Any :
"""Convenience function to access the transition register of a specific
kind .
: param name : Name of the register you want to see
: param default : What to return by default""" | tr = self . register . get ( Register . TRANSITION , { } )
return tr . get ( name , default ) |
def bind ( self , instance , auto = False ) :
"""Bind deps to instance
: param instance :
: param auto : follow update of DI and refresh binds once we will get something new
: return :""" | methods = [ ( m , cls . __dict__ [ m ] ) for cls in inspect . getmro ( type ( instance ) ) for m in cls . __dict__ if inspect . isfunction ( cls . __dict__ [ m ] ) ]
try :
deps_of_endpoints = [ ( method_ptr , self . entrypoint_deps ( method_ptr ) ) for ( method_name , method_ptr ) in methods ]
for ( method_ptr ... |
def get_persistent_items ( self ) :
"""Returns attached container items and container configurations that are marked as persistent . Each returned
item is in the format ` ` ( config name , instance / attached name ) ` ` , where the instance name can also be ` ` None ` ` .
: return : Lists of attached items .
... | attached_items = [ ( container , ac ) for container , config in self for ac in config . attaches ]
persistent_containers = [ ( container , ci ) for container , config in self if config . persistent for ci in config . instances or [ None ] ]
return attached_items , persistent_containers |
def X ( self , i , j = slice ( None , None , None ) ) :
'''Computes the design matrix at the given * PLD * order and the given
indices . The columns are the * PLD * vectors for the target at the
corresponding order , computed as the product of the fractional pixel
flux of all sets of : py : obj : ` n ` pixels... | X1 = self . fpix [ j ] / self . norm [ j ] . reshape ( - 1 , 1 )
X = np . product ( list ( multichoose ( X1 . T , i + 1 ) ) , axis = 1 ) . T
if self . X1N is not None :
return np . hstack ( [ X , self . X1N [ j ] ** ( i + 1 ) ] )
else :
return X |
def create ( zpool , * vdevs , ** kwargs ) :
'''. . versionadded : : 2015.5.0
Create a simple zpool , a mirrored zpool , a zpool having nested VDEVs , a hybrid zpool with cache , spare and log drives or a zpool with RAIDZ - 1 , RAIDZ - 2 or RAIDZ - 3
zpool : string
Name of storage pool
vdevs : string
One ... | # # Configure pool
# NOTE : initialize the defaults
flags = [ ]
opts = { }
target = [ ]
# NOTE : push pool and filesystem properties
pool_properties = kwargs . get ( 'properties' , { } )
filesystem_properties = kwargs . get ( 'filesystem_properties' , { } )
# NOTE : set extra config based on kwargs
if kwargs . get ( 'f... |
def disable_process_breakpoints ( self , dwProcessId ) :
"""Disables all breakpoints for the given process .
@ type dwProcessId : int
@ param dwProcessId : Process global ID .""" | # disable code breakpoints
for bp in self . get_process_code_breakpoints ( dwProcessId ) :
self . disable_code_breakpoint ( dwProcessId , bp . get_address ( ) )
# disable page breakpoints
for bp in self . get_process_page_breakpoints ( dwProcessId ) :
self . disable_page_breakpoint ( dwProcessId , bp . get_addr... |
def request ( self , method , * , path = None , json = None , params = None , headers = None , timeout = None , backoff_cap = None , ** kwargs ) :
"""Performs an HTTP request with the given parameters .
Implements exponential backoff .
If ` ConnectionError ` occurs , a timestamp equal to now +
the default del... | backoff_timedelta = self . get_backoff_timedelta ( )
if timeout is not None and timeout < backoff_timedelta :
raise TimeoutError
if backoff_timedelta > 0 :
time . sleep ( backoff_timedelta )
connExc = None
timeout = timeout if timeout is None else timeout - backoff_timedelta
try :
response = self . _request... |
def action_delete ( self , ids ) :
"""Delete selected sessions .""" | is_current = any ( SessionActivity . is_current ( sid_s = id_ ) for id_ in ids )
if is_current :
flash ( 'You could not remove your current session' , 'error' )
return
for id_ in ids :
delete_session ( sid_s = id_ )
db . session . commit ( ) |
def separated ( p , sep , mint , maxt = None , end = None ) :
'''Repeat a parser ` p ` separated by ` s ` between ` mint ` and ` maxt ` times .
When ` end ` is None , a trailing separator is optional .
When ` end ` is True , a trailing separator is required .
When ` end ` is False , a trailing separator is no... | maxt = maxt if maxt else mint
@ Parser
def sep_parser ( text , index ) :
cnt , values , res = 0 , Value . success ( index , [ ] ) , None
while cnt < maxt :
if end in [ False , None ] and cnt > 0 :
res = sep ( text , index )
if res . status : # ` sep ` found , consume it ( advance... |
def _F ( self , X ) :
"""analytic solution of the projection integral
: param x : R / Rs
: type x : float > 0""" | if isinstance ( X , int ) or isinstance ( X , float ) :
if X < 1 and X > 0 :
a = 1 / ( X ** 2 - 1 ) * ( 1 - 2 / np . sqrt ( 1 - X ** 2 ) * np . arctanh ( np . sqrt ( ( 1 - X ) / ( 1 + X ) ) ) )
elif X == 1 :
a = 1. / 3
elif X > 1 :
a = 1 / ( X ** 2 - 1 ) * ( 1 - 2 / np . sqrt ( X ** ... |
def pretty ( self ) :
'''Return a string like ' / foo / bar . py : 230 in foo . bar . my _ func ' .''' | return '{}:{} in {}.{}' . format ( self . filename , self . line_number , self . module_name , self . function_name ) |
def key_absent ( name , use_32bit_registry = False ) :
r'''. . versionadded : : 2015.5.4
Ensure a registry key is removed . This will remove the key , subkeys , and all
value entries .
Args :
name ( str ) :
A string representing the full path to the key to be removed to
include the hive and the keypath ... | ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' }
hive , key = _parse_key ( name )
# Determine what to do
if not __utils__ [ 'reg.read_value' ] ( hive = hive , key = key , use_32bit_registry = use_32bit_registry ) [ 'success' ] :
ret [ 'comment' ] = '{0} is already absent' . format ( name... |
def despike ( self , window_length = 33 , samples = True , z = 2 ) :
"""Args :
window ( int ) : window length in samples . Default 33 ( or 5 m for
most curves sampled at 0.1524 m intervals ) .
samples ( bool ) : window length is in samples . Use False for a window
length given in metres .
z ( float ) : Z ... | window_length //= 1 if samples else self . step
z *= np . nanstd ( self )
# Transform to curve ' s units
curve_sm = self . _rolling_window ( window_length , np . median )
spikes = np . where ( np . nan_to_num ( self - curve_sm ) > z ) [ 0 ]
spukes = np . where ( np . nan_to_num ( curve_sm - self ) > z ) [ 0 ]
out = np ... |
def get_date ( context , value ) :
"""Tries to return a DateTime . DateTime object""" | if not value :
return None
if isinstance ( value , DateTime ) :
return value
if isinstance ( value , datetime ) :
return dt2DT ( value )
if not isinstance ( value , basestring ) :
return None
def try_parse ( date_string , format ) :
if not format :
return None
try :
struct_time =... |
def plot_kmf ( df , condition_col , censor_col , survival_col , strata_col = None , threshold = None , title = None , xlabel = None , ylabel = None , ax = None , with_condition_color = "#B38600" , no_condition_color = "#A941AC" , with_condition_label = None , no_condition_label = None , color_map = None , label_map = N... | # set reasonable default threshold value depending on type of condition _ col
if threshold is None :
if df [ condition_col ] . dtype != "bool" and np . issubdtype ( df [ condition_col ] . dtype , np . number ) :
threshold = "median"
# check inputs for threshold for validity
elif isinstance ( threshold , num... |
def dtype ( self ) :
"""Pixel data type .""" | pixels_group = self . label [ 'IsisCube' ] [ 'Core' ] [ 'Pixels' ]
byte_order = self . BYTE_ORDERS [ pixels_group [ 'ByteOrder' ] ]
pixel_type = self . PIXEL_TYPES [ pixels_group [ 'Type' ] ]
return pixel_type . newbyteorder ( byte_order ) |
def _gettables ( self ) :
"""Return a list of hdf5 tables name PyMCsamples .""" | groups = self . _h5file . list_nodes ( "/" )
if len ( groups ) == 0 :
return [ ]
else :
return [ gr . PyMCsamples for gr in groups if gr . _v_name [ : 5 ] == 'chain' ] |
def _load_texture ( file_name , resolver ) :
"""Load a texture from a file into a PIL image .""" | file_data = resolver . get ( file_name )
image = PIL . Image . open ( util . wrap_as_stream ( file_data ) )
return image |
def upload ( state , host , hostname , filename , remote_filename = None , use_remote_sudo = False , ssh_keyscan = False , ssh_user = None , ) :
'''Upload files to other servers using ` ` scp ` ` .
+ hostname : hostname to upload to
+ filename : file to upload
+ remote _ filename : where to upload the file to... | remote_filename = remote_filename or filename
# Figure out where we ' re connecting ( host or user @ host )
connection_target = hostname
if ssh_user :
connection_target = '@' . join ( ( ssh_user , hostname ) )
if ssh_keyscan :
yield keyscan ( state , host , hostname )
# If we ' re not using sudo on the remote s... |
def norm_int_dict ( int_dict ) :
"""Normalizes values in the given dict with int values .
Parameters
int _ dict : list
A dict object mapping each key to an int value .
Returns
dict
A dict where each key is mapped to its relative part in the sum of
all dict values .
Example
> > > dict _ obj = { ' a... | norm_dict = int_dict . copy ( )
val_sum = sum ( norm_dict . values ( ) )
for key in norm_dict :
norm_dict [ key ] = norm_dict [ key ] / val_sum
return norm_dict |
def _AbandonInactiveProcessingTasks ( self ) :
"""Marks processing tasks that exceed the inactive time as abandoned .
This method does not lock the manager and should be called by a method
holding the manager lock .""" | if self . _tasks_processing :
inactive_time = time . time ( ) - self . _TASK_INACTIVE_TIME
inactive_time = int ( inactive_time * definitions . MICROSECONDS_PER_SECOND )
# Abandon all tasks after they ' re identified so as not to modify the
# dict while iterating over it .
tasks_to_abandon = [ ]
... |
def on_KeyPress ( self , event ) :
'''To adjust the distance between pitch markers .''' | if event . GetKeyCode ( ) == wx . WXK_UP :
self . dist10deg += 0.1
print ( 'Dist per 10 deg: %.1f' % self . dist10deg )
elif event . GetKeyCode ( ) == wx . WXK_DOWN :
self . dist10deg -= 0.1
if self . dist10deg <= 0 :
self . dist10deg = 0.1
print ( 'Dist per 10 deg: %.1f' % self . dist10deg ... |
def ajax ( authenticated = True , data_required = False , json_encoder = json . JSONEncoder ) :
"""Decorator to allow the wrappered view to exist in an AJAX environment .
Provide a decorator to wrap a view method so that it may exist in an
entirely AJAX environment :
- data decoded from JSON as input and data... | def decorator ( function , authenticated = authenticated , data_required = data_required ) :
@ functools . wraps ( function , assigned = decorators . available_attrs ( function ) )
def _wrapped ( self , request , * args , ** kw ) :
if authenticated and not request . user . is_authenticated :
... |
def get_changelog ( repo_path , from_commit = None ) :
"""Given a repo path and an option commit / tag / refspec to start from , will
get the rpm compatible changelog
Args :
repo _ path ( str ) : path to the git repo
from _ commit ( str ) : refspec ( partial commit hash , tag , branch , full
refspec , par... | repo = dulwich . repo . Repo ( repo_path )
tags = get_tags ( repo )
refs = get_refs ( repo )
changelog = [ ]
maj_version = 0
feat_version = 0
fix_version = 0
start_including = False
cur_line = ''
if from_commit is None :
start_including = True
for commit_sha , children in reversed ( get_children_per_first_parent ( ... |
def placeholder_plugin_filter ( self , request , queryset ) :
"""This is only used on models which use placeholders from the django - cms""" | if not request :
return queryset
if GLL . is_active :
return queryset . filter ( language = GLL . language_code )
return queryset |
def _iter_convert_to_object ( self , iterable ) :
"""Iterable yields tuples of ( binsha , mode , name ) , which will be converted
to the respective object representation""" | for binsha , mode , name in iterable :
path = join_path ( self . path , name )
try :
yield self . _map_id_to_type [ mode >> 12 ] ( self . repo , binsha , mode , path )
except KeyError :
raise TypeError ( "Unknown mode %o found in tree data for path '%s'" % ( mode , path ) ) |
def scramble_string ( s , key ) :
"""s is the puzzle ' s solution in column - major order , omitting black squares :
i . e . if the puzzle is :
C A T
solution is CATAR
Key is a 4 - digit number in the range 1000 < = key < = 9999""" | key = key_digits ( key )
for k in key : # foreach digit in the key
s = shift ( s , key )
# for each char by each digit in the key in sequence
s = s [ k : ] + s [ : k ]
# cut the sequence around the key digit
s = shuffle ( s )
# do a 1:1 shuffle of the ' deck '
return s |
def full_travel_count ( self ) :
"""Returns the number of tacho counts in the full travel of the motor . When
combined with the ` count _ per _ m ` atribute , you can use this value to
calculate the maximum travel distance of the motor . ( linear motors only )""" | ( self . _full_travel_count , value ) = self . get_cached_attr_int ( self . _full_travel_count , 'full_travel_count' )
return value |
def _kbos_from_survey_sym_model_input_file ( model_file ) :
"""Load a Survey Simulator model file as an array of ephem EllipticalBody objects .
@ param model _ file :
@ return :""" | lines = storage . open_vos_or_local ( model_file ) . read ( ) . split ( '\n' )
kbos = [ ]
for line in lines :
if len ( line ) == 0 or line [ 0 ] == '#' : # skip initial column descriptors and the final blank line
continue
kbo = ephem . EllipticalBody ( )
values = line . split ( )
kbo . name = va... |
def _initialize ( self , show_bounds , reset_camera , outline ) :
"""Outlines the input dataset and sets up the scene""" | self . plotter . subplot ( * self . loc )
if outline is None :
self . plotter . add_mesh ( self . input_dataset . outline_corners ( ) , reset_camera = False , color = vtki . rcParams [ 'outline_color' ] , loc = self . loc )
elif outline :
self . plotter . add_mesh ( self . input_dataset . outline ( ) , reset_ca... |
def mutate ( self , p_mutate ) :
"""Simulate mutation against a probability .
p _ mutate : probability for mutation to occur""" | new_dna = [ ]
for bit in self . dna :
if random . random ( ) < p_mutate :
new_bit = bit
while new_bit == bit :
new_bit = random . choice ( self . GENETIC_MATERIAL_OPTIONS )
bit = new_bit
new_dna . append ( bit )
self . dna = '' . join ( new_dna ) |
def import_locations ( self , zone_file ) :
"""Parse zoneinfo zone description data files .
` ` import _ locations ( ) ` ` returns a list of : class : ` Zone ` objects .
It expects data files in one of the following formats : :
AN + 1211-06900America / Curacao
AO - 0848 + 01314Africa / Luanda
AQ - 7750 + ... | self . _zone_file = zone_file
field_names = ( 'country' , 'location' , 'zone' , 'comments' )
data = utils . prepare_csv_read ( zone_file , field_names , delimiter = r" " )
for row in ( x for x in data if not x [ 'country' ] . startswith ( '#' ) ) :
if row [ 'comments' ] :
row [ 'comments' ] = row [ 'comment... |
def checar ( cliente_sat ) :
"""Checa em sequência os alertas registrados ( veja : func : ` registrar ` ) contra os
dados da consulta ao status operacional do equipamento SAT . Este método irá
então resultar em uma lista dos alertas ativos .
: param cliente _ sat : Uma instância de
: class : ` satcfe .... | resposta = cliente_sat . consultar_status_operacional ( )
alertas = [ ]
for classe_alerta in AlertaOperacao . alertas_registrados :
alerta = classe_alerta ( resposta )
if alerta . checar ( ) :
alertas . append ( alerta )
return alertas |
def create ( vm_ ) :
'''Create a single VM from a data dict
CLI Example :
. . code - block : : bash
salt - cloud - p proxmox - ubuntu vmhostname''' | try : # Check for required profile parameters before sending any API calls .
if vm_ [ 'profile' ] and config . is_profile_configured ( __opts__ , __active_provider_name__ or 'proxmox' , vm_ [ 'profile' ] , vm_ = vm_ ) is False :
return False
except AttributeError :
pass
ret = { }
__utils__ [ 'cloud.fire... |
def get_host ( self , endpoint_or_address ) :
"""Find a host in the metadata for a specific endpoint . If a string inet address is passed ,
iterate all hosts to match the : attr : ` ~ . pool . Host . broadcast _ rpc _ address ` attribute .""" | if not isinstance ( endpoint_or_address , EndPoint ) :
return self . _get_host_by_address ( endpoint_or_address )
return self . _hosts . get ( endpoint_or_address ) |
def send_message ( self , message , sign = True ) :
"""Send the given message to the connection .
@ type message : OmapiMessage
@ param sign : whether the message needs to be signed
@ raises OmapiError :
@ raises socket . error :""" | if sign :
message . sign ( self . authenticators [ self . defauth ] )
logger . debug ( "sending %s" , LazyStr ( message . dump_oneline ) )
self . transport . write ( message . as_string ( ) ) |
def tournament_name2number ( self , name ) :
"""Translate tournament name to tournament number .
Args :
name ( str ) : tournament name to translate
Returns :
number ( int ) : number of the tournament or ` None ` if unknown .
Examples :
> > > NumerAPI ( ) . tournament _ name2number ( ' delta ' )
> > > ... | tournaments = self . get_tournaments ( )
d = { t [ 'name' ] : t [ 'tournament' ] for t in tournaments }
return d . get ( name , None ) |
def set_rest_notification ( self , url , hit_type_id ) :
"""Set a REST endpoint to recieve notifications about the HIT
The newer AWS MTurk API does not support this feature , which means we
cannot use boto3 here . Instead , we make the call manually after
assembling a properly signed request .""" | ISO8601 = "%Y-%m-%dT%H:%M:%SZ"
notification_version = "2006-05-05"
API_version = "2014-08-15"
data = { "AWSAccessKeyId" : self . aws_key , "HITTypeId" : hit_type_id , "Notification.1.Active" : "True" , "Notification.1.Destination" : url , "Notification.1.EventType.1" : "AssignmentAccepted" , "Notification.1.EventType.2... |
def _toolkit_repr_print ( model , fields , section_titles , width = None ) :
"""Display a toolkit repr according to some simple rules .
Parameters
model : Turi Create model
fields : List of lists of tuples
Each tuple should be ( display _ name , field _ name ) , where field _ name can
be a string or a _ p... | assert len ( section_titles ) == len ( fields ) , "The number of section titles ({0}) " . format ( len ( section_titles ) ) + "doesn't match the number of groups of fields, {0}." . format ( len ( fields ) )
out_fields = [ ( "Class" , model . __class__ . __name__ ) , "" ]
# Record the max _ width so that if width is not... |
def callback ( self , filename , lines , ** kwargs ) :
"""publishes lines one by one to the given topic""" | timestamp = self . get_timestamp ( ** kwargs )
if kwargs . get ( 'timestamp' , False ) :
del kwargs [ 'timestamp' ]
for line in lines :
try :
import warnings
with warnings . catch_warnings ( ) :
warnings . simplefilter ( 'error' )
m = self . format ( filename , line , tim... |
def request_get_user ( self , user_ids ) -> dict :
"""Method to get users by ID , do not need authorization""" | method_params = { 'user_ids' : user_ids }
response = self . session . send_method_request ( 'users.get' , method_params )
self . check_for_errors ( 'users.get' , method_params , response )
return response |
def delete_consumer_group ( self , project , logstore , consumer_group ) :
"""Delete consumer group
: type project : string
: param project : project name
: type logstore : string
: param logstore : logstore name
: type consumer _ group : string
: param consumer _ group : consumer group name
: return ... | headers = { "x-log-bodyrawsize" : '0' }
params = { }
resource = "/logstores/" + logstore + "/consumergroups/" + consumer_group
( resp , header ) = self . _send ( "DELETE" , project , None , resource , params , headers )
return DeleteConsumerGroupResponse ( header , resp ) |
def validate_plugin ( self , plugin_class , experimental = False ) :
"""Verifies that the plugin _ class should execute under this policy""" | valid_subclasses = [ IndependentPlugin ] + self . valid_subclasses
if experimental :
valid_subclasses += [ ExperimentalPlugin ]
return any ( issubclass ( plugin_class , class_ ) for class_ in valid_subclasses ) |
def close ( self ) :
"""close an open connection""" | if not self . connected :
return True
self . _close ( )
self . connected = False
self . log ( "Closed Connection {}" , self . connection_config . interface_name )
return True |
def send_query ( self , ID , methodname , returnable , * args , ** kwargs ) :
"""将调用请求的ID , 方法名 , 参数包装为请求数据后编码为字节串发送出去 .
Parameters :
ID ( str ) : - 任务ID
methodname ( str ) : - 要调用的方法名
returnable ( bool ) : - 是否要求返回结果
args ( Any ) : - 要调用的方法的位置参数
kwargs ( Any ) : - 要调用的方法的关键字参数
Return :
( bool ) : -... | query = self . _make_query ( ID , methodname , returnable , * args , ** kwargs )
self . _send_query ( query )
self . tasks [ ID ] = self . loop . create_future ( )
return True |
def ssh_sa_ssh_server_mac ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ssh_sa = ET . SubElement ( config , "ssh-sa" , xmlns = "urn:brocade.com:mgmt:brocade-sec-services" )
ssh = ET . SubElement ( ssh_sa , "ssh" )
server = ET . SubElement ( ssh , "server" )
mac = ET . SubElement ( server , "mac" )
mac . text = kwargs . pop ( 'mac' )
callback = kwargs . po... |
def _parse_param ( key , val ) :
"""Parse the query param looking for sparse fields params
Ensure the ` val ` or what will become the sparse fields
is always an array . If the query param is not a sparse
fields query param then return None .
: param key :
the query parameter key in the request ( left of =... | regex = re . compile ( r'fields\[([A-Za-z]+)\]' )
match = regex . match ( key )
if match :
if not isinstance ( val , list ) :
val = val . split ( ',' )
fields = [ field . lower ( ) for field in val ]
rtype = match . groups ( ) [ 0 ] . lower ( )
return rtype , fields |
def camel_to_snake ( name ) :
"""http : / / stackoverflow . com / questions / 1175208/
elegant - python - function - to - convert - camelcase - to - camel - case""" | s1 = FIRST_CAP_RE . sub ( r'\1_\2' , name )
return ALL_CAP_RE . sub ( r'\1_\2' , s1 ) . lower ( ) |
def join_url_params ( dic ) :
"""根据传入的键值对 , 拼接 url 后面 ? 的参数 , 比如 ? key1 = value1 & key2 = value2
: param :
* dic : ( dict ) 参数键值对
: return :
* result : ( string ) 拼接好的参数
举例如下 : :
print ( ' - - - splice _ url _ params demo - - - ' )
dic1 = { ' key1 ' : ' value1 ' , ' key2 ' : ' value2 ' }
print ( spl... | od = OrderedDict ( sorted ( dic . items ( ) ) )
url = '?'
temp_str = urlencode ( od )
url = url + temp_str
return url |
def get_spherical_bounding_box ( lons , lats ) :
"""Given a collection of points find and return the bounding box ,
as a pair of longitudes and a pair of latitudes .
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays .
: return :
A tuple of fou... | north , south = numpy . max ( lats ) , numpy . min ( lats )
west , east = numpy . min ( lons ) , numpy . max ( lons )
assert ( - 180 <= west <= 180 ) and ( - 180 <= east <= 180 ) , ( west , east )
if get_longitudinal_extent ( west , east ) < 0 : # points are lying on both sides of the international date line
# ( meridi... |
def last_sleep_breakdown ( self ) :
"""Return durations of sleep stages for last complete session .""" | try :
stages = self . intervals [ 1 ] [ 'stages' ]
except KeyError :
return None
breakdown = { 'awake' : 0 , 'light' : 0 , 'deep' : 0 , 'rem' : 0 }
for stage in stages :
if stage [ 'stage' ] == 'awake' :
breakdown [ 'awake' ] += stage [ 'duration' ]
elif stage [ 'stage' ] == 'light' :
br... |
def matches ( self , spec ) :
"""Matches a specification against the current Plot .""" | if callable ( spec ) and not isinstance ( spec , type ) :
return spec ( self )
elif isinstance ( spec , type ) :
return isinstance ( self , spec )
else :
raise ValueError ( "Matching specs have to be either a type or a callable." ) |
def delete ( self , record ) :
"""Delete a record .
: param record : Record instance .""" | index , doc_type = self . record_to_index ( record )
return self . client . delete ( id = str ( record . id ) , index = index , doc_type = doc_type , ) |
def OnTimer ( self , event ) :
"""Update all frozen cells because of timer call""" | self . timer_updating = True
shape = self . grid . code_array . shape [ : 2 ]
selection = Selection ( [ ( 0 , 0 ) ] , [ ( shape ) ] , [ ] , [ ] , [ ] )
self . grid . actions . refresh_selected_frozen_cells ( selection )
self . grid . ForceRefresh ( ) |
def _extract_core_semantics ( self , docs ) :
"""Extracts core semantics for a list of documents , returning them along with
a list of all the concepts represented .""" | all_concepts = [ ]
doc_core_sems = [ ]
for doc in docs :
core_sems = self . _process_doc ( doc )
doc_core_sems . append ( core_sems )
all_concepts += [ con for con , weight in core_sems ]
return doc_core_sems , list ( set ( all_concepts ) ) |
def _encrypt ( self , archive ) :
"""Encrypts the compressed archive using GPG .
If encryption fails for any reason , it should be logged by sos but not
cause execution to stop . The assumption is that the unencrypted archive
would still be of use to the user , and / or that the end user has another
means o... | arc_name = archive . replace ( "sosreport-" , "secured-sosreport-" )
arc_name += ".gpg"
enc_cmd = "gpg --batch -o %s " % arc_name
env = None
if self . enc_opts [ "key" ] : # need to assume a trusted key here to be able to encrypt the
# archive non - interactively
enc_cmd += "--trust-model always -e -r %s " % self .... |
def file_transfer_protocol_send ( self , target_network , target_system , target_component , payload , force_mavlink1 = False ) :
'''File transfer message
target _ network : Network ID ( 0 for broadcast ) ( uint8 _ t )
target _ system : System ID ( 0 for broadcast ) ( uint8 _ t )
target _ component : Componen... | return self . send ( self . file_transfer_protocol_encode ( target_network , target_system , target_component , payload ) , force_mavlink1 = force_mavlink1 ) |
def jsonstrlen ( self , name , path = Path . rootPath ( ) ) :
"""Returns the length of the string JSON value under ` ` path ` ` at key
` ` name ` `""" | return self . execute_command ( 'JSON.STRLEN' , name , str_path ( path ) ) |
def _schemaPrepareInsert ( self , store ) :
"""Prepare each attribute in my schema for insertion into a given store ,
either by upgrade or by creation . This makes sure all references point
to this store and all relative paths point to this store ' s files
directory .""" | for name , atr in self . getSchema ( ) :
atr . prepareInsert ( self , store ) |
def maps_get_default_rules_output_rules_policyname ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
maps_get_default_rules = ET . Element ( "maps_get_default_rules" )
config = maps_get_default_rules
output = ET . SubElement ( maps_get_default_rules , "output" )
rules = ET . SubElement ( output , "rules" )
policyname = ET . SubElement ( rules , "policyname" )
policyname . text = kwar... |
def forward_lmm ( snps , pheno , K = None , covs = None , qvalues = False , threshold = 5e-8 , maxiter = 2 , test = 'lrt' , ** kw_args ) :
"""univariate fixed effects test with forward selection
Args :
snps : [ N x S ] SP . array of S SNPs for N individuals ( test SNPs )
pheno : [ N x 1 ] SP . array of 1 phen... | if K is None :
K = SP . eye ( snps . shape [ 0 ] )
if covs is None :
covs = SP . ones ( ( snps . shape [ 0 ] , 1 ) )
lm = simple_lmm ( snps , pheno , K = K , covs = covs , test = test , ** kw_args )
pvall = SP . zeros ( ( maxiter , snps . shape [ 1 ] ) )
pv = lm . getPv ( )
pvall [ 0 : 1 , : ] = pv
imin = pv . ... |
def create_widget ( self ) :
"""Create the underlying widget .
A dialog is not a subclass of view , hence we don ' t set name as widget
or children will try to use it as their parent .""" | d = self . declaration
style = d . style or '@style/Widget.DeviceDefault.PopupMenu'
self . window = PopupWindow ( self . get_context ( ) , None , 0 , style )
self . showing = False |
def channel_close ( self , registry_address : PaymentNetworkID , token_address : TokenAddress , partner_address : Address , retry_timeout : NetworkTimeout = DEFAULT_RETRY_TIMEOUT , ) :
"""Close a channel opened with ` partner _ address ` for the given
` token _ address ` .
Race condition , this can fail if chan... | self . channel_batch_close ( registry_address = registry_address , token_address = token_address , partner_addresses = [ partner_address ] , retry_timeout = retry_timeout , ) |
def right_click_high_equalarea ( self , event ) :
"""toggles between zoom and pan effects for the high equal area on
right click
Parameters
event : the wx . MouseEvent that triggered the call of this function
Alters
high _ EA _ setting , toolbar4 setting""" | if event . LeftIsDown ( ) :
return
elif self . high_EA_setting == "Zoom" :
self . high_EA_setting = "Pan"
try :
self . toolbar4 . pan ( 'off' )
except TypeError :
pass
elif self . high_EA_setting == "Pan" :
self . high_EA_setting = "Zoom"
try :
self . toolbar4 . zoom ( )
... |
def check_container ( self , container_path , container_format = None , config_string = None ) :
"""Check whether the given container is well - formed .
: param string container _ path : the path of the container to be checked
: param container _ format : the format of the container
: type container _ format ... | self . log ( [ u"Checking container '%s'" , container_path ] )
self . result = ValidatorResult ( )
if self . _are_safety_checks_disabled ( u"check_container" ) :
return self . result
if not ( gf . file_exists ( container_path ) or gf . directory_exists ( container_path ) ) :
self . _failed ( u"Container '%s' no... |
def _get_jwt_for_audience ( self , audience ) :
"""Get a JWT For a given audience .
If there is already an existing , non - expired token in the cache for
the audience , that token is used . Otherwise , a new token will be
created .
Args :
audience ( str ) : The intended audience .
Returns :
bytes : T... | token , expiry = self . _cache . get ( audience , ( None , None ) )
if token is None or expiry < _helpers . utcnow ( ) :
token , expiry = self . _make_jwt_for_audience ( audience )
self . _cache [ audience ] = token , expiry
return token |
def start_completion ( self , buffer_name = None , select_first = False , select_last = False , insert_common_part = False , complete_event = None ) :
"""Start asynchronous autocompletion of this buffer .
( This will do nothing if a previous completion was still in progress . )""" | buffer_name = buffer_name or self . current_buffer_name
completer = self . _async_completers . get ( buffer_name )
if completer :
completer ( select_first = select_first , select_last = select_last , insert_common_part = insert_common_part , complete_event = CompleteEvent ( completion_requested = True ) ) |
def create_ltp_package ( aleph_record , book_id , ebook_fn , data , url , urn_nbn = None ) :
"""Create LTP package as it is specified in specification v1.0 as I understand
it .
Args :
aleph _ record ( str ) : XML containing full aleph record .
book _ id ( str ) : UUID of the book .
ebook _ fn ( str ) : Or... | root_dir , orig_dir , meta_dir = _create_package_hierarchy ( book_id = book_id )
# create original file
original_fn = os . path . join ( orig_dir , fn_composers . original_fn ( book_id , ebook_fn ) )
with open ( original_fn , "wb" ) as f :
f . write ( data )
# create metadata files
metadata_filenames = [ ]
records ... |
def getVATAmount ( self ) :
"""Compute VAT Amount from the Price and system configured VAT""" | price , vat = self . getPrice ( ) , self . getVAT ( )
return float ( price ) * ( float ( vat ) / 100 ) |
def _set_traffic_class_exp_state ( self , v , load = False ) :
"""Setter method for traffic _ class _ exp _ state , mapped from YANG variable / traffic _ class _ exp _ state ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ traffic _ class _ exp _ state is c... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = traffic_class_exp_state . traffic_class_exp_state , is_container = 'container' , presence = False , yang_name = "traffic-class-exp-state" , rest_name = "traffic-class-exp-state" , parent = self , path_helper = self . _path_he... |
def do_round ( value , precision = 0 , method = 'common' ) :
"""Round the number to a given precision . The first
parameter specifies the precision ( default is ` ` 0 ` ` ) , the
second the rounding method :
- ` ` ' common ' ` ` rounds either up or down
- ` ` ' ceil ' ` ` always rounds up
- ` ` ' floor ' ... | if not method in ( 'common' , 'ceil' , 'floor' ) :
raise FilterArgumentError ( 'method must be common, ceil or floor' )
if method == 'common' :
return round ( value , precision )
func = getattr ( math , method )
return func ( value * ( 10 ** precision ) ) / ( 10 ** precision ) |
def get_current_user ( self , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # show - current - user""" | response = self . _get ( 'v2' , 'user' , params = params )
return self . _make_api_object ( response , CurrentUser ) |
def _process_pathway_disease ( self , limit ) :
"""We make a link between the pathway identifiers ,
and any diseases associated with them .
Since we model diseases as processes , we make a triple saying that
the pathway may be causally upstream of or within the disease process .
: param limit :
: return :... | LOG . info ( "Processing KEGG pathways to disease ids" )
if self . test_mode :
graph = self . testgraph
else :
graph = self . graph
line_counter = 0
raw = '/' . join ( ( self . rawdir , self . files [ 'pathway_disease' ] [ 'file' ] ) )
with open ( raw , 'r' , encoding = "iso-8859-1" ) as csvfile :
filereade... |
def get_Sb ( data ) :
"""returns vgp scatter for data set""" | Sb , N = 0. , 0.
for rec in data :
delta = 90. - abs ( rec [ 'vgp_lat' ] )
if rec [ 'average_k' ] != 0 :
k = rec [ 'average_k' ]
L = rec [ 'average_lat' ] * np . pi / 180.
# latitude in radians
Nsi = rec [ 'average_nn' ]
K = old_div ( k , ( 2. * ( 1. + 3. * np . sin ( L )... |
def datasets_update ( self , dataset_name , dataset_info ) :
"""Updates the Dataset info .
Args :
dataset _ name : the name of the dataset to update as a tuple of components .
dataset _ info : the Dataset resource with updated fields .""" | url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name )
return datalab . utils . Http . request ( url , method = 'PUT' , data = dataset_info , credentials = self . _credentials ) |
def main ( ) :
"""App entry point""" | # Check python version
if sys . version_info < ( 3 , 0 , 0 ) :
sys . stderr . write ( 'You need python 3.0 or later to run this script!' + os . linesep )
exit ( 1 )
# Generate requires
if platform . system ( ) == 'Windows' :
requirements_file = 'windows.txt'
else :
requirements_file = 'base.txt'
require... |
def execute ( self , stmt , args ) :
"""Execute a statement , returning a cursor . For internal use only .""" | self . logger ( stmt , args )
with self . cursor ( ) as cursor :
cursor . execute ( stmt , args )
return cursor |
def cluster ( dupes , threshold = .5 , max_components = 30000 ) :
'''Takes in a list of duplicate pairs and clusters them in to a
list records that all refer to the same entity based on a given
threshold
Keyword arguments :
threshold - - number betweent 0 and 1 ( default is . 5 ) . lowering the
number wil... | distance_threshold = 1 - threshold
dupe_sub_graphs = connected_components ( dupes , max_components )
for sub_graph in dupe_sub_graphs :
if len ( sub_graph ) > 1 :
i_to_id , condensed_distances , N = condensedDistance ( sub_graph )
linkage = fastcluster . linkage ( condensed_distances , method = 'cen... |
def estimate_umbrella_sampling ( us_trajs , us_dtrajs , us_centers , us_force_constants , md_trajs = None , md_dtrajs = None , kT = None , maxiter = 10000 , maxerr = 1.0E-15 , save_convergence_info = 0 , estimator = 'wham' , lag = 1 , dt_traj = '1 step' , init = None , init_maxiter = 10000 , init_maxerr = 1.0E-8 , widt... | from . util import get_umbrella_sampling_data as _get_umbrella_sampling_data
# sanity checks
if estimator not in [ 'wham' , 'mbar' , 'dtram' , 'tram' ] :
raise ValueError ( "unsupported estimator: %s" % estimator )
if not isinstance ( us_trajs , ( list , tuple ) ) :
raise ValueError ( "The parameter us_trajs mu... |
def get_api ( i ) :
"""Input : {
( path ) - path to module , if comes from access function
or
( module _ uoa ) - if comes from CMD
( func ) - func for API
( out ) - output
Output : {
return - return code = 0 , if successful
> 0 , if error
( error ) - error text if return > 0
title - title string... | p = i . get ( 'path' , '' )
f = i . get ( 'func' , '' )
o = i . get ( 'out' , '' )
muoa = i . get ( 'module_uoa' , '' )
t = ''
# last function description ( if redirect to another API )
t_orig = ''
# original function description
l = 0
# API line
a = ''
# accumulated API
if p == '' and muoa != '' :
rx = load ( { 'm... |
def _inputLine ( self , prompt , ** kwargs ) :
'Add prompt to bottom of screen and get line of input from user .' | self . inInput = True
rstatuslen = self . drawRightStatus ( self . scr , self . sheets [ 0 ] )
attr = 0
promptlen = clipdraw ( self . scr , self . windowHeight - 1 , 0 , prompt , attr , w = self . windowWidth - rstatuslen - 1 )
ret = self . editText ( self . windowHeight - 1 , promptlen , self . windowWidth - promptlen... |
def is_mass_balanced ( reaction ) :
"""Confirm that a reaction is mass balanced .""" | balance = defaultdict ( int )
for metabolite , coefficient in iteritems ( reaction . metabolites ) :
if metabolite . elements is None or len ( metabolite . elements ) == 0 :
return False
for element , amount in iteritems ( metabolite . elements ) :
balance [ element ] += coefficient * amount
ret... |
def match_file ( pattern , filename ) :
'''The function will match a pattern in a file and return
a rex object , which will have all the matches found in the file .''' | # Validate user data .
if pattern is None :
return None
if os . stat ( filename ) . st_size == 0 :
return None
rexobj = REX ( pattern , filename )
rexpatstr = reformat_pattern ( pattern )
# print " rexpatstr : " , rexpatstr
rexpat = re . compile ( rexpatstr )
rexobj . rex_patternstr = rexpatstr
rexobj . rex_pat... |
def remove ( self , key ) :
"""Clear a column value in the object . Note that this happens immediately :
it does not wait for save ( ) to be called .""" | payload = { key : { '__op' : 'Delete' } }
self . __class__ . PUT ( self . _absolute_url , ** payload )
del self . __dict__ [ key ] |
def add_untagged_ok ( self , text : MaybeBytes , code : Optional [ ResponseCode ] = None ) -> None :
"""Add an untagged ` ` OK ` ` response .
See Also :
: meth : ` . add _ untagged ` , : class : ` ResponseOk `
Args :
text : The response text .
code : Optional response code .""" | response = ResponseOk ( b'*' , text , code )
self . add_untagged ( response ) |
def match ( self , location ) :
"""Check if the given location " matches " .
: param location : The : class : ` Location ` object to try to match .
: returns : : data : ` True ` if the two locations are on the same system and
the : attr : ` directory ` can be matched as a filename pattern or
a literal match... | if self . ssh_alias != location . ssh_alias : # Never match locations on other systems .
return False
elif self . have_wildcards : # Match filename patterns using fnmatch ( ) .
return fnmatch . fnmatch ( location . directory , self . directory )
else : # Compare normalized directory pathnames .
self = os . ... |
def mtf_image_transformer_cifar_mp_4x ( ) :
"""Data parallel CIFAR parameters .""" | hparams = mtf_image_transformer_base_cifar ( )
hparams . mesh_shape = "model:4;batch:8"
hparams . layout = "batch:batch;d_ff:model;heads:model"
hparams . batch_size = 32
hparams . num_heads = 8
hparams . d_ff = 8192
return hparams |
def sync_hue_db ( self , * servers ) :
"""Synchronize the Hue server ' s database .
@ param servers : Name of Hue Server roles to synchronize . Not required starting with API v10.
@ return : List of submitted commands .""" | actual_version = self . _get_resource_root ( ) . version
if actual_version < 10 :
return self . _role_cmd ( 'hueSyncDb' , servers )
return self . _cmd ( 'hueSyncDb' , api_version = 10 ) |
def _concat ( self , egdfs ) :
"""Concatenate evaluated group dataframes
Parameters
egdfs : iterable
Evaluated dataframes
Returns
edata : pandas . DataFrame
Evaluated data""" | egdfs = list ( egdfs )
edata = pd . concat ( egdfs , axis = 0 , ignore_index = False , copy = False )
# groupby can mixup the rows . We try to maintain the original
# order , but we can only do that if the result has a one to
# one relationship with the original
one2one = ( self . keep_index and not any ( edata . index... |
def file_resolve ( backend , filepath ) :
"""Mark a conflicted file as resolved , so that a merge can be completed""" | recipe = DKRecipeDisk . find_recipe_name ( )
if recipe is None :
raise click . ClickException ( 'You must be in a recipe folder.' )
click . secho ( "%s - Resolving conflicts" % get_datetime ( ) )
for file_to_resolve in filepath :
if not os . path . exists ( file_to_resolve ) :
raise click . ClickExcepti... |
def callback_url ( self , request ) :
"""the url to go back after the external service call
: param request : contains the current session
: type request : dict
: rtype : string""" | service = self . service . split ( 'Service' ) [ 1 ] . lower ( )
return_to = '{service}_callback' . format ( service = service )
return '%s://%s%s' % ( request . scheme , request . get_host ( ) , reverse ( return_to ) ) |
def is_purrlog ( path ) :
"""Checks if path refers to a valid purrlog .
Path must exist , and must contain either at least one directory called entry - YYYYMMDD - HHMMSS , or the file " dirconfig " """ | if not os . path . isdir ( path ) :
return False
if list ( filter ( os . path . isdir , glob . glob ( os . path . join ( path , "entry-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]" ) ) ) ) :
return True
return os . path . exists ( os . path . join ( path , "dirconfig" ) ) |
def loss ( args ) :
"""% prog loss a . b . i1 . blocks [ a . b - genomic . blast ]
Extract likely gene loss candidates between genome a and b .""" | p = OptionParser ( loss . __doc__ )
p . add_option ( "--bed" , default = False , action = "store_true" , help = "Genomic BLAST is in bed format [default: %default]" )
p . add_option ( "--gdist" , default = 20 , type = "int" , help = "Gene distance [default: %default]" )
p . add_option ( "--bdist" , default = 20000 , ty... |
def search_lxc_bridges ( ) :
'''Search which bridges are potentially available as LXC bridges
CLI Example :
. . code - block : : bash
salt ' * ' lxc . search _ lxc _ bridges''' | bridges = __context__ . get ( 'lxc.bridges' , None )
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges :
bridges = set ( )
running_bridges = set ( )
bridges . add ( DEFAULT_BR )
try :
output = __salt__ [ 'cm... |
def get_raw_data ( self , times = 5 ) :
"""do some readings and aggregate them using the defined statistics function
: param times : how many measures to aggregate
: type times : int
: return : the aggregate of the measured values
: rtype float""" | self . _validate_measure_count ( times )
data_list = [ ]
while len ( data_list ) < times :
data = self . _read ( )
if data not in [ False , - 1 ] :
data_list . append ( data )
return data_list |
def read_in_config ( self ) :
"""Vyper will discover and load the configuration file from disk
and key / value stores , searching in one of the defined paths .""" | log . info ( "Attempting to read in config file" )
if self . _get_config_type ( ) not in constants . SUPPORTED_EXTENSIONS :
raise errors . UnsupportedConfigError ( self . _get_config_type ( ) )
with open ( self . _get_config_file ( ) ) as fp :
f = fp . read ( )
self . _config = { }
return self . _unmarshall_rea... |
def extract_frame ( self ) :
"""Pulls one complete frame off the buffer and returns it .
If there is no complete message in the buffer , returns None .
Note that the buffer can contain more than once message . You
should therefore call this method in a loop ( or use iterator
functionality exposed by class )... | # ( mbytes , hbytes ) = self . _ find _ message _ bytes ( self . buffer )
# if not mbytes :
# return None
# msgdata = self . buffer [ : mbytes ]
# self . buffer = self . buffer [ mbytes : ]
# hdata = msgdata [ : hbytes ]
# # Strip off any leading whitespace from headers ; this is necessary , because
# # we do not ( any... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.