sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def crtPrfNrlTc(aryBoxCar, varNumMtDrctn, varNumVol, tplPngSize, varNumX, varExtXmin, varExtXmax, varNumY, varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin, varPrfStdMax, varPar): """Create neural model time courses from pixel-wise boxcar functions. Parameters ---------...
Create neural model time courses from pixel-wise boxcar functions. Parameters ---------- aryBoxCar : 4d numpy array, shape [n_x_pix, n_y_pix, n_mtn_dir, n_vol] Description of input 1. varNumMtDrctn : float, positive Description of input 2. varNumVol : float, positive Descrip...
entailment
def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn, switchHrfSet, lgcOldSchoolHrf, varPar,): """Create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNu...
Create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNumVol : float, positive Description of input 2. varTr : float, positive Description of input 1. tplPngSize : tuple ...
entailment
def rsmplInHighRes(aryBoxCarConv, tplPngSize, tplVslSpcHighSze, varNumMtDrctn, varNumVol): """Resample pixel-time courses in high-res visual space. Parameters ---------- input1 : 2d numpy array, shape [n_samples, n_measurements...
Resample pixel-time courses in high-res visual space. Parameters ---------- input1 : 2d numpy array, shape [n_samples, n_measurements] Description of input 1. input2 : float, positive Description of input 2. Returns ------- data : 2d numpy array, shape [n_samples, n_measuremen...
entailment
def get_arg_parse(): """Parses the Command Line Arguments using argparse.""" # Create parser object: objParser = argparse.ArgumentParser() # Add argument to namespace -strCsvPrf results file path: objParser.add_argument('-strCsvPrf', required=True, metavar='/path/to/my_pr...
Parses the Command Line Arguments using argparse.
entailment
def main(): """pyprf_sim entry point.""" # Get list of input arguments (without first one, which is the path to the # function that is called): --NOTE: This is another way of accessing # input arguments, but since we use 'argparse' it is redundant. # lstArgs = sys.argv[1:] strWelcome = 'pyprf_s...
pyprf_sim entry point.
entailment
def login_required(wrapped): """ Requires that the user is logged in and authorized to execute requests Except if the method is in authorized_methods of the auth_collection Then he can execute the requests even not being authorized """ @wraps(wrapped) def wrapper(*args, **kwargs): re...
Requires that the user is logged in and authorized to execute requests Except if the method is in authorized_methods of the auth_collection Then he can execute the requests even not being authorized
entailment
def serializable(wrapped): """ If a keyword argument 'serialize' with a True value is passed to the Wrapped function, the return of the wrapped function will be serialized. Nothing happens if the argument is not passed or the value is not True """ @wraps(wrapped) def wrapper(*args, **kwargs...
If a keyword argument 'serialize' with a True value is passed to the Wrapped function, the return of the wrapped function will be serialized. Nothing happens if the argument is not passed or the value is not True
entailment
def deserialize(to_deserialize, *args, **kwargs): """ Deserializes a string into a PyMongo BSON """ if isinstance(to_deserialize, string_types): if re.match('^[0-9a-f]{24}$', to_deserialize): return ObjectId(to_deserialize) try: return bson_loads(to_deserialize, *...
Deserializes a string into a PyMongo BSON
entailment
def _doAtomicFileCreation(filePath): """Tries to atomically create the requested file.""" try: _os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL)) return True except OSError as e: if e.errno == _errno.EEXIST: return False else: raise e
Tries to atomically create the requested file.
entailment
def findNextFile(folder='.', prefix=None, suffix=None, fnameGen=None, base=0, maxattempts=10): """Finds the next available file-name in a sequence. This function will create a file of zero size and will return the path to ...
Finds the next available file-name in a sequence. This function will create a file of zero size and will return the path to it to the caller. No files which exist will be altered in this operation and concurrent executions of this function will return separate files. In case of conflict, the function w...
entailment
def _run(passedArgs=None, stderr=None, stdout=None, exitFn=None): """Executes the script, gets prefix/suffix from the command prompt and produces output on STDOUT. For help with command line options, invoke script with '--help'. """ description = """Finds the next available file-name in a sequence....
Executes the script, gets prefix/suffix from the command prompt and produces output on STDOUT. For help with command line options, invoke script with '--help'.
entailment
def _errstr(value): """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If it's truncated, the returned value will have '...' on the end. """ value = str(value) # We won't make the caller convert value to a string each time. if len(value) > MAX_ERROR_STR_LEN: return value[:...
Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If it's truncated, the returned value will have '...' on the end.
entailment
def _getStrippedValue(value, strip): """Like the strip() string method, except the strip argument describes different behavior: If strip is None, whitespace is stripped. If strip is a string, the characters in the string are stripped. If strip is False, nothing is stripped.""" if strip is Non...
Like the strip() string method, except the strip argument describes different behavior: If strip is None, whitespace is stripped. If strip is a string, the characters in the string are stripped. If strip is False, nothing is stripped.
entailment
def _raiseValidationException(standardExcMsg, customExcMsg=None): """Raise ValidationException with standardExcMsg, unless customExcMsg is specified.""" if customExcMsg is None: raise ValidationException(str(standardExcMsg)) else: raise ValidationException(str(customExcMsg))
Raise ValidationException with standardExcMsg, unless customExcMsg is specified.
entailment
def _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg=None): """Returns a tuple of two values: the first is a bool that tells the caller if they should immediately return True, the second is a new, possibly stripped value to replace the value passed for value parameter. ...
Returns a tuple of two values: the first is a bool that tells the caller if they should immediately return True, the second is a new, possibly stripped value to replace the value passed for value parameter. We'd want the caller immediately return value in some cases where further validation isn't neede...
entailment
def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes): """Returns None if the blank, strip, and blocklistRegexes parameters are valid of PySimpleValidate's validation functions have. Raises a PySimpleValidateException if any of the arguments are invalid.""" # Check blank para...
Returns None if the blank, strip, and blocklistRegexes parameters are valid of PySimpleValidate's validation functions have. Raises a PySimpleValidateException if any of the arguments are invalid.
entailment
def _validateParamsFor_validateNum(min=None, max=None, lessThan=None, greaterThan=None): """Raises an exception if the arguments are invalid. This is called by the validateNum(), validateInt(), and validateFloat() functions to check its arguments. This code was refactored out to a separate function so t...
Raises an exception if the arguments are invalid. This is called by the validateNum(), validateInt(), and validateFloat() functions to check its arguments. This code was refactored out to a separate function so that the PyInputPlus module (or other modules) could check their parameters' arguments for in...
entailment
def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not a string. This function is identical to the built-in input() function, but also offers the PySimpleValidate features of not allowing blank values by defau...
Raises ValidationException if value is not a string. This function is identical to the built-in input() function, but also offers the PySimpleValidate features of not allowing blank values by default, automatically stripping whitespace, and having allowlist/blocklist regular expressions. Returns va...
entailment
def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num', min=None, max=None, lessThan=None, greaterThan=None, excMsg=None): """Raises ValidationException if value is not a float or int. Returns value, so it can be used inline in an expression...
Raises ValidationException if value is not a float or int. Returns value, so it can be used inline in an expression: print(2 + validateNum(your_number)) Note that since int() and float() ignore leading or trailing whitespace when converting a string to a number, so does this validateNum(). *...
entailment
def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, min=None, max=None, lessThan=None, greaterThan=None, excMsg=None): """Raises ValidationException if value is not a int. Returns value, so it can be used inline in an expression: print(2 + vali...
Raises ValidationException if value is not a int. Returns value, so it can be used inline in an expression: print(2 + validateInt(your_number)) Note that since int() and ignore leading or trailing whitespace when converting a string to a number, so does this validateNum(). * value (str): The...
entailment
def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, numbered=False, lettered=False, caseSensitive=False, excMsg=None): """Raises PySimpleValidateException if the arguments are invalid. This is called by the validateChoice() fun...
Raises PySimpleValidateException if the arguments are invalid. This is called by the validateChoice() function to check its arguments. This code was refactored out to a separate function so that the PyInputPlus module (or other modules) could check their parameters' arguments for inputChoice().
entailment
def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, numbered=False, lettered=False, caseSensitive=False, excMsg=None): """Raises ValidationException if value is not one of the values in choices. Returns the selected choice. Returns th...
Raises ValidationException if value is not one of the values in choices. Returns the selected choice. Returns the value in choices that was selected, so it can be used inline in an expression: print('You chose ' + validateChoice(your_choice, ['cat', 'dog'])) Note that value itself is not retu...
entailment
def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises PySimpleValidateException if the arguments are invalid. This is called by the validateTime() function to check its arguments. This code was refactored out ...
Raises PySimpleValidateException if the arguments are invalid. This is called by the validateTime() function to check its arguments. This code was refactored out to a separate function so that the PyInputPlus module (or other modules) could check their parameters' arguments for inputTime().
entailment
def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None): """Raises ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime.time object of value. * value (...
Raises ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime.time object of value. * value (str): The value being validated as a time. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If None, whites...
entailment
def validateDate(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), excMsg=None): """Raises ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime.date obje...
Raises ValidationException if value is not a time formatted in one of the formats formats. Returns a datetime.date object of value. * value (str): The value being validated as a time. * blank (bool): If True, a blank string for value will be accepted. * strip (bool, str, None): If None, whitespace is s...
entailment
def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S', '%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%...
Raises ValidationException if value is not a datetime formatted in one of the formats formats. Returns a datetime.datetime object of value. * value (str): The value being validated as a datetime. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If ...
entailment
def validateFilename(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not a valid filename. Filenames can't contain \\ / : * ? " < > | or end with a space. Returns the value argument. Note that this validates filenames...
Raises ValidationException if value is not a valid filename. Filenames can't contain \\ / : * ? " < > | or end with a space. Returns the value argument. Note that this validates filenames, not filepaths. The / and \\ characters are invalid for filenames. * value (str): The value being validated as...
entailment
def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False): r"""Raises ValidationException if value is not a valid filename. Filenames can't contain \\ / : * ? " < > | Returns the value argument. * value (str): The value being valida...
r"""Raises ValidationException if value is not a valid filename. Filenames can't contain \\ / : * ? " < > | Returns the value argument. * value (str): The value being validated as an IP address. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): ...
entailment
def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not an IPv4 or IPv6 address. Returns the value argument. * value (str): The value being validated as an IP address. * blank (bool): If True, a blank strin...
Raises ValidationException if value is not an IPv4 or IPv6 address. Returns the value argument. * value (str): The value being validated as an IP address. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If None, whitespace is stripped from value. ...
entailment
def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value does not match the regular expression in regex. Returns the value argument. This is similar to calling inputStr() and using the allowlistRegex...
Raises ValidationException if value does not match the regular expression in regex. Returns the value argument. This is similar to calling inputStr() and using the allowlistRegexes keyword argument, however, validateRegex() allows you to pass regex flags such as re.IGNORECASE or re.VERBOSE. You can als...
entailment
def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value can't be used as a regular expression string. Returns the value argument as a regex object. If you want to check if a string matches a regular expression, ...
Raises ValidationException if value can't be used as a regular expression string. Returns the value argument as a regex object. If you want to check if a string matches a regular expression, call validateRegex(). * value (str): The value being validated as a regular expression string. * regex (str...
entailment
def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not a URL. Returns the value argument. The "http" or "https" protocol part of the URL is optional. * value (str): The value being validated as a URL. ...
Raises ValidationException if value is not a URL. Returns the value argument. The "http" or "https" protocol part of the URL is optional. * value (str): The value being validated as a URL. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If N...
entailment
def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not an email address. Returns the value argument. * value (str): The value being validated as an email address. * blank (bool): If True, a blank strin...
Raises ValidationException if value is not an email address. Returns the value argument. * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If None, whitespace is stripped from value. If ...
entailment
def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None): """Raises ValidationException if value is not a yes or no response. Returns the yesVal or noVal argument, not value. Note that value can be any case (...
Raises ValidationException if value is not a yes or no response. Returns the yesVal or noVal argument, not value. Note that value can be any case (by default) and can also just match the * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be acce...
entailment
def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None): """Raises ValidationException if value is not an email address. Returns the yesVal or noVal argument, not value. * value (str): The value being...
Raises ValidationException if value is not an email address. Returns the yesVal or noVal argument, not value. * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If None, whitespace is str...
entailment
def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False): """Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased s...
Raises ValidationException if value is not a USA state. Returns the capitalized state abbreviation, unless returnStateName is True in which case it returns the titlecased state name. * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be accepted....
entailment
def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None): """Raises ValidationException if value is not a month, like 'Jan' or 'March'. Returns the titlecased month. * value (str): The value being validated as an email address. ...
Raises ValidationException if value is not a month, like 'Jan' or 'March'. Returns the titlecased month. * value (str): The value being validated as an email address. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If None, whitespace is stripped...
entailment
def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None): """Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'. Returns the titlecased day of the week. * value (str): The value being...
Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'. Returns the titlecased day of the week. * value (str): The value being validated as a day of the week. * blank (bool): If True, a blank string will be accepted. Defaults to False. * strip (bool, str, None): If Non...
entailment
def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not a day of the month, from 1 to 28, 29, 30, or 31 depending on the month and year. Returns value. * value (str): The value being va...
Raises ValidationException if value is not a day of the month, from 1 to 28, 29, 30, or 31 depending on the month and year. Returns value. * value (str): The value being validated as existing as a numbered day in the given year and month. * year (int): The given year. * month (int): The given month...
entailment
def get_level(level_string): """ Returns an appropriate logging level integer from a string name """ levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} try: level = levels[level...
Returns an appropriate logging level integer from a string name
entailment
def config_logging(no_log_file, log_to, log_level, silent, verbosity): """ Configures and generates a Logger object, 'openaccess_epub' based on common parameters used for console interface script execution in OpenAccess_EPUB. These parameters are: no_log_file Boolean. Disables logging t...
Configures and generates a Logger object, 'openaccess_epub' based on common parameters used for console interface script execution in OpenAccess_EPUB. These parameters are: no_log_file Boolean. Disables logging to file. If set to True, log_to and log_level become irrelevant. log...
entailment
def replace_filehandler(logname, new_file, level=None, frmt=None): """ This utility function will remove a previous Logger FileHandler, if one exists, and add a new filehandler. Parameters: logname The name of the log to reconfigure, 'openaccess_epub' for example new_file ...
This utility function will remove a previous Logger FileHandler, if one exists, and add a new filehandler. Parameters: logname The name of the log to reconfigure, 'openaccess_epub' for example new_file The file location for the new FileHandler level Optional. Lev...
entailment
def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize, varExtXmin, varExtXmax, varExtYmin, varExtYmax): """Remap x, y, sigma parameters from pixel to degree. Parameters ---------- vecX : 1D numpy array Array with possible x parametrs in pixels vecY : 1D numpy array ...
Remap x, y, sigma parameters from pixel to degree. Parameters ---------- vecX : 1D numpy array Array with possible x parametrs in pixels vecY : 1D numpy array Array with possible y parametrs in pixels vecPrfSd : 1D numpy array Array with possible sd parametrs in pixels t...
entailment
def crt_mdl_prms(tplPngSize, varNum1, varExtXmin, varExtXmax, varNum2, varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin, varPrfStdMax, kwUnt='pix', kwCrd='crt'): """Create an array with all possible model parameter combinations Parameters ---------- tplPngSize : t...
Create an array with all possible model parameter combinations Parameters ---------- tplPngSize : tuple, 2 Pixel dimensions of the visual space (width, height). varNum1 : int, positive Number of x-positions to model varExtXmin : float Extent of visual space from centre in ne...
entailment
def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt', lgcPrint=True): """Create responses of 2D Gauss models to spatial conditions. Parameters ---------- arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions] All spatial conditions stacked ...
Create responses of 2D Gauss models to spatial conditions. Parameters ---------- arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions] All spatial conditions stacked along second axis. tplPngSize : tuple, 2 Pixel dimensions of the visual space (width, height). aryMdl...
entailment
def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol, varTmpOvsmpl, lgcPrint=True): """Create temporally upsampled neural time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond] Responses of 2D Gauss models to spatial...
Create temporally upsampled neural time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond] Responses of 2D Gauss models to spatial conditions. aryCnd : np.array 1D array with condition identifiers (every condition has its own int) ary...
entailment
def crt_prf_tc(aryNrlTc, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Convolve every neural time course with HRF function. Parameters ---------- aryNrlTc : 4d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_vol] Temporally upsamp...
Convolve every neural time course with HRF function. Parameters ---------- aryNrlTc : 4d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_vol] Temporally upsampled neural time course models. varNumVol : float, positive Number of volumes of the (fMRI) data. varTr : float, positive ...
entailment
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *...
Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond] Responses of 2D Gauss models to spatial conditions aryTmpExpInf: 2d numpy array, shape [unknown, 4] Temporal information about conditions varNumV...
entailment
def fnd_unq_rws(A, return_index=False, return_inverse=False): """Find unique rows in 2D array. Parameters ---------- A : 2d numpy array Array for which unique rows should be identified. return_index : bool Bool to decide whether I is returned. return_inverse : bool Bool ...
Find unique rows in 2D array. Parameters ---------- A : 2d numpy array Array for which unique rows should be identified. return_index : bool Bool to decide whether I is returned. return_inverse : bool Bool to decide whether J is returned. Returns ------- B : 1d ...
entailment
async def _request( self, method: str, endpoint: str, *, headers: dict = None) -> dict: """Make a request against air-matters.com.""" url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint) if not headers: headers = {} headers.update({ 'Host': DEFAULT_HOST...
Make a request against air-matters.com.
entailment
def filter_transform_response(get_response, params): """ This filter process the returned response. It does 3 things: - If the response is a ``sanic.response.HTTPResponse`` and not a :class:`rafter.http.Response`, return it immediately. - If the response is not a :class:`rafter.http.Response` ins...
This filter process the returned response. It does 3 things: - If the response is a ``sanic.response.HTTPResponse`` and not a :class:`rafter.http.Response`, return it immediately. - If the response is not a :class:`rafter.http.Response` instance, turn it to a :class:`rafter.http.Response` instance ...
entailment
def get_publisher(self): """ This method defines how the Article tries to determine the publisher of the article. This method relies on the success of the get_DOI method to fetch the appropriate full DOI for the article. It then takes the DOI prefix which corresponds to ...
This method defines how the Article tries to determine the publisher of the article. This method relies on the success of the get_DOI method to fetch the appropriate full DOI for the article. It then takes the DOI prefix which corresponds to the publisher and then uses that to attempt t...
entailment
def get_DOI(self): """ This method defines how the Article tries to detect the DOI. It attempts to determine the article DOI string by DTD-appropriate inspection of the article metadata. This method should be made as flexible as necessary to properly collect the DOI for any XML ...
This method defines how the Article tries to detect the DOI. It attempts to determine the article DOI string by DTD-appropriate inspection of the article metadata. This method should be made as flexible as necessary to properly collect the DOI for any XML publishing specification. ...
entailment
def np_lst_sq(vecMdl, aryFuncChnk): """Least squares fitting in numpy without cross-validation. Notes ----- This is just a wrapper function for np.linalg.lstsq to keep piping consistent. """ aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl, aryFuncCh...
Least squares fitting in numpy without cross-validation. Notes ----- This is just a wrapper function for np.linalg.lstsq to keep piping consistent.
entailment
def np_lst_sq_xval(vecMdl, aryFuncChnk, aryIdxTrn, aryIdxTst): """Least squares fitting in numpy with cross-validation. """ varNumXval = aryIdxTrn.shape[-1] varNumVoxChnk = aryFuncChnk.shape[-1] # pre-allocate ary to collect cross-validation # error for every xval fold aryResXval = np.emp...
Least squares fitting in numpy with cross-validation.
entailment
async def _raw_user_report_data(self) -> list: """Return user report data (if accompanied by latitude/longitude).""" data = await self._request('get', 'map/markers') return [ location for location in data if location['latitude'] and location['longitude'] ]
Return user report data (if accompanied by latitude/longitude).
entailment
async def _raw_state_data(self) -> list: """Return a list of states.""" data = await self._request('get', 'states') return [ location for location in data if location['name'] != 'United States' ]
Return a list of states.
entailment
async def nearest_by_coordinates( self, latitude: float, longitude: float) -> dict: """Get the nearest report (with local and state info) to a lat/lon.""" # Since user data is more granular than state or CDC data, find the # user report whose coordinates are closest to the provided ...
Get the nearest report (with local and state info) to a lat/lon.
entailment
def initialize(self, maxsize, history=None): '''size specifies the maximum amount of history to keep''' super().__init__() self.maxsize = int(maxsize) self.history = deque(maxlen=self.maxsize) # Preserves order history # If `items` are specified, then initialize with them ...
size specifies the maximum amount of history to keep
entailment
def insert(self, key, value): '''Adds a new key-value pair. Returns any discarded values.''' # Add to history and catch expectorate if len(self.history) == self.maxsize: expectorate = self.history[0] else: expectorate = None self.history.append((key, val...
Adds a new key-value pair. Returns any discarded values.
entailment
def up_to(self, key): '''Gets the recently inserted values up to a key''' for okey, ovalue in reversed(self.history): if okey == key: break else: yield ovalue
Gets the recently inserted values up to a key
entailment
def resource(self, uri, methods=frozenset({'GET'}), **kwargs): """ Decorates a function to be registered as a resource route. :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :...
Decorates a function to be registered as a resource route. :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param stream: :param version: :param name: user defined route name for url_for :pa...
entailment
def add_resource(self, handler, uri, methods=frozenset({'GET'}), **kwargs): """ Register a resource route. :param handler: function or class instance :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :p...
Register a resource route. :param handler: function or class instance :param uri: path of the URL :param methods: list or tuple of methods allowed :param host: :param strict_slashes: :param version: :param name: user defined route name for url_for :param ...
entailment
def check(session, rev_id, page_id=None, radius=defaults.RADIUS, before=None, window=None, rvprop=None): """ Checks the revert status of a revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by another edit and/or was 'reverted_to' by another ed...
Checks the revert status of a revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by another edit and/or was 'reverted_to' by another edit. :Parameters: session : :class:`mwapi.Session` An API session to make use of rev_id : int ...
entailment
def check_deleted(session, rev_id, title=None, timestamp=None, radius=defaults.RADIUS, before=None, window=None, rvprop=None): """ Checks the revert status of a deleted revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by...
Checks the revert status of a deleted revision. With this method, you can determine whether an edit is a 'reverting' edit, was 'reverted' by another edit and/or was 'reverted_to' by another edit. :Parameters: session : :class:`mwapi.Session` An API session to make use of rev_id...
entailment
def get_commits(repo_dir, old_commit, new_commit, hide_merges=True): """Find all commits between two commit SHAs.""" repo = Repo(repo_dir) commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit)) if hide_merges: return [x for x in commits if not x.summary.startswith("Merge ")] ...
Find all commits between two commit SHAs.
entailment
def get_commit_url(repo_url): """Determine URL to view commits for repo.""" if "github.com" in repo_url: return repo_url[:-4] if repo_url.endswith(".git") else repo_url if "git.openstack.org" in repo_url: uri = '/'.join(repo_url.split('/')[-2:]) return "https://github.com/{0}".format...
Determine URL to view commits for repo.
entailment
def get_projects(osa_repo_dir, commit): """Get all projects from multiple YAML files.""" # Check out the correct commit SHA from the repository repo = Repo(osa_repo_dir) checkout(repo, commit) yaml_files = glob.glob( '{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir) ) ...
Get all projects from multiple YAML files.
entailment
def checkout(repo, ref): """Checkout a repoself.""" # Delete local branch if it exists, remote branch will be tracked # automatically. This prevents stale local branches from causing problems. # It also avoids problems with appending origin/ to refs as that doesn't # work with tags, SHAs, and upstre...
Checkout a repoself.
entailment
def get_roles(osa_repo_dir, commit, role_requirements): """Read OSA role information at a particular commit.""" repo = Repo(osa_repo_dir) checkout(repo, commit) log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir, f=role_requirements...
Read OSA role information at a particular commit.
entailment
def make_osa_report(repo_dir, old_commit, new_commit, args): """Create initial RST report header for OpenStack-Ansible.""" update_repo(repo_dir, args.osa_repo_url, args.update) # Are these commits valid? validate_commits(repo_dir, [old_commit, new_commit]) # Do we have a valid ...
Create initial RST report header for OpenStack-Ansible.
entailment
def make_report(storage_directory, old_pins, new_pins, do_update=False, version_mappings=None): """Create RST report from a list of projects/roles.""" report = "" version_mappings = version_mappings or {} for new_pin in new_pins: repo_name, repo_url, commit_sha = new_pin ...
Create RST report from a list of projects/roles.
entailment
def normalize_yaml(yaml): """Normalize the YAML from project and role lookups. These are returned as a list of tuples. """ if isinstance(yaml, list): # Normalize the roles YAML data normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD')) for x in ya...
Normalize the YAML from project and role lookups. These are returned as a list of tuples.
entailment
def post_gist(report_data, old_sha, new_sha): """Post the report to a GitHub Gist and return the URL of the gist.""" payload = { "description": ("Changes in OpenStack-Ansible between " "{0} and {1}".format(old_sha, new_sha)), "public": True, "files": { ...
Post the report to a GitHub Gist and return the URL of the gist.
entailment
def prepare_storage_dir(storage_directory): """Prepare the storage directory.""" storage_directory = os.path.expanduser(storage_directory) if not os.path.exists(storage_directory): os.mkdir(storage_directory) return storage_directory
Prepare the storage directory.
entailment
def render_template(template_file, template_vars): """Render a jinja template.""" # Load our Jinja templates template_dir = "{0}/templates".format( os.path.dirname(os.path.abspath(__file__)) ) jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), trim_...
Render a jinja template.
entailment
def repo_pull(repo_dir, repo_url, fetch=False): """Reset repository and optionally update it.""" # Make sure the repository is reset to the master branch. repo = Repo(repo_dir) repo.git.clean("-df") repo.git.reset("--hard") repo.git.checkout("master") repo.head.reset(index=True, working_tree...
Reset repository and optionally update it.
entailment
def update_repo(repo_dir, repo_url, fetch=False): """Clone the repo if it doesn't exist already, otherwise update it.""" repo_exists = os.path.exists(repo_dir) if not repo_exists: log.info("Cloning repo {}".format(repo_url)) repo = repo_clone(repo_dir, repo_url) # Make sure the repo is ...
Clone the repo if it doesn't exist already, otherwise update it.
entailment
def validate_commits(repo_dir, commits): """Test if a commit is valid for the repository.""" log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir)) repo = Repo(repo_dir) for commit in commits: try: commit = repo.commit(commit) except Exception: msg...
Test if a commit is valid for the repository.
entailment
def validate_commit_range(repo_dir, old_commit, new_commit): """Check if commit range is valid. Flip it if needed.""" # Are there any commits between the two commits that were provided? try: commits = get_commits(repo_dir, old_commit, new_commit) except Exception: commits = [] if len...
Check if commit range is valid. Flip it if needed.
entailment
def get_release_notes(osa_repo_dir, osa_old_commit, osa_new_commit): """Get release notes between the two revisions.""" repo = Repo(osa_repo_dir) # Get a list of tags, sorted tags = repo.git.tag().split('\n') tags = sorted(tags, key=LooseVersion) # Currently major tags are being printed after r...
Get release notes between the two revisions.
entailment
def run_osa_differ(): """Start here.""" # Get our arguments from the command line args = parse_arguments() # Set up DEBUG logging if needed if args.debug: log.setLevel(logging.DEBUG) elif args.verbose: log.setLevel(logging.INFO) # Create the storage directory if it doesn't ...
Start here.
entailment
def append_new_text(destination, text, join_str=None): """ This method provides the functionality of adding text appropriately underneath the destination node. This will be either to the destination's text attribute or to the tail attribute of the last child. """ if join_str is None: joi...
This method provides the functionality of adding text appropriately underneath the destination node. This will be either to the destination's text attribute or to the tail attribute of the last child.
entailment
def append_all_below(destination, source, join_str=None): """ Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail attributes of elements is an oddity. It can even be a little frustrating when one is attempting to copy everything underneath some element to another element; one ha...
Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail attributes of elements is an oddity. It can even be a little frustrating when one is attempting to copy everything underneath some element to another element; one has to write in extra code to handle the text. This method provides ...
entailment
def all_text(element): """ A method for extending lxml's functionality, this will find and concatenate all text data that exists one level immediately underneath the given element. Unlike etree.tostring(element, method='text'), this will not recursively walk the entire underlying tree. It merely com...
A method for extending lxml's functionality, this will find and concatenate all text data that exists one level immediately underneath the given element. Unlike etree.tostring(element, method='text'), this will not recursively walk the entire underlying tree. It merely combines the element text attribut...
entailment
def remove_all_attributes(element, exclude=None): """ This method will remove all attributes of any provided element. A list of strings may be passed to the keyward-argument "exclude", which will serve as a list of attributes which will not be removed. """ if exclude is None: exclude = ...
This method will remove all attributes of any provided element. A list of strings may be passed to the keyward-argument "exclude", which will serve as a list of attributes which will not be removed.
entailment
def ns_format(element, namespaced_string): """ Provides a convenient method for adapting a tag or attribute name to use lxml's format. Use this for tags like ops:switch or attributes like xlink:href. """ if ':' not in namespaced_string: print('This name contains no namespace, returning i...
Provides a convenient method for adapting a tag or attribute name to use lxml's format. Use this for tags like ops:switch or attributes like xlink:href.
entailment
def rename_attributes(element, attrs): """ Renames the attributes of the element. Accepts the element and a dictionary of string values. The keys are the original names, and their values will be the altered names. This method treats all attributes as optional and will not fail on missing attributes....
Renames the attributes of the element. Accepts the element and a dictionary of string values. The keys are the original names, and their values will be the altered names. This method treats all attributes as optional and will not fail on missing attributes.
entailment
def elevate_element(node, adopt_name=None, adopt_attrs=None): """ This method serves a specialized function. It comes up most often when working with block level elements that may not be contained within paragraph elements, which are presented in the source document as inline ele...
This method serves a specialized function. It comes up most often when working with block level elements that may not be contained within paragraph elements, which are presented in the source document as inline elements (inside a paragraph element). It would be inappropriate to merely i...
entailment
def replace(old, new): """ A simple way to replace one element node with another. """ parent = old.getparent() parent.replace(old, new)
A simple way to replace one element node with another.
entailment
def insert_before(old, new): """ A simple way to insert a new element node before the old element node among its siblings. """ parent = old.getparent() parent.insert(parent.index(old), new)
A simple way to insert a new element node before the old element node among its siblings.
entailment
def comment(node): """ Converts the node received to a comment, in place, and will also return the comment element. """ parent = node.parentNode comment = node.ownerDocument.createComment(node.toxml()) parent.replaceChild(comment, node) return comment
Converts the node received to a comment, in place, and will also return the comment element.
entailment
def uncomment(comment): """ Converts the comment node received to a non-commented element, in place, and will return the new node. This may fail, primarily due to special characters within the comment that the xml parser is unable to handle. If it fails, this method will log an error and return...
Converts the comment node received to a non-commented element, in place, and will return the new node. This may fail, primarily due to special characters within the comment that the xml parser is unable to handle. If it fails, this method will log an error and return None
entailment
def serialize(element, strip=False): """ A handy way to serialize an element to text. """ text = etree.tostring(element, method='text', encoding='utf-8') if strip: text = text.strip() return str(text, encoding='utf-8')
A handy way to serialize an element to text.
entailment
def get_arg_parse(): """Parses the Command Line Arguments using argparse.""" # Create parser object: objParser = argparse.ArgumentParser() # Add argument to namespace -config file path: objParser.add_argument('-config', required=True, metavar='/path/to/config.csv', ...
Parses the Command Line Arguments using argparse.
entailment
def main(): """pyprf_opt_brute entry point.""" # Get list of input arguments (without first one, which is the path to the # function that is called): --NOTE: This is another way of accessing # input arguments, but since we use 'argparse' it is redundant. # lstArgs = sys.argv[1:] strWelcome = 'p...
pyprf_opt_brute entry point.
entailment
def _homogenize_data_filter(dfilter): """ Make data filter definition consistent. Create a tuple where first element is the row filter and the second element is the column filter """ if isinstance(dfilter, tuple) and (len(dfilter) == 1): dfilter = (dfilter[0], None) if (dfilter is N...
Make data filter definition consistent. Create a tuple where first element is the row filter and the second element is the column filter
entailment
def _tofloat(obj): """Convert to float if object is a float string.""" if "inf" in obj.lower().strip(): return obj try: return int(obj) except ValueError: try: return float(obj) except ValueError: return obj
Convert to float if object is a float string.
entailment
def _in_header(self, col): """Validate column identifier(s).""" # pylint: disable=R1704 if not self._has_header: # Conditionally register exceptions so that they do not appear # in situations where has_header is always True. In this way # they are not auto-doc...
Validate column identifier(s).
entailment
def _validate_frow(self, frow): """Validate frow argument.""" is_int = isinstance(frow, int) and (not isinstance(frow, bool)) pexdoc.exh.addai("frow", not (is_int and (frow >= 0))) return frow
Validate frow argument.
entailment