text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_file(self, fn: str) -> Iterator[InsertionPoint]: """ Returns an iterator over all of the insertion points in a given file. """
logger.debug("finding insertion points in file: %s", fn) yield from self.__file_insertions.get(fn, [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def at_line(self, line: FileLine) -> Iterator[InsertionPoint]: """ Returns an iterator over all of the insertion points located at a given line. """
logger.debug("finding insertion points at line: %s", str(line)) filename = line.filename # type: str line_num = line.num # type: int for ins in self.in_file(filename): if line_num == ins.location.line: logger.debug("found insertion point at line [%s]: %s", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadPng(varNumVol, tplPngSize, strPathPng): """Load PNG files. Parameters varNumVol : float Number of volumes, i.e. number of time points in all runs. tplPng...
print('------Load PNGs') # Create list of png files to load: lstPngPaths = [None] * varNumVol for idx01 in range(0, varNumVol): lstPngPaths[idx01] = (strPathPng + str(idx01) + '.png') # Load png files. The png data will be saved in a numpy array of the # following order: aryPngData[x-p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadPrsOrd(vecRunLngth, strPathPresOrd, vecVslStim): """Load presentation order of motion directions. Parameters vecRunLngth : list Number of volumes in ever...
print('------Load presentation order of motion directions') aryPresOrd = np.empty((0, 2)) for idx01 in range(0, len(vecRunLngth)): # reconstruct file name # ---> consider: some runs were shorter than others(replace next row) filename1 = (strPathPresOrd + str(vecVslStim[idx01]) + ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crtPwBoxCarFn(varNumVol, aryPngData, aryPresOrd, vecMtDrctn): """Create pixel-wise boxcar functions. Parameters input1 : 2d numpy array, shape [n_samples, n_...
print('------Create pixel-wise boxcar functions') aryBoxCar = np.empty(aryPngData.shape[0:2] + (len(vecMtDrctn),) + (varNumVol,), dtype='int64') for ind, num in enumerate(vecMtDrctn): aryCondTemp = np.zeros((aryPngData.shape), dtype='int64') lgcTempMtDrctn = [aryPre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cnvlGauss2D(idxPrc, aryBoxCar, aryMdlParamsChnk, tplPngSize, varNumVol, queOut): """Spatially convolve boxcar functions with 2D Gaussian. Parameters idxPrc :...
# Number of combinations of model parameters in the current chunk: varChnkSze = np.size(aryMdlParamsChnk, axis=0) # Determine number of motion directions varNumMtnDrtn = aryBoxCar.shape[2] # Output array with pRF model time courses: aryOut = np.zeros([varChnkSze, varNumMtnDrtn, varNumVol]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rsmplInHighRes(aryBoxCarConv, tplPngSize, tplVslSpcHighSze, varNumMtDrctn, varNumVol): """Resample pixel-time courses in high-res visual space. Parameters in...
# Array for super-sampled pixel-time courses: aryBoxCarConvHigh = np.zeros((tplVslSpcHighSze[0], tplVslSpcHighSze[1], varNumMtDrctn, varNumVol)) # Loop through volumes: for idxMtn in range(0, varNumMt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_sim ' + __version__ strDec = '=' * len(st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
@wraps(wrapped) def wrapper(*args, **kwargs): request = args[1] auth_collection = settings.AUTH_COLLECTION[ settings.AUTH_COLLECTION.rfind('.') + 1: ].lower() auth_document = request.environ.get(auth_collection) if auth_document and auth_document.is_authori...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
@wraps(wrapped) def wrapper(*args, **kwargs): should_serialize = kwargs.pop('serialize', False) result = wrapped(*args, **kwargs) return serialize(result) if should_serialize else result if hasattr(wrapped, 'decorators'): wrapper.decorators = wrapped.decorators wr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, *args, **kwargs) except: return bson_loads(bson_dumps(to_deserialize), *args, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findNextFile(folder='.', prefix=None, suffix=None, fnameGen=None, base=0, maxattempts=10): """Finds the next available file-name in a sequence. This function...
expFolder = _os.path.expanduser(_os.path.expandvars(folder)) return _findNextFile(expFolder, prefix, suffix, fnameGen, base, maxattempts, 0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _errstr(value): """Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If """
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[:MAX_ERROR_STR_LEN] + '...' else: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes): """Returns None if the blank, strip, and blocklistRegexes parameters are valid ...
# Check blank parameter. if not isinstance(blank, bool): raise PySimpleValidateException('blank argument must be a bool') # Check strip parameter. if not isinstance(strip, (bool, str, type(None))): raise PySimpleValidateException('strip argument must be a bool, None, or str') # C...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num', min=None, max=None, lessThan=None, greaterThan=None,...
# Validate parameters. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes) _validateParamsFor_validateNum(min=min, max=max, lessThan=lessThan, greaterThan=greaterThan) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, min=None, max=None, lessThan=None, greaterThan=None, excMsg=None): ...
return validateNum(value=value, blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes, _numType='int', min=min, max=max, lessThan=lessThan, greaterThan=greaterThan)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, numbered=False, lettered=False, caseSensitive=False, exc...
# Validate parameters. _validateParamsFor_validateChoice(choices=choices, blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes, numbered=numbered, lettered=lettered, caseSensitive=caseSensitive) if '' in choices: # blank needs to be set to True here, otherwis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None): """Raises Valid...
# TODO - handle this # Reuse the logic in _validateToDateTimeFormat() for this function. try: dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) return datetime.time(dt.hour, dt.minute, dt.second, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'), exc...
# Reuse the logic in _validateToDateTimeFormat() for this function. try: dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) return datetime.date(dt.year, dt.month, dt.day) except ValidationException:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# Reuse the logic in _validateToDateTimeFormat() for this function. try: return _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) except ValidationException: _raiseValidationException(_('%r is not a val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not an IPv4 ...
# Validate parameters. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg) if returnNow: return value # Reuse the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if va...
# Validate parameters. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg) if returnNow: return value # Search va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value can't be ...
# TODO - I'd be nice to check regexes in other languages, i.e. JS and Perl. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not a URL. ...
# Reuse the logic in validateRegex() try: result = validateRegex(value=value, regex=URL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) if result is not None: return result except ValidationException: # 'localhost' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not an em...
# Reuse the logic in validateRegex() try: result = validateRegex(value=value, regex=EMAIL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) if result is not None: return result except ValidationException: _raiseValida...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None): """R...
# Validate parameters. TODO - can probably improve this to remove the duplication. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, exc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None)...
# Validate parameters. TODO - can probably improve this to remove the duplication. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, exc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False): """Raises ValidationExceptio...
# TODO - note that this is USA-centric. I should work on trying to make this more international. # Validate parameters. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None): """Raises ValidationExce...
# returns full month name, e.g. 'January' # Validate parameters. _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg) if r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None): """Raises Valida...
# TODO - reuse validateChoice for this function # returns full day of the week str, e.g. 'Sunday' # Reuses validateMonth. try: return validateMonth(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, monthNames=ENGLISH_DAYS_OF_WEEK) exce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if ...
try: daysInMonth = calendar.monthrange(year, month)[1] except: raise PySimpleValidateException('invalid arguments for year and/or month') try: return validateInt(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, min=1, max=daysIn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_string.lower()] except KeyError: sys.exit('{0} is not a recognized logging level'.format(level_stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_logging(no_log_file, log_to, log_level, silent, verbosity): """ Configures and generates a Logger object, 'openaccess_epub' based on common parameters...
log_level = get_level(log_level) console_level = get_level(verbosity) #We want to configure our openaccess_epub as the parent log log = logging.getLogger('openaccess_epub') log.setLevel(logging.DEBUG) # Don't filter at the log level standard = logging.Formatter(STANDARD_FORMAT) message_o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
#Call up the Logger to get reconfigured log = logging.getLogger(logname) #Set up defaults and whether explicit for level if level is not None: level = get_level(level) explicit_level = True else: level = logging.DEBUG explicit_level = False #Set up defaults and...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize, varExtXmin, varExtXmax, varExtYmin, varExtYmax): """Remap x, y, sigma parameters from pixel to degree. Pa...
# Remap modelled x-positions of the pRFs: vecXdgr = rmp_rng(vecX, varExtXmin, varExtXmax, varOldThrMin=0.0, varOldAbsMax=(tplPngSize[0] - 1)) # Remap modelled y-positions of the pRFs: vecYdgr = rmp_rng(vecY, varExtYmin, varExtYmax, varOldThrMin=0.0, varOldA...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crt_mdl_prms(tplPngSize, varNum1, varExtXmin, varExtXmax, varNum2, varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin, varPrfStdMax, kwUnt='pix', kwCrd='crt...
# Number of pRF models to be created (i.e. number of possible # combinations of x-position, y-position, and standard deviation): varNumMdls = varNum1 * varNum2 * varNumPrfSizes # Array for the x-position, y-position, and standard deviations for # which pRF model time courses are going to be creat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt', lgcPrint=True): """Create responses of 2D Gauss models to spatial conditions. Param...
if varPar == 1: # if the number of cores requested by the user is equal to 1, # we save the overhead of multiprocessing by calling aryMdlCndRsp # directly aryMdlCndRsp = cnvl_2D_gauss(0, aryMdlParams, arySptExpInf, tplPngSize, None, strCrd=strCr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol, varTmpOvsmpl, lgcPrint=True): """Create temporally upsampled neural time courses. Parameters ...
# adjust the input, if necessary, such that input is 2D tplInpShp = aryMdlRsp.shape aryMdlRsp = aryMdlRsp.reshape((-1, aryMdlRsp.shape[-1])) # the first spatial condition might code the baseline (blank periods) with # all zeros. If this is the case, remove the first spatial condition, since #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crt_prf_tc(aryNrlTc, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Convolve every neural time course with...
# Create hrf time course function: if switchHrfSet == 3: lstHrf = [spmt, dspmt, ddspmt] elif switchHrfSet == 2: lstHrf = [spmt, dspmt] elif switchHrfSet == 1: lstHrf = [spmt] # If necessary, adjust the input such that input is 2D, with last dim time tplInpShp = aryNrlT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Create all spatial ...
# Identify number of unique features vecFeat = np.unique(aryTmpExpInf[:, 3]) vecFeat = vecFeat[np.nonzero(vecFeat)[0]] # Preallocate the output array aryPrfTc = np.zeros((aryMdlRsp.shape[0], 0, varNumVol), dtype=np.float32) # Loop over unique features for indFtr, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 b...
A = np.require(A, requirements='C') assert A.ndim == 2, "array must be 2-dim'l" B = np.unique(A.view([('', A.dtype)]*A.shape[1]), return_index=return_index, return_inverse=return_inverse) if return_index or return_inverse: return (B[0].view(A.dtype).reshap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_DO...
#For a detailed explanation of the DOI system, visit: #http://www.doi.org/hb.html #The basic syntax of a DOI is this <prefix>/<suffix> #The <prefix> specifies a unique DOI registrant, in our case, this #should correspond to the publisher. We use this information to register ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if self.dtd_name == 'JPTS': doi = self.root.xpath("./front/article-meta/article-id[@pub-id-type='doi']") if doi: return doi[0].text log.warning('Unable to locate DOI string for this article') return None else: log.warning('Unab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl, aryFuncChnk, rcond=-1)[:2] return aryTmpBts, vecTmpRes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.empty((varNumVoxChnk, varNumXval), dtype=np.float32) # loop over cross-valid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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' ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
def decorator(f): if kwargs.get('stream'): f.is_stream = kwargs['stream'] self.add_resource(f, uri=uri, methods=methods, **kwargs) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_resource(self, handler, uri, methods=frozenset({'GET'}), **kwargs): """ Register a resource route. :param handler: function or class instance :param uri:...
sanic_args = ('host', 'strict_slashes', 'version', 'name') view_kwargs = dict((k, v) for k, v in kwargs.items() if k in sanic_args) filters = kwargs.get('filters', self.default_filters) validators = kwargs.get('validators', []) filter_list = list(fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ")] else: return list(commits)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(uri) # If it didn't match these conditions, just return it. return re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) ) yaml_parsed = [] for yaml_file in yaml_files: with open(yaml_file, 'r') as f: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 upstreams not called origin. if ref in repo.branches: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)) filename = "{0}/{1}".format(osa_repo_dir, role_requirements) with open(filename, 'r') as f: role...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 yaml] else: # Extract the project names from the roles YAML and create a list of # tuples. projects = [x[:-9]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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": { "osa-diff-{0}-{1}.rst".format(old_sha, new_sha): { "content": report_data } } }...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_blocks=True ) rendered = jinja_env.get_template(template_file).render(templat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=True) # Compile the refspec appropriately to ensure # that if the repo is from github it i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 properly prepared # and has all the refs required log.info("Fetching repo {} (fetch: {})".format(repo_url, fetch)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = ("Commit {commit} could not be found in repo {repo}. " "You may need to pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(commits) == 0: # The user might have gotten their commits out of order. Let's flip # the order of the co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 rc and # b tags. We need to fix the list so that major # tags are printed before rc and b releases tags = _fix_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 exist already. try: storage_dir...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_new_text(destination, text, join_str=None): """ This method provides the functionality of adding text appropriately underneath the destination node. T...
if join_str is None: join_str = ' ' if len(destination) > 0: # Destination has children last = destination[-1] if last.tail is None: # Last child has no tail last.tail = text else: # Last child has a tail last.tail = join_str.join([last.tail, text]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if join_str is None: join_str = ' ' if source.text is not None: # If source has text if len(destination) == 0: # Destination has no children if destination.text is None: # Destination has no text destination.text = source.text else: # Destination has ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 keyw...
if exclude is None: exclude = [] for k in element.attrib.keys(): if k not in exclude: element.attrib.pop(k)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_attributes(element, attrs): """ Renames the attributes of the element. Accepts the element and a dictionary of string values. The keys are the origina...
for name in attrs.keys(): if name not in element.attrib: continue else: element.attrib[attrs[name]] = element.attrib.pop(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(old, new): """ A simple way to replace one element node with another. """
parent = old.getparent() parent.replace(old, new)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
parent = comment.parentNode h = html.parser.HTMLParser() data = h.unescape(comment.data) try: node = minidom.parseString(data).firstChild except xml.parsers.expat.ExpatError: # Could not parse! log.error('Could not uncomment node due to parsing error!') return None else...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = 'pyprf_opt_brute ' + __version__ strDec = '=' * ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if isinstance(dfilter, tuple) and (len(dfilter) == 1): dfilter = (dfilter[0], None) if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)): dfilter = (None, None) elif isinstance(dfilter, dict): dfilter = (dfilter, None) elif isinstance(dfilter, (list, str)) o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_rfilter(self, rfilter, letter="d"): """Validate that all columns in filter are in header."""
if letter == "d": pexdoc.exh.addai( "dfilter", ( (not self._has_header) and any([not isinstance(item, int) for item in rfilter.keys()]) ), ) else: pexdoc.exh.addai( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dsort(self, order): r""" Sort rows. :param order: Sort order :type order: :ref:`CsvColFilter` .. [[[cog cog.out(exobj.get_sphinx_autodoc()) ]]] .. Auto-gener...
# Make order conforming to a list of dictionaries order = order if isinstance(order, list) else [order] norder = [{item: "A"} if not isinstance(item, dict) else item for item in order] # Verify that all columns exist in file self._in_header([list(item.keys())[0] for item in nord...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def header(self, filtered=False): r""" Return data header. When the raw (input) data is used the data header is a list of the comma-separated values file header ...
return ( self._header if (not filtered) or (filtered and self._cfilter is None) else self._cfilter )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace(self, rdata, filtered=False): r""" Replace data. :param rdata: Replacement data :type rdata: list of lists :param filtered: Filtering type :type filt...
# pylint: disable=R0914 rdata_ex = pexdoc.exh.addai("rdata") rows_ex = pexdoc.exh.addex( ValueError, "Number of rows mismatch between input and replacement data" ) cols_ex = pexdoc.exh.addex( ValueError, "Number of columns mismatch between input and repla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self, request): """ Returns the list of documents found on the collection """
pipeline = [{'$match': request.args.pop('match', {})}] sort = request.args.pop('sort', {}) if sort: pipeline.append({'$sort': sort}) project = request.args.pop('project', {}) if project: pipeline.append({'$project': project}) return Response(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, request): """ Creates a new document based on the given data """
document = self.collection(request.json) document.created_at = datetime.utcnow() document.updated_at = document.created_at created = document.insert() return Response( response=serialize(created), status=( 201 if not all( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve(self, request, _id): """ Returns the document containing the given _id or 404 """
_id = deserialize(_id) retrieved = self.collection.find_one({'_id': _id}) if retrieved: return Response(serialize(retrieved)) else: return Response( response=serialize( DocumentNotFoundError(self.collection.__name__, _id) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, request, _id): """ Updates the document with the given _id using the given data """
_id = deserialize(_id) to_update = self.collection.find_one({'_id': _id}) if to_update: document = self.collection(dict(to_update, **request.json)) document.updated_at = datetime.utcnow() updated = document.update() return Response( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, request, _id): """ Deletes the document with the given _id if it exists """
_id = deserialize(_id) to_delete = self.collection.get({'_id': _id}) if to_delete: deleted = to_delete.delete() return Response( response=serialize(deleted), status=( 200 if not all( key in del...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_reactor_running(): """ Starts the twisted reactor if it is not running already. The reactor is started in a new daemon-thread. Has to perform dirty h...
if not reactor.running: # Some of the `signal` API can only be called # from the main-thread. So we do a dirty workaround. # # `signal.signal()` and `signal.wakeup_fd_capture()` # are temporarily monkey-patched while the reactor is # starting. # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_json(value): """Convert the given value to a JSON object."""
if hasattr(value, 'replace'): value = value.replace('\n', ' ') try: return json.loads(value) except json.JSONDecodeError: # Escape double quotes. if hasattr(value, 'replace'): value = value.replace('"', '\\"') # try putting the value into a string ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_list(key, *values): """Convert the given list of parameters to a JSON object. JSON object is of the form: where values represent the given list of param...
return json.dumps({key: [_get_json(value) for value in values]})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def progress(progress): """Convert given progress to a JSON object. Check that progress can be represented as float between 0 and 1 and return it in JSON of the ...
if isinstance(progress, int) or isinstance(progress, float): progress = float(progress) else: try: progress = float(json.loads(progress)) except (TypeError, ValueError): return warning("Progress must be a float.") if not 0 <= progress <= 1: return wa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_file(file_path): """Prepend the given parameter with ``export``"""
if not os.path.isfile(file_path): return error("Referenced file does not exist: '{}'.".format(file_path)) return "export {}".format(file_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadNiiData(lstNiiFls, strPathNiiMask=None, strPathNiiFunc=None): """load nii data. Parameters lstNiiFls : list, list of str with nii file names strPathNiiMa...
print('---------Loading nii data') # check whether a mask is available if strPathNiiMask is not None: aryMask = nb.load(strPathNiiMask).get_data().astype('bool') # check a parent path is available that needs to be preprended to nii files if strPathNiiFunc is not None: lstNiiFls = [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calcMse(predTst, yTest, axis=0): """calculate mean squared error. Assumes that axis=0 is time Parameters predTst : np.array, predicted reponse for yTest yTes...
return np.mean((yTest - predTst) ** 2, axis=axis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect(checksum_revisions, radius=defaults.RADIUS): """ Detects reverts that occur in a sequence of revisions. Note that, `revision` data meta will simply be...
revert_detector = Detector(radius) for checksum, revision in checksum_revisions: revert = revert_detector.process(checksum, revision) if revert is not None: yield revert
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process(self, article): """ Ingests an article and processes it for metadata and elements to provide proper references in the EPUB spine. This method may onl...
if self.article is not None and not self.collection: log.warning('Could not process additional article. Package only \ handles one article unless collection mode is set.') return False if article.publisher is None: log.error('''Package cannot be generated for an Art...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acquire_metadata(self): """ Handles the acquisition of metadata for both collection mode and single mode, uses the metadata methods belonging to the article'...
#For space economy publisher = self.article.publisher if self.collection: # collection mode metadata gathering pass else: # single mode metadata gathering self.pub_id = publisher.package_identifier() self.title = publisher.package_title() ...