signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _Completion ( self , match ) : # pylint : disable = C6114
r"""Replaces double square brackets with variable length completion .
Completion cannot be mixed with regexp matching or ' \ ' characters
i . e . ' [ [ ( \ n ) ] ] would become ( \ ( n ) ? ) ? . '
Args :
match : A regex Match ( ) object .
Retur... | # Strip the outer ' [ [ ' & ' ] ] ' and replace with ( ) ? regexp pattern .
word = str ( match . group ( ) ) [ 2 : - 2 ]
return '(' + ( '(' ) . join ( word ) + ')?' * len ( word ) |
def set_dep ( self , * deps ) -> "Model" :
"""Register the dependencies for this model .
: param deps : The parent models : objects or meta dicts .
: return : self""" | self . meta [ "dependencies" ] = [ ( d . meta if not isinstance ( d , dict ) else d ) for d in deps ]
return self |
def on_initialize_simulants ( self , pop_data : SimulantData ) :
"""Called by the simulation whenever new simulants are added .
This component is responsible for creating and filling four columns
in the population state table :
' age ' :
The age of the simulant in fractional years .
' sex ' :
The sex of... | age_start = self . config . population . age_start
age_end = self . config . population . age_end
if age_start == age_end :
age_window = pop_data . creation_window / pd . Timedelta ( days = 365 )
else :
age_window = age_end - age_start
age_draw = self . age_randomness . get_draw ( pop_data . index )
age = age_s... |
def configfield_ref_role ( name , rawtext , text , lineno , inliner , options = None , content = None ) :
"""Process a role that references the Task configuration field nodes
created by the ` ` lsst - config - fields ` ` , ` ` lsst - task - config - subtasks ` ` ,
and ` ` lsst - task - config - subtasks ` ` dir... | node = pending_configfield_xref ( rawsource = text )
return [ node ] , [ ] |
def sendResult ( self , future ) :
"""Send a terminated future back to its parent .""" | future = copy . copy ( future )
# Remove the ( now ) extraneous elements from future class
future . callable = future . args = future . kargs = future . greenlet = None
if not future . sendResultBack : # Don ' t reply back the result if it isn ' t asked
future . resultValue = None
self . _sendReply ( future . id . ... |
def get_all_clusters ( resource_root , view = None ) :
"""Get all clusters
@ param resource _ root : The root Resource object .
@ return : A list of ApiCluster objects .""" | return call ( resource_root . get , CLUSTERS_PATH , ApiCluster , True , params = view and dict ( view = view ) or None ) |
def tornadopath2openapi ( urlspec , method ) :
"""Convert Tornado URLSpec to OpenAPI - compliant path .
: param urlspec :
: type urlspec : URLSpec
: param method : Handler http method
: type method : function""" | if sys . version_info >= ( 3 , 3 ) :
args = list ( inspect . signature ( method ) . parameters . keys ( ) ) [ 1 : ]
else :
if getattr ( method , '__tornado_coroutine__' , False ) :
method = method . __wrapped__
args = inspect . getargspec ( method ) . args [ 1 : ]
params = tuple ( '{{{}}}' . format ... |
def time ( host = None , port = None , db = None , password = None ) :
'''Return the current server UNIX time in seconds
CLI Example :
. . code - block : : bash
salt ' * ' redis . time''' | server = _connect ( host , port , db , password )
return server . time ( ) [ 0 ] |
def _to_DOM ( self ) :
"""Dumps object data to a fully traversable DOM representation of the
object .
: returns : a ` ` xml . etree . Element ` ` object""" | root_node = ET . Element ( "ozone" )
reference_time_node = ET . SubElement ( root_node , "reference_time" )
reference_time_node . text = str ( self . _reference_time )
reception_time_node = ET . SubElement ( root_node , "reception_time" )
reception_time_node . text = str ( self . _reception_time )
interval_node = ET . ... |
def update_sentry_logging ( logging_dict : DictStrAny , sentry_dsn : Optional [ str ] , * loggers : str , level : Union [ str , int ] = None , ** kwargs : Any ) -> None :
r"""Enable Sentry logging if Sentry DSN passed .
. . note : :
Sentry logging requires ` raven < http : / / pypi . python . org / pypi / raven... | # No Sentry DSN , nothing to do
if not sentry_dsn :
return
# Add Sentry handler
kwargs [ 'class' ] = 'raven.handlers.logging.SentryHandler'
kwargs [ 'dsn' ] = sentry_dsn
logging_dict [ 'handlers' ] [ 'sentry' ] = dict ( level = level or 'WARNING' , ** kwargs )
loggers = tuple ( logging_dict [ 'loggers' ] ) if not l... |
def loadCurve ( data , groups , thresholds , absvals , fs , xlabels ) :
"""Accepts a data set from a whole test , averages reps and re - creates the
progress plot as the same as it was during live plotting . Number of thresholds
must match the size of the channel dimension""" | xlims = ( xlabels [ 0 ] , xlabels [ - 1 ] )
pw = ProgressWidget ( groups , xlims )
spike_counts = [ ]
# skip control
for itrace in range ( data . shape [ 0 ] ) :
count = 0
for ichan in range ( data . shape [ 2 ] ) :
flat_reps = data [ itrace , : , ichan , : ] . flatten ( )
count += len ( spikest... |
def _resize ( self , ratio_x , ratio_y , resampling ) :
"""Return raster resized by ratio .""" | new_width = int ( np . ceil ( self . width * ratio_x ) )
new_height = int ( np . ceil ( self . height * ratio_y ) )
dest_affine = self . affine * Affine . scale ( 1 / ratio_x , 1 / ratio_y )
if self . not_loaded ( ) :
window = rasterio . windows . Window ( 0 , 0 , self . width , self . height )
resized_raster =... |
def view_sbo ( self ) :
"""View slackbuild . org""" | sbo_url = self . sbo_url . replace ( "/slackbuilds/" , "/repository/" )
br1 , br2 , fix_sp = "" , "" , " "
if self . meta . use_colors in [ "off" , "OFF" ] :
br1 = "("
br2 = ")"
fix_sp = ""
print ( "" )
# new line at start
self . msg . template ( 78 )
print ( "| {0}{1}SlackBuilds Repository{2}" . format ( "... |
def as_flow ( cls , obj ) :
"""Convert obj into a Flow . Accepts filepath , dict , or Flow object .""" | if isinstance ( obj , cls ) :
return obj
if is_string ( obj ) :
return cls . pickle_load ( obj )
elif isinstance ( obj , collections . Mapping ) :
return cls . from_dict ( obj )
else :
raise TypeError ( "Don't know how to convert type %s into a Flow" % type ( obj ) ) |
def shutdown ( self ) :
"""Sends a shutdown message to other workers .""" | if self . OPEN :
self . OPEN = False
scoop . SHUTDOWN_REQUESTED = True
self . socket . send ( b"SHUTDOWN" )
self . socket . close ( )
self . infoSocket . close ( )
time . sleep ( 0.3 ) |
def generate_data_for_edit_page ( self ) :
"""Generate a custom representation of table ' s fields in dictionary type
if exist edit form else use default representation .
: return : dict""" | if not self . can_edit :
return { }
if self . edit_form :
return self . edit_form . to_dict ( )
return self . generate_simple_data_page ( ) |
def _get_sdict ( self , env ) :
"""Returns a dictionary mapping all of the source suffixes of all
src _ builders of this Builder to the underlying Builder that
should be called first .
This dictionary is used for each target specified , so we save a
lot of extra computation by memoizing it for each construc... | sdict = { }
for bld in self . get_src_builders ( env ) :
for suf in bld . src_suffixes ( env ) :
sdict [ suf ] = bld
return sdict |
def deactivate_user ( self , user ) :
"""Deactivate a user .
: param user : A : class : ` invenio _ accounts . models . User ` instance .
: returns : The datastore instance .""" | res = super ( SessionAwareSQLAlchemyUserDatastore , self ) . deactivate_user ( user )
if res :
delete_user_sessions ( user )
return res |
def setspan ( self , * args ) :
"""Sets the span of the span element anew , erases all data inside .
Arguments :
* args : Instances of : class : ` Word ` , : class : ` Morpheme ` or : class : ` Phoneme `""" | self . data = [ ]
for child in args :
self . append ( child ) |
def SetEncoding ( sval ) :
"""Sets the encoding variable according to the text passed
: param sval : text specification for the desired model""" | global encoding
s = sval . lower ( )
if s == "additive" :
encoding = Encoding . Additive
elif s == "dominant" :
encoding = Encoding . Dominant
elif s == "recessive" :
encoding = Encoding . Recessive
elif s == "genotype" :
encoding = Encoding . Genotype
elif s == "raw" :
encoding = Encoding . Raw
els... |
def limit ( self , limit ) :
"""Set absolute limit on number of images to return , or set to None to return
as many results as needed ; default 50 posts .""" | params = join_params ( self . parameters , { "limit" : limit } )
return self . __class__ ( ** params ) |
def step ( self , provided_inputs ) :
"""Run the simulation for a cycle
: param provided _ inputs : a dictionary mapping WireVectors ( or their names )
to their values for this step
eg : { wire : 3 , " wire _ name " : 17}""" | # validate _ inputs
for wire , value in provided_inputs . items ( ) :
wire = self . block . get_wirevector_by_name ( wire ) if isinstance ( wire , str ) else wire
if value > wire . bitmask or value < 0 :
raise PyrtlError ( "Wire {} has value {} which cannot be represented" " using its bitwidth" . format... |
def __deserialize_model ( self , data , klass ) :
"""Deserializes list or dict to model .
: param data : dict , list .
: param klass : class literal .
: return : model object .""" | if not klass . swagger_types :
return data
kwargs = { }
for attr , attr_type in iteritems ( klass . swagger_types ) :
if data is not None and klass . attribute_map [ attr ] in data and isinstance ( data , ( list , dict ) ) :
value = data [ klass . attribute_map [ attr ] ]
kwargs [ attr ] = self ... |
def sed_inplace ( filename , pattern , repl ) :
'''Perform the pure - Python equivalent of in - place ` sed ` substitution : e . g . ,
` sed - i - e ' s / ' $ { pattern } ' / ' $ { repl } ' " $ { filename } " ` .''' | # For efficiency , precompile the passed regular expression .
pattern_compiled = re . compile ( pattern )
# For portability , NamedTemporaryFile ( ) defaults to mode " w + b "
# ( i . e . , binary writing with updating ) .
# This is usually a good thing . In this case , # however , binary writing
# imposes non - trivia... |
def run_until ( self , endtime , timeunit = 'minutes' , save = True ) :
"""Run a case untile the specifiend endtime""" | integrator = self . case . solver . Integrator
integrator . rununtil ( endtime , timeunit )
if save is True :
self . case . save ( ) |
def status ( self ) :
"""Attempts to label this invoice with a status . Note that an invoice can be more than one of the choices .
We just set a priority on which status appears .""" | if self . paid :
return self . STATUS_PAID
if self . forgiven :
return self . STATUS_FORGIVEN
if self . closed :
return self . STATUS_CLOSED
return self . STATUS_OPEN |
def item_from_event ( self , domain_event ) :
"""Constructs a sequenced item from a domain event .""" | item_args = self . construct_item_args ( domain_event )
return self . construct_sequenced_item ( item_args ) |
def get_data_id_by_slug ( self , slug ) :
"""Find data object ID for given slug .
This method queries the Resolwe API and requires network access .""" | resolwe_host = os . environ . get ( 'RESOLWE_HOST_URL' )
url = urllib . parse . urljoin ( resolwe_host , '/api/data?slug={}&fields=id' . format ( slug ) )
with urllib . request . urlopen ( url , timeout = 60 ) as f :
data = json . loads ( f . read ( ) . decode ( 'utf-8' ) )
if len ( data ) == 1 :
return data [ ... |
def loadInstance ( self ) :
"""Loads the plugin from the proxy information that was created from the
registry file .""" | if self . _loaded :
return
self . _loaded = True
module_path = self . modulePath ( )
package = projex . packageFromPath ( module_path )
path = os . path . normpath ( projex . packageRootPath ( module_path ) )
if path in sys . path :
sys . path . remove ( path )
sys . path . insert ( 0 , path )
try :
__impor... |
def attach_remote ( self , id , name , ** kwargs ) :
"""create remote instance of widget
Arguments :
- id ( str ) : widget id
- name ( str ) : widget type name
Keyword Arguments :
- any further arguments you wish to pass
to the widget constructor""" | client_id = id . split ( "." ) [ 0 ]
widget = self . make_widget ( id , name , dispatcher = ProxyDispatcher ( self , link = getattr ( self . clients [ client_id ] , "link" , None ) ) , ** kwargs )
self . store_widget ( widget )
self . log_debug ( "Attached widget: %s" % id ) |
def fields ( self ) :
"""returns a list of feature fields""" | if 'feature' in self . _dict :
self . _attributes = self . _dict [ 'feature' ] [ 'attributes' ]
else :
self . _attributes = self . _dict [ 'attributes' ]
return self . _attributes . keys ( ) |
def setup_figure ( self , figure ) :
"""Makes any desired changes to the figure object
This method will be called once with a figure object
before any plotting has completed . Subclasses that
override this method should make sure that the base
class method is called .""" | for th in self . themeables . values ( ) :
th . setup_figure ( figure ) |
def delete_resource_subscription ( self , device_id = None , resource_path = None , fix_path = True ) :
"""Unsubscribe from device and / or resource _ path updates .
If device _ id or resource _ path is None , or this method is called without arguments ,
all subscriptions are removed .
Calling it with only de... | devices = [ _f for _f in [ device_id ] if _f ]
if not device_id :
devices = list ( self . _queues . keys ( ) )
resource_paths = [ resource_path ]
if not resource_path :
resource_paths = [ ]
for e in devices :
resource_paths . extend ( list ( self . _queues [ e ] . keys ( ) ) )
# Delete the subscript... |
def _create_api_call ( self , method , _url , kwargs ) :
"""This will create an APICall object and return it
: param method : str of the html method [ ' GET ' , ' POST ' , ' PUT ' , ' DELETE ' ]
: param _ url : str of the sub url of the api call ( ex . g / device / list )
: param kwargs : dict of additional a... | api_call = self . ApiCall ( name = '%s.%s' % ( _url , method ) , label = 'ID_%s' % self . _count , base_uri = self . base_uri , timeout = self . timeout , headers = self . headers , cookies = self . cookies , proxies = self . proxies , accepted_return = self . accepted_return or 'json' )
if self . max_history :
sel... |
def new_gp_object ( typename ) :
"""Create an indirect pointer to a GPhoto2 type , call its matching
constructor function and return the pointer to it .
: param typename : Name of the type to create .
: return : A pointer to the specified data type .""" | obj_p = backend . ffi . new ( "{0}**" . format ( typename ) )
backend . CONSTRUCTORS [ typename ] ( obj_p )
return obj_p [ 0 ] |
def image_url ( self , pixel_size = None ) :
"""Get the URL for the user icon in the desired pixel size , if it exists . If no
size is supplied , give the URL for the full - size image .""" | if "profile" not in self . _raw :
return
profile = self . _raw [ "profile" ]
if ( pixel_size ) :
img_key = "image_%s" % pixel_size
if img_key in profile :
return profile [ img_key ]
return profile [ self . _DEFAULT_IMAGE_KEY ] |
def jobs_insert_load ( self , source , table_name , append = False , overwrite = False , create = False , source_format = 'CSV' , field_delimiter = ',' , allow_jagged_rows = False , allow_quoted_newlines = False , encoding = 'UTF-8' , ignore_unknown_values = False , max_bad_records = 0 , quote = '"' , skip_leading_rows... | url = Api . _ENDPOINT + ( Api . _JOBS_PATH % ( table_name . project_id , '' ) )
if isinstance ( source , basestring ) :
source = [ source ]
write_disposition = 'WRITE_EMPTY'
if overwrite :
write_disposition = 'WRITE_TRUNCATE'
if append :
write_disposition = 'WRITE_APPEND'
data = { 'kind' : 'bigquery#job' , ... |
def synchronise_device_state ( self , device_state , authentication_headers ) :
"""Synchronizing the component states with AVS
Components state must be synchronised with AVS after establishing the
downchannel stream in order to create a persistent connection with AVS .
Note that currently this function is pay... | payload = { 'context' : device_state , 'event' : { 'header' : { 'namespace' : 'System' , 'name' : 'SynchronizeState' , 'messageId' : '' } , 'payload' : { } } }
multipart_data = MultipartEncoder ( fields = [ ( 'metadata' , ( 'metadata' , json . dumps ( payload ) , 'application/json' , { 'Content-Disposition' : "form-dat... |
def register ( action ) :
"""Action registration is used to support generating lists of
permitted actions from a permission set and an object pattern .
Only registered actions will be returned by such queries .""" | if isinstance ( action , str ) :
Action . register ( Action ( action ) )
elif isinstance ( action , Action ) :
Action . registered . add ( action )
else :
for a in action :
Action . register ( a ) |
def load_model ( ) :
"""Load a n - gram language model for mathematics in ARPA format which gets
shipped with hwrt .
Returns
A NgramLanguageModel object""" | logging . info ( "Load language model..." )
ngram_arpa_t = pkg_resources . resource_filename ( 'hwrt' , 'misc/ngram.arpa.tar.bz2' )
with tarfile . open ( ngram_arpa_t , 'r:bz2' ) as tar :
tarfolder = tempfile . mkdtemp ( )
tar . extractall ( path = tarfolder )
ngram_arpa_f = os . path . join ( tarfolder , 'ngra... |
def nullify ( function ) :
"Decorator . If empty list , returns None , else list ." | def wrapper ( * args , ** kwargs ) :
value = function ( * args , ** kwargs )
if ( type ( value ) == list and len ( value ) == 0 ) :
return None
return value
return wrapper |
def _all_possible_partitionings ( elements , sizes ) :
'''Helper function for Game . all _ possible _ hands ( ) . Given a set of elements
and the sizes of partitions , yields all possible partitionings of the
elements into partitions of the provided sizes .
: param set elements : a set of elements to partitio... | try : # get the size of the current partition
size = sizes [ 0 ]
except IndexError : # base case : no more sizes left
yield ( )
return
# don ' t include the current size in the recursive calls
sizes = sizes [ 1 : ]
# iterate over all possible partitions of the current size
for partition in itertools . combi... |
def get_module_files ( src_directory , blacklist , list_all = False ) :
"""given a package directory return a list of all available python
module ' s files in the package and its subpackages
: type src _ directory : str
: param src _ directory :
path of the directory corresponding to the package
: type bl... | files = [ ]
for directory , dirnames , filenames in os . walk ( src_directory ) :
if directory in blacklist :
continue
_handle_blacklist ( blacklist , dirnames , filenames )
# check for _ _ init _ _ . py
if not list_all and "__init__.py" not in filenames :
dirnames [ : ] = ( )
co... |
def _send ( self , email_message ) :
"""A helper method that does the actual sending .""" | if not email_message . recipients ( ) :
return False
from_email = email_message . from_email
recipients = email_message . recipients ( )
try :
self . connection . messages . create ( to = recipients , from_ = from_email , body = email_message . body )
except Exception :
if not self . fail_silently :
... |
def register ( name , _callable = None ) :
"""A decorator used for register custom check .
: param name : name of check
: type : str
: param _ callable : check class or a function which return check instance
: return : _ callable or a decorator""" | def wrapper ( _callable ) :
registered_checks [ name ] = _callable
return _callable
# If function or class is given , do the registeration
if _callable :
return wrapper ( _callable )
return wrapper |
def find_template_companion ( template , extension = '' , check = True ) :
"""Returns the first found template companion file""" | if check and not os . path . isfile ( template ) :
yield ''
return
# May be ' < stdin > ' ( click )
template = os . path . abspath ( template )
template_dirname = os . path . dirname ( template )
template_basename = os . path . basename ( template ) . split ( '.' )
current_path = template_dirname
stop_path = os... |
def check_response ( response ) :
"""checks the response if the server returned an error raises an exception .""" | if response . status_code < 200 or response . status_code > 300 :
raise ServerError ( 'API requests returned with error: %s' % response . status_code )
try :
response_text = loads ( response . text )
except ValueError :
raise ServerError ( 'The API did not returned a JSON string.' )
if not response_text :
... |
def plot3d ( self , elevation = 20 , azimuth = 30 , cmap = 'RdBu_r' , show = True , fname = None ) :
"""Plot the raw data on a 3d sphere .
This routines becomes slow for large grids because it is based on
matplotlib3d .
Usage
x . plot3d ( [ elevation , azimuth , show , fname ] )
Parameters
elevation : f... | from mpl_toolkits . mplot3d import Axes3D
nlat , nlon = self . nlat , self . nlon
cmap = _plt . get_cmap ( cmap )
if self . kind == 'real' :
data = self . data
elif self . kind == 'complex' :
data = _np . abs ( self . data )
else :
raise ValueError ( 'Grid has to be either real or complex, not {}' . format ... |
def pretty_descriptor ( self ) :
"""get the class or interface name , its accessor flags , its parent
class , and any interfaces it implements""" | f = " " . join ( self . pretty_access_flags ( ) )
if not self . is_interface ( ) :
f += " class"
n = self . pretty_this ( )
e = self . pretty_super ( )
i = "," . join ( self . pretty_interfaces ( ) )
if i :
return "%s %s extends %s implements %s" % ( f , n , e , i )
else :
return "%s %s extends %s" % ( f , ... |
def stats ( txt , color = False ) :
"Print stats" | if color :
txt = config . Col . OKBLUE + txt + config . Col . ENDC
print ( txt ) |
def _transition_stage ( self , step , total_steps , brightness = None ) :
"""Get a transition stage at a specific step .
: param step : The current step .
: param total _ steps : The total number of steps .
: param brightness : The brightness to transition to ( 0.0-1.0 ) .
: return : The stage at the specif... | if brightness is not None :
self . _assert_is_brightness ( brightness )
brightness = self . _interpolate ( self . brightness , brightness , step , total_steps )
return { 'brightness' : brightness } |
def rename_notes_folder ( self , title , folderid ) :
"""Rename a folder
: param title : New title of the folder
: param folderid : The UUID of the folder to rename""" | 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 ( '/notes/folders/rename/{}' . format ( folderid ) , post_data = { 'title' : title } )
return respon... |
def save_report ( self , file_path ) :
"""Write coveralls report to file .""" | try :
report = self . create_report ( )
except coverage . CoverageException as e :
log . error ( 'Failure to gather coverage:' , exc_info = e )
else :
with open ( file_path , 'w' ) as report_file :
report_file . write ( report ) |
def encrypt_folder ( path , sender , recipients ) :
"""This helper function should zip the contents of a folder and encrypt it as
a zip - file . Recipients are responsible for opening the zip - file .""" | for recipient_key in recipients :
crypto . assert_type_and_length ( 'recipient_key' , recipient_key , ( str , crypto . UserLock ) )
crypto . assert_type_and_length ( "sender_key" , sender , crypto . UserLock )
if ( not os . path . exists ( path ) ) or ( not os . path . isdir ( path ) ) :
raise OSError ( "Specif... |
def LoadExclusions ( self , snps ) :
"""Load locus exclusions .
: param snps : Can either be a list of rsids or a file containing rsids .
: return : None
If snps is a file , the file must only contain RSIDs separated
by whitespace ( tabs , spaces and return characters ) .""" | snp_names = [ ]
if len ( snps ) == 1 and os . path . isfile ( snps [ 0 ] ) :
snp_names = open ( snps ) . read ( ) . strip ( ) . split ( )
else :
snp_names = snps
for snp in snp_names :
if len ( snp . strip ( ) ) > 0 :
self . ignored_rs . append ( snp ) |
def checkout ( repo , ref ) :
"""Checkout a repoself .""" | # Delete local branch if it exists , remote branch will be tracked
# automatically . This prevents stale local branches from causing problems .
# It also avoids problems with appending origin / to refs as that doesn ' t
# work with tags , SHAs , and upstreams not called origin .
if ref in repo . branches : # eg delete ... |
def load ( items , default_section = _DEFAULT_SECTION ) :
"""从混合类型组中读取配置
: param default _ section :
: param items :
: return :""" | settings = [ ]
assert isinstance ( items , list ) , 'items必须为list'
logger . debug ( items )
for item in items :
if _is_conf ( item ) :
settings . append ( load_from_ini ( item , default_section ) )
else :
settings . append ( load_from_name ( item ) )
logger . debug ( settings )
return merge ( se... |
def get_wcs ( self , data_x , data_y ) :
"""Return ( re _ deg , dec _ deg ) for the ( data _ x , data _ y ) position
based on any WCS associated with the loaded image .""" | img = self . fitsimage . get_image ( )
ra , dec = img . pixtoradec ( data_x , data_y )
return ra , dec |
def buildconfig_update ( orig , new , remove_nonexistent_keys = False ) :
"""Performs update of given ` orig ` BuildConfig with values from ` new ` BuildConfig .
Both BuildConfigs have to be represented as ` dict ` s .
This function :
- adds all key / value pairs to ` orig ` from ` new ` that are missing
- ... | if isinstance ( orig , dict ) and isinstance ( new , dict ) :
clean_triggers ( orig , new )
if remove_nonexistent_keys :
missing = set ( orig . keys ( ) ) - set ( new . keys ( ) )
for k in missing :
orig . pop ( k )
for k , v in new . items ( ) :
if k == 'strategy' :
... |
def weights ( self , other ) :
"""Compute weights , given a scale or time - frequency representation
: param other : A time - frequency representation , or a scale
: return : a numpy array of weights""" | try :
return self . _wdata ( other )
except AttributeError :
frequency_dim = other . dimensions [ - 1 ]
return self . _wdata ( frequency_dim . scale ) |
def export_process_to_csv ( bpmn_diagram , directory , filename ) :
"""Root method of CSV export functionality .
: param bpmn _ diagram : an instance of BpmnDiagramGraph class ,
: param directory : a string object , which is a path of output directory ,
: param filename : a string object , which is a name of ... | nodes = copy . deepcopy ( bpmn_diagram . get_nodes ( ) )
start_nodes = [ ]
export_elements = [ ]
for node in nodes :
incoming_list = node [ 1 ] . get ( consts . Consts . incoming_flow )
if len ( incoming_list ) == 0 :
start_nodes . append ( node )
if len ( start_nodes ) != 1 :
raise bpmn_exception .... |
def _calc_mem_info ( self , unit , meminfo , memory ) :
"""Parse / proc / meminfo , grab the memory capacity and used size
then return ; Memory size ' total _ mem ' , Used _ mem , percentage
of used memory , and units of mem ( KiB , MiB , GiB ) .""" | if memory :
total_mem_kib = meminfo [ "MemTotal:" ]
used_mem_kib = ( total_mem_kib - meminfo [ "MemFree:" ] - ( meminfo [ "Buffers:" ] + meminfo [ "Cached:" ] + ( meminfo [ "SReclaimable:" ] - meminfo [ "Shmem:" ] ) ) )
else :
total_mem_kib = meminfo [ "SwapTotal:" ]
used_mem_kib = total_mem_kib - memin... |
def _resolve_path_load ( self , cdx , is_original , failed_files ) :
"""Load specific record based on filename , offset and length
fields in the cdx .
If original = True , use the orig . * fields for the cdx
Resolve the filename to full path using specified path resolvers
If failed _ files list provided , k... | if is_original :
( filename , offset , length ) = ( cdx [ 'orig.filename' ] , cdx [ 'orig.offset' ] , cdx [ 'orig.length' ] )
else :
( filename , offset , length ) = ( cdx [ 'filename' ] , cdx [ 'offset' ] , cdx . get ( 'length' , '-' ) )
# optimization : if same file already failed this request ,
# don ' t try... |
def __write_record ( self , record_type , data ) :
"""Write single physical record .""" | length = len ( data )
crc = crc32c . crc_update ( crc32c . CRC_INIT , [ record_type ] )
crc = crc32c . crc_update ( crc , data )
crc = crc32c . crc_finalize ( crc )
self . __writer . write ( struct . pack ( _HEADER_FORMAT , _mask_crc ( crc ) , length , record_type ) )
self . __writer . write ( data )
self . __position ... |
def todb ( table , dbo , tablename , schema = None , commit = True , create = False , drop = False , constraints = True , metadata = None , dialect = None , sample = 1000 ) :
"""Load data into an existing database table via a DB - API 2.0
connection or cursor . Note that the database table will be truncated ,
i... | needs_closing = False
# convenience for working with sqlite3
if isinstance ( dbo , string_types ) :
import sqlite3
dbo = sqlite3 . connect ( dbo )
needs_closing = True
try :
if create :
if drop :
drop_table ( dbo , tablename , schema = schema , commit = commit )
create_table ... |
def readmarheader ( filename ) :
"""Read a header from a MarResearch . image file .""" | with open ( filename , 'rb' ) as f :
intheader = np . fromstring ( f . read ( 10 * 4 ) , np . int32 )
floatheader = np . fromstring ( f . read ( 15 * 4 ) , '<f4' )
strheader = f . read ( 24 )
f . read ( 4 )
otherstrings = [ f . read ( 16 ) for i in range ( 29 ) ]
return { 'Xsize' : intheader [ 0 ] ,... |
def projected_inverse ( L ) :
"""Supernodal multifrontal projected inverse . The routine computes the projected inverse
. . math : :
Y = P ( L ^ { - T } L ^ { - 1 } )
where : math : ` L ` is a Cholesky factor . On exit , the argument : math : ` L ` contains the
projected inverse : math : ` Y ` .
: param L... | assert isinstance ( L , cspmatrix ) and L . is_factor is True , "L must be a cspmatrix factor"
n = L . symb . n
snpost = L . symb . snpost
snptr = L . symb . snptr
chptr = L . symb . chptr
chidx = L . symb . chidx
relptr = L . symb . relptr
relidx = L . symb . relidx
blkptr = L . symb . blkptr
blkval = L . blkval
stack... |
def parse_data_line ( self , sline ) :
"""Parses the data line and builds the dictionary .
: param sline : a split data line to parse
: returns : the number of rows to jump and parse the next data line or return the code error - 1""" | # if there are less values founded than headers , it ' s an error
if len ( sline ) != len ( self . _columns ) :
self . err ( "One data line has the wrong number of items" )
return - 1
rawdict = { }
for idx , result in enumerate ( sline ) :
rawdict [ self . _columns [ idx ] ] = result
# Getting resid
resid =... |
def open_hist ( self ) :
"""Open the HIST file located in the in self . outdir .
Returns : class : ` HistFile ` object , None if file could not be found or file is not readable .""" | if not self . hist_path :
if self . status == self . S_OK :
logger . critical ( "%s reached S_OK but didn't produce a HIST file in %s" % ( self , self . outdir ) )
return None
# Open the HIST file
from abipy . dynamics . hist import HistFile
try :
return HistFile ( self . hist_path )
except Exceptio... |
def execute_job ( self , job_request ) :
"""Processes and runs the action requests contained in the job and returns a ` JobResponse ` .
: param job _ request : The job request
: type job _ request : dict
: return : A ` JobResponse ` object
: rtype : JobResponse""" | # Run the Job ' s Actions
job_response = JobResponse ( )
job_switches = RequestSwitchSet ( job_request [ 'context' ] [ 'switches' ] )
for i , raw_action_request in enumerate ( job_request [ 'actions' ] ) :
action_request = EnrichedActionRequest ( action = raw_action_request [ 'action' ] , body = raw_action_request ... |
def get_user_cumulate ( self , begin_date , end_date ) :
"""获取累计用户数据
详情请参考
http : / / mp . weixin . qq . com / wiki / 3 / ecfed6e1a0a03b5f35e5efac98e864b7 . html
: param begin _ date : 起始日期
: param end _ date : 结束日期
: return : 统计数据列表""" | res = self . _post ( 'getusercumulate' , data = { 'begin_date' : self . _to_date_str ( begin_date ) , 'end_date' : self . _to_date_str ( end_date ) } , result_processor = lambda x : x [ 'list' ] )
return res |
def get_area_url ( location , distance ) :
"""Generate URL for downloading OSM data within a region .
This function defines a boundary box where the edges touch a circle of
` ` distance ` ` kilometres in radius . It is important to note that the box is
neither a square , nor bounded within the circle .
The ... | locations = [ location . destination ( i , distance ) for i in range ( 0 , 360 , 90 ) ]
latitudes = list ( map ( attrgetter ( 'latitude' ) , locations ) )
longitudes = list ( map ( attrgetter ( 'longitude' ) , locations ) )
bounds = ( min ( longitudes ) , min ( latitudes ) , max ( longitudes ) , max ( latitudes ) )
ret... |
def plot ( self , axis , ith_plot , total_plots , limits ) :
"""Plot the histogram as a whole over all groups .
Do not plot as individual groups like other plot types .""" | print ( self . plot_type_str . upper ( ) + " plot" )
print ( "%5s %9s %s" % ( "id" , " #points" , "group" ) )
for idx , group in enumerate ( self . groups ) :
print ( "%5s %9s %s" % ( idx + 1 , len ( self . groups [ group ] ) , group ) )
print ( '' )
datasets = [ ]
colors = [ ]
minx = np . inf
maxx = - np . inf
f... |
def download_links ( self , dir_path ) :
"""Download web pages or images from search result links .
Args :
dir _ path ( str ) :
Path of directory to save downloads of : class : ` api . results ` . links""" | links = self . links
if not path . exists ( dir_path ) :
makedirs ( dir_path )
for i , url in enumerate ( links ) :
if 'start' in self . cseargs :
i += int ( self . cseargs [ 'start' ] )
ext = self . cseargs [ 'fileType' ]
ext = '.html' if ext == '' else '.' + ext
file_name = self . cseargs ... |
def event_types ( self ) :
"""Raises
IndexError
When there is no selected rater""" | try :
events = self . rater . find ( 'events' )
except AttributeError :
raise IndexError ( 'You need to have at least one rater' )
return [ x . get ( 'type' ) for x in events ] |
def interpolate_tuple ( startcolor , goalcolor , steps ) :
"""Take two RGB color sets and mix them over a specified number of steps . Return the list""" | # white
R = startcolor [ 0 ]
G = startcolor [ 1 ]
B = startcolor [ 2 ]
targetR = goalcolor [ 0 ]
targetG = goalcolor [ 1 ]
targetB = goalcolor [ 2 ]
DiffR = targetR - R
DiffG = targetG - G
DiffB = targetB - B
buffer = [ ]
for i in range ( 0 , steps + 1 ) :
iR = R + ( DiffR * i // steps )
iG = G + ( DiffG * i //... |
def index_to_time_seg ( time_seg_idx , slide_step ) :
"""将时间片索引值转换为时间片字符串
: param time _ seg _ idx :
: param slide _ step :
: return :""" | assert ( time_seg_idx * slide_step < const . MINUTES_IN_A_DAY )
return time_util . minutes_to_time_str ( time_seg_idx * slide_step ) |
def onBatchCreated ( self , three_pc_batch : ThreePcBatch ) :
"""A batch of requests has been created and has been applied but
committed to ledger and state .
: param ledger _ id :
: param state _ root : state root after the batch creation
: return :""" | ledger_id = three_pc_batch . ledger_id
if ledger_id == POOL_LEDGER_ID :
if isinstance ( self . poolManager , TxnPoolManager ) :
self . get_req_handler ( POOL_LEDGER_ID ) . onBatchCreated ( three_pc_batch . state_root , three_pc_batch . pp_time )
elif self . get_req_handler ( ledger_id ) :
self . get_req... |
def frame_iv ( algorithm , sequence_number ) :
"""Builds the deterministic IV for a body frame .
: param algorithm : Algorithm for which to build IV
: type algorithm : aws _ encryption _ sdk . identifiers . Algorithm
: param int sequence _ number : Frame sequence number
: returns : Generated IV
: rtype : ... | if sequence_number < 1 or sequence_number > MAX_FRAME_COUNT :
raise ActionNotAllowedError ( "Invalid frame sequence number: {actual}\nMust be between 1 and {max}" . format ( actual = sequence_number , max = MAX_FRAME_COUNT ) )
prefix_len = algorithm . iv_len - 4
prefix = b"\x00" * prefix_len
return prefix + struct ... |
def create_or_update_cluster ( config_file , override_min_workers , override_max_workers , no_restart , restart_only , yes , override_cluster_name ) :
"""Create or updates an autoscaling Ray cluster from a config json .""" | config = yaml . load ( open ( config_file ) . read ( ) )
if override_min_workers is not None :
config [ "min_workers" ] = override_min_workers
if override_max_workers is not None :
config [ "max_workers" ] = override_max_workers
if override_cluster_name is not None :
config [ "cluster_name" ] = override_clu... |
def write_fix_accuracy ( self , accuracy = None ) :
"""Write the GPS fix accuracy header : :
writer . write _ fix _ accuracy ( )
# - > HFFXA500
writer . write _ fix _ accuracy ( 25)
# - > HFFXA025
: param accuracy : the estimated GPS fix accuracy in meters ( optional )""" | if accuracy is None :
accuracy = 500
accuracy = int ( accuracy )
if not 0 < accuracy < 1000 :
raise ValueError ( 'Invalid fix accuracy' )
self . write_fr_header ( 'FXA' , '%03d' % accuracy ) |
def construct_pipeline_block_lambda ( env = '' , generated = None , previous_env = None , region = 'us-east-1' , region_subnets = None , settings = None , pipeline_data = None ) :
"""Create the Pipeline JSON from template .
This handles the common repeatable patterns in a pipeline , such as
judgement , infrastr... | LOG . info ( '%s block for [%s].' , env , region )
if env . startswith ( 'prod' ) :
template_name = 'pipeline/pipeline_{}_lambda.json.j2' . format ( env )
else :
template_name = 'pipeline/pipeline_stages_lambda.json.j2'
LOG . debug ( '%s info:\n%s' , env , pformat ( settings ) )
gen_app_name = generated . app_n... |
def _model_unpickle ( cls , data ) :
"""Unpickle a model by retrieving it from the database .""" | auto_field_value = data [ 'pk' ]
try :
obj = cls . objects . get ( pk = auto_field_value )
except Exception as e :
if isinstance ( e , OperationalError ) : # Attempt reconnect , we ' ve probably hit ;
# OperationalError ( 2006 , ' MySQL server has gone away ' )
logger . debug ( "Caught OperationalEr... |
def info_file ( self ) :
"""Grab sources from . info file and store filename""" | sources = SBoGrep ( self . prgnam ) . source ( ) . split ( )
for source in sources :
self . sbo_sources . append ( source . split ( "/" ) [ - 1 ] ) |
def route ( self ) :
'''The relative : class : ` . Route ` served by this
: class : ` Router ` .''' | parent = self . _parent
if parent and parent . _route . is_leaf :
return parent . route + self . _route
else :
return self . _route |
def wrap_paginated ( self , data , renderer_context ) :
"""Convert paginated data to JSON API with meta""" | pagination_keys = [ 'count' , 'next' , 'previous' , 'results' ]
for key in pagination_keys :
if not ( data and key in data ) :
raise WrapperNotApplicable ( 'Not paginated results' )
view = renderer_context . get ( "view" , None )
model = self . model_from_obj ( view )
resource_type = self . model_to_resourc... |
def get_logged_user ( self , ** kwargs ) :
"""Gets logged user and in case not existing creates a new one
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the response .
> > > def callback _ fu... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . get_logged_user_with_http_info ( ** kwargs )
else :
( data ) = self . get_logged_user_with_http_info ( ** kwargs )
return data |
def as_dict ( self ) :
"""turns attribute filter object into python dictionary""" | output_dictionary = dict ( )
for attribute_name , type_instance in inspect . getmembers ( self ) :
if attribute_name . startswith ( '__' ) or inspect . ismethod ( type_instance ) :
continue
if isinstance ( type_instance , bool ) :
output_dictionary [ attribute_name ] = type_instance
elif isi... |
def authorize_url ( self , scope = '' , ** kwargs ) :
"""Returns the url to redirect the user to for user consent""" | self . _check_configuration ( "site" , "authorization_url" , "redirect_uri" , "client_id" )
if isinstance ( scope , ( list , tuple , set , frozenset ) ) :
self . _check_configuration ( "scope_sep" )
scope = self . scope_sep . join ( scope )
oauth_params = { 'redirect_uri' : self . redirect_uri , 'client_id' : s... |
def _data2rec ( schema , rec_data ) :
'''schema = OrderedDict ( {
' prio ' : int ,
' weight ' : int ,
' port ' : to _ port ,
' name ' : str ,
rec _ data = ' 10 20 25 myawesome . nl '
res = { ' prio ' : 10 , ' weight ' : 20 , ' port ' : 25 ' name ' : ' myawesome . nl ' }''' | try :
rec_fields = rec_data . split ( ' ' )
# spaces in digest fields are allowed
assert len ( rec_fields ) >= len ( schema )
if len ( rec_fields ) > len ( schema ) :
cutoff = len ( schema ) - 1
rec_fields = rec_fields [ 0 : cutoff ] + [ '' . join ( rec_fields [ cutoff : ] ) ]
if len... |
def find_element_by_class ( self , class_ , update = False ) -> Elements :
'''Finds an element by class .
Args :
class _ : The class of the element to be found .
update : If the interface has changed , this option should be True .
Returns :
The element if it was found .
Raises :
NoSuchElementException... | return self . find_element ( by = By . CLASS , value = class_ , update = update ) |
def questions ( self ) :
"""获取收藏夹内所有问题对象 .
: return : 收藏夹内所有问题 , 返回生成器
: rtype : Question . Iterable""" | self . _make_soup ( )
# noinspection PyTypeChecker
for question in self . _page_get_questions ( self . soup ) :
yield question
i = 2
while True :
soup = BeautifulSoup ( self . _session . get ( self . url [ : - 1 ] + '?page=' + str ( i ) ) . text )
for question in self . _page_get_questions ( soup ) :
... |
def _find_calls ( self , ast_tree , called_module , called_func ) :
'''scan the abstract source tree looking for possible ways to call the called _ module
and called _ func
since - - 7-2-12 - - Jay
example - -
# import the module a couple ways :
import pout
from pout import v
from pout import v as voo... | s = set ( )
# always add the default call , the set will make sure there are no dupes . . .
s . add ( "{}.{}" . format ( called_module , called_func ) )
if hasattr ( ast_tree , 'name' ) :
if ast_tree . name == called_func : # the function is defined in this module
s . add ( called_func )
if hasattr ( ast_tr... |
def create_full_tear_sheet ( factor_data , long_short = True , group_neutral = False , by_group = False ) :
"""Creates a full tear sheet for analysis and evaluating single
return predicting ( alpha ) factor .
Parameters
factor _ data : pd . DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date ( lev... | plotting . plot_quantile_statistics_table ( factor_data )
create_returns_tear_sheet ( factor_data , long_short , group_neutral , by_group , set_context = False )
create_information_tear_sheet ( factor_data , group_neutral , by_group , set_context = False )
create_turnover_tear_sheet ( factor_data , set_context = False ... |
def delete_project ( self ) :
"""Delete the current project without deleting the files in the directory .""" | if self . current_active_project :
self . switch_to_plugin ( )
path = self . current_active_project . root_path
buttons = QMessageBox . Yes | QMessageBox . No
answer = QMessageBox . warning ( self , _ ( "Delete" ) , _ ( "Do you really want to delete <b>{filename}</b>?<br><br>" "<b>Note:</b> This action ... |
def _configure_iam_role ( config ) :
"""Setup a gcp service account with IAM roles .
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage / compute services . Specifically , the head node needs to have
an IAM role that allows it to create further gce instances and store ... | email = SERVICE_ACCOUNT_EMAIL_TEMPLATE . format ( account_id = DEFAULT_SERVICE_ACCOUNT_ID , project_id = config [ "provider" ] [ "project_id" ] )
service_account = _get_service_account ( email , config )
if service_account is None :
logger . info ( "_configure_iam_role: " "Creating new service account {}" . format ... |
def _htdigest ( username , password , ** kwargs ) :
'''Provide authentication via Apache - style htdigest files''' | realm = kwargs . get ( 'realm' , None )
if not realm :
log . error ( 'salt.auth.file: A ^realm must be defined in ' 'external_auth:file for htdigest filetype' )
return False
from passlib . apache import HtdigestFile
pwfile = HtdigestFile ( kwargs [ 'filename' ] )
# passlib below version 1.6 uses ' verify ' func... |
def gps_inject_data_send ( self , target_system , target_component , len , data , force_mavlink1 = False ) :
'''data for injecting into the onboard GPS ( used for DGPS )
target _ system : System ID ( uint8 _ t )
target _ component : Component ID ( uint8 _ t )
len : data length ( uint8 _ t )
data : raw data ... | return self . send ( self . gps_inject_data_encode ( target_system , target_component , len , data ) , force_mavlink1 = force_mavlink1 ) |
def LOS_CrossProj ( VType , Ds , us , kPIns , kPOuts , kRMins , Lplot = 'In' , proj = 'All' , multi = False ) :
"""Compute the parameters to plot the poloidal projection of the LOS""" | assert type ( VType ) is str and VType . lower ( ) in [ 'tor' , 'lin' ]
assert Lplot . lower ( ) in [ 'tot' , 'in' ]
assert type ( proj ) is str
proj = proj . lower ( )
assert proj in [ 'cross' , 'hor' , 'all' , '3d' ]
assert Ds . ndim == 2 and Ds . shape == us . shape
nL = Ds . shape [ 1 ]
k0 = kPIns if Lplot . lower ... |
def should_execute ( self , workload ) :
"""If we have been suspended by i3bar , only execute those modules that set the keep _ alive flag to a truthy
value . See the docs on the suspend _ signal _ handler method of the io module for more information .""" | if not self . _suspended . is_set ( ) :
return True
workload = unwrap_workload ( workload )
return hasattr ( workload , 'keep_alive' ) and getattr ( workload , 'keep_alive' ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.