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 addPSF(self, psf, date=None, info='', light_spectrum='visible'): ''' add a new point spread function ''' self._registerLight(light_spectrum) date = _toDate(date) f = self.coeffs['psf'] if light_spectrum not in f: f[light_spectrum] = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addFlatField(self, arr, date=None, info='', error=None, light_spectrum='visible'): ''' light_spectrum = light, IR ... ''' self._registerLight(light_spectrum) self._checkShape(arr) date = _toDate(date) f = self.coeffs['flat field'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addLens(self, lens, date=None, info='', light_spectrum='visible'): ''' lens -> instance of LensDistortion or saved file ''' self._registerLight(light_spectrum) date = _toDate(date) if not isinstance(lens, LensDistortion): l = LensDistortion() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clearOldCalibrations(self, date=None): ''' if not only a specific date than remove all except of the youngest calibration ''' self.coeffs['dark current'] = [self.coeffs['dark current'][-1]] self.coeffs['noise'] = [self.coeffs['noise'][-1]] for light in self.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 _correctNoise(self, image): ''' denoise using non-local-means with guessing best parameters ''' from skimage.restoration import denoise_nl_means # save startup time image[np.isnan(image)] = 0 # otherwise result =nan out = denoise_nl_means(image, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _correctArtefacts(self, image, threshold): ''' Apply a thresholded median replacing high gradients and values beyond the boundaries ''' image = np.nan_to_num(image) medianThreshold(image, threshold, copy=False) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getCoeff(self, name, light=None, date=None): ''' try to get calibration for right light source, but use another if they is none existent ''' d = self.coeffs[name] try: c = d[light] except KeyError: try: k, 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 error(self, nCells=15): ''' calculate the standard deviation of all fitted images, averaged to a grid ''' s0, s1 = self.fits[0].shape aR = s0 / s1 if aR > 1: ss0 = int(nCells) ss1 = int(ss0 / aR) else: ss...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _fitImg(self, img): ''' fit perspective and size of the input image to the reference image ''' img = imread(img, 'gray') if self.bg is not None: img = cv2.subtract(img, self.bg) if self.lens is not None: img = self.lens.correct(img, 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 _findObject(self, img): ''' Create a bounding box around the object within an image ''' from imgProcessor.imgSignal import signalMinimum # img is scaled already i = img > signalMinimum(img) # img.max()/2.5 # filter noise, single-time-effects etc. from ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filterVerticalLines(arr, min_line_length=4): """ Remove vertical lines in boolean array if linelength >=min_line_length """
gy = arr.shape[0] gx = arr.shape[1] mn = min_line_length-1 for i in range(gy): for j in range(gx): if arr[i,j]: for d in range(min_line_length): if not arr[i+d,j]: break if d == mn: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def imgAverage(images, copy=True): ''' returns an image average works on many, also unloaded images minimises RAM usage ''' i0 = images[0] out = imread(i0, dtype='float') if copy and id(i0) == id(out): out = out.copy() for i in images[1:]: out += imread...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def poisson(x, a, b, c, d=0): ''' Poisson function a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation d -> offset ''' from scipy.misc import factorial #save startup time lamb = 1 X = (x/(2*c)).astype(int) return a * ((...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gaussian(x, a, b, c, d=0): ''' a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ''' return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def imread(img, color=None, dtype=None): ''' dtype = 'noUint', uint8, float, 'float', ... ''' COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE, 'all': cv2.IMREAD_COLOR, None: cv2.IMREAD_ANYCOLOR } c = COLOR2CV[color] if callable(img): img...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def linearBlend(img1, img2, overlap, backgroundColor=None): ''' Stitch 2 images vertically together. Smooth the overlap area of both images with a linear fade from img1 to img2 @param img1: numpy.2dArray @param img2: numpy.2dArray of the same shape[1,2] as img1 @param overlap: number of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def maskedConvolve(arr, kernel, mask, mode='reflect'): ''' same as scipy.ndimage.convolve but is only executed on mask==True ... which should speed up everything ''' arr2 = extendArrayForConvolution(arr, kernel.shape, modex=mode, modey=mode) print(arr2.shape) out = np.zeros_like(arr) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def closestDirectDistance(arr, ksize=30, dtype=np.uint16): ''' return an array with contains the closest distance to the next positive value given in arr within a given kernel size ''' out = np.zeros_like(arr, dtype=dtype) _calc(out, arr, ksize) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setImgShape(self, shape): ''' image shape must be known for calculating camera matrix if method==Manual and addPoints is used instead of addImg this method must be called before .coeffs are obtained ''' self.img = type('Dummy', (object,), {}) # if imgPr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addImgStream(self, img): ''' add images using a continous stream - stop when max number of images is reached ''' if self.findCount > self.max_images: raise EnoughImages('have enough images') return self.addImg(img)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addImg(self, img): ''' add one chessboard image for detection lens distortion ''' # self.opts['imgs'].append(img) self.img = imread(img, 'gray', 'uint8') didFindCorners, corners = self.method() self.opts['foundPattern'].append(didFindCorners) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getCoeffStr(self): ''' get the distortion coeffs in a formated string ''' txt = '' for key, val in self.coeffs.items(): txt += '%s = %s\n' % (key, val) return txt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drawChessboard(self, img=None): ''' draw a grid fitting to the last added image on this one or an extra image img == None ==False -> draw chessbord on empty image ==img ''' assert self.findCount > 0, 'cannot draw chessboard if nothing 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 readFromFile(self, filename): ''' read the distortion coeffs from file ''' s = dict(np.load(filename)) try: self.coeffs = s['coeffs'][()] except KeyError: #LEGENCY - remove self.coeffs = s try: self.op...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def correct(self, image, keepSize=False, borderValue=0): ''' remove lens distortion from given image ''' image = imread(image) (h, w) = image.shape[:2] mapx, mapy = self.getUndistortRectifyMap(w, h) self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def distortImage(self, image): ''' opposite of 'correct' ''' image = imread(image) (imgHeight, imgWidth) = image.shape[:2] mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight) return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _scaleTo8bit(self, img): ''' The pattern comparator need images to be 8 bit -> find the range of the signal and scale the image ''' r = scaleSignalCutParams(img, 0.02) # , nSigma=3) self.signal_ranges.append(r) return toUIntArray(img, dtype=np.uint8, 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 findHomography(self, img, drawMatches=False): ''' Find homography of the image through pattern comparison with the base image ''' print("\t Finding points...") # Find points in the next frame img = self._prepareImage(img) features, descs = self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def patCircles(s0): '''make circle array''' arr = np.zeros((s0,s0), dtype=np.uint8) col = 255 for rad in np.linspace(s0,s0/7.,10): cv2.circle(arr, (0,0), int(round(rad)), color=col, thickness=-1, lineType=cv2.LINE_AA ) if col: col = 0 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 patText(s0): '''make text pattern''' arr = np.zeros((s0,s0), dtype=np.uint8) s = int(round(s0/100.)) p1 = 0 pp1 = int(round(s0/10.)) for pos0 in np.linspace(0,s0,10): cv2.putText(arr, 'helloworld', (p1,int(round(pos0))), cv2.FONT_HERSHEY_COMPLEX_SMALL, fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def removeSinglePixels(img): ''' img - boolean array remove all pixels that have no neighbour ''' gx = img.shape[0] gy = img.shape[1] for i in range(gx): for j in range(gy): if img[i, j]: found_neighbour = False for ii in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def numbaGaussian2d(psf, sy, sx): ''' 2d Gaussian to be used in numba code ''' ps0, ps1 = psf.shape c0,c1 = ps0//2, ps1//2 ssx = 2*sx**2 ssy = 2*sy**2 for i in range(ps0): for j in range(ps1): psf[i,j]=exp( -( (i-c0)**2/ssy +(j-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 estimateBackgroundLevel(img, image_is_artefact_free=False, min_rel_size=0.05, max_abs_size=11): ''' estimate background level through finding the most homogeneous area and take its average min_size - relative size of the examined area ''' s0,s1 = 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 shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4): ''' remap an image using velocity field ''' ny,nx = u.shape sy, sx = np.mgrid[:float(ny):1,:float(nx):1] sx += u*t sy += v*t return cv2.remap(img.astype(np.float32), (sx).astype(np.float32), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def stdDev(self): ''' get the standard deviation from the PSF is evaluated as 2d Gaussian ''' if self._corrPsf is None: self.psf() p = self._corrPsf.copy() mn = p.min() p[p<0.05*p.max()] = mn p-=mn p/=p.sum() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calcAspectRatioFromCorners(corners, in_plane=False): ''' simple and better alg. than below in_plane -> whether object has no tilt, but only rotation and translation ''' q = corners l0 = [q[0, 0], q[0, 1], q[1, 0], q[1, 1]] l1 = [q[0, 0], q[0, 1], q[-1, 0], q[-1, 1]] l2 = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fastMean(img, f=10, inplace=False): ''' for bigger ksizes it if often faster to resize an image rather than blur it... ''' s0,s1 = img.shape[:2] ss0 = int(round(s0/f)) ss1 = int(round(s1/f)) small = cv2.resize(img,(ss1,ss0), interpolation=cv2.INTER_AREA) #bigger ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def averageSameExpTimes(imgs_path): ''' average background images with same exposure time ''' firsts = imgs_path[:2] imgs = imgs_path[2:] for n, i in enumerate(firsts): firsts[n] = np.asfarray(imread(i)) d = DarkCurrentMap(firsts) for i in imgs: i = imread(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 sortForSameExpTime(expTimes, img_paths): # , excludeSingleImg=True): ''' return image paths sorted for same exposure time ''' d = {} for e, i in zip(expTimes, img_paths): if e not in d: d[e] = [] d[e].append(i) # for key in list(d.keys()): # if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getDarkCurrentAverages(exposuretimes, imgs): ''' return exposure times, image averages for each exposure time ''' x, imgs_p = sortForSameExpTime(exposuretimes, imgs) s0, s1 = imgs[0].shape imgs = np.empty(shape=(len(x), s0, s1), dtype=imgs[0].dtype) for i, 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 getDarkCurrentFunction(exposuretimes, imgs, **kwargs): ''' get dark current function from given images and exposure times ''' exposuretimes, imgs = getDarkCurrentAverages(exposuretimes, imgs) offs, ascent, rmse = getLinearityFunction(exposuretimes, imgs, **kwargs) return offs, ascent, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def alignImageAlongLine(img, line, height=15, length=None, zoom=1, fast=False, borderValue=0): ''' return a sub image aligned along given line @param img - numpy.2darray input image to get subimage from @param line - list of 2 points [x0,y0,x1,y1]) @param height - he...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nan_maximum_filter(arr, ksize): ''' same as scipy.filters.maximum_filter but working excluding nans ''' out = np.empty_like(arr) _calc(arr, out, ksize//2) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fitImg(self, img_rgb): ''' fit perspective and size of the input image to the base image ''' H = self.pattern.findHomography(img_rgb)[0] H_inv = self.pattern.invertHomography(H) s = self.img_orig.shape warped = cv2.warpPerspective(img_rgb, H_inv, (s[1],...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def scaleSignalCut(img, ratio, nbins=100): ''' scaling img cutting x percent of top and bottom part of histogram ''' start, stop = scaleSignalCutParams(img, ratio, nbins) img = img - start img /= (stop - start) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getBackgroundRange(fitParams): ''' return minimum, average, maximum of the background peak ''' smn, _, _ = getSignalParameters(fitParams) bg = fitParams[0] _, avg, std = bg bgmn = max(0, avg - 3 * std) if avg + 4 * std < smn: bgmx = avg + 4 * std if avg + 3 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hasBackground(fitParams): ''' compare the height of putative bg and signal peak if ratio if too height assume there is no background ''' signal = getSignalPeak(fitParams) bg = getBackgroundPeak(fitParams) if signal == bg: return False r = signal[0] / bg[0] 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 signalMinimum2(img, bins=None): ''' minimum position between signal and background peak ''' f = FitHistogramPeaks(img, bins=bins) i = signalPeakIndex(f.fitParams) spos = f.fitParams[i][1] # spos = getSignalPeak(f.fitParams)[1] # bpos = getBackgroundPeak(f.fitParams)[1] b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def signalMinimum(img, fitParams=None, n_std=3): ''' intersection between signal and background peak ''' if fitParams is None: fitParams = FitHistogramPeaks(img).fitParams assert len(fitParams) > 1, 'need 2 peaks so get minimum signal' i = signalPeakIndex(fitParams) signal ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getSignalParameters(fitParams, n_std=3): ''' return minimum, average, maximum of the signal peak ''' signal = getSignalPeak(fitParams) mx = signal[1] + n_std * signal[2] mn = signal[1] - n_std * signal[2] if mn < fitParams[0][1]: mn = fitParams[0][1] # set to bg ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def drawQuad(self, img=None, quad=None, thickness=30): ''' Draw the quad into given img ''' if img is None: img = self.img if quad is None: quad = self.quad q = np.int32(quad) c = int(img.max()) cv2.line(img, tuple(q[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 flatFieldFromFunction(self): ''' calculate flatField from fitting vignetting function to averaged fit-image returns flatField, average background level, fitted image, valid indices mask ''' fitimg, mask = self._prepare() mask = ~mask s0, s1 = fitimg.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 flatFieldFromFit(self): ''' calculate flatField from 2d-polynomal fit filling all high gradient areas within averaged fit-image returns flatField, average background level, fitted image, valid indices mask ''' fitimg, mask = self._prepare() out = 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 register_array_types_from_sources(self, source_files): '''Add array type definitions from a file list to internal registry Args: source_files (list of str): Files to parse for array definitions ''' for fname in source_files: if is_vhdl(fname): self._register_array_types(self.ext...
<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(self, text): '''Run lexer rules against a source text Args: text (str): Text to apply lexer to Yields: A sequence of lexer matches. ''' stack = ['root'] pos = 0 patterns = self.tokens[stack[-1]] while True: for pat, action, new_state in patterns: m ...
<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_package_version(verfile): '''Scan the script for the version string''' version = None with open(verfile) as fh: try: version = [line.split('=')[1].strip().strip("'") for line in fh if \ line.startswith('__version__')][0] except IndexError: pass return versio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_verilog(text): '''Parse a text buffer of Verilog code Args: text (str): Source code to parse Returns: List of parsed objects. ''' lex = VerilogLexer name = None kind = None saved_type = None mode = 'input' ptype = 'wire' metacomments = [] parameters = [] param_items = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def extract_objects(self, fname, type_filter=None): '''Extract objects from a source file Args: fname(str): Name of file to read from type_filter (class, optional): Object class to filter results Returns: List of objects extracted from the file. ''' objects = [] if fname in 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 load_json_from_file(file_path): """Load schema from a JSON file"""
try: with open(file_path) as f: json_data = json.load(f) except ValueError as e: raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e)) else: return json_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 load_json_from_string(string): """Load schema from JSON string"""
try: json_data = json.loads(string) except ValueError as e: raise ValueError('Given string is not valid JSON: {}'.format(e)) else: return json_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 _generate_one_fake(self, schema): """ Recursively traverse schema dictionary and for each "leaf node", evaluate the fake value Implementation: For each key-v...
data = {} for k, v in schema.items(): if isinstance(v, dict): data[k] = self._generate_one_fake(v) elif isinstance(v, list): data[k] = [self._generate_one_fake(item) for item in v] else: data[k] = getattr(self._faker, v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_and_parse(method, uri, params_prefix=None, **params): """Fetch the given uri and return the root Element of the response."""
doc = ElementTree.parse(fetch(method, uri, params_prefix, **params)) return _parse(doc.getroot())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse(root): """Recursively convert an Element into python data types"""
if root.tag == "nil-classes": return [] elif root.get("type") == "array": return [_parse(child) for child in root] d = {} for child in root: type = child.get("type") or "string" if child.get("nil"): value = None elif type == "boolean": v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expandDescendants(self, branches): """ Expand descendants from list of branches :param list branches: list of immediate children as TreeOfContents objs :retu...
return sum([b.descendants() for b in branches], []) + \ [b.source for b in 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 parseBranches(self, descendants): """ Parse top level of markdown :param list elements: list of source objects :return: list of filtered TreeOfContents objec...
parsed, parent, cond = [], False, lambda b: (b.string or '').strip() for branch in filter(cond, descendants): if self.getHeadingLevel(branch) == self.depth: parsed.append({'root':branch.string, 'source':branch}) parent = True elif not parent: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fromHTML(html, *args, **kwargs): """ Creates abstraction using HTML :param str html: HTML :return: TreeOfContents object """
source = BeautifulSoup(html, 'html.parser', *args, **kwargs) return TOC('[document]', source=source, descendants=source.children)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_data(cls, type, **data): """Create an attachment from data. :param str type: attachment type :param kwargs data: additional attachment data :return: an ...
try: return cls._types[type](**data) except KeyError: return cls(type=type, **data) except TypeError as e: error = 'could not create {!r} attachment'.format(type) raise TypeError('{}: {}'.format(error, e.args[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 from_file(self, fp): """Create a new image attachment from an image file. :param file fp: a file object containing binary image data :return: an image attach...
image_urls = self.upload(fp) return Image(image_urls['url'], source_url=image_urls['picture_url'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, fp): """Upload image data to the image service. Call this, rather than :func:`from_file`, you don't want to create an attachment of the image. :...
url = utils.urljoin(self.url, 'pictures') response = self.session.post(url, data=fp.read()) image_urls = response.data return image_urls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, image, url_field='url', suffix=None): """Download the binary data of an image attachment. :param image: an image attachment :type image: :clas...
url = getattr(image, url_field) if suffix is not None: url = '.'.join(url, suffix) response = self.session.get(url) return response.content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_preview(self, image, url_field='url'): """Downlaod the binary data of an image attachment at preview size. :param str url_field: the field of the im...
return self.download(image, url_field=url_field, suffix='preview')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_large(self, image, url_field='url'): """Downlaod the binary data of an image attachment at large size. :param str url_field: the field of the image ...
return self.download(image, url_field=url_field, suffix='large')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_avatar(self, image, url_field='url'): """Downlaod the binary data of an image attachment at avatar size. :param str url_field: the field of the imag...
return self.download(image, url_field=url_field, suffix='avatar')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autopage(self): """Iterate through results from all pages. :return: all results :rtype: generator """
while self.items: yield from self.items self.items = self.fetch_next()
<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_mode(cls, **params): """Detect which listing mode of the given params. :params kwargs params: the params :return: one of the available modes :rtype: s...
modes = [] for mode in cls.modes: if params.get(mode) is not None: modes.append(mode) if len(modes) > 1: error_message = 'ambiguous mode, must be one of {}' modes_csv = ', '.join(list(cls.modes)) raise ValueError(error_message.form...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_next_page_params(self): """Set the params so that the next page is fetched."""
if self.items: index = self.get_last_item_index() self.params[self.mode] = self.get_next_page_param(self.items[index])
<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): """List the users you have blocked. :return: a list of :class:`~groupy.api.blocks.Block`'s :rtype: :class:`list` """
params = {'user': self.user_id} response = self.session.get(self.url, params=params) blocks = response.data['blocks'] return [Block(self, **block) for block in blocks]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def between(self, other_user_id): """Check if there is a block between you and the given user. :return: ``True`` if the given user has been blocked :rtype: bool ...
params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.get(self.url, params=params) return response.data['between']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block(self, other_user_id): """Block the given user. :param str other_user_id: the ID of the user to block :return: the block created :rtype: :class:`~groupy...
params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.post(self.url, params=params) block = response.data['block'] return Block(self, **block)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unblock(self, other_user_id): """Unblock the given user. :param str other_user_id: the ID of the user to unblock :return: ``True`` if successful :rtype: bool...
params = {'user': self.user_id, 'otherUser': other_user_id} response = self.session.delete(self.url, params=params) return response.ok
<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, page=1, per_page=10): """List a page of chats. :param int page: which page :param int per_page: how many chats per page :return: chats with other ...
return pagers.ChatList(self, self._raw_list, per_page=per_page, page=page)
<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, before_id=None, since_id=None, after_id=None, limit=20): """Return a page of group messages. The messages come in reversed order (newest first). N...
return pagers.MessageList(self, self._raw_list, before_id=before_id, after_id=after_id, since_id=since_id, limit=limit)
<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_since(self, message_id, limit=None): """Return a page of group messages created since a message. This is used to fetch the most recent messages after an...
return self.list(since_id=message_id, limit=limit)
<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_after(self, message_id, limit=None): """Return a page of group messages created after a message. This is used to page forwards through messages. :param ...
return self.list(after_id=message_id, limit=limit)
<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_all_before(self, message_id, limit=None): """Return all group messages created before a message. :param str message_id: the ID of a message :param int l...
return self.list_before(message_id, limit=limit).autopage()
<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_all_after(self, message_id, limit=None): """Return all group messages created after a message. :param str message_id: the ID of a message :param int lim...
return self.list_after(message_id, limit=limit).autopage()
<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, text=None, attachments=None, source_guid=None): """Create a new message in the group. :param str text: the text of the message :param attachment...
message = { 'source_guid': source_guid or str(time.time()), } if text is not None: message['text'] = text if attachments is not None: message['attachments'] = [a.to_json() for a in attachments] payload = {'message': message} respons...
<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, before_id=None, since_id=None, **kwargs): """Return a page of direct messages. The messages come in reversed order (newest first). Note you can on...
return pagers.MessageList(self, self._raw_list, before_id=before_id, since_id=since_id, **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 list_all(self, before_id=None, since_id=None, **kwargs): """Return all direct messages. The messages come in reversed order (newest first). Note you can only...
return self.list(before_id=before_id, since_id=since_id, **kwargs).autopage()
<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(self, nickname, email=None, phone_number=None, user_id=None): """Add a user to the group. You must provide either the email, phone number, or user_id tha...
member = { 'nickname': nickname, 'email': email, 'phone_number': phone_number, 'user_id': user_id, } return self.add_multiple(member)
<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_multiple(self, *users): """Add multiple users to the group at once. Each given user must be a dictionary containing a nickname and either an email, phone...
guid = uuid.uuid4() for i, user_ in enumerate(users): user_['guid'] = '{}-{}'.format(guid, i) payload = {'members': users} url = utils.urljoin(self.url, 'add') response = self.session.post(url, json=payload) return MembershipRequest(self, *users, group_id=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 check(self, results_id): """Check for results of a membership request. :param str results_id: the ID of a membership request :return: successfully created me...
path = 'results/{}'.format(results_id) url = utils.urljoin(self.url, path) response = self.session.get(url) if response.status_code == 503: raise exceptions.ResultsNotReady(response) if response.status_code == 404: raise exceptions.ResultsExpired(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 remove(self, membership_id): """Remove a member from the group. :param str membership_id: the ID of a member in this group :return: ``True`` if the member wa...
path = '{}/remove'.format(membership_id) url = utils.urljoin(self.url, path) payload = {'membership_id': membership_id} response = self.session.post(url, json=payload) return response.ok
<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(self, text=None, attachments=None, source_guid=None): """Post a direct message to the user. :param str text: the message content :param attachments: mes...
return self.messages.create(text=text, attachments=attachments, source_guid=source_guid)
<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_to_group(self, group_id, nickname=None): """Add the member to another group. If a nickname is not provided the member's current nickname is used. :param ...
if nickname is None: nickname = self.nickname memberships = Memberships(self.manager.session, group_id=group_id) return memberships.add(nickname, user_id=self.user_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 check_if_ready(self): """Check for and fetch the results if ready."""
try: results = self.manager.check(self.results_id) except exceptions.ResultsNotReady as e: self._is_ready = False self._not_ready_exception = e except exceptions.ResultsExpired as e: self._is_ready = True self._expired_exception = 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 get_failed_requests(self, results): """Return the requests that failed. :param results: the results of a membership request check :type results: :class:`list...
data = {member['guid']: member for member in results} for request in self.requests: if request['guid'] not in data: yield request
<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_new_members(self, results): """Return the newly added members. :param results: the results of a membership request check :type results: :class:`list` :re...
for member in results: guid = member.pop('guid') yield Member(self.manager, self.group_id, **member) member['guid'] = guid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_ready(self, check=True): """Return ``True`` if the results are ready. If you pass ``check=False``, no attempt is made to check again for results. :param b...
if not self._is_ready and check: self.check_if_ready() return self._is_ready
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll(self, timeout=30, interval=2): """Return the results when they become ready. :param int timeout: the maximum time to wait for the results :param float i...
time.sleep(interval) start = time.time() while time.time() - start < timeout and not self.is_ready(): time.sleep(interval) return self.get()