signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_tags ( self , project , repository , filter = '' , limit = 1000 , order_by = None , start = 0 ) : """Retrieve the tags matching the supplied filterText param . The authenticated user must have REPO _ READ permission for the context repository to call this resource . : param project : : param repositor...
url = 'rest/api/1.0/projects/{project}/repos/{repository}/tags' . format ( project = project , repository = repository ) params = { } if start : params [ 'start' ] = start if limit : params [ 'limit' ] = limit if filter : params [ 'filter' ] = filter if order_by : params [ 'orderBy' ] = order_by result ...
def nextId ( self ) : """Returns the next id for this page . By default , it will provide the next id from the wizard , but this method can be overloaded to create a custom path . If - 1 is returned , then it will be considered the final page . : return < int >"""
if self . _nextId is not None : return self . _nextId wizard = self . wizard ( ) curr_id = wizard . currentId ( ) all_ids = wizard . pageIds ( ) try : return all_ids [ all_ids . index ( curr_id ) + 1 ] except IndexError : return - 1
def title ( self , value = None ) : """Get or set the document ' s title from / in the metadata No arguments : Get the document ' s title from metadata Argument : Set the document ' s title in metadata"""
if not ( value is None ) : if ( self . metadatatype == "native" ) : self . metadata [ 'title' ] = value else : self . _title = value if ( self . metadatatype == "native" ) : if 'title' in self . metadata : return self . metadata [ 'title' ] else : return None else : r...
def disconnect_async ( self , connection_id , callback ) : """Asynchronously disconnect from a device that has previously been connected Args : connection _ id ( int ) : A unique identifier for this connection on the DeviceManager that owns this adapter . callback ( callable ) : A function called as callback ...
try : context = self . connections . get_context ( connection_id ) except ArgumentError : callback ( connection_id , self . id , False , "Could not find connection information" ) return self . connections . begin_disconnection ( connection_id , callback , self . get_config ( 'default_timeout' ) ) self . bab...
def paintGroup ( self , painter ) : """Paints this item as the group look . : param painter | < QPainter >"""
# generate the rect rect = self . rect ( ) padding = self . padding ( ) gantt = self . scene ( ) . ganttWidget ( ) cell_w = gantt . cellWidth ( ) cell_h = gantt . cellHeight ( ) x = 0 y = self . padding ( ) w = rect . width ( ) h = rect . height ( ) - ( padding + 1 ) # grab the color options color = self . color ( ) al...
def undeploy_lambda_alb ( self , lambda_name ) : """The ` zappa undeploy ` functionality for ALB infrastructure ."""
print ( "Undeploying ALB infrastructure..." ) # Locate and delete alb / lambda permissions try : # https : / / boto3 . amazonaws . com / v1 / documentation / api / latest / reference / services / lambda . html # Lambda . Client . remove _ permission self . lambda_client . remove_permission ( FunctionName = lambda_n...
def paintEvent ( self , event ) : """Override Qt method"""
painter = QPainter ( self ) painter . setRenderHint ( QPainter . Antialiasing ) # Decoration painter . fillPath ( self . path_current , QBrush ( self . color ) ) painter . strokePath ( self . path_decoration , QPen ( self . color_decoration , self . stroke_decoration ) )
def parse_params ( self , core_params ) : """Goes through a set of parameters , extracting information about each . : param core _ params : The collection of parameters : type core _ params : A collection of ` ` < botocore . parameters . Parameter > ` ` subclasses : returns : A list of dictionaries"""
params = [ ] for core_param in core_params : params . append ( self . parse_param ( core_param ) ) return params
def render_pdf_file_to_image_files ( pdf_file_name , output_filename_root , program_to_use ) : """Render all the pages of the PDF file at pdf _ file _ name to image files with path and filename prefix given by output _ filename _ root . Any directories must have already been created , and the calling program is...
res_x = str ( args . resX ) res_y = str ( args . resY ) if program_to_use == "Ghostscript" : if ex . system_os == "Windows" : # Windows PIL is more likely to know BMP ex . render_pdf_file_to_image_files__ghostscript_bmp ( pdf_file_name , output_filename_root , res_x , res_y ) else : # Linux and Cygwin s...
def get_departments_by_college ( college ) : """Returns a list of restclients . Department models , for the passed College model ."""
url = "{}?{}" . format ( dept_search_url_prefix , urlencode ( { "college_abbreviation" : college . label } ) ) return _json_to_departments ( get_resource ( url ) , college )
def _departmentsVoc ( self ) : """Vocabulary of available departments"""
query = { "portal_type" : "Department" , "is_active" : True } results = api . search ( query , "bika_setup_catalog" ) items = map ( lambda dept : ( api . get_uid ( dept ) , api . get_title ( dept ) ) , results ) dept_uids = map ( api . get_uid , results ) # Currently assigned departments depts = self . getDepartments (...
def create_app ( self , args ) : """创建应用 在指定区域创建一个新应用 , 所属应用为当前请求方 。 Args : - args : 请求参数 ( json ) , 参考 http : / / kirk - docs . qiniu . com / apidocs / Returns : - result 成功返回所创建的应用信息 , 若失败则返回None - ResponseInfo 请求的Response信息"""
url = '{0}/v3/apps' . format ( self . host ) return http . _post_with_qiniu_mac ( url , args , self . auth )
def convert_npdist ( self , node ) : """Convert the given node into a Nodal Plane Distribution . : param node : a nodalPlaneDist node : returns : a : class : ` openquake . hazardlib . geo . NodalPlane ` instance"""
with context ( self . fname , node ) : npdist = [ ] for np in node . nodalPlaneDist : prob , strike , dip , rake = ( np [ 'probability' ] , np [ 'strike' ] , np [ 'dip' ] , np [ 'rake' ] ) npdist . append ( ( prob , geo . NodalPlane ( strike , dip , rake ) ) ) if not self . spinning_floating...
def _parse_date_greek ( dateString ) : '''Parse a string according to a Greek 8 - bit date format .'''
m = _greek_date_format_re . match ( dateString ) if not m : return wday = _greek_wdays [ m . group ( 1 ) ] month = _greek_months [ m . group ( 3 ) ] rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % { 'wday' : wday , 'day' : m . group ( 2 ) , 'month' : month , 'year' ...
def _new_controller ( self , addr , port ) : """Get an uid for your controller . : param addr : Address of the controller : param port : Port of the controller : type addr : str : type port : int : return : Unique id of the controller : rtype : str"""
for uid , controller in self . controllers . items ( ) : if controller [ 0 ] == addr : # duplicate address . sending the uid again # print ( ' / uid / { } = > { } : { } ' . format ( uid , addr , port ) ) self . sock . sendto ( '/uid/{}' . format ( uid ) . encode ( 'utf-8' ) , ( addr , port ) ) r...
def constrain_norms ( self , srcNames , cov_scale = 1.0 ) : """Constrain the normalizations of one or more sources by adding gaussian priors with sigma equal to the parameter error times a scaling factor ."""
# Get the covariance matrix for name in srcNames : par = self . like . normPar ( name ) err = par . error ( ) val = par . getValue ( ) if par . error ( ) == 0.0 or not par . isFree ( ) : continue self . add_gauss_prior ( name , par . getName ( ) , val , err * cov_scale )
def _remove_boring_lines ( text ) : """Remove lines that do not start with a letter or a quote . From inspecting the data , this seems to leave in most prose and remove most weird stuff . Args : text : a string Returns : a string"""
lines = text . split ( "\n" ) filtered = [ line for line in lines if re . match ( "[a-zA-z\"\']" , line ) ] return "\n" . join ( filtered )
def create_matching_kernel ( source_psf , target_psf , window = None ) : """Create a kernel to match 2D point spread functions ( PSF ) using the ratio of Fourier transforms . Parameters source _ psf : 2D ` ~ numpy . ndarray ` The source PSF . The source PSF should have higher resolution ( i . e . narrower...
# inputs are copied so that they are not changed when normalizing source_psf = np . copy ( np . asanyarray ( source_psf ) ) target_psf = np . copy ( np . asanyarray ( target_psf ) ) if source_psf . shape != target_psf . shape : raise ValueError ( 'source_psf and target_psf must have the same shape ' '(i.e. register...
def position_after_whitespace ( body , start_position ) : # type : ( str , int ) - > int """Reads from body starting at start _ position until it finds a non - whitespace or commented character , then returns the position of that character for lexing ."""
body_length = len ( body ) position = start_position while position < body_length : code = char_code_at ( body , position ) if code in ignored_whitespace_characters : position += 1 elif code == 35 : # # , skip comments position += 1 while position < body_length : code = c...
def get ( self , conn_name , default = None , ** kwargs ) : """returns the specified connection args : conn _ name : the name of the connection"""
if isinstance ( conn_name , RdfwConnections ) : return conn_name try : return self . conns [ conn_name ] except KeyError : if default : return self . get ( default , ** kwargs ) raise LookupError ( "'%s' connection has not been set" % conn_name )
def from_passwd ( uid_min = None , uid_max = None ) : """Create collection from locally discovered data , e . g . / etc / passwd ."""
import pwd users = Users ( oktypes = User ) passwd_list = pwd . getpwall ( ) if not uid_min : uid_min = UID_MIN if not uid_max : uid_max = UID_MAX sudoers_entries = read_sudoers ( ) for pwd_entry in passwd_list : if uid_min <= pwd_entry . pw_uid <= uid_max : user = User ( name = text_type ( pwd_entr...
def sheet2matrixidx ( self , x , y ) : """Convert a point ( x , y ) in sheet coordinates to the integer row and column index of the matrix cell in which that point falls , given a bounds and density . Returns ( row , column ) . Note that if coordinates along the right or bottom boundary are passed into this...
r , c = self . sheet2matrix ( x , y ) r = np . floor ( r ) c = np . floor ( c ) if hasattr ( r , 'astype' ) : return r . astype ( int ) , c . astype ( int ) else : return int ( r ) , int ( c )
def update_object ( objref , data , ** api_opts ) : '''Update raw infoblox object . This is a low level api call . CLI Example : . . code - block : : bash salt - call infoblox . update _ object objref = [ ref _ of _ object ] data = { }'''
if '__opts__' in globals ( ) and __opts__ [ 'test' ] : return { 'Test' : 'Would attempt to update object: {0}' . format ( objref ) } infoblox = _get_infoblox ( ** api_opts ) return infoblox . update_object ( objref , data )
def git_log_iterator ( path ) : """yield commits using git log - - < dir >"""
N = 10 count = 0 while True : lines = _run_git_command_lines ( [ 'log' , '--oneline' , '-n' , str ( N ) , '--skip' , str ( count ) , '--' , '.' ] , cwd = path ) for line in lines : sha = line . split ( ' ' , 1 ) [ 0 ] count += 1 yield sha if len ( lines ) < N : break
def evaluate ( self , source ) : """Evaluates the board state from ` source ` and returns an iterable of Actions as a result ."""
ret = self . check ( source ) if self . _neg : ret = not ret if ret : if self . _if : return self . _if elif self . _else : return self . _else
def load_frequencyseries ( path , group = None ) : """Load a FrequencySeries from a . hdf , . txt or . npy file . The default data types will be double precision floating point . Parameters path : string source file path . Must end with either . npy or . txt . group : string Additional name for internal...
ext = _os . path . splitext ( path ) [ 1 ] if ext == '.npy' : data = _numpy . load ( path ) elif ext == '.txt' : data = _numpy . loadtxt ( path ) elif ext == '.hdf' : key = 'data' if group is None else group f = h5py . File ( path , 'r' ) data = f [ key ] [ : ] series = FrequencySeries ( data , ...
def _get_fis_parameters ( request , geometry ) : """Returns parameters dictionary for FIS request . : param request : OGC - type request with specified bounding box , cloud coverage for specific product . : type request : OgcRequest or GeopediaRequest : param geometry : list of bounding boxes or geometries ...
date_interval = parse_time_interval ( request . time ) params = { 'CRS' : CRS . ogc_string ( geometry . crs ) , 'LAYER' : request . layer , 'RESOLUTION' : request . resolution , 'TIME' : '{}/{}' . format ( date_interval [ 0 ] , date_interval [ 1 ] ) } if not isinstance ( geometry , ( BBox , Geometry ) ) : raise Val...
def primary_mrna ( entrystream , parenttype = 'gene' ) : """Select a single mRNA as a representative for each protein - coding gene . The primary mRNA is the one with the longest translation product . In cases where multiple isoforms have the same translated length , the feature ID is used for sorting . Thi...
for entry in entrystream : if not isinstance ( entry , tag . Feature ) : yield entry continue for parent in tag . select . features ( entry , parenttype , traverse = True ) : mrnas = [ f for f in parent . children if f . type == 'mRNA' ] if len ( mrnas ) == 0 : contin...
def parse ( self , method , endpoint , body ) : '''calls parse on list or detail'''
if isinstance ( body , dict ) : # request body was already parsed return body if endpoint == 'list' : return self . parse_list ( body ) return self . parse_detail ( body )
def setExecutorEnv ( self , key = None , value = None , pairs = None ) : """Set an environment variable to be passed to executors ."""
if ( key is not None and pairs is not None ) or ( key is None and pairs is None ) : raise Exception ( "Either pass one key-value pair or a list of pairs" ) elif key is not None : self . set ( "spark.executorEnv." + key , value ) elif pairs is not None : for ( k , v ) in pairs : self . set ( "spark.e...
def detect_mode ( cls , ** params ) : """Detect which listing mode of the given params . : params kwargs params : the params : return : one of the available modes : rtype : str : raises ValueError : if multiple modes are detected"""
modes = [ ] for mode in cls . modes : if params . get ( mode ) is not None : modes . append ( mode ) if len ( modes ) > 1 : error_message = 'ambiguous mode, must be one of {}' modes_csv = ', ' . join ( list ( cls . modes ) ) raise ValueError ( error_message . format ( modes_csv ) ) return modes ...
def zero2d ( self ) : """get an 2D instance of self with all zeros Returns Matrix : Matrix"""
return type ( self ) ( x = np . atleast_2d ( np . zeros ( ( self . shape [ 0 ] , self . shape [ 1 ] ) ) ) , row_names = self . row_names , col_names = self . col_names , isdiagonal = False )
def _init_update_po_files ( self , domains ) : """Update or initialize the ` . po ` translation files"""
for language in settings . TRANSLATIONS : for domain , options in domains . items ( ) : if language == options [ 'default' ] : continue # Default language of the domain doesn ' t need translations if os . path . isfile ( _po_path ( language , domain ) ) : # If the translation...
def exists ( self , path = None , client_kwargs = None , assume_exists = None ) : """Return True if path refers to an existing path . Args : path ( str ) : Path or URL . client _ kwargs ( dict ) : Client arguments . assume _ exists ( bool or None ) : This value define the value to return in the case there...
try : self . head ( path , client_kwargs ) except ObjectNotFoundError : return False except ObjectPermissionError : if assume_exists is None : raise return assume_exists return True
def normalVectorRDD ( sc , numRows , numCols , numPartitions = None , seed = None ) : """Generates an RDD comprised of vectors containing i . i . d . samples drawn from the standard normal distribution . : param sc : SparkContext used to create the RDD . : param numRows : Number of Vectors in the RDD . : pa...
return callMLlibFunc ( "normalVectorRDD" , sc . _jsc , numRows , numCols , numPartitions , seed )
def getsize ( o_file ) : """get the size , either by seeeking to the end ."""
startpos = o_file . tell ( ) o_file . seek ( 0 ) o_file . seek ( 0 , SEEK_END ) size = o_file . tell ( ) o_file . seek ( startpos ) return size
def send_captcha_result ( self , stc_id , captcha_result ) : """In case a captcha was encountered , solves it using an element ID and a response parameter . The stc _ id can be extracted from a CaptchaElement , and the captcha result needs to be extracted manually with a browser . Please see solve _ captcha _ w...
log . info ( "[+] Trying to solve a captcha with result: '{}'" . format ( captcha_result ) ) return self . _send_xmpp_element ( login . CaptchaSolveRequest ( stc_id , captcha_result ) )
def init_dispatcher_logger ( ) : """Initialize dispatcher logging configuration"""
logger_file_path = 'dispatcher.log' if dispatcher_env_vars . NNI_LOG_DIRECTORY is not None : logger_file_path = os . path . join ( dispatcher_env_vars . NNI_LOG_DIRECTORY , logger_file_path ) init_logger ( logger_file_path , dispatcher_env_vars . NNI_LOG_LEVEL )
def ConsultarBonificacionesPenalizaciones ( self , sep = "||" ) : "Retorna un listado de bonificaciones / penalizaciones con código y descripción"
ret = self . client . consultarBonificacionesPenalizaciones ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit' : self . Cuit , } , ) [ 'respuesta' ] self . __analizar_errores ( ret ) self . XmlResponse = self . client . xml_response array = ret . get ( 'tipo' , [ ] ) if sep is None : # sin separador , de...
def get_favorite_radio_shows ( self , * args , ** kwargs ) : """Convenience method for ` get _ music _ library _ information ` with ` ` search _ type = ' radio _ stations ' ` ` . For details of other arguments , see ` that method < # soco . music _ library . MusicLibrary . get _ music _ library _ information ...
args = tuple ( [ 'radio_shows' ] + list ( args ) ) return self . get_music_library_information ( * args , ** kwargs )
def check ( text ) : """Suggest the preferred forms ."""
err = "misc.waxed" msg = u"The modifier following 'waxed' must be an adj.: '{}' is correct" waxes = [ "wax" , "waxes" , "waxed" , "waxing" ] modifiers = [ ( "ebullient" , "ebulliently" ) , ( "ecstatic" , "ecstatically" ) , ( "eloquent" , "eloquently" ) , ( "enthusiastic" , "enthusiastically" ) , ( "euphoric" , "euphori...
def filter_event ( tag , data , defaults ) : '''Accept a tag , a dict and a list of default keys to return from the dict , and check them against the cloud configuration for that tag'''
ret = { } keys = [ ] use_defaults = True for ktag in __opts__ . get ( 'filter_events' , { } ) : if tag != ktag : continue keys = __opts__ [ 'filter_events' ] [ ktag ] [ 'keys' ] use_defaults = __opts__ [ 'filter_events' ] [ ktag ] . get ( 'use_defaults' , True ) if use_defaults is False : defaul...
def read_paraphrase_file ( filename ) : '''Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures . Arguments : - ` filename ` :'''
with open ( filename , 'rb' ) as input_file : doc = etree . parse ( input_file ) assert doc . getroot ( ) . tag == 'wiktionaryParaphrases' paraphrases = [ ] for child in doc . getroot ( ) : if child . tag == 'wiktionaryParaphrase' : paraphrase = child warn_attribs ( '' , paraphrase , PARAPHRASE_...
def resolve_outputs_due_to_exception ( resolvers : Dict [ str , Resolver ] , exn : Exception ) : """Resolves all outputs with resolvers exceptionally , using the given exception as the reason why the resolver has failed to resolve . : param resolvers : Resolvers associated with a resource ' s outputs . : para...
for key , resolve in resolvers . items ( ) : log . debug ( f"sending exception to resolver for {key}" ) resolve ( None , False , exn )
def to_data ( value ) : """Standardize data types . Converts PyTorch tensors to Numpy arrays , and Numpy scalars to Python scalars ."""
# TODO : Use get _ framework ( ) for better detection . if value . __class__ . __module__ . startswith ( "torch" ) : import torch if isinstance ( value , torch . nn . parameter . Parameter ) : value = value . data if isinstance ( value , torch . Tensor ) : if value . requires_grad : ...
def encrypt_ige ( plain_text , key , iv ) : """Encrypts the given text in 16 - bytes blocks by using the given key and 32 - bytes initialization vector ."""
padding = len ( plain_text ) % 16 if padding : plain_text += os . urandom ( 16 - padding ) if cryptg : return cryptg . encrypt_ige ( plain_text , key , iv ) if libssl . encrypt_ige : return libssl . encrypt_ige ( plain_text , key , iv ) iv1 = iv [ : len ( iv ) // 2 ] iv2 = iv [ len ( iv ) // 2 : ] aes = pya...
def save ( self , filename , binary = True ) : """Writes a structured grid to disk . Parameters filename : str Filename of grid to be written . The file extension will select the type of writer to use . " . vtk " will use the legacy writer , while " . vts " will select the VTK XML writer . binary : bool...
filename = os . path . abspath ( os . path . expanduser ( filename ) ) # Use legacy writer if vtk is in filename if '.vtk' in filename : writer = vtk . vtkStructuredGridWriter ( ) if binary : writer . SetFileTypeToBinary ( ) else : writer . SetFileTypeToASCII ( ) elif '.vts' in filename : ...
def delete ( self , photo_id , album_id = 0 ) : """Delete a photo from the logged in users account . : param photo _ id : The okcupid id of the photo to delete . : param album _ id : The album from which to delete the photo ."""
if isinstance ( photo_id , Info ) : photo_id = photo_id . id return self . _session . okc_post ( 'photoupload' , data = { 'albumid' : album_id , 'picid' : photo_id , 'authcode' : self . _authcode , 'picture.delete_ajax' : 1 } )
def extend_access_token ( self , app_id , app_secret ) : """Extends the expiration time of a valid OAuth access token . See < https : / / developers . facebook . com / roadmap / offline - access - removal / # extend _ token >"""
args = { "client_id" : app_id , "client_secret" : app_secret , "grant_type" : "fb_exchange_token" , "fb_exchange_token" : self . access_token , } response = urllib2 . urlopen ( "https://graph.facebook.com/oauth/" "access_token?" + urllib . parse . urlencode ( args ) ) . read ( ) . decode ( 'utf-8' ) query_str = parse_q...
def check_for_soliton ( img_id ) : """Workhorse function . Creates the polynom . Calculates radius constraints from attributes in ` ringcube ` object . Parameters ringcube : pyciss . ringcube . RingCube A containter class for a ring - projected ISS image file . Returns dict Dictionary with all solit...
pm = io . PathManager ( img_id ) try : ringcube = RingCube ( pm . cubepath ) except FileNotFoundError : ringcube = RingCube ( pm . undestriped ) polys = create_polynoms ( ) minrad = ringcube . minrad . to ( u . km ) maxrad = ringcube . maxrad . to ( u . km ) delta_years = get_year_since_resonance ( ringcube ) s...
def apply_filters ( target , lines ) : """Applys filters to the lines of a datasource . This function is used only in integration tests . Filters are applied in an equivalent but more performant way at run time ."""
filters = get_filters ( target ) if filters : for l in lines : if any ( f in l for f in filters ) : yield l else : for l in lines : yield l
def get_training_image_text_data_iters ( source_root : str , source : str , target : str , validation_source_root : str , validation_source : str , validation_target : str , vocab_target : vocab . Vocab , vocab_target_path : Optional [ str ] , batch_size : int , batch_by_words : bool , batch_num_devices : int , source_...
logger . info ( "===============================" ) logger . info ( "Creating training data iterator" ) logger . info ( "===============================" ) # define buckets buckets = define_empty_source_parallel_buckets ( max_seq_len_target , bucket_width ) if bucketing else [ ( 0 , max_seq_len_target ) ] source_images...
def set_sample_weight ( pipeline_steps , sample_weight = None ) : """Recursively iterates through all objects in the pipeline and sets sample weight . Parameters pipeline _ steps : array - like List of ( str , obj ) tuples from a scikit - learn pipeline or related object sample _ weight : array - like Lis...
sample_weight_dict = { } if not isinstance ( sample_weight , type ( None ) ) : for ( pname , obj ) in pipeline_steps : if inspect . getargspec ( obj . fit ) . args . count ( 'sample_weight' ) : step_sw = pname + '__sample_weight' sample_weight_dict [ step_sw ] = sample_weight if samp...
async def get_word ( self , term : str ) -> 'asyncurban.word.Word' : """Gets the first matching word available . Args : term : The word to be defined . Returns : The closest matching : class : ` Word ` from UrbanDictionary . Raises : UrbanConnectionError : If the response status isn ' t ` ` 200 ` ` . ...
resp = await self . _get ( term = term ) return Word ( resp [ 'list' ] [ 0 ] )
def generate ( env ) : """Add Builders and construction variables for dvipdf to an Environment ."""
global PDFAction if PDFAction is None : PDFAction = SCons . Action . Action ( '$DVIPDFCOM' , '$DVIPDFCOMSTR' ) global DVIPDFAction if DVIPDFAction is None : DVIPDFAction = SCons . Action . Action ( DviPdfFunction , strfunction = DviPdfStrFunction ) from . import pdf pdf . generate ( env ) bld = env [ 'BUILDERS'...
def __receiver_loop ( self ) : """Main loop listening for incoming data ."""
log . info ( "Starting receiver loop" ) notify_disconnected = True try : while self . running : try : while self . running : frames = self . __read ( ) for frame in frames : f = utils . parse_frame ( frame ) if f is None : ...
def prepare_time_micros ( data , schema ) : """Convert datetime . time to int timestamp with microseconds"""
if isinstance ( data , datetime . time ) : return long ( data . hour * MCS_PER_HOUR + data . minute * MCS_PER_MINUTE + data . second * MCS_PER_SECOND + data . microsecond ) else : return data
def sync ( lock ) : """A synchronization decorator"""
def sync ( f ) : @ wraps ( f ) def new_function ( * args , ** kwargs ) : lock . acquire ( ) try : return f ( * args , ** kwargs ) finally : lock . release ( ) return new_function return sync
def sinogram_as_radon ( uSin , align = True ) : r"""Compute the phase from a complex wave field sinogram This step is essential when using the ray approximation before computation of the refractive index with the inverse Radon transform . Parameters uSin : 2d or 3d complex ndarray The background - corre...
ndims = len ( uSin . shape ) if ndims == 2 : # unwrapping is very important phiR = np . unwrap ( np . angle ( uSin ) , axis = - 1 ) else : # Unwrap gets the dimension of the problem from the input # data . Since we have a sinogram , we need to pass it the # slices one by one . phiR = np . angle ( uSin ) for...
def get_line_pattern_rules ( declarations , dirs ) : """Given a list of declarations , return a list of output . Rule objects . Optionally provide an output directory for local copies of image files ."""
property_map = { 'line-pattern-file' : 'file' , 'line-pattern-width' : 'width' , 'line-pattern-height' : 'height' , 'line-pattern-type' : 'type' , 'line-pattern-meta-output' : 'meta-output' , 'line-pattern-meta-writer' : 'meta-writer' } property_names = property_map . keys ( ) # a place to put rules rules = [ ] for ( f...
async def eval ( self , text , opts = None , user = None ) : '''Evaluate a storm query and yield Nodes only .'''
if user is None : user = self . auth . getUserByName ( 'root' ) await self . boss . promote ( 'storm' , user = user , info = { 'query' : text } ) async with await self . snap ( user = user ) as snap : async for node in snap . eval ( text , opts = opts , user = user ) : yield node
def get_readlock ( pid , path ) : """Obtain a readlock on a file . Parameters path : str Name of the file on which to obtain a readlock"""
timestamp = int ( time . time ( ) * 1e6 ) lockdir_name = "%s.readlock.%i.%i" % ( path , pid , timestamp ) os . mkdir ( lockdir_name ) # Register function to release the readlock at the end of the script atexit . register ( release_readlock , lockdir_name = lockdir_name )
def _get_vpn_status ( self ) : """Returns None if no VPN active , Id if active ."""
# Sleep for a bit to let any changes in state finish sleep ( 0.3 ) # Check if any active connections are a VPN bus = SystemBus ( ) ids = [ ] for name in self . active : conn = bus . get ( ".NetworkManager" , name ) if conn . Vpn : ids . append ( conn . Id ) # No active VPN return ids
def run ( self ) : """Run command ."""
from container . cli import LOGGING from logging import config from container import core if self . debug : LOGGING [ 'loggers' ] [ 'container' ] [ 'level' ] = 'DEBUG' config . dictConfig ( LOGGING ) core . hostcmd_prebake ( self . distros , debug = self . debug , cache = self . cache , ignore_errors = self . ignor...
def finto ( x , ii , n , null = 0 ) : '''finto ( x , ii , n ) yields a vector u of length n such that u [ ii ] = x . Notes : * The ii index may be a tuple ( as can be passed to numpy arrays ' getitem method ) in order to specify that the specific elements of a multidimensional output be set . In this case , t...
x = x . toarray ( ) if sps . issparse ( x ) else np . asarray ( x ) shx = x . shape if isinstance ( ii , tuple ) : if not pimms . is_vector ( n ) : n = tuple ( [ n for _ in ii ] ) if len ( n ) != len ( ii ) : raise ValueError ( '%d-dim index but %d-dim output' % ( len ( ii ) , len ( n ) ) ) ...
def labeled_uniform_sample ( self , sample_size , replace = True ) : """Returns a Dataset object with labeled data only , which is resampled uniformly with given sample size . Parameter ` replace ` decides whether sampling with replacement or not . Parameters sample _ size"""
if replace : samples = [ random . choice ( self . get_labeled_entries ( ) ) for _ in range ( sample_size ) ] else : samples = random . sample ( self . get_labeled_entries ( ) , sample_size ) return Dataset ( * zip ( * samples ) )
def check_time_extrator ( self ) : """将抽取得时间转换为date标准时间格式 Keyword arguments : string - - 含有时间的文本 , str类型 Return : release _ time - - 新闻发布时间"""
if self . year_check and self . month_check and self . day_check : time = str ( self . year ) + '-' + str ( self . month ) + '-' + str ( self . day ) release_time = datetime . datetime . strptime ( time , "%Y-%m-%d" ) . date ( ) return release_time
def update_domain_smarthost ( self , domainid , serverid , data ) : """Update a domain smarthost"""
return self . api_call ( ENDPOINTS [ 'domainsmarthosts' ] [ 'update' ] , dict ( domainid = domainid , serverid = serverid ) , body = data )
def create_task ( self , element ) : """Create a new task for the given element : param element : the element for the task : type element : : class : ` jukeboxcore . djadapter . models . Shot ` | : class : ` jukeboxcore . djadapter . models . Asset ` : returns : None : rtype : None : raises : None"""
dialog = TaskCreatorDialog ( element = element , parent = self ) dialog . exec_ ( ) task = dialog . task return task
def _backup_bytes ( target , offset , length ) : """Read bytes from one file and write it to a backup file with the . bytes _ backup suffix"""
click . echo ( 'Backup {l} byes at position {offset} on file {file} to .bytes_backup' . format ( l = length , offset = offset , file = target ) ) with open ( target , 'r+b' ) as f : f . seek ( offset ) with open ( target + '.bytes_backup' , 'w+b' ) as b : for _ in xrange ( length ) : byte = ...
def get_aspect ( cx , aspect_name ) : """Return an aspect given the name of the aspect"""
if isinstance ( cx , dict ) : return cx . get ( aspect_name ) for entry in cx : if list ( entry . keys ( ) ) [ 0 ] == aspect_name : return entry [ aspect_name ]
def process_json_line ( self , data , name , idx ) : """Processes single json line : param data : : param name : : param idx : : return :"""
data = data . strip ( ) if len ( data ) == 0 : return ret = [ ] try : js = json . loads ( data ) self . num_json += 1 ret . append ( self . process_json_rec ( js , name , idx , [ ] ) ) except Exception as e : logger . debug ( 'Exception in processing JSON %s idx %s : %s' % ( name , idx , e ) ) s...
def phase_estimation_circuit ( gate : Gate , outputs : Qubits ) -> Circuit : """Returns a circuit for quantum phase estimation . The gate has an eigenvector with eigenvalue e ^ ( i 2 pi phase ) . To run the circuit , the eigenvector should be set on the gate qubits , and the output qubits should be in the zer...
circ = Circuit ( ) circ += map_gate ( H ( ) , list ( zip ( outputs ) ) ) # Hadamard on all output qubits for cq in reversed ( outputs ) : cgate = control_gate ( cq , gate ) circ += cgate gate = gate @ gate circ += qft_circuit ( outputs ) . H return circ
def get_task_groups ( self , project , task_group_id = None , expanded = None , task_id_filter = None , deleted = None , top = None , continuation_token = None , query_order = None ) : """GetTaskGroups . [ Preview API ] List task groups . : param str project : Project ID or project name : param str task _ gro...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if task_group_id is not None : route_values [ 'taskGroupId' ] = self . _serialize . url ( 'task_group_id' , task_group_id , 'str' ) query_parameters = { } if expanded is not None : ...
def adjust_attribute_sequence ( * fields ) : """Move marrow . schema fields around to control positional instantiation order ."""
amount = None if fields and isinstance ( fields [ 0 ] , int ) : amount , fields = fields [ 0 ] , fields [ 1 : ] def adjust_inner ( cls ) : for field in fields : if field not in cls . __dict__ : # TODO : Copy the field definition . raise TypeError ( "Can only override sequence on non-inherite...
def searchsorted ( self , value , side = 'left' , sorter = None ) : """Find indices where elements should be inserted to maintain order . Find the indices into a sorted array ` self ` such that , if the corresponding elements in ` value ` were inserted before the indices , the order of ` self ` would be prese...
if isinstance ( value , str ) : value = self . _scalar_from_string ( value ) if not ( isinstance ( value , ( self . _scalar_type , type ( self ) ) ) or isna ( value ) ) : raise ValueError ( "Unexpected type for 'value': {valtype}" . format ( valtype = type ( value ) ) ) self . _check_compatible_with ( value ) i...
def _delegate_required ( self , path ) : # type : ( Text ) - > FS """Check that there is a filesystem with the given ` ` path ` ` ."""
fs = self . _delegate ( path ) if fs is None : raise errors . ResourceNotFound ( path ) return fs
def build_and_submit_jobs ( root_dir , jobs , sgeargs = None ) : """Submits the passed iterable of Job objects to SGE , placing SGE ' s output in the passed root directory - root _ dir Root directory for SGE and job output - jobs List of Job objects , describing each job to be submitted - sgeargs Additional...
# If the passed set of jobs is not a list , turn it into one . This makes the # use of a single JobGroup a little more intutitive if not isinstance ( jobs , list ) : jobs = [ jobs ] # Build and submit the passed jobs build_directories ( root_dir ) # build all necessary directories build_job_scripts ( root_dir , job...
def _change_source_state ( name , state ) : '''Instructs Chocolatey to change the state of a source . name Name of the repository to affect . state State in which you want the chocolatey repository .'''
choc_path = _find_chocolatey ( __context__ , __salt__ ) cmd = [ choc_path , 'source' , state , '--name' , name ] result = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False ) if result [ 'retcode' ] != 0 : raise CommandExecutionError ( 'Running chocolatey failed: {0}' . format ( result [ 'stdout' ] ) ) return ...
def do_action ( self , command , journal = True ) : """Implementation for declarative file operations ."""
cmd = 0 ; src = 1 ; path = 1 ; data = 2 ; dst = 2 if journal is True : self . journal . write ( json . dumps ( command [ 'undo' ] ) + "\n" ) self . journal . flush ( ) d = command [ 'do' ] if d [ cmd ] == 'copy' : shutil . copy ( d [ src ] , d [ dst ] ) elif d [ cmd ] == 'move' : shutil . move ( d [ src...
def find_files ( directory , pattern , recursively = True ) : """Yield a list of files with their base directories , recursively or not . Returns : A list of ( base _ directory , filename ) Args : directory : base directory to start the search . pattern : fnmatch pattern for filenames . complete _ filen...
for root , dirs , files in os . walk ( directory ) : for basename in files : if fnmatch . fnmatch ( basename , pattern ) : yield root , basename if not recursively : break
def create_simple_writer ( outputDef , defaultOutput , outputFormat , fieldNames , compress = True , valueClassMappings = None , datasetMetaProps = None , fieldMetaProps = None ) : """Create a simple writer suitable for writing flat data e . g . as BasicObject or TSV ."""
if not outputDef : outputBase = defaultOutput else : outputBase = outputDef if outputFormat == 'json' : write_squonk_datasetmetadata ( outputBase , True , valueClassMappings , datasetMetaProps , fieldMetaProps ) return BasicObjectWriter ( open_output ( outputDef , 'data' , compress ) ) , outputBase elif...
def functions_to_table ( mod , colwidth = [ 27 , 48 ] ) : r"""Given a module of functions , returns a ReST formatted text string that outputs a table when printed . Parameters mod : module The module containing the functions to be included in the table , such as ' porespy . filters ' . colwidths : list ...
temp = mod . __dir__ ( ) funcs = [ i for i in temp if not i [ 0 ] . startswith ( '_' ) ] funcs . sort ( ) row = '+' + '-' * colwidth [ 0 ] + '+' + '-' * colwidth [ 1 ] + '+' fmt = '{0:1s} {1:' + str ( colwidth [ 0 ] - 2 ) + 's} {2:1s} {3:' + str ( colwidth [ 1 ] - 2 ) + 's} {4:1s}' lines = [ ] lines . append ( row ) li...
def get_b ( self ) : """Get Galactic latitude ( b ) corresponding to the current position : return : Latitude"""
try : return self . b . value except AttributeError : # Transform from L , B to R . A . , Dec return self . sky_coord . transform_to ( 'galactic' ) . b . value
def calc_crc ( raw_mac ) : """This algorithm is the equivalent of esp _ crc8 ( ) in ESP32 ROM code This is CRC - 8 w / inverted polynomial value 0x8C & initial value 0x00."""
result = 0x00 for b in struct . unpack ( "B" * 6 , raw_mac ) : result ^= b for _ in range ( 8 ) : lsb = result & 1 result >>= 1 if lsb != 0 : result ^= 0x8c return result
def set_typ ( self , typ ) : """Set the type of the entity Make sure the type is registered in the : class : ` RefobjInterface ` . : param typ : the type of the entity : type typ : str : returns : None : rtype : None : raises : ValueError"""
if typ not in self . _refobjinter . types : raise ValueError ( "The given typ is not supported by RefobjInterface. Given %s, supported: %s" % ( typ , self . _refobjinter . types . keys ( ) ) ) self . _typ = typ self . _typicon = self . get_refobjinter ( ) . get_typ_icon ( typ )
def get_market_summary ( self , market ) : """Used to get the last 24 hour summary of all active exchanges in specific coin Endpoint : 1.1 / public / getmarketsummary 2.0 / pub / Market / GetMarketSummary : param market : String literal for the market ( ex : BTC - XRP ) : type market : str : return : ...
return self . _api_query ( path_dict = { API_V1_1 : '/public/getmarketsummary' , API_V2_0 : '/pub/Market/GetMarketSummary' } , options = { 'market' : market , 'marketname' : market } , protection = PROTECTION_PUB )
def _check_fit_data ( self , X ) : """Verify that the number of samples given is larger than k"""
X = check_array ( X , accept_sparse = "csr" , dtype = [ np . float64 , np . float32 ] ) n_samples , n_features = X . shape if X . shape [ 0 ] < self . n_clusters : raise ValueError ( "n_samples=%d should be >= n_clusters=%d" % ( X . shape [ 0 ] , self . n_clusters ) ) for ee in range ( n_samples ) : if sp . iss...
def get ( self , sid ) : """Constructs a ShortCodeContext : param sid : The unique string that identifies the resource : returns : twilio . rest . proxy . v1 . service . short _ code . ShortCodeContext : rtype : twilio . rest . proxy . v1 . service . short _ code . ShortCodeContext"""
return ShortCodeContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = sid , )
def __parse_loc_data ( loc_data , result ) : """Parse the xml data from selected weatherstation ."""
result [ DATA ] = { ATTRIBUTION : ATTRIBUTION_INFO , FORECAST : [ ] , PRECIPITATION_FORECAST : None } for key , [ value , func ] in SENSOR_TYPES . items ( ) : result [ DATA ] [ key ] = None try : from buienradar . buienradar import condition_from_code sens_data = loc_data [ value ] if ke...
def create_placeholder_weld_object ( data ) : """Helper method that creates a WeldObject that evaluates to itself . Parameters data : numpy . ndarray or WeldObject or str Data to wrap around . If str , it is a placeholder or ' str ' literal . Returns WeldObject WeldObject wrapped around data ."""
obj_id , weld_obj = create_weld_object ( data ) weld_obj . weld_code = '{}' . format ( str ( obj_id ) ) return weld_obj
def plot_net ( fignum ) : """Draws circle and tick marks for equal area projection ."""
# make the perimeter plt . figure ( num = fignum , ) plt . clf ( ) plt . axis ( "off" ) Dcirc = np . arange ( 0 , 361. ) Icirc = np . zeros ( 361 , 'f' ) Xcirc , Ycirc = [ ] , [ ] for k in range ( 361 ) : XY = pmag . dimap ( Dcirc [ k ] , Icirc [ k ] ) Xcirc . append ( XY [ 0 ] ) Ycirc . append ( XY [ 1 ] )...
def _enforce_size_limit ( self , capacity ) : """Shrink the cache if necessary , evicting the oldest items ."""
while len ( self . _cache ) > capacity : key , value = self . _cache . popitem ( last = False ) if self . _on_evict is not None : self . _on_evict ( key , value )
def remove_summaries ( ) : """Remove summaries from the default graph ."""
g = tf . get_default_graph ( ) key = tf . GraphKeys . SUMMARIES log_debug ( "Remove summaries %s" % str ( g . get_collection ( key ) ) ) del g . get_collection_ref ( key ) [ : ] assert not g . get_collection ( key )
def install_plugin ( pkgpath , plugin_type , install_path , register_func ) : """Install specified plugin . : param pkgpath : Name of plugin to be downloaded from online repo or path to plugin folder or zip file . : param install _ path : Path where plugin will be installed . : param register _ func : Method ...
service_name = os . path . basename ( pkgpath ) if os . path . exists ( os . path . join ( install_path , service_name ) ) : raise exceptions . PluginAlreadyInstalled ( pkgpath ) if os . path . exists ( pkgpath ) : logger . debug ( "%s exists in filesystem" , pkgpath ) if os . path . isdir ( pkgpath ) : ...
def class_check ( vector ) : """Check different items in matrix classes . : param vector : input vector : type vector : list : return : bool"""
for i in vector : if not isinstance ( i , type ( vector [ 0 ] ) ) : return False return True
def restoreWidget ( self , viewWidget , parent , xwidget ) : """Creates the widget with the inputed parent based on the given xml type . : param viewWidget | < XViewWidget > parent | < QWidget > xwidget | < xml . etree . Element > : return < QWidget >"""
# create a new splitter if xwidget . tag == 'split' : widget = XSplitter ( parent ) if ( xwidget . get ( 'orient' ) == 'horizontal' ) : widget . setOrientation ( Qt . Horizontal ) else : widget . setOrientation ( Qt . Vertical ) # restore the children for xchild in xwidget : ...
def importMsgfMzidResults ( siiContainer , filelocation , specfile = None , qcAttr = 'eValue' , qcLargerBetter = False , qcCutoff = 0.01 , rankAttr = 'score' , rankLargerBetter = True ) : """Import peptide spectrum matches ( PSMs ) from a MS - GF + mzIdentML file , generate : class : ` Sii < maspy . core . Sii > ...
path = os . path . dirname ( filelocation ) siiList = readMsgfMzidResults ( filelocation , specfile ) # If the mzIdentML file contains multiple specfiles , split the sii elements # up according to their specified " specfile " attribute . specfiles = ddict ( list ) if specfile is None : for sii in siiList : ...
def token ( cls : Type [ SIGType ] , pubkey : str ) -> SIGType : """Return SIG instance from pubkey : param pubkey : Public key of the signature issuer : return :"""
sig = cls ( ) sig . pubkey = pubkey return sig
def alert ( msg , body = "" , icon = None ) : """alerts the user of something happening via ` notify - send ` . If it is not installed , the alert will be printed to the console ."""
if type ( body ) == str : body = body [ : 200 ] if call ( [ "which" , "notify-send" ] ) == 0 : if icon is not None : call ( [ "notify-send" , msg , "-i" , icon , body ] ) else : call ( [ "notify-send" , msg , body ] ) else : print ( ( "ALERT: " , msg ) )