signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _config ( self ) :
"""Value to be written to the device ' s config register""" | config = 0
if self . mode == MODE_NORMAL :
config += ( self . _t_standby << 5 )
if self . _iir_filter :
config += ( self . _iir_filter << 2 )
return config |
def daterange_with_details ( value ) :
'''Display a date range in the shorter possible maner .''' | delta = value . end - value . start
start , end = None , None
if is_first_year_day ( value . start ) and is_last_year_day ( value . end ) :
start = value . start . year
if delta . days > 365 :
end = value . end . year
elif is_first_month_day ( value . start ) and is_last_month_day ( value . end ) :
... |
def _append_pairs ( new_pairs ) :
"""Load the pairlist , add new stuff , save it out""" | desired_pairs = restore_pairs ( ) or [ ]
desired_pairs += new_pairs
print ( "Adding {} new pairs, queue has {} pairs" . format ( len ( new_pairs ) , len ( desired_pairs ) ) )
save_pairs ( desired_pairs ) |
def overall ( self , node ) :
"""Calculate overall size of the node including children and empty space""" | return sum ( [ self . value ( value , node ) for value in self . children ( node ) ] ) |
def get_residue_annotations ( self , seq_resnum , seqprop = None , structprop = None , chain_id = None , use_representatives = False ) :
"""Get all residue - level annotations stored in the SeqProp ` ` letter _ annotations ` ` field for a given residue number .
Uses the representative sequence , structure , and c... | if use_representatives :
if seqprop and structprop and chain_id :
raise ValueError ( 'Overriding sequence, structure, and chain IDs with representatives. ' 'Set use_representatives to False if custom IDs are to be used.' )
else :
if not seqprop or not structprop or not chain_id :
raise ValueErro... |
def post ( self , route , data = None , params = None , follow_redirects = True ) :
"""Send POST request to app .
: param route : route to send request to
: type route : str
: param data : form data to include in request
: type data : dict
: param params : URL parameters to include in request
: param fo... | return self . _send ( "POST" , route , data , params , follow_redirects = follow_redirects ) |
def toggle_wrap_mode ( self , checked ) :
"""Toggle wrap mode""" | if self . tabwidget is None :
return
for editor in self . editors :
editor . toggle_wrap_mode ( checked )
self . set_option ( 'wrap' , checked ) |
def alter_change_column ( self , table , column_name , field ) :
"""Support change columns .""" | context = super ( PostgresqlMigrator , self ) . alter_change_column ( table , column_name , field )
context . _sql . insert ( - 1 , 'TYPE' )
context . _sql . insert ( - 1 , ' ' )
return context |
def PushBack ( self , string = '' , ** unused_kwargs ) :
"""Push the match back on the stream .
Args :
string : optional data .""" | self . buffer = string + self . buffer
self . processed_buffer = self . processed_buffer [ : - len ( string ) ] |
def write_Track ( file , track , bpm = 120 , repeat = 0 , verbose = False ) :
"""Write a mingus . Track to a MIDI file .
Write the name to the file and set the instrument if the instrument has
the attribute instrument _ nr , which represents the MIDI instrument
number . The class MidiInstrument in mingus . co... | m = MidiFile ( )
t = MidiTrack ( bpm )
m . tracks = [ t ]
while repeat >= 0 :
t . play_Track ( track )
repeat -= 1
return m . write_file ( file , verbose ) |
def _get_column_value ( self , obj , column ) :
"""Return a single cell ' s value
: param obj obj : The instance we manage
: param dict column : The column description dictionnary
: returns : The associated value""" | return self . _get_formatted_val ( obj , column [ '__col__' ] . key , column ) |
def _move_modules ( self , temp_repo , destination ) :
"""Move odoo modules from the temp directory to the destination .
This step is different from a standard repository . In the base code
of Odoo , the modules are contained in a addons folder at the root
of the git repository . However , when deploying the ... | tmp_addons = os . path . join ( temp_repo , 'addons' )
tmp_odoo_addons = os . path . join ( temp_repo , 'odoo/addons' )
folders = self . _get_module_folders ( tmp_addons )
for folder in folders :
force_move ( folder , tmp_odoo_addons )
tmp_odoo = os . path . join ( temp_repo , 'odoo' )
force_move ( tmp_odoo , desti... |
def temporary_path ( self ) :
"""A context manager that enables a reasonably short , general and
magic - less way to solve the : ref : ` AtomicWrites ` .
* On * entering * , it will create the parent directories so the
temporary _ path is writeable right away .
This step uses : py : meth : ` FileSystem . mk... | num = random . randrange ( 0 , 1e10 )
slashless_path = self . path . rstrip ( '/' ) . rstrip ( "\\" )
_temp_path = '{}-luigi-tmp-{:010}{}' . format ( slashless_path , num , self . _trailing_slash ( ) )
# TODO : os . path doesn ' t make sense here as it ' s os - dependent
tmp_dir = os . path . dirname ( slashless_path )... |
def convex_hull_collide ( nodes1 , nodes2 ) :
"""Determine if the convex hulls of two curves collide .
. . note : :
This is a helper for : func : ` from _ linearized ` .
Args :
nodes1 ( numpy . ndarray ) : Control points of a first curve .
nodes2 ( numpy . ndarray ) : Control points of a second curve .
... | polygon1 = _helpers . simple_convex_hull ( nodes1 )
_ , polygon_size1 = polygon1 . shape
polygon2 = _helpers . simple_convex_hull ( nodes2 )
_ , polygon_size2 = polygon2 . shape
if polygon_size1 == 2 and polygon_size2 == 2 :
return line_line_collide ( polygon1 , polygon2 )
else :
return _helpers . polygon_colli... |
def pairwise ( values ) :
"""WITH values = [ a , b , c , d , . . . ]
RETURN [ ( a , b ) , ( b , c ) , ( c , d ) , . . . ]""" | i = iter ( values )
a = next ( i )
for b in i :
yield ( a , b )
a = b |
def start_semester_view ( request ) :
"""Initiates a semester " s worth of workshift , with the option to copy
workshift types from the previous semester .""" | page_name = "Start Semester"
year , season = utils . get_year_season ( )
start_date , end_date = utils . get_semester_start_end ( year , season )
semester_form = SemesterForm ( data = request . POST or None , initial = { "year" : year , "season" : season , "start_date" : start_date . strftime ( date_formats [ 0 ] ) , "... |
def u ( d ) :
"""convert string , string container or unicode
: param d :
: return :""" | if six . PY2 :
if isinstance ( d , six . binary_type ) :
return d . decode ( "utf8" , "ignore" )
elif isinstance ( d , list ) :
return [ u ( x ) for x in d ]
elif isinstance ( d , tuple ) :
return tuple ( u ( x ) for x in d )
elif isinstance ( d , dict ) :
return dict ( (... |
def component_type ( cls_or_slf , node ) :
"Return the type . group . label dotted information" | if node is None :
return ''
return cls_or_slf . type_formatter . format ( type = str ( type ( node ) . __name__ ) ) |
def fill_into_dict ( self , items , dest ) :
"""Take an iterable of ` items ` and group it into the given ` dest ` dict ,
using the : attr : ` key ` function .
The ` dest ` dict must either already contain the keys which are
generated by the : attr : ` key ` function for the items in ` items ` , or must
def... | for item in items :
dest [ self . key ( item ) ] . append ( item ) |
def set_container_setting ( name , container , settings ) :
'''Set the value of the setting for an IIS container .
. . versionadded : : 2016.11.0
Args :
name ( str ) : The name of the IIS container .
container ( str ) : The type of IIS container . The container types are :
AppPools , Sites , SslBindings
... | identityType_map2string = { '0' : 'LocalSystem' , '1' : 'LocalService' , '2' : 'NetworkService' , '3' : 'SpecificUser' , '4' : 'ApplicationPoolIdentity' }
identityType_map2numeric = { 'LocalSystem' : '0' , 'LocalService' : '1' , 'NetworkService' : '2' , 'SpecificUser' : '3' , 'ApplicationPoolIdentity' : '4' }
ps_cmd = ... |
def query_disc ( nside , vec , radius , inclusive = False , fact = 4 , nest = False ) :
"""Wrapper around healpy . query _ disc to deal with old healpy implementation .
nside : int
The nside of the Healpix map .
vec : float , sequence of 3 elements
The coordinates of unit vector defining the disk center .
... | try : # New - style call ( healpy 1.6.3)
return hp . query_disc ( nside , vec , np . radians ( radius ) , inclusive , fact , nest )
except Exception as e :
print ( e )
# Old - style call ( healpy 0.10.2)
return hp . query_disc ( nside , vec , np . radians ( radius ) , nest , deg = False ) |
def format ( format_string , cast = lambda x : x ) :
"""A pre - called helper to supply a modern string format ( the kind with { } instead of % s ) , so that
it can apply to each value in the column as it is rendered . This can be useful for string
padding like leading zeroes , or rounding floating point number... | def helper ( instance , * args , ** kwargs ) :
value = kwargs . get ( 'default_value' )
if value is None :
value = instance
value = cast ( value )
return format_string . format ( value , obj = instance )
return helper |
def transaction ( self , _filter = None , default = None , yield_resource = False ) :
"""transaction ( _ filter = None , default = None )
Claims a resource from the pool for use in a thread - safe ,
reentrant manner ( as part of a with statement ) . Resources are
created as needed when all members of the pool... | resource = self . acquire ( _filter = _filter , default = default )
try :
if yield_resource :
yield resource
else :
yield resource . object
if resource . errored :
self . delete_resource ( resource )
except BadResource :
self . delete_resource ( resource )
raise
finally :
... |
def rvs ( self , * args , ** kwargs ) :
"""Draw Random Variates .
Parameters
size : int , optional ( default = 1)
random _ state _ : optional ( default = None )""" | # TODO REVERSE THIS FUCK PYTHON2
size = kwargs . pop ( 'size' , 1 )
random_state = kwargs . pop ( 'size' , None )
# don ' t ask me why it uses ` self . _ size `
return self . _kde . sample ( n_samples = size , random_state = random_state ) |
def prefetch ( self , file_size = None ) :
"""Pre - fetch the remaining contents of this file in anticipation of future
` . read ` calls . If reading the entire file , pre - fetching can
dramatically improve the download speed by avoiding roundtrip latency .
The file ' s contents are incrementally buffered in... | if file_size is None :
file_size = self . stat ( ) . st_size
# queue up async reads for the rest of the file
chunks = [ ]
n = self . _realpos
while n < file_size :
chunk = min ( self . MAX_REQUEST_SIZE , file_size - n )
chunks . append ( ( n , chunk ) )
n += chunk
if len ( chunks ) > 0 :
self . _sta... |
def is_birthday ( self , dt = None ) :
"""Check if its the birthday .
Compares the date / month values of the two dates .
: rtype : bool""" | if dt is None :
dt = Date . today ( )
instance = dt1 = self . __class__ ( dt . year , dt . month , dt . day )
return ( self . month , self . day ) == ( instance . month , instance . day ) |
def is_python_binding_installed_on_pip ( self ) :
"""Check if the Python binding has already installed .""" | pip_version = self . _get_pip_version ( )
Log . debug ( 'Pip version: {0}' . format ( pip_version ) )
pip_major_version = int ( pip_version . split ( '.' ) [ 0 ] )
installed = False
# - - format is from pip v9.0.0
# https : / / pip . pypa . io / en / stable / news /
if pip_major_version >= 9 :
json_obj = self . _ge... |
def _create_proxy ( proxy_setting ) :
"""Create a Network proxy for the given proxy settings .""" | proxy = QNetworkProxy ( )
proxy_scheme = proxy_setting [ 'scheme' ]
proxy_host = proxy_setting [ 'host' ]
proxy_port = proxy_setting [ 'port' ]
proxy_username = proxy_setting [ 'username' ]
proxy_password = proxy_setting [ 'password' ]
proxy_scheme_host = '{0}://{1}' . format ( proxy_scheme , proxy_host )
proxy . setTy... |
def _generate_paragraphs ( package , subpackages ) :
"""Generate the paragraphs of the API documentation .""" | # API doc of each module .
for subpackage in _iter_subpackages ( package , subpackages ) :
subpackage_name = subpackage . __name__
yield "## {}" . format ( subpackage_name )
# Subpackage documentation .
yield _doc ( _import_module ( subpackage_name ) )
# List of top - level functions in the subpacka... |
def save_image ( self , img , filename = None , ** kwargs ) : # floating _ point = False ,
"""Save the image to the given * filename * in ninjotiff _ format .
. . _ ninjotiff : http : / / www . ssec . wisc . edu / ~ davidh / polar2grid / misc / NinJo _ Satellite _ Import _ Formats . html""" | filename = filename or self . get_filename ( ** img . data . attrs )
nt . save ( img , filename , ** kwargs ) |
def count_nonzero ( data , mapper = None , blen = None , storage = None , create = 'array' , ** kwargs ) :
"""Count the number of non - zero elements .""" | return reduce_axis ( data , reducer = np . count_nonzero , block_reducer = np . add , mapper = mapper , blen = blen , storage = storage , create = create , ** kwargs ) |
def save_models ( self , models_file ) :
"""Saves model parameters at each iteration of the optimization
: param models _ file : name of the file or a file buffer , in which the results are saved .""" | if self . model_parameters_iterations is None :
raise ValueError ( "No iterations have been carried out yet and hence no iterations of the BO can be saved" )
iterations = np . array ( range ( 1 , self . model_parameters_iterations . shape [ 0 ] + 1 ) ) [ : , None ]
results = np . hstack ( ( iterations , self . mode... |
def gen_search_gzh_url ( keyword , page = 1 ) :
"""拼接搜索 公众号 URL
Parameters
keyword : str or unicode
搜索文字
page : int , optional
页数 the default is 1
Returns
str
search _ gzh _ url""" | assert isinstance ( page , int ) and page > 0
qs_dict = OrderedDict ( )
qs_dict [ 'type' ] = _search_type_gzh
qs_dict [ 'page' ] = page
qs_dict [ 'ie' ] = 'utf8'
qs_dict [ 'query' ] = keyword
return 'http://weixin.sogou.com/weixin?{}' . format ( urlencode ( qs_dict ) ) |
def _set_cached_solve ( self , solver_dict ) :
"""Store a solve to memcached .
If there is NOT a resolve timestamp :
- store the solve to a non - timestamped entry .
If there IS a resolve timestamp ( let us call this T ) :
- if NO newer package in the solve has been released since T ,
- then store the sol... | if self . status_ != ResolverStatus . solved :
return
# don ' t cache failed solves
if not ( self . caching and self . memcached_servers ) :
return
# most recent release times get stored with solve result in the cache
releases_since_solve = False
release_times_dict = { }
variant_states_dict = { }
for variant in... |
def dlogpdf_dtheta ( self , f , y , Y_metadata = None ) :
"""TODO : Doc strings""" | if self . size > 0 :
if self . not_block_really :
raise NotImplementedError ( "Need to make a decorator for this!" )
if isinstance ( self . gp_link , link_functions . Identity ) :
return self . dlogpdf_link_dtheta ( f , y , Y_metadata = Y_metadata )
else :
inv_link_f = self . gp_link... |
def connect_async ( self , host , port = 1883 , keepalive = 60 , bind_address = "" ) :
"""Connect to a remote broker asynchronously . This is a non - blocking
connect call that can be used with loop _ start ( ) to provide very quick
start .
host is the hostname or IP address of the remote broker .
port is t... | if host is None or len ( host ) == 0 :
raise ValueError ( 'Invalid host.' )
if port <= 0 :
raise ValueError ( 'Invalid port number.' )
if keepalive < 0 :
raise ValueError ( 'Keepalive must be >=0.' )
if bind_address != "" and bind_address is not None :
if ( sys . version_info [ 0 ] == 2 and sys . versio... |
def _summarize_result ( self , root_action , leaf_eot ) :
"""Return a dict with useful information that summarizes this action .""" | root_board = root_action . parent . board
action_detail = root_action . position_pair
score = self . _relative_score ( root_action , leaf_eot , root_action . parent . player , root_action . parent . opponent )
# mana drain info
total_leaves = 0
mana_drain_leaves = 0
for leaf in root_action . leaves ( ) :
total_leav... |
def version ( self , path , postmap = None , ** params ) :
"""Return the taskforce version .
Supports standard options .""" | q = httpd . merge_query ( path , postmap )
ans = { 'taskforce' : taskforce_version , 'python' : '.' . join ( str ( x ) for x in sys . version_info [ : 3 ] ) , }
ans [ 'platform' ] = { 'system' : platform . system ( ) , }
# Add in some extra details if this is a control path .
# These might give away too many details on... |
def _check_generic_pos ( self , * tokens ) :
"""Check if the different tokens were logged in one record , any level .""" | for record in self . records :
if all ( token in record . message for token in tokens ) :
return
# didn ' t exit , all tokens are not present in the same record
msgs = [ "Tokens {} not found, all was logged is..." . format ( tokens ) ]
for record in self . records :
msgs . append ( " {:9s} {!r}" . fo... |
def hash_from_algo ( algo ) :
"""Return a : mod : ` hashlib ` hash given the : xep : ` 300 ` ` algo ` .
: param algo : The algorithm identifier as defined in : xep : ` 300 ` .
: type algo : : class : ` str `
: raises NotImplementedError : if the hash algortihm is not supported by
: mod : ` hashlib ` .
: r... | try :
enabled , ( fun_name , fun_args , fun_kwargs ) = _HASH_ALGO_MAP [ algo ]
except KeyError :
raise NotImplementedError ( "hash algorithm {!r} unknown" . format ( algo ) ) from None
if not enabled :
raise ValueError ( "support of {} in XMPP is forbidden" . format ( algo ) )
try :
fun = getattr ( hash... |
def traverse ( data , key , default = None , delimiter = DEFAULT_TARGET_DELIM ) :
'''Traverse a dict or list using a colon - delimited ( or otherwise delimited ,
using the ` ` delimiter ` ` param ) target string . The target ` ` foo : bar : 0 ` ` will
return ` ` data [ ' foo ' ] [ ' bar ' ] [ 0 ] ` ` if this va... | return _traverse_dict_and_list ( data , key , default = default , delimiter = delimiter ) |
def gen3d_conformer ( self ) :
"""A combined method to first generate 3D structures from 0D or 2D
structures and then find the minimum energy conformer :
1 . Use OBBuilder to create a 3D structure using rules and ring templates
2 . Do 250 steps of a steepest descent geometry optimization with the
MMFF94 for... | gen3d = ob . OBOp . FindType ( "Gen3D" )
gen3d . Do ( self . _obmol ) |
def label_present ( name , value , node = None , apiserver_url = None ) :
'''. . versionadded : : 2016.3.0
Set label to the current node
CLI Example :
. . code - block : : bash
salt ' * ' k8s . label _ present hw / disktype ssd
salt ' * ' k8s . label _ present hw / disktype ssd kube - node . cluster . loc... | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
# Get salt minion ID
node = _guess_node_id ( node )
# Try to get kubernetes master
apiserver_url = _guess_apiserver ( apiserver_url )
if apiserver_url is None :
return False
# Get all labels
labels = _get_labels ( node , apiserver_url )
if... |
def get_path ( self ) :
"""Gets the path to the focused statistics . Each step is a hash of
statistics object .""" | path = deque ( )
__ , node = self . get_focus ( )
while not node . is_root ( ) :
stats = node . get_value ( )
path . appendleft ( hash ( stats ) )
node = node . get_parent ( )
return path |
def get_filenames ( dirname ) :
"""Return all model output filenames inside a model output directory ,
sorted by iteration number .
Parameters
dirname : str
A path to a directory .
Returns
filenames : list [ str ]
Paths to all output files inside ` dirname ` , sorted in order of
increasing iteration... | filenames = glob . glob ( '{}/*.pkl' . format ( dirname ) )
return sorted ( filenames , key = _f_to_i ) |
def _execute ( self , sql , args ) :
"""执行sql语句
: param sql : sql语句
: param args : 参数
: return : 返回的都是数组对象""" | sql = sql . lower ( ) . strip ( )
args = args or ( )
tmp = sql [ : 6 ]
with ( yield self . _pool . Connection ( ) ) as conn :
try :
with conn . cursor ( ) as cursor :
yield cursor . execute ( sql , args = args )
if tmp == 'select' :
datas = cursor . fetchall ( )
... |
def tempoAdjust3 ( self , tempoFactor ) :
"""Adjust tempo by aggregating active basal cell votes for pre vs . post ( like tempoAdjust2)
- > if vote total = 0 ( tied ) , use result of last vote
: param tempoFactor : scaling signal to MC clock from last sequence item
: return : adjusted scaling signal""" | late_votes = ( len ( self . adtm . getNextBasalPredictedCells ( ) ) - len ( self . apicalIntersect ) ) * - 1
early_votes = len ( self . apicalIntersect )
votes = late_votes + early_votes
print ( 'vote tally' , votes )
if votes > 0 :
tempoFactor = tempoFactor * 0.5
self . prevVote = 0.5
print 'speed up'
elif... |
def make_redirect_url ( self , path_info , query_args = None , domain_part = None ) :
"""Creates a redirect URL .
: internal :""" | suffix = ''
if query_args :
suffix = '?' + self . encode_query_args ( query_args )
return str ( '%s://%s/%s%s' % ( self . url_scheme , self . get_host ( domain_part ) , posixpath . join ( self . script_name [ : - 1 ] . lstrip ( '/' ) , url_quote ( path_info . lstrip ( '/' ) , self . map . charset , safe = '/:|+' ) ... |
def get_by_id ( self , style_id , style_type ) :
"""Return the style of * style _ type * matching * style _ id * .
Returns the default for * style _ type * if * style _ id * is not found or is | None | , or
if the style having * style _ id * is not of * style _ type * .""" | if style_id is None :
return self . default ( style_type )
return self . _get_by_id ( style_id , style_type ) |
def create_push ( self , push , repository_id , project = None ) :
"""CreatePush .
Push changes to the repository .
: param : class : ` < GitPush > < azure . devops . v5_0 . git . models . GitPush > ` push :
: param str repository _ id : The name or ID of the repository .
: param str project : Project ID or... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if repository_id is not None :
route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' )
content = self . _serialize . body ( push , 'GitPu... |
def head ( self , file_path ) :
"""Onlye read the first packets that come , try to max out at 1024kb
: return : up to 1024b of the first block of the file""" | processor = lambda path , node , tail_only = True , append = False : self . _handle_head ( path , node )
# Find items and go
for item in self . _client . _find_items ( [ file_path ] , processor , include_toplevel = True , include_children = False , recurse = False ) :
if item :
return item |
def get_quoted_foreign_columns ( self , platform ) :
"""Returns the quoted representation of the referenced table column names
the foreign key constraint is associated with .
But only if they were defined with one or the referenced table column name
is a keyword reserved by the platform .
Otherwise the plai... | columns = [ ]
for column in self . _foreign_column_names . values ( ) :
columns . append ( column . get_quoted_name ( platform ) )
return columns |
def search_user_for_facet ( self , facet , ** kwargs ) : # noqa : E501
"""Lists the values of a specific facet over the customer ' s users # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . search_user_for_facet_with_http_info ( facet , ** kwargs )
# noqa : E501
else :
( data ) = self . search_user_for_facet_with_http_info ( facet , ** kwargs )
# noqa : E501
return data |
def _refine_stmt ( self , stmt : Statement , sctx : SchemaContext ) -> None :
"""Handle * * refine * * statement .""" | target = self . get_schema_descendant ( sctx . schema_data . sni2route ( stmt . argument , sctx ) )
if not sctx . schema_data . if_features ( stmt , sctx . text_mid ) :
target . parent . children . remove ( target )
else :
target . _handle_substatements ( stmt , sctx ) |
def selected_hazard_category ( self ) :
"""Obtain the hazard category selected by user .
: returns : Metadata of the selected hazard category .
: rtype : dict , None""" | item = self . lstHazardCategories . currentItem ( )
try :
return definition ( item . data ( QtCore . Qt . UserRole ) )
except ( AttributeError , NameError ) :
return None |
def watch ( self , username , watch = { "friend" : True , "deviations" : True , "journals" : True , "forum_threads" : True , "critiques" : True , "scraps" : True , "activity" : True , "collections" : True } ) :
"""Watch a user
: param username : The username you want to watch""" | if self . standard_grant_type is not "authorization_code" :
raise DeviantartError ( "Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint." )
response = self . _req ( '/user/friends/watch/{}' . format ( username ) , post_data = { "watch[friend]" : watch [ 'friend' ... |
def visit_ImportFrom ( self , node ) :
"""Visit an from - import node .""" | line = self . _code_lines [ node . lineno - 1 ]
module_name = line . split ( "from" ) [ 1 ] . split ( "import" ) [ 0 ] . strip ( )
for name in node . names :
imported_name = name . name
if name . asname :
imported_name = name . asname + "::" + imported_name
self . imported_names [ imported_name ] = ... |
def inject ( fun : Callable ) -> Callable :
"""A decorator for injection dependencies into functions / methods , based
on their type annotations .
. . code - block : : python
class SomeClass :
@ inject
def _ _ init _ _ ( self , my _ dep : DepType ) - > None :
self . my _ dep = my _ dep
. . important :... | sig = inspect . signature ( fun )
injectables : Dict [ str , Any ] = { }
for name , param in sig . parameters . items ( ) :
type_ = param . annotation
if name == 'self' :
continue
else :
injectables [ name ] = type_
@ wraps ( fun )
def _inner ( * args , ** kwargs ) :
container = Containe... |
def get_json_response_object ( self , datatable ) :
"""Returns the JSON - compatible dictionary that will be serialized for an AJAX response .
The value names are in the form " s ~ " for strings , " i ~ " for integers , and " a ~ " for arrays ,
if you ' re unfamiliar with the old C - style jargon used in dataTa... | # Ensure the object list is calculated .
# Calling get _ records ( ) will do this implicitly , but we want simultaneous access to the
# ' total _ initial _ record _ count ' , and ' unpaged _ record _ count ' values .
datatable . populate_records ( )
draw = getattr ( self . request , self . request . method ) . get ( 'd... |
def visit_BoolOp ( self , node ) :
"""Return type may come from any boolop operand .""" | return sum ( ( self . visit ( value ) for value in node . values ) , [ ] ) |
def unlink ( self ) :
"""Overrides orm unlink method .
@ param self : The object pointer
@ return : True / False .""" | sale_line_obj = self . env [ 'sale.order.line' ]
fr_obj = self . env [ 'folio.room.line' ]
for line in self :
if line . order_line_id :
sale_unlink_obj = ( sale_line_obj . browse ( [ line . order_line_id . id ] ) )
for rec in sale_unlink_obj :
room_obj = self . env [ 'hotel.room' ] . sea... |
def get_servers ( self ) :
"""Create the list of Server object inside the Datacenter objects .
Build an internal list of VM Objects ( pro or smart ) as iterator .
: return : bool""" | json_scheme = self . gen_def_json_scheme ( 'GetServers' )
json_obj = self . call_method_post ( method = 'GetServers' , json_scheme = json_scheme )
self . json_servers = json_obj
# if this method is called I assume that i must re - read the data
# so i reinitialize the vmlist
self . vmlist = VMList ( )
# getting all ins... |
def get_static ( root = None ) :
'''. . versionadded : : 2015.8.5
Return a list of all static services
root
Enable / disable / mask unit files in the specified root directory
CLI Example :
. . code - block : : bash
salt ' * ' service . get _ static''' | ret = set ( )
# Get static systemd units . Can ' t use - - state = static here because it ' s
# not present until systemd 216.
out = __salt__ [ 'cmd.run' ] ( _systemctl_cmd ( '--full --no-legend --no-pager list-unit-files' , root = root ) , python_shell = False , ignore_retcode = True )
for line in salt . utils . itert... |
def run ( self , host = None , port = None , debug = None , use_reloader = None , open_browser = False ) :
"""Starts a server to render the README .""" | if host is None :
host = self . config [ 'HOST' ]
if port is None :
port = self . config [ 'PORT' ]
if debug is None :
debug = self . debug
if use_reloader is None :
use_reloader = self . config [ 'DEBUG_GRIP' ]
# Verify the server is not already running and start
with self . _run_mutex :
if self . ... |
def getopt_default ( self , option ) :
"""Default method to get an option""" | if option not in self . conf :
print ( "Unrecognized option %r" % option )
return
print ( "%s: %s" % ( option , self . conf [ option ] ) ) |
def beacon ( config ) :
'''Scan the shell execve routines . This beacon will convert all login shells
. . code - block : : yaml
beacons :
sh : [ ]''' | ret = [ ]
pkey = 'sh.vt'
shells = _get_shells ( )
ps_out = __salt__ [ 'status.procs' ] ( )
track_pids = [ ]
for pid in ps_out :
if any ( ps_out [ pid ] . get ( 'cmd' , '' ) . lstrip ( '-' ) in shell for shell in shells ) :
track_pids . append ( pid )
if pkey not in __context__ :
__context__ [ pkey ] = {... |
def accumulate ( self , buf ) :
'''add in some more bytes''' | accum = self . crc
for b in buf :
tmp = b ^ ( accum & 0xff )
tmp = ( tmp ^ ( tmp << 4 ) ) & 0xFF
accum = ( accum >> 8 ) ^ ( tmp << 8 ) ^ ( tmp << 3 ) ^ ( tmp >> 4 )
self . crc = accum |
def _backwards_aliases ( self ) :
"""In order to keep this backwards - compatible with previous versions ,
alias the old names to the new methods .""" | self . list_containers = self . list_container_names
self . get_all_containers = self . list
self . get_container = self . get
self . create_container = self . create
self . delete_container = self . delete
self . get_container_objects = self . list_container_objects
self . get_container_object_names = self . list_cont... |
def get_num_nodes ( properties = None , hadoop_conf_dir = None , offline = False ) :
"""Get the number of task trackers in the Hadoop cluster .
All arguments are passed to : func : ` get _ task _ trackers ` .""" | return len ( get_task_trackers ( properties , hadoop_conf_dir , offline ) ) |
def _connect ( self , id_mask ) :
"""Connects to all of the load cells serially .""" | # Get all devices attached as USB serial
all_devices = glob . glob ( '/dev/ttyUSB*' )
# Identify which of the devices are LoadStar Serial Sensors
sensors = [ ]
for device in all_devices :
try :
ser = serial . Serial ( port = device , timeout = 0.5 , exclusive = True )
ser . write ( 'ID\r' )
... |
def package_data ( pkg , root_list ) :
"""Generic function to find package _ data for ` pkg ` under ` root ` .""" | data = [ ]
for root in root_list :
for dirname , _ , files in os . walk ( os . path . join ( pkg , root ) ) :
for fname in files :
data . append ( os . path . relpath ( os . path . join ( dirname , fname ) , pkg ) )
return { pkg : data } |
def deleteBy ( self , func ) :
'Delete rows for which func ( row ) is true . Returns number of deleted rows .' | oldrows = copy ( self . rows )
oldidx = self . cursorRowIndex
ndeleted = 0
row = None
# row to re - place cursor after
while oldidx < len ( oldrows ) :
if not func ( oldrows [ oldidx ] ) :
row = self . rows [ oldidx ]
break
oldidx += 1
self . rows . clear ( )
for r in Progress ( oldrows , 'delet... |
def dc_element ( self , parent , name , text ) :
"""Add DC element ` name ` containing ` text ` to ` parent ` .""" | if self . dc_uri in self . namespaces :
dcel = SchemaNode ( self . namespaces [ self . dc_uri ] + ":" + name , text = text )
parent . children . insert ( 0 , dcel ) |
def append ( self , other , inplace = True , pad = None , gap = None , resize = True ) :
"""Connect another series onto the end of the current one .
Parameters
other : ` Series `
another series of the same type to connect to this one
inplace : ` bool ` , optional
perform operation in - place , modifying c... | if gap is None :
gap = 'raise' if pad is None else 'pad'
if pad is None and gap == 'pad' :
pad = 0.
# check metadata
self . is_compatible ( other )
# make copy if needed
if not inplace :
self = self . copy ( )
# fill gap
if self . is_contiguous ( other ) != 1 :
if gap == 'pad' :
ngap = floor ( (... |
def setup_migrate ( app ) :
"""Setup flask - migrate .""" | directory = path . join ( path . dirname ( __file__ ) , 'migrations' )
migrate . init_app ( app , db , directory = directory ) |
async def restore_networking_configuration ( self ) :
"""Restore machine ' s networking configuration to its initial state .""" | self . _data = await self . _handler . restore_networking_configuration ( system_id = self . system_id ) |
def show_tracebacks ( self ) :
"""Show tracebacks""" | if self . broker . tracebacks :
for tb in self . broker . tracebacks . values ( ) : # tb = " Traceback { 0 } " . format ( str ( tb ) )
self . logit ( str ( tb ) , self . pid , self . user , "insights-run" , logging . ERROR ) |
def get_or_add_ext_rel ( self , reltype , target_ref ) :
"""Return rId of external relationship of * reltype * to * target _ ref * ,
newly added if not already present in collection .""" | rel = self . _get_matching ( reltype , target_ref , is_external = True )
if rel is None :
rId = self . _next_rId
rel = self . add_relationship ( reltype , target_ref , rId , is_external = True )
return rel . rId |
def descendants ( obj , refattrs = ( SEGMENTATION , ALIGNMENT ) , follow = 'first' ) :
"""> > > for des in query . descendants ( igt . get _ item ( ' p1 ' ) , refattrs = ( SEGMENTATION , ALIGNMENT ) ) :
. . . print ( des )
( < Tier object ( id : p type : phrases ) at . . . > , ' segmentation ' , < Tier object (... | if hasattr ( obj , 'tier' ) :
tier = obj . tier
items = [ obj ]
else :
tier = obj
items = tier . items
igt = tier . igt
visited = set ( )
agenda = deque ( [ ( tier , items ) ] )
while agenda :
tier , items = agenda . popleft ( )
tier_refs = tier . referrers ( refattrs )
item_ids = set ( item... |
def _handle_authn_request ( self , context , binding_in , idp ) :
"""See doc for handle _ authn _ request method .
: type context : satosa . context . Context
: type binding _ in : str
: type idp : saml . server . Server
: rtype : satosa . response . Response
: param context : The current context
: para... | req_info = idp . parse_authn_request ( context . request [ "SAMLRequest" ] , binding_in )
authn_req = req_info . message
satosa_logging ( logger , logging . DEBUG , "%s" % authn_req , context . state )
try :
resp_args = idp . response_args ( authn_req )
except SAMLError as e :
satosa_logging ( logger , logging ... |
def _report_problem ( self , problem , level = logging . ERROR ) :
'''Report a given problem''' | problem = self . basename + ': ' + problem
if self . _logger . isEnabledFor ( level ) :
self . _problematic = True
if self . _check_raises :
raise DapInvalid ( problem )
self . _logger . log ( level , problem ) |
def read ( self , size = - 1 ) :
"""Read at most ` size ` bytes from the file ( less if there
isn ' t enough data ) .
The bytes are returned as an instance of : class : ` str ` ( : class : ` bytes `
in python 3 ) . If ` size ` is negative or omitted all data is read .
: Parameters :
- ` size ` ( optional ... | self . _ensure_file ( )
if size == 0 :
return EMPTY
remainder = int ( self . length ) - self . __position
if size < 0 or size > remainder :
size = remainder
received = 0
data = StringIO ( )
while received < size :
chunk_data = self . readchunk ( )
received += len ( chunk_data )
data . write ( chunk_... |
def save ( path , im ) :
"""Saves an image to file .
If the image is type float , it will assume to have values in [ 0 , 1 ] .
Parameters
path : str
Path to which the image will be saved .
im : ndarray ( image )
Image .""" | from PIL import Image
if im . dtype == np . uint8 :
pil_im = Image . fromarray ( im )
else :
pil_im = Image . fromarray ( ( im * 255 ) . astype ( np . uint8 ) )
pil_im . save ( path ) |
def kvp_convert ( input_coll ) :
'''Converts a list of string attributes and / or tuples into an OrderedDict .
If passed in an OrderedDict , function is idempotent .
Key / value pairs map to ` first _ tuple _ element ` - > ` second _ tuple _ element ` if
a tuple , or ` scalar _ value ` - > None if not a tuple... | if isinstance ( input_coll , OrderedDict ) :
return input_coll
else :
return OrderedDict ( ( l , None ) if not isinstance ( l , tuple ) else ( l [ 0 ] , l [ 1 ] ) for l in input_coll ) |
def add_response_headers ( h ) :
"""Add HTTP - headers to response .
Example :
@ add _ response _ headers ( { ' Refresh ' : ' 10 ' , ' X - Powered - By ' : ' Django ' } )
def view ( request ) :""" | def headers_wrapper ( fun ) :
def wrapped_function ( * args , ** kwargs ) :
response = fun ( * args , ** kwargs )
for k , v in h . iteritems ( ) :
response [ k ] = v
return response
return wrapped_function
return headers_wrapper |
def evaluate_postfix ( tokens ) :
"""Given a list of evaluatable tokens in postfix format ,
calculate a solution .""" | stack = [ ]
for token in tokens :
total = None
if is_int ( token ) or is_float ( token ) or is_constant ( token ) :
stack . append ( token )
elif is_unary ( token ) :
a = stack . pop ( )
total = mathwords . UNARY_FUNCTIONS [ token ] ( a )
elif len ( stack ) :
b = stack . ... |
def scan ( self , concurrency = 1 ) :
"""Iterates over the applications installed within the disk
and queries the CVE DB to determine whether they are vulnerable .
Concurrency controls the amount of concurrent queries
against the CVE DB .
For each vulnerable application the method yields a namedtuple :
Vu... | self . logger . debug ( "Scanning FS content." )
with ThreadPoolExecutor ( max_workers = concurrency ) as executor :
results = executor . map ( self . query_vulnerabilities , self . applications ( ) )
for report in results :
application , vulnerabilities = report
vulnerabilities = list ( lookup_vulnerabilit... |
def get_path ( self , path ) :
"""Construct a Path object from a path string .
The Path string must be declared in the API .
: type path : str
: rtype : lepo . path . Path""" | mapping = self . get_path_mapping ( path )
return self . path_class ( api = self , path = path , mapping = mapping ) |
def get_input_widget ( self , fieldname , arnum = 0 , ** kw ) :
"""Get the field widget of the AR in column < arnum >
: param fieldname : The base fieldname
: type fieldname : string""" | # temporary AR Context
context = self . get_ar ( )
# request = self . request
schema = context . Schema ( )
# get original field in the schema from the base _ fieldname
base_fieldname = fieldname . split ( "-" ) [ 0 ]
field = context . getField ( base_fieldname )
# fieldname with - < arnum > suffix
new_fieldname = self... |
def encode ( data , encoding = None , errors = 'strict' , keep = False , preserve_dict_class = False , preserve_tuples = False ) :
'''Generic function which will encode whichever type is passed , if necessary
If ` strict ` is True , and ` keep ` is False , and we fail to encode , a
UnicodeEncodeError will be ra... | if isinstance ( data , Mapping ) :
return encode_dict ( data , encoding , errors , keep , preserve_dict_class , preserve_tuples )
elif isinstance ( data , list ) :
return encode_list ( data , encoding , errors , keep , preserve_dict_class , preserve_tuples )
elif isinstance ( data , tuple ) :
return encode_... |
def _read_softgz ( filename ) -> AnnData :
"""Read a SOFT format data file .
The SOFT format is documented here
http : / / www . ncbi . nlm . nih . gov / geo / info / soft2 . html .
Notes
The function is based on a script by Kerby Shedden .
http : / / dept . stat . lsa . umich . edu / ~ kshedden / Python ... | filename = str ( filename )
# allow passing pathlib . Path objects
import gzip
with gzip . open ( filename , mode = 'rt' ) as file : # The header part of the file contains information about the
# samples . Read that information first .
samples_info = { }
for line in file :
if line . startswith ( "!datas... |
def weighted_choice ( choices , weight ) :
"""Make a random selection from the specified choices . Apply the * weight *
function to each to return a positive integer representing shares of
selection pool the choice should received . The * weight * function is passed a
single argument of the choice from the * ... | # requirements = random
weights = [ ]
# get weight values for each of the choices
for choice in choices :
choice_weight = weight ( choice )
if not ( isinstance ( choice_weight , int ) and choice_weight > 0 ) :
raise TypeError ( 'weight results must be positive integers' )
weights . append ( choice_w... |
def db_exec_literal ( self , sql : str ) -> int :
"""Executes SQL without modification . Returns rowcount .""" | self . ensure_db_open ( )
cursor = self . db . cursor ( )
debug_sql ( sql )
try :
cursor . execute ( sql )
return cursor . rowcount
except : # nopep8
log . exception ( "db_exec_literal: SQL was: " + sql )
raise |
def parse_cl_args ( arg_vector ) :
'''Parses the command line arguments''' | parser = argparse . ArgumentParser ( description = 'Compiles markdown files into html files for remark.js' )
parser . add_argument ( 'source' , metavar = 'source' , help = 'the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the current working direct... |
def get_domain_list ( list_name ) :
'''Retrieves a specific policy domain name list .
list _ name ( str ) : The name of the specific policy domain name list to retrieve .
CLI Example :
. . code - block : : bash
salt ' * ' bluecoat _ sslv . get _ domain _ list MyDomainNameList''' | payload = { "jsonrpc" : "2.0" , "id" : "ID0" , "method" : "get_policy_domain_names" , "params" : [ list_name , 0 , 256 ] }
response = __proxy__ [ 'bluecoat_sslv.call' ] ( payload , False )
return _convert_to_list ( response , 'item_name' ) |
def is_visit_primitive ( obj ) :
'''Returns true if properly visiting the object returns only the object itself .''' | from . base import visit
if ( isinstance ( obj , tuple ( PRIMITIVE_TYPES ) ) and not isinstance ( obj , STR ) and not isinstance ( obj , bytes ) ) :
return True
if ( isinstance ( obj , CONTAINERS ) and not isinstance ( obj , STR ) and not isinstance ( obj , bytes ) ) :
return False
if isinstance ( obj , STR ) o... |
def check_missing_files ( client ) :
"""Find missing files listed in datasets .""" | missing = defaultdict ( list )
for path , dataset in client . datasets . items ( ) :
for file in dataset . files :
filepath = ( path . parent / file )
if not filepath . exists ( ) :
missing [ str ( path . parent . relative_to ( client . renku_datasets_path ) ) ] . append ( os . path . no... |
def _reply_json ( self , json_payload , status_code = 200 ) :
"""Return a JSON - serializable data structure""" | self . _send_headers ( status_code = status_code )
json_str = json . dumps ( json_payload )
self . wfile . write ( json_str ) |
def tokens ( istr ) :
"""Same as tokenize , but returns only tokens
( and at all parantheses levels ) .""" | # make a list of all alphanumeric tokens
toks = re . findall ( r'[^\*\\\+\-\^\(\)]+\(?' , istr )
# remove the functions
return [ t for t in toks if not t . endswith ( '(' ) ] |
def delete_project ( self , project_name ) :
"""delete project
Unsuccessful opertaion will cause an LogException .
: type project _ name : string
: param project _ name : the Project name
: return : DeleteProjectResponse
: raise : LogException""" | headers = { }
params = { }
resource = "/"
( resp , header ) = self . _send ( "DELETE" , project_name , None , resource , params , headers )
return DeleteProjectResponse ( header , resp ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.