signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def ping ( self ) :
"""Return true if the server successfully pinged""" | randomToken = '' . join ( random . choice ( string . ascii_uppercase + string . ascii_lowercase + string . digits ) for x in range ( 32 ) )
r = self . doQuery ( 'ping?data=' + randomToken )
if r . status_code == 200 : # Query ok ?
if r . json ( ) [ 'data' ] == randomToken : # Token equal ?
return True
retur... |
def init_signal ( self ) :
"""allow clean shutdown on sigint""" | signal . signal ( signal . SIGINT , lambda sig , frame : self . exit ( - 2 ) )
# need a timer , so that QApplication doesn ' t block until a real
# Qt event fires ( can require mouse movement )
# timer trick from http : / / stackoverflow . com / q / 4938723/938949
timer = QtCore . QTimer ( )
# Let the interpreter run e... |
def hexdump ( src , length = 8 ) :
"""Produce a string hexdump of src , for debug output .""" | if not src :
return str ( src )
src = input_validate_str ( src , 'src' )
offset = 0
result = ''
for this in group ( src , length ) :
hex_s = ' ' . join ( [ "%02x" % ord ( x ) for x in this ] )
result += "%04X %s\n" % ( offset , hex_s )
offset += length
return result |
def resolve ( cls , propname , objcls = None ) :
'''resolve type of the class property for the class . If objcls is not set then
assume that cls argument ( class that the function is called from ) is the class
we are trying to resolve the type for
: param cls :
: param objcls :
: param propname :''' | # object class is not given
if objcls is None :
objcls = cls
# get type
typemap = cls . _types . get ( objcls )
if ( typemap is not None ) : # nothing registered for this property
return typemap . get ( propname , None )
# type map didn ' t exist so none
return None |
def create_widget ( self ) :
"""Create the underlying widget .""" | d = self . declaration
self . widget = Chronometer ( self . get_context ( ) , None , d . style ) |
def get_table_names_by_filter ( self , dbname , filter , max_tables ) :
"""Parameters :
- dbname
- filter
- max _ tables""" | self . send_get_table_names_by_filter ( dbname , filter , max_tables )
return self . recv_get_table_names_by_filter ( ) |
async def _process_latching ( self , key , latching_entry ) :
"""This is a private utility method .
This method process latching events and either returns them via
callback or stores them in the latch map
: param key : Encoded pin
: param latching _ entry : a latch table entry
: returns : Callback or stor... | if latching_entry [ Constants . LATCH_CALLBACK ] : # auto clear entry and execute the callback
if latching_entry [ Constants . LATCH_CALLBACK_TYPE ] :
await latching_entry [ Constants . LATCH_CALLBACK ] ( [ key , latching_entry [ Constants . LATCHED_DATA ] , time . time ( ) ] )
# noinspection PyPep8
... |
def write ( self , output = None ) :
"""Write association table to a file .""" | if not output :
outfile = self [ 'output' ] + '_asn.fits'
output = self [ 'output' ]
else :
outfile = output
# Delete the file if it exists .
if os . path . exists ( outfile ) :
warningmsg = "\n#########################################\n"
warningmsg += "# #\n"
... |
def _HostPrefix ( client_id ) :
"""Build a host prefix for a notification message based on a client id .""" | if not client_id :
return ""
hostname = None
if data_store . RelationalDBEnabled ( ) :
client_snapshot = data_store . REL_DB . ReadClientSnapshot ( client_id )
if client_snapshot :
hostname = client_snapshot . knowledge_base . fqdn
else :
client_fd = aff4 . FACTORY . Open ( client_id , mode = "r... |
def user_query ( username , email ) :
"""Find a user match with username and email
: param username :
: param email :
: returns :""" | query = db . query ( User )
if username :
query = query . filter_by ( username = username )
if email :
query = query . filter_by ( username = username )
return query |
def multchoicebox ( msg = "Pick as many items as you like." , title = " " , choices = ( ) , ** kwargs ) :
"""Present the user with a list of choices .
allow him to select multiple items and return them in a list .
if the user doesn ' t choose anything from the list , return the empty list .
return None if he ... | if len ( choices ) == 0 :
choices = [ "Program logic error - no choices were specified." ]
global __choiceboxMultipleSelect
__choiceboxMultipleSelect = 1
return __choicebox ( msg , title , choices ) |
def security_group_delete ( auth = None , ** kwargs ) :
'''Delete a security group
name _ or _ id
The name or unique ID of the security group
CLI Example :
. . code - block : : bash
salt ' * ' neutronng . security _ group _ delete name _ or _ id = secgroup1''' | cloud = get_operator_cloud ( auth )
kwargs = _clean_kwargs ( ** kwargs )
return cloud . delete_security_group ( ** kwargs ) |
def stop ( self , actor , exc = None , exit_code = None ) :
"""Gracefully stop the ` ` actor ` ` .""" | if actor . state <= ACTOR_STATES . RUN : # The actor has not started the stopping process . Starts it now .
actor . state = ACTOR_STATES . STOPPING
actor . event ( 'start' ) . clear ( )
if exc :
if not exit_code :
exit_code = getattr ( exc , 'exit_code' , 1 )
if exit_code == 1 :
... |
def make ( world_name , gl_version = GL_VERSION . OPENGL4 , window_res = None , cam_res = None , verbose = False ) :
"""Creates a holodeck environment using the supplied world name .
Args :
world _ name ( str ) : The name of the world to load as an environment . Must match the name of a world in an
installed ... | holodeck_worlds = _get_worlds_map ( )
if world_name not in holodeck_worlds :
raise HolodeckException ( "Invalid World Name" )
param_dict = copy ( holodeck_worlds [ world_name ] )
param_dict [ "start_world" ] = True
param_dict [ "uuid" ] = str ( uuid . uuid4 ( ) )
param_dict [ "gl_version" ] = gl_version
param_dict ... |
def write_file_list_cache ( opts , data , list_cache , w_lock ) :
'''Checks the cache file to see if there is a new enough file list cache , and
returns the match ( if found , along with booleans used by the fileserver
backend to determine if the cache needs to be refreshed / written ) .''' | serial = salt . payload . Serial ( opts )
with salt . utils . files . fopen ( list_cache , 'w+b' ) as fp_ :
fp_ . write ( serial . dumps ( data ) )
_unlock_cache ( w_lock )
log . trace ( 'Lockfile %s removed' , w_lock ) |
def _register_plotter ( cls , identifier , module , plotter_name , plotter_cls = None ) :
"""Register a plotter in the : class : ` Project ` class to easy access it
Parameters
identifier : str
Name of the attribute that is used to filter for the instances
belonging to this plotter
module : str
The modul... | if plotter_cls is not None : # plotter has already been imported
def get_x ( self ) :
return self ( plotter_cls )
else :
def get_x ( self ) :
return self ( getattr ( import_module ( module ) , plotter_name ) )
setattr ( cls , identifier , property ( get_x , doc = ( "List of data arrays that are ... |
def allPolygons ( self ) :
"""Return a list of all polygons in this BSP tree .""" | polygons = self . polygons [ : ]
if self . front :
polygons . extend ( self . front . allPolygons ( ) )
if self . back :
polygons . extend ( self . back . allPolygons ( ) )
return polygons |
def insert_sequences_into_tree ( aln , moltype , params = { } ) :
"""Returns a tree from placement of sequences""" | # convert aln to phy since seq _ names need fixed to run through parsinsert
new_aln = get_align_for_phylip ( StringIO ( aln ) )
# convert aln to fasta in case it is not already a fasta file
aln2 = Alignment ( new_aln )
seqs = aln2 . toFasta ( )
parsinsert_app = ParsInsert ( params = params )
result = parsinsert_app ( s... |
async def purge ( self , * , limit = 100 , check = None , before = None , after = None , around = None , oldest_first = False , bulk = True ) :
"""| coro |
Purges a list of messages that meet the criteria given by the predicate
` ` check ` ` . If a ` ` check ` ` is not provided then all messages are deleted
w... | if check is None :
check = lambda m : True
iterator = self . history ( limit = limit , before = before , after = after , oldest_first = oldest_first , around = around )
ret = [ ]
count = 0
minimum_time = int ( ( time . time ( ) - 14 * 24 * 60 * 60 ) * 1000.0 - 1420070400000 ) << 22
strategy = self . delete_messages... |
def fit ( self , X , * args , ** kwargs ) :
"""Fit scipy model to an array of values .
Args :
X ( ` np . ndarray ` or ` pd . DataFrame ` ) : Datapoints to be estimated from . Must be 1 - d
Returns :
None""" | self . constant_value = self . _get_constant_value ( X )
if self . constant_value is None :
if self . unfittable_model :
self . model = getattr ( scipy . stats , self . model_class ) ( * args , ** kwargs )
else :
self . model = getattr ( scipy . stats , self . model_class ) ( X , * args , ** kwa... |
def encode ( data ) :
'''bytes - > str''' | if riemann . network . CASHADDR_PREFIX is None :
raise ValueError ( 'Network {} does not support cashaddresses.' . format ( riemann . get_current_network_name ( ) ) )
data = convertbits ( data , 8 , 5 )
checksum = calculate_checksum ( riemann . network . CASHADDR_PREFIX , data )
payload = b32encode ( data + checksu... |
def normalize ( self , dt , is_dst = False ) :
"""Correct the timezone information on the given datetime""" | if dt . tzinfo is self :
return dt
if dt . tzinfo is None :
raise ValueError ( 'Naive time - no tzinfo set' )
return dt . astimezone ( self ) |
def posthoc_dscf ( a , val_col = None , group_col = None , sort = False ) :
'''Dwass , Steel , Critchlow and Fligner all - pairs comparison test for a
one - factorial layout with non - normally distributed residuals . As opposed to
the all - pairs comparison procedures that depend on Kruskal ranks , the DSCF
... | x , _val_col , _group_col = __convert_to_df ( a , val_col , group_col )
if not sort :
x [ _group_col ] = Categorical ( x [ _group_col ] , categories = x [ _group_col ] . unique ( ) , ordered = True )
x . sort_values ( by = [ _group_col ] , ascending = True , inplace = True )
groups = np . unique ( x [ _group_col ] ... |
def top2_full ( votes ) :
"""Description :
Top 2 alternatives 16 moment conditions values calculation
Parameters :
votes : ordinal preference data ( numpy ndarray of integers )""" | res = np . zeros ( 16 )
for vote in votes : # the top ranked alternative is in vote [ 0 ] [ 0 ] , second in vote [ 1 ] [ 0]
if vote [ 0 ] [ 0 ] == 0 : # i . e . the first alt is ranked first
res [ 0 ] += 1
if vote [ 1 ] [ 0 ] == 1 : # i . e . the second alt is ranked second
res [ 4 ] += ... |
def unit_tangent ( self , t = None ) :
"""returns the unit tangent of the segment at t .""" | assert self . end != self . start
dseg = self . end - self . start
return dseg / abs ( dseg ) |
def _execute_data_download ( self , data_filter , redownload , max_threads , raise_download_errors ) :
"""Calls download module and executes the download process
: param data _ filter : Used to specify which items will be returned by the method and in which order . E . g . with
` data _ filter = [ 0 , 2 , - 1 ]... | is_repeating_filter = False
if data_filter is None :
filtered_download_list = self . download_list
elif isinstance ( data_filter , ( list , tuple ) ) :
try :
filtered_download_list = [ self . download_list [ index ] for index in data_filter ]
except IndexError :
raise IndexError ( 'Indices o... |
def setup_toolbar ( self ) :
"""Setup the toolbar""" | savefig_btn = create_toolbutton ( self , icon = ima . icon ( 'filesave' ) , tip = _ ( "Save Image As..." ) , triggered = self . save_figure )
saveall_btn = create_toolbutton ( self , icon = ima . icon ( 'save_all' ) , tip = _ ( "Save All Images..." ) , triggered = self . save_all_figures )
copyfig_btn = create_toolbutt... |
def download_stories ( self , userids : Optional [ List [ Union [ int , Profile ] ] ] = None , fast_update : bool = False , filename_target : Optional [ str ] = ':stories' , storyitem_filter : Optional [ Callable [ [ StoryItem ] , bool ] ] = None ) -> None :
"""Download available stories from user followees or all ... | if not userids :
self . context . log ( "Retrieving all visible stories..." )
else :
userids = [ p if isinstance ( p , int ) else p . userid for p in userids ]
for user_story in self . get_stories ( userids ) :
name = user_story . owner_username
self . context . log ( "Retrieving stories from profile {}... |
def complementTab ( seq = [ ] ) :
"""returns a list of complementary sequence without inversing it""" | complement = { 'A' : 'T' , 'C' : 'G' , 'G' : 'C' , 'T' : 'A' , 'R' : 'Y' , 'Y' : 'R' , 'M' : 'K' , 'K' : 'M' , 'W' : 'W' , 'S' : 'S' , 'B' : 'V' , 'D' : 'H' , 'H' : 'D' , 'V' : 'B' , 'N' : 'N' , 'a' : 't' , 'c' : 'g' , 'g' : 'c' , 't' : 'a' , 'r' : 'y' , 'y' : 'r' , 'm' : 'k' , 'k' : 'm' , 'w' : 'w' , 's' : 's' , 'b' :... |
def sheardec2D ( X , shearletsystem ) :
"""Shearlet Decomposition function .""" | coeffs = np . zeros ( shearletsystem . shearlets . shape , dtype = complex )
Xfreq = fftshift ( fft2 ( ifftshift ( X ) ) )
for i in range ( shearletsystem . nShearlets ) :
coeffs [ : , : , i ] = fftshift ( ifft2 ( ifftshift ( Xfreq * np . conj ( shearletsystem . shearlets [ : , : , i ] ) ) ) )
return coeffs . real |
def read_links_file ( self , file_path ) :
'''Read links and associated categories for specified articles
in text file seperated by a space
Args :
file _ path ( str ) : The path to text file with news article links
and category
Returns :
articles : Array of tuples that contains article link & cateogory ... | articles = [ ]
with open ( file_path ) as f :
for line in f :
line = line . strip ( )
# Ignore blank lines
if len ( line ) != 0 :
link , category = line . split ( ' ' )
articles . append ( ( category . rstrip ( ) , link . strip ( ) ) )
return articles |
def _repr_html_ ( self ) :
"""Give a nice representation of tables in notebooks .""" | out = "<table class='taqltable' style='overflow-x:auto'>\n"
# Print column names ( not if they are all auto - generated )
if not ( all ( [ colname [ : 4 ] == "Col_" for colname in self . colnames ( ) ] ) ) :
out += "<tr>"
for colname in self . colnames ( ) :
out += "<th><b>" + colname + "</b></th>"
... |
def rhombus_polygon ( self , X , Y , str_id , hor_size , vert_size ) :
"""Draw a rhombus polygon .
Horizontal size ( - hor _ size , + hor _ size ) and
vertical size ( - vert _ size , + vert _ size ) .
with its center on position X , Y
and with its str _ id as text in the middle .""" | x0 , y0 = X - hor_size , Y
# mid _ west
x1 , y1 = X , Y - vert_size
# mid _ north
x2 , y2 = X + hor_size , Y
# mid _ east
x3 , y3 = X , Y + vert_size
# mid _ south
polygon = SvgPolygon ( 4 )
polygon . set_stroke ( width = 2 , color = 'black' )
poly_name = gui . SvgText ( X , Y + 5 , str_id )
poly_name . attributes [ 't... |
def s3_list ( s3_bucket , s3_access_key_id , s3_secret_key , prefix = None ) :
"""Lists the contents of the S3 bucket that end in . tbz and match
the passed prefix , if any .""" | bucket = s3_connect ( s3_bucket , s3_access_key_id , s3_secret_key )
return sorted ( [ key . name for key in bucket . list ( ) if key . name . endswith ( ".tbz" ) and ( prefix is None or key . name . startswith ( prefix ) ) ] ) |
def send_password_change_message ( self , user , base_url ) :
"""Send password change message""" | subject = 'Change your password here'
if 'password_change' in self . email_subjects . keys ( ) :
subject = self . email_subjects [ 'password_change' ]
sender = current_app . config [ 'MAIL_DEFAULT_SENDER' ]
recipient = user . email
link = '{url}/{link}/' . format ( url = base_url . rstrip ( '/' ) , link = user . pa... |
def compute_bearing ( start_lat , start_lon , end_lat , end_lon ) :
'''Get the compass bearing from start to end .
Formula from
http : / / www . movable - type . co . uk / scripts / latlong . html''' | # make sure everything is in radians
start_lat = math . radians ( start_lat )
start_lon = math . radians ( start_lon )
end_lat = math . radians ( end_lat )
end_lon = math . radians ( end_lon )
dLong = end_lon - start_lon
dPhi = math . log ( math . tan ( end_lat / 2.0 + math . pi / 4.0 ) / math . tan ( start_lat / 2.0 +... |
def setup_scheduler ( self , before_connect = False ) :
'''Set up the scheduler .
This is safe to call multiple times .''' | self . _setup_core ( )
loop_interval = self . opts [ 'loop_interval' ]
new_periodic_callbacks = { }
if 'schedule' not in self . periodic_callbacks :
if 'schedule' not in self . opts :
self . opts [ 'schedule' ] = { }
if not hasattr ( self , 'schedule' ) :
self . schedule = salt . utils . schedul... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'consumption_preference_id' ) and self . consumption_preference_id is not None :
_dict [ 'consumption_preference_id' ] = self . consumption_preference_id
if hasattr ( self , 'name' ) and self . name is not None :
_dict [ 'name' ] = self . name
if hasattr ( self , 'score' ) and se... |
def floordiv ( x , y , context = None ) :
"""Return the floor of ` ` x ` ` divided by ` ` y ` ` .
The result is a ` ` BigFloat ` ` instance , rounded to the
context if necessary . Special cases match those of the
` ` div ` ` function .""" | return _apply_function_in_current_context ( BigFloat , mpfr_floordiv , ( BigFloat . _implicit_convert ( x ) , BigFloat . _implicit_convert ( y ) , ) , context , ) |
def enrich ( args ) :
"""% prog enrich omgfile groups ntaxa > enriched . omg
Enrich OMG output by pulling genes misses by OMG .""" | p = OptionParser ( enrich . __doc__ )
p . add_option ( "--ghost" , default = False , action = "store_true" , help = "Add ghost homologs already used [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 3 :
sys . exit ( not p . print_help ( ) )
omgfile , groupsfile , ntaxa = args
ntaxa = i... |
def upload_asset ( self , content_type , name , asset ) :
"""Upload an asset to this release .
All parameters are required .
: param str content _ type : The content type of the asset . Wikipedia has
a list of common media types
: param str name : The name of the file
: param asset : The file or bytes obj... | headers = Release . CUSTOM_HEADERS . copy ( )
headers . update ( { 'Content-Type' : content_type } )
url = self . upload_urlt . expand ( { 'name' : name } )
r = self . _post ( url , data = asset , json = False , headers = headers , verify = False )
if r . status_code in ( 201 , 202 ) :
return Asset ( r . json ( ) ,... |
def _require_staff_for_shared_settings ( request , view , obj = None ) :
"""Allow to execute action only if service settings are not shared or user is staff""" | if obj is None :
return
if obj . settings . shared and not request . user . is_staff :
raise PermissionDenied ( _ ( 'Only staff users are allowed to import resources from shared services.' ) ) |
def from_section ( cls , stream , section_name = '.pic' ) :
"""Construct a Converter object from the specified section
of the specified binary stream .""" | binary = Executable ( stream )
section_data = binary . get_section_data ( section_name )
return cls ( section_data , binary . system ) |
def evaluate_forward ( distribution , x_data , parameters = None , cache = None , ) :
"""Evaluate forward Rosenblatt transformation .
Args :
distribution ( Dist ) :
Distribution to evaluate .
x _ data ( numpy . ndarray ) :
Locations for where evaluate forward transformation at .
parameters ( : py : data... | assert len ( x_data ) == len ( distribution ) , ( "distribution %s is not of length %d" % ( distribution , len ( x_data ) ) )
assert hasattr ( distribution , "_cdf" ) , ( "distribution require the `_cdf` method to function." )
cache = cache if cache is not None else { }
parameters = load_parameters ( distribution , "_c... |
def _execute ( self , connection , query , fetch = True ) :
"""Executes given query and returns result .
Args :
connection : connection to postgres database who stores mpr data .
query ( str ) : sql query
fetch ( boolean , optional ) : if True , fetch query result and return it . If False , do not fetch .
... | # execute query
with connection . cursor ( ) as cursor :
cursor . execute ( query )
if fetch :
return cursor . fetchall ( )
else :
cursor . execute ( 'COMMIT;' ) |
def save_parameters ( self , filename ) :
"""Save model
Parameters
filename : str
path to model file""" | params = self . _collect_params_with_prefix ( )
if self . pret_word_embs : # don ' t save word embeddings inside model
params . pop ( 'pret_word_embs.weight' , None )
arg_dict = { key : val . _reduce ( ) for key , val in params . items ( ) }
ndarray . save ( filename , arg_dict ) |
def record ( self , * args , ** kwargs ) :
"""Track and record values each day .
Parameters
* * kwargs
The names and values to record .
Notes
These values will appear in the performance packets and the performance
dataframe passed to ` ` analyze ` ` and returned from
: func : ` ~ zipline . run _ algor... | # Make 2 objects both referencing the same iterator
args = [ iter ( args ) ] * 2
# Zip generates list entries by calling ` next ` on each iterator it
# receives . In this case the two iterators are the same object , so the
# call to next on args [ 0 ] will also advance args [ 1 ] , resulting in zip
# returning ( a , b ... |
def query_list_pager ( con , idx , kind = '2' ) :
'''Get records of certain pager .''' | all_list = MPost . query_under_condition ( con , kind = kind )
return all_list [ ( idx - 1 ) * CMS_CFG [ 'list_num' ] : idx * CMS_CFG [ 'list_num' ] ] |
def bind ( self , study , ** kwargs ) : # @ UnusedVariable
"""Used for duck typing Collection objects with Spec and Match
in source and sink initiation . Checks IDs match sessions in study .""" | if self . frequency == 'per_subject' :
tree_subject_ids = list ( study . tree . subject_ids )
subject_ids = list ( self . _collection . keys ( ) )
if tree_subject_ids != subject_ids :
raise ArcanaUsageError ( "Subject IDs in collection provided to '{}' ('{}') " "do not match Study tree ('{}')" . for... |
def shrink_to_node ( self , scc ) :
"""Shrink a strongly connected component into a node .""" | assert not self . final , 'Trying to mutate a final graph.'
self . graph . add_node ( scc )
edges = list ( self . graph . edges )
for k , v in edges :
if k not in scc and v in scc :
self . graph . remove_edge ( k , v )
self . graph . add_edge ( k , scc )
elif k in scc and v not in scc :
... |
def render_sparktext ( self , relative_to = None ) :
"""Make a mini text sparkline from chart""" | bars = u ( '▁▂▃▄▅▆▇█' )
if len ( self . raw_series ) == 0 :
return u ( '' )
values = list ( self . raw_series [ 0 ] [ 0 ] )
if len ( values ) == 0 :
return u ( '' )
chart = u ( '' )
values = list ( map ( lambda x : max ( x , 0 ) , values ) )
vmax = max ( values )
if relative_to is None :
relative_to = min (... |
async def SetMachineAddresses ( self , machine_addresses ) :
'''machine _ addresses : typing . Sequence [ ~ MachineAddresses ]
Returns - > typing . Sequence [ ~ ErrorResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'Machiner' , request = 'SetMachineAddresses' , version = 1 , params = _params )
_params [ 'machine-addresses' ] = machine_addresses
reply = await self . rpc ( msg )
return reply |
def get_ncbi_taxon_num_by_label ( label ) :
"""Here we want to look up the NCBI Taxon id using some kind of label .
It will only return a result if there is a unique hit .
: return :""" | req = { 'db' : 'taxonomy' , 'retmode' : 'json' , 'term' : label }
req . update ( EREQ )
request = SESSION . get ( ESEARCH , params = req )
LOG . info ( 'fetching: %s' , request . url )
request . raise_for_status ( )
result = request . json ( ) [ 'esearchresult' ]
# Occasionally eutils returns the json blob
# { ' ERROR ... |
def _track_modify ( self , cls , name , detail , keep , trace ) :
"""Modify settings of a tracked class""" | self . _observers [ cls ] . modify ( name , detail , keep , trace ) |
def similar_items ( self , itemid , N = 10 ) :
"""Returns a list of the most similar other items""" | if itemid >= self . similarity . shape [ 0 ] :
return [ ]
return sorted ( list ( nonzeros ( self . similarity , itemid ) ) , key = lambda x : - x [ 1 ] ) [ : N ] |
def create ( self , request , * args , ** kwargs ) :
"""A new project can be created by users with staff privilege ( is _ staff = True ) or customer owners .
Project resource quota is optional . Example of a valid request :
. . code - block : : http
POST / api / projects / HTTP / 1.1
Content - Type : applic... | return super ( ProjectViewSet , self ) . create ( request , * args , ** kwargs ) |
def is_docstring ( node ) :
"""Returns True if the node appears to be a docstring""" | return ( node . type == syms . simple_stmt and len ( node . children ) > 0 and node . children [ 0 ] . type == token . STRING ) |
def _prepare_general_arguments ( RRTMGobject ) :
'''Prepare arguments needed for both RRTMG _ SW and RRTMG _ LW with correct dimensions .''' | tlay = _climlab_to_rrtm ( RRTMGobject . Tatm )
tlev = _climlab_to_rrtm ( interface_temperature ( ** RRTMGobject . state ) )
play = _climlab_to_rrtm ( RRTMGobject . lev * np . ones_like ( tlay ) )
plev = _climlab_to_rrtm ( RRTMGobject . lev_bounds * np . ones_like ( tlev ) )
ncol , nlay = tlay . shape
tsfc = _climlab_to... |
def memset ( self , allocation , value , size ) :
"""set the memory in allocation to the value in value
: param allocation : An Argument for some memory allocation unit
: type allocation : Argument
: param value : The value to set the memory to
: type value : a single 8 - bit unsigned int
: param size : T... | C . memset ( allocation . ctypes , value , size ) |
def request ( self , path , method = 'GET' , params = None ) :
"""Builds a request and gets a response .""" | if params is None :
params = { }
url = urljoin ( self . endpoint , path )
headers = { 'Accept' : 'application/json' , 'Authorization' : 'AccessKey ' + self . access_key , 'User-Agent' : self . user_agent , 'Content-Type' : 'application/json' }
if method == 'DELETE' :
response = requests . delete ( url , verify ... |
def create_model ( modelfunc , fname = '' , listw = [ ] , outfname = '' , limit = int ( 3e6 ) , min_pwlen = 6 , topk = 10000 , sep = r'\s+' ) :
""": modelfunc : is a function that takes a word and returns its
splits . for ngram model this function returns all the ngrams of a
word , for PCFG it will return split... | def length_filter ( pw ) :
pw = '' . join ( c for c in pw if c in VALID_CHARS )
return len ( pw ) >= min_pwlen
pws = [ ]
if fname :
pws = helper . open_get_line ( fname , limit = limit , pw_filter = length_filter , sep = sep )
big_dict = defaultdict ( int )
total_f , total_e = 0 , 0
# Add topk passwords fro... |
def editColormap ( self ) :
"""Prompts the user with a dialog to change colormap""" | self . editor = pg . ImageView ( )
# remove the ROI and Norm buttons
self . editor . ui . roiBtn . setVisible ( False )
self . editor . ui . menuBtn . setVisible ( False )
self . editor . setImage ( self . imageArray )
if self . imgArgs [ 'state' ] is not None :
self . editor . getHistogramWidget ( ) . item . gradi... |
def create ( self , label = None , name = None , critical_state = None , ok_state = None , warning_state = None ) :
"""Creates a notification plan to be executed when a monitoring check
triggers an alarm . You can optionally label ( or name ) the plan .
A plan consists of one or more notifications to be execute... | uri = "/%s" % self . uri_base
body = { "label" : label or name }
def make_list_of_ids ( parameter ) :
params = utils . coerce_to_list ( parameter )
return [ utils . get_id ( param ) for param in params ]
if critical_state :
critical_state = utils . coerce_to_list ( critical_state )
body [ "critical_stat... |
def close ( self ) :
"""Close the connection
: raises : ConnectionBusyError""" | LOGGER . debug ( 'Connection %s closing' , self . id )
if self . busy :
raise ConnectionBusyError ( self )
with self . _lock :
if not self . handle . closed :
try :
self . handle . close ( )
except psycopg2 . InterfaceError as error :
LOGGER . error ( 'Error closing socke... |
def fit_loop ( self , X , y = None , epochs = None , ** fit_params ) :
"""The proper fit loop .
Contains the logic of what actually happens during the fit
loop .
Parameters
X : input data , compatible with skorch . dataset . Dataset
By default , you should be able to pass :
* numpy arrays
* torch tens... | self . check_data ( X , y )
epochs = epochs if epochs is not None else self . max_epochs
dataset_train , dataset_valid = self . get_split_datasets ( X , y , ** fit_params )
on_epoch_kwargs = { 'dataset_train' : dataset_train , 'dataset_valid' : dataset_valid , }
y_train_is_ph = uses_placeholder_y ( dataset_train )
y_va... |
def _utf8 ( value ) :
"""Converts a string argument to a byte string .
If the argument is already a byte string or None , it is returned unchanged .
Otherwise it must be a unicode string and is encoded as utf8.""" | if isinstance ( value , _UTF8_TYPES ) :
return value
if not isinstance ( value , unicode_type ) :
raise TypeError ( "Expected bytes, unicode, or None; got %r" % type ( value ) )
return value . encode ( "utf-8" ) |
def add_user_role ( self , user , role_name ) :
"""Associate a role name with a user .""" | # For SQL : user . roles is list of pointers to Role objects
if isinstance ( self . db_adapter , SQLDbAdapter ) : # user . roles is a list of Role IDs
# Get or add role
role = self . db_adapter . find_first_object ( self . RoleClass , name = role_name )
if not role :
role = self . RoleClass ( name = rol... |
def worklogs ( self , issue ) :
"""Get a list of worklog Resources from the server for an issue .
: param issue : ID or key of the issue to get worklogs from
: rtype : List [ Worklog ]""" | r_json = self . _get_json ( 'issue/' + str ( issue ) + '/worklog' )
worklogs = [ Worklog ( self . _options , self . _session , raw_worklog_json ) for raw_worklog_json in r_json [ 'worklogs' ] ]
return worklogs |
def _next_pattern ( self ) :
"""Parses the next pattern by matching each in turn .""" | current_state = self . state_stack [ - 1 ]
position = self . _position
for pattern in self . patterns :
if current_state not in pattern . states :
continue
m = pattern . regex . match ( self . source , position )
if not m :
continue
position = m . end ( )
token = None
if pattern ... |
def write_weight_map ( self , model_name = None ) :
"""Save counts model map to a FITS file .""" | if model_name is None :
suffix = self . config [ 'file_suffix' ]
else :
suffix = '_%s%s' % ( model_name , self . config [ 'file_suffix' ] )
self . logger . info ( 'Generating model map for component %s.' , self . name )
outfile = os . path . join ( self . config [ 'fileio' ] [ 'workdir' ] , 'wcube%s.fits' % ( s... |
def get_references ( chebi_ids ) :
'''Returns references''' | references = [ ]
chebi_ids = [ str ( chebi_id ) for chebi_id in chebi_ids ]
filename = get_file ( 'reference.tsv.gz' )
with io . open ( filename , 'r' , encoding = 'cp1252' ) as textfile :
next ( textfile )
for line in textfile :
tokens = line . strip ( ) . split ( '\t' )
if tokens [ 0 ] in cheb... |
def upload ( self , image , name = None ) :
"""Upload the given image , which can be a http [ s ] URL , a path to an existing file ,
binary image data , or an open file handle .""" | assert self . client_id , "imgur client ID is not set! Export the IMGUR_CLIENT_ID environment variable..."
assert self . client_secret , "imgur client secret is not set! Export the IMGUR_CLIENT_SECRET environment variable..."
# Prepare image
try :
image_data = ( image + '' )
except ( TypeError , ValueError ) :
... |
def max_achievable_number ( num : int , t : int ) -> int :
"""Calculates the maximum achievable number x which can become equal to num by applying the
operation of either increasing or decreasing x by 1 and simultaneously increasing or decreasing
num by 1 , for no more than t times .
Parameters :
num ( int ... | # Each operation can increase num by 1 and at the same time decrease x by 1
# we can apply the operation t times , so we have num + t = = x - t
# so x = = num + 2 * t
return num + 2 * t |
def cublasZgerc ( handle , m , n , alpha , x , incx , y , incy , A , lda ) :
"""Rank - 1 operation on complex general matrix .""" | status = _libcublas . cublasZgerc_v2 ( handle , m , n , ctypes . byref ( cuda . cuDoubleComplex ( alpha . real , alpha . imag ) ) , int ( x ) , incx , int ( y ) , incy , int ( A ) , lda )
cublasCheckStatus ( status ) |
def tables_get ( self , table_name ) :
"""Issues a request to retrieve information about a table .
Args :
table _ name : a tuple representing the full name of the table .
Returns :
A parsed result object .
Raises :
Exception if there is an error performing the operation .""" | url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name )
return datalab . utils . Http . request ( url , credentials = self . _credentials ) |
def await_metadata_by_name ( self , name , metadata_key , timeout , caster = None ) :
"""Block up to a timeout for process metadata to arrive on disk .
: param string name : The ProcessMetadataManager identity / name ( e . g . ' pantsd ' ) .
: param string metadata _ key : The metadata key ( e . g . ' pid ' ) .... | file_path = self . _metadata_file_path ( name , metadata_key )
self . _wait_for_file ( file_path , timeout = timeout )
return self . read_metadata_by_name ( name , metadata_key , caster ) |
def _deserialize_property_value ( self , to_deserialize : PrimitiveJsonType , deserializer_cls : Type ) -> Any :
"""Deserializes the given value using the given deserializer .
: param to _ deserialize : the value to deserialize
: param deserializer _ cls : the type of deserializer to use
: return : deserializ... | deserializer = self . _create_deserializer_of_type_with_cache ( deserializer_cls )
assert deserializer is not None
return deserializer . deserialize ( to_deserialize ) |
def handle_read_value ( self , buff , start , end ) :
'''handle read of the value based on the expected length
: param buff :
: param start :
: param end :''' | segmenttype = self . _state [ 1 ] . value . segmenttype
value = None
eventtype = None
ftype = self . _state [ 0 ]
# parsing value
if segmenttype <= SegmentType . VARIABLE_LENGTH_VALUE :
self . _scstate = self . next_state_afterraw ( )
value = self . parse_value ( self . _state [ 0 ] , buff , start , end )
e... |
def _minion_event ( self , load ) :
'''Receive an event from the minion and fire it on the master event
interface''' | if 'id' not in load :
return False
if 'events' not in load and ( 'tag' not in load or 'data' not in load ) :
return False
if 'events' in load :
for event in load [ 'events' ] :
if 'data' in event :
event_data = event [ 'data' ]
else :
event_data = event
self .... |
def get_config ( cls , service , config = None ) :
"""Get get configuration of the specified rate limiter
: param str service :
rate limiter name
: param config :
optional global rate limiters configuration .
If not specified , then use rate limiters configuration
specified at application level""" | config = config or cls . get_configs ( )
return config [ service ] |
def open_pcap ( iface , * args , ** kargs ) :
"""open _ pcap : Windows routine for creating a pcap from an interface .
This function is also responsible for detecting monitor mode .""" | iface_pcap_name = pcapname ( iface )
if not isinstance ( iface , NetworkInterface ) and iface_pcap_name is not None :
iface = IFACES . dev_from_name ( iface )
if iface . is_invalid ( ) :
raise Scapy_Exception ( "Interface is invalid (no pcap match found) !" )
# Only check monitor mode when manually specified .
... |
def fit ( self , index , distvec , recalc = False , dimensions = 3 ) :
"""Replace distance matrix values at row / column index with
distances in distvec , and compute new coordinates .
Optionally use distvec to update means and ( potentially )
get a better estimate .
distvec values should be plain distances... | brow = self . new_B_row ( index , distvec ** 2 , recalc )
return self . new_coords ( brow ) [ : dimensions ] |
def doc ( self ) :
"""Return the root Doc element ( if there is one )""" | guess = self
while guess is not None and guess . tag != 'Doc' :
guess = guess . parent
# If no parent , this will be None
return guess |
def recruit ( self ) :
"""Recruit one participant at a time until all networks are full .""" | if self . networks ( full = False ) :
self . recruiter . recruit ( n = 1 )
else :
self . recruiter . close_recruitment ( ) |
def parse_column_names ( text ) :
"""Extracts column names from a string containing quoted and comma separated
column names .
: param text : Line extracted from ` COPY ` statement containing quoted and
comma separated column names .
: type text : str
: return : Tuple containing just the column names .
:... | return tuple ( re . sub ( r"^\"(.*)\"$" , r"\1" , column_name . strip ( ) ) for column_name in text . split ( "," ) ) |
def char_width ( char ) :
"""Get the display length of a unicode character .""" | if ord ( char ) < 128 :
return 1
elif unicodedata . east_asian_width ( char ) in ( 'F' , 'W' ) :
return 2
elif unicodedata . category ( char ) in ( 'Mn' , ) :
return 0
else :
return 1 |
def draw_path ( self , gc , path , transform , rgbFace = None ) :
"""Draw the path""" | nmax = rcParams [ 'agg.path.chunksize' ]
# here at least for testing
npts = path . vertices . shape [ 0 ]
if ( nmax > 100 and npts > nmax and path . should_simplify and rgbFace is None and gc . get_hatch ( ) is None ) :
nch = np . ceil ( npts / float ( nmax ) )
chsize = int ( np . ceil ( npts / nch ) )
i0 =... |
def child_ ( self , ctx ) :
"""If the root resource is requested , return the primary
application ' s front page , if a primary application has been
chosen . Otherwise return ' self ' , since this page can render a
simple index .""" | if self . frontPageItem . defaultApplication is None :
return self . webViewer . wrapModel ( _OfferingsFragment ( self . frontPageItem ) )
else :
return SharingIndex ( self . frontPageItem . defaultApplication . open ( ) , self . webViewer ) . locateChild ( ctx , [ '' ] ) [ 0 ] |
def find ( self , search_str , by = 'name' , language = 'en' ) :
'''Select values by attribute
Args :
searchstr ( str ) : the string to search for
by ( str ) : the name of the attribute to search by , defaults to ' name '
The specified attribute must be either a string
or a dict mapping language codes to ... | s = search_str . lower ( )
# We distinguish between international strings stored as dict such as
# name . en , name . fr , and normal strings .
if by in [ 'name' , 'description' ] :
get_field = lambda obj : getattr ( obj , by ) [ language ]
else : # normal string
get_field = lambda obj : getattr ( obj , by )
re... |
def link_methods ( self ) :
"""Perform linkage of addresses between methods .""" | from . . compiler import Compiler
for method in self . methods :
method . prepare ( )
self . all_vm_tokens = OrderedDict ( )
address = 0
for method in self . orderered_methods :
if not method . is_interop : # print ( " ADDING METHOD % s " % method . full _ name )
method . address = address
for k... |
def formulas_iter ( self ) :
"""Iterates over all variable - clauses in the logical network
Yields
tuple [ str , frozenset [ caspo . core . clause . Clause ] ]
The next tuple of the form ( variable , set of clauses ) in the logical network .""" | for var in it . ifilter ( self . has_node , self . variables ( ) ) :
yield var , frozenset ( self . predecessors ( var ) ) |
def get_content ( self , offset , size ) :
"""Return the specified number of bytes from the current section .""" | return _bfd . section_get_content ( self . bfd , self . _ptr , offset , size ) |
def delete_role ( self , role , mount_point = DEFAULT_MOUNT_POINT ) :
"""Delete the previously registered role .
Supported methods :
DELETE : / auth / { mount _ point } / role / { role } . Produces : 204 ( empty body )
: param role : The name of the role to delete .
: type role : str | unicode
: param mou... | params = { 'role' : role , }
api_path = '/v1/auth/{mount_point}/role/{role}' . format ( mount_point = mount_point , role = role , )
return self . _adapter . delete ( url = api_path , json = params , ) |
def load ( self , name ) :
"""Loads and returns foreign library .""" | name = ctypes . util . find_library ( name )
return ctypes . cdll . LoadLibrary ( name ) |
def send ( self ) :
"""Send this message to the controller .""" | self . _file . write ( self . as_bytes ( ) )
self . _file . write ( b'\r\n' ) |
def _get_base_command ( self ) :
"""Returns the full command string
Overridden here because there are positional arguments ( specifically
the input and output files ) .""" | command_parts = [ ]
# Append a change directory to the beginning of the command to change
# to self . WorkingDir before running the command
# WorkingDir should be in quotes - - filenames might contain spaces
cd_command = '' . join ( [ 'cd ' , str ( self . WorkingDir ) , ';' ] )
if self . _command is None :
raise Ap... |
def eformat ( format_str , lst , dct , defvalue = '-' ) :
"""Formats a list and a dictionary , manages unkown keys
It works like : meth : ` string . Formatter . vformat ` except that it accepts a defvalue for not matching keys .
Defvalue can be a callable that will receive the requested key as argument and retu... | return vformat ( format_str , DefaultList ( defvalue , lst ) , DefaultDict ( defvalue , dct ) ) |
def category ( self ) -> Optional [ str ] :
'''Determine the category of existing statement''' | if self . statements :
if self . statements [ - 1 ] [ 0 ] == ':' : # a hack . . . . to avoid calling isValid recursively
def validDirective ( ) :
if not self . values :
return True
if self . values [ - 1 ] . strip ( ) . endswith ( ',' ) :
return False
... |
def extractSubsetFromWatershed ( subset_network_file , subset_network_river_id_field , watershed_file , watershed_network_river_id_field , out_watershed_subset_file ) :
"""Extract catchment by using subset network file .
Use this after using either
: func : ` ~ RAPIDpy . gis . taudem . TauDEM . extractSubNetwor... | subset_network_shapefile = ogr . Open ( subset_network_file )
subset_network_layer = subset_network_shapefile . GetLayer ( )
ogr_watershed_shapefile = ogr . Open ( watershed_file )
ogr_watershed_shapefile_lyr = ogr_watershed_shapefile . GetLayer ( )
ogr_watershed_shapefile_lyr_defn = ogr_watershed_shapefile_lyr . GetLa... |
def QA_data_min_resample ( min_data , type_ = '5min' ) :
"""分钟线采样成大周期
分钟线采样成子级别的分钟线
time + OHLC = = > resample
Arguments :
min { [ type ] } - - [ description ]
raw _ type { [ type ] } - - [ description ]
new _ type { [ type ] } - - [ description ]""" | try :
min_data = min_data . reset_index ( ) . set_index ( 'datetime' , drop = False )
except :
min_data = min_data . set_index ( 'datetime' , drop = False )
CONVERSION = { 'code' : 'first' , 'open' : 'first' , 'high' : 'max' , 'low' : 'min' , 'close' : 'last' , 'vol' : 'sum' , 'amount' : 'sum' } if 'vol' in min... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.