signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def read ( self , filename , binary = False ) :
"""Returns contents of given file with AppDir .
If file doesn ' t exist , returns None .""" | self . _raise_if_none ( )
fn = path_join ( self . path , filename )
if binary :
flags = 'br'
else :
flags = 'r'
try :
with open ( fn , flags ) as f :
return f . read ( )
except IOError :
return None |
def transform ( self , X = None , y = None ) :
"""Transform an image using an Affine transform with
zoom parameters randomly generated from the user - specified
range . Return the transform if X = None .
Arguments
X : ANTsImage
Image to transform
y : ANTsImage ( optional )
Another image to transform
... | # random draw in zoom range
zoom_x = np . exp ( random . gauss ( np . log ( self . zoom_range [ 0 ] ) , np . log ( self . zoom_range [ 1 ] ) ) )
zoom_y = np . exp ( random . gauss ( np . log ( self . zoom_range [ 0 ] ) , np . log ( self . zoom_range [ 1 ] ) ) )
zoom_z = np . exp ( random . gauss ( np . log ( self . zoo... |
def render_head_repr ( expr : Any , sub_render = None , key_sub_render = None ) -> str :
"""Render a textual representation of ` expr ` using
Positional and keyword arguments are recursively
rendered using ` sub _ render ` , which defaults to ` render _ head _ repr ` by
default . If desired , a different rend... | head_repr_fmt = r'{head}({args}{kwargs})'
if sub_render is None :
sub_render = render_head_repr
if key_sub_render is None :
key_sub_render = sub_render
if isinstance ( expr . __class__ , Singleton ) : # We exploit that Singletons override _ _ expr _ _ to directly return
# their name
return repr ( expr )
if ... |
def __create_matcher ( self , match_class , ** keywds ) :
"""implementation details""" | matcher_args = keywds . copy ( )
del matcher_args [ 'function' ]
del matcher_args [ 'recursive' ]
if 'allow_empty' in matcher_args :
del matcher_args [ 'allow_empty' ]
decl_matcher = decl_matcher = match_class ( ** matcher_args )
if keywds [ 'function' ] :
self . _logger . debug ( 'running query: %s and <user d... |
def update_views ( self ) :
"""Update stats views .""" | # Call the father ' s method
super ( Plugin , self ) . update_views ( )
# Add specifics informations
# Alert and log
for key in [ 'user' , 'system' , 'iowait' ] :
if key in self . stats :
self . views [ key ] [ 'decoration' ] = self . get_alert_log ( self . stats [ key ] , header = key )
# Alert only
for ke... |
def edit ( self , id ) :
"""Edit a pool .""" | c . pool = Pool . get ( int ( id ) )
c . prefix_list = Prefix . list ( { 'pool_id' : c . pool . id } )
c . prefix = ''
# save changes to NIPAP
if request . method == 'POST' :
c . pool . name = request . params [ 'name' ]
c . pool . description = request . params [ 'description' ]
c . pool . default_type = r... |
def pingback_extensions_get_pingbacks ( target ) :
"""pingback . extensions . getPingbacks ( url ) = > ' [ url , url , . . . ] '
Returns an array of URLs that link to the specified url .
See : http : / / www . aquarionics . com / misc / archives / blogite / 0198 . html""" | site = Site . objects . get_current ( )
target_splitted = urlsplit ( target )
if target_splitted . netloc != site . domain :
return TARGET_DOES_NOT_EXIST
try :
view , args , kwargs = resolve ( target_splitted . path )
except Resolver404 :
return TARGET_DOES_NOT_EXIST
try :
entry = Entry . published . ge... |
def listBlockSummaries ( self , block_name = "" , dataset = "" , detail = False ) :
"""API that returns summary information like total size and total number of events in a dataset or a list of blocks
: param block _ name : list block summaries for block _ name ( s )
: type block _ name : str , list
: param da... | if bool ( dataset ) + bool ( block_name ) != 1 :
dbsExceptionHandler ( "dbsException-invalid-input2" , dbsExceptionCode [ "dbsException-invalid-input2" ] , self . logger . exception , "Dataset or block_names must be specified at a time." )
if block_name and isinstance ( block_name , basestring ) :
try :
... |
def joinRes ( lstPrfRes , varPar , idxPos , inFormat = '1D' ) :
"""Join results from different processing units ( here cores ) .
Parameters
lstPrfRes : list
Output of results from parallelization .
varPar : integer , positive
Number of cores that were used during parallelization
idxPos : integer , posit... | if inFormat == '1D' : # initialize output array
aryOut = np . zeros ( ( 0 , ) )
# gather arrays from different processing units
for idxRes in range ( 0 , varPar ) :
aryOut = np . append ( aryOut , lstPrfRes [ idxRes ] [ idxPos ] )
elif inFormat == '2D' : # initialize output array
aryOut = np . z... |
def wait ( self , timeout = None ) :
"""Waits until the result is available or until timeout
seconds pass .""" | self . _event . wait ( timeout )
return self . _event . isSet ( ) |
def apply ( cls , fs ) :
"""replace bound methods of fs .""" | logger . debug ( 'Patching %s with %s.' , fs . __class__ . __name__ , cls . __name__ )
fs . _patch = cls
for method_name in cls . patch_methods : # if fs hasn ' t method , raise AttributeError .
origin = getattr ( fs , method_name )
method = getattr ( cls , method_name )
bound_method = method . __get__ ( fs... |
def folderitem ( self , obj , item , index ) :
"""Applies new properties to the item ( analysis ) that is currently
being rendered as a row in the list .
: param obj : analysis to be rendered as a row in the list
: param item : dict representation of the analysis , suitable for the list
: param index : curr... | item = super ( AnalysesView , self ) . folderitem ( obj , item , index )
item_obj = api . get_object ( obj )
uid = item [ "uid" ]
# Slot is the row position where all analyses sharing the same parent
# ( eg . AnalysisRequest , SampleReference ) , will be displayed as a group
slot = self . get_item_slot ( uid )
item [ "... |
def handle_response ( response ) :
"""Handle a response from the newton API""" | response = json . loads ( response . read ( ) )
# Was the expression valid ?
if 'error' in response :
raise ValueError ( response [ 'error' ] )
else : # Some of the strings returned can be parsed to integers or floats
try :
return json . loads ( response [ 'result' ] )
except ( TypeError , json . de... |
def download_file ( url , destination , ** kwargs ) :
"""Download file process :
- Open the url
- Check if it has been downloaded and it hanged .
- Download it to the destination folder .
Args :
: urls : url to take the file .
: destionation : place to store the downloaded file .""" | web_file = open_remote_url ( url , ** kwargs )
file_size = 0
if not web_file :
logger . error ( "Remote file not found. Attempted URLs: {}" . format ( url ) )
return
modified = is_remote_file_modified ( web_file , destination )
if modified :
logger . info ( "Downloading: " + web_file . url )
file_size =... |
def rmon_event_entry_event_index ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
rmon = ET . SubElement ( config , "rmon" , xmlns = "urn:brocade.com:mgmt:brocade-rmon" )
event_entry = ET . SubElement ( rmon , "event-entry" )
event_index = ET . SubElement ( event_entry , "event-index" )
event_index . text = kwargs . pop ( 'event_index' )
callback = kwargs . pop ( '... |
def summarize ( self , test_arr , vectorizable_token , sentence_list , limit = 5 ) :
'''Summarize input document .
Args :
test _ arr : ` np . ndarray ` of observed data points . .
vectorizable _ token : is - a ` VectorizableToken ` .
sentence _ list : ` list ` of all sentences .
limit : The number of sele... | if isinstance ( vectorizable_token , VectorizableToken ) is False :
raise TypeError ( )
_ = self . inference ( test_arr )
_ , loss_arr , _ = self . compute_retrospective_loss ( )
loss_list = loss_arr . tolist ( )
abstract_list = [ ]
for i in range ( limit ) :
key = loss_arr . argmin ( )
_ = loss_list . pop ... |
def get_extended_summary ( self , s , base = None ) :
"""Get the extended summary from a docstring
This here is the extended summary
Parameters
s : str
The docstring to use
base : str or None
A key under which the summary shall be stored in the : attr : ` params `
attribute . If not None , the summary... | # Remove the summary and dedent
s = self . _remove_summary ( s )
ret = ''
if not self . _all_sections_patt . match ( s ) :
m = self . _extended_summary_patt . match ( s )
if m is not None :
ret = m . group ( ) . strip ( )
if base is not None :
self . params [ base + '.summary_ext' ] = ret
return ret |
def server_info ( self , session = None ) :
"""Get information about the MongoDB server we ' re connected to .
: Parameters :
- ` session ` ( optional ) : a
: class : ` ~ pymongo . client _ session . ClientSession ` .
. . versionchanged : : 3.6
Added ` ` session ` ` parameter .""" | return self . admin . command ( "buildinfo" , read_preference = ReadPreference . PRIMARY , session = session ) |
def area ( self ) :
r"""The area of the current surface .
For surfaces in : math : ` \ mathbf { R } ^ 2 ` , this computes the area via
Green ' s theorem . Using the vector field : math : ` \ mathbf { F } =
\ left [ - y , x \ right ] ^ T ` , since : math : ` \ partial _ x ( x ) - \ partial _ y ( - y ) = 2 `
... | if self . _dimension != 2 :
raise NotImplementedError ( "2D is the only supported dimension" , "Current dimension" , self . _dimension , )
edge1 , edge2 , edge3 = self . _get_edges ( )
return _surface_helpers . compute_area ( ( edge1 . _nodes , edge2 . _nodes , edge3 . _nodes ) ) |
def _hash_scalar ( val , encoding = 'utf8' , hash_key = None ) :
"""Hash scalar value
Returns
1d uint64 numpy array of hash value , of length 1""" | if isna ( val ) : # this is to be consistent with the _ hash _ categorical implementation
return np . array ( [ np . iinfo ( np . uint64 ) . max ] , dtype = 'u8' )
if getattr ( val , 'tzinfo' , None ) is not None : # for tz - aware datetimes , we need the underlying naive UTC value and
# not the tz aware object or ... |
def calculate_decagonal_number ( n ) :
"""This function calculates the nth decagonal number .
Examples :
calculate _ decagonal _ number ( 3 ) - > 27
calculate _ decagonal _ number ( 7 ) - > 175
calculate _ decagonal _ number ( 10 ) - > 370
: param n : The position of decagonal number that needs to be calc... | return 4 * n ** 2 - 3 * n |
def to_geopandas ( raster , ** kwargs ) :
"""Convert GeoRaster to GeoPandas DataFrame , which can be easily exported to other types of files
and used to do other types of operations .
The DataFrame has the geometry ( Polygon ) , row , col , value , x , and y values for each cell
Usage :
df = gr . to _ geopa... | df = to_pandas ( raster , ** kwargs )
df [ 'geometry' ] = df . apply ( squares , georaster = raster , axis = 1 )
df = gp . GeoDataFrame ( df , crs = from_string ( raster . projection . ExportToProj4 ( ) ) )
return df |
def _annotation_dict_any_filter ( edge_data : EdgeData , query : Mapping [ str , Iterable [ str ] ] ) -> bool :
"""Match edges with the given dictionary as a sub - dictionary .
: param query : The annotation query dict to match""" | annotations = edge_data . get ( ANNOTATIONS )
if annotations is None :
return False
return any ( key in annotations and value in annotations [ key ] for key , values in query . items ( ) for value in values ) |
def egg ( qualifier : Union [ str , Type ] = '' , profile : str = None ) :
"""A function that returns a decorator ( or acts like a decorator )
that marks class or function as a source of ` base ` .
If a class is decorated , it should inherit after from ` base ` type .
If a function is decorated , it declared ... | first_arg = qualifier
def egg_dec ( obj : Union [ FunctionType , type ] ) -> T :
if isinstance ( obj , FunctionType ) :
spec = inspect . signature ( obj )
return_annotation = spec . return_annotation
if return_annotation is Signature . empty :
raise ConfigurationError ( 'No retur... |
def table ( self , name ) :
"""Return a table expression referencing a table in this database
Returns
table : TableExpr""" | qualified_name = self . _qualify ( name )
return self . client . table ( qualified_name , self . name ) |
def find_filter ( self , filter_cls ) :
"""Find or create a filter instance of the provided ` ` filter _ cls ` ` . If it
is found , use remaining arguments to augment the filter otherwise
create a new instance of the desired type and add it to the
current : class : ` ~ es _ fluent . builder . QueryBuilder ` a... | for filter_instance in self . filters :
if isinstance ( filter_instance , filter_cls ) :
return filter_instance
return None |
def torque_off ( self ) :
"""Set the torques of Herkulex to zero
In this mode , position control and velocity control
will not work , enable torque before that . Also the
servo shaft is freely movable
Args :
none""" | data = [ ]
data . append ( 0x0A )
data . append ( self . servoid )
data . append ( RAM_WRITE_REQ )
data . append ( TORQUE_CONTROL_RAM )
data . append ( 0x01 )
data . append ( 0x00 )
send_data ( data ) |
def from_name ( cls , name , * , queue = DefaultJobQueueName . Workflow , clear_data_store = True , arguments = None ) :
"""Create a workflow object from a workflow script .
Args :
name ( str ) : The name of the workflow script .
queue ( str ) : Name of the queue the workflow should be scheduled to .
clear ... | new_workflow = cls ( queue = queue , clear_data_store = clear_data_store )
new_workflow . load ( name , arguments = arguments )
return new_workflow |
def configure_error_handlers ( graph ) :
"""Register error handlers .""" | # override all of the werkzeug HTTPExceptions
for code in default_exceptions . keys ( ) :
graph . flask . register_error_handler ( code , make_json_error )
# register catch all for user exceptions
graph . flask . register_error_handler ( Exception , make_json_error ) |
def maintenance_view ( template = None ) :
"""Create the Maintenance view
Must be instantiated
import maintenance _ view
MaintenanceView = maintenance _ view ( )
: param view _ template : The directory containing the view pages
: return :""" | if not template :
template = "Pylot/Maintenance/index.html"
class Maintenance ( Pylot ) :
@ classmethod
def register ( cls , app , ** kwargs ) :
super ( cls , cls ) . register ( app , ** kwargs )
if cls . config_ ( "MAINTENANCE_ON" ) :
@ app . before_request
def on_ma... |
def initialize__ ( cls ) :
"""Mocha specific
To setup some models data after
: return :""" | [ cls . new ( level = r [ 0 ] , name = r [ 1 ] ) for r in cls . ROLES ] |
def refresh_db ( ** kwargs ) :
'''Update the portage tree using the first available method from the following
list :
- emaint sync
- eix - sync
- emerge - webrsync
- emerge - - sync
To prevent the portage tree from being synced within one day of the
previous sync , add the following pillar data for th... | has_emaint = os . path . isdir ( '/etc/portage/repos.conf' )
has_eix = True if 'eix.sync' in __salt__ else False
has_webrsync = True if __salt__ [ 'makeconf.features_contains' ] ( 'webrsync-gpg' ) else False
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt . utils . pkg . clear_rtag ( __o... |
def cmd_link_add ( self , args ) :
'''add new link''' | device = args [ 0 ]
print ( "Adding link %s" % device )
self . link_add ( device ) |
def declare_label ( self , label , lineno , value = None , local = False , namespace = None ) :
"""Sets a label with the given value or with the current address ( org )
if no value is passed .
Exits with error if label already set ,
otherwise return the label object""" | ex_label , namespace = Memory . id_name ( label , namespace )
is_address = value is None
if value is None :
value = self . org
if ex_label in self . local_labels [ - 1 ] . keys ( ) :
self . local_labels [ - 1 ] [ ex_label ] . define ( value , lineno )
self . local_labels [ - 1 ] [ ex_label ] . is_address = ... |
def init_registry ( mongo , model_defs , clear_collection = False ) :
"""Initialize a model registry with a list of model definitions in Json
format .
Parameters
mongo : scodata . MongoDBFactory
Connector for MongoDB
model _ defs : list ( )
List of model definitions in Json - like format
clear _ colle... | # Create model registry
registry = SCOEngine ( mongo ) . registry
# Drop collection if clear flag is set to True
if clear_collection :
registry . clear_collection ( )
for i in range ( len ( model_defs ) ) :
model = registry . from_dict ( model_defs [ i ] )
registry . register_model ( model . identifier , mo... |
def certify_parameter ( certifier , name , value , kwargs = None ) :
"""Internal certifier for kwargs passed to Certifiable public methods .
: param callable certifier :
The certifier to use
: param str name :
The name of the kwargs
: param object value :
The value of the kwarg .
: param bool required... | try :
certifier ( value , ** kwargs or { } )
except CertifierError as err :
six . raise_from ( CertifierParamError ( name , value , ) , err ) |
def find_importer_frame ( ) :
"""Returns the outer frame importing this " end " module .
If this module is being imported by other means than import statement ,
None is returned .
Returns :
A frame object or None .""" | byte = lambda ch : ord ( ch ) if PY2 else ch
frame = inspect . currentframe ( )
try :
while frame :
code = frame . f_code
lasti = frame . f_lasti
if byte ( code . co_code [ lasti ] ) == dis . opmap [ 'IMPORT_NAME' ] : # FIXME : Support EXTENDED _ ARG .
arg = ( byte ( code . co_co... |
def find_matlab_version ( process_path ) :
"""Tries to guess matlab ' s version according to its process path .
If we couldn ' t gues the version , None is returned .""" | bin_path = os . path . dirname ( process_path )
matlab_path = os . path . dirname ( bin_path )
matlab_dir_name = os . path . basename ( matlab_path )
version = matlab_dir_name
if not is_linux ( ) :
version = matlab_dir_name . replace ( 'MATLAB_' , '' ) . replace ( '.app' , '' )
if not is_valid_release_version ( ver... |
def logout ( self ) :
"""View function to log a user out . Supports html and json requests .""" | if current_user . is_authenticated :
self . security_service . logout_user ( )
if request . is_json :
return '' , HTTPStatus . NO_CONTENT
self . flash ( _ ( 'flask_unchained.bundles.security:flash.logout' ) , category = 'success' )
return self . redirect ( 'SECURITY_POST_LOGOUT_REDIRECT_ENDPOINT' ) |
def add_lb_secgroup ( self , lb_name , hosts , port ) :
"""Used by the load balancer deployer to register a hostname
for a load balancer , in order that security group rules can be
applied later . This is multiprocess - safe , but since keys are
accessed only be a single load balancer deployer there should be... | self . lb_sec_groups . merge ( lb_name , { 'hosts' : hosts , 'port' : port } ) |
def get_select_title_url ( self , attach = None ) :
"""获取商户专属开票链接
商户调用接口 , 获取链接 。 用户扫码 , 可以选择抬头发给商户 。 可以将链接转成二维码 , 立在收银台 。
详情请参考
https : / / mp . weixin . qq . com / wiki ? id = mp1496554912 _ vfWU0
: param attach : 附加字段 , 用户提交发票时会发送给商户
: return : 商户专属开票链接""" | return self . _post ( 'biz/getselecttitleurl' , data = { 'attach' : attach , } , result_processor = lambda x : x [ 'url' ] , ) |
def reset_globals ( version = None , loop = None ) :
"""Reinitialize the global singletons with a given API version .
: param version : 1 or 2 . If ` None ` , pulled from the ` useProtocolApiV2 `
advanced setting .""" | global containers
global instruments
global labware
global robot
global reset
global modules
global hardware
robot , reset , instruments , containers , labware , modules , hardware = build_globals ( version , loop ) |
def import_module_from_file ( filename , only_if_newer_than = None ) :
"""Imports ( cython generated ) shared object file ( . so )
Provide a list of paths in ` only _ if _ newer _ than ` to check
timestamps of dependencies . import _ raises an ImportError
if any is newer .
Word of warning : Python ' s cachi... | import imp
path , name = os . path . split ( filename )
name , ext = os . path . splitext ( name )
name = name . split ( '.' ) [ 0 ]
fobj , filename , data = imp . find_module ( name , [ path ] )
if only_if_newer_than :
for dep in only_if_newer_than :
if os . path . getmtime ( filename ) < os . path . getmt... |
def _parse_geometry ( self , geom ) :
"""Parse a geometry string and return Molecule object from
it .""" | atoms = [ ]
for i , line in enumerate ( geom . splitlines ( ) ) :
sym , atno , x , y , z = line . split ( )
atoms . append ( Atom ( sym , [ float ( x ) , float ( y ) , float ( z ) ] , id = i ) )
return Molecule ( atoms ) |
def get_candlesticks ( self , pair , start_time , end_time , interval ) :
"""Function to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange .
Execution of this function is as follows : :
get _ candlesticks ( pair = " SWTH _ NEO " ,
start _ time = round ( time . time ( )... | api_params = { "pair" : pair , "interval" : interval , "start_time" : start_time , "end_time" : end_time , "contract_hash" : self . contract_hash }
return self . request . get ( path = '/tickers/candlesticks' , params = api_params ) |
def mapping_args ( parser ) :
"""Add various variable mapping command line options to the parser""" | parser . add_argument ( '--add-prefix' , dest = 'add_prefix' , help = 'Specify a prefix to use when ' 'generating secret key names' )
parser . add_argument ( '--add-suffix' , dest = 'add_suffix' , help = 'Specify a suffix to use when ' 'generating secret key names' )
parser . add_argument ( '--merge-path' , dest = 'mer... |
def transplant ( new_net , net , suffix = '' ) :
"""Transfer weights by copying matching parameters , coercing parameters of
incompatible shape , and dropping unmatched parameters .
The coercion is useful to convert fully connected layers to their
equivalent convolutional layers , since the weights are the sa... | for p in net . params :
p_new = p + suffix
if p_new not in new_net . params :
print 'dropping' , p
continue
for i in range ( len ( net . params [ p ] ) ) :
if i > ( len ( new_net . params [ p_new ] ) - 1 ) :
print 'dropping' , p , i
break
if net . para... |
def mapper ( self , meta_data , instance ) :
"""Pull out the meta data plate value and put it into the instance value
: param meta _ data : the original meta data
: param instance : the original instance
: return : the modified instance""" | d = dict ( meta_data )
v = d . pop ( self . aggregation_meta_data )
instance = deepcopy ( instance )
instance . value [ self . aggregation_meta_data ] = v
return instance |
def auth_basic ( check , realm = "private" , text = "Access denied" ) :
'''Callback decorator to require HTTP auth ( basic ) .
TODO : Add route ( check _ auth = . . . ) parameter .''' | def decorator ( func ) :
def wrapper ( * a , ** ka ) :
user , password = request . auth or ( None , None )
if user is None or not check ( user , password ) :
response . headers [ 'WWW-Authenticate' ] = 'Basic realm="%s"' % realm
return HTTPError ( 401 , text )
return ... |
def codemirror_parameters ( field ) :
"""Filter to include CodeMirror parameters as a JSON string for a single
field .
This must be called only on an allready rendered field , meaning you must
not use this filter on a field before a form . Else , the field widget won ' t
be correctly initialized .
Example... | manifesto = CodemirrorAssetTagRender ( )
names = manifesto . register_from_fields ( field )
config = manifesto . get_codemirror_parameters ( names [ 0 ] )
return mark_safe ( json . dumps ( config ) ) |
def main ( arguments = None ) :
"""* The main function used when ` ` cl _ utils . py ` ` is run as a single script from the cl , or when installed as a cl command *""" | # setup the command - line util settings
dev_flag = False
su = tools ( arguments = arguments , docString = __doc__ , logLevel = "DEBUG" , options_first = False , projectName = "rockAtlas" )
arguments , settings , log , dbConn = su . setup ( )
# unpack remaining cl arguments using ` exec ` to setup the variable names
# ... |
def list ( self ) :
"""Return a list of Accounts from Toshl for the current user""" | response = self . client . _make_request ( '/accounts' )
response = response . json ( )
return self . client . _list_response ( response ) |
def rand_resize_crop ( size : int , max_scale : float = 2. , ratios : Tuple [ float , float ] = ( 0.75 , 1.33 ) ) :
"Randomly resize and crop the image to a ratio in ` ratios ` after a zoom of ` max _ scale ` ." | return [ zoom_squish ( scale = ( 1. , max_scale , 8 ) , squish = ( * ratios , 8 ) , invert = ( 0.5 , 8 ) , row_pct = ( 0. , 1. ) , col_pct = ( 0. , 1. ) ) , crop ( size = size ) ] |
def build ( self , obj , context = None ) -> bytes :
"""Build bytes from the python object .
: param obj : Python object to build bytes from .
: param context : Optional context dictionary .""" | stream = BytesIO ( )
self . build_stream ( obj , stream , context )
return stream . getvalue ( ) |
def initialize_ui ( self ) :
"""Initializes the Component ui .
: return : Method success .
: rtype : bool""" | LOGGER . debug ( "> Initializing '{0}' Component ui." . format ( self . __class__ . __name__ ) )
self . __Port_spinBox_set_ui ( )
self . __Autostart_TCP_Server_checkBox_set_ui ( )
# Signals / Slots .
self . Port_spinBox . valueChanged . connect ( self . __Port_spinBox__valueChanged )
self . Autostart_TCP_Server_checkBo... |
def delete_file ( self , project_name , remote_path ) :
"""Delete a file or folder from a project
: param project _ name : str : name of the project containing a file we will delete
: param remote _ path : str : remote path specifying file to delete""" | project = self . _get_or_create_project ( project_name )
remote_file = project . get_child_for_path ( remote_path )
remote_file . delete ( ) |
def copyNode ( self , node , extended ) :
"""Do a copy of the node to a given document .""" | if node is None :
node__o = None
else :
node__o = node . _o
ret = libxml2mod . xmlDocCopyNode ( node__o , self . _o , extended )
if ret is None :
raise treeError ( 'xmlDocCopyNode() failed' )
__tmp = xmlNode ( _obj = ret )
return __tmp |
def audit_1_15 ( self ) :
"""1.15 Ensure IAM policies are attached only to groups or roles ( Scored )""" | for policy in resources . iam . policies . all ( ) :
self . assertEqual ( len ( list ( policy . attached_users . all ( ) ) ) , 0 , "{} has users attached to it" . format ( policy ) ) |
def as_spectrum ( self , binned = True , wavelengths = None ) :
"""Reduce the observation to an empirical source spectrum .
An observation is a complex object with some restrictions
on its capabilities . At times , it would be useful to work
with the observation as a simple object that is easier to
manipula... | if binned :
w , y = self . _get_binned_arrays ( wavelengths , self . _internal_flux_unit )
else :
w , y = self . _get_arrays ( wavelengths , flux_unit = self . _internal_flux_unit )
header = { 'observation' : str ( self ) , 'binned' : binned }
return SourceSpectrum ( Empirical1D , points = w , lookup_table = y ... |
def add_datasets ( self , datasets , datasets_to_check = None ) : # type : ( List [ Union [ hdx . data . dataset . Dataset , Dict , str ] ] , List [ hdx . data . dataset . Dataset ] ) - > bool
"""Add multiple datasets
Args :
datasets ( List [ Union [ Dataset , Dict , str ] ] ) : A list of either dataset ids or ... | if datasets_to_check is None :
datasets_to_check = self . get_datasets ( )
alldatasetsadded = True
for dataset in datasets :
if not self . add_dataset ( dataset , datasets_to_check = datasets_to_check ) :
alldatasetsadded = False
return alldatasetsadded |
def svg ( svg_dom : str , filename : str = None ) :
"""Adds the specified SVG string to the display . If a filename is
included , the SVG data will also be saved to that filename within the
project results folder .
: param svg _ dom :
The SVG string data to add to the display .
: param filename :
An opt... | r = _get_report ( )
r . append_body ( render . svg ( svg_dom ) )
r . stdout_interceptor . write_source ( '[ADDED] SVG\n' )
if not filename :
return
if not filename . endswith ( '.svg' ) :
filename += '.svg'
r . files [ filename ] = svg_dom |
def srv_name ( svc , proto = 'tcp' , domain = None ) :
'''Generate SRV record name
: param svc : ldap , 389 etc
: param proto : tcp , udp , sctp etc .
: param domain : name to append
: return :''' | proto = RFC . validate ( proto , RFC . SRV_PROTO )
if isinstance ( svc , int ) or svc . isdigit ( ) :
svc = _to_port ( svc )
if domain :
domain = '.' + domain
return '_{0}._{1}{2}' . format ( svc , proto , domain ) |
def stop ( self , terminate = False ) :
"""Stops the TCP server .
: return : Method success .
: rtype : bool""" | if not self . __online :
raise foundations . exceptions . ServerOperationError ( "{0} | '{1}' TCP Server is not online!" . format ( self . __class__ . __name__ , self ) )
if not terminate :
self . __server . shutdown ( )
else :
self . __server . _BaseServer__shutdown_request = True
self . __server = None
se... |
def get ( self , key , default = None ) :
'''Note : we override default impl from parent to avoid costly KeyError''' | valu = self . data . get ( key , default )
if key in self . data :
self . data . move_to_end ( key )
return valu |
def column ( self , column , option = None , ** kw ) :
"""Query or modify the options for the specified column .
If ` kw ` is not given , returns a dict of the column option values . If
` option ` is specified then the value for that option is returned .
Otherwise , sets the options to the corresponding value... | config = False
if option == 'type' :
return self . _column_types [ column ]
elif 'type' in kw :
config = True
self . _column_types [ column ] = kw . pop ( 'type' )
if kw :
self . _visual_drag . column ( ttk . Treeview . column ( self , column , 'id' ) , option , ** kw )
if kw or option :
return ttk ... |
def add_visual ( self , visual ) :
"""Add a visual to the canvas , and build its program by the same
occasion .
We can ' t build the visual ' s program before , because we need the canvas '
transforms first .""" | # Retrieve the visual ' s GLSL inserter .
inserter = visual . inserter
# Add the visual ' s transforms .
inserter . add_transform_chain ( visual . transforms )
# Then , add the canvas ' transforms .
canvas_transforms = visual . canvas_transforms_filter ( self . transforms )
inserter . add_transform_chain ( canvas_trans... |
def ChildField ( cls , default = NOTHING , required = True , repr = True , cmp = True , key = None ) :
"""Create new child field on a model .
: param cls : class ( or name ) of the model to be related .
: param default : any object value of type cls
: param bool required : whether or not the object is invalid... | default = _init_fields . init_default ( required , default , None )
converter = converters . to_child_field ( cls )
validator = _init_fields . init_validator ( required , object if isinstance ( cls , str ) else cls )
return attrib ( default = default , converter = converter , validator = validator , repr = repr , cmp =... |
def padding ( self , padding = True ) :
"""Sets padding mode of the cipher""" | padding_flag = 1 if padding else 0
libcrypto . EVP_CIPHER_CTX_set_padding ( self . ctx , padding_flag ) |
def v_theta ( self ) :
"""Return the ` ` ( v , theta ) ` ` equivalent of the ( normalized ) quaternion .
Returns
v : float
theta : float""" | # compute theta
norm = np . sqrt ( np . sum ( self . wxyz ** 2 ) )
theta = 2 * np . arccos ( self . wxyz [ 0 ] / norm )
# compute the unit vector
v = np . array ( self . wxyz [ 1 : ] )
v = v / np . sqrt ( np . sum ( v ** 2 ) )
return v , theta |
def toggle_wrap_mode ( self , checked ) :
"""Toggle wrap mode""" | self . shell . toggle_wrap_mode ( checked )
self . set_option ( 'wrap' , checked ) |
def add_callback ( self , event , cb , args = None ) :
'''Add a callback to this node .
Callbacks are called when the specified event occurs . The available
events depends on the specific node type . Args should be a value to
pass to the callback when it is called . The callback should be of the
format :
... | if event not in self . _cbs :
raise exceptions . NoSuchEventError
self . _cbs [ event ] = [ ( cb , args ) ] |
def getGameHighScores ( self , user_id , game_message_identifier ) :
"""See : https : / / core . telegram . org / bots / api # getgamehighscores
: param game _ message _ identifier : Same as ` ` msg _ identifier ` ` in : meth : ` telepot . Bot . editMessageText `""" | p = _strip ( locals ( ) , more = [ 'game_message_identifier' ] )
p . update ( _dismantle_message_identifier ( game_message_identifier ) )
return self . _api_request ( 'getGameHighScores' , _rectify ( p ) ) |
def handle_table ( self , table_dict ) :
"""Loads the table data based on a given table _ dict and handles them .
For the given dict containing a ` ` DataTable ` ` and a ` ` TableTab ` `
instance , it loads the table data for that tab and calls the
table ' s : meth : ` ~ horizon . tables . DataTable . maybe _... | table = table_dict [ 'table' ]
tab = table_dict [ 'tab' ]
tab . load_table_data ( )
table_name = table . _meta . name
tab . _tables [ table_name ] . _meta . has_prev_data = self . has_prev_data ( table )
tab . _tables [ table_name ] . _meta . has_more_data = self . has_more_data ( table )
handled = tab . _tables [ tabl... |
def compute_probability_settle ( trajectory_files , bbox = None , nx = 1000 , ny = 1000 , method = 'overall' ) :
"""This function creates a probability ( stochastic ) grid
for trajectory model data based on settlement location ,
normalized by run .
probability _ grid = compute _ probability _ settle ( [ myfil... | prob = compute_probability ( trajectory_files , bbox , nx , ny , method , parameter = 'settlement' , )
return prob |
def copy_object ( self , container , obj , new_container , new_obj_name = None , content_type = None , extra_info = None ) :
"""Copies the object to the new container , optionally giving it a new name .
If you copy to the same container , you must supply a different name .
You can optionally change the content ... | return self . _manager . copy_object ( container , obj , new_container , new_obj_name = new_obj_name , content_type = content_type ) |
def display_molecule ( mol , autozoom = True ) :
'''Display a ` ~ chemlab . core . Molecule ` instance in the viewer .
This function wraps the molecule in a system before displaying
it .''' | s = System ( [ mol ] )
display_system ( s , autozoom = True ) |
def jsonify_payload ( self ) :
"""Dump the payload to JSON""" | # Assume already json serialized
if isinstance ( self . payload , string_types ) :
return self . payload
return json . dumps ( self . payload , cls = StandardJSONEncoder ) |
def lookup ( cls , backend , obj ) :
"""Given an object , lookup the corresponding customized option
tree if a single custom tree is applicable .""" | ids = set ( [ el for el in obj . traverse ( lambda x : x . id ) if el is not None ] )
if len ( ids ) == 0 :
raise Exception ( "Object does not own a custom options tree" )
elif len ( ids ) != 1 :
idlist = "," . join ( [ str ( el ) for el in sorted ( ids ) ] )
raise Exception ( "Object contains elements comb... |
def read_json ( path_or_buf = None , orient = None , typ = 'frame' , dtype = True , convert_axes = True , convert_dates = True , keep_default_dates = True , numpy = False , precise_float = False , date_unit = None , encoding = None , lines = False ) :
"""Convert a JSON string to pandas object
Parameters
path _ ... | filepath_or_buffer , _ , _ = get_filepath_or_buffer ( path_or_buf , encoding = encoding )
if isinstance ( filepath_or_buffer , compat . string_types ) :
try :
exists = os . path . exists ( filepath_or_buffer )
# if the filepath is too long will raise here
# 5874
except ( TypeError , ValueError )... |
def findFirst ( self , tableClass , comparison = None , offset = None , sort = None , default = None ) :
"""Usage : :
s . findFirst ( tableClass [ , query arguments except ' limit ' ] )
Example : :
class YourItemType ( Item ) :
a = integer ( )
b = text ( )
c = integer ( )
it = s . findFirst ( YourItem... | limit = 1
for item in self . query ( tableClass , comparison , limit , offset , sort ) :
return item
return default |
def stop ( self ) :
'''Shutdown kafka consumer .''' | log . info ( 'Stopping te kafka listener class' )
self . consumer . unsubscribe ( )
self . consumer . close ( ) |
def guess_content_kind ( path = None , web_video_data = None , questions = None ) :
"""guess _ content _ kind : determines what kind the content is
Args :
files ( str or list ) : files associated with content
Returns : string indicating node ' s kind""" | # If there are any questions , return exercise
if questions and len ( questions ) > 0 :
return content_kinds . EXERCISE
# See if any files match a content kind
if path :
ext = os . path . splitext ( path ) [ 1 ] [ 1 : ] . lower ( )
if ext in content_kinds . MAPPING :
return content_kinds . MAPPING [... |
def setOrientation ( self , orientation ) :
"""Sets the orientation for this handle and updates the widgets linked with it .
: param orientation | < Qt . Orientation >""" | super ( XSplitterHandle , self ) . setOrientation ( orientation )
if ( orientation == Qt . Vertical ) :
self . layout ( ) . setDirection ( QBoxLayout . LeftToRight )
# update the widgets
self . _collapseBefore . setFixedSize ( 30 , 10 )
self . _collapseAfter . setFixedSize ( 30 , 10 )
self . _resize... |
def motion_commanded ( self ) :
"""Whether motion is commanded or not .
` ` bool ` `
Can ' t be set .
Notes
It is the value of the first bit of the ' TAS ' command .""" | rsp = self . driver . send_command ( 'TAS' , immediate = True )
if self . driver . command_error ( rsp ) or len ( rsp [ 4 ] ) != 1 or rsp [ 4 ] [ 0 ] [ 0 : 4 ] != '*TAS' :
return False
else :
return ( rsp [ 4 ] [ 0 ] [ 4 ] == '1' ) |
def feature_scp_generator ( path ) :
"""Return a generator over all feature matrices defined in a scp .""" | scp_entries = textfile . read_key_value_lines ( path , separator = ' ' )
for utterance_id , rx_specifier in scp_entries . items ( ) :
yield utterance_id , KaldiWriter . read_float_matrix ( rx_specifier ) |
def _get_raw_value ( self , setting_name , accept_deprecated = '' , warn_if_overridden = False , suppress_warnings = False , warning_stacklevel = 3 ) :
"""Returns the original / raw value for an app setting with the name
` ` setting _ name ` ` , exactly as it has been defined in the defaults
module or a user ' ... | if not self . in_defaults ( setting_name ) :
self . _raise_invalid_setting_name_error ( setting_name )
if self . is_overridden ( setting_name ) :
if ( warn_if_overridden and not suppress_warnings and setting_name in self . _deprecated_settings ) :
depr = self . _deprecated_settings [ setting_name ]
... |
def drop_extension ( name , if_exists = None , restrict = None , cascade = None , user = None , host = None , port = None , maintenance_db = None , password = None , runas = None ) :
'''Drop an installed postgresql extension
CLI Example :
. . code - block : : bash
salt ' * ' postgres . drop _ extension ' admi... | if cascade is None :
cascade = True
if if_exists is None :
if_exists = False
if restrict is None :
restrict = False
args = [ 'DROP EXTENSION' ]
if if_exists :
args . append ( 'IF EXISTS' )
args . append ( name )
if cascade :
args . append ( 'CASCADE' )
if restrict :
args . append ( 'RESTRICT' )
... |
def generateLayers ( self , scene , nodes , connections ) :
"""Breaks the nodes into layers by grouping the nodes together based on
their connection scheme .
: param nodes | [ < XNode > , . . ]""" | depth = { }
for node in nodes :
depth [ node ] = ( self . calculateDepth ( node , connections ) , len ( connections [ node ] [ 0 ] ) )
ordered = depth . keys ( )
ordered . sort ( key = lambda x : depth [ x ] )
layers = { }
processed = [ ]
for node in ordered :
self . collectLayer ( node , connections , layers ,... |
def delete ( self , ids ) :
"""Method to delete neighbors by their id ' s
: param ids : Identifiers of neighbors
: return : None""" | url = build_uri_with_ids ( 'api/v4/neighbor/%s/' , ids )
return super ( ApiV4Neighbor , self ) . delete ( url ) |
def huffman_decode ( cls , i , ibl ) : # type : ( int , int ) - > str
"""huffman _ decode decodes the bitstring provided as parameters .
@ param int i : the bitstring to decode
@ param int ibl : the bitlength of i
@ return str : the string decoded from the bitstring
@ raise AssertionError , InvalidEncodingE... | assert ( i >= 0 )
assert ( ibl >= 0 )
if isinstance ( cls . static_huffman_tree , type ( None ) ) :
cls . huffman_compute_decode_tree ( )
assert ( not isinstance ( cls . static_huffman_tree , type ( None ) ) )
s = [ ]
j = 0
interrupted = False
cur = cls . static_huffman_tree
cur_sym = 0
cur_sym_bl = 0
while j < ibl... |
def mssql_transaction_count ( engine_or_conn : Union [ Connection , Engine ] ) -> int :
"""For Microsoft SQL Server specifically : fetch the value of the ` ` TRANCOUNT ` `
variable ( see e . g .
https : / / docs . microsoft . com / en - us / sql / t - sql / functions / trancount - transact - sql ? view = sql - ... | sql = "SELECT @@TRANCOUNT"
with contextlib . closing ( engine_or_conn . execute ( sql ) ) as result : # type : ResultProxy # noqa
row = result . fetchone ( )
return row [ 0 ] if row else None |
def is_valid_isbn ( isbn ) :
"""Validate given ` isbn ` . Wrapper for : func : ` is _ isbn10 _ valid ` /
: func : ` is _ isbn13 _ valid ` .
Args :
isbn ( str / list ) : ISBN number as string or list of digits .
Note :
Function doesn ' t require ` isbn ` type to be specified ( it can be both
10/13 isbn '... | length = len ( isbn )
if length == 10 :
return is_isbn10_valid ( isbn )
elif length == 13 :
return is_isbn13_valid ( isbn )
return False |
def create_station ( name , latlonalt , parent_frame = WGS84 , orientation = 'N' , mask = None ) :
"""Create a ground station instance
Args :
name ( str ) : Name of the station
latlonalt ( tuple of float ) : coordinates of the station , as follow :
* Latitude in degrees
* Longitude in degrees
* Altitude... | if isinstance ( orientation , str ) :
orient = { 'N' : np . pi , 'S' : 0. , 'E' : np . pi / 2. , 'W' : 3 * np . pi / 2. }
heading = orient [ orientation ]
else :
heading = orientation
latlonalt = list ( latlonalt )
latlonalt [ : 2 ] = np . radians ( latlonalt [ : 2 ] )
coordinates = TopocentricFrame . _geod... |
def gueymard94_pw ( temp_air , relative_humidity ) :
r"""Calculates precipitable water ( cm ) from ambient air temperature ( C )
and relatively humidity ( % ) using an empirical model . The
accuracy of this method is approximately 20 % for moderate PW ( 1-3
cm ) and less accurate otherwise .
The model was d... | T = temp_air + 273.15
# Convert to Kelvin # noqa : N806
RH = relative_humidity
# noqa : N806
theta = T / 273.15
# Eq . 1 from Keogh and Blakers
pw = ( 0.1 * ( 0.4976 + 1.5265 * theta + np . exp ( 13.6897 * theta - 14.9188 * ( theta ) ** 3 ) ) * ( 216.7 * RH / ( 100 * T ) * np . exp ( 22.330 - 49.140 * ( 100 / T ) - 10.... |
def getAllowedTransitions ( instance ) :
"""Returns a list with the transition ids that can be performed against
the instance passed in .
: param instance : A content object
: type instance : ATContentType
: returns : A list of transition / action ids
: rtype : list""" | wftool = getToolByName ( instance , "portal_workflow" )
transitions = wftool . getTransitionsFor ( instance )
return [ trans [ 'id' ] for trans in transitions ] |
def _extract_annotations_from_task ( self , task ) :
"""Removes annotations from a task and returns a list of annotations""" | annotations = list ( )
if 'annotations' in task :
existing_annotations = task . pop ( 'annotations' )
for v in existing_annotations :
if isinstance ( v , dict ) :
annotations . append ( v [ 'description' ] )
else :
annotations . append ( v )
for key in list ( task . keys ... |
def set_amount_cb ( self , widget , val ) :
"""This method is called when ' Zoom Amount ' control is adjusted .""" | self . zoom_amount = val
zoomlevel = self . fitsimage_focus . get_zoom ( )
self . _zoomset ( self . fitsimage_focus , zoomlevel ) |
def trocar_codigo_de_ativacao ( retorno ) :
"""Constrói uma : class : ` RespostaSAT ` para o retorno ( unicode ) da função
: meth : ` ~ satcfe . base . FuncoesSAT . trocar _ codigo _ de _ ativacao ` .""" | resposta = analisar_retorno ( forcar_unicode ( retorno ) , funcao = 'TrocarCodigoDeAtivacao' )
if resposta . EEEEE not in ( '18000' , ) :
raise ExcecaoRespostaSAT ( resposta )
return resposta |
def _apply_index_days ( self , i , roll ) :
"""Add days portion of offset to DatetimeIndex i .
Parameters
i : DatetimeIndex
roll : ndarray [ int64 _ t ]
Returns
result : DatetimeIndex""" | nanos = ( roll % 2 ) * Timedelta ( days = self . day_of_month - 1 ) . value
return i + nanos . astype ( 'timedelta64[ns]' ) |
def save ( self ) :
"""Convert to JSON .
Returns
` dict `
JSON data .""" | data = super ( ) . save ( )
data [ 'resize' ] = list ( self . resize ) if self . resize is not None else None
data [ 'traversal' ] = [ t . save ( ) for t in self . traversal ]
data [ 'levels' ] = self . levels
data [ 'level_scale' ] = self . level_scale
data [ 'scale' ] = self . scale
return data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.