signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _nullify_stdio ( self ) : """Open / dev / null to replace stdin , and stdout / stderr temporarily . In case of odd startup , assume we may be allocated a standard handle ."""
fd = os . open ( '/dev/null' , os . O_RDWR ) try : for stdfd in ( 0 , 1 , 2 ) : if fd != stdfd : os . dup2 ( fd , stdfd ) finally : if fd not in ( 0 , 1 , 2 ) : os . close ( fd )
def set_implicitly_wait ( self ) : """Read implicitly timeout from configuration properties and configure driver implicitly wait"""
implicitly_wait = self . driver_wrapper . config . get_optional ( 'Driver' , 'implicitly_wait' ) if implicitly_wait : self . driver_wrapper . driver . implicitly_wait ( implicitly_wait )
def Main ( ) : """The main program function . Returns : bool : True if successful or False if not ."""
argument_parser = argparse . ArgumentParser ( description = 'Validates dtFabric format definitions.' ) argument_parser . add_argument ( 'source' , nargs = '?' , action = 'store' , metavar = 'PATH' , default = None , help = ( 'path of the file or directory containing the dtFabric format ' 'definitions.' ) ) options = ar...
def get_doc_counts ( self , cache = True ) : """Get the number of related documents of various types for the artist . The types include audio , biographies , blogs , images , news , reviews , songs , videos . Note that these documents can be retrieved by calling artist . < document type > , for example , arti...
if not cache or not ( 'doc_counts' in self . cache ) : response = self . get_attribute ( "profile" , bucket = 'doc_counts' ) self . cache [ 'doc_counts' ] = response [ 'artist' ] [ 'doc_counts' ] return self . cache [ 'doc_counts' ]
def know ( self , what , confidence ) : """Know something with the given confidence , and return self for chaining . If confidence is higher than that of what we already know , replace what we already know with what you ' re telling us ."""
if confidence > self . confidence : self . best = what self . confidence = confidence return self
def unique_element ( ll ) : """returns unique elements from a list preserving the original order"""
seen = { } result = [ ] for item in ll : if item in seen : continue seen [ item ] = 1 result . append ( item ) return result
def request ( self , uri , method = GET , headers = None , cookies = None , params = None , data = None , post_files = None , ** kwargs ) : """Makes a request using requests @ param uri : The uri to send request @ param method : Method to use to send request @ param headers : Any headers to send with request ...
coyote_args = { 'headers' : headers , 'cookies' : cookies , 'params' : params , 'files' : post_files , 'data' : data , 'verify' : self . verify_certificates , } coyote_args . update ( kwargs ) if method == self . POST : response = self . session . post ( uri , ** coyote_args ) elif method == self . PUT : respon...
def readEncodedU32 ( self ) : """Read a encoded unsigned int"""
self . reset_bits_pending ( ) ; result = self . readUI8 ( ) ; if result & 0x80 != 0 : result = ( result & 0x7f ) | ( self . readUI8 ( ) << 7 ) if result & 0x4000 != 0 : result = ( result & 0x3fff ) | ( self . readUI8 ( ) << 14 ) if result & 0x200000 != 0 : result = ( result & 0x1ffff...
def prepare_framework_container_def ( model , instance_type , s3_operations ) : """Prepare the framework model container information . Specify related S3 operations for Airflow to perform . ( Upload ` source _ dir ` ) Args : model ( sagemaker . model . FrameworkModel ) : The framework model instance _ type ...
deploy_image = model . image if not deploy_image : region_name = model . sagemaker_session . boto_session . region_name deploy_image = fw_utils . create_image_uri ( region_name , model . __framework_name__ , instance_type , model . framework_version , model . py_version ) base_name = utils . base_name_from_imag...
def _render_op ( self , identifier , hs = None , dagger = False , args = None , superop = False ) : """Render an operator Args : identifier ( str or SymbolicLabelBase ) : The identifier ( name / symbol ) of the operator . May include a subscript , denoted by ' _ ' . hs ( HilbertSpace ) : The Hilbert space i...
hs_label = None if hs is not None and self . _settings [ 'show_hs_label' ] : hs_label = self . _render_hs_label ( hs ) name , total_subscript , total_superscript , args_str = self . _split_op ( identifier , hs_label , dagger , args ) if self . _settings [ 'unicode_op_hats' ] and len ( name ) == 1 : if superop :...
def write_lines ( self , lines , level = 0 ) : """Append multiple new lines"""
for line in lines : self . write_line ( line , level )
def pdf_rotate ( input : str , counter_clockwise : bool = False , pages : [ str ] = None , output : str = None , ) : """Rotate the given Pdf files clockwise or counter clockwise . : param inputs : pdf files : param counter _ clockwise : rotate counter clockwise if true else clockwise : param pages : list of p...
infile = open ( input , "rb" ) reader = PdfFileReader ( infile ) writer = PdfFileWriter ( ) # get pages from source depending on pages parameter if pages is None : source_pages = reader . pages else : pages = parse_rangearg ( pages , len ( reader . pages ) ) source_pages = [ reader . getPage ( i ) for i in ...
async def on_raw_kick ( self , message ) : """KICK command ."""
kicker , kickermeta = self . _parse_user ( message . source ) self . _sync_user ( kicker , kickermeta ) if len ( message . params ) > 2 : channels , targets , reason = message . params else : channels , targets = message . params reason = None channels = channels . split ( ',' ) targets = targets . split ( ...
def beacon ( config ) : '''Watch the configured files Example Config . . code - block : : yaml beacons : inotify : - files : / path / to / file / or / dir : mask : - open - create - close _ write recurse : True auto _ add : True exclude : - / path / to / file / or / dir / exclude1 - / ...
_config = { } list ( map ( _config . update , config ) ) ret = [ ] notifier = _get_notifier ( _config ) wm = notifier . _watch_manager # Read in existing events if notifier . check_events ( 1 ) : notifier . read_events ( ) notifier . process_events ( ) queue = __context__ [ 'inotify.queue' ] while queue...
def update_data_display ( self , data ) : """Triggered when the selected device / IMU is changed . Updates the background colours of the text widgets in the UI to indicate which sensors have calibration data available ( green ) and which do not ( red )"""
acc_cal = self . ACC_TIMESTAMP in data mag_cal = self . MAG_TIMESTAMP in data gyro_cal = self . GYRO_TIMESTAMP in data uncal = 'QLineEdit {background-color: #cc3333;};' cal = 'QLineEdit {background-color: #33cc33;};' if acc_cal : self . dataAccX . setStyleSheet ( cal ) self . dataAccY . setStyleSheet ( cal ) ...
def purchase_ip ( self , debug = False ) : """Return an ip object representing a new bought IP @ param debug [ Boolean ] if true , request and response will be printed @ return ( Ip ) : Ip object"""
json_scheme = self . gen_def_json_scheme ( 'SetPurchaseIpAddress' ) json_obj = self . call_method_post ( method = 'SetPurchaseIpAddress' , json_scheme = json_scheme , debug = debug ) try : ip = Ip ( ) ip . ip_addr = json_obj [ 'Value' ] [ 'Value' ] ip . resid = json_obj [ 'Value' ] [ 'ResourceId' ] retu...
def to_json ( df , columns , confidence = { } ) : """Transforms dataframe to properly formatted json response"""
records = [ ] display_cols = list ( columns . keys ( ) ) if not display_cols : display_cols = list ( df . columns ) bounds = { } for c in confidence : bounds [ c ] = { "min" : df [ confidence [ c ] [ "lower" ] ] . min ( ) , "max" : df [ confidence [ c ] [ "upper" ] ] . max ( ) , "lower" : confidence [ c ] [ "lo...
def addAnalysis ( self , analysis , position = None ) : """- add the analysis to self . Analyses ( ) . - position is overruled if a slot for this analysis ' parent exists - if position is None , next available pos is used ."""
# Cannot add an analysis if not open , unless a retest if api . get_review_status ( self ) not in [ "open" , "to_be_verified" ] : retracted = analysis . getRetestOf ( ) if retracted not in self . getAnalyses ( ) : return # Cannot add an analysis that is assigned already if analysis . getWorksheet ( ) : ...
def calculate_nf ( sample_frame , ref_targets , ref_sample ) : """Calculates a normalization factor from the geometric mean of the expression of all ref _ targets , normalized to a reference sample . : param DataFrame sample _ frame : A sample data frame . : param iterable ref _ targets : A list or Series of ...
grouped = sample_frame . groupby ( [ 'Target' , 'Sample' ] ) [ 'Cq' ] . aggregate ( average_cq ) samples = sample_frame [ 'Sample' ] . unique ( ) nfs = gmean ( [ pow ( 2 , - grouped . ix [ zip ( repeat ( ref_gene ) , samples ) ] + grouped . ix [ ref_gene , ref_sample ] ) for ref_gene in ref_targets ] ) return pd . Seri...
def print_experiments ( experiments ) : """Prints job details in a table . Includes urls and mode parameters"""
headers = [ "JOB NAME" , "CREATED" , "STATUS" , "DURATION(s)" , "INSTANCE" , "DESCRIPTION" , "METRICS" ] expt_list = [ ] for experiment in experiments : expt_list . append ( [ normalize_job_name ( experiment . name ) , experiment . created_pretty , experiment . state , experiment . duration_rounded , experiment . i...
def init_app ( self , app ) : '''Configures an application . This registers an ` after _ request ` call , and attaches this ` LoginManager ` to it as ` app . login _ manager ` .'''
self . _config = app . config . get ( 'LDAP' , { } ) app . ldap_login_manager = self self . config . setdefault ( 'BIND_DN' , '' ) self . config . setdefault ( 'BIND_AUTH' , '' ) self . config . setdefault ( 'URI' , 'ldap://127.0.0.1' ) self . config . setdefault ( 'OPTIONS' , { } ) # Referrals are disabled by default ...
def assemble_cx ( ) : """Assemble INDRA Statements and return CX network json ."""
if request . method == 'OPTIONS' : return { } response = request . body . read ( ) . decode ( 'utf-8' ) body = json . loads ( response ) stmts_json = body . get ( 'statements' ) stmts = stmts_from_json ( stmts_json ) ca = CxAssembler ( stmts ) model_str = ca . make_model ( ) res = { 'model' : model_str } return res
def resolve ( self , definitions ) : """Resolve named references to other WSDL objects . This includes cross - linking information ( from ) the portType ( to ) the I { soap } protocol information on the binding for each operation . @ param definitions : A definitions object . @ type definitions : L { Defini...
self . resolveport ( definitions ) for op in self . operations . values ( ) : self . resolvesoapbody ( definitions , op ) self . resolveheaders ( definitions , op ) self . resolvefaults ( definitions , op )
def create_layer_2_socket ( ) : """create _ layer _ 2 _ socket"""
# create a socket for recording layer 2 , 3 and 4 frames s = None try : log . info ( "Creating l234 socket" ) s = socket . socket ( socket . AF_PACKET , socket . SOCK_RAW , socket . ntohs ( 0x0003 ) ) except socket . error as msg : log . error ( ( "Socket could not be created ex={}" ) . format ( msg ) ) ret...
def logs_handle_build_job ( job_uuid : str , job_name : str , log_lines : Optional [ Union [ str , Iterable [ str ] ] ] , temp : bool = True ) -> None : """Task handling for sidecars logs ."""
handle_build_job_logs ( job_uuid = job_uuid , job_name = job_name , log_lines = log_lines , temp = temp )
def process_request ( request ) : """Adds a " mobile " attribute to the request which is True or False depending on whether the request should be considered to come from a small - screen device such as a phone or a PDA"""
if 'HTTP_X_OPERAMINI_FEATURES' in request . META : # Then it ' s running opera mini . ' Nuff said . # Reference from : # http : / / dev . opera . com / articles / view / opera - mini - request - headers / request . mobile = True return None if 'HTTP_ACCEPT' in request . META : s = request . META [ 'HTTP_ACC...
def is_direct_subclass ( class_ , of ) : """Check whether given class is a direct subclass of the other . : param class _ : Class to check : param of : Superclass to check against : return : Boolean result of the test . . versionadded : : 0.0.4"""
ensure_class ( class_ ) ensure_class ( of ) # TODO ( xion ) : support predicates in addition to classes return of in class_ . __bases__
def set_rate ( self , param ) : """Models " Rate Command " functionality of device . Sets the target rate of temperature change . : param param : Rate of temperature change in C / min , multiplied by 100 , as a string . Must be positive . : return : Empty string ."""
# TODO : Is not having leading zeroes / 4 digits an error ? rate = int ( param ) if 1 <= rate <= 15000 : self . device . temperature_rate = rate / 100.0 return ""
def json ( self ) : """Return a JSON - serializable representation of this result . The output of this function can be converted to a serialized string with : any : ` json . dumps ` ."""
data = super ( CalTRACKHourlyModel , self ) . json ( ) data . update ( { "occupancy_lookup" : self . occupancy_lookup . to_json ( orient = "split" ) , "temperature_bins" : self . temperature_bins . to_json ( orient = "split" ) , } ) return data
def make_organisms ( self , genome_list , genome_dir ) : '''Organism factory method . Appends organisms to the organisms list . Args genome _ list ( list ) genome _ dir ( string )'''
for genome in genome_list : genome_path = genome_dir + genome handle = open ( genome_path , "rU" ) print 'Adding organism attributes for' , genome try : seq_record = SeqIO . read ( handle , "genbank" ) self . organisms . append ( Organism ( seq_record , genome_path , self ) ) del...
def scroll_to_horizontally ( self , obj , * args , ** selectors ) : """Scroll ( horizontally ) on the object : obj to specific UI object which has * selectors * attributes appears . Return true if the UI object , else return false . See ` Scroll To Vertically ` for more details ."""
return obj . scroll . horiz . to ( ** selectors )
def get_bounding_box ( self , lon , lat , trt = None , mag = None ) : """Build a bounding box around the given lon , lat by computing the maximum _ distance at the given tectonic region type and magnitude . : param lon : longitude : param lat : latitude : param trt : tectonic region type , possibly None :...
if trt is None : # take the greatest integration distance maxdist = max ( self ( trt , mag ) for trt in self . dic ) else : # get the integration distance for the given TRT maxdist = self ( trt , mag ) a1 = min ( maxdist * KM_TO_DEGREES , 90 ) a2 = min ( angular_distance ( maxdist , lat ) , 180 ) return lon - a...
def execute_notebook ( input_path , output_path , parameters = None , engine_name = None , prepare_only = False , kernel_name = None , progress_bar = True , log_output = False , start_timeout = 60 , report_mode = False , cwd = None , ) : """Executes a single notebook locally . Parameters input _ path : str Pa...
path_parameters = add_builtin_parameters ( parameters ) input_path = parameterize_path ( input_path , path_parameters ) output_path = parameterize_path ( output_path , path_parameters ) logger . info ( "Input Notebook: %s" % get_pretty_path ( input_path ) ) logger . info ( "Output Notebook: %s" % get_pretty_path ( out...
def call_hpp ( self , message , action , hmac_key = "" , ** kwargs ) : """This will call the adyen hpp . hmac _ key and platform are pulled from root module level and or self object . AdyenResult will be returned on 200 response . Otherwise , an exception is raised . Args : request _ data ( dict ) : The d...
if not self . http_init : self . http_client = HTTPClient ( self . app_name , self . USER_AGENT_SUFFIX , self . LIB_VERSION , self . http_force ) self . http_init = True # hmac provided in function has highest priority . fallback to self then # root module and ensure that it is set . hmac = hmac_key if self . h...
def build_trees_from_text ( text , layer , ** kwargs ) : '''Given a text object and the name of the layer where dependency syntactic relations are stored , builds trees ( estnltk . syntax . utils . Tree objects ) from all the sentences of the text and returns as a list of Trees . Uses the method build _ trees...
from estnltk . text import Text assert isinstance ( text , Text ) , '(!) Unexpected text argument! Should be Estnltk\'s Text object.' assert layer in text , '(!) The layer ' + str ( layer ) + ' is missing from the input text.' text_sentences = list ( text . divide ( layer = WORDS , by = SENTENCES ) ) all_sentence_trees...
def _setup_apikey_policy ( config , params ) : """Setup ` nefertari . ApiKeyAuthenticationPolicy ` . Notes : * User may provide model name in : params [ ' user _ model ' ] : do define the name of the user model . * ` auth _ model . get _ groups _ by _ token ` is used to perform username and token check ...
from nefertari . authentication . views import ( TokenAuthRegisterView , TokenAuthClaimView , TokenAuthResetView ) log . info ( 'Configuring ApiKey Authn policy' ) auth_model = config . registry . auth_model params [ 'check' ] = auth_model . get_groups_by_token params [ 'credentials_callback' ] = auth_model . get_token...
def _model ( self , beta ) : """Creates the structure of the model ( model matrices etc ) Parameters beta : np . ndarray Contains untransformed starting values for the latent variables Returns mu : np . ndarray Contains the predicted values ( location ) for the time series Y : np . ndarray Contains ...
Y = np . array ( self . data [ self . max_lag : ] ) # Transform latent variables z = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] ) bias = z [ self . latent_variables . z_indices [ 'Bias' ] [ 'start' ] : self . latent_variables . z_indi...
def _parse_version ( self , value ) : """Parses ` version ` option value . : param value : : rtype : str"""
version = self . _parse_file ( value ) if version != value : version = version . strip ( ) # Be strict about versions loaded from file because it ' s easy to # accidentally include newlines and other unintended content if isinstance ( parse ( version ) , LegacyVersion ) : tmpl = ( 'Version loade...
def delegated_login ( self , login , admin_zc , duration = 0 ) : """Use another client to get logged in via delegated _ auth mechanism by an already logged in admin . : param admin _ zc : An already logged - in admin client : type admin _ zc : ZimbraAdminClient : param login : the user login ( or email ) yo...
# a duration of zero is interpretted literaly by the API . . . selector = zobjects . Account ( name = login ) . to_selector ( ) delegate_args = { 'account' : selector } if duration : delegate_args [ 'duration' : duration ] resp = admin_zc . request ( 'DelegateAuth' , delegate_args ) lifetime = resp [ 'lifetime' ] a...
def flux_matrix ( T , pi , qminus , qplus , netflux = True ) : r"""Compute the TPT flux network for the reaction A - - > B . Parameters T : ( M , M ) ndarray transition matrix pi : ( M , ) ndarray Stationary distribution corresponding to T qminus : ( M , ) ndarray Backward comittor qplus : ( M , ) n...
if issparse ( T ) : return sparse . tpt . flux_matrix ( T , pi , qminus , qplus , netflux = netflux ) elif isdense ( T ) : return dense . tpt . flux_matrix ( T , pi , qminus , qplus , netflux = netflux ) else : raise _type_not_supported
def get_license_metadata ( self ) : """Gets the metadata for the license . return : ( osid . Metadata ) - metadata for the license * compliance : mandatory - - This method must be implemented . *"""
metadata = dict ( self . _license_metadata ) metadata . update ( { 'existing_string_values' : self . my_osid_object_form . _my_map [ 'license' ] } ) return Metadata ( ** metadata )
def validate_url ( self , original_string ) : """Returns the original string if it was valid , raises an argument error if it ' s not ."""
# nipped from stack overflow : http : / / stackoverflow . com / questions / 827557 / how - do - you - validate - a - url - with - a - regular - expression - in - python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse . urlparse ( original_string ) try : if self ....
def is_auth_alive ( self ) : "Return true if the auth is not expired , else false"
model = self . model ( 'ir.model' ) try : model . search ( [ ] , None , 1 , None ) except ClientError as err : if err and err . message [ 'code' ] == 403 : return False raise except Exception : raise else : return True
def stop ( self , api = None ) : """Stop automation run . : param api : sevenbridges Api instance . : return : AutomationRun object"""
api = api or self . _API return api . post ( url = self . _URL [ 'actions' ] . format ( id = self . id , action = AutomationRunActions . STOP ) ) . content
def ls ( self , path , offset = None , amount = None ) : """Return list of files / directories . Each item is a dict . Keys : ' path ' , ' creationdate ' , ' displayname ' , ' length ' , ' lastmodified ' , ' isDir ' ."""
def parseContent ( content ) : result = [ ] root = ET . fromstring ( content ) for response in root . findall ( './/d:response' , namespaces = self . namespaces ) : node = { 'path' : response . find ( "d:href" , namespaces = self . namespaces ) . text , 'creationdate' : response . find ( "d:propstat...
def _load_schema ( name , path = __file__ ) : """Load a schema from disk"""
path = os . path . join ( os . path . dirname ( path ) , name + '.yaml' ) with open ( path ) as handle : schema = yaml . safe_load ( handle ) fast_schema = rapidjson . Validator ( rapidjson . dumps ( schema ) ) return path , ( schema , fast_schema )
def brpoplpush ( self , source , destination , timeout = 0 ) : """Emulate brpoplpush"""
transfer_item = self . brpop ( source , timeout ) if transfer_item is None : return None key , val = transfer_item self . lpush ( destination , val ) return val
def resolve_annotations ( raw_annotations : Dict [ str , AnyType ] , module_name : Optional [ str ] ) -> Dict [ str , AnyType ] : """Partially taken from typing . get _ type _ hints . Resolve string or ForwardRef annotations into type objects if possible ."""
if module_name : base_globals : Optional [ Dict [ str , Any ] ] = sys . modules [ module_name ] . __dict__ else : base_globals = None annotations = { } for name , value in raw_annotations . items ( ) : if isinstance ( value , str ) : value = ForwardRef ( value , is_argument = False ) try : ...
def get_randomness_stream ( self , decision_point : str , for_initialization : bool = False ) -> RandomnessStream : """Provides a new source of random numbers for the given decision point . Parameters decision _ point : A unique identifier for a stream of random numbers . Typically represents a decision tha...
if decision_point in self . _decision_points : raise RandomnessError ( f"Two separate places are attempting to create " f"the same randomness stream for {decision_point}" ) stream = RandomnessStream ( key = decision_point , clock = self . _clock , seed = self . _seed , index_map = self . _key_mapping , manager = se...
def set_database_path ( dbfolder ) : """Use to write the database path into the config . Parameters dbfolder : str or pathlib . Path Path to where pyciss will store the ISS images it downloads and receives ."""
configpath = get_configpath ( ) try : d = get_config ( ) except IOError : d = configparser . ConfigParser ( ) d [ 'pyciss_db' ] = { } d [ 'pyciss_db' ] [ 'path' ] = dbfolder with configpath . open ( 'w' ) as f : d . write ( f ) print ( "Saved database path into {}." . format ( configpath ) )
def _compute_intra_event_std ( self , C , C_PGA , pga1100 , mag , vs30 , vs30measured ) : """Compute intra event standard deviation ( equation 24 ) as described in the errata and not in the original paper ."""
sigma_b = self . _compute_sigma_b ( C , mag , vs30measured ) sigma_b_pga = self . _compute_sigma_b ( C_PGA , mag , vs30measured ) delta_amp = self . _compute_partial_derivative_site_amp ( C , pga1100 , vs30 ) std_intra = np . sqrt ( sigma_b ** 2 + self . CONSTS [ 'sigma_amp' ] ** 2 + ( delta_amp ** 2 ) * ( sigma_b_pga ...
def pages ( self ) : """A generator of all pages in the stream . Returns : types . GeneratorType [ google . cloud . bigquery _ storage _ v1beta1 . ReadRowsPage ] : A generator of pages ."""
# Each page is an iterator of rows . But also has num _ items , remaining , # and to _ dataframe . avro_schema , column_names = _avro_schema ( self . _read_session ) for block in self . _reader : self . _status = block . status yield ReadRowsPage ( avro_schema , column_names , block )
def connectionMade ( self ) : """Register with the stomp server ."""
cmd = self . sm . connect ( ) self . transport . write ( cmd )
def pass_missingremoterelease_v1 ( self ) : """Update the outlet link sequence | dam _ senders . D | ."""
flu = self . sequences . fluxes . fastaccess sen = self . sequences . senders . fastaccess sen . d [ 0 ] += flu . missingremoterelease
def get_instrument_variables ( ds ) : '''Returns a list of instrument variables : param netCDF4 . Dataset ds : An open netCDF4 Dataset'''
candidates = [ ] for variable in ds . variables : instrument = getattr ( ds . variables [ variable ] , 'instrument' , '' ) if instrument and instrument in ds . variables : if instrument not in candidates : candidates . append ( instrument ) instrument = getattr ( ds , 'instrument' , '' ) if ...
def _init_taskqueue_stub ( self , ** stub_kwargs ) : """Initializes the taskqueue stub using nosegae config magic"""
task_args = { } # root _ path is required so the stub can find ' queue . yaml ' or ' queue . yml ' if 'root_path' not in stub_kwargs : for p in self . _app_path : # support - - gae - application values that may be a . yaml file dir_ = os . path . dirname ( p ) if os . path . isfile ( p ) else p if o...
def _get ( self , url , param_dict = { } , securityHandler = None , additional_headers = [ ] , handlers = [ ] , proxy_url = None , proxy_port = None , compress = True , custom_handlers = [ ] , out_folder = None , file_name = None ) : """Performs a GET operation Inputs : Output : returns dictionary , string or...
self . _last_method = "GET" CHUNK = 4056 param_dict , handler , cj = self . _processHandler ( securityHandler , param_dict ) headers = [ ] + additional_headers if compress : headers . append ( ( 'Accept-encoding' , 'gzip' ) ) else : headers . append ( ( 'Accept-encoding' , '' ) ) headers . append ( ( 'User-Agen...
def _next_rId ( self ) : """Next available rId in collection , starting from ' rId1 ' and making use of any gaps in numbering , e . g . ' rId2 ' for rIds [ ' rId1 ' , ' rId3 ' ] ."""
for n in range ( 1 , len ( self ) + 2 ) : rId_candidate = 'rId%d' % n # like ' rId19' if rId_candidate not in self : return rId_candidate
def get_eco_map ( url ) : """To conver the three column file to a hashmap we join primary and secondary keys , for example IEAGO _ REF : 000002ECO : 0000256 IEAGO _ REF : 000003ECO : 0000501 IEADefaultECO : 0000501 becomes IEA - GO _ REF : 000002 : ECO : 0000256 IEA - GO _ REF : 000003 : ECO : 00005...
# this would go in a translation table but it is generated dynamicly # maybe when we move to a make driven system eco_map = { } request = urllib . request . Request ( url ) response = urllib . request . urlopen ( request ) for line in response : line = line . decode ( 'utf-8' ) . rstrip ( ) if re . match ( r'^#...
def begin_state ( self , batch_size = 0 , func = ndarray . zeros , ** kwargs ) : """Initial state for this cell . Parameters func : callable , default symbol . zeros Function for creating initial state . For Symbol API , func can be ` symbol . zeros ` , ` symbol . uniform ` , ` symbol . var etc ` . Use ` ...
assert not self . _modified , "After applying modifier cells (e.g. ZoneoutCell) the base " "cell cannot be called directly. Call the modifier cell instead." states = [ ] for info in self . state_info ( batch_size ) : self . _init_counter += 1 if info is not None : info . update ( kwargs ) else : ...
def start_date ( request ) : """Add the start date to the context for eighth admin views ."""
if request . user and request . user . is_authenticated and request . user . is_eighth_admin : return { "admin_start_date" : get_start_date ( request ) } return { }
def read_int16 ( self , little_endian = True ) : """Read 2 byte as a signed integer value from the stream . Args : little _ endian ( bool ) : specify the endianness . ( Default ) Little endian . Returns : int :"""
if little_endian : endian = "<" else : endian = ">" return self . unpack ( '%sh' % endian , 2 )
def blend_palette ( colors , n_colors = 6 , as_cmap = False ) : """Make a palette that blends between a list of colors . Parameters colors : sequence of matplotlib colors hex , rgb - tuple , or html color name n _ colors : int , optional number of colors in the palette as _ cmap : bool , optional if T...
name = "-" . join ( map ( str , colors ) ) pal = mpl . colors . LinearSegmentedColormap . from_list ( name , colors ) if not as_cmap : pal = pal ( np . linspace ( 0 , 1 , n_colors ) ) return pal
def _init_itemid2name ( self ) : """Print gene symbols instead of gene IDs , if provided ."""
if not hasattr ( self . args , 'id2sym' ) : return None fin_id2sym = self . args . id2sym if fin_id2sym is not None and os . path . exists ( fin_id2sym ) : id2sym = { } cmpl = re . compile ( r'^\s*(\S+)[\s,;]+(\S+)' ) with open ( fin_id2sym ) as ifstrm : for line in ifstrm : mtch = c...
def logical_chassis_fwdl_sanity_input_rbridge_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) logical_chassis_fwdl_sanity = ET . Element ( "logical_chassis_fwdl_sanity" ) config = logical_chassis_fwdl_sanity input = ET . SubElement ( logical_chassis_fwdl_sanity , "input" ) rbridge_id = ET . SubElement ( input , "rbridge-id" ) rbridge_id . text = kwargs . pop ( 'rbridge_id' ) c...
def load_json ( self , path ) : """Load a JSON file from the user profile ."""
with open ( self . profile_path ( path , must_exist = True ) , encoding = 'utf-8' ) as f : data = json . load ( f ) return data
def get_colours ( color_group , color_name , reverse = False ) : color_group = color_group . lower ( ) cmap = get_map ( color_group , color_name , reverse = reverse ) return cmap . hex_colors """if not reverse : return cmap . hex _ colors else : return cmap . hex _ colors [ : : - 1]"""
def reccyl ( rectan ) : """Convert from rectangular to cylindrical coordinates . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / reccyl _ c . html : param rectan : Rectangular coordinates of a point . : type rectan : 3 - Element Array of floats : return : Distance from z ax...
rectan = stypes . toDoubleVector ( rectan ) radius = ctypes . c_double ( 0 ) lon = ctypes . c_double ( 0 ) z = ctypes . c_double ( 0 ) libspice . reccyl_c ( rectan , ctypes . byref ( radius ) , ctypes . byref ( lon ) , ctypes . byref ( z ) ) return radius . value , lon . value , z . value
def deleteMediaPreviews ( self ) : """Delete the preview thumbnails for items in this library . This cannot be undone . Recreating media preview files can take hours or even days ."""
key = '/library/sections/%s/indexes' % self . key self . _server . query ( key , method = self . _server . _session . delete )
def query_one ( self , * args , ** kwargs ) : """Return first document from : meth : ` query ` , with same parameters ."""
for r in self . query ( * args , ** kwargs ) : return r return None
def confirmation ( self , apdu ) : """This function is called when the application has provided a response and needs it to be sent to the client ."""
if _debug : ServerSSM . _debug ( "confirmation %r" , apdu ) # check to see we are in the correct state if self . state != AWAIT_RESPONSE : if _debug : ServerSSM . _debug ( " - warning: not expecting a response" ) # abort response if ( apdu . apduType == AbortPDU . pduType ) : if _debug : ...
def check_exists ( name , path ) : '''Check if the given path is an alternative for a name . . . versionadded : : 2015.8.4 CLI Example : . . code - block : : bash salt ' * ' alternatives . check _ exists name path'''
cmd = [ _get_cmd ( ) , '--display' , name ] out = __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False ) if out [ 'retcode' ] > 0 and out [ 'stderr' ] != '' : return False return any ( ( line . startswith ( path ) for line in out [ 'stdout' ] . splitlines ( ) ) )
def is_dead ( self , proc , name ) : """Checks to see if the specified process is dead . : param psutil . Process proc : The process to check : param str name : The name of consumer : rtype : bool"""
LOGGER . debug ( 'Checking %s (%r)' , name , proc ) try : status = proc . status ( ) except psutil . NoSuchProcess : LOGGER . debug ( 'NoSuchProcess: %s (%r)' , name , proc ) return True LOGGER . debug ( 'Process %s (%s) status: %r (Unresponsive Count: %s)' , name , proc . pid , status , self . unresponsive...
def load_template ( self , name ) : """Attempts to load the relevant template from our templating system / environment . Args : name : The name of the template to load . Return : On success , a StatikTemplate object that can be used to render content ."""
# hopefully speeds up loading of templates a little , especially when loaded multiple times if name in self . cached_templates : logger . debug ( "Using cached template: %s" , name ) return self . cached_templates [ name ] logger . debug ( "Attempting to find template by name: %s" , name ) name_with_ext , provi...
def result ( self ) : """Get the result ( s ) for this hook call ( DEPRECATED in favor of ` ` get _ result ( ) ` ` ) ."""
msg = "Use get_result() which forces correct exception handling" warnings . warn ( DeprecationWarning ( msg ) , stacklevel = 2 ) return self . _result
def split_camel ( word : str ) -> str : """Separate any words joined in Camel case fashion using a single space . > > > split _ camel ( ' esseCarthaginienses ' ) ' esse Carthaginienses ' > > > split _ camel ( ' urbemCertimam ' ) ' urbem Certimam '"""
m = re . match ( '[a-z]+[A-Z][a-z]' , word ) if m : _ , end = m . span ( ) return word [ : end - 2 ] + ' ' + word [ end - 2 : ] return word
def acl_middleware ( callback ) : """Returns a aiohttp _ auth . acl middleware factory for use by the aiohttp application object . Args : callback : This is a callable which takes a user _ id ( as returned from the auth . get _ auth function ) , and expects a sequence of permitted ACL groups to be returne...
async def _acl_middleware_factory ( app , handler ) : async def _middleware_handler ( request ) : # Save the policy in the request request [ GROUPS_KEY ] = callback # Call the next handler in the chain return await handler ( request ) return _middleware_handler return _acl_middleware_fac...
def _handleDecodeHextileRAW ( self , block , bg , color , x , y , width , height , tx , ty , tw , th ) : """the tile is in raw encoding"""
self . updateRectangle ( tx , ty , tw , th , block ) self . _doNextHextileSubrect ( bg , color , x , y , width , height , tx , ty )
def QA_data_tick_resample ( tick , type_ = '1min' ) : """tick采样成任意级别分钟线 Arguments : tick { [ type ] } - - transaction Returns : [ type ] - - [ description ]"""
tick = tick . assign ( amount = tick . price * tick . vol ) resx = pd . DataFrame ( ) _temp = set ( tick . index . date ) for item in _temp : _data = tick . loc [ str ( item ) ] _data1 = _data [ time ( 9 , 31 ) : time ( 11 , 30 ) ] . resample ( type_ , closed = 'right' , base = 30 , loffset = type_ ) . apply ( ...
async def get_shade ( self , shade_id , from_cache = True ) -> BaseShade : """Get a shade instance based on shade id ."""
if not from_cache : await self . get_shades ( ) for _shade in self . shades : if _shade . id == shade_id : return _shade raise ResourceNotFoundException ( "Shade not found. Id: {}" . format ( shade_id ) )
def sun_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : """Calculate all the info for the sun at once . All times are returned in the UTC timezone . : param date : Date to calculate for . : type date : : class : ` datetime . date ` : param latitude : Latitude - Northern latitudes shoul...
dawn = self . dawn_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) sunrise = self . sunrise_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) noon = self . solar_noon_utc ( date , longitude ) sunset = self . sunset_utc ( date , latitude , longitude , observer_el...
def GET_save_getitemvalues ( self ) -> None : """Save the values of all current | GetItem | objects ."""
for item in state . getitems : for name , value in item . yield_name2value ( state . idx1 , state . idx2 ) : state . getitemvalues [ self . _id ] [ name ] = value
def sort ( line ) : """change point position if x1 , y0 < x0 , y0"""
x0 , y0 , x1 , y1 = line # if ( x0 * * 2 + y0 * * 2 ) * * 0.5 < ( x1 * * 2 + y1 * * 2 ) * * 0.5: # return ( x1 , y1 , x0 , y0) # return line # if x1 < x0: # return ( x1 , y1 , x0 , y0) # return line turn = False if abs ( x1 - x0 ) > abs ( y1 - y0 ) : if x1 < x0 : turn = True elif y1 < y0 : turn = True i...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'sentence_id' ) and self . sentence_id is not None : _dict [ 'sentence_id' ] = self . sentence_id if hasattr ( self , 'text' ) and self . text is not None : _dict [ 'text' ] = self . text if hasattr ( self , 'tones' ) and self . tones is not None : _dict [ 'tones' ] = [ x . _...
def draw_text ( data , obj ) : """Paints text on the graph ."""
content = [ ] properties = [ ] style = [ ] if isinstance ( obj , mpl . text . Annotation ) : _annotation ( obj , data , content ) # 1 : coordinates # 2 : properties ( shapes , rotation , etc ) # 3 : text style # 4 : the text # - - - - - 1 - - - - - 2 - - - 3 - - 4 - - pos = obj . get_position ( ) # from . util impo...
def autocorr_noise_id ( x , af , data_type = "phase" , dmin = 0 , dmax = 2 ) : """Lag - 1 autocorrelation based noise identification Parameters x : numpy . array phase or fractional frequency time - series data minimum recommended length is len ( x ) > 30 roughly . af : int averaging factor data _ typ...
d = 0 # number of differentiations lag = 1 if data_type is "phase" : if af > 1 : # x = scipy . signal . decimate ( x , af , n = 1 , ftype = ' fir ' ) x = x [ 0 : len ( x ) : af ] # decimate by averaging factor x = detrend ( x , deg = 2 ) # remove quadratic trend ( frequency offset and drift ...
def sanity_check ( vcs ) : """Do sanity check before making changes Check that we are not on a tag and / or do not have local changes . Returns True when all is fine ."""
if not vcs . is_clean_checkout ( ) : q = ( "This is NOT a clean checkout. You are on a tag or you have " "local changes.\n" "Are you sure you want to continue?" ) if not ask ( q , default = False ) : sys . exit ( 1 )
def _get_subplot_extents ( self , overlay , ranges , range_type ) : """Iterates over all subplots and collects the extents of each ."""
if range_type == 'combined' : extents = { 'extents' : [ ] , 'soft' : [ ] , 'hard' : [ ] , 'data' : [ ] } else : extents = { range_type : [ ] } items = overlay . items ( ) if self . batched and self . subplots : subplot = list ( self . subplots . values ( ) ) [ 0 ] subplots = [ ( k , subplot ) for k in o...
def connection_lost ( self , exception ) : """Called when the serial port is closed or the reader loop terminated otherwise ."""
if isinstance ( exception , Exception ) : logger . debug ( 'Connection to port `%s` lost: %s' , self . port , exception ) else : logger . debug ( 'Connection to port `%s` closed' , self . port ) self . connected . clear ( ) self . disconnected . set ( )
def from_string ( cls , key , key_id = None ) : """Construct an Signer instance from a private key in PEM format . Args : key ( str ) : Private key in PEM format . key _ id ( str ) : An optional key id used to identify the private key . Returns : google . auth . crypt . Signer : The constructed signer . ...
key = _helpers . from_bytes ( key ) # PEM expects str in Python 3 marker_id , key_bytes = pem . readPemBlocksFromFile ( six . StringIO ( key ) , _PKCS1_MARKER , _PKCS8_MARKER ) # Key is in pkcs1 format . if marker_id == 0 : private_key = rsa . key . PrivateKey . load_pkcs1 ( key_bytes , format = 'DER' ) # Key is in...
def pathFromIndex ( self , index ) : """Returns the joined path from the given model index . This will join together the full path with periods . : param index | < QModelIndex > : return < str >"""
item = self . _model . itemFromIndex ( index ) out = [ ] while ( item ) : out . append ( nativestring ( item . text ( ) ) ) item = item . parent ( ) return '.' . join ( reversed ( out ) )
def layer_covariance ( layer1 , layer2 = None ) : """Computes the covariance matrix between the neurons of two layers . If only one layer is passed , computes the symmetric covariance matrix of that layer ."""
layer2 = layer2 or layer1 act1 , act2 = layer1 . activations , layer2 . activations num_datapoints = act1 . shape [ 0 ] # cast to avoid numpy type promotion during division return np . matmul ( act1 . T , act2 ) / float ( num_datapoints )
def _GetParentModificationTime ( self , gzip_file_entry ) : """Retrieves the modification time of the file entry ' s parent file . Note that this retrieves the time from the file entry of the parent of the gzip file entry ' s path spec , which is different from trying to retrieve it from the gzip file entry '...
parent_file_entry = path_spec_resolver . Resolver . OpenFileEntry ( gzip_file_entry . path_spec . parent ) if not parent_file_entry : return None return parent_file_entry . modification_time
def _threshold_batch ( self , vectors , batch_size , threshold , show_progressbar , return_names ) : """Batched cosine distance ."""
vectors = self . normalize ( vectors ) # Single transpose , makes things faster . reference_transposed = self . norm_vectors . T for i in tqdm ( range ( 0 , len ( vectors ) , batch_size ) , disable = not show_progressbar ) : distances = vectors [ i : i + batch_size ] . dot ( reference_transposed ) # For safety ...
def reduce_by ( self , package_request ) : """Reduce this scope wrt a package request . Returns : A ( _ PackageScope , [ Reduction ] ) tuple , where the scope is a new scope copy with reductions applied , or self if there were no reductions , or None if the scope was completely reduced ."""
self . solver . reduction_broad_tests_count += 1 if self . package_request . conflict : # conflict scopes don ' t reduce . Instead , other scopes will be # reduced against a conflict scope . return ( self , [ ] ) # perform the reduction new_slice , reductions = self . variant_slice . reduce_by ( package_request ) #...
def calc_offset ( cube ) : """Calculate an offset . Calculate offset from the side of data so that at least 200 image pixels are in the MAD stats . Parameters cube : pyciss . ringcube . RingCube Cubefile with ring image"""
i = 0 while pd . Series ( cube . img [ : , i ] ) . count ( ) < 200 : i += 1 return max ( i , 20 )
def set_linetrace_on_frame ( f , localtrace = None ) : """Non - portable function to modify linetracing . Remember to enable global tracing with : py : func : ` sys . settrace ` , otherwise no effect !"""
traceptr , _ , _ = get_frame_pointers ( f ) if localtrace is not None : # Need to incref to avoid the frame causing a double - delete ctypes . pythonapi . Py_IncRef ( localtrace ) # Not sure if this is the best way to do this , but it works . addr = id ( localtrace ) else : addr = 0 traceptr . contents ...
def normalize_bins ( self , inplace : bool = False ) -> "HistogramCollection" : """Normalize each bin in the collection so that the sum is 1.0 for each bin . Note : If a bin is zero in all collections , the result will be inf ."""
col = self if inplace else self . copy ( ) sums = self . sum ( ) . frequencies for h in col . histograms : h . set_dtype ( float ) h . _frequencies /= sums h . _errors2 /= sums ** 2 # TODO : Does this make sense ? return col
async def enqueue_job ( self , function : str , * args : Any , _job_id : Optional [ str ] = None , _defer_until : Optional [ datetime ] = None , _defer_by : Union [ None , int , float , timedelta ] = None , _expires : Union [ None , int , float , timedelta ] = None , _job_try : Optional [ int ] = None , ** kwargs : Any...
job_id = _job_id or uuid4 ( ) . hex job_key = job_key_prefix + job_id assert not ( _defer_until and _defer_by ) , "use either 'defer_until' or 'defer_by' or neither, not both" defer_by_ms = to_ms ( _defer_by ) expires_ms = to_ms ( _expires ) with await self as conn : pipe = conn . pipeline ( ) pipe . unwatch ( ...
def from_string ( cls , cl_function , dependencies = ( ) , nmr_constraints = None ) : """Parse the given CL function into a SimpleCLFunction object . Args : cl _ function ( str ) : the function we wish to turn into an object dependencies ( list or tuple of CLLibrary ) : The list of CL libraries this function ...
return_type , function_name , parameter_list , body = split_cl_function ( cl_function ) return SimpleConstraintFunction ( return_type , function_name , parameter_list , body , dependencies = dependencies , nmr_constraints = nmr_constraints )