signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def set_header ( self , name : str , value : _HeaderTypes ) -> None :
"""Sets the given response header name and value .
All header values are converted to strings ( ` datetime ` objects
are formatted according to the HTTP specification for the
` ` Date ` ` header ) .""" | self . _headers [ name ] = self . _convert_header_value ( value ) |
def bracketOrder ( self , action : str , quantity : float , limitPrice : float , takeProfitPrice : float , stopLossPrice : float , ** kwargs ) -> BracketOrder :
"""Create a limit order that is bracketed by a take - profit order and
a stop - loss order . Submit the bracket like :
. . code - block : : python
fo... | assert action in ( 'BUY' , 'SELL' )
reverseAction = 'BUY' if action == 'SELL' else 'SELL'
parent = LimitOrder ( action , quantity , limitPrice , orderId = self . client . getReqId ( ) , transmit = False , ** kwargs )
takeProfit = LimitOrder ( reverseAction , quantity , takeProfitPrice , orderId = self . client . getReq... |
def from_time_ranges ( cls , min_times , max_times , delta_t = DEFAULT_OBSERVATION_TIME ) :
"""Create a TimeMOC from a range defined by two ` astropy . time . Time `
Parameters
min _ times : ` astropy . time . Time `
astropy times defining the left part of the intervals
max _ times : ` astropy . time . Time... | min_times_arr = np . asarray ( min_times . jd * TimeMOC . DAY_MICRO_SEC , dtype = int )
max_times_arr = np . asarray ( max_times . jd * TimeMOC . DAY_MICRO_SEC , dtype = int )
intervals_arr = np . vstack ( ( min_times_arr , max_times_arr + 1 ) ) . T
# degrade the TimeMoc to the order computer from ` ` delta _ t ` `
ord... |
def _unpack ( self , data ) :
"""Unpacks the given byte string and parses the result from JSON .
Returns None on failure and saves data into " self . buffer " .""" | msg_magic , msg_length , msg_type = self . _unpack_header ( data )
msg_size = self . _struct_header_size + msg_length
# XXX : Message shouldn ' t be any longer than the data
payload = data [ self . _struct_header_size : msg_size ]
return payload . decode ( 'utf-8' , 'replace' ) |
def load_filters ( self ) :
"""Load filter module ( s )""" | for f in sorted ( logdissect . filters . __filters__ ) :
self . filter_modules [ f ] = __import__ ( 'logdissect.filters.' + f , globals ( ) , locals ( ) , [ logdissect ] ) . FilterModule ( args = self . filter_args ) |
def new ( self , name = None , stack = 'cedar' , region = None ) :
"""Creates a new app .""" | payload = { }
if name :
payload [ 'app[name]' ] = name
if stack :
payload [ 'app[stack]' ] = stack
if region :
payload [ 'app[region]' ] = region
r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , ) , data = payload )
name = json . loads ( r . content ) . get ( 'name' )
return self . _... |
def share ( self , group_id , group_access , expires_at = None , ** kwargs ) :
"""Share the project with a group .
Args :
group _ id ( int ) : ID of the group .
group _ access ( int ) : Access level for the group .
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenti... | path = '/projects/%s/share' % self . get_id ( )
data = { 'group_id' : group_id , 'group_access' : group_access , 'expires_at' : expires_at }
self . manager . gitlab . http_post ( path , post_data = data , ** kwargs ) |
def send_keys ( key_string ) :
"""sends the text or keys to the active application using shell
Note , that the imp module shows deprecation warning .
Examples :
shell . SendKeys ( " ^ a " ) # CTRL + A
shell . SendKeys ( " { DELETE } " ) # Delete key
shell . SendKeys ( " hello this is a lot of text with a ... | try :
shell = win32com . client . Dispatch ( "WScript.Shell" )
shell . SendKeys ( key_string )
except Exception as ex :
print ( 'error calling win32com.client.Dispatch (SendKeys)' ) |
def clear ( * objects_to_clear ) :
"""Clears allowances / expectations on objects
: param object objects _ to _ clear : The objects to remove allowances and
expectations from .""" | if not hasattr ( _thread_local_data , 'current_space' ) :
return
space = current_space ( )
for obj in objects_to_clear :
space . clear ( obj ) |
def main ( ) :
"""Build and parse command line .""" | parser = argument_parser ( version = __version__ )
args = parser . parse_args ( )
if args . debug :
log_level = logging . DEBUG
elif args . verbose :
log_level = logging . INFO
else :
log_level = logging . WARNING
logging . basicConfig ( format = '%(levelname)s: %(message)s' , level = log_level )
max_retrie... |
def remove ( self , interval ) :
"""Returns self after removing the interval and balancing .
If interval is not present , raise ValueError .""" | # since this is a list , called methods can set this to [ 1 ] ,
# making it true
done = [ ]
return self . remove_interval_helper ( interval , done , should_raise_error = True ) |
def get_site_packages ( venv ) :
'''Return the path to the site - packages directory of a virtualenv
venv
Path to the virtualenv .
CLI Example :
. . code - block : : bash
salt ' * ' virtualenv . get _ site _ packages / path / to / my / venv''' | bin_path = _verify_virtualenv ( venv )
ret = __salt__ [ 'cmd.exec_code_all' ] ( bin_path , 'from distutils import sysconfig; ' 'print(sysconfig.get_python_lib())' )
if ret [ 'retcode' ] != 0 :
raise CommandExecutionError ( '{stdout}\n{stderr}' . format ( ** ret ) )
return ret [ 'stdout' ] |
def digest ( args ) :
"""% prog digest fastafile NspI , BfuCI
Digest fasta sequences to map restriction site positions .""" | p = OptionParser ( digest . __doc__ )
p . set_outfile ( )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
fastafile , enzymes = args
enzymes = enzymes . split ( "," )
enzymes = [ x for x in AllEnzymes if str ( x ) in enzymes ]
f = Fasta ( fastafile , lazy = True )
... |
def _havdalah_datetime ( self ) :
"""Compute the havdalah time based on settings .""" | if self . havdalah_offset == 0 :
return self . zmanim [ "three_stars" ]
# Otherwise , use the offset .
return ( self . zmanim [ "sunset" ] + dt . timedelta ( minutes = self . havdalah_offset ) ) |
def fromutc ( self , dt ) :
'''See datetime . tzinfo . fromutc''' | dt = dt . replace ( tzinfo = None )
idx = max ( 0 , bisect_right ( self . _utc_transition_times , dt ) - 1 )
inf = self . _transition_info [ idx ]
return ( dt + inf [ 0 ] ) . replace ( tzinfo = self . _tzinfos [ inf ] ) |
def maximin_distance_subset1d ( items , K = None , min_thresh = None , verbose = False ) :
r"""Greedy algorithm , may be exact for 1d case .
First , choose the first item , then choose the next item that is farthest
away from all previously chosen items . Iterate .
CommandLine :
python - m utool . util _ al... | if False :
import pulp
# Formulate integer program
prob = pulp . LpProblem ( "MaxSizeLargeDistSubset" , pulp . LpMaximize )
# Solution variable indicates if set it chosen or not
item_indices = list ( range ( len ( items ) ) )
pair_indices = list ( ut . combinations ( item_indices , 2 ) )
x =... |
def visit_FunctionDef ( self , node ) :
"""Initialize variable for the current function to add edges from calls .
We compute variable to call dependencies and add edges when returns
are reach .""" | # Ensure there are no nested functions .
assert self . current_function is None
self . current_function = node
self . naming = dict ( )
self . in_cond = False
# True when we are in a if , while or for
self . generic_visit ( node )
self . current_function = None |
def updatePassword ( self , user , currentPassword , newPassword ) :
"""Change the password of a user .""" | return self . __post ( '/api/updatePassword' , data = { 'user' : user , 'currentPassword' : currentPassword , 'newPassword' : newPassword } ) |
async def play ( self ) :
"""Starts playback from lavalink .""" | if self . repeat and self . current is not None :
self . queue . append ( self . current )
self . current = None
self . position = 0
self . _paused = False
if not self . queue :
await self . stop ( )
else :
self . _is_playing = True
if self . shuffle :
track = self . queue . pop ( randrange ( le... |
def slugify ( s ) :
"""Convert any string to a " slug " , a simplified form suitable for filename and URL part .
EXAMPLE : " Trees about bees " = > ' trees - about - bees '
EXAMPLE : " My favorites ! " = > ' my - favorites '
N . B . that its behavior should match this client - side slugify function , so
we ... | slug = s . lower ( )
# force to lower case
slug = re . sub ( '[^a-z0-9 -]' , '' , slug )
# remove invalid chars
slug = re . sub ( r'\s+' , '-' , slug )
# collapse whitespace and replace by -
slug = re . sub ( '-+' , '-' , slug )
# collapse dashes
if not slug :
slug = 'untitled'
return slug |
def clean ( ctx ) :
"""Clean previously built package artifacts .""" | ctx . run ( f"python setup.py clean" )
dist = ROOT . joinpath ( "dist" )
build = ROOT . joinpath ( "build" )
print ( f"[clean] Removing {dist} and {build}" )
if dist . exists ( ) :
shutil . rmtree ( str ( dist ) )
if build . exists ( ) :
shutil . rmtree ( str ( build ) ) |
def is_valid ( n ) :
"""Python function to verify if the frequency of every digit does not exceed its own value .
Examples :
is _ valid ( 1234 ) - > True
is _ valid ( 51241 ) - > False
is _ valid ( 321 ) - > True""" | for i in range ( 10 ) :
temp = n
frequency = 0
while temp :
if ( ( temp % 10 ) == i ) :
frequency += 1
if ( frequency > i ) :
return False
temp //= 10
return True |
def start_auth ( self , context , request_info ) :
"""See super class method satosa . backends . base # start _ auth
: type context : satosa . context . Context
: type request _ info : satosa . internal . InternalData""" | oidc_nonce = rndstr ( )
oidc_state = rndstr ( )
state_data = { NONCE_KEY : oidc_nonce , STATE_KEY : oidc_state }
context . state [ self . name ] = state_data
args = { "scope" : self . config [ "client" ] [ "auth_req_params" ] [ "scope" ] , "response_type" : self . config [ "client" ] [ "auth_req_params" ] [ "response_t... |
def recruit_participants ( self , n = 1 , exp = None ) :
"""Recruit n participants .""" | for i in xrange ( n ) :
newcomer = exp . agent_type ( )
exp . newcomer_arrival_trigger ( newcomer ) |
def operator_numeric_type ( method ) :
"""Intended to wrap operator methods , this decorator ensures a numeric type
was passed .
: param method : The method being decorated .
: return : The wrapper to replace the method with .""" | def wrapper ( self , other ) :
if not isinstance ( other , _NUMERIC_TYPES ) :
raise TypeError ( 'unsupported operand types: \'{0}\' and \'{1}\'' . format ( self . __class__ . __name__ , other . __class__ . __name__ ) )
return method ( self , other )
return wrapper |
def _run_train ( ppo_hparams , event_dir , model_dir , restarter , train_summary_op , eval_summary_op , initializers , report_fn = None , model_save_fn = None ) :
"""Train .""" | summary_writer = tf . summary . FileWriter ( event_dir , graph = tf . get_default_graph ( ) , flush_secs = 60 )
model_saver = tf . train . Saver ( tf . global_variables ( ppo_hparams . policy_network + "/.*" ) + tf . global_variables ( "training/" + ppo_hparams . policy_network + "/.*" ) + # tf . global _ variables ( "... |
def setup ( app ) :
'''Required Sphinx extension setup function .''' | app . add_config_value ( 'bokeh_gallery_dir' , join ( "docs" , "gallery" ) , 'html' )
app . connect ( 'config-inited' , config_inited_handler )
app . add_directive ( 'bokeh-gallery' , BokehGalleryDirective ) |
def maelstrom ( args ) :
"""Run the maelstrom method .""" | infile = args . inputfile
genome = args . genome
outdir = args . outdir
pwmfile = args . pwmfile
methods = args . methods
ncpus = args . ncpus
if not os . path . exists ( infile ) :
raise ValueError ( "file {} does not exist" . format ( infile ) )
if methods :
methods = [ x . strip ( ) for x in methods . split ... |
def openconfig_lacp ( device_name = None ) :
'''. . versionadded : : 2019.2.0
Return a dictionary structured as standardised in the
` openconfig - lacp < http : / / ops . openconfig . net / branches / master / openconfig - lacp . html > ` _
YANG model , with configuration data for Link Aggregation Control Pro... | oc_lacp = { }
interfaces = get_interfaces ( device_name = device_name )
for interface in interfaces :
if not interface [ 'lag' ] :
continue
if_name , if_unit = _if_name_unit ( interface [ 'name' ] )
parent_if = interface [ 'lag' ] [ 'name' ]
if parent_if not in oc_lacp :
oc_lacp [ parent... |
def get_learning_objective_ids ( self ) :
"""This method mirrors that in the Item .
So that questions can also be inspected for learning objectives""" | if 'learningObjectiveIds' not in self . _my_map : # Will this ever be the case ?
collection = JSONClientValidated ( 'assessment' , collection = 'Item' , runtime = self . _runtime )
item_map = collection . find_one ( { '_id' : ObjectId ( Id ( self . _my_map [ 'itemId' ] ) . get_identifier ( ) ) } )
self . _m... |
def do_use ( self , region ) :
"""Switch the AWS region
> use us - west - 1
> use us - east - 1""" | if self . _local_endpoint is not None :
host , port = self . _local_endpoint
# pylint : disable = W0633
self . engine . connect ( region , session = self . session , host = host , port = port , is_secure = False )
else :
self . engine . connect ( region , session = self . session ) |
def timeOneSearch ( queryString ) :
"""Returns ( search result as JSON string , time elapsed during search )""" | startTime = time . clock ( )
resultString = backend . runSearchVariants ( queryString )
endTime = time . clock ( )
elapsedTime = endTime - startTime
return resultString , elapsedTime |
def writeTicks ( self , ticks ) :
'''read quotes''' | tName = self . tableName ( HBaseDAM . TICK )
if tName not in self . __hbase . getTableNames ( ) :
self . __hbase . createTable ( tName , [ ColumnDescriptor ( name = HBaseDAM . TICK , maxVersions = 5 ) ] )
for tick in ticks :
self . __hbase . updateRow ( self . tableName ( HBaseDAM . TICK ) , tick . time , [ Mut... |
def node ( self , name , label = None , _attributes = None , ** attrs ) :
"""Create a node .
Args :
name : Unique identifier for the node inside the source .
label : Caption to be displayed ( defaults to the node ` ` name ` ` ) .
attrs : Any additional node attributes ( must be strings ) .""" | name = self . _quote ( name )
attr_list = self . _attr_list ( label , attrs , _attributes )
line = self . _node % ( name , attr_list )
self . body . append ( line ) |
def get_report_data_rows ( self , request , queryset ) :
"""Using the builders for the queryset model , iterates over the queryset to generate a result
with headers and rows . This queryset must be the exact same received in the . process method ,
which tells us that this function should be called inside . proc... | model = queryset . model
meta = model . _meta
field_names = set ( field . name for field in meta . fields )
list_report = self . get_list_report ( request ) or field_names
queried_field_named = [ l for l in list_report if l in field_names ] or [ 'id' ]
columns = self . get_report_column_builders ( request , model )
hea... |
def initial_contact ( self , enable_ssh = True , time_zone = None , keyboard = None , install_on_server = None , filename = None , as_base64 = False ) :
"""Allows to save the initial contact for for the specified node
: param bool enable _ ssh : flag to know if we allow the ssh daemon on the
specified node
: ... | result = self . make_request ( NodeCommandFailed , method = 'create' , raw_result = True , resource = 'initial_contact' , params = { 'enable_ssh' : enable_ssh } )
if result . content :
if as_base64 :
result . content = b64encode ( result . content )
if filename :
try :
save_to_file (... |
def loader_for_file ( filename ) :
"""Returns a Loader that can load the specified file , based on the file extension . None if failed to determine .
: param filename : the filename to get the loader for
: type filename : str
: return : the assoicated loader instance or None if none found
: rtype : Loader""... | loader = javabridge . static_call ( "weka/core/converters/ConverterUtils" , "getLoaderForFile" , "(Ljava/lang/String;)Lweka/core/converters/AbstractFileLoader;" , filename )
if loader is None :
return None
else :
return Loader ( jobject = loader ) |
def transform_33_32 ( inst , new_inst , i , n , offset , instructions , new_asm ) :
"""MAKE _ FUNCTION , and MAKE _ CLOSURE have an additional LOAD _ CONST of a name
that are not in Python 3.2 . Remove these .""" | add_size = xdis . op_size ( new_inst . opcode , opcode_33 )
if inst . opname in ( 'MAKE_FUNCTION' , 'MAKE_CLOSURE' ) : # Previous instruction should be a load const which
# contains the name of the function to call
prev_inst = instructions [ i - 1 ]
assert prev_inst . opname == 'LOAD_CONST'
assert isinstanc... |
def _obj ( self ) :
"""Get an objective .""" | class Objectives ( object ) :
def __getitem__ ( _self , name ) :
return self . getObjective ( name )
def __iter__ ( _self ) :
return self . getObjectives ( )
return Objectives ( ) |
def _parse_response ( self , resp ) :
"""Gets the authentication information from the returned JSON .""" | super ( RaxIdentity , self ) . _parse_response ( resp )
user = resp [ "access" ] [ "user" ]
defreg = user . get ( "RAX-AUTH:defaultRegion" )
if defreg :
self . _default_region = defreg |
def static_url ( redis , path ) :
"""Gets the static path for a file""" | file_hash = get_cache_buster ( redis , path )
return "%s/%s?v=%s" % ( oz . settings [ "static_host" ] , path , file_hash ) |
def plot_data ( self ) :
"""Plots the loaded data""" | # Clear the plot before plotting onto it
self . ax . cla ( )
if self . sample is None :
return
if self . current_channels is None :
self . current_channels = self . sample . channel_names [ : 2 ]
channels = self . current_channels
channels_to_plot = channels [ 0 ] if len ( channels ) == 1 else channels
self . s... |
def initialize_dag ( self , targets : Optional [ List [ str ] ] = [ ] , nested : bool = False ) -> SoS_DAG :
'''Create a DAG by analyzing sections statically .''' | self . reset_dict ( )
dag = SoS_DAG ( name = self . md5 )
targets = sos_targets ( targets )
self . add_forward_workflow ( dag , self . workflow . sections )
if self . resolve_dangling_targets ( dag , targets ) == 0 :
if targets :
raise UnknownTarget ( f'No step to generate target {targets}.' )
# now , there... |
def get_by_example_skiplist ( cls , collection , index_id , example_data , allow_multiple = True , skip = None , limit = None ) :
"""This will find all documents matching a given example , using the specified skiplist index .
: param collection Collection instance
: param index _ id ID of the index which should... | kwargs = { 'index' : index_id , 'skip' : skip , 'limit' : limit , }
return cls . _construct_query ( name = 'by-example-skiplist' , collection = collection , example = example_data , multiple = allow_multiple , ** kwargs ) |
def create_attributes ( self , cell , cell_type = None ) :
"""Turn the attribute dict into an attribute string
for the code block .""" | if self . strip_outputs or not hasattr ( cell , 'execution_count' ) :
return 'python'
attrs = cell . metadata . get ( 'attributes' )
attr = PandocAttributes ( attrs , 'dict' )
if 'python' in attr . classes :
attr . classes . remove ( 'python' )
if 'input' in attr . classes :
attr . classes . remove ( 'input... |
def _format_host ( host , data , indent_level = 1 ) :
'''Main highstate formatter . can be called recursively if a nested highstate
contains other highstates ( ie in an orchestration )''' | host = salt . utils . data . decode ( host )
colors = salt . utils . color . get_colors ( __opts__ . get ( 'color' ) , __opts__ . get ( 'color_theme' ) )
tabular = __opts__ . get ( 'state_tabular' , False )
rcounts = { }
rdurations = [ ]
hcolor = colors [ 'GREEN' ]
hstrs = [ ]
nchanges = 0
strip_colors = __opts__ . get... |
def get_state ( cls , clz ) :
"""Retrieve the state of a given Class .
: param clz : types . ClassType
: return : Class state .
: rtype : dict""" | if clz not in cls . __shared_state :
cls . __shared_state [ clz ] = ( clz . init_state ( ) if hasattr ( clz , "init_state" ) else { } )
return cls . __shared_state [ clz ] |
def computePi ( self , method = 'power' ) :
"""Calculate the steady state distribution using your preferred method and store it in the attribute ` pi ` .
By default uses the most robust method , ' power ' . Other methods are ' eigen ' , ' linear ' , and ' krylov '
Parameters
method : string , optional ( defau... | methodSet = [ 'power' , 'eigen' , 'linear' , 'krylov' ]
assert method in methodSet , "Incorrect method specified. Choose from %r" % methodSet
method = method + 'Method'
return getattr ( self , method ) ( ) |
def dict_isect_combine ( dict1 , dict2 , combine_op = op . add ) :
"""Intersection of dict keys and combination of dict values""" | keys3 = set ( dict1 . keys ( ) ) . intersection ( set ( dict2 . keys ( ) ) )
dict3 = { key : combine_op ( dict1 [ key ] , dict2 [ key ] ) for key in keys3 }
return dict3 |
def placeOrder ( self , contract , order , orderId = None , account = None ) :
"""Place order on IB TWS""" | # get latest order id before submitting an order
self . requestOrderIds ( )
# continue . . .
useOrderId = self . orderId if orderId == None else orderId
if account :
order . m_account = account
self . ibConn . placeOrder ( useOrderId , contract , order )
account_key = order . m_account
self . orders [ useOrderId ] ... |
def ssh_cmd ( self , name , ssh_command ) :
"""SSH into given container and executre command if given""" | if not self . container_exists ( name = name ) :
exit ( "Unknown container {0}" . format ( name ) )
if not self . container_running ( name = name ) :
exit ( "Container {0} is not running" . format ( name ) )
ip = self . get_container_ip ( name )
if not ip :
exit ( "Failed to get network address for " "conta... |
def get_simplex_solution_graph ( self ) :
'''API :
get _ simplex _ solution _ graph ( self ) :
Description :
Assumes a feasible flow solution stored in ' flow ' attribute ' s of
arcs . Returns the graph with arcs that have flow between 0 and
capacity .
Pre :
(1 ) ' flow ' attribute represents a feasib... | simplex_g = Graph ( type = DIRECTED_GRAPH )
for i in self . neighbors :
simplex_g . add_node ( i )
for e in self . edge_attr :
flow_e = self . edge_attr [ e ] [ 'flow' ]
capacity_e = self . edge_attr [ e ] [ 'capacity' ]
if flow_e > 0 and flow_e < capacity_e :
simplex_g . add_edge ( e [ 0 ] , e ... |
def parse_filter ( args , analog = False , sample_rate = None ) :
"""Parse arbitrary input args into a TF or ZPK filter definition
Parameters
args : ` tuple ` , ` ~ scipy . signal . lti `
filter definition , normally just captured positional ` ` * args ` `
from a function call
analog : ` bool ` , optional... | if analog and not sample_rate :
raise ValueError ( "Must give sample_rate frequency to convert " "analog filter to digital" )
# unpack filter
if isinstance ( args , tuple ) and len ( args ) == 1 : # either packed defintion ( ( z , p , k ) ) or simple definition ( lti , )
args = args [ 0 ]
# parse FIR filter
if ... |
def _reassign_quantity_indexer ( data , indexers ) :
"""Reassign a units . Quantity indexer to units of relevant coordinate .""" | def _to_magnitude ( val , unit ) :
try :
return val . to ( unit ) . m
except AttributeError :
return val
for coord_name in indexers : # Handle axis types for DataArrays
if ( isinstance ( data , xr . DataArray ) and coord_name not in data . dims and coord_name in readable_to_cf_axes ) :
... |
def training_loop_hparams_from_scoped_overrides ( scoped_overrides , trial_id ) :
"""Create HParams suitable for training loop from scoped HParams .
Args :
scoped _ overrides : HParams , with keys all scoped by one of HP _ SCOPES . These
parameters are overrides for the base HParams created by
create _ loop... | trial_hp_overrides = scoped_overrides . values ( )
# Create loop , model , and ppo base HParams
loop_hp = create_loop_hparams ( )
model_hp_name = trial_hp_overrides . get ( "loop.generative_model_params" , loop_hp . generative_model_params )
model_hp = registry . hparams ( model_hp_name ) . parse ( FLAGS . hparams )
ba... |
def longTouch ( self , x , y , duration = 2000 , orientation = - 1 ) :
'''Long touches at ( x , y )
@ param duration : duration in ms
@ param orientation : the orientation ( - 1 : undefined )
This workaround was suggested by U { HaMi < http : / / stackoverflow . com / users / 2571957 / hami > }''' | self . __checkTransport ( )
self . drag ( ( x , y ) , ( x , y ) , duration , orientation ) |
def pack ( window , sizer , expand = 1.1 ) :
"simple wxPython pack function" | tsize = window . GetSize ( )
msize = window . GetMinSize ( )
window . SetSizer ( sizer )
sizer . Fit ( window )
nsize = ( 10 * int ( expand * ( max ( msize [ 0 ] , tsize [ 0 ] ) / 10 ) ) , 10 * int ( expand * ( max ( msize [ 1 ] , tsize [ 1 ] ) / 10. ) ) )
window . SetSize ( nsize ) |
def parse_config_h ( fp , vars = None ) :
"""Parse a config . h - style file .
A dictionary containing name / value pairs is returned . If an
optional dictionary is passed in as the second argument , it is
used instead of a new dictionary .""" | if vars is None :
vars = { }
define_rx = re . compile ( "#define ([A-Z][A-Za-z0-9_]+) (.*)\n" )
undef_rx = re . compile ( "/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n" )
while True :
line = fp . readline ( )
if not line :
break
m = define_rx . match ( line )
if m :
n , v = m . group ( 1 ... |
def read_img ( path ) :
"""Reads image specified by path into numpy . ndarray""" | img = cv2 . resize ( cv2 . imread ( path , 0 ) , ( 80 , 30 ) ) . astype ( np . float32 ) / 255
img = np . expand_dims ( img . transpose ( 1 , 0 ) , 0 )
return img |
def uncertainty_pi ( self ) :
"""Estimate of the element - wise asymptotic standard deviation
in the stationary distribution .""" | if self . information_ is None :
self . _build_information ( )
sigma_pi = _ratematrix . sigma_pi ( self . information_ , theta = self . theta_ , n = self . n_states_ )
return sigma_pi |
def get_zones ( region = None , key = None , keyid = None , profile = None ) :
'''Get a list of AZs for the configured region .
CLI Example :
. . code - block : : bash
salt myminion boto _ ec2 . get _ zones''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
return [ z . name for z in conn . get_all_zones ( ) ] |
def prepare_csv_to_dataframe ( data_file , config , use_target = True ) :
"""Parses the given data file following the data model of the given configuration .
@ return : pandas DataFrame""" | names , dtypes = [ ] , [ ]
model = config . get_data_model ( )
for feature in model :
assert feature . get_name ( ) not in names , "Two features can't have the same name."
if not use_target and feature . is_target ( ) :
continue
names . append ( feature . get_name ( ) )
data = pd . read_csv ( data_f... |
def remove_binary_support ( self , api_id , cors = False ) :
"""Remove binary support""" | response = self . apigateway_client . get_rest_api ( restApiId = api_id )
if "binaryMediaTypes" in response and "*/*" in response [ "binaryMediaTypes" ] :
self . apigateway_client . update_rest_api ( restApiId = api_id , patchOperations = [ { 'op' : 'remove' , 'path' : '/binaryMediaTypes/*~1*' } ] )
if cors : # go ... |
def remove_stage ( self , stage , edit_version = None , ** kwargs ) :
''': param stage : A number for the stage index ( for the nth stage , starting from 0 ) , or a string of the stage index , name , or ID
: type stage : int or string
: param edit _ version : if provided , the edit version of the workflow that ... | stage_id = self . _get_stage_id ( stage )
remove_stage_input = { "stage" : stage_id }
self . _add_edit_version_to_request ( remove_stage_input , edit_version )
try :
dxpy . api . workflow_remove_stage ( self . _dxid , remove_stage_input , ** kwargs )
finally :
self . describe ( )
# update cached describe
re... |
def list_sas ( self , filters = None ) :
"""Retrieve active IKE _ SAs and associated CHILD _ SAs .
: param filters : retrieve only matching IKE _ SAs ( optional )
: type filters : dict
: return : list of active IKE _ SAs and associated CHILD _ SAs
: rtype : list""" | _ , sa_list = self . handler . streamed_request ( "list-sas" , "list-sa" , filters )
return sa_list |
def handle ( self , pkt , raddress , rport ) :
"""Handle a packet we just received .""" | log . debug ( "In TftpStateServerStart.handle" )
if isinstance ( pkt , TftpPacketRRQ ) :
log . debug ( "Handling an RRQ packet" )
return TftpStateServerRecvRRQ ( self . context ) . handle ( pkt , raddress , rport )
elif isinstance ( pkt , TftpPacketWRQ ) :
log . debug ( "Handling a WRQ packet" )
return ... |
def get_symbol ( num_classes , num_layers = 11 , batch_norm = False , dtype = 'float32' , ** kwargs ) :
"""Parameters
num _ classes : int , default 1000
Number of classification classes .
num _ layers : int
Number of layers for the variant of densenet . Options are 11 , 13 , 16 , 19.
batch _ norm : bool ,... | vgg_spec = { 11 : ( [ 1 , 1 , 2 , 2 , 2 ] , [ 64 , 128 , 256 , 512 , 512 ] ) , 13 : ( [ 2 , 2 , 2 , 2 , 2 ] , [ 64 , 128 , 256 , 512 , 512 ] ) , 16 : ( [ 2 , 2 , 3 , 3 , 3 ] , [ 64 , 128 , 256 , 512 , 512 ] ) , 19 : ( [ 2 , 2 , 4 , 4 , 4 ] , [ 64 , 128 , 256 , 512 , 512 ] ) }
if num_layers not in vgg_spec :
raise V... |
def tag_dssp_solvent_accessibility ( self , force = False ) :
"""Tags each ` Residues ` Polymer with its solvent accessibility .
Notes
For more about DSSP ' s solvent accessibilty metric , see :
http : / / swift . cmbi . ru . nl / gv / dssp / HTML / descrip . html # ACC
References
. . [ 1 ] Kabsch W , San... | tagged = [ 'dssp_acc' in x . tags . keys ( ) for x in self . _monomers ]
if ( not all ( tagged ) ) or force :
dssp_out = run_dssp ( self . pdb , path = False )
if dssp_out is None :
return
dssp_acc_list = extract_solvent_accessibility_dssp ( dssp_out , path = False )
for monomer , dssp_acc in zi... |
def set_I ( self , I = None ) :
"""Set the current circulating on the coil ( A )""" | C0 = I is None
C1 = type ( I ) in [ int , float , np . int64 , np . float64 ]
C2 = type ( I ) in [ list , tuple , np . ndarray ]
msg = "Arg I must be None, a float or an 1D np.ndarray !"
assert C0 or C1 or C2 , msg
if C1 :
I = np . array ( [ I ] , dtype = float )
elif C2 :
I = np . asarray ( I , dtype = float )... |
def get_taf_flight_rules ( lines : [ dict ] ) -> [ dict ] : # type : ignore
"""Get flight rules by looking for missing data in prior reports""" | for i , line in enumerate ( lines ) :
temp_vis , temp_cloud = line [ 'visibility' ] , line [ 'clouds' ]
for report in reversed ( lines [ : i ] ) :
if not _is_tempo_or_prob ( report [ 'type' ] ) :
if temp_vis == '' :
temp_vis = report [ 'visibility' ]
if 'SKC' in r... |
def rows ( self , offs ) :
'''Iterate over raw indx , bytes tuples from a given offset .''' | lkey = s_common . int64en ( offs )
for lkey , byts in self . slab . scanByRange ( lkey , db = self . db ) :
indx = s_common . int64un ( lkey )
yield indx , byts |
def _vard ( ins ) :
"""Defines a memory space with a default set of bytes / words in hexadecimal
( starting with a number ) or literals ( starting with # ) .
Numeric values with more than 2 digits represents a WORD ( 2 bytes ) value .
E . g . ' 01 ' = > 0 , ' 001 ' = > 1 , 0 bytes
Literal values starts with... | output = [ ]
output . append ( '%s:' % ins . quad [ 1 ] )
q = eval ( ins . quad [ 2 ] )
for x in q :
if x [ 0 ] == '#' : # literal ?
size_t = 'W' if x [ 1 ] == '#' else 'B'
output . append ( 'DEF{0} {1}' . format ( size_t , x . lstrip ( '#' ) ) )
continue
# must be an hex number
x = ... |
def get_git_branch ( git_path = 'git' ) :
"""Returns the name of the current git branch""" | branch_match = call ( ( git_path , 'rev-parse' , '--symbolic-full-name' , 'HEAD' ) )
if branch_match == "HEAD" :
return None
else :
return os . path . basename ( branch_match ) |
async def messages ( self ) :
"""Iterate through RMB posts from newest to oldest .
Returns
an asynchronous generator that yields : class : ` Post `""" | # Messages may be posted on the RMB while the generator is running .
oldest_id_seen = float ( 'inf' )
for offset in count ( step = 100 ) :
posts_bunch = await self . _get_messages ( offset = offset )
for post in reversed ( posts_bunch ) :
if post . id < oldest_id_seen :
yield post
oldest... |
def pix_to_skydir ( xpix , ypix , wcs ) :
"""Convert pixel coordinates to a skydir object .
Gracefully handles 0 - d coordinate arrays .
Always returns a celestial coordinate .
Parameters
xpix : ` numpy . ndarray `
ypix : ` numpy . ndarray `
wcs : ` ~ astropy . wcs . WCS `""" | xpix = np . array ( xpix )
ypix = np . array ( ypix )
if xpix . ndim > 0 and len ( xpix ) == 0 :
return SkyCoord ( np . empty ( 0 ) , np . empty ( 0 ) , unit = 'deg' , frame = 'icrs' )
return SkyCoord . from_pixel ( xpix , ypix , wcs , origin = 0 ) . transform_to ( 'icrs' ) |
def wind_bft ( ms ) :
"Convert wind from metres per second to Beaufort scale" | if ms is None :
return None
for bft in range ( len ( _bft_threshold ) ) :
if ms < _bft_threshold [ bft ] :
return bft
return len ( _bft_threshold ) |
def send_message ( self , user = None , message = None , channel = None ) :
"""Todo connect""" | self . transport . send_message ( user = user , message = message , channel = channel ) |
def resume ( self , mask , filename , port , pos ) :
"""Resume a DCC send""" | self . connections [ 'send' ] [ 'masks' ] [ mask ] [ port ] . offset = pos
message = 'DCC ACCEPT %s %d %d' % ( filename , port , pos )
self . bot . ctcp ( mask , message ) |
def _prepare_doc ( func , args , delimiter_chars ) :
"""From the function docstring get the arg parse description and arguments
help message . If there is no docstring simple description and help
message are created .
Args :
func : the function that needs argument parsing
args : name of the function argum... | _LOG . debug ( "Preparing doc for '%s'" , func . __name__ )
if not func . __doc__ :
return _get_default_help_message ( func , args )
description = [ ]
args_help = { }
fill_description = True
arg_name = None
arg_doc_regex = re . compile ( "\b*(?P<arg_name>\w+)\s*%s\s*(?P<help_msg>.+)" % delimiter_chars )
for line in... |
def iterative_limited_depth_first ( problem , graph_search = False , viewer = None ) :
'''Iterative limited depth first search .
If graph _ search = True , will avoid exploring repeated states .
Requires : SearchProblem . actions , SearchProblem . result , and
SearchProblem . is _ goal .''' | solution = None
limit = 0
while not solution :
solution = limited_depth_first ( problem , depth_limit = limit , graph_search = graph_search , viewer = viewer )
limit += 1
if viewer :
viewer . event ( 'no_more_runs' , solution , 'returned after %i runs' % limit )
return solution |
def get_finder ( sources = None , pip_command = None , pip_options = None ) : # type : ( List [ Dict [ S , Union [ S , bool ] ] ] , Optional [ Command ] , Any ) - > PackageFinder
"""Get a package finder for looking up candidates to install
: param sources : A list of pipfile - formatted sources , defaults to None... | if not pip_command :
pip_command = get_pip_command ( )
if not sources :
sources = [ { "url" : "https://pypi.org/simple" , "name" : "pypi" , "verify_ssl" : True } ]
if not pip_options :
pip_options = get_pip_options ( sources = sources , pip_command = pip_command )
session = pip_command . _build_session ( pi... |
def get_response ( self ) :
"""High level function for getting a response . This is what the concrete
controller should call . Returns a controller specific response .""" | last_good_request = self . request
middleware_result = None
try :
last_good_request , middleware_result = self . program . execute_input_middleware_stream ( self . request , self )
except GiottoException as exc : # save this exception so it can be re - raised from within
# get _ data _ response ( ) so that get _ co... |
def _Open ( self , path_spec , mode = 'rb' ) :
"""Opens the file system defined by path specification .
Args :
path _ spec ( PathSpec ) : path specification .
mode ( Optional [ str ] ) : file access mode . The default is ' rb ' which
represents read - only binary .
Raises :
AccessError : if the access t... | if not path_spec . HasParent ( ) :
raise errors . PathSpecError ( 'Unsupported path specification without parent.' )
file_object = resolver . Resolver . OpenFileObject ( path_spec . parent , resolver_context = self . _resolver_context )
try : # Set the file offset to 0 because tarfile . open ( ) does not .
file... |
def get_requested_aosp_permissions ( self ) :
"""Returns requested permissions declared within AOSP project .
This includes several other permissions as well , which are in the platform apps .
: rtype : list of str""" | aosp_permissions = [ ]
all_permissions = self . get_permissions ( )
for perm in all_permissions :
if perm in list ( self . permission_module . keys ( ) ) :
aosp_permissions . append ( perm )
return aosp_permissions |
def __decompressContent ( self , coding , pgctnt ) :
"""This is really obnoxious""" | # preLen = len ( pgctnt )
if coding == 'deflate' :
compType = "deflate"
bits_opts = [ - zlib . MAX_WBITS , # deflate
zlib . MAX_WBITS , # zlib
zlib . MAX_WBITS | 16 , # gzip
zlib . MAX_WBITS | 32 , # " automatic header detection "
0 , # Try to guess from header
# Try all the raw window optio... |
def id_request ( self ) :
"""The Force . com Identity Service ( return type dict of text _ type )""" | # https : / / developer . salesforce . com / page / Digging _ Deeper _ into _ OAuth _ 2.0 _ at _ Salesforce . com ? language = en & language = en # The _ Force . com _ Identity _ Service
if 'id' in self . oauth :
url = self . oauth [ 'id' ]
else : # dynamic auth without ' id ' parameter
url = self . urls_reques... |
def _color_image_callback ( self , image_msg ) :
"""subscribe to image topic and keep it up to date""" | color_arr = self . _process_image_msg ( image_msg )
self . _cur_color_im = ColorImage ( color_arr [ : , : , : : - 1 ] , self . _frame ) |
def _climlab_to_cam3 ( self , field ) :
'''Prepare field with proper dimension order .
CAM3 code expects 3D arrays with ( KM , JM , 1)
and 2D arrays with ( JM , 1 ) .
climlab grid dimensions are any of :
- ( KM , )
- ( JM , KM )
- ( JM , IM , KM )
( longitude dimension IM not yet implemented here ) .'... | if np . isscalar ( field ) :
return field
# Check to see if column vector needs to be replicated over latitude
elif self . JM > 1 :
if ( field . shape == ( self . KM , ) ) :
return np . tile ( field [ ... , np . newaxis ] , self . JM )
else :
return np . squeeze ( np . transpose ( field ) ) ... |
def get_interface_detail_output_interface_line_protocol_state_info ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_interface_detail = ET . Element ( "get_interface_detail" )
config = get_interface_detail
output = ET . SubElement ( get_interface_detail , "output" )
interface = ET . SubElement ( output , "interface" )
interface_type_key = ET . SubElement ( interface , "interface-type" )
interfac... |
def status ( AuxiliaryStates_presence = 0 ) :
"""STATUS Section 9.3.27""" | a = TpPd ( pd = 0x3 )
b = MessageType ( mesType = 0x3d )
# 00111101
c = Cause ( )
d = CallState ( )
packet = a / b / c / d
if AuxiliaryStates_presence is 1 :
e = AuxiliaryStatesHdr ( ieiAS = 0x24 , eightBitAS = 0x0 )
packet = packet / e
return packet |
def get_out_net_id ( cls , tenant_id ) :
"""Retrieve the network ID of OUT network .""" | if 'out' not in cls . ip_db_obj :
LOG . error ( "Fabric not prepared for tenant %s" , tenant_id )
return None
db_obj = cls . ip_db_obj . get ( 'out' )
out_subnet_dict = cls . get_out_ip_addr ( tenant_id )
sub = db_obj . get_subnet ( out_subnet_dict . get ( 'subnet' ) )
return sub . network_id |
def delete ( cls , label = 'default' , path = None ) :
"""Delete a server configuration .
This method is thread safe .
: param label : A string . The configuration identified by ` ` label ` ` is
deleted .
: param path : A string . The configuration file to be manipulated .
Defaults to what is returned by ... | if path is None :
path = _get_config_file_path ( cls . _xdg_config_dir , cls . _xdg_config_file )
cls . _file_lock . acquire ( )
try :
with open ( path ) as config_file :
config = json . load ( config_file )
del config [ label ]
with open ( path , 'w' ) as config_file :
json . dump ( con... |
def timedeltaToString ( delta ) :
"""Convert timedelta to an ical DURATION .""" | if delta . days == 0 :
sign = 1
else :
sign = delta . days / abs ( delta . days )
delta = abs ( delta )
days = delta . days
hours = int ( delta . seconds / 3600 )
minutes = int ( ( delta . seconds % 3600 ) / 60 )
seconds = int ( delta . seconds % 60 )
output = ''
if sign == - 1 :
output += '-'
output += 'P'... |
def get_description ( self ) :
"""Get description ( as dictionary )""" | message = self . _get_description_message ( )
data = self . _parse_description ( message )
return data |
def get_ad_leads ( self , start_date = None , end_date = None , filtering = ( ) , page = 1 , page_size = 100 , version = 'v1.0' ) :
"""获取朋友圈销售线索数据接口
: param start _ date : 开始日期 默认今天
: param end _ date : 结束日期 默认今天
: param filtering : 过滤条件 [ { field : 过滤字段 , operator : 操作符 , values : 字段取值 } ]
: param page : 页... | today = datetime . date . today ( )
if start_date is None :
start_date = today
if end_date is None :
end_date = today
if isinstance ( start_date , datetime . date ) :
start_date = start_date . strftime ( "%Y-%m-%d" )
if isinstance ( end_date , datetime . date ) :
end_date = end_date . strftime ( "%Y-%m-... |
def status_counter ( self ) :
"""Returns a : class : ` Counter ` object that counts the number of tasks with
given status ( use the string representation of the status as key ) .""" | # Count the number of tasks with given status in each work .
counter = self [ 0 ] . status_counter
for work in self [ 1 : ] :
counter += work . status_counter
return counter |
def delete_variant_by_id ( cls , variant_id , ** kwargs ) :
"""Delete Variant
Delete an instance of Variant by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . delete _ variant _ by _ id ( variant _ id , a... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _delete_variant_by_id_with_http_info ( variant_id , ** kwargs )
else :
( data ) = cls . _delete_variant_by_id_with_http_info ( variant_id , ** kwargs )
return data |
def euc_to_utf8 ( euchex ) :
"""Convert EUC hex ( e . g . " d2bb " ) to UTF8 hex ( e . g . " e4 b8 80 " ) .""" | utf8 = euc_to_python ( euchex ) . encode ( "utf-8" )
uf8 = utf8 . decode ( 'unicode_escape' )
uf8 = uf8 . encode ( 'latin1' )
uf8 = uf8 . decode ( 'euc-jp' )
return uf8 |
def user_with_name ( self , given_name = None , sn = None ) :
"""Get a unique user object by given name ( first / nickname and last ) .""" | results = [ ]
if sn and not given_name :
results = User . objects . filter ( last_name = sn )
elif given_name :
query = { 'first_name' : given_name }
if sn :
query [ 'last_name' ] = sn
results = User . objects . filter ( ** query )
if len ( results ) == 0 : # Try their first name as a nickna... |
def do_index_command ( self , index , ** options ) :
"""Rebuild search index .""" | if options [ "interactive" ] :
logger . warning ( "This will permanently delete the index '%s'." , index )
if not self . _confirm_action ( ) :
logger . warning ( "Aborting rebuild of index '%s' at user's request." , index )
return
try :
delete = delete_index ( index )
except TransportError :... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.