signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def caller_name ( self , skip = 2 ) :
"""Get a name of a caller in the format module . class . method
` skip ` specifies how many levels of stack to skip while getting caller
name . skip = 1 means " who calls me " , skip = 2 " who calls my caller " etc .
An empty string is returned if skipped levels exceed st... | stack = inspect . stack ( )
start = 0 + skip
if len ( stack ) < start + 1 :
return ''
parentframe = stack [ start ] [ 0 ]
name = [ ]
module = inspect . getmodule ( parentframe )
# ` modname ` can be None when frame is executed directly in console
# TODO ( asr1kteam ) : consider using _ _ main _ _
if module :
na... |
def replace_postgres_db ( self , file_url ) :
"""Replace postgres database with database from specified source .""" | self . print_message ( "Replacing postgres database" )
if file_url :
self . print_message ( "Sourcing data from online backup file '%s'" % file_url )
source_file = self . download_file_from_url ( self . args . source_app , file_url )
elif self . databases [ 'source' ] [ 'name' ] :
self . print_message ( "So... |
def create_marker_table ( self ) :
"""Create marker table if it doesn ' t exist .
Using a separate connection since the transaction might have to be reset .""" | if self . marker_table is None :
self . marker_table = luigi . configuration . get_config ( ) . get ( 'sqlalchemy' , 'marker-table' , 'table_updates' )
engine = self . engine
with engine . begin ( ) as con :
metadata = sqlalchemy . MetaData ( )
if not con . dialect . has_table ( con , self . marker_table ) ... |
def create_channel ( api_key , api_secret , channel_type = 'manual' , ** kwargs ) :
"""Function which creates a new channel . Channels serve as containers of video / media objects .
: param api _ key : < string > JWPlatform api - key
: param api _ secret : < string > JWPlatform shared - secret
: param channel... | jwplatform_client = jwplatform . Client ( api_key , api_secret )
logging . info ( "Creating new channel with keyword args." )
try :
response = jwplatform_client . channels . create ( type = channel_type , ** kwargs )
except jwplatform . errors . JWPlatformError as e :
logging . error ( "Encountered an error cre... |
def generate_n_vectors ( N_max , dx = 1 , dy = 1 , dz = 1 , half_lattice = True ) :
r"""Generate integer vectors , : math : ` \ boldsymbol { n } ` , with
: math : ` | \ boldsymbol { n } | < N _ { \ rm max } ` .
If ` ` half _ lattice = True ` ` , only return half of the three - dimensional
lattice . If the set... | vecs = np . meshgrid ( np . arange ( - N_max , N_max + 1 , dx ) , np . arange ( - N_max , N_max + 1 , dy ) , np . arange ( - N_max , N_max + 1 , dz ) )
vecs = np . vstack ( map ( np . ravel , vecs ) ) . T
vecs = vecs [ np . linalg . norm ( vecs , axis = 1 ) <= N_max ]
if half_lattice :
ix = ( ( vecs [ : , 2 ] > 0 )... |
def list_vms ( search = None , sort = None , order = 'uuid,type,ram,state,alias' , keyed = True ) :
'''Return a list of VMs
search : string
vmadm filter property
sort : string
vmadm sort ( - s ) property
order : string
vmadm order ( - o ) property - - Default : uuid , type , ram , state , alias
keyed ... | ret = { }
# vmadm list [ - p ] [ - H ] [ - o field , . . . ] [ - s field , . . . ] [ field = value . . . ]
cmd = 'vmadm list -p -H {order} {sort} {search}' . format ( order = '-o {0}' . format ( order ) if order else '' , sort = '-s {0}' . format ( sort ) if sort else '' , search = search if search else '' )
res = __sa... |
def _split_path ( self , path ) :
"""Splits a Registry path and returns the hive and key .
@ type path : str
@ param path : Registry path .
@ rtype : tuple ( int , str )
@ return : Tuple containing the hive handle and the subkey path .
The hive handle is always one of the following integer constants :
-... | if '\\' in path :
p = path . find ( '\\' )
hive = path [ : p ]
path = path [ p + 1 : ]
else :
hive = path
path = None
handle = self . _hives_by_name [ hive . upper ( ) ]
return handle , path |
def get_session_identifiers ( cls , folder = None , inputfile = None ) :
"""Retrieve the list of session identifiers contained in the
data on the folder or the inputfile .
For this plugin , it returns the list of excel sheet available .
: kwarg folder : the path to the folder containing the files to
check .... | sessions = [ ]
if inputfile and folder :
raise MQ2Exception ( 'You should specify either a folder or a file' )
if folder :
if not os . path . isdir ( folder ) :
return sessions
for root , dirs , files in os . walk ( folder ) :
for filename in files :
filename = os . path . join (... |
def tidy_ssh_user ( url = None , user = None ) :
"""make sure a git repo ssh : / / url has a user set""" | if url and url . startswith ( 'ssh://' ) : # is there a user already ?
match = re . compile ( 'ssh://([^@]+)@.+' ) . match ( url )
if match :
ssh_user = match . group ( 1 )
if user and ssh_user != user : # assume prevalence of argument
url = url . replace ( re . escape ( ssh_user ) +... |
def get_image_list ( self , page = 1 , per_page = 20 ) :
"""Return a list of user ' s saved images
: param page : ( optional ) Page number ( default : 1)
: param per _ page : ( optional ) Number of images per page
( default : 20 , min : 1 , max : 100)""" | url = self . api_url + '/api/images'
params = { 'page' : page , 'per_page' : per_page }
response = self . _request_url ( url , 'get' , params = params , with_access_token = True )
headers , result = self . _parse_and_check ( response )
images = ImageList . from_list ( result )
images . set_attributes_from_headers ( hea... |
def render_electrode_shapes ( self , df_shapes = None , shape_scale = 0.8 , fill = ( 1 , 1 , 1 ) ) :
'''Render electrode state shapes .
By default , draw each electrode shape filled white .
See also : meth : ` render _ shapes ( ) ` .
Parameters
df _ shapes = : pandas . DataFrame
. . versionadded : : 0.12'... | surface = self . get_surface ( )
if df_shapes is None :
if hasattr ( self . canvas , 'df_canvas_shapes' ) :
df_shapes = self . canvas . df_canvas_shapes
else :
return surface
if 'x_center' not in df_shapes or 'y_center' not in df_shapes : # No center points have been computed for shapes .
re... |
def getPixmap ( self , matrix = None , colorspace = None , alpha = 0 ) :
"""getPixmap ( self , matrix = None , colorspace = None , alpha = 0 ) - > Pixmap""" | CheckParent ( self )
return _fitz . Annot_getPixmap ( self , matrix , colorspace , alpha ) |
def _kld_error ( args ) :
"""Internal ` pool . map ` - friendly wrapper for : meth : ` kld _ error ` used by
: meth : ` stopping _ function ` .""" | # Extract arguments .
results , error , approx = args
return kld_error ( results , error , rstate = np . random , return_new = True , approx = approx ) |
def attribute_difference ( att_diff ) :
'''The attribute distance .''' | ret = 0
for a_value , b_value in att_diff :
if max ( a_value , b_value ) == 0 :
ret += 0
else :
ret += abs ( a_value - b_value ) * 1.0 / max ( a_value , b_value )
return ret * 1.0 / len ( att_diff ) |
def notebook_start ( self , ** kwargs ) :
"""Initialize a notebook , clearing its metadata , and save it .
When starting a notebook , this initializes and clears the metadata for
the notebook and its cells , and saves the notebook to the given
output path .
Called by Engine when execution begins .""" | self . set_timer ( )
self . nb . metadata . papermill [ 'start_time' ] = self . start_time . isoformat ( )
self . nb . metadata . papermill [ 'end_time' ] = None
self . nb . metadata . papermill [ 'duration' ] = None
self . nb . metadata . papermill [ 'exception' ] = None
for cell in self . nb . cells : # Reset the cel... |
def add_object_file ( self , obj_file ) :
"""Add object file to the jit . object _ file can be instance of
: class : ObjectFile or a string representing file system path""" | if isinstance ( obj_file , str ) :
obj_file = object_file . ObjectFileRef . from_path ( obj_file )
ffi . lib . LLVMPY_MCJITAddObjectFile ( self , obj_file ) |
def iter_changes ( self , issue , include_resolution_changes = True ) :
"""Yield an IssueSnapshot for each time the issue changed status or
resolution""" | is_resolved = False
# Find the first status change , if any
try :
status_changes = list ( filter ( lambda h : h . field == 'status' , itertools . chain . from_iterable ( [ c . items for c in issue . changelog . histories ] ) ) )
except AttributeError :
return
last_status = status_changes [ 0 ] . fromString if l... |
def repartition ( self , numPartitions , * cols ) :
"""Returns a new : class : ` DataFrame ` partitioned by the given partitioning expressions . The
resulting DataFrame is hash partitioned .
: param numPartitions :
can be an int to specify the target number of partitions or a Column .
If it is a Column , it... | if isinstance ( numPartitions , int ) :
if len ( cols ) == 0 :
return DataFrame ( self . _jdf . repartition ( numPartitions ) , self . sql_ctx )
else :
return DataFrame ( self . _jdf . repartition ( numPartitions , self . _jcols ( * cols ) ) , self . sql_ctx )
elif isinstance ( numPartitions , (... |
def tile_and_concat ( image , latent , concat_latent = True ) :
"""Tile latent and concatenate to image across depth .
Args :
image : 4 - D Tensor , ( batch _ size X height X width X channels )
latent : 2 - D Tensor , ( batch _ size X latent _ dims )
concat _ latent : If set to False , the image is returned... | if not concat_latent :
return image
image_shape = common_layers . shape_list ( image )
latent_shape = common_layers . shape_list ( latent )
height , width = image_shape [ 1 ] , image_shape [ 2 ]
latent_dims = latent_shape [ 1 ]
height_multiples = height // latent_dims
pad = height - ( height_multiples * latent_dims... |
def keys_values ( data , * keys ) :
"""Get an entry as a list from a dict . Provide a fallback key .""" | values = [ ]
if is_mapping ( data ) :
for key in keys :
if key in data :
values . extend ( ensure_list ( data [ key ] ) )
return values |
def _remove_redundant_overlapping_blocks ( self ) :
"""On some architectures there are sometimes garbage bytes ( usually nops ) between functions in order to properly
align the succeeding function . CFGFast does a linear sweeping which might create duplicated blocks for
function epilogues where one block starts... | sorted_nodes = sorted ( self . graph . nodes ( ) , key = lambda n : n . addr if n is not None else 0 )
all_plt_stub_addrs = set ( itertools . chain . from_iterable ( obj . reverse_plt . keys ( ) for obj in self . project . loader . all_objects if isinstance ( obj , cle . MetaELF ) ) )
# go over the list . for each node... |
def _build_codes ( ) -> Dict [ str , Dict [ str , str ] ] :
"""Build code map , encapsulated to reduce module - level globals .""" | built = { 'fore' : { } , 'back' : { } , 'style' : { } , }
# type : Dict [ str , Dict [ str , str ] ]
# Set codes for forecolors ( 30-37 ) and backcolors ( 40-47)
# Names are given to some of the 256 - color variants as ' light ' colors .
for name , number in _namemap : # Not using format _ * functions here , no validat... |
def get_filepath_findex_from_user ( self , wildcard , message , style , filterindex = 0 ) :
"""Opens a file dialog and returns filepath and filterindex
Parameters
wildcard : String
\t Wildcard string for file dialog
message : String
\t Message in the file dialog
style : Integer
\t Dialog style , e . g... | dlg = wx . FileDialog ( self . main_window , wildcard = wildcard , message = message , style = style , defaultDir = os . getcwd ( ) , defaultFile = "" )
# Set the initial filterindex
dlg . SetFilterIndex ( filterindex )
filepath = None
filter_index = None
if dlg . ShowModal ( ) == wx . ID_OK :
filepath = dlg . GetP... |
def patch_qt ( qt_support_mode ) :
'''This method patches qt ( PySide , PyQt4 , PyQt5 ) so that we have hooks to set the tracing for QThread .''' | if not qt_support_mode :
return
if qt_support_mode is True or qt_support_mode == 'True' : # do not break backward compatibility
qt_support_mode = 'auto'
if qt_support_mode == 'auto' :
qt_support_mode = os . getenv ( 'PYDEVD_PYQT_MODE' , 'auto' )
# Avoid patching more than once
global _patched_qt
if _patched... |
def get_least_salient_words ( vocab , topic_word_distrib , doc_topic_distrib , doc_lengths , n = None ) :
"""Order the words from ` vocab ` by " saliency score " ( Chuang et al . 2012 ) from least to most salient . Optionally only
return the ` n ` least salient words .
J . Chuang , C . Manning , J . Heer 2012 :... | return _words_by_salience_score ( vocab , topic_word_distrib , doc_topic_distrib , doc_lengths , n , least_to_most = True ) |
def make_iterable ( obj , default = None ) :
"""Ensure obj is iterable .""" | if obj is None :
return default or [ ]
if isinstance ( obj , ( compat . string_types , compat . integer_types ) ) :
return [ obj ]
return obj |
def __onKeyEvent ( self , event = None ) :
"""handles key events on canvas""" | if event is None :
return
key = event . guiEvent . GetKeyCode ( )
if ( key < wx . WXK_SPACE or key > 255 ) :
return
ckey = chr ( key )
mod = event . guiEvent . ControlDown ( )
if self . is_macosx :
mod = event . guiEvent . MetaDown ( )
if mod :
if ckey == 'C' :
self . canvas . Copy_to_Clipboard ... |
def delete ( self , url , code ) :
"""Request a URL be deleted .
This will only work if you supply the valid deletion code .
: param url : the shortened url to delete
: type url : str
: param code : the deletion code given to you on URL shorten
: type code : str
: return : the deletion request ' s reply... | data = self . fetch ( "/delete" , { "short" : url , "delete" : code } )
return data |
def dirty_load ( yaml_string , schema = None , label = u"<unicode string>" , allow_flow_style = False ) :
"""Parse the first YAML document in a string
and produce corresponding YAML object .
If allow _ flow _ style is set to True , then flow style is allowed .""" | return generic_load ( yaml_string , schema = schema , label = label , allow_flow_style = allow_flow_style ) |
def to_mask ( self , method = 'exact' , subpixels = 5 ) :
"""Return a list of ` ~ photutils . ApertureMask ` objects , one for each
aperture position .
Parameters
method : { ' exact ' , ' center ' , ' subpixel ' } , optional
The method used to determine the overlap of the aperture on
the pixel grid . Not ... | use_exact , subpixels = self . _translate_mask_mode ( method , subpixels )
if hasattr ( self , 'a' ) :
a = self . a
b = self . b
elif hasattr ( self , 'a_in' ) : # annulus
a = self . a_out
b = self . b_out
b_in = self . a_in * self . b_out / self . a_out
else :
raise ValueError ( 'Cannot determi... |
def slug ( request , url ) :
"""Look up a page by url ( which is a tree of slugs )""" | page = None
if url :
for slug in url . split ( '/' ) :
if not slug :
continue
try :
page = Page . objects . get ( slug = slug , parent = page )
except Page . DoesNotExist :
raise Http404
else :
try :
page = Page . objects . get ( slug = 'index'... |
def max ( self , array , role = None ) :
"""Return the maximum value of ` ` array ` ` for the entity members .
` ` array ` ` must have the dimension of the number of persons in the simulation
If ` ` role ` ` is provided , only the entity member with the given role are taken into account .
Example :
> > > sa... | return self . reduce ( array , reducer = np . maximum , neutral_element = - np . infty , role = role ) |
def _generate_next_parameter_value ( self , parameter , forecastingMethod ) :
"""Generator for a specific parameter of the given forecasting method .
: param string parameter : Name of the parameter the generator is used for .
: param BaseForecastingMethod forecastingMethod : Instance of a ForecastingMethod .
... | interval = forecastingMethod . get_interval ( parameter )
precision = 10 ** self . _precison
startValue = interval [ 0 ]
endValue = interval [ 1 ]
if not interval [ 2 ] :
startValue += precision
if interval [ 3 ] :
endValue += precision
while startValue < endValue : # fix the parameter precision
parameterVa... |
def authenticated_get ( username , password , url , verify = True ) :
"""Perform an authorized query to the url , and return the result""" | try :
response = requests . get ( url , auth = ( username , password ) , verify = verify )
if response . status_code == 401 :
raise BadCredentialsException ( "Unable to authenticate user %s to %s with password provided!" % ( username , url ) )
except requests . exceptions . SSLError :
raise Certific... |
def get_unique_schema_name ( components , name , counter = 0 ) :
"""Function to generate a unique name based on the provided name and names
already in the spec . Will append a number to the name to make it unique if
the name is already in the spec .
: param Components components : instance of the components o... | if name not in components . _schemas :
return name
if not counter : # first time through recursion
warnings . warn ( "Multiple schemas resolved to the name {}. The name has been modified. " "Either manually add each of the schemas with a different name or " "provide a custom schema_name_resolver." . format ( na... |
def async_rpc ( address , rpc_id , arg_format , resp_format = None ) :
"""Decorator to denote that a function implements an RPC with the given ID and address .
The underlying function should be a member function that will take
individual parameters after the RPC payload has been decoded according
to arg _ for... | if rpc_id < 0 or rpc_id > 0xFFFF :
raise RPCInvalidIDError ( "Invalid RPC ID: {}" . format ( rpc_id ) )
def _rpc_wrapper ( func ) :
async def _rpc_executor ( self , payload ) :
try :
args = unpack_rpc_payload ( arg_format , payload )
except struct . error as exc :
raise R... |
def create_temp_file ( file_name = None , string_or_another_file = "" ) :
"""Creates a temp file using a given name . Temp files are placed in the Project / temp /
directory . Any temp files being created with an existing temp file , will be
overridden . This is useful for testing uploads , where you would want... | temp_file_path = temp_path ( file_name )
if isinstance ( string_or_another_file , file ) : # attempt to read it as a file .
temp_file = open ( temp_file_path , "wb" )
temp_file . write ( string_or_another_file . read ( ) )
else : # handle as a string type if we can ' t handle as a file .
temp_file = codecs ... |
def submit ( command_filename , workingdir , send_mail = False , username = None ) :
'''Submit the given command filename to the queue . Adapted from the qb3 example .''' | return sge_interface . submit ( command_filename , workingdir , send_mail = send_mail , username = username ) |
def move_to_group ( self , items , new_group_id : int ) :
""": type items : list of ProtocolTreeItem""" | group = self . rootItem . child ( new_group_id )
for item in items :
group . appendChild ( item )
self . controller . refresh ( ) |
def encode ( self ) :
"""Encodes this SeqDelay to a binary bytearray .""" | delay_s = int ( math . floor ( self . delay ) )
delay_ms = int ( ( self . delay - delay_s ) * 255.0 )
return struct . pack ( '>H' , delay_s ) + struct . pack ( 'B' , delay_ms ) |
def load_addresses ( self ) :
"""Loads member addresses from Hazelcast . cloud endpoint .
: return : ( Sequence ) , The possible member addresses to connect to .""" | try :
return list ( self . cloud_discovery . discover_nodes ( ) . keys ( ) )
except Exception as ex :
self . logger . warning ( "Failed to load addresses from Hazelcast.cloud: {}" . format ( ex . args [ 0 ] ) , extra = self . _logger_extras )
return [ ] |
def read_ipv6_opts ( self , length , extension ) :
"""Read Destination Options for IPv6.
Structure of IPv6 - Opts header [ RFC 8200 ] :
| Next Header | Hdr Ext Len | |
. Options .
Octets Bits Name Description
0 0 opt . next Next Header
1 8 opt . length Header Extensive Length
2 16 opt . options Option... | if length is None :
length = len ( self )
_next = self . _read_protos ( 1 )
_hlen = self . _read_unpack ( 1 )
# _ opts = self . _ read _ fileng ( _ hlen * 8 + 6)
ipv6_opts = dict ( next = _next , length = ( _hlen + 1 ) * 8 , )
options = self . _read_ipv6_opts_options ( _hlen * 8 + 6 )
ipv6_opts [ 'options' ] = opti... |
def get ( self ) :
"""Gets the current evaluation result .
Returns
names : list of str
Name of the metrics .
values : list of float
Value of the evaluations .""" | if self . num_inst == 0 :
return ( self . name , float ( 'nan' ) )
else :
return ( self . name , self . sum_metric / self . num_inst ) |
def _get_conn ( ) :
'''Return a postgres connection .''' | try :
conn = psycopg2 . connect ( host = __opts__ [ 'master_job_cache.postgres.host' ] , user = __opts__ [ 'master_job_cache.postgres.user' ] , password = __opts__ [ 'master_job_cache.postgres.passwd' ] , database = __opts__ [ 'master_job_cache.postgres.db' ] , port = __opts__ [ 'master_job_cache.postgres.port' ] )... |
def retrieve_content ( self ) :
"""Retrieve the content of a resource .""" | path = self . _construct_path_to_source_content ( )
res = self . _http . get ( path )
self . _populated_fields [ 'content' ] = res [ 'content' ]
return res [ 'content' ] |
def send ( self , subname , delta ) :
'''Send the data to statsd via self . connection
: keyword subname : The subname to report the data to ( appended to the
client name )
: type subname : str
: keyword delta : The time delta ( time . time ( ) - time . time ( ) ) to report
: type delta : float''' | ms = delta * 1000
if ms > self . min_send_threshold :
name = self . _get_name ( self . name , subname )
self . logger . info ( '%s: %0.08fms' , name , ms )
return statsd . Client . _send ( self , { name : '%0.08f|ms' % ms } )
else :
return True |
def run ( self , * args , ** kwargs ) :
"""Call all the registered handlers with the arguments passed .
If this signal is a class member , call also the handlers registered
at class - definition time . If an external publish function is
supplied , call it with the provided arguments .
: returns : an instanc... | if self . fvalidation is not None :
try :
if self . fvalidation ( * args , ** kwargs ) is False :
raise ExecutionError ( "Validation returned ``False``" )
except Exception as e :
if __debug__ :
logger . exception ( "Validation failed" )
else :
logger .... |
def predict ( self , recording , result_format = None ) :
"""Predict the class of the given recording .
Parameters
recording : string
Recording of a single handwritten dataset in JSON format .
result _ format : string , optional
If it is ' LaTeX ' , then only the latex code will be returned
Returns
li... | evaluate = utils . evaluate_model_single_recording_preloaded
results = evaluate ( self . preprocessing_queue , self . feature_list , self . model , self . output_semantics , recording )
if result_format == 'LaTeX' :
for i in range ( len ( results ) ) :
results [ i ] [ 'semantics' ] = results [ i ] [ 'semant... |
def choose_init ( module ) :
"""Select a init system
Returns the name of a init system ( upstart , sysvinit . . . ) .""" | # Upstart checks first because when installing ceph , the
# ` / lib / systemd / system / ceph . target ` file may be created , fooling this
# detection mechanism .
if is_upstart ( module . conn ) :
return 'upstart'
if is_systemd ( module . conn ) or module . conn . remote_module . path_exists ( "/lib/systemd/system... |
def read_zmat ( cls , inputfile , implicit_index = True ) :
"""Reads a zmat file .
Lines beginning with ` ` # ` ` are ignored .
Args :
inputfile ( str ) :
implicit _ index ( bool ) : If this option is true the first column
has to be the element symbols for the atoms .
The row number is used to determine... | cols = [ 'atom' , 'b' , 'bond' , 'a' , 'angle' , 'd' , 'dihedral' ]
if implicit_index :
zmat_frame = pd . read_table ( inputfile , comment = '#' , delim_whitespace = True , names = cols )
zmat_frame . index = range ( 1 , len ( zmat_frame ) + 1 )
else :
zmat_frame = pd . read_table ( inputfile , comment = '#... |
def subsample ( data , sampling ) :
"""Compute a simple mean subsampling .
Data should be a list of numerical itervalues
Return a subsampled list of sampling lenght""" | if len ( data ) <= sampling :
return data
sampling_length = int ( round ( len ( data ) / float ( sampling ) ) )
return [ mean ( data [ s * sampling_length : ( s + 1 ) * sampling_length ] ) for s in range ( 0 , sampling ) ] |
def markets ( self ) :
'''获取实时市场列表
: return : pd . dataFrame or None''' | with self . client . connect ( * self . bestip ) :
data = self . client . get_markets ( )
return self . client . to_df ( data )
return None |
def iterconsume ( self , limit = None ) :
"""Cycle between all consumers in consume mode .
See : meth : ` Consumer . iterconsume ` .""" | self . consume ( )
return self . backend . consume ( limit = limit ) |
def setfig ( fig = None , ** kwargs ) :
"""Sets figure to ' fig ' and clears ; if fig is 0 , does nothing ( e . g . for overplotting )
if fig is None ( or anything else ) , creates new figure
I use this for basically every function I write to make a plot .
I give the function
a " fig = None " kw argument , ... | if fig :
plt . figure ( fig , ** kwargs )
plt . clf ( )
elif fig == 0 :
pass
else :
plt . figure ( ** kwargs ) |
def _unrecognised ( achr ) :
"""Handle unrecognised characters .""" | if options [ 'handleUnrecognised' ] == UNRECOGNISED_ECHO :
return achr
elif options [ 'handleUnrecognised' ] == UNRECOGNISED_SUBSTITUTE :
return options [ 'substituteChar' ]
else :
raise KeyError ( achr ) |
def _generate_union_class_get_helpers ( self , ns , data_type ) : # type : ( ApiNamespace , Union ) - > None
"""Generates the following section in the ' union Shape ' example :
def get _ circle ( self ) - > float : . . .""" | for field in data_type . fields :
field_name = fmt_func ( field . name )
if not is_void_type ( field . data_type ) : # generate getter for field
val_type = self . map_stone_type_to_pep484_type ( ns , field . data_type )
self . emit ( 'def get_{field_name}(self) -> {val_type}: ...' . format ( fie... |
def weber_MS ( I , J , x , y , w ) :
"""weber - - model for solving the weber problem using soco ( multiple source version ) .
Parameters :
- I : set of customers
- J : set of potential facilities
- x [ i ] : x position of customer i
- y [ i ] : y position of customer i
- w [ i ] : weight of customer i ... | M = max ( [ ( ( x [ i ] - x [ j ] ) ** 2 + ( y [ i ] - y [ j ] ) ** 2 ) for i in I for j in I ] )
model = Model ( "weber - multiple source" )
X , Y , v , u = { } , { } , { } , { }
xaux , yaux , uaux = { } , { } , { }
for j in J :
X [ j ] = model . addVar ( lb = - model . infinity ( ) , vtype = "C" , name = "X(%s)" ... |
def plot_boolean ( self , on , boolean_col , plot_col = None , boolean_label = None , boolean_value_map = { } , order = None , ax = None , alternative = "two-sided" , ** kwargs ) :
"""Plot a comparison of ` boolean _ col ` in the cohort on a given variable via
` on ` or ` col ` .
If the variable ( through ` on ... | cols , df = self . as_dataframe ( on , return_cols = True , ** kwargs )
plot_col = self . plot_col_from_cols ( cols = cols , plot_col = plot_col )
df = filter_not_null ( df , boolean_col )
df = filter_not_null ( df , plot_col )
if boolean_label :
df [ boolean_label ] = df [ boolean_col ]
boolean_col = boolean_l... |
def handle_note ( self , note , command = '' , training_input = '' ) :
"""Handle notes and walkthrough option .
@ param note : See send ( )""" | shutit_global . shutit_global_object . yield_to_draw ( )
if self . build [ 'walkthrough' ] and note != None and note != '' :
assert isinstance ( note , str ) , shutit_util . print_debug ( )
wait = self . build [ 'walkthrough_wait' ]
wrap = '\n' + 80 * '=' + '\n'
message = wrap + note + wrap
if comma... |
def image_from_docker_args ( args ) :
"""This scans docker run args and attempts to find the most likely docker image argument .
If excludes any argments that start with a dash , and the argument after it if it isn ' t a boolean
switch . This can be improved , we currently fallback gracefully when this fails ."... | bool_args = [ "-t" , "--tty" , "--rm" , "--privileged" , "--oom-kill-disable" , "--no-healthcheck" , "-i" , "--interactive" , "--init" , "--help" , "--detach" , "-d" , "--sig-proxy" , "-it" , "-itd" ]
last_flag = - 2
last_arg = ""
possible_images = [ ]
if len ( args ) > 0 and args [ 0 ] == "run" :
args . pop ( 0 )
... |
def sendline ( command , method = 'cli_show_ascii' , ** kwargs ) :
'''Send arbitrary show or config commands to the NX - OS device .
command
The command to be sent .
method :
` ` cli _ show _ ascii ` ` : Return raw test or unstructured output .
` ` cli _ show ` ` : Return structured output .
` ` cli _ c... | try :
if CONNECTION == 'ssh' :
result = _sendline_ssh ( command , ** kwargs )
elif CONNECTION == 'nxapi' :
result = _nxapi_request ( command , method , ** kwargs )
except ( TerminalException , NxosCliError ) as e :
log . error ( e )
raise
return result |
def set ( self , id , newObj ) :
"""Set a object
Args :
id ( int ) : Target Object ID
newObj ( object ) : New object will be set
Returns :
Object : New object
None : If specified object id is not found
MultipleInvalid : If input object is invaild""" | newObj = self . validation ( newObj )
for index in xrange ( 0 , len ( self . model . db ) ) :
if self . model . db [ index ] [ "id" ] != id :
continue
newObj [ "id" ] = id
self . model . db [ index ] = self . _cast_model ( newObj )
if not self . _batch . enable . is_set ( ) :
self . mode... |
def __store_callable ( self , o , method_name , member ) :
"""Stores a callable member to the private _ _ store _ _
: param mixed o : Any callable ( function or method )
: param str method _ name : The name of the attribute
: param mixed member : A reference to the member""" | self . __store__ [ 'callables' ] [ method_name ] = eval ( "o." + method_name )
self . __store__ [ 'callables' ] [ method_name [ 0 ] . lower ( ) + method_name [ 1 : ] ] = eval ( "o." + method_name )
ret_val = self . __wrap ( method_name )
self . __store__ [ method_name ] = ret_val
self . __store__ [ method_name [ 0 ] . ... |
def tail ( self , fname , encoding , window , position = None ) :
"""Read last N lines from file fname .""" | if window <= 0 :
raise ValueError ( 'invalid window %r' % window )
encodings = ENCODINGS
if encoding :
encodings = [ encoding ] + ENCODINGS
for enc in encodings :
try :
f = self . open ( encoding = enc )
if f :
return self . tail_read ( f , window , position = position )
... |
def node_rank ( self ) :
"""Returns the maximum rank for each * * topological node * * in the
` ` DictGraph ` ` . The rank of a node is defined as the number of edges
between the node and a node which has rank 0 . A * * topological node * *
has rank 0 if it has no incoming edges .""" | nodes = self . postorder ( )
node_rank = { }
for node in nodes :
max_rank = 0
for child in self [ node ] . nodes ( ) :
some_rank = node_rank [ child ] + 1
max_rank = max ( max_rank , some_rank )
node_rank [ node ] = max_rank
return node_rank |
def insert_value ( self , agg , value , idx , name = '' ) :
"""Insert * value * into member number * idx * from aggregate .""" | if not isinstance ( idx , ( tuple , list ) ) :
idx = [ idx ]
instr = instructions . InsertValue ( self . block , agg , value , idx , name = name )
self . _insert ( instr )
return instr |
def request ( self , method , url , params = None , data = None , headers = None , auth = None , timeout = None , allow_redirects = False ) :
"""Make a signed HTTP Request
: param str method : The HTTP method to use
: param str url : The URL to request
: param dict params : Query parameters to append to the U... | session = self . session or Session ( )
request = Request ( method . upper ( ) , url , params = params , data = data , headers = headers , auth = auth )
prepared_request = session . prepare_request ( request )
if 'Host' not in prepared_request . headers and 'host' not in prepared_request . headers :
prepared_reques... |
def split_sentences ( text ) :
"""Utility function to return a list of sentences .
@ param text The text that must be split in to sentences .""" | sentence_delimiters = re . compile ( u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]' )
sentences = sentence_delimiters . split ( text )
return sentences |
def collect_filters_to_first_location_occurrence ( compound_match_query ) :
"""Collect all filters for a particular location to the first instance of the location .
Adding edge field non - exsistence filters in ` _ prune _ traverse _ using _ omitted _ locations ` may
result in filters being applied to locations... | new_match_queries = [ ]
# Each MatchQuery has a different set of locations , and associated Filters .
# Hence , each of them is processed independently .
for match_query in compound_match_query . match_queries : # Construct mapping from location - > list of filter predicates applied at that location
location_to_fil... |
def obfn_g0var ( self ) :
"""Variable to be evaluated in computing the TV regularisation
term , depending on the ` ` gEvalY ` ` option value .""" | # Use of self . block _ sep0 ( self . AXnr ) instead of self . cnst _ A0 ( self . X )
# reduces number of calls to self . cnst _ A0
return self . var_y0 ( ) if self . opt [ 'gEvalY' ] else self . block_sep0 ( self . AXnr ) |
def position ( msg0 , msg1 , t0 , t1 , lat_ref = None , lon_ref = None ) :
"""Decode position from a pair of even and odd position message
( works with both airborne and surface position messages )
Args :
msg0 ( string ) : even message ( 28 bytes hexadecimal string )
msg1 ( string ) : odd message ( 28 bytes... | tc0 = typecode ( msg0 )
tc1 = typecode ( msg1 )
if ( 5 <= tc0 <= 8 and 5 <= tc1 <= 8 ) :
if ( not lat_ref ) or ( not lon_ref ) :
raise RuntimeError ( "Surface position encountered, a reference \
position lat/lon required. Location of \
receiver c... |
def points_from_xywh ( box ) :
"""Constructs a polygon representation from a rectangle described as a dict with keys x , y , w , h .""" | x , y , w , h = box [ 'x' ] , box [ 'y' ] , box [ 'w' ] , box [ 'h' ]
# tesseract uses a different region representation format
return "%i,%i %i,%i %i,%i %i,%i" % ( x , y , x + w , y , x + w , y + h , x , y + h ) |
def split_unit ( self , unit_id , indices ) :
'''This function splits a root from the curation tree according to the given unit _ id and indices . It creates two new unit _ ids
and roots that have the split root as a child . This function splits the spike train of the root by the given indices .
Parameters
un... | root_ids = [ ]
for i in range ( len ( self . _roots ) ) :
root_id = self . _roots [ i ] . unit_id
root_ids . append ( root_id )
if ( unit_id in root_ids ) :
indices_1 = np . sort ( np . asarray ( list ( set ( indices ) ) ) )
root_index = root_ids . index ( unit_id )
new_child = self . _roots [ root_... |
def value_validate ( self , value ) :
"""Converts the input single value into the expected Python data type ,
raising django . core . exceptions . ValidationError if the data can ' t be
converted . Returns the converted value . Subclasses should override
this .""" | if not isinstance ( value , datetime . date ) :
raise tldap . exceptions . ValidationError ( "is invalid date" )
# a datetime is also a date but they are not compatable
if isinstance ( value , datetime . datetime ) :
raise tldap . exceptions . ValidationError ( "should be a date, not a datetime" ) |
def branches ( directory = None , verbose = False ) :
"""Show current branch points""" | config = current_app . extensions [ 'migrate' ] . migrate . get_config ( directory )
if alembic_version >= ( 0 , 7 , 0 ) :
command . branches ( config , verbose = verbose )
else :
command . branches ( config ) |
def create_args_parser ( ) :
"""Return command line parser""" | parser = argparse . ArgumentParser ( description = 'Dialect-aware s-expression indenter' , prog = 'yasi' )
parser . add_argument ( 'files' , help = 'List of files to be indented. ' 'Will indent from standard input if no files are specified' , nargs = '*' )
parser . add_argument ( '-nc' , '--no-compact' , '--nc' , dest ... |
def Hash ( self ) :
"""Get the hash value of the Blockbase .
Returns :
UInt256 : containing the hash of the data .""" | if not self . __hash :
hashdata = self . RawData ( )
ba = bytearray ( binascii . unhexlify ( hashdata ) )
hash = bin_dbl_sha256 ( ba )
self . __hash = UInt256 ( data = hash )
return self . __hash |
def get_table_cache_key ( db_alias , table ) :
"""Generates a cache key from a SQL table .
: arg db _ alias : Alias of the used database
: type db _ alias : str or unicode
: arg table : Name of the SQL table
: type table : str or unicode
: return : A cache key
: rtype : int""" | cache_key = '%s:%s' % ( db_alias , table )
return sha1 ( cache_key . encode ( 'utf-8' ) ) . hexdigest ( ) |
def update ( self , typ , id , ** kwargs ) :
"""update just fields sent by keyword args""" | return self . _load ( self . _request ( typ , id = id , method = 'PUT' , data = kwargs ) ) |
def execute ( self , i , o ) :
"""Executes the command .
: type i : cleo . inputs . input . Input
: type o : cleo . outputs . output . Output""" | super ( MigrateMakeCommand , self ) . execute ( i , o )
creator = MigrationCreator ( )
name = i . get_argument ( 'name' )
table = i . get_option ( 'table' )
create = bool ( i . get_option ( 'create' ) )
if not table and create is not False :
table = create
path = i . get_option ( 'path' )
if path is None :
path... |
def _reset_stylesheet ( self ) :
"""Resets stylesheet""" | self . setFont ( QtGui . QFont ( self . _font_family , self . _font_size + self . _zoom_level ) )
flg_stylesheet = hasattr ( self , '_flg_stylesheet' )
if QtWidgets . QApplication . instance ( ) . styleSheet ( ) or flg_stylesheet :
self . _flg_stylesheet = True
# On Window , if the application once had a styles... |
def list_groups ( self , filtr = None ) :
"""Get the groups the logged in user is a member of .
Optionally filter by ' member ' or ' maintainer ' .
Args :
filtr ( optional [ string | None ] ) : [ ' member ' | ' maintainer ' ] or defaults to None .
Returns :
( list [ string ] ) : List of group names .
Ra... | return self . service . list_groups ( filtr , self . url_prefix , self . auth , self . session , self . session_send_opts ) |
def command ( self ) :
"""Manually import a CSV into a nYNAB budget""" | print ( 'pynYNAB CSV import' )
args = self . parser . parse_args ( )
verify_common_args ( args )
verify_csvimport ( args . schema , args . accountname )
client = clientfromkwargs ( ** args )
delta = do_csvimport ( args , client )
client . push ( expected_delta = delta ) |
def sampling_query ( sql , context , fields = None , count = 5 , sampling = None , udfs = None , data_sources = None ) :
"""Returns a sampling Query for the SQL object .
Args :
sql : the SQL statement ( string ) or Query object to sample .
context : a Context object providing project _ id and credentials .
... | return Query ( _sampling . Sampling . sampling_query ( sql , fields , count , sampling ) , context = context , udfs = udfs , data_sources = data_sources ) |
def _organize_inits ( inits , pars , dims ) :
"""Obtain a list of initial values for each chain .
The parameter ' lp _ _ ' will be removed from the chains .
Parameters
inits : list
list of initial values for each chain .
pars : list of str
dims : list of list of int
from ( via cython conversion ) vect... | try :
idx_of_lp = pars . index ( 'lp__' )
del pars [ idx_of_lp ]
del dims [ idx_of_lp ]
except ValueError :
pass
starts = _calc_starts ( dims )
return [ _par_vector2dict ( init , pars , dims , starts ) for init in inits ] |
def split_blocks ( text_block , w , cols , part_fmter = None ) :
"""splits while multiline blocks vertically ( for large tables )""" | ts = [ ]
for line in text_block . splitlines ( ) :
parts = [ ]
# make equal len :
line = line . ljust ( w , ' ' )
# first part full width , others a bit indented :
parts . append ( line [ : cols ] )
scols = cols - 2
# the txt _ block _ cut in low makes the whole secondary tables
# low . ... |
def create_and_run_collector ( document , options ) :
"""Create and run collector process for report data .""" | collector = None
if not options . report == 'off' :
collector = Collector ( )
collector . store . configure ( document )
Event . configure ( collector_queue = collector . queue )
collector . start ( )
return collector |
def diff_flux_threshold ( self , skydir , fn , ts_thresh , min_counts ) :
"""Compute the differential flux threshold for a point source at
position ` ` skydir ` ` with spectral parameterization ` ` fn ` ` .
Parameters
skydir : ` ~ astropy . coordinates . SkyCoord `
Sky coordinates at which the sensitivity w... | sig , bkg , bkg_fit = self . compute_counts ( skydir , fn )
norms = irfs . compute_norm ( sig , bkg , ts_thresh , min_counts , sum_axes = [ 2 , 3 ] , rebin_axes = [ 10 , 1 ] , bkg_fit = bkg_fit )
npred = np . squeeze ( np . apply_over_axes ( np . sum , norms * sig , [ 2 , 3 ] ) )
norms = np . squeeze ( norms )
flux = n... |
def subtree ( self , event , create = False ) :
'''Find a subtree from an event''' | current = self
for i in range ( self . depth , len ( event . indices ) ) :
if not hasattr ( current , 'index' ) :
return current
ind = event . indices [ i ]
if create :
current = current . index . setdefault ( ind , EventTree ( current , self . branch ) )
current . parentIndex = ind
... |
def store_directory ( ctx , param , value ) :
"""Store directory as a new Git home .""" | Path ( value ) . mkdir ( parents = True , exist_ok = True )
set_git_home ( value )
return value |
def get_client ( self , service , region , public = True , cached = True , client_class = None ) :
"""Returns the client object for the specified service and region .
By default the public endpoint is used . If you wish to work with a
services internal endpoints , specify ` public = False ` .
By default , if ... | if not self . authenticated :
raise exc . NotAuthenticated ( "You must authenticate before trying " "to create clients." )
clt = ep = None
mapped_service = self . service_mapping . get ( service ) or service
svc = self . services . get ( mapped_service )
if svc :
ep = svc . endpoints . get ( region )
if ep :
... |
def data_shape ( self ) :
"""Shape tuple of the whole data block as determined from ` header ` .
If no header is available ( i . e . , before it has been initialized ) ,
or any of the header entries ` ` ' nx ' , ' ny ' , ' nz ' ` ` is missing ,
-1 is returned , which makes reshaping a no - op .
Otherwise , ... | if not self . header :
return - 1
try :
nx = self . header [ 'nx' ] [ 'value' ]
ny = self . header [ 'ny' ] [ 'value' ]
nz = self . header [ 'nz' ] [ 'value' ]
except KeyError :
return - 1
else :
return tuple ( int ( n ) for n in ( nx , ny , nz ) ) |
def check_ontology ( fname ) :
"""reads the ontology yaml file and does basic verifcation""" | with open ( fname , 'r' ) as stream :
y = yaml . safe_load ( stream )
import pprint
pprint . pprint ( y ) |
def fetch ( self , _filter = None , ignore_incremental = False ) :
"""Fetch the items from raw or enriched index . An optional _ filter
could be provided to filter the data collected""" | logger . debug ( "Creating a elastic items generator." )
scroll_id = None
page = self . get_elastic_items ( scroll_id , _filter = _filter , ignore_incremental = ignore_incremental )
if not page :
return [ ]
scroll_id = page [ "_scroll_id" ]
scroll_size = page [ 'hits' ] [ 'total' ]
if scroll_size == 0 :
logger ... |
def _get_adjusted_merge_area ( self , attrs , insertion_point , no_to_insert , axis ) :
"""Returns updated merge area
Parameters
attrs : Dict
\t Cell attribute dictionary that shall be adjusted
insertion _ point : Integer
\t Pont on axis , before which insertion takes place
no _ to _ insert : Integer > ... | assert axis in range ( 2 )
if "merge_area" not in attrs or attrs [ "merge_area" ] is None :
return
top , left , bottom , right = attrs [ "merge_area" ]
selection = Selection ( [ ( top , left ) ] , [ ( bottom , right ) ] , [ ] , [ ] , [ ] )
selection . insert ( insertion_point , no_to_insert , axis )
__top , __left ... |
def read_aims ( filename ) :
"""Method to read FHI - aims geometry files in phonopy context .""" | lines = open ( filename , 'r' ) . readlines ( )
cell = [ ]
is_frac = [ ]
positions = [ ]
symbols = [ ]
magmoms = [ ]
for line in lines :
fields = line . split ( )
if not len ( fields ) :
continue
if fields [ 0 ] == "lattice_vector" :
vec = lmap ( float , fields [ 1 : 4 ] )
cell . app... |
def upload_files_in_folder ( self , dirname , fnames ) :
"""Handles the iteration across files within a folder .""" | if utils . match_pattern ( dirname , self . ignore ) :
return False
good_names = ( nm for nm in fnames if not utils . match_pattern ( nm , self . ignore ) )
for fname in good_names :
if self . client . _should_abort_folder_upload ( self . upload_key ) :
return
full_path = os . path . join ( dirname ... |
def traceroute_batch ( input_list , results = { } , method = "udp" , cmd_arguments = None , delay_time = 0.1 , max_threads = 100 ) :
"""This is a parallel version of the traceroute primitive .
: param input _ list : the input is a list of domain names
: param method : the packet type used for traceroute , UDP b... | threads = [ ]
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len ( input_list )
for domain in input_list :
wait_time = 0
while threading . active_count ( ) > max_threads :
time . sleep ( 1 )
wait_time += 1
if wait_time > thread_wait_timeout :
thread... |
def on_add_cols ( self , event ) :
"""Show simple dialog that allows user to add a new column name""" | col_labels = self . grid . col_labels
# do not list headers that are already column labels in the grid
er_items = [ head for head in self . grid_headers [ self . grid_type ] [ 'er' ] [ 2 ] if head not in col_labels ]
# remove unneeded headers
er_items = builder . remove_list_headers ( er_items )
pmag_headers = sorted (... |
def lnprior ( self , X ) :
"""Use a uniform , bounded prior .""" | if np . any ( X < self . _lower_left ) or np . any ( X > self . _upper_right ) :
return - np . inf
else :
return 0.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.