signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
async def send ( self ) : '''send data that was changed to emby | coro | This should be used after using any of the setter . Not necessarily immediately , but soon after . See Also post : same thing update : refresh : Returns aiohttp . ClientResponse or None if nothing needed updating'''
# Why does the whole dict need to be sent ? # because emby is dumb , and will break if I don ' t path = 'Items/{}' . format ( self . id ) resp = await self . connector . post ( path , data = self . object_dict , remote = False ) if resp . status == 400 : await EmbyObject ( self . object_dict , self . connector ) . ...
def syllabify ( word ) : '''Syllabify the given word , whether simplex or complex .'''
word = split ( word ) # detect any non - delimited compounds compound = True if re . search ( r'-| |\.' , word ) else False syllabify = _syllabify_compound if compound else _syllabify syll , rules = syllabify ( word ) yield syll , rules n = 3 if 'T4' in rules : yield syllabify ( word , T4 = False ) n -= 1 if 'e...
def get_connected_components ( graph ) : """Finds all connected components of the graph . Returns a list of lists , each containing the nodes that form a connected component . Returns an empty list for an empty graph ."""
list_of_components = [ ] component = [ ] # Not strictly necessary due to the while loop structure , but it helps the automated analysis tools # Store a list of all unreached vertices unreached = set ( graph . get_all_node_ids ( ) ) to_explore = deque ( ) while len ( unreached ) > 0 : # This happens when we reach the en...
def numpy2gdalint ( self ) : """create a dictionary for mapping numpy data types to GDAL data type codes Returns dict the type map"""
if not hasattr ( self , '__numpy2gdalint' ) : tmap = { } for group in [ 'int' , 'uint' , 'float' , 'complex' ] : for dtype in np . sctypes [ group ] : code = gdal_array . NumericTypeCodeToGDALTypeCode ( dtype ) if code is not None : tmap [ dtype ( ) . dtype . name...
def get_unique_filename ( filename , new_filename = None , new_extension = None ) : """Génère un nouveau nom pour un fichier en gardant son extension Soit le nouveau nom est généré à partir de la date ( heures + minutes + secondes + microsecondes ) soit un nouveau nom est spécifié et on l ' utilise te...
if new_extension : extension = new_extension else : extension = splitext ( filename ) [ 1 ] [ 1 : ] if not new_filename : now = real_datetime . now ( ) return '%s%s%s%s.%s' % ( unicode ( now . hour ) . zfill ( 2 ) , unicode ( now . minute ) . zfill ( 2 ) , unicode ( now . second ) . zfill ( 2 ) , unicod...
def list_cmd ( only_active , only_aliases , verbose ) : """List indices ."""
def _tree_print ( d , rec_list = None , verbose = False , indent = 2 ) : # Note that on every recursion rec _ list is copied , # which might not be very effective for very deep dictionaries . rec_list = rec_list or [ ] for idx , key in enumerate ( sorted ( d ) ) : line = ( [ '│' + ' ' * indent if i == 1...
def _timestamp_extractor_cmu ( self , staging_audio_basename , str_timestamps_with_sil_conf ) : """Parameters str _ timestamps _ with _ sil _ conf : [ [ str , str , str , str ] ] Of the form [ [ word , starting _ sec , ending _ sec , confidence ] ] Returns timestamps : [ [ str , float , float ] ]"""
filter_untimed = filter ( lambda x : len ( x ) == 4 , str_timestamps_with_sil_conf ) if filter_untimed != str_timestamps_with_sil_conf : self . __errors [ ( time ( ) , staging_audio_basename ) ] = str_timestamps_with_sil_conf str_timestamps = [ str_timestamp [ : - 1 ] for str_timestamp in filter_untimed if not any ...
def dft_preprocess_data ( arr , shift = True , axes = None , sign = '-' , out = None ) : """Pre - process the real - space data before DFT . This function multiplies the given data with the separable function : : p ( x ) = exp ( + - 1j * dot ( x - x [ 0 ] , xi [ 0 ] ) ) where ` ` x [ 0 ] ` ` and ` ` xi [ 0 ...
arr = np . asarray ( arr ) if not is_numeric_dtype ( arr . dtype ) : raise ValueError ( 'array has non-numeric data type {}' '' . format ( dtype_repr ( arr . dtype ) ) ) elif is_real_dtype ( arr . dtype ) and not is_real_floating_dtype ( arr . dtype ) : arr = arr . astype ( 'float64' ) if axes is None : axe...
def subtract ( self , expr , simplify ) : """Return a new expression where the ` expr ` expression has been removed from this expression if it exists ."""
args = self . args if expr in self . args : args = list ( self . args ) args . remove ( expr ) elif isinstance ( expr , self . __class__ ) : if all ( arg in self . args for arg in expr . args ) : args = tuple ( arg for arg in self . args if arg not in expr ) if len ( args ) == 0 : return None if...
def strip_headers_footers_pagebreaks ( docbody , page_break_posns , num_head_lines , num_foot_lines ) : """Remove page - break lines , header lines , and footer lines from the document . @ param docbody : ( list ) of strings , whereby each string in the list is a line in the document . @ param page _ break ...
num_breaks = len ( page_break_posns ) page_lens = [ ] for x in xrange ( 0 , num_breaks ) : if x < num_breaks - 1 : page_lens . append ( page_break_posns [ x + 1 ] - page_break_posns [ x ] ) page_lens . sort ( ) if ( len ( page_lens ) > 0 ) and ( num_head_lines + num_foot_lines + 1 < page_lens [ 0 ] ) : # Sa...
def _setup_profiles ( self , conversion_profiles ) : '''Add given conversion profiles checking for invalid profiles'''
# Check for invalid profiles for key , path in conversion_profiles . items ( ) : if isinstance ( path , str ) : path = ( path , ) for left , right in pair_looper ( path ) : pair = ( _format ( left ) , _format ( right ) ) if pair not in self . converters : msg = 'Invalid conve...
def _get_pga_on_rock ( self , C , rup , dists ) : """Returns the median PGA on rock , which is a sum of the magnitude and distance scaling"""
return np . exp ( self . _get_magnitude_scaling_term ( C , rup ) + self . _get_path_scaling ( C , dists , rup . mag ) )
def _use_color ( msg , ansi_fmt , output_stream ) : '''Based on : data : ` ~ exhale . configs . alwaysColorize ` , returns the colorized or non - colorized output when ` ` output _ stream ` ` is not a TTY ( e . g . redirecting to a file ) . * * Parameters * * ` ` msg ` ` ( str ) The message that is going ...
if configs . _on_rtd or ( not configs . alwaysColorize and not output_stream . isatty ( ) ) : log = msg else : log = colorize ( msg , ansi_fmt ) return log
def sync ( self , json_obj = None ) : """synchronize this transport with the Ariane server transport : return :"""
LOGGER . debug ( "Transport.sync" ) if json_obj is None : params = None if self . id is not None : params = SessionService . complete_transactional_req ( { 'ID' : self . id } ) if params is not None : if MappingService . driver_type != DriverFactory . DRIVER_REST : params [ 'OPER...
def _createphotoset ( self , myset ) : """Creates a photo set ( album ) on FB"""
if not self . _connectToFB ( ) : print ( "%s - Couldn't connect to fb" % ( directory ) ) return False logger . debug ( 'fb: Creating photo set %s' % ( myset ) ) resp = self . fb . put_object ( USER_ID , "albums" , name = myset ) if not resp . has_key ( 'id' ) : logger . error ( "%s - fb: _createphotoset fai...
def _generate_iam_role_policy ( self ) : """Generate the policy for the IAM Role . Terraform name : aws _ iam _ role . lambda _ role"""
endpoints = self . config . get ( 'endpoints' ) queue_arns = [ ] for ep in endpoints : for qname in endpoints [ ep ] [ 'queues' ] : qarn = 'arn:aws:sqs:%s:%s:%s' % ( self . aws_region , self . aws_account_id , qname ) if qarn not in queue_arns : queue_arns . append ( qarn ) pol = { "Vers...
def _decorate_urlconf ( urlpatterns , decorator = require_auth , * args , ** kwargs ) : '''Decorate all urlpatterns by specified decorator'''
if isinstance ( urlpatterns , ( list , tuple ) ) : for pattern in urlpatterns : if getattr ( pattern , 'callback' , None ) : pattern . _callback = decorator ( pattern . callback , * args , ** kwargs ) if getattr ( pattern , 'url_patterns' , [ ] ) : _decorate_urlconf ( pattern...
def memwarp ( src_ds , res = None , extent = None , t_srs = None , r = None , oudir = None , dst_ndv = 0 , verbose = True ) : """Helper function that calls warp for single input Dataset with output to memory ( GDAL Memory Driver )"""
driver = iolib . mem_drv return warp ( src_ds , res , extent , t_srs , r , driver = driver , dst_ndv = dst_ndv , verbose = verbose )
def YamlLoader ( string ) : """Load an AFF4 object from a serialized YAML representation ."""
representation = yaml . Parse ( string ) result_cls = aff4 . FACTORY . AFF4Object ( representation [ "aff4_class" ] ) aff4_attributes = { } for predicate , values in iteritems ( representation [ "attributes" ] ) : attribute = aff4 . Attribute . PREDICATES [ predicate ] tmp = aff4_attributes [ attribute ] = [ ] ...
def setCmdline ( self , value = 1 ) : """Set cmdline flag"""
# set through dictionary to avoid extra calls to _ _ setattr _ _ if value : self . __dict__ [ 'flags' ] = self . flags | _cmdlineFlag else : self . __dict__ [ 'flags' ] = self . flags & ~ _cmdlineFlag
def _save_if_needed ( request , response_content ) : """Save data to disk , if requested by the user : param request : Download request : type request : DownloadRequest : param response _ content : content of the download response : type response _ content : bytes"""
if request . save_response : file_path = request . get_file_path ( ) create_parent_folder ( file_path ) with open ( file_path , 'wb' ) as file : file . write ( response_content ) LOGGER . debug ( 'Saved data from %s to %s' , request . url , file_path )
def createLearningRateScheduler ( self , params , optimizer ) : """Creates the learning rate scheduler and attach the optimizer"""
lr_scheduler = params . get ( "lr_scheduler" , None ) if lr_scheduler is None : return None if lr_scheduler == "StepLR" : lr_scheduler_params = "{'step_size': 1, 'gamma':" + str ( params [ "learning_rate_factor" ] ) + "}" else : lr_scheduler_params = params . get ( "lr_scheduler_params" , None ) if lr_s...
def do_related ( parser , token ) : """Get N related models into a context variable optionally specifying a named related finder . * * Usage * * : : { % related < limit > [ query _ type ] [ app . model , . . . ] for < object > as < result > % } * * Parameters * * : : Option Description ` ` limit ` ` Num...
bits = token . split_contents ( ) obj_var , count , var_name , mods , finder = parse_related_tag ( bits ) return RelatedNode ( obj_var , count , var_name , mods , finder )
def _create_m2m_links_step ( self , rel_model_name , rel_key , rel_value , relation_name ) : """Link many - to - many models together . Syntax : And ` model ` with ` field ` " ` value ` " is linked to ` other model ` in the database : Example : . . code - block : : gherkin And article with name " Guidel...
lookup = { rel_key : rel_value } rel_model = get_model ( rel_model_name ) . objects . get ( ** lookup ) relation = None for m2m in rel_model . _meta . many_to_many : if relation_name in ( m2m . name , m2m . verbose_name ) : relation = getattr ( rel_model , m2m . name ) break if not relation : tr...
def SetDefaultValue ( self , scan_object ) : """Sets the default ( non - match ) value . Args : scan _ object : a scan object , either a scan tree sub node ( instance of PathFilterScanTreeNode ) or a string containing a path . Raises : TypeError : if the scan object is of an unsupported type . ValueErro...
if ( not isinstance ( scan_object , PathFilterScanTreeNode ) and not isinstance ( scan_object , py2to3 . STRING_TYPES ) ) : raise TypeError ( 'Unsupported scan object type.' ) if self . default_value : raise ValueError ( 'Default value already set.' ) self . default_value = scan_object
def run_main ( args : argparse . Namespace , do_exit = True ) -> None : """Runs the checks and exits . To extend this tool , use this function and set do _ exit to False to get returned the status code ."""
if args . init : generate ( ) return None # exit after generate instead of starting to lint handler = CheckHandler ( file = args . config_file , out_json = args . json , files = args . files ) for style in get_stylers ( ) : handler . run_linter ( style ( ) ) for linter in get_linters ( ) : handler . run...
def from_path_and_array ( cls , path , folder , y , classes = None , val_idxs = None , test_name = None , num_workers = 8 , tfms = ( None , None ) , bs = 64 ) : """Read in images given a sub - folder and their labels given a numpy array Arguments : path : a root path of the data ( used for storing trained model...
assert not ( tfms [ 0 ] is None or tfms [ 1 ] is None ) , "please provide transformations for your train and validation sets" assert not ( os . path . isabs ( folder ) ) , "folder needs to be a relative path" fnames = np . core . defchararray . add ( f'{folder}/' , sorted ( os . listdir ( f'{path}{folder}' ) ) ) return...
def transform_from_rot_trans ( R , t ) : """Transforation matrix from rotation matrix and translation vector ."""
R = R . reshape ( 3 , 3 ) t = t . reshape ( 3 , 1 ) return np . vstack ( ( np . hstack ( [ R , t ] ) , [ 0 , 0 , 0 , 1 ] ) )
def enrollment_start ( self , name , mode = None , pin = None , phone_number = None ) : """Start Client Enrollment . Uses the POST to / enrollments interface . : Args : * * client * : ( str ) Client ' s Name * * mode * : ( str ) DEPRECATED . Presence of PIN is used to determine mode ( AudioPass vs AudioPIN ) ...
data = { "name" : name , } if mode : warning_msg = 'WARNING: The "mode" parameter for enrollment_start is DEPRECATED and will be ignored. ' 'To avoid incompatibility with a future release please stop providing it.' print ( warning_msg , file = sys . stderr ) if pin : data [ "pin" ] = pin if phone_number : ...
def get_absolute_name ( package , relative_name ) : """Joins a package name and a relative name . Args : package : A dotted name , e . g . foo . bar . baz relative _ name : A dotted name with possibly some leading dots , e . g . . . x . y Returns : The relative name appended to the parent ' s package , af...
path = package . split ( '.' ) if package else [ ] name = relative_name . lstrip ( '.' ) ndots = len ( relative_name ) - len ( name ) if ndots > len ( path ) : return relative_name absolute_path = path [ : len ( path ) + 1 - ndots ] if name : absolute_path . append ( name ) return '.' . join ( absolute_path )
def __scripts ( self , filestem ) : """Generates the required scripts ."""
script_construct = open ( '%s/%s' % ( self . tmpdir , RSD . CONSTRUCT ) , 'w' ) script_save = open ( '%s/%s' % ( self . tmpdir , RSD . SAVE ) , 'w' ) script_subgroups = open ( '%s/%s' % ( self . tmpdir , RSD . SUBGROUPS ) , 'w' ) # Permit the owner to execute and read this script for fn in RSD . SCRIPTS : os . chmo...
def get_rules ( ) : """Returns all enabled rules . : rtype : [ Rule ]"""
paths = [ rule_path for path in get_rules_import_paths ( ) for rule_path in sorted ( path . glob ( '*.py' ) ) ] return sorted ( get_loaded_rules ( paths ) , key = lambda rule : rule . priority )
def resourceprep ( string , allow_unassigned = False ) : """Process the given ` string ` using the Resourceprep ( ` RFC 6122 ` _ ) profile . In the error cases defined in ` RFC 3454 ` _ ( stringprep ) , a : class : ` ValueError ` is raised ."""
chars = list ( string ) _resourceprep_do_mapping ( chars ) do_normalization ( chars ) check_prohibited_output ( chars , ( stringprep . in_table_c12 , stringprep . in_table_c21 , stringprep . in_table_c22 , stringprep . in_table_c3 , stringprep . in_table_c4 , stringprep . in_table_c5 , stringprep . in_table_c6 , string...
def fetch ( self , refund_id , data = { } , ** kwargs ) : """Refund object for given paymnet Id Args : refund _ id : Refund Id for which refund has to be retrieved Returns : Refund dict for given refund Id"""
return super ( Refund , self ) . fetch ( refund_id , data , ** kwargs )
def chain_split ( * splits : Iterable [ Callable [ ... , Any ] ] ) -> Callable [ [ BaseChain ] , Iterable [ BaseChain ] ] : # noqa : E501 """Construct and execute multiple concurrent forks of the chain . Any number of forks may be executed . For each fork , provide an iterable of commands . Returns the result...
if not splits : raise ValidationError ( "Cannot use `chain_split` without providing at least one split" ) @ functools . wraps ( chain_split ) @ to_tuple def _chain_split ( chain : BaseChain ) -> Iterable [ BaseChain ] : for split_fns in splits : result = build ( chain , * split_fns , ) yield res...
def getActive ( cls ) : """Return either the currently active StreamingContext ( i . e . , if there is a context started but not stopped ) or None ."""
activePythonContext = cls . _activeContext if activePythonContext is not None : # Verify that the current running Java StreamingContext is active and is the same one # backing the supposedly active Python context activePythonContextJavaId = activePythonContext . _jssc . ssc ( ) . hashCode ( ) activeJvmContextOp...
def fetch_ludic_numbers ( limit : int ) -> list : """Function to generate and return all ludic numbers up to a given limit . Examples : fetch _ ludic _ numbers ( 10) returns [ 1 , 2 , 3 , 5 , 7] fetch _ ludic _ numbers ( 25) returns [ 1 , 2 , 3 , 5 , 7 , 11 , 13 , 17 , 23 , 25] fetch _ ludic _ numbers (...
ludics = list ( range ( 1 , limit + 1 ) ) idx = 1 while idx != len ( ludics ) : n_val = ludics [ idx ] del_ind = idx + n_val while del_ind < len ( ludics ) : del ludics [ del_ind ] del_ind += ( n_val - 1 ) idx += 1 return ludics
def get_rotation_parameters ( phases , magnitudes ) : """Simulates one step of rotations . Given lists of phases and magnitudes of the same length : math : ` N ` , such that : math : ` N = 2 ^ n ` for some positive integer : math : ` n ` , finds the rotation angles required for one step of phase and magnitude...
# will hold the angles for controlled rotations # in the phase unification and probability unification steps , # respectively z_thetas = [ ] y_thetas = [ ] # will hold updated phases and magnitudes after rotations new_phases = [ ] new_magnitudes = [ ] for i in range ( 0 , len ( phases ) , 2 ) : # find z rotation angles...
def _datetime ( self ) : """Conversion of the Date object into a : py : class : ` datetime . datetime ` . The resulting object is a timezone - naive instance in the REF _ SCALE time - scale"""
if 'dt' not in self . _cache . keys ( ) : self . _cache [ 'dt' ] = self . MJD_T0 + timedelta ( days = self . _d , seconds = self . _s ) return self . _cache [ 'dt' ]
def _set_attributes ( self ) : """Recursively transforms config dictionaries into instance attrs to make for easy dot attribute access instead of dictionary access ."""
# turn config dict into nested objects config = obj ( self . _config_dict ) # set the attributes onto instance for k , v in self . _config_dict . items ( ) : setattr ( self , k , getattr ( config , k ) )
def aggregate ( self , region_agg = None , sector_agg = None , region_names = None , sector_names = None , inplace = True , pre_aggregation = False ) : """Aggregates the IO system . Aggregation can be given as vector ( use pymrio . build _ agg _ vec ) or aggregation matrix . In the case of a vector this must be...
# Development note : This can not be put in the CoreSystem b / c # than the recalculation of the extension coefficients would not # work . if not inplace : self = self . copy ( ) try : self . reset_to_flows ( ) except ResetError : raise AggregationError ( "System under-defined for aggregation - " "do a 'cal...
def token_range ( self , first_token , last_token , include_extra = False ) : """Yields all tokens in order from first _ token through and including last _ token . If include _ extra is True , includes non - coding tokens such as tokenize . NL and . COMMENT ."""
for i in xrange ( first_token . index , last_token . index + 1 ) : if include_extra or not is_non_coding_token ( self . _tokens [ i ] . type ) : yield self . _tokens [ i ]
async def forget ( request ) : """Called to forget the userid for a request Args : request : aiohttp Request object Raises : RuntimeError : Middleware is not installed"""
auth_policy = request . get ( POLICY_KEY ) if auth_policy is None : raise RuntimeError ( 'auth_middleware not installed' ) return await auth_policy . forget ( request )
def alleleupdater ( self , sample , gene , targetallele ) : """Updates file of alleles if the new allele passes length and identity checks : param sample : sample object : param gene : name of gene of interest : param targetallele : closest allele in database"""
from Bio . Seq import Seq from Bio . Alphabet import IUPAC from Bio . SeqRecord import SeqRecord # As there is some discrepancy with the capitalisation of terms , make sure it is consistent analysistype = 'rMLST' if self . analysistype . lower ( ) == 'rmlst' else 'MLST' # Set the directory containing the profile and al...
def which ( exe_name ) : """Locate a program file in the user ' s path . @ param exec _ name : name of the executable file . @ return : ` ` None ` ` if the executable has not been found in the user ' s path , or the path for the executable file ."""
def is_exe ( file_path_name ) : return os . path . isfile ( file_path_name ) and os . access ( file_path_name , os . X_OK ) is_platform_windows = ( platform . system ( ) == 'Windows' ) fpath , _fname = os . path . split ( exe_name ) if fpath : if is_exe ( exe_name ) : return exe_name else : for path...
def get_request ( cls ) : """Get the HTTPRequest object from thread storage or from a callee by searching each frame in the call stack ."""
request = cls . get_global ( 'request' ) if request : return request try : stack = inspect . stack ( ) except IndexError : # in some cases this may return an index error # ( pyc files dont match py files for example ) return for frame , _ , _ , _ , _ , _ in stack : if 'request' in frame . f_locals : ...
def get_token ( authed_user : hug . directives . user ) : """Get Job details : param authed _ user : : return :"""
user_model = Query ( ) user = db . search ( user_model . username == authed_user ) [ 0 ] if user : out = { 'user' : user [ 'username' ] , 'api_key' : user [ 'api_key' ] } else : # this should never happen out = { 'error' : 'User {0} does not exist' . format ( authed_user ) } return out
def setAutoResizeToContents ( self , state ) : """Sets whether or not this widget should automatically resize its height based on its contents . : param state | < bool >"""
self . _autoResizeToContents = state if state : self . resizeToContents ( ) self . setVerticalScrollBarPolicy ( QtCore . Qt . ScrollBarAlwaysOff ) self . setHorizontalScrollBarPolicy ( QtCore . Qt . ScrollBarAlwaysOff ) else : self . setVerticalScrollBarPolicy ( QtCore . Qt . ScrollBarAsNeeded ) sel...
def p_break_statement_1 ( self , p ) : """break _ statement : BREAK SEMI | BREAK AUTOSEMI"""
p [ 0 ] = self . asttypes . Break ( ) p [ 0 ] . setpos ( p )
def get_params ( self , tid ) : """Returns the parameters found in the stack when the hooked function was last called by this thread . @ type tid : int @ param tid : Thread global ID . @ rtype : tuple ( arg , arg , arg . . . ) @ return : Tuple of arguments ."""
try : params = self . get_params_stack ( tid ) [ - 1 ] except IndexError : msg = "Hooked function called from thread %d already returned" raise IndexError ( msg % tid ) return params
def add_task_to_job ( self , job_or_job_name , task_command , task_name = None , ** kwargs ) : """Add a task to a job owned by the Dagobah instance ."""
if isinstance ( job_or_job_name , Job ) : job = job_or_job_name else : job = self . get_job ( job_or_job_name ) if not job : raise DagobahError ( 'job %s does not exist' % job_or_job_name ) logger . debug ( 'Adding task with command {0} to job {1}' . format ( task_command , job . name ) ) if not job . state...
def _expect ( self , expected , times = 50 ) : """Find the ` expected ` line within ` times ` trials . Args : expected str : the expected string times int : number of trials"""
print '[%s] Expecting [%s]' % ( self . port , expected ) retry_times = 10 while times > 0 and retry_times > 0 : line = self . _readline ( ) print '[%s] Got line [%s]' % ( self . port , line ) if line == expected : print '[%s] Expected [%s]' % ( self . port , expected ) return if not line...
def video_search ( self , entitiy_type , query , ** kwargs ) : """Search the TV schedule database Where ` ` entitiy _ type ` ` is a comma separated list of : ` ` movie ` ` Movie ` ` tvseries ` ` TV series ` ` episode ` ` Episode titles ` ` onetimeonly ` ` TV programs ` ` credit ` ` People work...
return self . make_request ( 'video' , entitiy_type , query , kwargs )
def build_score_request ( scoring_system , request , context_name = None , rev_id = None , model_name = None ) : """Build an : class : ` ores . ScoreRequest ` from information contained in a request . : Parameters : scoring _ system : : class : ` ores . ScoringSystem ` A scoring system to build request with...
rev_ids = parse_rev_ids ( request , rev_id ) model_names = parse_model_names ( request , model_name ) precache = 'precache' in request . args include_features = 'features' in request . args injection_caches = parse_injection ( request , rev_id ) model_info = parse_model_info ( request ) if context_name and context_name...
def _disconnect ( self , error ) : "done"
if self . _on_disconnect : self . _on_disconnect ( str ( error ) ) if self . _sender : self . _sender . connectionLost ( Failure ( error ) ) self . _when_done . fire ( Failure ( error ) )
def flip_whole ( self , tour ) : """Test flipping all contigs at the same time to see if score improves ."""
score , = self . evaluate_tour_Q ( tour ) self . signs = - self . signs score_flipped , = self . evaluate_tour_Q ( tour ) if score_flipped > score : tag = ACCEPT else : self . signs = - self . signs tag = REJECT self . flip_log ( "FLIPWHOLE" , score , score_flipped , tag ) return tag
def login ( session , username , password , class_name = None ) : """Login on coursera . org with the given credentials . This adds the following cookies to the session : sessionid , maestro _ login , maestro _ login _ flag"""
logging . debug ( 'Initiating login.' ) try : session . cookies . clear ( '.coursera.org' ) logging . debug ( 'Cleared .coursera.org cookies.' ) except KeyError : logging . debug ( 'There were no .coursera.org cookies to be cleared.' ) # Hit class url if class_name is not None : class_url = CLASS_URL . ...
def reset ( self , fid = 0 ) : """Reset the object ' s resources to its initialized state . : param fid : the id of a sub - fitter"""
self . _checkid ( fid ) self . _fitids [ fid ] [ "solved" ] = False self . _fitids [ fid ] [ "haserr" ] = False if not self . _fitids [ fid ] [ "looped" ] : return self . _fitproxy . reset ( fid ) else : self . _fitids [ fid ] [ "looped" ] = False return True
def request_login ( blink , url , username , password , is_retry = False ) : """Login request . : param blink : Blink instance . : param url : Login url . : param username : Blink username . : param password : Blink password . : param is _ retry : Is this part of a re - authorization attempt ?"""
headers = { 'Host' : DEFAULT_URL , 'Content-Type' : 'application/json' } data = dumps ( { 'email' : username , 'password' : password , 'client_specifier' : 'iPhone 9.2 | 2.2 | 222' } ) return http_req ( blink , url = url , headers = headers , data = data , json_resp = False , reqtype = 'post' , is_retry = is_retry )
def route ( app_or_blueprint , context = default_context , ** kwargs ) : """attach a transmute route ."""
def decorator ( fn ) : fn = describe ( ** kwargs ) ( fn ) transmute_func = TransmuteFunction ( fn ) routes , handler = create_routes_and_handler ( transmute_func , context ) for r in routes : # push swagger info . if not hasattr ( app_or_blueprint , SWAGGER_ATTR_NAME ) : setattr ( ap...
def find_out_pattern ( self , pattern ) : """This function will read the standard error of the program and return a matching pattern if found . EG . prog _ obj . FindErrPattern ( " Update of mySQL failed " )"""
if self . wdir != '' : stdout = "%s/%s" % ( self . wdir , self . stdout ) else : stdout = self . stdout response = [ ] # First we check if the file we want to print does exists if os . path . exists ( stdout ) : with open_ ( stdout , 'r' ) as f : for line in f : if pattern in line : ...
def _open ( self ) : """Opens the compressed log file . Returns file : file - like object of the resulting stream ."""
# The gzip module supports directly setting encoding as of Python 3.3. # pylint : disable = unexpected - keyword - arg if py2to3 . PY_3 : return gzip . open ( self . baseFilename , mode = self . mode , encoding = self . encoding ) return gzip . open ( self . baseFilename , self . mode )
def get_vnetwork_portgroups_input_datacenter ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_vnetwork_portgroups = ET . Element ( "get_vnetwork_portgroups" ) config = get_vnetwork_portgroups input = ET . SubElement ( get_vnetwork_portgroups , "input" ) datacenter = ET . SubElement ( input , "datacenter" ) datacenter . text = kwargs . pop ( 'datacenter' ) callback = kwargs...
def spark_shape ( points , shapes , fill = None , color = 'blue' , width = 5 , yindex = 0 , heights = None ) : """TODO : Docstring for spark . Parameters points : array - like shapes : array - like fill : array - like , optional Returns Chart"""
assert len ( points ) == len ( shapes ) + 1 data = [ { 'marker' : { 'color' : 'white' } , 'x' : [ points [ 0 ] , points [ - 1 ] ] , 'y' : [ yindex , yindex ] } ] if fill is None : fill = [ False ] * len ( shapes ) if heights is None : heights = [ 0.4 ] * len ( shapes ) lays = [ ] for i , ( shape , height ) in e...
def is_generic_union ( type_ : Type ) -> bool : """Determines whether a type is a Union [ . . . ] . How to do this varies for different Python versions , due to the typing library not having a stable API . This functions smooths over the differences . Args : type _ : The type to check . Returns : True...
if hasattr ( typing , '_GenericAlias' ) : # 3.7 return ( isinstance ( type_ , typing . _GenericAlias ) and # type : ignore type_ . __origin__ is Union ) else : if hasattr ( typing , '_Union' ) : # 3.6 return isinstance ( type_ , typing . _Union ) # type : ignore else : # 3.5 and earlier ...
def get_attrs ( self ) : """Get the global attributes from underlying data set ."""
return FrozenOrderedDict ( ( a , getattr ( self . ds , a ) ) for a in self . ds . ncattrs ( ) )
def to_XML ( self , xml_declaration = True , xmlns = True ) : """Dumps object fields to an XML - formatted string . The ' xml _ declaration ' switch enables printing of a leading standard XML line containing XML version and encoding . The ' xmlns ' switch enables printing of qualified XMLNS prefixes . : par...
root_node = self . _to_DOM ( ) if xmlns : xmlutils . annotate_with_XMLNS ( root_node , NO2INDEX_XMLNS_PREFIX , NO2INDEX_XMLNS_URL ) return xmlutils . DOM_node_to_XML ( root_node , xml_declaration )
def console_to_str ( data ) : # type : ( bytes ) - > Text """Return a string , safe for output , of subprocess output . We assume the data is in the locale preferred encoding . If it won ' t decode properly , we warn the user but decode as best we can . We also ensure that the output can be safely written t...
# First , get the encoding we assume . This is the preferred # encoding for the locale , unless that is not found , or # it is ASCII , in which case assume UTF - 8 encoding = locale . getpreferredencoding ( ) if ( not encoding ) or codecs . lookup ( encoding ) . name == "ascii" : encoding = "utf-8" # Now try to dec...
def _PrintAnalysisReportsDetails ( self , storage_reader ) : """Prints the details of the analysis reports . Args : storage _ reader ( StorageReader ) : storage reader ."""
if not storage_reader . HasAnalysisReports ( ) : self . _output_writer . Write ( 'No analysis reports stored.\n\n' ) return for index , analysis_report in enumerate ( storage_reader . GetAnalysisReports ( ) ) : title = 'Analysis report: {0:d}' . format ( index ) table_view = views . ViewsFactory . GetTa...
def _interpolate_with_fill ( self , method = 'pad' , axis = 0 , inplace = False , limit = None , fill_value = None , coerce = False , downcast = None ) : """fillna but using the interpolate machinery"""
inplace = validate_bool_kwarg ( inplace , 'inplace' ) # if we are coercing , then don ' t force the conversion # if the block can ' t hold the type if coerce : if not self . _can_hold_na : if inplace : return [ self ] else : return [ self . copy ( ) ] values = self . values i...
def import_from_dict ( session , data , sync = [ ] ) : """Imports databases and druid clusters from dictionary"""
if isinstance ( data , dict ) : logging . info ( 'Importing %d %s' , len ( data . get ( DATABASES_KEY , [ ] ) ) , DATABASES_KEY ) for database in data . get ( DATABASES_KEY , [ ] ) : Database . import_from_dict ( session , database , sync = sync ) logging . info ( 'Importing %d %s' , len ( data . ge...
def ParseTextToDicts ( self , * args , ** kwargs ) : """Calls ParseText and turns the result into list of dicts . List items are dicts of rows , dict key is column header and value is column value . Args : text : ( str ) , Text to parse with embedded newlines . eof : ( boolean ) , Set to False if we are p...
result_lists = self . ParseText ( * args , ** kwargs ) result_dicts = [ ] for row in result_lists : result_dicts . append ( dict ( zip ( self . header , row ) ) ) return result_dicts
def hash_file ( filename ) : """Hash a file using the same method the registry uses ( currently SHA - 256 ) . : param filename : Name of file to hash : type filename : str : rtype : str : returns : Hex - encoded hash of file ' s content ( prefixed by ` ` sha256 : ` ` )"""
sha256 = hashlib . sha256 ( ) with open ( filename , 'rb' ) as f : for chunk in iter ( lambda : f . read ( 8192 ) , b'' ) : sha256 . update ( chunk ) return 'sha256:' + sha256 . hexdigest ( )
def build_ports_dict ( nsg , direction_key , ip_protocol ) : """Build entire ports array filled with True ( Allow ) , False ( Deny ) and None ( default - Deny ) based on the provided Network Security Group object , direction and protocol ."""
rules = nsg [ 'properties' ] [ 'securityRules' ] rules = sorted ( rules , key = lambda k : k [ 'properties' ] [ 'priority' ] ) ports = { } for rule in rules : # Skip rules with different direction if not StringUtils . equal ( direction_key , rule [ 'properties' ] [ 'direction' ] ) : continue # Check the...
def _sample_item ( self , ** kwargs ) : """Sample an item from the pool according to the instrumental distribution"""
loc = np . random . choice ( self . _n_items , p = self . _inst_pmf ) weight = ( 1 / self . _n_items ) / self . _inst_pmf [ loc ] return loc , weight , { }
def set_mlag_id ( self , name , value = None , default = False , disable = False ) : """Configures the interface mlag value for the specified interface Args : name ( str ) : The interface to configure . Valid values for the name arg include Port - Channel * value ( str ) : The mlag identifier to cofigure on...
cmd = self . command_builder ( 'mlag' , value = value , default = default , disable = disable ) return self . configure_interface ( name , cmd )
def decorate_HTTP_verb_method ( method ) : """Prepare and Post - Process HTTP VERB method for BigIP - RESTServer request . This function decorates all of the HTTP VERB methods in the iControlRESTSession class . It provides the core logic for this module . If necessary it validates and assembles a uri from par...
@ functools . wraps ( method ) def wrapper ( self , RIC_base_uri , ** kwargs ) : partition = kwargs . pop ( 'partition' , '' ) sub_path = kwargs . pop ( 'subPath' , '' ) suffix = kwargs . pop ( 'suffix' , '' ) identifier , kwargs = _unique_resource_identifier_from_kwargs ( ** kwargs ) uri_as_parts =...
def pull_log_dump ( self , project_name , logstore_name , from_time , to_time , file_path , batch_size = None , compress = None , encodings = None , shard_list = None , no_escape = None ) : """dump all logs seperatedly line into file _ path , file _ path , the time parameters are log received time on server side . ...
file_path = file_path . replace ( "{}" , "{0}" ) if "{0}" not in file_path : file_path += "{0}" return pull_log_dump ( self , project_name , logstore_name , from_time , to_time , file_path , batch_size = batch_size , compress = compress , encodings = encodings , shard_list = shard_list , no_escape = no_escape )
def argvquote ( arg , force = False ) : """Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged . This is the same thing Popen does when supplied with an list of arguments . Arguments in a command line should be separated by spaces ; this ...
if not force and len ( arg ) != 0 and not any ( [ c in arg for c in ' \t\n\v"' ] ) : return arg else : n_backslashes = 0 cmdline = '"' for c in arg : if c == "\\" : # first count the number of current backslashes n_backslashes += 1 continue if c == '"' : # Escape ...
def get_service_location_info ( self , service_location_id ) : """Request service location info Parameters service _ location _ id : int Returns dict"""
url = urljoin ( URLS [ 'servicelocation' ] , service_location_id , "info" ) headers = { "Authorization" : "Bearer {}" . format ( self . access_token ) } r = requests . get ( url , headers = headers ) r . raise_for_status ( ) return r . json ( )
def _query_account_key ( cli_ctx , account_name ) : """Query the storage account key . This is used when the customer doesn ' t offer account key but name ."""
rg , scf = _query_account_rg ( cli_ctx , account_name ) t_storage_account_keys = get_sdk ( cli_ctx , CUSTOM_MGMT_STORAGE , 'models.storage_account_keys#StorageAccountKeys' ) if t_storage_account_keys : return scf . storage_accounts . list_keys ( rg , account_name ) . key1 # of type : models . storage _ account _ li...
async def sunionstore ( self , dest , keys , * args ) : """Store the union of sets specified by ` ` keys ` ` into a new set named ` ` dest ` ` . Returns the number of keys in the new set ."""
args = list_or_args ( keys , args ) return await self . execute_command ( 'SUNIONSTORE' , dest , * args )
def set ( self , k , v , obj = 'override' ) : 'obj is a Sheet instance , or a Sheet [ sub ] class . obj = " override " means override all ; obj = " default " means last resort .'
if k not in self : self [ k ] = dict ( ) self [ k ] [ self . objname ( obj ) ] = v return v
def sanitize_http_wsgi_env ( client , event ) : """Sanitizes WSGI environment variables : param client : an ElasticAPM client : param event : a transaction or error event : return : The modified event"""
try : env = event [ "context" ] [ "request" ] [ "env" ] event [ "context" ] [ "request" ] [ "env" ] = varmap ( _sanitize , env ) except ( KeyError , TypeError ) : pass return event
def draw ( self ) : """Draws the feature correlation to dependent variable , called from fit ."""
pos = np . arange ( self . scores_ . shape [ 0 ] ) + 0.5 self . ax . barh ( pos , self . scores_ ) # Set the labels for the bars self . ax . set_yticks ( pos ) self . ax . set_yticklabels ( self . features_ ) return self . ax
def get ( self , url ) : """Lookup the given url and return an entry if found . Else return None . The returned entry is a dict with metadata about the content and a ' content ' key with a file path value : param url : : return :"""
self . _load ( url ) self . _flush ( ) return self . metadata [ url ]
def create_widget ( self ) : """Create the underlying widget ."""
d = self . declaration self . widget = Icon ( self . get_context ( ) , None , d . style )
def cache_parameter_group_present ( name , region = None , key = None , keyid = None , profile = None , ** args ) : '''Ensure cache parameter group exists . name A name for the cache parameter group . CacheParameterGroupName A name for the cache parameter group . Note : In general this parameter is not ne...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } args = dict ( [ ( k , v ) for k , v in args . items ( ) if not k . startswith ( '_' ) ] ) tunables = args . pop ( 'ParameterNameValues' , None ) current = __salt__ [ 'boto3_elasticache.describe_cache_parameter_groups' ] ( name , region = regio...
def delete ( self , callback = None , errback = None ) : """Delete the Network and all associated addresses"""
return self . _rest . delete ( self . id , callback = callback , errback = errback )
def _create ( self , ** kwargs ) : """wrapped by ` create ` override that in subclasses to customize"""
if 'uri' in self . _meta_data : error = "There was an attempt to assign a new uri to this " "resource, the _meta_data['uri'] is %s and it should" " not be changed." % ( self . _meta_data [ 'uri' ] ) raise URICreationCollision ( error ) self . _check_exclusive_parameters ( ** kwargs ) requests_params = self . _h...
def stem ( self , word ) : """Stem a Dutch word and return the stemmed form . : param word : The word that is stemmed . : type word : str or unicode : return : The stemmed form . : rtype : unicode"""
word = word . lower ( ) step2_success = False # Vowel accents are removed . word = ( word . replace ( "\xE4" , "a" ) . replace ( "\xE1" , "a" ) . replace ( "\xEB" , "e" ) . replace ( "\xE9" , "e" ) . replace ( "\xED" , "i" ) . replace ( "\xEF" , "i" ) . replace ( "\xF6" , "o" ) . replace ( "\xF3" , "o" ) . replace ( "\...
def Add_text ( self ) : """Add measurement data lines to the text window ."""
self . selected_meas = [ ] if self . COORDINATE_SYSTEM == 'geographic' : zijdblock = self . Data [ self . s ] [ 'zijdblock_geo' ] elif self . COORDINATE_SYSTEM == 'tilt-corrected' : zijdblock = self . Data [ self . s ] [ 'zijdblock_tilt' ] else : zijdblock = self . Data [ self . s ] [ 'zijdblock' ] tmin_ind...
def sphere_ball_intersection ( R , r ) : """Compute the surface area of the intersection of sphere of radius R centered at ( 0 , 0 , 0 ) with a ball of radius r centered at ( R , 0 , 0 ) . Parameters R : float , sphere radius r : float , ball radius Returns area : float , the surface are ."""
x = ( 2 * R ** 2 - r ** 2 ) / ( 2 * R ) # x coord of plane if x >= - R : return 2 * np . pi * R * ( R - x ) if x < - R : return 4 * np . pi * R ** 2
def native_api_call ( self , service , method , data , options , multipart_form = False , multipart_form_data = None , stream = False , http_path = "/api/meta/v1/" , http_method = 'POST' , get_params = None , connect_timeout_sec = 60 ) : """: type app : metasdk . MetaApp : rtype : requests . Response"""
if get_params is None : get_params = { } if 'self' in data : # может не быть , если вызывается напрямую из кода , # а не из прослоек типа DbQueryService data . pop ( "self" ) if options : data . update ( options ) _headers = dict ( self . __default_headers ) if self . auth_user_id : _headers [ 'X-META-A...
def load_system_config ( config_file = None , work_dir = None , allow_missing = False ) : """Load bcbio _ system . yaml configuration file , handling standard defaults . Looks for configuration file in default location within final base directory from a standard installation . Handles both standard installs (...
docker_config = _get_docker_config ( ) if config_file is None : config_file = "bcbio_system.yaml" if not os . path . exists ( config_file ) : base_dir = get_base_installdir ( ) test_config = os . path . join ( base_dir , "galaxy" , config_file ) if os . path . exists ( test_config ) : config_fil...
def create_tempdir ( suffix = '' , prefix = 'tmp' , directory = None , delete = True ) : """Create a tempdir and return the path . This function registers the new temporary directory for deletion with the atexit module ."""
tempd = tempfile . mkdtemp ( suffix = suffix , prefix = prefix , dir = directory ) if delete : atexit . register ( _cleanup_tempdir , tempd ) return tempd
def make_fileitem_peinfo_type ( petype , condition = 'is' , negate = False , preserve_case = False ) : """Create a node for FileItem / PEInfo / Type : return : A IndicatorItem represented as an Element node"""
document = 'FileItem' search = 'FileItem/PEInfo/Type' content_type = 'string' content = petype ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate , preserve_case = preserve_case ) return ii_node
def get_latent_pred_loss ( latents_pred , latents_discrete_hot , hparams ) : """Latent prediction and loss ."""
latents_logits = tf . layers . dense ( latents_pred , 2 ** hparams . bottleneck_bits , name = "extra_logits" ) loss = tf . nn . softmax_cross_entropy_with_logits_v2 ( labels = tf . stop_gradient ( latents_discrete_hot ) , logits = latents_logits ) return loss
def parent ( self ) : """Select the direct child ( ren ) from the UI element ( s ) given by the query expression , see ` ` QueryCondition ` ` for more details about the selectors . Warnings : Experimental method , may not be available for all drivers . Returns : : py : class : ` UIObjectProxy < poco . pro...
sub_query = build_query ( None ) # as placeholder query = ( '^' , ( self . query , sub_query ) ) obj = UIObjectProxy ( self . poco ) obj . query = query return obj
def eval_py ( self , _globals , _locals ) : """Evaluates a file containing a Python params dictionary ."""
try : params = eval ( self . script , _globals , _locals ) except NameError as e : raise Exception ( 'Failed to evaluate parameters: {}' . format ( str ( e ) ) ) except ResolutionError as e : raise Exception ( 'GetOutput: {}' . format ( str ( e ) ) ) return params