signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def access_entries ( self ) : """List [ google . cloud . bigquery . dataset . AccessEntry ] : Dataset ' s access entries . ` ` role ` ` augments the entity type and must be present * * unless * * the entity type is ` ` view ` ` . Raises : TypeError : If ' value ' is not a sequence ValueError : If any ...
entries = self . _properties . get ( "access" , [ ] ) return [ AccessEntry . from_api_repr ( entry ) for entry in entries ]
def set_corner_widgets ( self , corner_widgets ) : """Set tabs corner widgets corner _ widgets : dictionary of ( corner , widgets ) corner : Qt . TopLeftCorner or Qt . TopRightCorner widgets : list of widgets ( may contains integers to add spacings )"""
assert isinstance ( corner_widgets , dict ) assert all ( key in ( Qt . TopLeftCorner , Qt . TopRightCorner ) for key in corner_widgets ) self . corner_widgets . update ( corner_widgets ) for corner , widgets in list ( self . corner_widgets . items ( ) ) : cwidget = QWidget ( ) cwidget . hide ( ) prev_widget...
def pool_by_environmentvip ( self , environment_vip_id ) : """Method to return list object pool by environment vip id Param environment _ vip _ id : environment vip id Return list object pool"""
uri = 'api/v3/pool/environment-vip/%s/' % environment_vip_id return super ( ApiPool , self ) . get ( uri )
def prepare ( self ) : """Prepare the handler , ensuring RabbitMQ is connected or start a new connection attempt ."""
super ( RabbitMQRequestHandler , self ) . prepare ( ) if self . _rabbitmq_is_closed : self . _connect_to_rabbitmq ( )
def _write_fragments ( self , fragments ) : """: param fragments : A generator of messages"""
answer = tornado . gen . Future ( ) if not fragments : answer . set_result ( None ) return answer io_loop = IOLoop . current ( ) def _write_fragment ( future ) : if future and future . exception ( ) : return answer . set_exc_info ( future . exc_info ( ) ) try : fragment = fragments . nex...
def unpack_flags ( value , flags ) : """Multiple flags might be packed in the same field ."""
try : return [ flags [ value ] ] except KeyError : return [ flags [ k ] for k in sorted ( flags . keys ( ) ) if k & value > 0 ]
def normalize ( alias ) : """Normalizes an alias by removing adverbs defined in IGNORED _ WORDS"""
# Convert from CamelCase to snake _ case alias = re . sub ( r'([a-z])([A-Z])' , r'\1_\2' , alias ) # Ignore words words = alias . lower ( ) . split ( '_' ) words = filter ( lambda w : w not in IGNORED_WORDS , words ) return '_' . join ( words )
def Inorm_bol_bb ( Teff = 5772. , logg = 4.43 , abun = 0.0 , atm = 'blackbody' , photon_weighted = False ) : """@ Teff : value or array of effective temperatures @ logg : surface gravity ; not used , for class compatibility only @ abun : abundances ; not used , for class compatibility only @ atm : atmosphere ...
if atm != 'blackbody' : raise ValueError ( 'atmosphere must be set to blackbody for Inorm_bol_bb.' ) if photon_weighted : factor = 2.6814126821264836e22 / Teff else : factor = 1.0 # convert scalars to vectors if necessary : if not hasattr ( Teff , '__iter__' ) : Teff = np . array ( ( Teff , ) ) return f...
def from_response ( cls , response , attrs ) : """Create an index from returned Dynamo data"""
proj = response [ 'Projection' ] hash_key = attrs . get ( response [ 'KeySchema' ] [ 0 ] [ 'AttributeName' ] ) range_key = None if len ( response [ 'KeySchema' ] ) > 1 : range_key = attrs [ response [ 'KeySchema' ] [ 1 ] [ 'AttributeName' ] ] throughput = Throughput . from_response ( response [ 'ProvisionedThroughp...
def http_session ( self ) : """HTTP Session property : return : vk _ requests . utils . VerboseHTTPSession instance"""
if self . _http_session is None : session = VerboseHTTPSession ( ) session . headers . update ( self . DEFAULT_HTTP_HEADERS ) self . _http_session = session return self . _http_session
def del_repo ( repo , basedir = None , ** kwargs ) : # pylint : disable = W0613 '''Delete a repo from < basedir > ( default basedir : all dirs in ` reposdir ` yum option ) . If the . repo file in which the repo exists does not contain any other repo configuration , the file itself will be deleted . CLI Exam...
# this is so we know which dirs are searched for our error messages below basedirs = _normalize_basedir ( basedir ) repos = list_repos ( basedirs ) if repo not in repos : return 'Error: the {0} repo does not exist in {1}' . format ( repo , basedirs ) # Find out what file the repo lives in repofile = '' for arepo in...
def dispatch ( self , request , start_response ) : """Handles dispatch to apiserver handlers . This typically ends up calling start _ response and returning the entire body of the response . Args : request : An ApiRequest , the request from the user . start _ response : A function with semantics defined i...
# Check if this matches any of our special handlers . dispatched_response = self . dispatch_non_api_requests ( request , start_response ) if dispatched_response is not None : return dispatched_response # Call the service . try : return self . call_backend ( request , start_response ) except errors . RequestErro...
def updateLayoutParameters ( self , algorithmName , body , verbose = None ) : """Updates the Layout parameters for the Layout algorithm specified by the ` algorithmName ` parameter . : param algorithmName : Name of the layout algorithm : param body : A list of Layout Parameters with Values . : param verbose :...
response = api ( url = self . ___url + 'apply/layouts/' + str ( algorithmName ) + '/parameters' , method = "PUT" , body = body , verbose = verbose ) return response
def warning ( f , * args , ** kwargs ) : """Automatically log progress on function entry and exit . Default logging value : warning . * Logging with values contained in the parameters of the decorated function * Message ( args [ 0 ] ) may be a string to be formatted with parameters passed to the decorated f...
kwargs . update ( { 'log' : logging . WARNING } ) return _stump ( f , * args , ** kwargs )
def get_my_feed ( self , limit = 150 , offset = 20 , sort = "updated" , nid = None ) : """Get my feed : type limit : int : param limit : Number of posts from feed to get , starting from ` ` offset ` ` : type offset : int : param offset : Offset starting from bottom of feed : type sort : str : param sort...
r = self . request ( method = "network.get_my_feed" , nid = nid , data = dict ( limit = limit , offset = offset , sort = sort ) ) return self . _handle_error ( r , "Could not retrieve your feed." )
def match ( self , string ) : """Match a string against the template . If the string matches the template , return a dict mapping template parameter names to converted values , otherwise return ` ` None ` ` . > > > t = Template ( ' Hello my name is { name } ! ' ) > > > t . match ( ' Hello my name is David !...
m = self . regex . match ( string ) if m : c = self . type_converters return dict ( ( k , c [ k ] ( v ) if k in c else v ) for k , v in m . groupdict ( ) . iteritems ( ) ) return None
def ed25519_private_key_from_string ( string ) : """Create an ed25519 private key from ` ` string ` ` , which is a seed . Args : string ( str ) : the string to use as a seed . Returns : Ed25519PrivateKey : the private key"""
try : return Ed25519PrivateKey . from_private_bytes ( base64 . b64decode ( string ) ) except ( UnsupportedAlgorithm , Base64Error ) as exc : raise ScriptWorkerEd25519Error ( "Can't create Ed25519PrivateKey: {}!" . format ( str ( exc ) ) )
def _set_account_info ( self ) : """Connect to the AWS IAM API via boto3 and run the GetUser operation on the current user . Use this to set ` ` self . aws _ account _ id ` ` and ` ` self . aws _ region ` ` ."""
if 'AWS_DEFAULT_REGION' in os . environ : logger . debug ( 'Connecting to IAM with region_name=%s' , os . environ [ 'AWS_DEFAULT_REGION' ] ) kwargs = { 'region_name' : os . environ [ 'AWS_DEFAULT_REGION' ] } elif 'AWS_REGION' in os . environ : logger . debug ( 'Connecting to IAM with region_name=%s' , os . ...
def add ( self , item ) : """Add a row to the table . List can be passed and are automatically converted to Rows . : param item : Item an element to add to the rows can be list or Row object : type item : row , list"""
if isinstance ( item , list ) : self . rows . append ( Row ( item ) ) elif isinstance ( item , Row ) : self . rows . append ( item ) else : raise InvalidMessageItemError ( item , item . __class__ )
def reset ( self ) : """Clean any processing data , and prepare object for reuse"""
self . current_table = None self . tables = [ ] self . data = [ { } ] self . additional_data = { } self . lines = [ ] self . set_state ( 'document' ) self . current_file = None self . set_of_energies = set ( )
def hexbin ( self , x , y , size , orientation = "pointytop" , palette = "Viridis256" , line_color = None , fill_color = None , aspect_scale = 1 , ** kwargs ) : '''Perform a simple equal - weight hexagonal binning . A : class : ` ~ bokeh . models . _ glyphs . HexTile ` glyph will be added to display the binning...
from . . util . hex import hexbin bins = hexbin ( x , y , size , orientation , aspect_scale = aspect_scale ) if fill_color is None : fill_color = linear_cmap ( 'c' , palette , 0 , max ( bins . counts ) ) source = ColumnDataSource ( data = dict ( q = bins . q , r = bins . r , c = bins . counts ) ) r = self . hex_til...
def find ( self , addr , what , max_search = None , max_symbolic_bytes = None , default = None , step = 1 , disable_actions = False , inspect = True , chunk_size = None ) : """Returns the address of bytes equal to ' what ' , starting from ' start ' . Note that , if you don ' t specify a default value , this searc...
addr = _raw_ast ( addr ) what = _raw_ast ( what ) default = _raw_ast ( default ) if isinstance ( what , bytes ) : # Convert it to a BVV what = claripy . BVV ( what , len ( what ) * self . state . arch . byte_width ) r , c , m = self . _find ( addr , what , max_search = max_search , max_symbolic_bytes = max_symbolic...
def GetCampaignFeeds ( client , feed , placeholder_type ) : """Get a list of Feed Item Ids used by a campaign via a given Campaign Feed . Args : client : an AdWordsClient instance . feed : a Campaign Feed . placeholder _ type : the Placeholder Type . Returns : A list of Feed Item Ids ."""
campaign_feed_service = client . GetService ( 'CampaignFeedService' , 'v201809' ) campaign_feeds = [ ] more_pages = True selector = { 'fields' : [ 'CampaignId' , 'MatchingFunction' , 'PlaceholderTypes' ] , 'predicates' : [ { 'field' : 'Status' , 'operator' : 'EQUALS' , 'values' : [ 'ENABLED' ] } , { 'field' : 'FeedId' ...
def target_in_range ( self , target : "Unit" , bonus_distance : Union [ int , float ] = 0 ) -> bool : """Includes the target ' s radius when calculating distance to target"""
if self . can_attack_ground and not target . is_flying : unit_attack_range = self . ground_range elif self . can_attack_air and ( target . is_flying or target . type_id == UnitTypeId . COLOSSUS ) : unit_attack_range = self . air_range else : unit_attack_range = - 1 return ( self . position . _distance_squar...
def GetKey ( self , public_key_hash ) : """Get the KeyPair belonging to the public key hash . Args : public _ key _ hash ( UInt160 ) : a public key hash to get the KeyPair for . Returns : KeyPair : If successful , the KeyPair belonging to the public key hash , otherwise None"""
if public_key_hash . ToBytes ( ) in self . _keys . keys ( ) : return self . _keys [ public_key_hash . ToBytes ( ) ] return None
def rawfile_within_timeframe ( rawfile , timeframe ) : """Checks whether the given raw filename timestamp falls within [ start , end ] timeframe ."""
matches = re . search ( r'-(\d{8})-' , rawfile ) if matches : ftime = datetime . strptime ( matches . group ( 1 ) , "%Y%m%d" ) ftime = pytz . utc . localize ( ftime ) return ftime . date ( ) >= timeframe [ 0 ] . date ( ) and ftime . date ( ) <= timeframe [ 1 ] . date ( )
def generate ( env ) : "Add RPCGEN Builders and construction variables for an Environment ."
client = Builder ( action = rpcgen_client , suffix = '_clnt.c' , src_suffix = '.x' ) header = Builder ( action = rpcgen_header , suffix = '.h' , src_suffix = '.x' ) service = Builder ( action = rpcgen_service , suffix = '_svc.c' , src_suffix = '.x' ) xdr = Builder ( action = rpcgen_xdr , suffix = '_xdr.c' , src_suffix ...
def log_difference ( lx , ly ) : """Returns log ( exp ( lx ) - exp ( ly ) ) without leaving log space ."""
# Negative log of double - precision infinity li = - 709.78271289338397 diff = ly - lx # Make sure log - difference can succeed if np . any ( diff >= 0 ) : raise ValueError ( 'Cannot compute log(x-y), because y>=x for some elements.' ) # Otherwise evaluate log - difference return lx + np . log ( 1. - np . exp ( dif...
def use_gl ( target = 'gl2' ) : """Let Vispy use the target OpenGL ES 2.0 implementation Also see ` ` vispy . use ( ) ` ` . Parameters target : str The target GL backend to use . Available backends : * gl2 - Use ES 2.0 subset of desktop ( i . e . normal ) OpenGL * gl + - Use the desktop ES 2.0 subset ...
target = target or 'gl2' target = target . replace ( '+' , 'plus' ) # Get options target , _ , options = target . partition ( ' ' ) debug = config [ 'gl_debug' ] or 'debug' in options # Select modules to import names from try : mod = __import__ ( target , globals ( ) , level = 1 ) except ImportError as err : ms...
def _sigma_pi_midE ( self , Tp ) : """Geant 4.10.0 model for 2 GeV < Tp < 5 GeV"""
m_p = self . _m_p Qp = ( Tp - self . _Tth ) / m_p multip = - 6e-3 + 0.237 * Qp - 0.023 * Qp ** 2 return self . _sigma_inel ( Tp ) * multip
def getAttributeValue ( self , namespaceURI , localName ) : '''Keyword arguments : namespaceURI - - namespace of attribute localName - - local name of attribute'''
if self . hasAttribute ( namespaceURI , localName ) : attr = self . node . getAttributeNodeNS ( namespaceURI , localName ) return attr . value return None
def dim ( self , dim_index ) : """Get an SDim instance given a dimension index number . Args : : dim _ index index number of the dimension ( numbering starts at 0) C library equivalent : SDgetdimid"""
id = _C . SDgetdimid ( self . _id , dim_index ) _checkErr ( 'dim' , id , 'invalid SDS identifier or dimension index' ) return SDim ( self , id , dim_index )
def locatedExpr ( expr ) : """Helper to decorate a returned token with its starting and ending locations in the input string . This helper adds the following results names : - locn _ start = location where matched expression begins - locn _ end = location where matched expression ends - value = the actual...
locator = Empty ( ) . setParseAction ( lambda s , l , t : l ) return Group ( locator ( "locn_start" ) + expr ( "value" ) + locator . copy ( ) . leaveWhitespace ( ) ( "locn_end" ) )
def dafus ( insum , nd , ni ) : """Unpack an array summary into its double precision and integer components . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / dafus _ c . html : param insum : Array summary . : type insum : Array of floats : param nd : Number of double precisio...
insum = stypes . toDoubleVector ( insum ) dc = stypes . emptyDoubleVector ( nd ) ic = stypes . emptyIntVector ( ni ) nd = ctypes . c_int ( nd ) ni = ctypes . c_int ( ni ) libspice . dafus_c ( insum , nd , ni , dc , ic ) return stypes . cVectorToPython ( dc ) , stypes . cVectorToPython ( ic )
def _parse_match_info ( match , soccer = False ) : """Parse string containing info of a specific match : param match : Match data : type match : string : param soccer : Set to true if match contains soccer data , defaults to False : type soccer : bool , optional : return : Dictionary containing match info...
match_info = { } i_open = match . index ( '(' ) i_close = match . index ( ')' ) match_info [ 'league' ] = match [ i_open + 1 : i_close ] . strip ( ) match = match [ i_close + 1 : ] i_vs = match . index ( 'vs' ) i_colon = match . index ( ':' ) match_info [ 'home_team' ] = match [ 0 : i_vs ] . replace ( '#' , ' ' ) . str...
def moments ( self ) : """The first two time delay weighted statistical moments of the MA coefficients ."""
moment1 = statstools . calc_mean_time ( self . delays , self . coefs ) moment2 = statstools . calc_mean_time_deviation ( self . delays , self . coefs , moment1 ) return numpy . array ( [ moment1 , moment2 ] )
def wait_for_shutdown_signal ( self , please_stop = False , # ASSIGN SIGNAL TO STOP EARLY allow_exit = False , # ALLOW " exit " COMMAND ON CONSOLE TO ALSO STOP THE APP wait_forever = True # IGNORE CHILD THREADS , NEVER EXIT . False = > IF NO CHILD THREADS LEFT , THEN EXIT ) : """FOR USE BY PROCESSES THAT NEVER DIE ...
self_thread = Thread . current ( ) if self_thread != MAIN_THREAD or self_thread != self : Log . error ( "Only the main thread can sleep forever (waiting for KeyboardInterrupt)" ) if isinstance ( please_stop , Signal ) : # MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL self . please_stop . on_go ( ...
def version ( * names , ** kwargs ) : '''Returns a string representing the package version or an empty string if not installed . If more than one package name is specified , a dict of name / version pairs is returned . . . note : : This function can accessed using ` ` pkg . info ` ` in addition to ` ` pkg...
with_origin = kwargs . pop ( 'with_origin' , False ) ret = __salt__ [ 'pkg_resource.version' ] ( * names , ** kwargs ) if not salt . utils . data . is_true ( with_origin ) : return ret # Put the return value back into a dict since we ' re adding a subdict if len ( names ) == 1 : ret = { names [ 0 ] : ret } orig...
def secondaries ( self ) : """return list of secondaries members"""
return [ { "_id" : self . host2id ( member ) , "host" : member , "server_id" : self . _servers . host_to_server_id ( member ) } for member in self . get_members_in_state ( 2 ) ]
def _get_pretty_table ( self , indent : int = 0 , align : int = ALIGN_CENTER , border : bool = False ) -> PrettyTable : """Returns the table format of the scheme , i . e . : < table name > | < field1 > | < field2 > . . . | value1 ( field1 ) | value1 ( field2) | value2 ( field1 ) | value2 ( field2) | value...
rows = self . rows columns = self . columns # Add the column color . if self . _headers_color != Printer . NORMAL and len ( rows ) > 0 and len ( columns ) > 0 : # We need to copy the lists so that we wont insert colors in the original ones . rows [ 0 ] = rows [ 0 ] [ : ] columns = columns [ : ] columns [ 0 ...
def _rank_cycle_function ( self , cycle , function , ranks ) : """Dijkstra ' s shortest paths algorithm . See also : - http : / / en . wikipedia . org / wiki / Dijkstra ' s _ algorithm"""
import heapq Q = [ ] Qd = { } p = { } visited = set ( [ function ] ) ranks [ function ] = 0 for call in compat_itervalues ( function . calls ) : if call . callee_id != function . id : callee = self . functions [ call . callee_id ] if callee . cycle is cycle : ranks [ callee ] = 1 ...
def _apply_advanced_config ( config_spec , advanced_config , vm_extra_config = None ) : '''Sets configuration parameters for the vm config _ spec vm . ConfigSpec object advanced _ config config key value pairs vm _ extra _ config Virtual machine vm _ ref . config . extraConfig object'''
log . trace ( 'Configuring advanced configuration ' 'parameters %s' , advanced_config ) if isinstance ( advanced_config , str ) : raise salt . exceptions . ArgumentValueError ( 'The specified \'advanced_configs\' configuration ' 'option cannot be parsed, please check the parameters' ) for key , value in six . iteri...
def activate ( self , engine ) : """Activates the Component . : param engine : Container to attach the Component to . : type engine : QObject : return : Method success . : rtype : bool"""
LOGGER . debug ( "> Activating '{0}' Component." . format ( self . __class__ . __name__ ) ) self . __engine = engine self . __settings = self . __engine . settings self . __settings_section = self . name self . __default_script_editor_directory = os . path . join ( self . __engine . user_application_data_directory , Co...
def prop ( key , dct_or_obj ) : """Implementation of prop ( get _ item ) that also supports object attributes : param key : : param dct _ or _ obj : : return :"""
# Note that hasattr is a builtin and getattr is a ramda function , hence the different arg position if isinstance ( dict , dct_or_obj ) : if has ( key , dct_or_obj ) : return dct_or_obj [ key ] else : raise Exception ( "No key %s found for dict %s" % ( key , dct_or_obj ) ) elif isinstance ( list...
async def _auth_cram_md5 ( self , username , password ) : """Performs an authentication attemps using the CRAM - MD5 mechanism . Protocol : 1 . Send ' AUTH CRAM - MD5 ' to server ; 2 . If the server replies with a 334 return code , we can go on : 1 ) The challenge ( sent by the server ) is base64 - decoded ...
mechanism = "CRAM-MD5" code , message = await self . do_cmd ( "AUTH" , mechanism , success = ( 334 , ) ) decoded_challenge = base64 . b64decode ( message ) challenge_hash = hmac . new ( key = password . encode ( "utf-8" ) , msg = decoded_challenge , digestmod = "md5" ) hex_hash = challenge_hash . hexdigest ( ) response...
def hashstr_arr ( arr , lbl = 'arr' , pathsafe = False , ** kwargs ) : r"""Args : arr ( ndarray ) : lbl ( str ) : ( default = ' arr ' ) pathsafe ( bool ) : ( default = False ) Returns : str : arr _ hashstr CommandLine : python - m utool . util _ hash - - test - hashstr _ arr python - m utool . util ...
if isinstance ( arr , list ) : arr = tuple ( arr ) # force arrays into a tuple for hashability # TODO : maybe for into numpy array instead ? tuples might have problems if pathsafe : lbrace1 , rbrace1 , lbrace2 , rbrace2 = '_' , '_' , '-' , '-' else : lbrace1 , rbrace1 , lbrace2 , rbrace2 = '(' , ')'...
def getRealContributions ( self ) : """Get the real number of contributions ( private + public ) ."""
datefrom = datetime . now ( ) - relativedelta ( days = 366 ) dateto = datefrom + relativedelta ( months = 1 ) - relativedelta ( days = 1 ) private = 0 while datefrom < datetime . now ( ) : fromstr = datefrom . strftime ( "%Y-%m-%d" ) tostr = dateto . strftime ( "%Y-%m-%d" ) url = self . server + self . name...
def _fail ( self , request_id , failure , duration ) : """Publish a CommandFailedEvent ."""
self . listeners . publish_command_failure ( duration , failure , self . name , request_id , self . sock_info . address , self . op_id )
def _recompress_archive ( archive , verbosity = 0 , interactive = True ) : """Try to recompress an archive to smaller size ."""
format , compression = get_archive_format ( archive ) if compression : # only recompress the compression itself ( eg . for . tar . xz ) format = compression tmpdir = util . tmpdir ( ) tmpdir2 = util . tmpdir ( ) base , ext = os . path . splitext ( os . path . basename ( archive ) ) archive2 = util . get_single_outf...
def load ( obj , cls , default_factory ) : """Create or load an object if necessary . Parameters obj : ` object ` or ` dict ` or ` None ` cls : ` type ` default _ factory : ` function ` Returns ` object `"""
if obj is None : return default_factory ( ) if isinstance ( obj , dict ) : return cls . load ( obj ) return obj
def _new_render ( response ) : """Decorator for the TemplateResponse . render ( ) function"""
orig_render = response . __class__ . render # No arguments , is used as bound method . def _inner_render ( ) : try : return orig_render ( response ) except HttpRedirectRequest as e : return HttpResponseRedirect ( e . url , status = e . status ) return _inner_render
def _fetch_langs ( ) : """Fetch ( scrape ) languages from Google Translate . Google Translate loads a JavaScript Array of ' languages codes ' that can be spoken . We intersect this list with all the languages Google Translate provides to get the ones that support text - to - speech . Returns : dict : A di...
# Load HTML page = requests . get ( URL_BASE ) soup = BeautifulSoup ( page . content , 'html.parser' ) # JavaScript URL # The < script src = ' ' > path can change , but not the file . # Ex : / zyx / abc / 20180211 / desktop _ module _ main . js js_path = soup . find ( src = re . compile ( JS_FILE ) ) [ 'src' ] js_url =...
def find_connectable_ip ( host , port = None ) : """Resolve a hostname to an IP , preferring IPv4 addresses . We prefer IPv4 so that we don ' t change behavior from previous IPv4 - only implementations , and because some drivers ( e . g . , FirefoxDriver ) do not support IPv6 connections . If the optional p...
try : addrinfos = socket . getaddrinfo ( host , None ) except socket . gaierror : return None ip = None for family , _ , _ , _ , sockaddr in addrinfos : connectable = True if port : connectable = is_connectable ( port , sockaddr [ 0 ] ) if connectable and family == socket . AF_INET : ...
def keyframe ( self , keyframe ) : """Set keyframe ."""
if self . _keyframe == keyframe : return if self . _keyframe is not None : raise RuntimeError ( 'cannot reset keyframe' ) if len ( self . _offsetscounts [ 0 ] ) != len ( keyframe . dataoffsets ) : raise RuntimeError ( 'incompatible keyframe' ) if keyframe . is_tiled : pass if keyframe . is_contiguous : ...
def is_valid_single_address ( self , single_address ) : """Check if a potentially ambiguous single address spec really exists . : param single _ address : A SingleAddress spec . : return : True if given spec exists , False otherwise ."""
if not isinstance ( single_address , SingleAddress ) : raise TypeError ( 'Parameter "{}" is of type {}, expecting type {}.' . format ( single_address , type ( single_address ) , SingleAddress ) ) try : return bool ( self . scan_specs ( [ single_address ] ) ) except AddressLookupError : return False
def get_battery_level ( self ) : """Reads the battery level descriptor on the device . Returns : int . If successful this will be a positive value representing the current battery level as a percentage . On error , - 1 is returned ."""
battery_level = self . get_characteristic_handle_from_uuid ( UUID_BATTERY_LEVEL ) if battery_level is None : logger . warn ( 'Failed to find handle for battery level' ) return None level = self . dongle . _read_attribute ( self . conn_handle , battery_level ) if level is None : return - 1 return ord ( level...
def adjust_jobs_priority ( self , high_value_jobs , priority = 1 ) : """For every job priority determine if we need to increase or decrease the job priority Currently , high value jobs have a priority of 1 and a timeout of 0."""
# Only job priorities that don ' t have an expiration date ( 2 weeks for new jobs or year 2100 # for jobs update via load _ preseed ) are updated for jp in JobPriority . objects . filter ( expiration_date__isnull = True ) : if jp . unique_identifier ( ) not in high_value_jobs : if jp . priority != SETA_LOW_...
def export_kml_file ( self ) : """Generate KML element tree from ` ` Placemarks ` ` . Returns : etree . ElementTree : KML element tree depicting ` ` Placemarks ` `"""
kml = create_elem ( 'kml' ) kml . Document = create_elem ( 'Document' ) for place in sorted ( self . values ( ) , key = lambda x : x . name ) : kml . Document . append ( place . tokml ( ) ) return etree . ElementTree ( kml )
def get_values ( js_dict , value = 'value' ) : """Get values from input data . Args : js _ dict ( dict ) : dictionary containing dataset data and metadata . value ( string , optional ) : name of the value column . Defaults to ' value ' . Returns : values ( list ) : list of dataset values ."""
values = js_dict [ value ] if type ( values ) is list : if type ( values [ 0 ] ) is not dict or tuple : return values # being not a list of dicts or tuples leaves us with a dict . . . values = { int ( key ) : value for ( key , value ) in values . items ( ) } if js_dict . get ( 'size' ) : max_val = np . ...
def plot_pdf ( self , names = None , Nbest = 5 , lw = 2 ) : """Plots Probability density functions of the distributions : param str , list names : names can be a single distribution name , or a list of distribution names , or kept as None , in which case , the first Nbest distribution will be taken ( default ...
assert Nbest > 0 if Nbest > len ( self . distributions ) : Nbest = len ( self . distributions ) if isinstance ( names , list ) : for name in names : pylab . plot ( self . x , self . fitted_pdf [ name ] , lw = lw , label = name ) elif names : pylab . plot ( self . x , self . fitted_pdf [ names ] , lw...
def show ( self ) : """Prints the content of this method to stdout . This will print the method signature and the decompiled code ."""
args , ret = self . method . get_descriptor ( ) [ 1 : ] . split ( ")" ) if self . code : # We patch the descriptor here and add the registers , if code is available args = args . split ( " " ) reg_len = self . code . get_registers_size ( ) nb_args = len ( args ) start_reg = reg_len - nb_args args = ...
def fill ( args ) : """% prog fill frag _ reads _ corr . fastb Run FillFragments on ` frag _ reads _ corr . fastb ` ."""
p = OptionParser ( fill . __doc__ ) p . add_option ( "--stretch" , default = 3 , type = "int" , help = "MAX_STRETCH to pass to FillFragments [default: %default]" ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) fastb , = args assert fastb == "frag...
def transform_points ( points , matrix , translate = True ) : """Returns points , rotated by transformation matrix If points is ( n , 2 ) , matrix must be ( 3,3) if points is ( n , 3 ) , matrix must be ( 4,4) Parameters points : ( n , d ) float Points where d is 2 or 3 matrix : ( 3,3 ) or ( 4,4 ) float ...
points = np . asanyarray ( points , dtype = np . float64 ) # no points no cry if len ( points ) == 0 : return points . copy ( ) matrix = np . asanyarray ( matrix , dtype = np . float64 ) if ( len ( points . shape ) != 2 or ( points . shape [ 1 ] + 1 != matrix . shape [ 1 ] ) ) : raise ValueError ( 'matrix shape...
def parse ( cls , request : web . Request ) -> AuthWidgetData : """Parse request as Telegram auth widget data . : param request : : return : : obj : ` AuthWidgetData ` : raise : : obj : ` aiohttp . web . HTTPBadRequest `"""
try : query = dict ( request . query ) query [ 'id' ] = int ( query [ 'id' ] ) query [ 'auth_date' ] = int ( query [ 'auth_date' ] ) widget = AuthWidgetData ( ** query ) except ( ValueError , KeyError ) : raise web . HTTPBadRequest ( text = 'Invalid auth data' ) else : return widget
def rotate_v1 ( array , k ) : """Rotate the entire array ' k ' times T ( n ) - O ( nk ) : type array : List [ int ] : type k : int : rtype : void Do not return anything , modify array in - place instead ."""
array = array [ : ] n = len ( array ) for i in range ( k ) : # unused variable is not a problem temp = array [ n - 1 ] for j in range ( n - 1 , 0 , - 1 ) : array [ j ] = array [ j - 1 ] array [ 0 ] = temp return array
def main ( ) : """Command - line tool to inspect model embeddings ."""
setup_main_logger ( file_logging = False ) params = argparse . ArgumentParser ( description = 'Shows nearest neighbours of input tokens in the embedding space.' ) params . add_argument ( '--model' , '-m' , required = True , help = 'Model folder to load config from.' ) params . add_argument ( '--checkpoint' , '-c' , req...
def sequencetyper ( self ) : """Determines the sequence type of each strain based on comparisons to sequence type profiles"""
for sample in self . metadata : if sample . general . bestassemblyfile != 'NA' : if type ( sample [ self . analysistype ] . allelenames ) == list : # Initialise variables header = 0 # Iterate through the genomes # for sample in self . metadata : genome = sampl...
def release_all ( self , keys : Sequence [ str ] ) -> Set [ str ] : """Releases all of the given keys . : param keys : the keys to release : return : the names of the keys that were released"""
released : List [ str ] = [ ] for key in keys : released . append ( self . release ( key ) ) return set ( filter ( None , released ) )
def read ( self , symbol , as_of = None , date_range = None , from_version = None , allow_secondary = None , ** kwargs ) : """Read data for the named symbol . Returns a VersionedItem object with a data and metdata element ( as passed into write ) . Parameters symbol : ` str ` symbol name for the item as _...
try : read_preference = self . _read_preference ( allow_secondary ) _version = self . _read_metadata ( symbol , as_of = as_of , read_preference = read_preference ) return self . _do_read ( symbol , _version , from_version , date_range = date_range , read_preference = read_preference , ** kwargs ) except ( O...
def single ( fun , name , test = None , queue = False , ** kwargs ) : '''Execute a single state function with the named kwargs , returns False if insufficient data is sent to the command By default , the values of the kwargs will be parsed as YAML . So , you can specify lists values , or lists of single entry...
conflict = _check_queue ( queue , kwargs ) if conflict is not None : return conflict comps = fun . split ( '.' ) if len ( comps ) < 2 : __context__ [ 'retcode' ] = salt . defaults . exitcodes . EX_STATE_COMPILER_ERROR return 'Invalid function passed' kwargs . update ( { 'state' : comps [ 0 ] , 'fun' : comps...
def reynolds ( target , u0 , b , temperature = 'pore.temperature' ) : r"""Uses exponential model by Reynolds [ 1 ] for the temperature dependance of shear viscosity Parameters target : OpenPNM Object The object for which these values are being calculated . This controls the length of the calculated array ...
value = u0 * sp . exp ( b * target [ temperature ] ) return value
def _delete_example ( self , request ) : """Deletes the specified example . Args : request : A request that should contain ' index ' . Returns : An empty response ."""
index = int ( request . args . get ( 'index' ) ) if index >= len ( self . examples ) : return http_util . Respond ( request , { 'error' : 'invalid index provided' } , 'application/json' , code = 400 ) del self . examples [ index ] self . updated_example_indices = set ( [ i if i < index else i - 1 for i in self . up...
def write_file ( file_path , content ) : """Write file at the specified path with content . If file exists , it will be overwritten ."""
handler = open ( file_path , 'w+' ) handler . write ( content ) handler . close ( )
def interface_type ( self , ift ) : """Set the CoRE Link Format if attribute of the resource . : param ift : the CoRE Link Format if attribute"""
if not isinstance ( ift , str ) : ift = str ( ift ) self . _attributes [ "if" ] = ift
def find_response_component ( self , api_id = None , signature_id = None ) : '''Find one or many repsonse components . Args : api _ id ( str ) : Api id associated with the component ( s ) to be retrieved . signature _ id ( str ) : Signature id associated with the component ( s ) to be retrieved . Returns : ...
if not api_id and not signature_id : raise ValueError ( 'At least one of api_id and signature_id is required' ) components = list ( ) if self . response_data : for component in self . response_data : if ( api_id and component [ 'api_id' ] ) == api_id or ( signature_id and component [ 'signature_id' ] ==...
def write ( self , data ) : """Write data to the transport . This is an invalid operation if the stream is not writable , that is , if it is closed . During TLS negotiation , the data is buffered ."""
if not isinstance ( data , ( bytes , bytearray , memoryview ) ) : raise TypeError ( 'data argument must be byte-ish (%r)' , type ( data ) ) if not self . _state . is_writable or self . _closing : raise self . _invalid_state ( "write() called" ) if not data : return if not self . _buffer : self . _loop ....
def get_permissions_assignments ( self , obj = None , permission = None ) : """: param permission : return only roles having this permission : returns : an dict where keys are ` permissions ` and values ` roles ` iterable ."""
session = None if obj is not None : assert isinstance ( obj , Entity ) session = object_session ( obj ) if obj . id is None : obj = None if session is None : session = db . session ( ) pa = session . query ( PermissionAssignment . permission , PermissionAssignment . role ) . filter ( PermissionA...
def write_command ( self , request_id , msg , docs ) : """A proxy for SocketInfo . write _ command that handles event publishing ."""
if self . publish : duration = datetime . datetime . now ( ) - self . start_time self . _start ( request_id , docs ) start = datetime . datetime . now ( ) try : reply = self . sock_info . write_command ( request_id , msg ) if self . publish : duration = ( datetime . datetime . now ( ) - star...
def nll ( data , model ) : """Negative log likelihood given data and a model Parameters Returns float Negative log likelihood Examples > > > import macroeco . models as md > > > import macroeco . compare as comp > > > # Generate random data > > > rand _ samp = md . logser . rvs ( p = 0.9 , size = ...
try : log_lik_vals = model . logpmf ( data ) except : log_lik_vals = model . logpdf ( data ) return - np . sum ( log_lik_vals )
def convert_cmus_output ( self , cmus_output ) : """Change the newline separated string of output data into a dictionary which can then be used to replace the strings in the config format . cmus _ output : A string with information about cmus that is newline seperated . Running cmus - remote - Q in a termin...
cmus_output = cmus_output . split ( '\n' ) cmus_output = [ x . replace ( 'tag ' , '' ) for x in cmus_output if not x in '' ] cmus_output = [ x . replace ( 'set ' , '' ) for x in cmus_output ] status = { } partitioned = ( item . partition ( ' ' ) for item in cmus_output ) status = { item [ 0 ] : item [ 2 ] for item in p...
def plot ( self , normed = False , scale_errors_by = 1.0 , scale_histogram_by = 1.0 , plt = plt , errors = False , ** kwargs ) : """Plots the histogram with Poisson ( sqrt ( n ) ) error bars - scale _ errors _ by multiplies the error bars by its argument - scale _ histogram _ by multiplies the histogram AND the...
if not CAN_PLOT : raise ValueError ( "matplotlib did not import, so can't plot your histogram..." ) if errors : kwargs . setdefault ( 'linestyle' , 'none' ) yerr = np . sqrt ( self . histogram ) if normed : y = self . normalized_histogram yerr /= self . n else : y = self . hi...
def next ( self , vRef ) : """Get the reference number of the vdata following a given vdata . Args : : vRef Reference number of the vdata preceding the one we require . Set to - 1 to get the first vdata in the HDF file . Knowing its reference number , the vdata can then be opened ( attached ) by passing...
num = _C . VSgetid ( self . _hdf_inst . _id , vRef ) _checkErr ( 'next' , num , 'cannot get next vdata' ) return num
def searchNs ( self , node , nameSpace ) : """Search a Ns registered under a given name space for a document . recurse on the parents until it finds the defined namespace or return None otherwise . @ nameSpace can be None , this is a search for the default namespace . We don ' t allow to cross entities boun...
if node is None : node__o = None else : node__o = node . _o ret = libxml2mod . xmlSearchNs ( self . _o , node__o , nameSpace ) if ret is None : raise treeError ( 'xmlSearchNs() failed' ) __tmp = xmlNs ( _obj = ret ) return __tmp
def _get_average_time_stamp ( action_set ) : """Return the average time stamp for the rules in this action set ."""
# This is the average value of the iteration counter upon the most # recent update of each rule in this action set . total_time_stamps = sum ( rule . time_stamp * rule . numerosity for rule in action_set ) total_numerosity = sum ( rule . numerosity for rule in action_set ) return total_time_stamps / ( total_numerosity ...
def _new_name ( method , old_name ) : """Return a method with a deprecation warning ."""
# Looks suspiciously like a decorator , but isn ' t ! @ wraps ( method ) def _method ( * args , ** kwargs ) : warnings . warn ( "method '{}' has been deprecated, please rename to '{}'" . format ( old_name , method . __name__ ) , DeprecationWarning , ) return method ( * args , ** kwargs ) deprecated_msg = """ ...
def convert_unicode_2_utf8 ( input ) : '''Return a copy of ` input ` with every str component encoded from unicode to utf - 8.'''
if isinstance ( input , dict ) : try : # python - 2.6 return dict ( ( convert_unicode_2_utf8 ( key ) , convert_unicode_2_utf8 ( value ) ) for key , value in input . iteritems ( ) ) except AttributeError : # since python - 2.7 cf . http : / / stackoverflow . com / a / 1747827 # [ the ugly eval ( ' . ...
def _dataToString ( self , data ) : """Conversion function used to convert the ( default ) data to the display value ."""
if self . specialValueText is not None and data == self . minValue : return self . specialValueText else : return "{}{:.{}f}{}" . format ( self . prefix , data , self . decimals , self . suffix )
def build_path ( operation , ns ) : """Build a path URI for an operation ."""
try : return ns . url_for ( operation , _external = False ) except BuildError as error : # we are missing some URI path parameters uri_templates = { argument : "{{{}}}" . format ( argument ) for argument in error . suggested . arguments } # flask will sometimes try to quote ' { ' and ' } ' characters re...
def _get_base_command ( self ) : """Returns the base command plus command - line options . Handles everything up to and including the classpath . The positional training parameters are added by the _ input _ handler _ decorator method ."""
cd_command = '' . join ( [ 'cd ' , str ( self . WorkingDir ) , ';' ] ) jvm_command = "java" jvm_args = self . _commandline_join ( [ self . Parameters [ k ] for k in self . _jvm_parameters ] ) cp_args = '-cp "%s" %s' % ( self . _get_jar_fp ( ) , self . TrainingClass ) command_parts = [ cd_command , jvm_command , jvm_arg...
def checktype ( self , val , kind , ** kargs ) : """Raise TypeError if val does not satisfy kind ."""
if not isinstance ( val , kind ) : raise TypeError ( 'Expected {}; got {}' . format ( self . str_kind ( kind ) , self . str_valtype ( val ) ) )
def solve ( graph , debug = False , anim = None ) : # TODO : check docstring """Do MV routing for given nodes in ` graph ` . Translate data from node objects to appropriate format before . Args graph : : networkx : ` NetworkX Graph Obj < > ` NetworkX graph object with nodes debug : bool , defaults to Fals...
# TODO : Implement debug mode ( pass to solver ) to get more information while routing ( print routes , draw network , . . ) # translate DING0 graph to routing specs specs = ding0_graph_to_routing_specs ( graph ) # create routing graph using specs RoutingGraph = Graph ( specs ) timeout = 30000 # create solver objects s...
def _sha256 ( path ) : """Calculate the sha256 hash of the file at path ."""
sha256hash = hashlib . sha256 ( ) chunk_size = 8192 with open ( path , "rb" ) as buff : while True : buffer = buff . read ( chunk_size ) if not buffer : break sha256hash . update ( buffer ) return sha256hash . hexdigest ( )
def _pecl ( command , defaults = False ) : '''Execute the command passed with pecl'''
cmdline = 'pecl {0}' . format ( command ) if salt . utils . data . is_true ( defaults ) : cmdline = 'yes ' "''" + ' | ' + cmdline ret = __salt__ [ 'cmd.run_all' ] ( cmdline , python_shell = True ) if ret [ 'retcode' ] == 0 : return ret [ 'stdout' ] else : log . error ( 'Problem running pecl. Is php-pear ins...
def asciigraph ( self , values = None , max_height = None , max_width = None , label = False ) : '''Accepts a list of y values and returns an ascii graph Optionally values can also be a dictionary with a key of timestamp , and a value of value . InGraphs returns data in this format for example .'''
result = '' border_fill_char = '*' start_ctime = None end_ctime = None if not max_width : max_width = 180 # If this is a dict of timestamp - > value , sort the data , store the start / end time , and convert values to a list of values if isinstance ( values , dict ) : time_series_sorted = sorted ( list ( values...
def save_file ( self , filename = 'StockChart' ) : """save htmlcontent as . html file"""
filename = filename + '.html' with open ( filename , 'w' ) as f : # self . buildhtml ( ) f . write ( self . htmlcontent ) f . closed
def get_vep_info ( vep_string , vep_header ) : """Make the vep annotations into a dictionaries A vep dictionary will have the vep column names as keys and the vep annotations as values . The dictionaries are stored in a list Args : vep _ string ( string ) : A string with the CSQ annotation vep _ header ...
vep_annotations = [ dict ( zip ( vep_header , vep_annotation . split ( '|' ) ) ) for vep_annotation in vep_string . split ( ',' ) ] return vep_annotations
def computeStatistics ( tped , tfam , snps ) : """Computes the completion and concordance of each SNPs . : param tped : a representation of the ` ` tped ` ` . : param tfam : a representation of the ` ` tfam ` ` : param snps : the position of the duplicated markers in the ` ` tped ` ` . : type tped : numpy ....
# The completion data type completion = np . array ( [ [ 0 for i in xrange ( len ( tped ) ) ] , [ 0 for i in xrange ( len ( tped ) ) ] ] ) # The concordance data type concordance = { } for snpID in snps . keys ( ) : nbDup = len ( snps [ snpID ] ) concordance [ snpID ] = [ np . asmatrix ( np . zeros ( ( nbDup , ...
def parse_editable ( editable_req , default_vcs = None ) : """Parses svn + http : / / blahblah @ rev # egg = Foobar into a requirement ( Foobar ) and a URL"""
url = editable_req if os . path . isdir ( url ) and os . path . exists ( os . path . join ( url , 'setup.py' ) ) : # Treating it as code that has already been checked out url = path_to_url ( url ) if url . lower ( ) . startswith ( 'file:' ) : return None , url for version_control in vcs : if url . lower ( )...
def average_hudson_fst ( ac1 , ac2 , blen ) : """Estimate average Fst between two populations and standard error using the block - jackknife . Parameters ac1 : array _ like , int , shape ( n _ variants , n _ alleles ) Allele counts array from the first population . ac2 : array _ like , int , shape ( n _ v...
# calculate per - variant values num , den = hudson_fst ( ac1 , ac2 , fill = np . nan ) # calculate overall estimate fst = np . nansum ( num ) / np . nansum ( den ) # compute the numerator and denominator within each block num_bsum = moving_statistic ( num , statistic = np . nansum , size = blen ) den_bsum = moving_sta...
def from_json ( cls , data ) : """Create a data type from a dictionary . Args : data : Data as a dictionary . " name " : data type name of the data type as a string " data _ type " : the class name of the data type as a string " base _ unit " : the base unit of the data type"""
assert 'name' in data , 'Required keyword "name" is missing!' assert 'data_type' in data , 'Required keyword "data_type" is missing!' if cls . _type_enumeration is None : cls . _type_enumeration = _DataTypeEnumeration ( import_modules = False ) if data [ 'data_type' ] == 'GenericType' : assert 'base_unit' in da...