signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def replay_sgf ( sgf_contents ) : """Wrapper for sgf files , returning go . PositionWithContext instances . It does NOT return the very final position , as there is no follow up . To get the final position , call pwc . position . play _ move ( pwc . next _ move ) on the last PositionWithContext returned . E...
root_node = get_sgf_root_node ( sgf_contents ) props = root_node . properties assert int ( sgf_prop ( props . get ( 'GM' , [ '1' ] ) ) ) == 1 , "Not a Go SGF!" komi = 0 if props . get ( 'KM' ) is not None : komi = float ( sgf_prop ( props . get ( 'KM' ) ) ) result = utils . parse_game_result ( sgf_prop ( props . ge...
def _get_paths ( self ) : """Return a list of paths to search for plugins in The list is searched in order ."""
ret = [ ] ret += [ '%s/library/' % os . path . dirname ( os . path . dirname ( __file__ ) ) ] ret += self . _extra_dirs for basedir in _basedirs : fullpath = os . path . join ( basedir , self . subdir ) if fullpath not in ret : ret . append ( fullpath ) ret += self . config . split ( os . pathsep ) ret ...
def on_mouse_drag ( x , y , dx , dy , buttons , modifiers ) : """ε½“ιΌ ζ ‡ζŒ‰δΈ‹εΉΆδΈ”η§»εŠ¨ηš„ζ—Άε€™θ§¦ε‘"""
mouse . x , mouse . y = x , y mouse . move ( )
def do_NOTIFY ( self ) : # pylint : disable = invalid - name """Serve a ` ` NOTIFY ` ` request . A ` ` NOTIFY ` ` request will be sent by a Sonos device when a state variable changes . See the ` UPnP Spec Β§ 4.3 [ pdf ] < http : / / upnp . org / specs / arch / UPnP - arch - DeviceArchitecture - v1.1 . pdf > ...
timestamp = time . time ( ) headers = requests . structures . CaseInsensitiveDict ( self . headers ) seq = headers [ 'seq' ] # Event sequence number sid = headers [ 'sid' ] # Event Subscription Identifier content_length = int ( headers [ 'content-length' ] ) content = self . rfile . read ( content_length ) # Find the r...
def show ( self , resolve_mac = True ) : """Print list of available network interfaces in human readable form"""
print ( "%s %s %s %s" % ( "INDEX" . ljust ( 5 ) , "IFACE" . ljust ( 35 ) , "IP" . ljust ( 15 ) , "MAC" ) ) for iface_name in sorted ( self . data . keys ( ) ) : dev = self . data [ iface_name ] mac = dev . mac if resolve_mac and iface_name != LOOPBACK_NAME : mac = conf . manufdb . _resolve_MAC ( ...
def _compiler_plugins_cp_entries ( self ) : """Any additional global compiletime classpath entries for compiler plugins ."""
java_options_src = Java . global_instance ( ) scala_options_src = ScalaPlatform . global_instance ( ) def cp ( instance , toolname ) : scope = instance . options_scope return instance . tool_classpath_from_products ( self . _products , toolname , scope = scope ) classpaths = ( cp ( java_options_src , 'javac-plu...
def load ( self , cnf , metadata_construction = False ) : """The base load method , loads the configuration : param cnf : The configuration as a dictionary : param metadata _ construction : Is this only to be able to construct metadata . If so some things can be left out . : return : The Configuration insta...
_uc = self . unicode_convert for arg in COMMON_ARGS : if arg == "virtual_organization" : if "virtual_organization" in cnf : for key , val in cnf [ "virtual_organization" ] . items ( ) : self . vorg [ key ] = VirtualOrg ( None , key , val ) continue elif arg == "extens...
def get_content ( self , key ) : """Gets given content from the cache . Usage : : > > > cache = Cache ( ) > > > cache . add _ content ( John = " Doe " , Luke = " Skywalker " ) True > > > cache . get _ content ( " Luke " ) ' Skywalker ' : param key : Content to retrieve . : type key : object : retu...
LOGGER . debug ( "> Retrieving '{0}' content from the cache." . format ( self . __class__ . __name__ , key ) ) return self . get ( key )
def plot_report ( report , success_name , fail_names , label = None , is_max_confidence = True , linewidth = LINEWIDTH , plot_upper_bound = True ) : """Plot a success fail curve from a confidence report : param report : A confidence report ( the type of object saved by make _ confidence _ report . py ) : para...
( fail_optimal , success_optimal , fail_lower_bound , fail_upper_bound , success_bounded ) = make_curve ( report , success_name , fail_names ) assert len ( fail_lower_bound ) == len ( fail_upper_bound ) fail_optimal = np . array ( fail_optimal ) fail_lower_bound = np . array ( fail_lower_bound ) fail_upper_bound = np ....
def _generate_sync_documents ( self ) : """* generate sync documents * * * Key Arguments : * * * * Return : * * - None * * Usage : * * . . todo : : - add usage info - create a sublime snippet for usage - update package tutorial if needed . . code - block : : python usage code"""
self . log . info ( 'starting the ``_generate_sync_documents`` method' ) for tag in self . syncTags : pathToWriteFile = self . syncFolder + "/" + tag + ".taskpaper" try : self . log . debug ( "attempting to open the file %s" % ( pathToWriteFile , ) ) writeFile = codecs . open ( pathToWriteFile ,...
def describe_splits ( self , cfName , start_token , end_token , keys_per_split ) : """experimental API for hadoop / parallel query support . may change violently and without warning . returns list of token strings such that first subrange is ( list [ 0 ] , list [ 1 ] ] , next is ( list [ 1 ] , list [ 2 ] ] , ...
self . _seqid += 1 d = self . _reqs [ self . _seqid ] = defer . Deferred ( ) self . send_describe_splits ( cfName , start_token , end_token , keys_per_split ) return d
def render ( self , element ) : """Renders the given element to string . : param element : a element to be rendered . : returns : the output string or any values ."""
# Store the root node to provide some context to render functions if not self . root_node : self . root_node = element render_func = getattr ( self , self . _cls_to_func_name ( element . __class__ ) , None ) if not render_func : render_func = self . render_children return render_func ( element )
def import_model ( model_file ) : """Imports the ONNX model file , passed as a parameter , into MXNet symbol and parameters . Operator support and coverage - https : / / cwiki . apache . org / confluence / display / MXNET / MXNet - ONNX + Integration Parameters model _ file : str ONNX model file name Re...
graph = GraphProto ( ) try : import onnx except ImportError : raise ImportError ( "Onnx and protobuf need to be installed. " + "Instructions to install - https://github.com/onnx/onnx" ) # loads model file and returns ONNX protobuf object model_proto = onnx . load_model ( model_file ) sym , arg_params , aux_para...
def create_assessment_offered ( self , assessment_offered_form ) : """Creates a new ` ` AssessmentOffered ` ` . arg : assessment _ offered _ form ( osid . assessment . AssessmentOfferedForm ) : the form for this ` ` AssessmentOffered ` ` return : ( osid . assessment . AssessmentOffered ) - the new ` ` Ass...
# Implemented from template for # osid . resource . ResourceAdminSession . create _ resource _ template collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentOffered' , runtime = self . _runtime ) if not isinstance ( assessment_offered_form , ABCAssessmentOfferedForm ) : raise errors . InvalidAr...
def yieldefer ( function ) : """Replacement for : func : ` defer . inlineCallbacks ` that supports cancellation ."""
defer . inlineCallbacks return lambda * args , ** kwargs : _yielddefer ( function , * args , ** kwargs )
def _remove_string_from_commastring ( self , field , string ) : # type : ( str , str ) - > bool """Remove a string from a comma separated list of strings Args : field ( str ) : Field containing comma separated list string ( str ) : String to remove Returns : bool : True if string removed or False if not""...
commastring = self . data . get ( field , '' ) if string in commastring : self . data [ field ] = commastring . replace ( string , '' ) return True return False
def TrTp ( self , pot = None , ** kwargs ) : """NAME : TrTp PURPOSE : the ' ratio ' between the radial and azimuthal period Tr / Tphi * pi INPUT : pot - potential type = ( ' staeckel ' ) type of actionAngle module to use 1 ) ' adiabatic ' 2 ) ' staeckel ' 3 ) ' isochroneApprox ' 4 ) ' spherical ...
if not pot is None : pot = flatten_potential ( pot ) _check_consistent_units ( self , pot ) self . _orb . _setupaA ( pot = pot , ** kwargs ) if self . _orb . _aAType . lower ( ) == 'isochroneapprox' : return float ( self . _orb . _aA . actionsFreqs ( self ( ) ) [ 4 ] [ 0 ] / self . _orb . _aA . actionsFreqs ( s...
def prj_create_atype ( self , * args , ** kwargs ) : """Create a new project : returns : None : rtype : None : raises : None"""
if not self . cur_prj : return atype = self . create_atype ( projects = [ self . cur_prj ] ) if atype : atypedata = djitemdata . AtypeItemData ( atype ) treemodel . TreeItem ( atypedata , self . prj_atype_model . root )
def run_on ( * , event : str ) : """A decorator to store and link a callback to an event ."""
def decorator ( callback ) : @ functools . wraps ( callback ) def decorator_wrapper ( ) : RTMClient . on ( event = event , callback = callback ) return decorator_wrapper ( ) return decorator
def _update_preview ( self ) : """Update color preview ."""
color = self . hexa . get ( ) if self . alpha_channel : prev = overlay ( self . _transparent_bg , hexa_to_rgb ( color ) ) self . _im_color = ImageTk . PhotoImage ( prev , master = self ) self . color_preview . configure ( image = self . _im_color ) else : self . color_preview . configure ( background = ...
def _from_dataframe ( dataframe , default_type = 'STRING' ) : """Infer a BigQuery table schema from a Pandas dataframe . Note that if you don ' t explicitly set the types of the columns in the dataframe , they may be of a type that forces coercion to STRING , so even though the fields in the dataframe themselve...
type_mapping = { 'i' : 'INTEGER' , 'b' : 'BOOLEAN' , 'f' : 'FLOAT' , 'O' : 'STRING' , 'S' : 'STRING' , 'U' : 'STRING' , 'M' : 'TIMESTAMP' } fields = [ ] for column_name , dtype in dataframe . dtypes . iteritems ( ) : fields . append ( { 'name' : column_name , 'type' : type_mapping . get ( dtype . kind , default_typ...
def _format_axes ( self ) : """Try to format axes if they are datelike ."""
if not self . obj . index . is_unique and self . orient in ( 'index' , 'columns' ) : raise ValueError ( "DataFrame index must be unique for orient=" "'{orient}'." . format ( orient = self . orient ) ) if not self . obj . columns . is_unique and self . orient in ( 'index' , 'columns' , 'records' ) : raise ValueE...
def list_dependency_artifacts ( id , page_size = 200 , page_index = 0 , sort = "" , q = "" ) : """List dependency artifacts associated with a BuildRecord"""
data = list_dependency_artifacts_raw ( id , page_size , page_index , sort , q ) if data : return utils . format_json_list ( data )
def _CanSkipDataStream ( self , file_entry , data_stream ) : """Determines if analysis and extraction of a data stream can be skipped . This is used to prevent Plaso trying to run analyzers or extract content from a pipe or socket it encounters while processing a mounted filesystem . Args : file _ entry ( d...
if file_entry . IsFile ( ) : return False if data_stream . IsDefault ( ) : return True return False
def set_outline ( self , color ) : """Uses an outline rectangle . : param color : Color of the outline rect : type color : QtGui . QColor"""
self . format . setProperty ( QtGui . QTextFormat . OutlinePen , QtGui . QPen ( color ) )
def _set_mac_learn_disable ( self , v , load = False ) : """Setter method for mac _ learn _ disable , mapped from YANG variable / interface / port _ channel / mac _ learning / mac _ learn _ disable ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ mac _ lear...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = mac_learn_disable . mac_learn_disable , is_container = 'container' , presence = False , yang_name = "mac-learn-disable" , rest_name = "disable" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmet...
def _create_imshow_objects ( self ) : """Turns off all the x and y axes in each Axis"""
# uniform values for initial image can cause weird behaviour with normalization # as imshow . set _ data ( ) does not automatically update the normalization ! ! # using random data is a better choice random_image = np . random . rand ( 20 , 20 ) self . images = [ None ] * len ( self . flat_grid ) for ix , ax in enumera...
def decrypt_yubikey_otp ( self , from_key ) : """Try to decrypt a YubiKey OTP . Returns a string starting with either ' OK ' or ' ERR ' : ' OK counter = ab12 low = dd34 high = 2a use = 0a ' ' ERR Unknown public _ id ' on YubiHSM errors ( or bad OTP ) , only ' ERR ' is returned ."""
if not re . match ( valid_input_from_key , from_key ) : self . log_error ( "IN: %s, Invalid OTP" % ( from_key ) ) if self . stats_url : stats [ 'invalid' ] += 1 return "ERR Invalid OTP" public_id , _otp = pyhsm . yubikey . split_id_otp ( from_key ) try : aead = self . aead_backend . load_aead ( ...
def _nav_to_tree ( root ) : """Given an etree containing a navigation document structure rooted from the ' nav ' element , parse to a tree : { ' id ' : < id > | ' subcol ' , ' title ' : < title > , ' contents ' : [ < tree > , . . . ] }"""
def expath ( e , x ) : return e . xpath ( x , namespaces = HTML_DOCUMENT_NAMESPACES ) for li in expath ( root , 'xhtml:ol/xhtml:li' ) : is_subtree = bool ( [ e for e in li . getchildren ( ) if e . tag [ e . tag . find ( '}' ) + 1 : ] == 'ol' ] ) if is_subtree : # It ' s a sub - tree and have a ' span ' and ...
def handle_api_static_request ( self , request , start_response ) : """Handler for requests to { base _ path } / static / . * . This calls start _ response and returns the response body . Args : request : An ApiRequest , the request from the user . start _ response : A function with semantics defined in PEP...
if request . path == PROXY_PATH : return util . send_wsgi_response ( '200 OK' , [ ( 'Content-Type' , 'text/html' ) ] , PROXY_HTML , start_response ) else : _logger . debug ( 'Unknown static url requested: %s' , request . relative_url ) return util . send_wsgi_response ( '404 Not Found' , [ ( 'Content-Type' ...
def SXTH ( self , params ) : """STXH Ra , Rb Sign extend the half word in Rb and store the result in Ra"""
Ra , Rb = self . get_two_parameters ( r'\s*([^\s,]*),\s*([^\s,]*)(,\s*[^\s,]*)*\s*' , params ) self . check_arguments ( low_registers = ( Ra , Rb ) ) def SXTH_func ( ) : if self . register [ Rb ] & ( 1 << 15 ) : self . register [ Ra ] = 0xFFFF0000 + ( self . register [ Rb ] & 0xFFFF ) else : sel...
def import_block ( block : BaseBlock , chain : BaseChain ) -> BaseChain : """Import the provided ` ` block ` ` into the chain ."""
chain . import_block ( block ) return chain
def find_peaks_indexes ( arr , window_width = 5 , threshold = 0.0 , fpeak = 0 ) : """Find indexes of peaks in a 1d array . Note that window _ width must be an odd number . The function imposes that the fluxes in the window _ width / 2 points to the left ( and right ) of the peak decrease monotonously as one m...
_check_window_width ( window_width ) if ( fpeak < 0 or fpeak + 1 >= window_width ) : raise ValueError ( 'fpeak must be in the range 0- window_width - 2' ) kernel_peak = kernel_peak_function ( threshold , fpeak ) out = generic_filter ( arr , kernel_peak , window_width , mode = "reflect" ) result , = numpy . nonzero ...
def visualRectRC ( self , row , column ) : """The rectangle for the bounds of the item at * row * , * column * : param row : row of the item : type row : int : param column : column of the item : type column : int : returns : : qtdoc : ` QRect ` - - rectangle of the borders of the item"""
rect = self . _rects [ row ] [ column ] if rect . isValid ( ) : return QtCore . QRect ( rect . x ( ) - self . horizontalScrollBar ( ) . value ( ) , rect . y ( ) - self . verticalScrollBar ( ) . value ( ) , rect . width ( ) , rect . height ( ) ) else : return rect
def append ( self , parent , content ) : """Append the specified L { content } to the I { parent } . @ param parent : The parent node to append to . @ type parent : L { Element } @ param content : The content to append . @ type content : L { Object }"""
log . debug ( 'appending parent:\n%s\ncontent:\n%s' , parent , content ) if self . start ( content ) : self . appender . append ( parent , content ) self . end ( parent , content )
async def _sync_revoc ( self , rr_id : str ) -> None : """Pick up tails file reader handle for input revocation registry identifier . If no symbolic link is present , get the revocation registry definition to retrieve its tails file hash , then find the tails file and link it . Raise AbsentTails for missing c...
LOGGER . debug ( 'HolderProver._sync_revoc >>> rr_id: %s' , rr_id ) ( cd_id , tag ) = rev_reg_id2cred_def_id__tag ( rr_id ) try : json . loads ( await self . get_cred_def ( cd_id ) ) except AbsentCredDef : LOGGER . debug ( 'HolderProver._sync_revoc: <!< corrupt tails tree %s may be for another ledger' , self . ...
async def permits ( self , identity , permission , context = None ) : """Check user permissions . Return True if the identity is allowed the permission in the current context , else return False ."""
# pylint : disable = unused - argument user = self . user_map . get ( identity ) if not user : return False return permission in user . permissions
def select_row ( self , steps ) : """Select row in list widget based on a number of steps with direction . Steps can be positive ( next rows ) or negative ( previous rows ) ."""
row = self . current_row ( ) + steps if 0 <= row < self . count ( ) : self . set_current_row ( row )
def getSensoryAssociatedLocationRepresentation ( self ) : """Get the location cells in the location layer that were driven by the input layer ( or , during learning , were associated with this input . )"""
cells = np . array ( [ ] , dtype = "uint32" ) totalPrevCells = 0 for module in self . L6aModules : cells = np . append ( cells , module . sensoryAssociatedCells + totalPrevCells ) totalPrevCells += module . numberOfCells ( ) return cells
def collapse_subtree ( self , name , recursive = True ) : # noqa : D302 r"""Collapse a sub - tree . Nodes that have a single child and no data are combined with their child as a single tree node : param name : Root of the sub - tree to collapse : type name : : ref : ` NodeName ` : param recursive : Flag t...
if self . _validate_node_name ( name ) : raise RuntimeError ( "Argument `name` is not valid" ) if not isinstance ( recursive , bool ) : raise RuntimeError ( "Argument `recursive` is not valid" ) self . _node_in_tree ( name ) self . _collapse_subtree ( name , recursive )
def get_model ( model , ctx , opt ) : """Model initialization ."""
kwargs = { 'ctx' : ctx , 'pretrained' : opt . use_pretrained , 'classes' : classes } if model . startswith ( 'resnet' ) : kwargs [ 'thumbnail' ] = opt . use_thumbnail elif model . startswith ( 'vgg' ) : kwargs [ 'batch_norm' ] = opt . batch_norm net = models . get_model ( model , ** kwargs ) if opt . resume : ...
def plot_moist_adiabats ( self , p = None , thetaes = None , ** kwargs ) : r'''Plot moist adiabats . Adds saturated pseudo - adiabats ( lines of constant equivalent potential temperature ) to the plot . The default style of these lines is dashed blue lines with an alpha value of 0.5 . These can be overridden ...
for artist in self . _moist_adiabats : artist . remove ( ) self . _moist_adiabats = [ ] def dT_dp ( y , p0 ) : return calculate ( 'Gammam' , T = y , p = p0 , RH = 100. , p_units = 'hPa' , T_units = 'degC' ) / ( g0 * calculate ( 'rho' , T = y , p = p0 , p_units = 'hPa' , T_units = 'degC' , RH = 100. ) ) * 100. i...
def temporary_assignment ( obj , attr , value ) : """Temporarily assign obj . attr to value ."""
original = getattr ( obj , attr , None ) setattr ( obj , attr , value ) yield setattr ( obj , attr , original )
def __we_c ( cls , calib , tc , temp , we_v ) : """Compute weC from sensor temperature compensation of weV"""
offset_v = calib . pid_elc_mv / 1000.0 response_v = we_v - offset_v # remove electronic zero response_c = tc . correct ( temp , response_v ) # correct the response component if response_c is None : return None we_c = response_c + offset_v # replace electronic zero return we_c
def _is_definition_section ( source ) : """Determine if the source is a definition section . Args : source : The usage string source that may be a section . Returns : True if the source describes a definition section ; otherwise , False ."""
try : definitions = textwrap . dedent ( source ) . split ( '\n' , 1 ) [ 1 ] . splitlines ( ) return all ( re . match ( r'\s\s+((?!\s\s).+)\s\s+.+' , s ) for s in definitions ) except IndexError : return False
def label_for_lm ( self , ** kwargs ) : "A special labelling method for language models ."
self . __class__ = LMTextList kwargs [ 'label_cls' ] = LMLabelList return self . label_const ( 0 , ** kwargs )
def get_labs ( format ) : """Gets Repair Cafe data from repairecafe . org ."""
data = data_from_repaircafe_org ( ) repaircafes = { } # Load all the Repair Cafes for i in data : # Create a lab current_lab = RepairCafe ( ) # Add existing data from first scraping current_lab . name = i [ "name" ] slug = i [ "url" ] . replace ( "https://repaircafe.org/locations/" , "" ) if slug . ...
def commit ( self , id , impreq ) : # pylint : disable = invalid - name , redefined - builtin """Commit a staged import . : param id : Staged import ID as an int . : param impreq : : class : ` imports . Request < imports . Request > ` object : return : : class : ` imports . Request < imports . Request > ` obj...
schema = RequestSchema ( ) json = self . service . encode ( schema , impreq ) schema = RequestSchema ( ) resp = self . service . post ( self . base + str ( id ) + '/' , json = json ) return self . service . decode ( schema , resp )
def _count_inversions ( a , b ) : '''Count the number of inversions in two numpy arrays : # points i , j where a [ i ] > = b [ j ] Parameters a , b : np . ndarray , shape = ( n , ) ( m , ) The arrays to be compared . This implementation is optimized for arrays with many repeated values . Returns inv...
a , a_counts = np . unique ( a , return_counts = True ) b , b_counts = np . unique ( b , return_counts = True ) inversions = 0 i = 0 j = 0 while i < len ( a ) and j < len ( b ) : if a [ i ] < b [ j ] : i += 1 elif a [ i ] >= b [ j ] : inversions += np . sum ( a_counts [ i : ] ) * b_counts [ j ] ...
async def loadCoreModule ( self , ctor , conf = None ) : '''Load a single cortex module with the given ctor and conf . Args : ctor ( str ) : The python module class path conf ( dict ) : Config dictionary for the module'''
if conf is None : conf = { } modu = self . _loadCoreModule ( ctor , conf = conf ) try : await s_coro . ornot ( modu . preCoreModule ) except asyncio . CancelledError : # pragma : no cover raise except Exception : logger . exception ( f'module preCoreModule failed: {ctor}' ) self . modules . pop ( ct...
def erase_display ( method = EraseMethod . ALL_MOVE , file = sys . stdout ) : """Clear the screen or part of the screen , and possibly moves the cursor to the " home " position ( 1 , 1 ) . See ` method ` argument below . Esc [ < method > J Arguments : method : One of these possible values : EraseMethod . ...
erase . display ( method ) . write ( file = file )
def upload_to_pypi ( ) : """Upload sdist and bdist _ eggs to pypi"""
# One more safety input and then we are ready to go : ) x = prompt ( "Are you sure to upload the current version to pypi?" ) if not x or not x . lower ( ) in [ "y" , "yes" ] : return local ( "rm -rf dist" ) local ( "python setup.py sdist" ) version = _get_cur_version ( ) fn = "RPIO-%s.tar.gz" % version put ( "dist/...
def discover_setup_packages ( ) : """Summarize packages currently set up by EUPS , listing their set up directories and EUPS version names . Returns packages : ` dict ` Dictionary with keys that are EUPS package names . Values are dictionaries with fields : - ` ` ' dir ' ` ` : absolute directory path of...
logger = logging . getLogger ( __name__ ) # Not a PyPI dependency ; assumed to be available in the build environment . import eups eups_client = eups . Eups ( ) products = eups_client . getSetupProducts ( ) packages = { } for package in products : name = package . name info = { 'dir' : package . dir , 'version'...
def add_propagate ( self , req : Request , sender : str ) : """Add the specified request to the list of received PROPAGATEs . : param req : the REQUEST to add : param sender : the name of the node sending the msg"""
data = self . add ( req ) data . propagates [ sender ] = req
def warning ( self , s ) : """Prints out a warning message to stderr . : param s : The warning string to print : return : None"""
print ( " WARNING: '%s', %s" % ( self . src_id , s ) , file = sys . stderr )
def create_ecdsa_encrypted_pem ( private_pem , passphrase ) : """< Purpose > Return a string in PEM format , where the private part of the ECDSA key is encrypted . The private part of the ECDSA key is encrypted as done by pyca / cryptography : " Encrypt using the best available encryption for a given key ' ...
# Does ' private _ key ' have the correct format ? # Raise ' securesystemslib . exceptions . FormatError ' if the check fails . securesystemslib . formats . PEMRSA_SCHEMA . check_match ( private_pem ) # Does ' passphrase ' have the correct format ? securesystemslib . formats . PASSWORD_SCHEMA . check_match ( passphrase...
def start_readout ( self , * args , ** kwargs ) : '''Starting the FIFO readout . Starting of the FIFO readout is executed only once by a random thread . Starting of the FIFO readout is synchronized between all threads reading out the FIFO .'''
# Pop parameters for fifo _ readout . start callback = kwargs . pop ( 'callback' , self . handle_data ) errback = kwargs . pop ( 'errback' , self . handle_err ) reset_rx = kwargs . pop ( 'reset_rx' , True ) reset_fifo = kwargs . pop ( 'reset_fifo' , True ) fill_buffer = kwargs . pop ( 'fill_buffer' , False ) no_data_ti...
def where ( self , attrs , first = False ) : """Return objects matching child objects properties . Parameters attrs : dict tmux properties to match values of Returns list"""
# from https : / / github . com / serkanyersen / underscore . py def by ( val , * args ) : for key , value in attrs . items ( ) : try : if attrs [ key ] != val [ key ] : return False except KeyError : return False return True if first : return list...
def _set_rstp ( self , v , load = False ) : """Setter method for rstp , mapped from YANG variable / brocade _ xstp _ ext _ rpc / get _ stp _ brief _ info / output / spanning _ tree _ info / rstp ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ rstp is consi...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = rstp . rstp , is_container = 'container' , presence = False , yang_name = "rstp" , rest_name = "rstp" , parent = self , choice = ( u'spanning-tree-mode' , u'rstp' ) , path_helper = self . _path_helper , extmethods = self . _e...
def generate ( self , x , ** kwargs ) : """Generates the adversarial sample for the given input . : param x : The model ' s inputs . : param eps : ( optional float ) attack step size ( input variation ) : param ord : ( optional ) Order of the norm ( mimics NumPy ) . Possible values : np . inf , 1 or 2. : ...
# Parse and save attack - specific parameters assert self . parse_params ( ** kwargs ) labels , _nb_classes = self . get_or_guess_labels ( x , kwargs ) return self . fgm ( x , labels = labels , targeted = ( self . y_target is not None ) )
def drop_continuous_query ( self , name , database = None ) : """Drop an existing continuous query for a database . : param name : the name of continuous query to drop : type name : str : param database : the database for which the continuous query is dropped . Defaults to current client ' s database : ty...
query_string = ( "DROP CONTINUOUS QUERY {0} ON {1}" ) . format ( quote_ident ( name ) , quote_ident ( database or self . _database ) ) self . query ( query_string )
def register ( self , preference_class ) : """Store the given preference class in the registry . : param preference _ class : a : py : class : ` prefs . Preference ` subclass"""
preference = preference_class ( registry = self ) self . section_objects [ preference . section . name ] = preference . section try : self [ preference . section . name ] [ preference . name ] = preference except KeyError : self [ preference . section . name ] = collections . OrderedDict ( ) self [ preferen...
def _check_bounds ( x , bounds ) : """Checks whether ` x ` is within ` bounds ` . JIT - compiled in ` nopython ` mode using Numba . Parameters x : ndarray ( float , ndim = 1) 1 - D array with shape ( n , ) of independent variables . bounds : ndarray ( float , ndim = 2) Sequence of ( min , max ) pairs fo...
if bounds . shape == ( 0 , 2 ) : return True else : return ( ( np . atleast_2d ( bounds ) [ : , 0 ] <= x ) . all ( ) and ( x <= np . atleast_2d ( bounds ) [ : , 1 ] ) . all ( ) )
def save ( self , ** kwargs ) : """Create the organization , then get the user , then make the owner ."""
is_active = True try : user = get_user_model ( ) . objects . get ( email = self . cleaned_data [ "email" ] ) except get_user_model ( ) . DoesNotExist : user = invitation_backend ( ) . invite_by_email ( self . cleaned_data [ "email" ] , ** { "domain" : get_current_site ( self . request ) , "organization" : self ...
def getFile ( self , name , relative = None ) : """Returns a file name or None"""
if self . pathCallback is not None : return getFile ( self . _getFileDeprecated ( name , relative ) ) return getFile ( name , relative or self . pathDirectory )
def constructPrimaryIdentifier ( self , data , ordered_identifier_candidates ) : """Construct and return a primary identifier value from the data asserted by the IdP using the ordered list of candidates from the configuration ."""
logprefix = PrimaryIdentifier . logprefix context = self . context attributes = data . attributes satosa_logging ( logger , logging . DEBUG , "{} Input attributes {}" . format ( logprefix , attributes ) , context . state ) value = None for candidate in ordered_identifier_candidates : satosa_logging ( logger , loggi...
def iterate_date_values ( d , start_date = None , stop_date = None , default = 0 ) : """Convert ( date , value ) sorted lists into contiguous value - per - day data sets . Great for sparklines . Example : : [ ( datetime . date ( 2011 , 1 , 1 ) , 1 ) , ( datetime . date ( 2011 , 1 , 4 ) , 2 ) ] - > [ 1 , 0 , 0 ,...
dataiter = iter ( d ) cur_day , cur_val = next ( dataiter ) start_date = start_date or cur_day while cur_day < start_date : cur_day , cur_val = next ( dataiter ) for d in iterate_date ( start_date , stop_date ) : if d != cur_day : yield default continue yield cur_val try : cur_da...
def db ( cmd , args = ( ) ) : """Run a database command"""
if cmd not in commands : okcmds = '\n' . join ( '%s %s' % ( name , repr ( ' ' . join ( args ) ) if args else '' ) for name , args in sorted ( commands . items ( ) ) ) print ( 'Invalid command "%s": choose one from\n%s' % ( cmd , okcmds ) ) elif len ( args ) != len ( commands [ cmd ] ) : print ( 'Wrong numbe...
def check_or ( state , * tests ) : """Test whether at least one SCT passes . If all of the tests fail , the feedback of the first test will be presented to the student . Args : state : State instance describing student and solution code , can be omitted if used with Ex ( ) tests : one or more sub - SCTs to ...
success = False first_feedback = None for test in iter_tests ( tests ) : try : multi ( state , test ) success = True except TestFail as e : if not first_feedback : first_feedback = e . feedback if success : return state # todo : add test state . report ( first_fee...
def updateitem ( self , key , new_val ) : """Update the priority value of an existing item . Raises ` ` KeyError ` ` if key is not in the pqdict ."""
if key not in self . _position : raise KeyError ( key ) self [ key ] = new_val
def multi_path_generator ( pathnames ) : """yields ( name , chunkgen ) for all of the files found under the list of pathnames given . This is recursive , so directories will have their contents emitted . chunkgen is a function that can called and iterated over to obtain the contents of the file in multiple ...
for pathname in pathnames : if isdir ( pathname ) : for entry in directory_generator ( pathname ) : yield entry else : yield pathname , file_chunk ( pathname )
def create_tags ( self , resource_ids , tags ) : """Create new metadata tags for the specified resource ids . : type resource _ ids : list : param resource _ ids : List of strings : type tags : dict : param tags : A dictionary containing the name / value pairs . If you want to create only a tag name , the...
params = { } self . build_list_params ( params , resource_ids , 'ResourceId' ) self . build_tag_param_list ( params , tags ) return self . get_status ( 'CreateTags' , params , verb = 'POST' )
def DviPsStrFunction ( target = None , source = None , env = None ) : """A strfunction for dvipdf that returns the appropriate command string for the no _ exec options ."""
if env . GetOption ( "no_exec" ) : result = env . subst ( '$PSCOM' , 0 , target , source ) else : result = '' return result
def plotting_correlation ( params , x0 , x1 , ax , lag = 20. , scaling = None , normalize = True , color = 'k' , unit = r'$cc=%.3f$' , title = 'firing_rate vs LFP' , scalebar = True , ** kwargs ) : '''mls on axes plot the correlation between x0 and x1 args : x0 : first dataset x1 : second dataset - the LFP ...
zvec = np . r_ [ params . electrodeParams [ 'z' ] ] zvec = np . r_ [ zvec , zvec [ - 1 ] + np . diff ( zvec ) [ - 1 ] ] xcorr_all = np . zeros ( ( params . electrodeParams [ 'z' ] . size , x0 . shape [ - 1 ] ) ) if normalize : for i , z in enumerate ( params . electrodeParams [ 'z' ] ) : if x0 . ndim == 1 :...
def wcparams ( mol , type_ ) : """Calculate Wildman - Crippen logP Wildman S . , Crippen G . , Prediction of Physicochemical Parameters by Atomic Contribution , J . Chem . Inf . Model . 39 ( 1999 ) 868-873"""
try : assign_wctype ( mol ) except : return "N/A" scores = [ ] for i , atom in mol . atoms_iter ( ) : scores . append ( float ( DATA [ type_ ] [ atom . wctype ] ) ) if atom . H_count : if atom . symbol == "C" : scores . append ( DATA [ type_ ] [ "H1" ] * atom . H_count ) elif...
def _closeElements ( childs , HTMLElement ) : """Create ` endtags ` to elements which looks like openers , but doesn ' t have proper : attr : ` HTMLElement . endtag ` . Args : childs ( list ) : List of childs ( : class : ` HTMLElement ` obj ) - typically from : attr : ` HTMLElement . childs ` property . R...
out = [ ] # close all unclosed pair tags for e in childs : if not e . isTag ( ) : out . append ( e ) continue if not e . isNonPairTag ( ) and not e . isEndTag ( ) and not e . isComment ( ) and e . endtag is None : e . childs = _closeElements ( e . childs , HTMLElement ) out . app...
def run_fit ( self ) : """Performing fit of the OCV steps in the cycles set by set _ cycles ( ) from the data set by set _ data ( ) r is found by calculating v0 / i _ start - - > err ( r ) = err ( v0 ) + err ( i _ start ) . c is found from using tau / r - - > err ( c ) = err ( r ) + err ( tau ) Returns : ...
# Check if data is set if self . time is [ ] : self . result = [ ] return try : self . fit_model ( ) except ValueError as e : print ( e ) except AttributeError as e : print ( e )
def log_deprecated ( name = "" , text = "" , eos = "" ) : """Log deprecation warning . Args : name ( str ) : name of the deprecated item . text ( str , optional ) : information about the deprecation . eos ( str , optional ) : end of service date such as " YYYY - MM - DD " ."""
assert name or text if eos : eos = "after " + datetime ( * map ( int , eos . split ( "-" ) ) ) . strftime ( "%d %b" ) if name : if eos : warn_msg = "%s will be deprecated %s. %s" % ( name , eos , text ) else : warn_msg = "%s was deprecated. %s" % ( name , text ) else : warn_msg = text ...
def add_new_reset_method ( cls ) : """Replace existing cls . reset ( ) method with a new one which also calls reset ( ) on any clones ."""
orig_reset = cls . reset def new_reset ( self , seed = None ) : logger . debug ( f"Calling reset() on {self} (seed={seed})" ) orig_reset ( self , seed ) for c in self . _dependent_generators : c . reset_dependent_generator ( seed ) return self cls . reset = new_reset
def _page_to_text ( page ) : """Extract the text from a page . Args : page : a unicode string Returns : a unicode string"""
# text start tag looks like " < text . . otherstuff > " start_pos = page . find ( u"<text" ) assert start_pos != - 1 end_tag_pos = page . find ( u">" , start_pos ) assert end_tag_pos != - 1 end_tag_pos += len ( u">" ) end_pos = page . find ( u"</text>" ) if end_pos == - 1 : return u"" return page [ end_tag_pos : en...
def write ( self , data ) : 'write data to the ssl channel and return the # of bytes transferred'
return self . _with_retry ( functools . partial ( self . _sslobj . write , data ) , self . gettimeout ( ) )
def _compile_target ( self , vt ) : """' Compiles ' a python target . ' Compiling ' means forming an isolated chroot of its sources and transitive deps and then attempting to import each of the target ' s sources in the case of a python library or else the entry point in the case of a python binary . For a ...
target = vt . target with self . context . new_workunit ( name = target . address . spec ) : modules = self . _get_modules ( target ) if not modules : # Nothing to eval , so a trivial compile success . return 0 interpreter = self . _get_interpreter_for_target_closure ( target ) reqs_pex = self ....
def get_instance ( self , payload ) : """Build an instance of WorkspaceRealTimeStatisticsInstance : param dict payload : Payload response from the API : returns : twilio . rest . taskrouter . v1 . workspace . workspace _ real _ time _ statistics . WorkspaceRealTimeStatisticsInstance : rtype : twilio . rest . ...
return WorkspaceRealTimeStatisticsInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , )
def get_chest ( self , index = 0 ) : '''Get your current chest + - the index'''
index += self . chest_cycle . position if index == self . chest_cycle . super_magical : return 'Super Magical' if index == self . chest_cycle . epic : return 'Epic' if index == self . chest_cycle . legendary : return 'Legendary' return CHESTS [ index % len ( CHESTS ) ]
def cmd_position ( self , args ) : '''position x - m y - m z - m'''
if ( len ( args ) != 3 ) : print ( "Usage: position x y z (meters)" ) return if ( len ( args ) == 3 ) : x_m = float ( args [ 0 ] ) y_m = float ( args [ 1 ] ) z_m = float ( args [ 2 ] ) print ( "x:%f, y:%f, z:%f" % ( x_m , y_m , z_m ) ) self . master . mav . set_position_target_local_ned_send...
def init_device ( ** kwargs ) : """same arguments as OCLDevice . _ _ init _ _ e . g . id _ platform = 0 id _ device = 1"""
new_device = OCLDevice ( ** kwargs ) # just change globals if new _ device is different from old if _ocl_globals . device . device != new_device . device : _ocl_globals . device = new_device
def publish_message ( self , message , expire = None ) : """Publish a ` ` message ` ` on the subscribed channel on the Redis datastore . ` ` expire ` ` sets the time in seconds , on how long the message shall additionally of being published , also be persisted in the Redis datastore . If unset , it defaults to ...
if expire is None : expire = self . _expire if not isinstance ( message , RedisMessage ) : raise ValueError ( 'message object is not of type RedisMessage' ) for channel in self . _publishers : self . _connection . publish ( channel , message ) if expire > 0 : self . _connection . setex ( channel...
def authenticate_user ( self , response , ** kwargs ) : """Handles user authentication with gssapi / kerberos"""
host = urlparse ( response . url ) . hostname try : auth_header = self . generate_request_header ( response , host ) except KerberosExchangeError : # GSS Failure , return existing response return response log . debug ( "authenticate_user(): Authorization header: {0}" . format ( auth_header ) ) response . reques...
def insert ( exif , image , new_file = None ) : """py : function : : piexif . insert ( exif _ bytes , filename ) Insert exif into JPEG . : param bytes exif _ bytes : Exif as bytes : param str filename : JPEG"""
if exif [ 0 : 6 ] != b"\x45\x78\x69\x66\x00\x00" : raise ValueError ( "Given data is not exif data" ) output_file = False # Prevents " UnicodeWarning : Unicode equal comparison failed " warnings on Python 2 maybe_image = sys . version_info >= ( 3 , 0 , 0 ) or isinstance ( image , str ) if maybe_image and image [ 0 ...
def plot_fit ( self , intervals = False , ** kwargs ) : """Plots the fit of the model Parameters intervals : Boolean Whether to plot 95 % confidence interval of states Returns None ( plots data and the fit )"""
import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) series_type = kwargs . get ( 'series_type' , 'Smoothed' ) if self . latent_variables . estimated is False : raise Exception ( "No latent variables estimated!" ) else : date_index = copy . deepcopy ( self . ...
def delete_expired ( self , expires ) : """Delete all expired taskset results ."""
meta = self . model . _meta with commit_on_success ( ) : self . get_all_expired ( expires ) . update ( hidden = True ) cursor = self . connection_for_write ( ) . cursor ( ) cursor . execute ( 'DELETE FROM {0.db_table} WHERE hidden=%s' . format ( meta ) , ( True , ) , )
def list_dynamodb ( region , filter_by_kwargs ) : """List all DynamoDB tables ."""
conn = boto . dynamodb . connect_to_region ( region ) tables = conn . list_tables ( ) return lookup ( tables , filter_by = filter_by_kwargs )
def stop ( self , kill = False , timeout = 15 ) : """terminate process and wipe out the temp work directory , but only if we actually started it"""
super ( AbstractDcsController , self ) . stop ( kill = kill , timeout = timeout ) if self . _work_directory : shutil . rmtree ( self . _work_directory )
def flatten_dict ( dict_obj , separator = '.' , flatten_lists = False ) : """Flattens the given dict into a single - level dict with flattend keys . Parameters dict _ obj : dict A possibly nested dict . separator : str , optional The character to use as a separator between keys . Defaults to ' . ' . fla...
reducer = _get_key_reducer ( separator ) flat = { } def _flatten_key_val ( key , val , parent ) : flat_key = reducer ( parent , key ) try : _flatten ( val , flat_key ) except TypeError : flat [ flat_key ] = val def _flatten ( d , parent = None ) : try : for key , val in d . items...
def make_source_mask ( data , snr , npixels , mask = None , mask_value = None , filter_fwhm = None , filter_size = 3 , filter_kernel = None , sigclip_sigma = 3.0 , sigclip_iters = 5 , dilate_size = 11 ) : """Make a source mask using source segmentation and binary dilation . Parameters data : array _ like The ...
from scipy import ndimage threshold = detect_threshold ( data , snr , background = None , error = None , mask = mask , mask_value = None , sigclip_sigma = sigclip_sigma , sigclip_iters = sigclip_iters ) kernel = None if filter_kernel is not None : kernel = filter_kernel if filter_fwhm is not None : sigma = filt...
def validate ( self , api_key = None ) : """The original contents of the Event message must be confirmed by refetching it and comparing the fetched data with the original data . This function makes an API call to Stripe to redownload the Event data and returns whether or not it matches the WebhookEventTrigger...
local_data = self . json_body if "id" not in local_data or "livemode" not in local_data : return False if self . is_test_event : logger . info ( "Test webhook received: {}" . format ( local_data ) ) return False if djstripe_settings . WEBHOOK_VALIDATION is None : # validation disabled return True elif (...
def _download_py3 ( link , path , __hdr__ ) : """Download a file from a link in Python 3."""
try : req = urllib . request . Request ( link , headers = __hdr__ ) u = urllib . request . urlopen ( req ) except Exception as e : raise Exception ( ' Download failed with the error:\n{}' . format ( e ) ) with open ( path , 'wb' ) as outf : for l in u : outf . write ( l ) u . close ( )
def _copyToNewWorkingDir ( newdir , input ) : """Copy input file and all related files necessary for processing to the new working directory . This function works in a greedy manner , in that all files associated with all inputs ( have the same rootname ) will be copied to the new working directory ."""
flist = [ ] if '_asn.fits' in input : asndict = asnutil . readASNTable ( input , None ) flist . append ( input [ : input . find ( '_' ) ] ) flist . extend ( asndict [ 'order' ] ) flist . append ( asndict [ 'output' ] ) else : flist . append ( input [ : input . find ( '_' ) ] ) # copy all files relat...
def derivative ( self , point ) : """Derivative of this operator . For example , if A and B are operators [ [ A , 0 ] , [0 , B ] ] The derivative is given by : [ [ A ' , 0 ] , [0 , B ' ] ] This is only well defined if each sub - operator has a derivative Parameters point : ` element - like ` in ` ...
point = self . domain . element ( point ) derivs = [ op . derivative ( p ) for op , p in zip ( self . operators , point ) ] return DiagonalOperator ( * derivs , domain = self . domain , range = self . range )
def return_single_convert_numpy ( self , object_id , converter , add_args = None ) : """Converts an object specified by the object _ id into a numpy array and returns the array , the conversion is done by the ' converter ' function Parameters object _ id : int , id of object in database converter : function...
return return_single_convert_numpy_base ( self . dbpath , self . path_to_set , self . _set_object , object_id , converter , add_args )