Search is not available for this dataset
text
stringlengths
75
104k
def rgb_color(self): """Return the color property as list of [R, G, B], each 0-255.""" self.update() return [self._red, self._green, self._blue]
def turn_on(self): """Turn bulb on (full brightness).""" command = "C {},,,,100,\r\n".format(self._zid) response = self._hub.send_command(command) _LOGGER.debug("Turn on %s: %s", repr(command), response) return response
def set_brightness(self, brightness): """Set brightness of bulb.""" command = "C {},,,,{},\r\n".format(self._zid, brightness) response = self._hub.send_command(command) _LOGGER.debug("Set brightness %s: %s", repr(command), response) return response
def set_all(self, red, green, blue, brightness): """Set color and brightness of bulb.""" command = "C {},{},{},{},{},\r\n".format(self._zid, red, green, blue, brightness) response = self._hub.send_command(command) _LOGGER.debug("Set all %s...
def update(self): """Update light objects to their current values.""" bulbs = self._hub.get_lights() if not bulbs: _LOGGER.debug("%s is offline, send command failed", self._zid) self._online = False
def functional(ifunctional): """ fun(fn) -> function or fun(fn, args...) -> call of fn(args...) :param ifunctional: f :return: decorated function """ @wraps(ifunctional) def wrapper(fn, *args, **kw): fn = ifunctional(fn) if args or kw: return fn(*args, **kw)...
def tuple_arg(fn): """ fun(1,2) -> fun((1,), (2,))๋กœ f(1,2,3) => f((1,), (2,), (3,)) :param fn: :return: """ @wraps(fn) def wrapped(*args, **kwargs): args = map(tuplefy, args) return fn(*args, **kwargs) return wrapped
def tuple_args(fn): """ args ํŒŒ์‹ฑ ์œ ํ‹ธ function fun(p1, p2, ...pn, **kwargs) or fun([p1, p2, ..], **kwargs) ex) ์ƒ˜ํ”Œ:: @tuple_arg def f(args, **kwargs): for d in args: print d f(1,2,3) => f([1,2,3]) :param function fn: :return: """ @wraps(...
def unpack_args(classfun, nth=0): """ args ๊ฐฏ์ˆ˜๊ฐ€ nth + 1 ๊ฐœ ์ผ๋•Œ, ๊ทธ๊ฒŒ ๋งŒ์•ฝ tuple์ด๋ฉด, unpack :param classfun: :param nth: nth = 0, ์ผ๋ฐ˜ ํ•จ์ˆ˜, nth = 1: ํด๋ž˜์Šค ํ•จ์ˆ˜ 1์ด self๋‹ˆ๊น. :return: """ if classfun: nth = 1 def deco(fn): def wrapped(*args, **kwargs): if len(args) == nth + 1 an...
def optional_str(deco): """ string 1๊ฐœ๋งŒ deco ์ธ์ž๋กœ ์˜ค๊ฑฐ๋‚˜ ์—†๊ฑฐ๋‚˜. :param deco: :return: """ @wraps(deco) def dispatcher(*args, **kwargs): # when only function arg if not kwargs and len(args) == 1 and not isinstance(args[0], str) \ and args[0] is not None: ...
def patchmethod(*cls, **kwargs): """ ํด๋ž˜์Šค ๋ฉค๋ฒ„ ํŒจ์น˜ @patchmethod(Cls1, ..., [name='membername']) ex) class A(object): def __init__(self, data): self.data = data @patchmethod(A) def sample(self): ''' haha docstrings ''' print self.data @patchmethod(A, name='me...
def patchproperty(*cls, **kwargs): """ class getter ํ•จ์ˆ˜ ํŒจ์น˜ decorator EX) class B(A): pass @patchproperty(B) def prop(self): return 'hello' :param cls: :param kwargs: """ def _patch(fun): m = kwargs.pop('property', None) or fun.__name__ p = proper...
def on_interrupt(handler, reraise=False): """ context for handling keyboardinterrupt ex) with on_interrupt(handler): critical_work_to_prevent() from logger import logg on_interrupt.signal = None :param function handler: :param bool reraise: :return: context """ def...
def interrupt_guard(msg='', reraise=True): """ context for guard keyboardinterrupt ex) with interrupt_guard('need long time'): critical_work_to_prevent() :param str msg: message to print when interrupted :param reraise: re-raise or not when exit :return: context """ def echo...
def is_main_alive(): """ is ๋ฉ”์ธ ์“ฐ๋ ˆ๋“œ alive? :rtype: bool """ for t in threading.enumerate(): if t.name == 'MainThread': return t.is_alive() print('MainThread not found') return False
def retrieve_document(file_path, directory='sec_filings'): ''' This function takes a file path beginning with edgar and stores the form in a directory. The default directory is sec_filings but can be changed through a keyword argument. ''' ftp = FTP('ftp.sec.gov', timeout=None) ftp.login...
def action(self, item): """ for overriding :param item: :return: """ fun, args, kwargs = item return fun(*args, **kwargs)
def push_job(self, fun, *args, **kwargs): """ put job if possible, non-blocking :param fun: :param args: :param kwargs: :return: """ assert callable(fun) return self.put((fun, args, kwargs), block=True)
def put_job(self, fun, *args, **kwargs): """ put job if possible, non-blocking :param fun: :param args: :param kwargs: :return: """ if not args and not kwargs and isinstance(fun, (tuple, list)): # ex) q.put_job([fun, args, kwargs]) ...
def add_flag(*args, **kwargs): """ define a single flag. add_flag(flagname, default_value, help='', **kwargs) add_flag([(flagname, default_value, help), ...]) or define flags without help message add_flag(flagname, default_value, help='', **kwargs) add_flag('gpu', 1, help='CUDA_VISIBLE_...
def run(main=None, argv=None, **flags): """ :param main: main or sys.modules['__main__'].main :param argv: argument list used in argument parse :param flags: flags to define with defaults :return: """ """Runs the program with an optional 'main' function and 'argv' list.""" import sys as ...
def mkdir_if_not(filepath, ispath=False): """ path ๋ถ€๋ถ„์ด ์—†์œผ๋ฉด mkdir ์„ ํ•œ๋‹ค. :param filepath: ํŒŒ์ผ ํŒจ์“ฐ :return: filpath ๊ทธ๋Œ€๋กœ ๋ฆฌํ„ด """ if not ispath: p, _ = os.path.split(filepath) else: p = filepath if not p: return filepath if not os.path.exists(p): # M.info('%s...
def readlines(filepath): """ read lines from a textfile :param filepath: :return: list[line] """ with open(filepath, 'rt') as f: lines = f.readlines() lines = map(str.strip, lines) lines = [l for l in lines if l] return lines
def readtxt(filepath): """ read file as is""" with open(filepath, 'rt') as f: lines = f.readlines() return ''.join(lines)
def savefile(obj, filepath, compress=True): """ ํŒŒ์ผ ์žˆ์œผ๋ฉด ๋ฎ์–ด์”€ :param obj: :param str filepath: :param compress: :return: """ try: import cPickle as pickle except Exception: import pickle import joblib # ์ผ๋‹จ ์ž„์‹œ ํŒŒ์ผ์— ์ €์žฅ. tmpfile = filepath + '.tmp' mkdir_if_...
def loadfile(filepath, mmap_mode=None): """ :param filepath: :param mmap_mode: {None, โ€˜r+โ€™, โ€˜rโ€™, โ€˜w+โ€™, โ€˜cโ€™} see. joblib.load :return: """ import joblib try: return joblib.load(filepath, mmap_mode=mmap_mode) except IOError: return None
def load_or_run(filepath, fun, *args, **kwargs): """ ๊ณ„์‚ฐ๋œ ๊ฒฐ๊ณผ ํŒŒ์ผ์ด ์žˆ์œผ๋ฉด ๋กœ๋”ฉํ•˜๊ณ , ์—†์œผ๋ฉด ๊ณ„์‚ฐํ›„ ์ €์žฅ ex) res = load_or_run('file_loadorsave', funlongtime, ...., force=False) :param filepath: :param fun: :param force: :return: """ force = kwargs.pop('force', False) compress = kwargs.pop('comp...
def fnmatches(fname, patterns, matchfun): """" matches? :param fname: file name :type fname: str :param patterns: list of filename pattern. see fnmatch.fnamtch :type patterns: [str] :rtype: generator of bool """ import fnmatch matchfun = matchfun or fnmatch.fnmatch for p in p...
def listdir(p, match='*', exclude='', listtype='file', matchfun=None): """ list file(or folder) for this path (NOT recursive) :param p: :param match: :param exclude: :param listtype: ('file' | 'filepath' |'dir' | 'all') :param matchfun: match fun (default fnmatch.fnmatch) True/False = matchf...
def listfile(p): """ generator of list files in the path. filenames only """ try: for entry in scandir.scandir(p): if entry.is_file(): yield entry.name except OSError: return
def listfilepath(p): """ generator of list files in the path. filenames only """ for entry in scandir.scandir(p): if entry.is_file(): yield entry.path
def listfolder(p): """ generator of list folder in the path. folders only """ for entry in scandir.scandir(p): if entry.is_dir(): yield entry.name
def listfolderpath(p): """ generator of list folder in the path. folders only """ for entry in scandir.scandir(p): if entry.is_dir(): yield entry.path
def _pred_pattern(match='*', exclude='', patterntype='fnmatch'): """ internal use """ m, x = match, exclude if m == '*': if not x: pred = lambda n: True else: x = [x] if _is_str(x) else x matcher = get_match_fun(x, patterntype) pred = lambda n...
def findfolder(toppath, match='*', exclude=''): """ recursively find folder path from toppath. patterns to decide to walk folder path or not :type toppath: str :type match: str or list(str) :type exclude: str or list(str) :rtype: generator for path str """ pred = _pred_pattern(match,...
def walkfolder(toppath, pred): """ walk folder if pred(foldername) is True :type toppath: str :type pred: function(str) => bool """ for entry in scandir.scandir(toppath): if not entry.is_dir() or not pred(entry.name): continue yield entry.path for p in walkfol...
def tempfolder(prefix=''): """์ž„์‹œ ํด๋”๋ฅผ ๋งŒ๋“ค์–ด์„œ ๋ฆฌํ„ด""" import uuid p = prefix + str(uuid.uuid4()) d = tempdir() tmpd = os.path.join(d, p) return mkdir_if_not(tmpd, ispath=True)
def imsize(fname): """ return image size (height, width) :param fname: :return: """ from PIL import Image im = Image.open(fname) return im.size[1], im.size[0]
def intersect(self, other): """ self์™€ other ํ‚ค๊ฐ€ ๋™์ผํ•œ ์•„์ดํ…œ์˜ dictobj :type other: dict :rtype: dictobj: """ return DictObj({k: self[k] for k in self if k in other})
def from_dict(dic): """ recursive dict to dictobj ์ปจ๋ฒ„ํŠธ :param dic: :return: """ return DictObj({k: DictObj.convert_ifdic(v) for k, v in dic.items()})
def _clean_up(paths): """ Clean up after ourselves, removing created files. @param {[String]} A list of file paths specifying the files we've created during run. Will all be deleted. @return {None} """ print('Cleaning up') # Iterate over the given paths, unlinking them for path i...
def _create_index_file( root_dir, location, image_files, dirs, force_no_processing=False): """ Create an index file in the given location, supplying known lists of present image files and subdirectories. @param {String} root_dir - The root directory of the entire crawl. Used to ascertain...
def _create_index_files(root_dir, force_no_processing=False): """ Crawl the root directory downwards, generating an index HTML file in each directory on the way down. @param {String} root_dir - The top level directory to crawl down from. In normal usage, this will be '.'. @param {Boolean=Fal...
def _get_image_from_file(dir_path, image_file): """ Get an instance of PIL.Image from the given file. @param {String} dir_path - The directory containing the image file @param {String} image_file - The filename of the image file within dir_path @return {PIL.Image} An instance of the image file as a ...
def _get_image_link_target_from_file(dir_path, image_file, force_no_processing=False): """ Get the value to be used as the href for links from thumbnail images. For most image formats this will simply be the image file name itself. However, some image formats (tif) are not natively displayable by many b...
def _get_image_src_from_file(dir_path, image_file, force_no_processing=False): """ Get base-64 encoded data as a string for the given image file's full image, for use directly in HTML <img> tags, or a path to the original if image scaling is not supported. This is a full-sized version of _get_thumbn...
def _get_src_from_image(img, fallback_image_file): """ Get base-64 encoded data as a string for the given image. Fallback to return fallback_image_file if cannot get the image data or img is None. @param {Image} img - The PIL Image to get src data for @param {String} fallback_image_file - The filena...
def _get_thumbnail_image_from_file(dir_path, image_file): """ Get a PIL.Image from the given image file which has been scaled down to THUMBNAIL_WIDTH wide. @param {String} dir_path - The directory containing the image file @param {String} image_file - The filename of the image file within dir_path ...
def _get_thumbnail_src_from_file(dir_path, image_file, force_no_processing=False): """ Get base-64 encoded data as a string for the given image file's thumbnail, for use directly in HTML <img> tags, or a path to the original if image scaling is not supported. @param {String} dir_path - The directory...
def _run_server(): """ Run the image server. This is blocking. Will handle user KeyboardInterrupt and other exceptions appropriately and return control once the server is stopped. @return {None} """ # Get the port to run on port = _get_server_port() # Configure allow_reuse_address to...
def serve_dir(dir_path): """ Generate indexes and run server from the given directory downwards. @param {String} dir_path - The directory path (absolute, or relative to CWD) @return {None} """ # Create index files, and store the list of their paths for cleanup later # This time, force no pro...
def modulename(cls, depth=1): """ get caller's __name__ """ depth += cls.extra_depth frame = sys._getframe(depth) return frame.f_globals['__name__']
def deco_optional(decorator): """ optional argument ๋ฅผ ํฌํ•จํ•˜๋Š” decorator๋ฅผ ๋งŒ๋“œ๋Š” decorator """ @functools.wraps(decorator) def dispatcher(*args, **kwargs): one_arg = len(args) == 1 and not kwargs if one_arg and inspect.isfunction(args[0]): decor_obj = decorator() re...
def optional(deco): """ decorator option์€ kwargs๋งŒ ํ—ˆ์šฉ :param deco: :return: """ @functools.wraps(deco) def dispatcher(*args, **kwargs): decorator = deco(**kwargs) if args: assert len(args) == 1 return decorator(args[0]) else: return ...
def bindargs(fun, *argsbind, **kwbind): """ _ = bind.placeholder # unbound placeholder (arg) f = bind(fun, _, _, arg3, kw=kw1, kw2=kw2), f(arg1, arg2) :param fun: :param argsbind: :param kwbind: :return: """ assert argsbind argsb = list(argsbind) iargs = [i for i in range(...
def bindkw(fun, **kwbind): """ kwarg ๋ฐ”์ธ๋”ฉ๋œ ํ•จ์ˆ˜ return. ex) def fun(opt1, opt2): print opt1, opt2 f = bind(fun, opt1=2, opt2=3) f() :param function fun: :param kwbind: :return: function """ @functools.wraps(fun) def wrapped(*args, **kwargs): kws = kwbind.co...
def default(fun, **kwdefault): """ change default value for function ex) def sample(a, b=1, c=1): print 'from sample:', a, b, c return a, b, c fun = default(sample, b=4,c=5) print fun.default # get default value dictionary fun(1) # print 1, 5, 5 and return :param fun: ...
def setup_once(initfn): """ call class instance method for initial setup :: class B(object): def init(self, a): print 'init call:', a @setup_once(init) def mycall(self, a): print 'real call:', a b = B() b.mycall(222)...
def static(**kwargs): """ USE carefully ^^ """ def wrap(fn): fn.func_globals['static'] = fn fn.__dict__.update(kwargs) return fn return wrap
def rand_crop(sz, *imagez): """ random crop # assume imagez has same size (H, W) # assume sz is less or equal than size of image :param sz: cropped image sz :param imagez: imagez :return: rand cropped image pairs or function bound to sz """ def _rand_crop(*imgz): imsz = imgz...
def rand_rotate(anglerange, *imagez): """ :param anglerange: :param imagez: :return: """ r = float(anglerange[1] - anglerange[0]) s = anglerange[0] def _rand_rotate(*imgz): angle = np.random.random(1)[0] * r + s out = tuple(rotate(img, angle) for img in imgz) ret...
def blend_discrete(images, depthmask, depth=None): """ depthmask : shape of [batch, h, w] """ imshape = images.shape depth = depth or images.shape[3] blend = np.empty(shape=(imshape[0], imshape[1], imshape[2])) for d in range(depth): imask = (depthmask == d) channel = images[...
def rand_blend_mask(shape, rand=rand.uniform(-10, 10), **kwargs): """ random blending masks """ # batch, channel = shape[0], shape[3] z = rand(shape[0]) # seed noise = snoise2dz((shape[1], shape[2]), z, **kwargs) return noise
def snoise2dvec(size, *params, **kwargs): #, vlacunarity): """ vector parameters :param size: :param vz: :param vscale: :param voctave: :param vpersistence: :param vlacunarity: :return: """ data = (snoise2d(size, *p, **kwargs) for p in zip(*params)) # , vlacunarity)) re...
def snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0): """ z value as like a seed """ import noise data = np.empty(size, dtype='float32') for y in range(size[0]): for x in range(size[1]): v = noise.snoise3(x * scale, y * scale, z, ...
def snoise2dz(size, z, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0): """ z as seeds scale์ด ์ž‘์„ ์ˆ˜๋ก ํŒจํ„ด์ด ์ปค์ง€๋Š” ํšจ๊ณผ """ import noise z_l = len(z) data = np.empty((z_l, size[0], size[1]), dtype='float32') for iz in range(z_l): zvalue = z[iz] for y in range(size[0]): ...
def rand_brightness(imagez, scale=1.0, randfun=rand.normal(0., .1), clamp=(0., 1.)): """ :param images: :param scale: scale for random value :param randfun: any randfun binding except shape :param clamp: clamping range :return: """ l, h = clamp r = randfun((imagez[0].shape[0], 1, 1, ...
def elastic_transform(im, alpha=0.5, sigma=0.2, affine_sigma=1.): """ Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5 elastic deformation of images as described in [Simard2003] """ # fixme : not implemented for multi channel ! import cv2 islist = isinstance(im, (tuple, lis...
def rotate_crop(centerij, sz, angle, img=None, mode='constant', **kwargs): """ rotate and crop if no img, then return crop function :param centerij: :param sz: :param angle: :param img: [h,w,d] :param mode: padding option :return: cropped image or function """ # crop enough s...
def crop(img, center, sz, mode='constant'): """ crop sz from ij as center :param img: :param center: ij :param sz: :param mode: :return: """ center = np.array(center) sz = np.array(sz) istart = (center - sz / 2.).astype('int32') iend = istart + sz imsz = img.shape[:2]...
def cropcenter(sz, img=None): """ if no img, then return crop function :param sz: :param img: :return: """ l = len(sz) sz = np.array(sz) def wrapped(im): imsz = np.array(im.shape) s = (imsz[:l] - sz) / 2 # start index to = s + sz # end index # img[...
def pad_if_need(sz_atleast, img, mode='constant'): # fixme : function or .... """ pad img if need to guarantee minumum size :param sz_atleast: [H,W] at least :param img: image np.array [H,W, ...] :param mode: str, padding mode :return: padded image or asis if enought size """ # sz_at...
def canny(img, threshold1=255/3, threshold2=255, **kwargs): """ canny edge """ import cv2 # edges=None, apertureSize=None, L2gradient=None if img.ndim <= 3: edge = cv2.Canny(img, threshold1, threshold2, **kwargs) if edge.ndim == 2: edge = np.expand_dims(edge, 2) elif img....
def guess_package_path(searchfrom): """ package path. return None if failed to guess """ from snipy.io import fileutil current = searchfrom + '/' init_found = False pack_found = False while not init_found and current != '/': current = os.path.dirname(current) initfile = ...
def find_package_path(searchfrom): """ package path. return None if failed to guess """ current = searchfrom + '/' init_found = False pack_found = False while not init_found and current != '/': current = os.path.dirname(current) initfile = os.path.join(current, '__init__.py'...
def append_this_package_path(depth=1): """ this_package.py ์—์„œ ์‚ฌ์šฉ import snipy.this_package """ from .caller import caller logg.debug('caller module %s', caller.modulename(depth + 1)) c = caller.abspath(depth + 1) logg.debug('caller path %s', c) p = guess_package_path(dirname(c)) ...
def flows(args): """ todo : add some example :param args: :return: """ def flow_if_not(fun): # t = type(fun) if isinstance(fun, iterator): return fun elif isinstance(fun, type) and 'itertools' in str(fun.__class__): return fun else: ...
def forever(it): """ forever todo : add example """ while True: # generator ๋‘๋ฒˆ์จฐ iteration ๋ฌดํ•œ ๋ฃจํ”„ ๋ฐฉ์ง€ i = iter(it) try: yield i.next() except StopIteration: raise StopIteration while True: try: yield i.next() ...
def ibatch(size, iterable=None, rest=False): """ add example :param size: :param iterable: :param rest: :return: """ @iterflow def exact_size(it): it = iter(it) while True: yield [it.next() for _ in xrange(size)] @iterflow def at_most(it): ...
def batchzip(size, iterable=None, rest=False): """ todo : add example :param size: :param iterable: :param rest: :return: """ fn = ibatch(size, rest=rest) >> zipflow return fn if iterable is None else fn(iterable)
def batchstack(size, iterable=None, rest=False): """ todo : add example :param size: :param iterable: :param rest: :return: """ def stack(data): import numpy as np return map(np.vstack, data) fn = batchzip(size, rest=rest) >> flow(stack) return fn if iterable i...
def shuffle(qsize=1024, iterable=None): """ add example :param qsize: :param iterable: :return: """ @iterflow def shuffleit(it): from random import randrange q = [] for i, d in enumerate(it): q.insert(randrange(0, len(q) + 1), d) if i < q...
def to_permutation_matrix(matches): """Converts a permutation into a permutation matrix. `matches` is a dictionary whose keys are vertices and whose values are partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the returned matrix will be a ``1`` if and only if ``matches[u] == v``. ...
def four_blocks(topleft, topright, bottomleft, bottomright): """Convenience function that creates a block matrix with the specified blocks. Each argument must be a NumPy matrix. The two top matrices must have the same number of rows, as must the two bottom matrices. The two left matrices must have ...
def to_bipartite_matrix(A): """Returns the adjacency matrix of a bipartite graph whose biadjacency matrix is `A`. `A` must be a NumPy array. If `A` has **m** rows and **n** columns, then the returned matrix has **m + n** rows and columns. """ m, n = A.shape return four_blocks(zeros(m,...
def to_pattern_matrix(D): """Returns the Boolean matrix in the same shape as `D` with ones exactly where there are nonzero entries in `D`. `D` must be a NumPy array. """ result = np.zeros_like(D) # This is a cleverer way of doing # # for (u, v) in zip(*(D.nonzero())): # ...
def birkhoff_von_neumann_decomposition(D): """Returns the Birkhoff--von Neumann decomposition of the doubly stochastic matrix `D`. The input `D` must be a square NumPy array representing a doubly stochastic matrix (that is, a matrix whose entries are nonnegative reals and whose row sums and column ...
def bump_version(version, which=None): """Returns the result of incrementing `version`. If `which` is not specified, the "patch" part of the version number will be incremented. If `which` is specified, it must be ``'major'``, ``'minor'``, or ``'patch'``. If it is one of these three strings, the corres...
def get_version(filename, pattern): """Gets the current version from the specified file. This function assumes the file includes a string of the form:: <pattern> = <version> """ with open(filename) as f: match = re.search(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, f.read()) if ma...
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """ print('Error:', message, file=sys.stderr) sys.exit(exit_status or 1)
def git_tag(tag): """Tags the current version.""" print('Tagging "{}"'.format(tag)) msg = '"Released version {}"'.format(tag) Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()
def initialize(self, templates_path, global_data): """initialize with templates' path parameters templates_path str the position of templates directory global_data dict globa data can be got in any templates""" self.env = Environment(loader=FileSystemLoader(temp...
def render(self, template, **data): """Render data with template, return html unicodes. parameters template str the template's filename data dict the data to render """ # make a copy and update the copy dct = self.global_data.copy() dct.update...
def render_to(self, path, template, **data): """Render data with template and then write to path""" html = self.render(template, **data) with open(path, 'w') as f: f.write(html.encode(charset))
def render(template, **data): """shortcut to render data with `template`. Just add exception catch to `renderer.render`""" try: return renderer.render(template, **data) except JinjaTemplateNotFound as e: logger.error(e.__doc__ + ', Template: %r' % template) sys.exit(e.exit_code)
def replace_relative_url_to_absolute(self, content): """Replace '../' leaded url with absolute uri. """ p = os.path.join(os.getcwd(), './src', '../') return content.replace('../', p)
def get_dataframe(self): """ Get the DataFrame for this view. Defaults to using `self.dataframe`. This method should always be used rather than accessing `self.dataframe` directly, as `self.dataframe` gets evaluated only once, and those results are cached for all subsequ...
def index_row(self, dataframe): """ Indexes the row based on the request parameters. """ return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T
def get_object(self): """ Returns the row the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ dataframe = self.filter_dataf...
def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() ...