signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def swaplevel ( self , i = - 2 , j = - 1 , copy = True ) :
"""Swap levels i and j in a MultiIndex .
Parameters
i , j : int , str ( can be mixed )
Level of index to be swapped . Can pass level name as string .
Returns
Series
Series with levels swapped in MultiIndex .
. . versionchanged : : 0.18.1
The... | new_index = self . index . swaplevel ( i , j )
return self . _constructor ( self . _values , index = new_index , copy = copy ) . __finalize__ ( self ) |
def count_lines_to_next_cell ( cell_end_marker , next_cell_start , total , explicit_eoc ) :
"""How many blank lines between end of cell marker and next cell ?""" | if cell_end_marker < total :
lines_to_next_cell = next_cell_start - cell_end_marker
if explicit_eoc :
lines_to_next_cell -= 1
if next_cell_start >= total :
lines_to_next_cell += 1
return lines_to_next_cell
return 1 |
def maps_re_apply_policy_input_rbridge_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
maps_re_apply_policy = ET . Element ( "maps_re_apply_policy" )
config = maps_re_apply_policy
input = ET . SubElement ( maps_re_apply_policy , "input" )
rbridge_id = ET . SubElement ( input , "rbridge-id" )
rbridge_id . text = kwargs . pop ( 'rbridge_id' )
callback = kwargs . pop ( 'ca... |
def guess_encoding ( self ) :
"""Guess encoding using the language , falling back on chardet .
: return : the guessed encoding .
: rtype : str""" | logger . info ( 'Guessing encoding for language %s' , self . language )
# always try utf - 8 first
encodings = [ 'utf-8' ]
# add language - specific encodings
if self . language . alpha3 == 'zho' :
encodings . extend ( [ 'gb18030' , 'big5' ] )
elif self . language . alpha3 == 'jpn' :
encodings . append ( 'shift... |
def GET_AUTH ( self , courseid ) : # pylint : disable = arguments - differ
"""GET request""" | course , __ = self . get_course_and_check_rights ( courseid , allow_all_staff = False )
return self . show_page ( course , web . input ( ) ) |
def _get_python_cmd ( self ) :
"""return the python executable in the virtualenv .
Try first sys . executable but use fallbacks .""" | file_names = [ "pypy.exe" , "python.exe" , "python" ]
executable = sys . executable
if executable is not None :
executable = os . path . split ( executable ) [ 1 ]
file_names . insert ( 0 , executable )
return self . _get_bin_file ( * file_names ) |
def get_valid_build_systems ( working_dir , package = None ) :
"""Returns the build system classes that could build the source in given dir .
Args :
working _ dir ( str ) : Dir containing the package definition and potentially
build files .
package ( ` Package ` ) : Package to be built . This may or may not... | from rez . plugin_managers import plugin_manager
from rez . exceptions import PackageMetadataError
try :
package = package or get_developer_package ( working_dir )
except PackageMetadataError : # no package , or bad package
pass
if package :
if getattr ( package , "build_command" , None ) is not None :
... |
def basicConfig ( level = logging . WARNING , transient_level = logging . NOTSET ) :
"""Shortcut for setting up transient logging
I am a replica of ` ` logging . basicConfig ` ` which installs a
transient logging handler to stderr .""" | fmt = "%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] %(message)s"
logging . root . setLevel ( transient_level )
# < - - - IMPORTANT
hand = TransientStreamHandler ( level = level )
hand . setFormatter ( logging . Formatter ( fmt ) )
logging . root . addHandler ( hand ) |
def validate_unwrap ( self , value , session = None ) :
'''Validates that the DBRef is valid as well as can be done without
retrieving it .''' | if not isinstance ( value , DBRef ) :
self . _fail_validation_type ( value , DBRef )
if self . type :
expected = self . type . type . get_collection_name ( )
got = value . collection
if expected != got :
self . _fail_validation ( value , '''Wrong collection for reference: ''' '''got "%s" instead... |
def _set_tlv_type ( self , v , load = False ) :
"""Setter method for tlv _ type , mapped from YANG variable / protocol / cfm / domain _ name / ma _ name / cfm _ ma _ sub _ commands / mep / cfm _ mep _ sub _ commands / tlv _ type ( ccm - tlv - type )
If this variable is read - only ( config : false ) in the
sour... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'port-status-tlv' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "tlv-type" , rest_name = "tlv-type" , parent = self , p... |
def get_parent_log_nodes ( self ) :
"""Gets the parents of this log .
return : ( osid . logging . LogNodeList ) - the parents of this log
* compliance : mandatory - - This method must be implemented . *""" | parent_log_nodes = [ ]
for node in self . _my_map [ 'parentNodes' ] :
parent_log_nodes . append ( LogNode ( node . _my_map , runtime = self . _runtime , proxy = self . _proxy , lookup_session = self . _lookup_session ) )
return LogNodeList ( parent_log_nodes ) |
def add_lifecycle_delete_rule ( self , ** kw ) :
"""Add a " delete " rule to lifestyle rules configured for this bucket .
See https : / / cloud . google . com / storage / docs / lifecycle and
https : / / cloud . google . com / storage / docs / json _ api / v1 / buckets
. . literalinclude : : snippets . py
:... | rules = list ( self . lifecycle_rules )
rules . append ( LifecycleRuleDelete ( ** kw ) )
self . lifecycle_rules = rules |
def pkg ( pkg_path , pkg_sum , hash_type , test = None , ** kwargs ) :
'''Execute a packaged state run , the packaged state run will exist in a
tarball available locally . This packaged state
can be generated using salt - ssh .
CLI Example :
. . code - block : : bash
salt ' * ' state . pkg / tmp / salt _ ... | # TODO - Add ability to download from salt master or other source
popts = salt . utils . state . get_sls_opts ( __opts__ , ** kwargs )
if not os . path . isfile ( pkg_path ) :
return { }
if not salt . utils . hashutils . get_hash ( pkg_path , hash_type ) == pkg_sum :
return { }
root = tempfile . mkdtemp ( )
s_p... |
def generate_request_access_signature ( parameters , secret_key ) :
"""Generate the parameter signature used during third party access requests""" | # pull out the parameter keys
keys = parameters . keys ( )
# alphanumerically sort the keys in place
keys . sort ( )
# create an array of url encoded key : value pairs
encoded_pairs = [ urlencode ( { key : parameters [ key ] } ) for key in keys ]
# create the serialized parameters in a single , URL style string
seriali... |
def stylize ( obj , style = 'plastique' , theme = 'projexui' ) :
"""Styles the inputed object with the given options .
: param obj | < QtGui . QWidget > | | < QtGui . QApplication >
style | < str >
base | < str >""" | obj . setStyle ( style )
if theme :
sheet = resources . read ( 'styles/{0}/style.css' . format ( theme ) )
if sheet :
obj . setStyleSheet ( sheet ) |
def do_counter_conversion ( self ) :
"""Update latest value to the diff between it and the previous value""" | if self . is_counter :
if self . _previous_counter_value is None :
prev_value = self . latest_value
else :
prev_value = self . _previous_counter_value
self . _previous_counter_value = self . latest_value
self . latest_value = self . latest_value - prev_value |
def collections ( self , values ) :
"""Set list of collections .""" | # if cache server is configured , save collection list
if self . cache :
self . cache . set ( self . app . config [ 'COLLECTIONS_CACHE_KEY' ] , values ) |
def register_inline_handler ( self , callback , * custom_filters , state = None , run_task = None , ** kwargs ) :
"""Register handler for inline query
Example :
. . code - block : : python3
dp . register _ inline _ handler ( some _ inline _ handler , lambda inline _ query : True )
: param callback :
: par... | if custom_filters is None :
custom_filters = [ ]
filters_set = self . filters_factory . resolve ( self . inline_query_handlers , * custom_filters , state = state , ** kwargs )
self . inline_query_handlers . register ( self . _wrap_async_task ( callback , run_task ) , filters_set ) |
def _list_records ( self , rtype = None , name = None , content = None ) :
"""Connects to Hetzner account and returns a list of records filtered by record
rtype , name and content . The list is empty if no records found .""" | with self . _session ( self . domain , self . domain_id ) as ddata :
name = self . _fqdn_name ( name ) if name else None
return self . _list_records_in_zone ( ddata [ 'zone' ] [ 'data' ] , rtype , name , content ) |
def upload ( ) :
"""Uploads an artifact referenced by a run .""" | build = g . build
utils . jsonify_assert ( len ( request . files ) == 1 , 'Need exactly one uploaded file' )
file_storage = request . files . values ( ) [ 0 ]
data = file_storage . read ( )
content_type , _ = mimetypes . guess_type ( file_storage . filename )
artifact = _save_artifact ( build , data , content_type )
db... |
def late ( ) :
"""Used by functions in package . py that are evaluated lazily .
The term ' late ' refers to the fact these package attributes are evaluated
late , ie when the attribute is queried for the first time .
If you want to implement a package . py attribute as a function , you MUST use
this decorat... | from rez . package_resources_ import package_rex_keys
def decorated ( fn ) : # this is done here rather than in standard schema validation because
# the latter causes a very obfuscated error message
if fn . __name__ in package_rex_keys :
raise ValueError ( "Cannot use @late decorator on function '%s'" % fn ... |
def _rise_set_trig ( t , target , location , prev_next , rise_set ) :
"""Crude time at next rise / set of ` ` target ` ` using spherical trig .
This method is ~ 15 times faster than ` _ calcriseset ` ,
and inherently does * not * take the atmosphere into account .
The time returned should not be used in calcu... | dec = target . transform_to ( coord . ICRS ) . dec
with warnings . catch_warnings ( ) :
warnings . simplefilter ( 'ignore' )
# ignore astropy deprecation warnings
lat = location . latitude
cosHA = - np . tan ( dec ) * np . tan ( lat . radian )
# find the absolute value of the hour Angle
HA = coord . Longitu... |
async def update ( self ) :
"""Update sirbot
Trigger the update method of the plugins . This is needed if the plugins
need to perform update migration ( i . e database )""" | logger . info ( 'Updating Sir Bot-a-lot' )
for name , plugin in self . _plugins . items ( ) :
plugin_update = getattr ( plugin [ 'plugin' ] , 'update' , None )
if callable ( plugin_update ) :
logger . info ( 'Updating %s' , name )
await plugin_update ( self . config . get ( name , { } ) , self .... |
def get_model_voice ( self , app , model_item ) :
"""Model voice
Returns the js menu compatible voice dict if the user
can see it , None otherwise""" | if model_item . get ( 'name' , None ) is None :
raise ImproperlyConfigured ( 'Model menu voices must have a name key' )
# noqa
if self . check_model_permission ( app , model_item . get ( 'name' , None ) ) :
return { 'type' : 'model' , 'label' : model_item . get ( 'label' , '' ) , 'icon' : model_item . get ( 'ic... |
def _load_data ( self ) :
"""Load all fixtures from : attr : ` fixtures _ dir `""" | filenames = [ ]
model_identifiers = defaultdict ( list )
# attempt to load fixture files from given directories ( first pass )
# for each valid model fixture file , read it into the cache and get the
# list of identifier keys from it
for fixtures_dir in self . fixture_dirs :
for filename in os . listdir ( fixtures_... |
def setIcon ( self , icon ) :
"""Sets the icon for this hotspot . If this method is called with a valid
icon , then the style will automatically switch to Icon , otherwise ,
the style will be set to Invisible .
: param icon | < QIcon > | | < str > | | None""" | icon = QIcon ( icon )
if icon . isNull ( ) :
self . _icon = None
self . _style = XNodeHotspot . Style . Invisible
else :
self . _icon = icon
self . _style = XNodeHotspot . Style . Icon |
def profile_get ( user , default_hidden = True ) :
'''List profiles for user
user : string
username
default _ hidden : boolean
hide default profiles
CLI Example :
. . code - block : : bash
salt ' * ' rbac . profile _ get leo
salt ' * ' rbac . profile _ get leo default _ hidden = False''' | user_profiles = [ ]
# # read user _ attr file ( user : qualifier : res1 : res2 : attr )
with salt . utils . files . fopen ( '/etc/user_attr' , 'r' ) as user_attr :
for profile in user_attr :
profile = salt . utils . stringutils . to_unicode ( profile )
profile = profile . strip ( ) . split ( ':' )
... |
def copy_entry_to_entry ( self , fromentry , destentry , check_for_dupes = True , compare_to_existing = True ) :
"""Used by ` merge _ duplicates `""" | self . log . info ( "Copy entry object '{}' to '{}'" . format ( fromentry [ fromentry . _KEYS . NAME ] , destentry [ destentry . _KEYS . NAME ] ) )
newsourcealiases = { }
if self . proto . _KEYS . SOURCES in fromentry :
for source in fromentry [ self . proto . _KEYS . SOURCES ] :
alias = source . pop ( SOUR... |
def move_round_to ( self , points , steps ) :
"""Follow a path pre - defined by a set of at least 4 points . This Path will
interpolate the points into a curve and follow that curve .
: param points : The list of points that defines the path .
: param steps : The number of steps to take to follow the path .""... | # Spline interpolation needs a before and after point for the curve .
# Duplicate the first and last points to handle this . We also need
# to move from the current position to the first specified point .
points . insert ( 0 , ( self . _rec_x , self . _rec_y ) )
points . insert ( 0 , ( self . _rec_x , self . _rec_y ) )... |
def nearest_tile_to_node_using_tiles ( tile_ids , node_coord ) :
"""Get the first tile found adjacent to the given node . Returns a tile identifier .
: param tile _ ids : tiles to look at for adjacency , list ( Tile . tile _ id )
: param node _ coord : node coordinate to find an adjacent tile to , int
: retur... | for tile_id in tile_ids :
if node_coord - tile_id_to_coord ( tile_id ) in _tile_node_offsets . keys ( ) :
return tile_id
logging . critical ( 'Did not find a tile touching node={}' . format ( node_coord ) ) |
def _DoSection ( args , context , callback , trace ) :
"""{ . section foo }""" | block = args
# If a section present and " true " , push the dictionary onto the stack as the
# new context , and show it
if context . PushSection ( block . section_name , block . pre_formatters ) :
_Execute ( block . Statements ( ) , context , callback , trace )
context . Pop ( )
else : # missing or " false " -... |
def _downcase_word ( text , pos ) :
"""Lowercase the current ( or following ) word .""" | text , new_pos = _forward_word ( text , pos )
return text [ : pos ] + text [ pos : new_pos ] . lower ( ) + text [ new_pos : ] , new_pos |
def set_paths ( etc_paths = [ "/etc/" ] ) :
"""Sets the paths where the configuration files will be searched
* You can have multiple configuration files ( e . g . in the / etc / default folder
and in / etc / appfolder / )""" | global _ETC_PATHS
_ETC_PATHS = [ ]
for p in etc_paths :
_ETC_PATHS . append ( os . path . expanduser ( p ) ) |
def add_years ( datetime_like_object , n , return_date = False ) :
"""Returns a time that n years after a time .
: param datetimestr : a datetime object or a datetime str
: param n : number of years , value can be negative
: param return _ date : returns a date object instead of datetime
* * 中文文档 * *
返回给定... | a_datetime = parser . parse_datetime ( datetime_like_object )
# try assign year , month , day
try :
a_datetime = datetime ( a_datetime . year + n , a_datetime . month , a_datetime . day , a_datetime . hour , a_datetime . minute , a_datetime . second , a_datetime . microsecond , tzinfo = a_datetime . tzinfo , )
exce... |
def availability_set_get ( name , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Get a dictionary representing an availability set ' s properties .
: param name : The availability set to get .
: param resource _ group : The resource group name assigned to the
availability set .
CLI Exampl... | compconn = __utils__ [ 'azurearm.get_client' ] ( 'compute' , ** kwargs )
try :
av_set = compconn . availability_sets . get ( resource_group_name = resource_group , availability_set_name = name )
result = av_set . as_dict ( )
except CloudError as exc :
__utils__ [ 'azurearm.log_cloud_error' ] ( 'compute' , s... |
def cleanup_failed_attacks ( self ) :
"""Cleans up data of failed attacks .""" | print_header ( 'Cleaning up failed attacks' )
attacks_to_replace = { }
self . attack_work . read_all_from_datastore ( )
failed_submissions = set ( )
error_msg = set ( )
for k , v in iteritems ( self . attack_work . work ) :
if v [ 'error' ] is not None :
attacks_to_replace [ k ] = dict ( v )
failed_... |
def parse ( self , text ) :
"""The parser entry point .
Parse the provided text to check for its validity .
On success , the parsing tree is available into the result
attribute . It is a list of sievecommands . Command objects ( see
the module documentation for specific information ) .
On error , an strin... | if isinstance ( text , text_type ) :
text = text . encode ( "utf-8" )
self . __reset_parser ( )
try :
for ttype , tvalue in self . lexer . scan ( text ) :
if ttype == "hash_comment" :
self . hash_comments += [ tvalue . strip ( ) ]
continue
if ttype == "bracket_comment" :
... |
def mi ( mi , iq = None , pl = None ) : # pylint : disable = redefined - outer - name
"""This function is a wrapper for
: meth : ` ~ pywbem . WBEMConnection . ModifyInstance ` .
Modify the property values of an instance .
Parameters :
mi ( : class : ` ~ pywbem . CIMInstance ` ) :
Modified instance , also ... | CONN . ModifyInstance ( mi , IncludeQualifiers = iq , PropertyList = pl ) |
def rpush ( self , name , * values ) :
"""Push the value into the list from the * right * side
: param name : str the name of the redis key
: param values : a list of values or single value to push
: return : Future ( )""" | with self . pipe as pipe :
v_encode = self . valueparse . encode
values = [ v_encode ( v ) for v in self . _parse_values ( values ) ]
return pipe . rpush ( self . redis_key ( name ) , * values ) |
def as_blocks ( self , copy = True ) :
"""Convert the frame to a dict of dtype - > Constructor Types that each has
a homogeneous dtype .
. . deprecated : : 0.21.0
NOTE : the dtypes of the blocks WILL BE PRESERVED HERE ( unlike in
as _ matrix )
Parameters
copy : boolean , default True
Returns
values ... | warnings . warn ( "as_blocks is deprecated and will " "be removed in a future version" , FutureWarning , stacklevel = 2 )
return self . _to_dict_of_blocks ( copy = copy ) |
def increment_cell_value ( self , column_family_id , column , int_value ) :
"""Increments a value in an existing cell .
Assumes the value in the cell is stored as a 64 bit integer
serialized to bytes .
. . note : :
This method adds a read - modify rule protobuf to the accumulated
read - modify rules on th... | column = _to_bytes ( column )
rule_pb = data_v2_pb2 . ReadModifyWriteRule ( family_name = column_family_id , column_qualifier = column , increment_amount = int_value , )
self . _rule_pb_list . append ( rule_pb ) |
def get_suitable_slot_for_duplicate ( self , src_slot ) :
"""Returns the suitable position for a duplicate analysis , taking into
account if there is a WorksheetTemplate assigned to this worksheet .
By default , returns a new slot at the end of the worksheet unless there
is a slot defined for a duplicate of t... | slot_from = to_int ( src_slot , 0 )
if slot_from < 1 :
return - 1
# Are the analyses from src _ slot suitable for duplicates creation ?
container = self . get_container_at ( slot_from )
if not container or not IAnalysisRequest . providedBy ( container ) : # We cannot create duplicates from analyses other than routi... |
async def unpinChatMessage ( self , chat_id ) :
"""See : https : / / core . telegram . org / bots / api # unpinchatmessage""" | p = _strip ( locals ( ) )
return await self . _api_request ( 'unpinChatMessage' , _rectify ( p ) ) |
def get ( self , variable_path : str , default : t . Optional [ t . Any ] = None , coerce_type : t . Optional [ t . Type ] = None , coercer : t . Optional [ t . Callable ] = None , ** kwargs ) :
"""Reads a value of ` ` variable _ path ` ` from environment .
If ` ` coerce _ type ` ` is ` ` bool ` ` and no ` ` coer... | var_name = self . get_env_var_name ( variable_path )
val = self . env . get ( var_name , self . sentinel )
if val is self . sentinel :
return default
# coerce to bool with default env coercer if no coercer specified
if coerce_type and coerce_type is bool and not coercer :
coercer = coerce_str_to_bool
return sel... |
def iflat_tasks_wti ( self , status = None , op = "==" , nids = None ) :
"""Generator to iterate over all the tasks of the ` Flow ` .
Yields :
( task , work _ index , task _ index )
If status is not None , only the tasks whose status satisfies
the condition ( task . status op status ) are selected
status ... | return self . _iflat_tasks_wti ( status = status , op = op , nids = nids , with_wti = True ) |
def _recv_thread ( self ) :
"""Internal thread to iterate over source messages and dispatch callbacks .""" | for msg , metadata in self . _source :
if msg . msg_type :
self . _call ( msg , ** metadata )
# Break any upstream iterators
for sink in self . _sinks :
i = sink ( )
if i is not None :
i . breakiter ( )
self . _dead = True |
def string_profiler ( string , start_delimiter = '(' , end_delimiter = ')' , remove = True ) :
'''long = ' ( life is is good ) love world " ( blah ) blah " " here I am " once again " yes " blah '
print ( string _ profiler ( long ) )
null = ' '
print ( string _ profiler ( null ) )
short = ' ( life love ) yes... | mark = 0
string_list = [ ]
tmp_string = ''
for i in range ( len ( string ) ) :
curr_index = i + mark
if curr_index == len ( string ) :
break
if string [ curr_index ] == start_delimiter :
flag = True
else :
flag = False
if flag :
if tmp_string :
string_list... |
def readlink ( link ) :
"""readlink ( link ) - > target
Return a string representing the path to which the symbolic link points .""" | handle = api . CreateFile ( link , 0 , 0 , None , api . OPEN_EXISTING , api . FILE_FLAG_OPEN_REPARSE_POINT | api . FILE_FLAG_BACKUP_SEMANTICS , None , )
if handle == api . INVALID_HANDLE_VALUE :
raise WindowsError ( )
res = reparse . DeviceIoControl ( handle , api . FSCTL_GET_REPARSE_POINT , None , 10240 )
bytes = ... |
def step ( self , data ) :
"""Run convolution over a single position . The data must be exactly as wide as the convolution filters .
: param data : Shape : ( batch _ size , kernel _ width , num _ hidden ) .
: return : Single result of a convolution . Shape : ( batch _ size , 1 , num _ hidden ) .""" | # As we only run convolution over a single window that is exactly the size of the convolutional filter
# we can use FullyConnected instead of Convolution for efficiency reasons . Additionally we do not need to
# perform any masking .
num_hidden = self . _pre_activation_num_hidden ( )
# ( batch _ size , num _ hidden , k... |
def nearest_neighbor ( self , vectors , num = 10 , batch_size = 100 , show_progressbar = False , return_names = True ) :
"""Find the nearest neighbors to some arbitrary vector .
This function is meant to be used in composition operations . The
most _ similar function can only handle items that are in vocab , an... | vectors = np . array ( vectors )
if np . ndim ( vectors ) == 1 :
vectors = vectors [ None , : ]
result = [ ]
result = self . _batch ( vectors , batch_size , num + 1 , show_progressbar , return_names )
return list ( result ) |
def query_boost_version ( boost_root ) :
'''Read in the Boost version from a given boost _ root .''' | boost_version = None
if os . path . exists ( os . path . join ( boost_root , 'Jamroot' ) ) :
with codecs . open ( os . path . join ( boost_root , 'Jamroot' ) , 'r' , 'utf-8' ) as f :
for line in f . readlines ( ) :
parts = line . split ( )
if len ( parts ) >= 5 and parts [ 1 ] == 'BO... |
def _detect ( detector , st , threshold , trig_int , moveout = 0 , min_trig = 0 , process = True , extract_detections = False , cores = 1 , debug = 0 ) :
"""Detect within continuous data using the subspace method .
Not to be called directly , use the detector . detect method .
: type detector : eqcorrscan . cor... | detections = [ ]
# First process the stream
if process :
debug_print ( 'Processing Stream' , 0 , debug )
stream , stachans = _subspace_process ( streams = [ st . copy ( ) ] , lowcut = detector . lowcut , highcut = detector . highcut , filt_order = detector . filt_order , sampling_rate = detector . sampling_rate... |
def newest_packages ( pypi_server = "https://pypi.python.org/pypi?%3Aaction=packages_rss" ) :
"""Constructs a request to the PyPI server and returns a list of
: class : ` yarg . parse . Package ` .
: param pypi _ server : ( option ) URL to the PyPI server .
> > > import yarg
> > > yarg . newest _ packages (... | items = _get ( pypi_server )
i = [ ]
for item in items :
i_dict = { 'name' : item [ 0 ] . text . split ( ) [ 0 ] , 'url' : item [ 1 ] . text , 'description' : item [ 3 ] . text , 'date' : item [ 4 ] . text }
i . append ( Package ( i_dict ) )
return i |
def dispatch ( self , request , * args , ** kwargs ) :
'''Handle the session data passed by the prior view .''' | lessonSession = request . session . get ( PRIVATELESSON_VALIDATION_STR , { } )
try :
self . lesson = PrivateLessonEvent . objects . get ( id = lessonSession . get ( 'lesson' ) )
except ( ValueError , ObjectDoesNotExist ) :
messages . error ( request , _ ( 'Invalid lesson identifier passed to sign-up form.' ) )
... |
from typing import List
def max_jumps ( nums : List [ int ] , target : int ) -> int :
"""Calculate the maximum number of jumps to reach the end of the array ,
obeying the condition that the absolute difference between the starting
and ending element of the jump should not exceed the target .
Args :
nums ( L... | n = len ( nums )
dp = [ 0 ]
for i in range ( 1 , n ) :
dp . append ( - 1 )
# Initialize the dp [ i ] with - 1
for j in range ( i ) :
if - target <= nums [ j ] - nums [ i ] <= target : # absolute difference not exceeding the target
if dp [ j ] != - 1 and ( dp [ i ] == - 1 or dp [ j ] + 1 ... |
def write ( self , outputfile = 'out.pdb' , appended = False ) :
"""Save the second PDB file aligned to the first .
If appended is True , both are saved as different chains .""" | # FIXME some cases don ' t work .
matrix = self . get_matrix ( ** self . get_current_values ( ) )
out = open ( outputfile , 'w' )
atomid = 1
if appended :
for line in open ( self . pdb1 ) :
if not line . startswith ( 'ATOM' ) or ( line [ 21 ] != self . chain_1 and line [ 21 ] != ' ' ) :
continue... |
def load_raw_data ( assets , data_query_cutoff_times , expr , odo_kwargs , checkpoints = None ) :
"""Given an expression representing data to load , perform normalization and
forward - filling and return the data , materialized . Only accepts data with a
` sid ` field .
Parameters
assets : pd . int64index
... | lower_dt , upper_dt = data_query_cutoff_times [ [ 0 , - 1 ] ]
raw = ffill_query_in_range ( expr , lower_dt , upper_dt , checkpoints = checkpoints , odo_kwargs = odo_kwargs , )
sids = raw [ SID_FIELD_NAME ]
raw . drop ( sids [ ~ sids . isin ( assets ) ] . index , inplace = True )
return raw |
def subseq ( cls , fasta , start = None , stop = None , strand = None ) :
"""Take Bio . SeqRecord and slice " start : stop " from it , does proper
index and error handling""" | start = start - 1 if start is not None else 0
stop = stop if stop is not None else len ( fasta )
if start < 0 :
msg = "start ({0}) must > 0 of `{1}`. Reset to 1" . format ( start + 1 , fasta . id )
logging . error ( msg )
start = 0
if stop > len ( fasta ) :
msg = "stop ({0}) must be <= length of `{1}` (... |
def _format_obj ( self , item = None ) :
"""Determines the type of the object and maps it to the correct
formatter""" | # Order here matters , odd behavior with tuples
if item is None :
return getattr ( self , 'number' ) ( item )
elif isinstance ( item , self . str_ ) : # : String
return item + " "
elif isinstance ( item , bytes ) : # : Bytes
return getattr ( self , 'bytes' ) ( item )
elif isinstance ( item , self . numeric_... |
def ADD ( self , params ) :
"""ADD [ Rx , ] Ry , [ Rz , PC ]
ADD [ Rx , ] [ SP , PC ] , # imm10_4
ADD [ SP , ] SP , # imm9_4
Add Ry and Rz and store the result in Rx
Rx , Ry , and Rz can be any register
If Rx is omitted , then it is assumed to be Ry""" | # This instruction allows for an optional destination register
# If it is omitted , then it is assumed to be Rb
# As defined in http : / / infocenter . arm . com / help / index . jsp ? topic = / com . arm . doc . dui0662b / index . html
# TODO can we have ADD SP , # imm9_4?
try :
Rx , Ry , Rz = self . get_three_par... |
def forward ( self , # pylint : disable = arguments - differ
inputs : torch . Tensor , mask : torch . LongTensor ) -> torch . Tensor :
"""Parameters
inputs : ` ` torch . Tensor ` ` , required .
A Tensor of shape ` ` ( batch _ size , sequence _ length , hidden _ size ) ` ` .
mask : ` ` torch . LongTensor ` ` ,... | batch_size , total_sequence_length = mask . size ( )
stacked_sequence_output , final_states , restoration_indices = self . sort_and_run_forward ( self . _lstm_forward , inputs , mask )
num_layers , num_valid , returned_timesteps , encoder_dim = stacked_sequence_output . size ( )
# Add back invalid rows which were remov... |
def normalize_getitem_args ( args ) :
'''Turns the arguments to _ _ getitem _ _ magic methods into a uniform
list of tuples and strings''' | if not isinstance ( args , tuple ) :
args = ( args , )
return_val = [ ]
for arg in args :
if isinstance ( arg , six . string_types + ( int , ) ) :
return_val . append ( arg )
elif isinstance ( arg , slice ) :
return_val . append ( ( arg . start , arg . stop ) )
else :
raise TypeE... |
def analysis ( self ) :
"""Get ANALYSIS segment of the FCS file .""" | if self . _analysis is None :
with open ( self . path , 'rb' ) as f :
self . read_analysis ( f )
return self . _analysis |
def from_dict ( cls , d ) :
"""Decode a dictionary , as from : meth : ` to _ dict ` , into a Dmrs object .""" | def _node ( obj ) :
return Node ( obj . get ( 'nodeid' ) , Pred . surface_or_abstract ( obj . get ( 'predicate' ) ) , sortinfo = obj . get ( 'sortinfo' ) , lnk = _lnk ( obj . get ( 'lnk' ) ) , surface = obj . get ( 'surface' ) , base = obj . get ( 'base' ) , carg = obj . get ( 'carg' ) )
def _link ( obj ) :
ret... |
def update_resource ( self , resource ) :
'''Perform an atomic update for an existing resource''' | index = self . resources . index ( resource )
data = { 'resources__{index}' . format ( index = index ) : resource }
self . update ( ** data )
self . reload ( )
post_save . send ( self . __class__ , document = self ) |
def find_next ( lines , find_str , start_index ) :
"""Find the next instance of find _ str from lines starting from start _ index .
: param lines : Lines to look through
: param find _ str : String or Invert to look for
: param start _ index : Index to start from
: return : ( boolean , index , line )""" | mode = None
if isinstance ( find_str , basestring ) :
mode = 'normal'
message = find_str
elif isinstance ( find_str , Invert ) :
mode = 'invert'
message = str ( find_str )
else :
raise TypeError ( "Unsupported message type" )
for i in range ( start_index , len ( lines ) ) :
if re . search ( mess... |
def _get_frame ( self , key ) :
"""Creates a clone of the Layout with the nth - frame for each
Element .""" | cached = self . current_key is None
layout_frame = self . layout . clone ( shared_data = False )
if key == self . current_key and not self . _force :
return self . current_frame
else :
self . current_key = key
key_map = dict ( zip ( [ d . name for d in self . dimensions ] , key ) )
for path , item in self . lay... |
async def _dump_tuple ( self , writer , elem , elem_type , params = None ) :
"""Dumps tuple of elements to the writer .
: param writer :
: param elem :
: param elem _ type :
: param params :
: return :""" | if len ( elem ) != len ( elem_type . f_specs ( ) ) :
raise ValueError ( "Fixed size tuple has not defined size: %s" % len ( elem_type . f_specs ( ) ) )
await dump_uvarint ( writer , len ( elem ) )
elem_fields = params [ 0 ] if params else None
if elem_fields is None :
elem_fields = elem_type . f_specs ( )
for i... |
def check_window ( self , name = "default" , level = 0 , baseline = False ) :
"""* * * Automated Visual Testing with SeleniumBase * * *
The first time a test calls self . check _ window ( ) for a unique " name "
parameter provided , it will set a visual baseline , meaning that it
creates a folder , saves the ... | if level == "0" :
level = 0
if level == "1" :
level = 1
if level == "2" :
level = 2
if level == "3" :
level = 3
if level != 0 and level != 1 and level != 2 and level != 3 :
raise Exception ( 'Parameter "level" must be set to 0, 1, 2, or 3!' )
module = self . __class__ . __module__
if '.' in module a... |
def nancorr ( a , b , method = 'pearson' , min_periods = None ) :
"""a , b : ndarrays""" | if len ( a ) != len ( b ) :
raise AssertionError ( 'Operands to nancorr must have same size' )
if min_periods is None :
min_periods = 1
valid = notna ( a ) & notna ( b )
if not valid . all ( ) :
a = a [ valid ]
b = b [ valid ]
if len ( a ) < min_periods :
return np . nan
f = get_corr_func ( method )... |
def walk ( node ) :
"""Iterate over all nodes . This is useful if you only want to modify nodes in
place and don ' t care about the context or the order the nodes are returned .""" | from collections import deque
todo = deque ( [ node ] )
while todo :
node = todo . popleft ( )
todo . extend ( iter_child_nodes ( node ) )
yield node |
def Unique ( a , t ) :
"""Unique op .""" | _ , idxs , inv = np . unique ( a , return_index = True , return_inverse = True )
return np . copy ( a ) [ np . sort ( idxs ) ] , idxs [ inv ] . astype ( dtype_map [ t ] ) |
def colorlog ( msg , color , bold = False , blink = False ) :
"""Colors messages on non - Windows systems supporting ANSI escape .""" | # ANSI Escape Codes
PINK_COL = '\x1b[35m'
GREEN_COL = '\x1b[32m'
RED_COL = '\x1b[31m'
YELLOW_COL = '\x1b[33m'
BLINK = '\x1b[5m'
RESET = '\x1b[0m'
if platform . system ( ) != 'Windows' :
if blink :
msg = BLINK + msg + RESET
if color == 'yellow' :
msg = YELLOW_COL + msg + RESET
if color == 're... |
def check_isomorphism ( s1 : str , s2 : str ) -> bool :
"""A python function to assess if two given strings are isomorphic .
Isomorphism exists if every character in string1 can be replaced to get string2.
> > > check _ isomorphism ( ' paper ' , ' title ' )
True
> > > check _ isomorphism ( ' ab ' , ' ba ' )... | map_s1 = { }
map_s2 = { }
for i , value in enumerate ( s1 ) :
map_s1 [ value ] = map_s1 . get ( value , [ ] ) + [ i ]
for i , value in enumerate ( s2 ) :
map_s2 [ value ] = map_s2 . get ( value , [ ] ) + [ i ]
return sorted ( map_s1 . values ( ) ) == sorted ( map_s2 . values ( ) ) |
def read_response ( self , delegate : httputil . HTTPMessageDelegate ) -> Awaitable [ bool ] :
"""Read a single HTTP response .
Typical client - mode usage is to write a request using ` write _ headers ` ,
` write ` , and ` finish ` , and then call ` ` read _ response ` ` .
: arg delegate : a ` . HTTPMessageD... | if self . params . decompress :
delegate = _GzipMessageDelegate ( delegate , self . params . chunk_size )
return self . _read_message ( delegate ) |
def match ( self , xn ) :
"""Processes a transaction against this rule
If all conditions are satisfied , a list of outcomes is returned .
If any condition is unsatisifed , None is returned .""" | if all ( map ( lambda x : x . match ( xn ) , self . conditions ) ) :
return self . outcomes
return None |
def vcf2pileup ( vcf , sample ) :
'''convert vcf record to pileup record .''' | chromosome = vcf . contig
pos = vcf . pos
reference = vcf . ref
allelles = [ reference ] + vcf . alt
data = vcf [ sample ]
# get genotype
genotypes = data [ "GT" ]
if len ( genotypes ) > 1 :
raise ValueError ( "only single genotype per position, %s" % ( str ( vcf ) ) )
genotypes = genotypes [ 0 ]
# not a variant
if... |
def get ( self , idx , default = None ) :
"""Return the first placeholder shape with matching * idx * value , or
* default * if not found .""" | for placeholder in self :
if placeholder . element . ph_idx == idx :
return placeholder
return default |
def updateLodState ( self , verbose = None ) :
"""Switch between full graphics details < - - - > fast rendering mode .
Returns a success message .
: param verbose : print more
: returns : 200 : successful operation""" | response = api ( url = self . ___url + 'ui/lod' , method = "PUT" , verbose = verbose )
return response |
def job_details ( job_id , connection = None ) :
"""Returns the job data with its scheduled timestamp .
: param job _ id : the ID of the job to retrieve .""" | if connection is None :
connection = r
data = connection . hgetall ( job_key ( job_id ) )
job_data = { 'id' : job_id , 'schedule_at' : int ( connection . zscore ( REDIS_KEY , job_id ) ) }
for key , value in data . items ( ) :
try :
decoded = value . decode ( 'utf-8' )
except UnicodeDecodeError :
... |
def centroid_distance ( item_a , time_a , item_b , time_b , max_value ) :
"""Euclidean distance between the centroids of item _ a and item _ b .
Args :
item _ a : STObject from the first set in ObjectMatcher
time _ a : Time integer being evaluated
item _ b : STObject from the second set in ObjectMatcher
t... | ax , ay = item_a . center_of_mass ( time_a )
bx , by = item_b . center_of_mass ( time_b )
return np . minimum ( np . sqrt ( ( ax - bx ) ** 2 + ( ay - by ) ** 2 ) , max_value ) / float ( max_value ) |
def in_casapy ( helper , vis = None ) :
"""This function is run inside the weirdo casapy IPython environment ! A
strange set of modules is available , and the
` pwkit . environments . casa . scripting ` system sets up a very particular
environment to allow encapsulated scripting .""" | import numpy as np , sys
from correct_ant_posns import correct_ant_posns
info = correct_ant_posns ( vis , False )
if len ( info ) != 3 or info [ 0 ] != 0 or not len ( info [ 1 ] ) :
helper . die ( 'failed to fetch VLA antenna positions; got %r' , info )
antenna = info [ 1 ]
parameter = info [ 2 ]
with open ( helper... |
def start ( self , measurementId ) :
"""Posts to the target to tell it a named measurement is starting .
: param measurementId :""" | self . sendURL = self . rootURL + measurementId + '/' + self . deviceName
self . startResponseCode = self . _doPut ( self . sendURL ) |
def route_delete ( name , route_table , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Delete a route from a route table .
: param name : The route to delete .
: param route _ table : The route table containing the route .
: param resource _ group : The resource group name assigned to the
... | result = False
netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs )
try :
route = netconn . routes . delete ( resource_group_name = resource_group , route_table_name = route_table , route_name = name )
route . wait ( )
result = True
except CloudError as exc :
__utils__ [ 'azurearm.log... |
def go_to_parent_directory ( self ) :
"""Go to parent directory""" | self . chdir ( osp . abspath ( osp . join ( getcwd_or_home ( ) , os . pardir ) ) ) |
def escape_string ( value ) :
"""Converts a string to its S - expression representation , adding quotes
and escaping funny characters .""" | res = StringIO ( )
res . write ( '"' )
for c in value :
if c in CHAR_TO_ESCAPE :
res . write ( f'\\{CHAR_TO_ESCAPE[c]}' )
elif c . isprintable ( ) :
res . write ( c )
elif ord ( c ) < 0x100 :
res . write ( f'\\x{ord(c):02x}' )
elif ord ( c ) < 0x10000 :
res . write ( f'\\... |
def p0f ( pkt ) :
"""Passive OS fingerprinting : which OS emitted this TCP packet ?
p0f ( packet ) - > accuracy , [ list of guesses ]""" | db , sig = packet2p0f ( pkt )
if db :
pb = db . get_base ( )
else :
pb = [ ]
if not pb :
warning ( "p0f base empty." )
return [ ]
# s = len ( pb [ 0 ] [ 0 ] )
r = [ ]
max = len ( sig [ 4 ] . split ( "," ) ) + 5
for b in pb :
d = p0f_correl ( sig , b )
if d == max :
r . append ( ( b [ 6 ]... |
def log ( self , sequence , infoarray ) -> None :
"""Pass the given | IoSequence | to a suitable instance of
a | NetCDFVariableBase | subclass .
When writing data , the second argument should be an | InfoArray | .
When reading data , this argument is ignored . Simply pass | None | .
(1 ) We prepare some dev... | aggregated = ( ( infoarray is not None ) and ( infoarray . info [ 'type' ] != 'unmodified' ) )
descr = sequence . descr_sequence
if aggregated :
descr = '_' . join ( [ descr , infoarray . info [ 'type' ] ] )
if descr in self . variables :
var_ = self . variables [ descr ]
else :
if aggregated :
cls ... |
def updateRPYLocations ( self ) :
'''Update the locations of roll , pitch , yaw text .''' | # Locations
self . rollText . set_position ( ( self . leftPos + ( self . vertSize / 10.0 ) , - 0.97 + ( 2 * self . vertSize ) - ( self . vertSize / 10.0 ) ) )
self . pitchText . set_position ( ( self . leftPos + ( self . vertSize / 10.0 ) , - 0.97 + self . vertSize - ( 0.5 * self . vertSize / 10.0 ) ) )
self . yawText ... |
async def getUpdates ( self , offset = None , limit = None , timeout = None , allowed_updates = None ) :
"""See : https : / / core . telegram . org / bots / api # getupdates""" | p = _strip ( locals ( ) )
return await self . _api_request ( 'getUpdates' , _rectify ( p ) ) |
def get_cert_file ( ) :
"""Get the certificates file for https""" | try :
current_path = os . path . realpath ( __file__ )
ca_cert_path = os . path . join ( current_path , ".." , ".." , ".." , "conf" , "cacert.pem" )
return os . path . abspath ( ca_cert_path )
except Exception :
return None |
def sum_mags ( mags , weights = None ) :
"""Sum an array of magnitudes in flux space .
Parameters :
mags : array of magnitudes
weights : array of weights for each magnitude ( i . e . from a pdf )
Returns :
sum _ mag : the summed magnitude of all the stars""" | flux = 10 ** ( - np . asarray ( mags ) / 2.5 )
if weights is None :
return - 2.5 * np . log10 ( np . sum ( flux ) )
else :
return - 2.5 * np . log10 ( np . sum ( weights * flux ) ) |
def add_time_dependent_effects ( self , ts ) :
"""Given a timeseries , apply a model to it .
Parameters
ts :
Time series of i . i . d . observations as a Numpy array
returns the time series with added time - dependent effects as a Numpy array .""" | destts = Vectors . dense ( [ 0 ] * len ( ts ) )
result = self . _jmodel . addTimeDependentEffects ( _py2java ( self . _ctx , Vectors . dense ( ts ) ) , _py2java ( self . _ctx , destts ) )
return _java2py ( self . _ctx , result . toArray ( ) ) |
def _dmi_data ( dmi_raw , clean , fields ) :
'''Parse the raw DMIdecode output of a single handle
into a nice dict''' | dmi_data = { }
key = None
key_data = [ None , [ ] ]
for line in dmi_raw :
if re . match ( r'\t[^\s]+' , line ) : # Finish previous key
if key is not None : # log . debug ( ' Evaluating DMI key { 0 } : { 1 } ' . format ( key , key _ data ) )
value , vlist = key_data
if vlist :
... |
def web_hook_receiver ( sender , ** kwargs ) :
"""Generic receiver for the web hook firing piece .""" | deployment = Deployment . objects . get ( pk = kwargs . get ( 'deployment_id' ) )
hooks = deployment . web_hooks
if not hooks :
return
for hook in hooks :
data = payload_generator ( deployment )
deliver_hook ( deployment , hook . url , data ) |
def pre_check ( self , data ) :
"""Count chars , words and sentences in the text .""" | sentences = len ( re . findall ( '[\.!?]+\W+' , data ) ) or 1
chars = len ( data ) - len ( re . findall ( '[^a-zA-Z0-9]' , data ) )
num_words = len ( re . findall ( '\s+' , data ) )
data = re . split ( '[^a-zA-Z]+' , data )
return data , sentences , chars , num_words |
def _bind ( self ) :
"""bind to the ldap with the technical account""" | ldap_client = self . _connect ( )
try :
ldap_client . simple_bind_s ( self . binddn , self . bindpassword )
except Exception as e :
ldap_client . unbind_s ( )
self . _exception_handler ( e )
return ldap_client |
def print_file ( self , f = sys . stdout , file_format = "cif" , tw = 0 ) :
"""Print : class : ` ~ nmrstarlib . nmrstarlib . CIFFile ` into a file or stdout .
: param io . StringIO f : writable file - like stream .
: param str file _ format : Format to use : ` cif ` or ` json ` .
: param int tw : Tab width . ... | if file_format == "cif" :
for key in self . keys ( ) :
if key == u"data" :
print ( u"{}_{}" . format ( key , self [ key ] ) , file = f )
elif key . startswith ( u"comment" ) :
print ( u"{}" . format ( self [ key ] . strip ( ) ) , file = f )
elif key . startswith ( u"l... |
def cache_get ( key ) :
"""Wrapper for ` ` cache . get ` ` . The expiry time for the cache entry
is stored with the entry . If the expiry time has past , put the
stale entry back into cache , and don ' t return it to trigger a
fake cache miss .""" | packed = cache . get ( _hashed_key ( key ) )
if packed is None :
return None
value , refresh_time , refreshed = packed
if ( time ( ) > refresh_time ) and not refreshed :
cache_set ( key , value , settings . CACHE_SET_DELAY_SECONDS , True )
return None
return value |
def set_dependencies ( ctx , archive_name , dependency = None ) :
'''Set the dependencies of an archive''' | _generate_api ( ctx )
kwargs = _parse_dependencies ( dependency )
var = ctx . obj . api . get_archive ( archive_name )
var . set_dependencies ( dependencies = kwargs ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.