repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
tschaume/ccsgp_get_started
ccsgp_get_started/examples/gp_lcltpt.py
gp_lcltpt
python
def gp_lcltpt(): inDir, outDir = getWorkDirs() nSets = len(default_colors) make_plot( data = [ np.array([ [0,i,0,0,0], [1,i,0,0,0] ]) for i in xrange(nSets) ], properties = [ 'with linespoints lw 4 lc %s lt %d pt %d' % (col, i, i) for i, col in enumerate(default_colors) ], ...
example plot to display linecolors, linetypes and pointtypes .. image:: pics/gp_lcltpt.png :width: 450 px
train
https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_lcltpt.py#L7-L28
[ "def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package...
import os import numpy as np from ..ccsgp.ccsgp import make_plot from .utils import getWorkDirs from ..ccsgp.config import default_colors if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() args = parser.parse_args() print gp_lcltpt()
tschaume/ccsgp_get_started
ccsgp_get_started/examples/gp_datdir.py
gp_datdir
python
def gp_datdir(initial, topN): # prepare input/output directories inDir, outDir = getWorkDirs() initial = initial.capitalize() inDir = os.path.join(inDir, initial) if not os.path.exists(inDir): # catch missing initial return "initial %s doesn't exist" % initial # prepare data data = OrderedDict() for...
example for plotting from a text file via numpy.loadtxt 1. prepare input/output directories 2. load the data into an OrderedDict() [adjust axes units] 3. sort countries from highest to lowest population 4. select the <topN> most populated countries 5. call ccsgp.make_plot with data from 4 Below is an outp...
train
https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_datdir.py#L8-L78
[ "def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package...
import logging, argparse, os, sys import numpy as np from collections import OrderedDict from ..ccsgp.ccsgp import make_plot from .utils import getWorkDirs from ..ccsgp.utils import getOpts if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("initial", help="country initial = input s...
tschaume/ccsgp_get_started
ccsgp_get_started/examples/gp_rdiff.py
gp_rdiff
python
def gp_rdiff(version, nomed, noxerr, diffRel, divdNdy): inDir, outDir = getWorkDirs() inDir = os.path.join(inDir, version) data, cocktail, medium, rhofo, vacrho = \ OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict() #scale = { # QM14 (19 GeV skip later, factor here only informat...
example for ratio or difference plots using QM12 data (see gp_panel) - uses uncertainties package for easier error propagation and rebinning - stat. error for medium = 0! - stat. error for cocktail ~ 0! - statistical error bar on data stays the same for diff - TODO: implement ratio! - TODO: adjust statisti...
train
https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_rdiff.py#L17-L491
[ "def getWorkDirs():\n \"\"\"get input/output dirs (same input/output layout as for package)\"\"\"\n # get caller module\n caller_fullurl = inspect.stack()[1][1]\n caller_relurl = os.path.relpath(caller_fullurl)\n caller_modurl = os.path.splitext(caller_relurl)[0]\n # split caller_url & append 'Dir' to package...
import logging, argparse, os, sys, re import numpy as np from fnmatch import fnmatch from collections import OrderedDict from .utils import getWorkDirs, eRanges, getEnergy4Key from .utils import getUArray, getEdges, getCocktailSum, enumzipEdges, getMassRangesSums from .utils import getErrorComponent from ..ccsgp.ccsgp ...
bwesterb/mirte
src/__init__.py
get_a_manager
python
def get_a_manager(threadPool_settings=None): global __singleton_manager if __singleton_manager is None: def _thread_entry(): if prctl: prctl.set_name('mirte manager') m.run() l.info('manager.run() returned') l = logging.getLogger('mirte.get_a_m...
On first call, creates and returns a @mirte.core.Manager. On subsequent calls, returns the previously created instance. If it is the first call, it will initialize the threadPool with @threadPool_settings.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/__init__.py#L17-L38
null
import logging import threading from mirte.core import Manager __names__ = ['get_a_manager'] try: import prctl except ImportError: prctl = None __singleton_manager = None # vim: et:sta:bs=2:sw=4:
bwesterb/mirte
src/main.py
parse_cmdLine_instructions
python
def parse_cmdLine_instructions(args): instructions = dict() rargs = list() for arg in args: if arg[:2] == '--': tmp = arg[2:] bits = tmp.split('=', 1) if len(bits) == 1: bits.append('') instructions[bits[0]] = bits[1] else: ...
Parses command-line arguments. These are instruction to the manager to create instances and put settings.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/main.py#L14-L29
null
import logging import os.path import sys import six from mirte.core import Manager from mirte.mirteFile import load_mirteFile from sarah.order import sort_by_successors import sarah.coloredLogging def execute_cmdLine_instructions(instructions, m, l): """ Applies the instructions given via <instruction...
bwesterb/mirte
src/main.py
execute_cmdLine_instructions
python
def execute_cmdLine_instructions(instructions, m, l): opt_lut = dict() inst_lut = dict() for k, v in six.iteritems(instructions): bits = k.split('-', 1) if len(bits) == 1: if v not in m.modules: raise KeyError("No such module: %s" % v) inst_lut[bits[0]...
Applies the instructions given via <instructions> on the manager <m>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/main.py#L32-L67
null
import logging import os.path import sys import six from mirte.core import Manager from mirte.mirteFile import load_mirteFile from sarah.order import sort_by_successors import sarah.coloredLogging def parse_cmdLine_instructions(args): """ Parses command-line arguments. These are instruction to the man...
bwesterb/mirte
src/main.py
main
python
def main(): sarah.coloredLogging.basicConfig(level=logging.DEBUG, formatter=MirteFormatter()) l = logging.getLogger('mirte') instructions, args = parse_cmdLine_instructions(sys.argv[1:]) m = Manager(l) load_mirteFile(args[0] if args else 'default', m, logger=l) ...
Entry-point
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/main.py#L86-L95
[ "def parse_cmdLine_instructions(args):\n \"\"\" Parses command-line arguments. These are\n instruction to the manager to create instances and\n put settings. \"\"\"\n instructions = dict()\n rargs = list()\n for arg in args:\n if arg[:2] == '--':\n tmp = arg[2:]\n ...
import logging import os.path import sys import six from mirte.core import Manager from mirte.mirteFile import load_mirteFile from sarah.order import sort_by_successors import sarah.coloredLogging def parse_cmdLine_instructions(args): """ Parses command-line arguments. These are instruction to the man...
bwesterb/mirte
src/mirteFile.py
depsOf_of_mirteFile_instance_definition
python
def depsOf_of_mirteFile_instance_definition(man, insts): return lambda x: [a[1] for a in six.iteritems(insts[x]) if a[0] in [dn for dn, d in ( six.iteritems(man.modules[insts[x]['module']].deps) if 'module' in insts[x] else [])]]
Returns a function that returns the dependencies of an instance definition by its name, where insts is a dictionary of instance definitions from a mirteFile
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L31-L38
null
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
depsOf_of_mirteFile_module_definition
python
def depsOf_of_mirteFile_module_definition(defs): return lambda x: (list(filter(lambda z: z is not None and z in defs, map(lambda y: y[1].get('type'), six.iteritems(defs[x]['settings']) if 'settings' in defs[x] else []))))...
Returns a function that returns the dependencies of a module definition by its name, where defs is a dictionary of module definitions from a mirteFile
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L41-L49
null
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
module_definition_from_mirteFile_dict
python
def module_definition_from_mirteFile_dict(man, d): m = ModuleDefinition() if 'inherits' not in d: d['inherits'] = list() if 'settings' not in d: d['settings'] = dict() if 'implementedBy' in d: m.implementedBy = d['implementedBy'] m.inherits = set(d['inherits']) for p in d...
Creates a ModuleDefinition instance from the dictionary <d> from a mirte-file for the Manager instance <man>.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L52-L92
null
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
load_mirteFile
python
def load_mirteFile(path, m, logger=None): l = logging.getLogger('load_mirteFile') if logger is None else logger had = set() for name, path, d in walk_mirteFiles(path, logger): if os.path.realpath(path) in m.loaded_mirteFiles: continue identifier = name if name in had: ...
Loads the mirte-file at <path> into the manager <m>.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L95-L109
[ "def walk_mirteFiles(name, logger=None):\n \"\"\" Yields (cpath, d) for all dependencies of and including the\n mirte-file <name>, where <d> are the dictionaries from\n the mirte-file at <cpath> \"\"\"\n stack = [(name, find_mirteFile(name, (os.getcwd(),)))]\n loadStack = []\n had = dict()...
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
_load_mirteFile
python
def _load_mirteFile(d, m): defs = d['definitions'] if 'definitions' in d else {} insts = d['instances'] if 'instances' in d else {} # Filter out existing instances insts_to_skip = [] for k in insts: if k in m.insts: m.update_instance(k, dict(insts[k])) insts_to_skip.a...
Loads the dictionary from the mirteFile into <m>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L112-L156
[ "def depsOf_of_mirteFile_instance_definition(man, insts):\n \"\"\" Returns a function that returns the dependencies of\n an instance definition by its name, where insts is a\n dictionary of instance definitions from a mirteFile \"\"\"\n return lambda x: [a[1] for a in six.iteritems(insts[x])\n ...
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
find_mirteFile
python
def find_mirteFile(name, extra_path=None): extra_path = () if extra_path is None else extra_path for bp in chain(extra_path, sys.path): pb = os.path.join(bp, name) p = pb + FILE_SUFFIX if os.path.exists(p): return os.path.abspath(p) p = os.path.join(pb, DEFAULT_FILE) ...
Resolves <name> to a path. Uses <extra_path>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L159-L170
null
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
walk_mirteFiles
python
def walk_mirteFiles(name, logger=None): stack = [(name, find_mirteFile(name, (os.getcwd(),)))] loadStack = [] had = dict() while stack: name, path = stack.pop() if path in had: d = had[path] else: d = _parse_mirteFile(path, logger) had[path] = ...
Yields (cpath, d) for all dependencies of and including the mirte-file <name>, where <d> are the dictionaries from the mirte-file at <cpath>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L173-L199
[ "def find_mirteFile(name, extra_path=None):\n \"\"\" Resolves <name> to a path. Uses <extra_path> \"\"\"\n extra_path = () if extra_path is None else extra_path\n for bp in chain(extra_path, sys.path):\n pb = os.path.join(bp, name)\n p = pb + FILE_SUFFIX\n if os.path.exists(p):\n ...
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/mirteFile.py
_parse_mirteFile
python
def _parse_mirteFile(path, logger=None): l = logging.getLogger('_parse_mirteFile') if logger is None else logger cache_path = os.path.join(os.path.dirname(path), CACHE_FILENAME_TEMPLATE % os.path.basename(path)) if (os.path.exists(cache_path) and os.path.getmtime(ca...
Open and parses the mirteFile at <path>.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/mirteFile.py#L202-L221
null
from sarah.lazy import lazy import os import sys import copy import errno import os.path import msgpack import logging from itertools import chain import six from sarah.order import sort_by_successors, dual_cover, restricted_cover from mirte.core import ModuleDefinition, DepDefinition, VSettingDefinition @lazy d...
bwesterb/mirte
src/core.py
Manager._get_all
python
def _get_all(self, _type): if _type not in self.modules: raise ValueError("No such module, %s" % _type) if not self.insts_implementing.get(_type, None): raise ValueError("No instance implementing %s" % _type) return self.insts_implementing[_type]
Gets all instances implementing type <_type>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L69-L75
null
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
bwesterb/mirte
src/core.py
Manager._get_a
python
def _get_a(self, _type): tmp = self._get_all(_type) ret = pick(tmp) if len(tmp) != 1: self.l.warn(("get_a: %s all implement %s; " + "picking %s") % (tmp, _type, ret)) return ret
Gets an instance implementing type <_type>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L81-L88
[ "def _get_all(self, _type):\n \"\"\" Gets all instances implementing type <_type> \"\"\"\n if _type not in self.modules:\n raise ValueError(\"No such module, %s\" % _type)\n if not self.insts_implementing.get(_type, None):\n raise ValueError(\"No instance implementing %s\" % _type)\n retur...
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
bwesterb/mirte
src/core.py
Manager.got_a
python
def got_a(self, _type): if _type not in self.modules: raise ValueError("No such module, %s" % _type) return (_type in self.insts_implementing and self.insts_implementing[_type])
Returns whether there is an instance implementing <_type>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L90-L96
null
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
bwesterb/mirte
src/core.py
Manager._get_or_create_a
python
def _get_or_create_a(self, _type): self.l.debug("get_or_create_a: %s" % _type) stack = [Manager.GoCa_Plan(self, {_type: ()})] while stack: p = stack.pop() if p.finished: p.execute() return p.get_a(_type) for c in p.branches(): ...
Gets or creates an instance of type <_type>
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L201-L212
null
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
bwesterb/mirte
src/core.py
Manager.update_instance
python
def update_instance(self, name, settings): if name not in self.insts: raise ValueError("There's no instance named %s" % name) if 'module' in settings: raise ValueError(("Can't change module of existing instan" + "ce %s") % name) self.l.info('...
Updates settings of instance <name> with the dictionary <settings>.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L235-L245
[ "def change_setting(self, instance_name, key, raw_value):\n \"\"\" Change the settings <key> to <raw_value> of an instance\n named <instance_name>. <raw_value> should be a string and\n is properly converted. \"\"\"\n ii = self.insts[instance_name]\n mo = self.modules[ii.module]\n if key i...
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
bwesterb/mirte
src/core.py
Manager.create_instance
python
def create_instance(self, name, moduleName, settings): if name in self.insts: raise ValueError("There's already an instance named %s" % name) if moduleName not in self.modules: raise ValueError("There's no module %s" % moduleName) md = self.mo...
Creates an instance of <moduleName> at <name> with <settings>.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L247-L278
[ "def _get_or_create_a(self, _type):\n \"\"\" Gets or creates an instance of type <_type> \"\"\"\n self.l.debug(\"get_or_create_a: %s\" % _type)\n stack = [Manager.GoCa_Plan(self, {_type: ()})]\n while stack:\n p = stack.pop()\n if p.finished:\n p.execute()\n return p....
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
bwesterb/mirte
src/core.py
Manager.change_setting
python
def change_setting(self, instance_name, key, raw_value): ii = self.insts[instance_name] mo = self.modules[ii.module] if key in mo.deps: if raw_value not in self.insts: raise ValueError("No such instance %s" % raw_value) vii = self.insts[raw_value] ...
Change the settings <key> to <raw_value> of an instance named <instance_name>. <raw_value> should be a string and is properly converted.
train
https://github.com/bwesterb/mirte/blob/c58db8c993cd15ffdc64b52703cd466213913200/src/core.py#L333-L358
null
class Manager(Module): def __init__(self, logger=None): if logger is None: logger = logging.getLogger(object.__repr__(self)) super(Manager, self).__init__({}, logger) self.running = False self.running_event = threading.Event() self.modules = dict() self.t...
mrallen1/pygett
pygett/request.py
BaseRequest.get
python
def get(self, endpoint, *args, **kwargs): endpoint = self.base_url + endpoint return self._make_request(endpoint, type='GET')
**get** Make a GET call to a remote endpoint Input: * An endpoint relative to the ``base_url`` Output: * A :py:mod:`pygett.request.GettResponse` object
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/request.py#L45-L58
[ "def _make_request(self, endpoint, type='GET'):\n pass\n", "def _make_request(self, endpoint, **kwargs):\n status_code = None\n response = None\n\n self.endpoint = endpoint\n self.__dict__.update(kwargs)\n\n if self.type == \"GET\":\n response = requests.get(self.endpoint)\n elif self....
class BaseRequest(object): """ Base request class """ def __init__(self, *args, **kwargs): self.base_url = "https://open.ge.tt/1" def _make_request(self, endpoint, type='GET'): pass def post(self, endpoint, d, *args, **kwargs): """ **post** Make a POST...
mrallen1/pygett
pygett/request.py
BaseRequest.post
python
def post(self, endpoint, d, *args, **kwargs): endpoint = self.base_url + endpoint if not isinstance(d, str): d = json.dumps(d) return self._make_request(endpoint, type='POST', data=d)
**post** Make a POST call to a remote endpoint Input: * An endpoint relative to the ``base_url`` * POST data **NOTE**: Passed POST data will be automatically serialized to a JSON string if it's not already a string Output: * A :py:mod:`pyge...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/request.py#L60-L80
[ "def _make_request(self, endpoint, type='GET'):\n pass\n", "def _make_request(self, endpoint, **kwargs):\n status_code = None\n response = None\n\n self.endpoint = endpoint\n self.__dict__.update(kwargs)\n\n if self.type == \"GET\":\n response = requests.get(self.endpoint)\n elif self....
class BaseRequest(object): """ Base request class """ def __init__(self, *args, **kwargs): self.base_url = "https://open.ge.tt/1" def _make_request(self, endpoint, type='GET'): pass def get(self, endpoint, *args, **kwargs): """ **get** Make a GET call t...
mrallen1/pygett
pygett/request.py
BaseRequest.put
python
def put(self, endpoint, d, *args, **kwargs): return self._make_request(endpoint, type='PUT', data=d)
**put** Make a PUT call to a remove endpoint Input: * An absolute endpoint * A data stream Output: * A :py:mod:`pygett.request.GettResponse` object
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/request.py#L82-L96
[ "def _make_request(self, endpoint, type='GET'):\n pass\n", "def _make_request(self, endpoint, **kwargs):\n status_code = None\n response = None\n\n self.endpoint = endpoint\n self.__dict__.update(kwargs)\n\n if self.type == \"GET\":\n response = requests.get(self.endpoint)\n elif self....
class BaseRequest(object): """ Base request class """ def __init__(self, *args, **kwargs): self.base_url = "https://open.ge.tt/1" def _make_request(self, endpoint, type='GET'): pass def get(self, endpoint, *args, **kwargs): """ **get** Make a GET call t...
mrallen1/pygett
pygett/files.py
GettFile.contents
python
def contents(self): response = GettRequest().get("/files/%s/%s/blob" % (self.sharename, self.fileid)) return response.response
This method downloads the contents of the file represented by a `GettFile` object's metadata. Input: * None Output: * A byte stream **NOTE**: You are responsible for handling any encoding/decoding which may be necessary. Example:: file = client.ge...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L48-L67
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class GettFile(object): """ Encapsulate a file in the Gett service. **Attributes** This object has the following attributes: - ``fileid`` - A file id as assigned by the Gett service - ``sharename`` - The sharename in which this file is contained - ``downloads`` - The number of ...
mrallen1/pygett
pygett/files.py
GettFile.thumbnail
python
def thumbnail(self): response = GettRequest().get("/files/%s/%s/blob/thumb" % (self.sharename, self.fileid)) return response.response
This method returns a thumbnail representation of the file if the data is a supported graphics format. Input: * None Output: * A byte stream representing a thumbnail of a support graphics file Example:: file = client.get_file("4ddfds", 0) open(...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L69-L86
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class GettFile(object): """ Encapsulate a file in the Gett service. **Attributes** This object has the following attributes: - ``fileid`` - A file id as assigned by the Gett service - ``sharename`` - The sharename in which this file is contained - ``downloads`` - The number of ...
mrallen1/pygett
pygett/files.py
GettFile.upload_url
python
def upload_url(self): if self.put_upload_url: return self.put_upload_url else: response = GettRequest().get("/files/%s/%s/upload?accesstoken=%s" % (self.sharename, self.fileid, self.user.access_token())) if response.http_status == 200: return response....
This method generates URLs which allow overwriting a file's content with new content. The output is suitable for use in the ``send_data()`` method below. Input: * None Output: * A URL (string) Example:: file = client.get_file("4ddfds", 0) ...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L108-L130
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class GettFile(object): """ Encapsulate a file in the Gett service. **Attributes** This object has the following attributes: - ``fileid`` - A file id as assigned by the Gett service - ``sharename`` - The sharename in which this file is contained - ``downloads`` - The number of ...
mrallen1/pygett
pygett/files.py
GettFile.send_data
python
def send_data(self, **kwargs): put_url = None if 'put_url' in kwargs: put_url = kwargs['put_url'] else: put_url = self.put_upload_url if 'data' not in kwargs: raise AttributeError("'data' parameter is required") if not put_url: ra...
This method transmits data to the Gett service. Input: * ``put_url`` A PUT url to use when transmitting the data (required) * ``data`` A byte stream (required) Output: * ``True`` Example:: if file.send_data(put_url=file.upload_url, data=open("e...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/files.py#L155-L189
[ "def put(self, endpoint, d, *args, **kwargs):\n \"\"\"\n **put**\n\n Make a PUT call to a remove endpoint\n\n Input:\n * An absolute endpoint\n * A data stream\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n\n return self._make_request(endpoint, ty...
class GettFile(object): """ Encapsulate a file in the Gett service. **Attributes** This object has the following attributes: - ``fileid`` - A file id as assigned by the Gett service - ``sharename`` - The sharename in which this file is contained - ``downloads`` - The number of ...
mrallen1/pygett
pygett/shares.py
GettShare.update
python
def update(self, **kwargs): if 'title' in kwargs: params = {"title": kwargs['title']} else: params = {"title": None} response = GettRequest().post("/shares/%s/update?accesstoken=%s" % (self.sharename, self.user.access_token()), params) if response.http_status ==...
Add, remove or modify a share's title. Input: * ``title`` The share title, if any (optional) **NOTE**: Passing ``None`` or calling this method with an empty argument list will remove the share's title. Output: * None Example:: share = client.get_s...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/shares.py#L38-L64
[ "def post(self, endpoint, d, *args, **kwargs):\n \"\"\"\n **post**\n\n Make a POST call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n * POST data\n\n **NOTE**: Passed POST data will be automatically serialized to a JSON string\n if it's not already a ...
class GettShare(object): """ Encapsulate a share in the Gett service. **Attributes** - ``sharename`` The sharename - ``title`` The share title (if any) - ``created`` Unix epoch seconds when the share was created - ``files`` A list of all files contained in a share as :py:mod...
mrallen1/pygett
pygett/shares.py
GettShare.destroy
python
def destroy(self): response = GettRequest().post("/shares/%s/destroy?accesstoken=%s" % (self.sharename, self.user.access_token()), None) if response.http_status == 200: return True
This method removes this share and all of its associated files. There is no way to recover a share or its contents once this method has been called. Input: * None Output: * ``True`` Example:: client.get_share("4ddfds").destroy()
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/shares.py#L66-L84
[ "def post(self, endpoint, d, *args, **kwargs):\n \"\"\"\n **post**\n\n Make a POST call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n * POST data\n\n **NOTE**: Passed POST data will be automatically serialized to a JSON string\n if it's not already a ...
class GettShare(object): """ Encapsulate a share in the Gett service. **Attributes** - ``sharename`` The sharename - ``title`` The share title (if any) - ``created`` Unix epoch seconds when the share was created - ``files`` A list of all files contained in a share as :py:mod...
mrallen1/pygett
pygett/shares.py
GettShare.refresh
python
def refresh(self): response = GettRequest().get("/shares/%s" % self.sharename) if response.http_status == 200: self.__init__(self.user, **response.response)
This method refreshes the object with current metadata from the Gett service. Input: * None Output: * None Example:: share = client.get_share("4ddfds") print share.files[0].filename # prints 'foobar' if share.files[0].destroy()...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/shares.py#L86-L107
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class GettShare(object): """ Encapsulate a share in the Gett service. **Attributes** - ``sharename`` The sharename - ``title`` The share title (if any) - ``created`` Unix epoch seconds when the share was created - ``files`` A list of all files contained in a share as :py:mod...
mrallen1/pygett
pygett/base.py
Gett.get_shares
python
def get_shares(self, **kwargs): response = self._get_shares(**kwargs) rv = dict() if response.http_status == 200: for share in response.response: rv[share['sharename']] = GettShare(self.user, **share) return rv
Gets *all* shares. Input: * ``skip`` the number of shares to skip (optional) * ``limit`` the maximum number of shares to return (optional) Output: * a dict where keys are sharenames and the values are corresponding :py:mod:`pygett.shares.GettShare` objects ...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L63-L87
[ "def _get_shares(self, **kwargs):\n endpoint = \"/shares?accesstoken=%s\" % self.user.access_token()\n if 'limit' in kwargs and isinstance(kwargs['limit'], int) and kwargs['limit'] > 0:\n endpoint = endpoint + \"&limit=%d\" % kwargs['limit']\n if 'skip' in kwargs and isinstance(kwargs['skip'], int) ...
class Gett(object): """ Base client object Requires the following keyword arguments: - ``apikey`` - The API key assigned to an application by Gett - ``email`` - The email address linked to the API key - ``password`` - The password linked to the API key **Attribute** - `...
mrallen1/pygett
pygett/base.py
Gett.get_shares_list
python
def get_shares_list(self, **kwargs): response = self._get_shares(**kwargs) rv = list() if response.http_status == 200: for share in response.response: rv.append(GettShare(self.user, **share)) return rv
Gets *all* shares. Input: * ``skip`` the number of shares to skip (optional) * ``limit`` the maximum number of shares to return (optional) Output: * a list of :py:mod:`pygett.shares.GettShare` objects Example:: shares_list = client.get_shares_l...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L89-L113
[ "def _get_shares(self, **kwargs):\n endpoint = \"/shares?accesstoken=%s\" % self.user.access_token()\n if 'limit' in kwargs and isinstance(kwargs['limit'], int) and kwargs['limit'] > 0:\n endpoint = endpoint + \"&limit=%d\" % kwargs['limit']\n if 'skip' in kwargs and isinstance(kwargs['skip'], int) ...
class Gett(object): """ Base client object Requires the following keyword arguments: - ``apikey`` - The API key assigned to an application by Gett - ``email`` - The email address linked to the API key - ``password`` - The password linked to the API key **Attribute** - `...
mrallen1/pygett
pygett/base.py
Gett.get_share
python
def get_share(self, sharename): response = GettRequest().get("/shares/%s" % sharename) if response.http_status == 200: return GettShare(self.user, **response.response)
Get a specific share. Does not require authentication. Input: * A sharename Output: * A :py:mod:`pygett.shares.GettShare` object Example:: share = client.get_share("4ddfds")
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L115-L133
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class Gett(object): """ Base client object Requires the following keyword arguments: - ``apikey`` - The API key assigned to an application by Gett - ``email`` - The email address linked to the API key - ``password`` - The password linked to the API key **Attribute** - `...
mrallen1/pygett
pygett/base.py
Gett.get_file
python
def get_file(self, sharename, fileid): if not isinstance(fileid, int): raise TypeError("'fileid' must be an integer") response = GettRequest().get("/files/%s/%d" % (sharename, fileid)) if response.http_status == 200: return GettFile(self.user, **response.response)
Get a specific file. Does not require authentication. Input: * A sharename * A fileid - must be an integer Output: * A :py:mod:`pygett.files.GettFile` object Example:: file = client.get_file("4ddfds", 0)
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L135-L157
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class Gett(object): """ Base client object Requires the following keyword arguments: - ``apikey`` - The API key assigned to an application by Gett - ``email`` - The email address linked to the API key - ``password`` - The password linked to the API key **Attribute** - `...
mrallen1/pygett
pygett/base.py
Gett.create_share
python
def create_share(self, **kwargs): params = None if 'title' in kwargs: params = {"title": kwargs['title']} response = GettRequest().post(("/shares/create?accesstoken=%s" % self.user.access_token()), params) if response.http_status == 200: return GettShare(self.u...
Create a new share. Takes a keyword argument. Input: * ``title`` optional share title (optional) Output: * A :py:mod:`pygett.shares.GettShare` object Example:: new_share = client.create_share( title="Example Title" )
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L159-L181
[ "def post(self, endpoint, d, *args, **kwargs):\n \"\"\"\n **post**\n\n Make a POST call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n * POST data\n\n **NOTE**: Passed POST data will be automatically serialized to a JSON string\n if it's not already a ...
class Gett(object): """ Base client object Requires the following keyword arguments: - ``apikey`` - The API key assigned to an application by Gett - ``email`` - The email address linked to the API key - ``password`` - The password linked to the API key **Attribute** - `...
mrallen1/pygett
pygett/base.py
Gett.upload_file
python
def upload_file(self, **kwargs): params = None if 'filename' not in kwargs: raise AttributeError("Parameter 'filename' must be given") else: params = { "filename": kwargs['filename'] } if 'data' not in kwargs: raise Attribu...
Upload a file to the Gett service. Takes keyword arguments. Input: * ``filename`` the filename to use in the Gett service (required) * ``data`` the file contents to store in the Gett service (required) - must be a string * ``sharename`` the name of the share in which to stor...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L183-L230
[ "def create_share(self, **kwargs):\n \"\"\"\n Create a new share. Takes a keyword argument.\n\n Input:\n * ``title`` optional share title (optional)\n\n Output:\n * A :py:mod:`pygett.shares.GettShare` object\n\n Example::\n\n new_share = client.create_share( title=\"Example Title...
class Gett(object): """ Base client object Requires the following keyword arguments: - ``apikey`` - The API key assigned to an application by Gett - ``email`` - The email address linked to the API key - ``password`` - The password linked to the API key **Attribute** - `...
mrallen1/pygett
pygett/user.py
GettUser.login
python
def login(self, **params): if not params: params = { "apikey": self.apikey, "email": self.email, "password": self.password } response = GettRequest().post("/users/login", params) if response.http_status == 200: ...
**login** Use the current credentials to get a valid Gett access token. Input: * A dict of parameters to use for the login attempt (optional) Output: * ``True`` Example:: if client.user.login(): print "You have %s bytes of storage ...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/user.py#L49-L85
[ "def post(self, endpoint, d, *args, **kwargs):\n \"\"\"\n **post**\n\n Make a POST call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n * POST data\n\n **NOTE**: Passed POST data will be automatically serialized to a JSON string\n if it's not already a ...
class GettUser(object): """ Encapsulates Gett user functionality **Attributes** - ``apikey`` The API key assigned by Gett for an application - ``email`` The email linked to the API key - ``password`` The password linked to the API key After a successful login the following attr...
mrallen1/pygett
pygett/user.py
GettUser.access_token
python
def access_token(self): if not self._access_token: self.login() if time() > (self.access_token_expires - self.access_token_grace): self.login({"refreshtoken": self.refresh_token}) return self._access_token
**access_token** Returns a valid access token. If the user is not currently logged in, attempts to do so. If the current time exceeds the grace period, attempts to retrieve a new access token. Input: * None Output: * A valid access token Example:: ...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/user.py#L87-L110
[ "def login(self, **params):\n \"\"\"\n **login**\n\n Use the current credentials to get a valid Gett access token.\n\n Input:\n * A dict of parameters to use for the login attempt (optional)\n\n Output:\n * ``True``\n\n Example::\n\n if client.user.login():\n print ...
class GettUser(object): """ Encapsulates Gett user functionality **Attributes** - ``apikey`` The API key assigned by Gett for an application - ``email`` The email linked to the API key - ``password`` The password linked to the API key After a successful login the following attr...
mrallen1/pygett
pygett/user.py
GettUser.refresh
python
def refresh(self): response = GettRequest().get("/users/me?accesstoken=%s" % self.access_token()) if response.http_status == 200: self.userid = response.response['userid'] self.fullname = response.response['fullname'] self.storage_used = response.response['storage'][...
**refresh** Refresh this user object with data from the Gett service Input: * None Output: * ``True`` Example:: if client.user.refresh(): print "User data refreshed!" print "You have %s bytes of storage remaining." ...
train
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/user.py#L112-L139
[ "def get(self, endpoint, *args, **kwargs):\n \"\"\"\n **get**\n\n Make a GET call to a remote endpoint\n\n Input:\n * An endpoint relative to the ``base_url``\n\n Output:\n * A :py:mod:`pygett.request.GettResponse` object\n \"\"\"\n endpoint = self.base_url + endpoint\n return ...
class GettUser(object): """ Encapsulates Gett user functionality **Attributes** - ``apikey`` The API key assigned by Gett for an application - ``email`` The email linked to the API key - ``password`` The password linked to the API key After a successful login the following attr...
hkff/FodtlMon
fodtlmon/fotl/fotl.py
IPredicate.eval
python
def eval(self, valuation=None, trace=None): args2 = [] for a in self.args: if isinstance(a, Function) or isinstance(a, IPredicate): args2.append(Constant(a.eval(valuation=valuation, trace=trace))) elif isinstance(a, Variable): found = False ...
This method should be always called by subclasses :param valuation :param trace :return: Arguments evaluation
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/fotl/fotl.py#L154-L178
null
class IPredicate(Exp, metaclass=MetaBase): """ Interpreted Predicate """ def __init__(self, *args): # IMPORTANT : Test the size of args, because of subclass super call self.args = list(args[0] if len(args) == 1 else args) def __str__(self): return "%s(%s)" % (self.__class__....
hkff/FodtlMon
fodtlmon/fotl/fotl.py
Function.eval
python
def eval(self, valuation=None, trace=None): return super().eval(valuation=valuation, trace=trace)
This method should be override to return some value :param valuation :param trace :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/fotl/fotl.py#L201-L208
[ "def eval(self, valuation=None, trace=None):\n \"\"\"\n This method should be always called by subclasses\n :param valuation\n :param trace\n :return: Arguments evaluation\n \"\"\"\n args2 = []\n for a in self.args:\n if isinstance(a, Function) or isinstance(a, IPredicate):\n ...
class Function(IPredicate): """ Function """ @staticmethod def get_class_from_name(klass): return next(filter(lambda x: issubclass(x, Function) and x.__name__ == klass, MetaBase.classes), None)
hkff/FodtlMon
fodtlmon/tools/color.py
_pad_input
python
def _pad_input(incoming): incoming_expanded = incoming.replace('{', '{{').replace('}', '}}') for key in _BASE_CODES: before, after = '{{%s}}' % key, '{%s}' % key if before in incoming_expanded: incoming_expanded = incoming_expanded.replace(before, after) return incoming_expanded
Avoid IndexError and KeyError by ignoring un-related fields. Example: '{0}{autored}' becomes '{{0}}{autored}'. Positional arguments: incoming -- the input unicode value. Returns: Padded unicode value.
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L218-L234
null
"""Colorful worry-free console applications for Linux, Mac OS X, and Windows. Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called. Gives you expected and sane results from methods like len() and .capitalize(). https://github.com/Robpol86/colorclass htt...
hkff/FodtlMon
fodtlmon/tools/color.py
_parse_input
python
def _parse_input(incoming): codes = dict((k, v) for k, v in _AutoCodes().items() if '{%s}' % k in incoming) color_codes = dict((k, '' if _AutoCodes.DISABLE_COLORS else '\033[{0}m'.format(v)) for k, v in codes.items()) incoming_padded = _pad_input(incoming) output_colors = incoming_padded.format(**color_...
Performs the actual conversion of tags to ANSI escaped codes. Provides a version of the input without any colors for len() and other methods. Positional arguments: incoming -- the input unicode value. Returns: 2-item tuple. First item is the parsed output. Second item is a version of the input wi...
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L237-L267
[ "def _pad_input(incoming):\n \"\"\"Avoid IndexError and KeyError by ignoring un-related fields.\n\n Example: '{0}{autored}' becomes '{{0}}{autored}'.\n\n Positional arguments:\n incoming -- the input unicode value.\n\n Returns:\n Padded unicode value.\n \"\"\"\n incoming_expanded = incoming....
"""Colorful worry-free console applications for Linux, Mac OS X, and Windows. Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called. Gives you expected and sane results from methods like len() and .capitalize(). https://github.com/Robpol86/colorclass htt...
hkff/FodtlMon
fodtlmon/tools/color.py
list_tags
python
def list_tags(): codes = _AutoCodes() grouped = set([(k, '/{0}'.format(k), codes[k], codes['/{0}'.format(k)]) for k in codes if not k.startswith('/')]) # Add half-tags like /all. found = [c for r in grouped for c in r[:2]] missing = set([('', r[0], None, r[1]) if r[0].startswith('/') else (r[0], ''...
Lists the available tags. Returns: Tuple of tuples. Child tuples are four items: ('opening tag', 'closing tag', main ansi value, closing ansi value).
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L287-L312
null
"""Colorful worry-free console applications for Linux, Mac OS X, and Windows. Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called. Gives you expected and sane results from methods like len() and .capitalize(). https://github.com/Robpol86/colorclass htt...
hkff/FodtlMon
fodtlmon/tools/color.py
Windows.disable
python
def disable(): if os.name != 'nt' or not Windows.is_enabled(): return False getattr(sys.stderr, '_reset_colors', lambda: False)() getattr(sys.stdout, '_reset_colors', lambda: False)() if isinstance(sys.stderr, _WindowsStream): sys.stderr = getattr(sys.stderr, 'o...
Restore sys.stderr and sys.stdout to their original objects. Resets colors to their original values.
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L483-L496
null
class Windows(object): """Enable and disable Windows support for ANSI color character codes. Call static method Windows.enable() to enable color support for the remainder of the process' lifetime. This class is also a context manager. You can do this: with Windows(): print(Color('{autored}Test...
hkff/FodtlMon
fodtlmon/tools/color.py
Windows.enable
python
def enable(auto_colors=False, reset_atexit=False): if os.name != 'nt': return False # Overwrite stream references. if not isinstance(sys.stderr, _WindowsStream): sys.stderr.flush() sys.stderr = _WindowsStream(stderr=True) if not isinstance(sys.stdout,...
Enables color text with print() or sys.stdout.write() (stderr too). Keyword arguments: auto_colors -- automatically selects dark or light colors based on current terminal's background color. Only works with {autored} and related tags. reset_atexit -- resets original colors upon Pyth...
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L504-L535
null
class Windows(object): """Enable and disable Windows support for ANSI color character codes. Call static method Windows.enable() to enable color support for the remainder of the process' lifetime. This class is also a context manager. You can do this: with Windows(): print(Color('{autored}Test...
hkff/FodtlMon
fodtlmon/tools/color.py
_WindowsStream._get_colors
python
def _get_colors(self): try: csbi = _WindowsCSBI.get_info(self.win32_stream_handle) return csbi['fg_color'], csbi['bg_color'] except IOError: return 7, 0
Returns a tuple of two integers representing current colors: (foreground, background).
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L693-L699
[ "def get_info(handle):\n \"\"\"Get information about this current console window (for Microsoft Windows only).\n\n Raises IOError if attempt to get information fails (if there is no console window).\n\n Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.\n\n ...
class _WindowsStream(object): """Replacement stream (overwrites sys.stdout and sys.stderr). When writing or printing, ANSI codes are converted. ANSI (Linux/Unix) color codes are converted into win32 system calls, changing the next character's color before printing it. Resources referenced: https://...
hkff/FodtlMon
fodtlmon/tools/color.py
_WindowsStream._set_color
python
def _set_color(self, color_code): # Get current color code. current_fg, current_bg = self._get_colors() # Handle special negative codes. Also determine the final color code. if color_code == -39: final_color_code = self.default_fg | current_bg # Reset the foreground only. ...
Changes the foreground and background colors for subsequently printed characters. Since setting a color requires including both foreground and background codes (merged), setting just the foreground color resets the background color to black, and vice versa. This function first gets the current...
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/tools/color.py#L705-L738
null
class _WindowsStream(object): """Replacement stream (overwrites sys.stdout and sys.stderr). When writing or printing, ANSI codes are converted. ANSI (Linux/Unix) color codes are converted into win32 system calls, changing the next character's color before printing it. Resources referenced: https://...
hkff/FodtlMon
fodtlmon/dtl/systemd.py
Actor.run
python
def run(self, once=True): print("\n- Actor %s " % self.name) for m in self.submons: res = m.monitor(once=once) print(" | Submonitor %s : %s" % (self.name, res)) # print("%s %s %s %s lst %s" % (self.name, m.fid, m.last, m.counter, m.last)) self.get_kv().u...
Run main monitor and all sub monitors :param : once :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L93-L106
[ "def get_kv(self):\n return self.monitor.get_kv()\n" ]
class Actor: """ Actor class """ class Event: """ Internal actor event in : actor-> event coming from actor out : ->actor sending event to actor """ class EventType(Enum): IN = "in", OUT = "out" EMPTY = "EMPTY" ...
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.add_actors
python
def add_actors(self, actor): if isinstance(actor, list): self.actors.extend(actor) elif isinstance(actor, Actor): self.actors.append(actor) return self
Add an actor / actor list to the system's actors :param actor: Actor | list<Actor> :return: self
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L137-L147
null
class System: """ Distributed system representation """ def __init__(self, actors=None, kv_implementation=KVector): """ Init the system coms is a dictionary that contains :param actors: actors list :param kv_implementation: the Knowledge vector implementation (IKV...
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.get_actor
python
def get_actor(self, name): return next((x for x in self.actors if x.name == name), None)
Get an actor by name :param name: str :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L149-L155
null
class System: """ Distributed system representation """ def __init__(self, actors=None, kv_implementation=KVector): """ Init the system coms is a dictionary that contains :param actors: actors list :param kv_implementation: the Knowledge vector implementation (IKV...
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.generate_monitors
python
def generate_monitors(self): submons = [] for a in self.actors: # Get all remote formula remotes = a.formula.walk(filter_type=At) # Compute formula hash for f in remotes: f.compute_hash(sid=a.name) # Create the global monitor f...
Generate monitors for each actor in the system :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L157-L191
[ "def get_actor(self, name):\n \"\"\"\n Get an actor by name\n :param name: str\n :return:\n \"\"\"\n return next((x for x in self.actors if x.name == name), None)\n" ]
class System: """ Distributed system representation """ def __init__(self, actors=None, kv_implementation=KVector): """ Init the system coms is a dictionary that contains :param actors: actors list :param kv_implementation: the Knowledge vector implementation (IKV...
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.run
python
def run(self, once=True): print(Color("{autored}\n====== System round %s ======{/red}" % self.turn)) print(Color("{autoblue}== Updating actors events...{/blue}")) # Handling OUT messages for a in self.actors: if self.turn < len(a.events): es = a.events[self.tu...
Run the system :param once :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L193-L234
null
class System: """ Distributed system representation """ def __init__(self, actors=None, kv_implementation=KVector): """ Init the system coms is a dictionary that contains :param actors: actors list :param kv_implementation: the Knowledge vector implementation (IKV...
hkff/FodtlMon
fodtlmon/dtl/systemd.py
System.parseJSON
python
def parseJSON(js): decoded = json.JSONDecoder().decode(js) actors = decoded.get("actors") if actors is None: raise Exception("No actors found in the system !") s = System() for a in actors: # Getting actor info a_name = a.get("name") ...
{ kv_type : "", type : "", actors : <Actors list> [ { actorName : <String>, formula: <String>, events: ["->b", "b->"], trace: [], speed: 1,...
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/dtl/systemd.py#L246-L295
[ "def add_actors(self, actor):\n \"\"\"\n Add an actor / actor list to the system's actors\n :param actor: Actor | list<Actor>\n :return: self\n \"\"\"\n if isinstance(actor, list):\n self.actors.extend(actor)\n elif isinstance(actor, Actor):\n self.actors.append(actor)\n return...
class System: """ Distributed system representation """ def __init__(self, actors=None, kv_implementation=KVector): """ Init the system coms is a dictionary that contains :param actors: actors list :param kv_implementation: the Knowledge vector implementation (IKV...
hkff/FodtlMon
fodtlmon/ltl/ltl.py
B3
python
def B3(formula): if isinstance(formula, true) or formula is True or formula == Boolean3.Top.name or formula == Boolean3.Top.value: return Boolean3.Top if isinstance(formula, false) or formula is False or formula == Boolean3.Bottom.name or formula == Boolean3.Bottom.value: return Boolean3.Bottom ...
Rewrite formula eval result into Boolean3 :param formula: :return: Boolean3
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/ltl/ltl.py#L626-L637
null
""" ltl Copyright (C) 2015 Walid Benghabrit This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the...
hkff/FodtlMon
fodtlmon/ltl/ltl.py
Formula.walk
python
def walk(self, filters: str=None, filter_type: type=None, pprint=False, depth=-1): children = self.children() if children is None: children = [] res = [] if depth == 0: return res elif depth != -1: depth -= 1 for child in children: ...
Iterate tree in pre-order wide-first search order :param filters: filter by python expression :param filter_type: Filter by class :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/ltl/ltl.py#L73-L113
[ "def children(self):\n return []\n" ]
class Formula: """ Abstract formula """ symbol = "" tspass = "" ltlfo = "" code = "" def toTSPASS(self): return str(self) def toLTLFO(self): return str(self) def prefix_print(self): return str(self) def toCODE(self): return self.__class__._...
hkff/FodtlMon
fodtlmon/ltl/ltlmon.py
ltlfo2mon
python
def ltlfo2mon(formula:Formula, trace:Trace): fl = formula.toLTLFO() if isinstance(formula, Formula) else formula tr = trace.toLTLFO() if isinstance(trace, Trace) else trace cmd = "echo \"%s\" | java -jar fodtlmon/tools/ltlfo2mon.jar -p \"%s\"" % (tr, fl) p = os.popen(cmd) res = p.readline()[:-1] ...
Run ltlfo2mon :param formula: Formula | ltlfo string formula :param trace: Trace | ltlfo string trace :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/ltl/ltlmon.py#L133-L146
null
""" ltlmon LTL monitor Copyright (C) 2015 Walid Benghabrit This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is dis...
hkff/FodtlMon
fodtlmon/mon.py
main
python
def main(argv): input_file = "" output_file = "" monitor = None formula = None trace = None iformula = None itrace = None isys = None online = False fuzzer = False l2m = False debug = False rounds = 1 server_port = 8080 webservice = False help_str_extende...
Main mon :param argv: console arguments :return:
train
https://github.com/hkff/FodtlMon/blob/0c9015a1a1f0a4a64d52945c86b45441d5871c56/fodtlmon/mon.py#L35-L179
[ "def ltlfo2mon(formula:Formula, trace:Trace):\n \"\"\"\n Run ltlfo2mon\n :param formula: Formula | ltlfo string formula\n :param trace: Trace | ltlfo string trace\n :return:\n \"\"\"\n fl = formula.toLTLFO() if isinstance(formula, Formula) else formula\n tr = trace.toLTLFO() if isinstance(tr...
#!/usr/bin/python3.4 """ fodtlmon version 1.0 Copyright (C) 2015 Walid Benghabrit This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later versio...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.add_result
python
def add_result(self, _type, test, exc_info=None): if exc_info is not None: exc_info = FrozenExcInfo(exc_info) test.time_taken = time.time() - self.start_time test._outcome = None self.result_queue.put((_type, test, exc_info))
Adds the given result to the list :param _type: type of the state of the test (TestState.failure, TestState.error, ...) :param test: the test :param exc_info: additional execution information
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L58-L70
null
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.addSuccess
python
def addSuccess(self, test: unittest.case.TestCase) -> None: # noinspection PyTypeChecker self.add_result(TestState.success, test)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L72-L79
[ "def add_result(self, _type, test, exc_info=None):\n \"\"\"\n Adds the given result to the list\n\n :param _type: type of the state of the test (TestState.failure, TestState.error, ...)\n :param test: the test\n :param exc_info: additional execution information\n \"\"\"\n if exc_info is not Non...
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.addFailure
python
def addFailure(self, test: unittest.case.TestCase, exc_info: tuple) -> None: # noinspection PyTypeChecker self.add_result(TestState.failure, test, exc_info)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save :param exc_info: tuple of the form (Exception class, Exception instance, traceback)
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L81-L89
[ "def add_result(self, _type, test, exc_info=None):\n \"\"\"\n Adds the given result to the list\n\n :param _type: type of the state of the test (TestState.failure, TestState.error, ...)\n :param test: the test\n :param exc_info: additional execution information\n \"\"\"\n if exc_info is not Non...
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.addError
python
def addError(self, test: unittest.case.TestCase, exc_info: tuple) -> None: # noinspection PyTypeChecker self.add_result(TestState.error, test, exc_info)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save :param exc_info: tuple of the form (Exception class, Exception instance, traceback)
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L91-L99
[ "def add_result(self, _type, test, exc_info=None):\n \"\"\"\n Adds the given result to the list\n\n :param _type: type of the state of the test (TestState.failure, TestState.error, ...)\n :param test: the test\n :param exc_info: additional execution information\n \"\"\"\n if exc_info is not Non...
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.addExpectedFailure
python
def addExpectedFailure(self, test: unittest.case.TestCase, err: tuple) -> None: # noinspection PyTypeChecker self.add_result(TestState.expected_failure, test, err)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save :param err: tuple of the form (Exception class, Exception instance, traceback)
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L101-L109
[ "def add_result(self, _type, test, exc_info=None):\n \"\"\"\n Adds the given result to the list\n\n :param _type: type of the state of the test (TestState.failure, TestState.error, ...)\n :param test: the test\n :param exc_info: additional execution information\n \"\"\"\n if exc_info is not Non...
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.addUnexpectedSuccess
python
def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: # noinspection PyTypeChecker self.add_result(TestState.unexpected_success, test)
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L111-L118
[ "def add_result(self, _type, test, exc_info=None):\n \"\"\"\n Adds the given result to the list\n\n :param _type: type of the state of the test (TestState.failure, TestState.error, ...)\n :param test: the test\n :param exc_info: additional execution information\n \"\"\"\n if exc_info is not Non...
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
InterProcessResult.addSkip
python
def addSkip(self, test: unittest.case.TestCase, reason: str): test.time_taken = time.time() - self.start_time test._outcome = None self.result_queue.put((TestState.skipped, test, reason))
Transforms the test in a serializable version of it and sends it to a queue for further analysis :param test: the test to save :param reason: the reason why the test was skipped
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L120-L129
null
class InterProcessResult(unittest.result.TestResult): """ A TestResult implementation to put results in a queue, for another thread to consume """ def __init__(self, result_queue: queue.Queue): super().__init__() self.result_queue = result_queue self.start_time = self.stop_time =...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.addError
python
def addError(self, test, err): super().addError(test, err) self.test_info(test) self._call_test_results('addError', test, err)
registers a test as error :param test: test to register :param err: error the test gave
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L211-L220
[ "def _call_test_results(self, method_name, *args, **kwargs):\n \"\"\"\n calls the given method on every test results instances\n\n :param method_name: name of the method to call\n :param args: arguments to pass to the method\n :param kwargs: keyword arguments to pass to the method\n \"\"\"\n me...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.addExpectedFailure
python
def addExpectedFailure(self, test, err): super().addExpectedFailure(test, err) self.test_info(test) self._call_test_results('addExpectedFailure', test, err)
registers as test as expected failure :param test: test to register :param err: error the test gave
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L222-L231
[ "def _call_test_results(self, method_name, *args, **kwargs):\n \"\"\"\n calls the given method on every test results instances\n\n :param method_name: name of the method to call\n :param args: arguments to pass to the method\n :param kwargs: keyword arguments to pass to the method\n \"\"\"\n me...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.addFailure
python
def addFailure(self, test, err): super().addFailure(test, err) self.test_info(test) self._call_test_results('addFailure', test, err)
registers a test as failure :param test: test to register :param err: error the test gave
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L233-L242
[ "def _call_test_results(self, method_name, *args, **kwargs):\n \"\"\"\n calls the given method on every test results instances\n\n :param method_name: name of the method to call\n :param args: arguments to pass to the method\n :param kwargs: keyword arguments to pass to the method\n \"\"\"\n me...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.addSkip
python
def addSkip(self, test, reason): super().addSkip(test, reason) self.test_info(test) self._call_test_results('addSkip', test, reason)
registers a test as skipped :param test: test to register :param reason: reason why the test was skipped
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L244-L253
[ "def _call_test_results(self, method_name, *args, **kwargs):\n \"\"\"\n calls the given method on every test results instances\n\n :param method_name: name of the method to call\n :param args: arguments to pass to the method\n :param kwargs: keyword arguments to pass to the method\n \"\"\"\n me...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.addSuccess
python
def addSuccess(self, test): super().addSuccess(test) self.test_info(test) self._call_test_results('addSuccess', test)
registers a test as successful :param test: test to register
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L255-L263
[ "def _call_test_results(self, method_name, *args, **kwargs):\n \"\"\"\n calls the given method on every test results instances\n\n :param method_name: name of the method to call\n :param args: arguments to pass to the method\n :param kwargs: keyword arguments to pass to the method\n \"\"\"\n me...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.addUnexpectedSuccess
python
def addUnexpectedSuccess(self, test): super().addUnexpectedSuccess(test) self.test_info(test) self._call_test_results('addUnexpectedSuccess', test)
registers a test as an unexpected success :param test: test to register
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L265-L273
[ "def _call_test_results(self, method_name, *args, **kwargs):\n \"\"\"\n calls the given method on every test results instances\n\n :param method_name: name of the method to call\n :param args: arguments to pass to the method\n :param kwargs: keyword arguments to pass to the method\n \"\"\"\n me...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/result.py
ResultCollector.run
python
def run(self) -> None: while not self.cleanup: try: result, test, additional_info = self.result_queue.get(timeout=1) except queue.Empty: continue self.result_queue.task_done() if result == TestState.serialization_failure: ...
processes entries in the queue until told to stop
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/result.py#L281-L315
[ "def addError(self, test, err):\n \"\"\"\n registers a test as error\n\n :param test: test to register\n :param err: error the test gave\n \"\"\"\n super().addError(test, err)\n self.test_info(test)\n self._call_test_results('addError', test, err)\n", "def addExpectedFailure(self, test, er...
class ResultCollector(threading.Thread, unittest.result.TestResult): """ Results handler. Given a report queue, will reform a complete report from it as what would come from a run of unittest.TestResult :param stream: stream on which to write information :param descriptions: whether to display test...
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner._makeResult
python
def _makeResult(self): return [reporter(self.stream, self.descriptions, self.verbosity) for reporter in self.resultclass]
instantiates the result class reporters
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L108-L110
null
class ParallelRunner: """ A parallel test runner for unittest :param stream: stream to use for tests reporting :param descriptions: whether to display descriptions or not :param verbosity: verbosity of the test result reporters :param failfast: stops the test on the first error or failure :...
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.module_can_run_parallel
python
def module_can_run_parallel(test_module: unittest.TestSuite) -> bool: for test_class in test_module: # if the test is already failed, we just don't filter it # and let the test runner deal with it later. if hasattr(unittest.loader, '_FailedTest'): # import failure in python ...
Checks if a given module of tests can be run in parallel or not :param test_module: the module to run :return: True if the module can be run on parallel, False otherwise
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L113-L135
null
class ParallelRunner: """ A parallel test runner for unittest :param stream: stream to use for tests reporting :param descriptions: whether to display descriptions or not :param verbosity: verbosity of the test result reporters :param failfast: stops the test on the first error or failure :...
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.class_can_run_parallel
python
def class_can_run_parallel(test_class: unittest.TestSuite) -> bool: for test_case in test_class: return not getattr(test_case, "__no_parallel__", False)
Checks if a given class of tests can be run in parallel or not :param test_class: the class to run :return: True if te class can be run in parallel, False otherwise
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L138-L146
null
class ParallelRunner: """ A parallel test runner for unittest :param stream: stream to use for tests reporting :param descriptions: whether to display descriptions or not :param verbosity: verbosity of the test result reporters :param failfast: stops the test on the first error or failure :...
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.print_summary
python
def print_summary(self, result, time_taken): if hasattr(result, "separator2"): self.stream.writeln(result.separator2) self.stream.writeln("Ran {number_of_tests} test{s} in {time:.3f}s\n".format( number_of_tests=result.testsRun, s="s" if result.testsRun != 1 else "", time=time_ta...
Prints the test summary, how many tests failed, how long it took, etc :param result: result class to use to print summary :param time_taken: the time all tests took to run
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L182-L217
null
class ParallelRunner: """ A parallel test runner for unittest :param stream: stream to use for tests reporting :param descriptions: whether to display descriptions or not :param verbosity: verbosity of the test result reporters :param failfast: stops the test on the first error or failure :...
BenjaminSchubert/NitPycker
nitpycker/runner.py
ParallelRunner.run
python
def run(self, test: unittest.TestSuite): start_time = time.time() process = [] resource_manager = multiprocessing.Manager() results_queue = resource_manager.Queue() tasks_running = resource_manager.BoundedSemaphore(self.process_number) test_suites, local_test_suites = se...
Given a TestSuite, will create one process per test case whenever possible and run them concurrently. Will then wait for the result and return them :param test: the TestSuite to run :return: a summary of the test run
train
https://github.com/BenjaminSchubert/NitPycker/blob/3ac2b3bf06f1d704b4853167a967311b0465a76f/nitpycker/runner.py#L219-L261
[ "def end_collection(self) -> None:\n \"\"\" Tells the thread that is it time to end \"\"\"\n self.cleanup = True\n", "def printErrors(self):\n \"\"\"\n print test report\n \"\"\"\n self._call_test_results('printErrors')\n", "def _makeResult(self):\n \"\"\" instantiates the result class repo...
class ParallelRunner: """ A parallel test runner for unittest :param stream: stream to use for tests reporting :param descriptions: whether to display descriptions or not :param verbosity: verbosity of the test result reporters :param failfast: stops the test on the first error or failure :...
shaypal5/utilitime
utilitime/datetime/datetime.py
utc_offset_by_timezone
python
def utc_offset_by_timezone(timezone_name): return int(pytz.timezone(timezone_name).utcoffset( utc_time()).total_seconds()/SECONDS_IN_HOUR)
Returns the UTC offset of the given timezone in hours. Arguments --------- timezone_name: str A string with a name of a timezone. Returns ------- int The UTC offset of the given timezone, in hours.
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/datetime/datetime.py#L29-L43
[ "def utc_time():\n \"\"\"Returns the current server time as a datetime object.\n\n This assumes all servers run in UTC time.\n \"\"\"\n return datetime.utcnow()\n" ]
"""Datetime-related utility functions.""" from datetime import datetime, timezone import pytz from decore import lazy_property from ..constants import ( SECONDS_IN_HOUR, ) # === datetime-related functions === @lazy_property def epoch_datetime(): """Returns the epoch as a datetime.datetime object.""" r...
shaypal5/utilitime
utilitime/datetime/datetime.py
localize_datetime
python
def localize_datetime(datetime_obj, timezone_name): return datetime_obj.replace(tzinfo=pytz.utc).astimezone( pytz.timezone(timezone_name))
Localizes the given UTC-aligned datetime by the given timezone. Arguments --------- datetime_obj : datetime.datetime A datetime object decipting a specific point in time, aligned by UTC. timezone_name: str A string with a name of a timezone. Returns ------- datetime.datetim...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/datetime/datetime.py#L46-L62
null
"""Datetime-related utility functions.""" from datetime import datetime, timezone import pytz from decore import lazy_property from ..constants import ( SECONDS_IN_HOUR, ) # === datetime-related functions === @lazy_property def epoch_datetime(): """Returns the epoch as a datetime.datetime object.""" r...
shaypal5/utilitime
utilitime/timestamp/timestamp.py
timestamp_to_local_time
python
def timestamp_to_local_time(timestamp, timezone_name): # first convert timestamp to UTC utc_time = datetime.utcfromtimestamp(float(timestamp)) delo = Delorean(utc_time, timezone='UTC') # shift d according to input timezone localized_d = delo.shift(timezone_name) return localized_d
Convert epoch timestamp to a localized Delorean datetime object. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. Returns ------- delorean.Delorean A localized Delorean datetime o...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L12-L32
null
"""Timestamp-related utility functions.""" from datetime import datetime import calendar import pytz from delorean import Delorean from ..datetime import datetime_to_dateint def timestamp_to_local_time_str( timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"): """Convert epoch timestamp to a localized...
shaypal5/utilitime
utilitime/timestamp/timestamp.py
timestamp_to_local_time_str
python
def timestamp_to_local_time_str( timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"): localized_d = timestamp_to_local_time(timestamp, timezone_name) localized_datetime_str = localized_d.format_datetime(fmt) return localized_datetime_str
Convert epoch timestamp to a localized datetime string. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. fmt : str The format of the output string. Returns ------- str ...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L35-L55
[ "def timestamp_to_local_time(timestamp, timezone_name):\n \"\"\"Convert epoch timestamp to a localized Delorean datetime object.\n\n Arguments\n ---------\n timestamp : int\n The timestamp to convert.\n timezone_name : datetime.timezone\n The timezone of the desired local time.\n\n R...
"""Timestamp-related utility functions.""" from datetime import datetime import calendar import pytz from delorean import Delorean from ..datetime import datetime_to_dateint def timestamp_to_local_time(timestamp, timezone_name): """Convert epoch timestamp to a localized Delorean datetime object. Arguments...
shaypal5/utilitime
utilitime/timestamp/timestamp.py
get_timestamp
python
def get_timestamp(timezone_name, year, month, day, hour=0, minute=0): tz = pytz.timezone(timezone_name) tz_datetime = tz.localize(datetime(year, month, day, hour, minute)) timestamp = calendar.timegm(tz_datetime.utctimetuple()) return timestamp
Epoch timestamp from timezone, year, month, day, hour and minute.
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L58-L63
null
"""Timestamp-related utility functions.""" from datetime import datetime import calendar import pytz from delorean import Delorean from ..datetime import datetime_to_dateint def timestamp_to_local_time(timestamp, timezone_name): """Convert epoch timestamp to a localized Delorean datetime object. Arguments...
shaypal5/utilitime
utilitime/time/time.py
decompose_seconds_in_day
python
def decompose_seconds_in_day(seconds): if seconds > SECONDS_IN_DAY: seconds = seconds - SECONDS_IN_DAY if seconds < 0: raise ValueError("seconds param must be non-negative!") hour = int(seconds / 3600) leftover = seconds - hour * 3600 minute = int(leftover / 60) second = leftover...
Decomposes seconds in day into hour, minute and second components. Arguments --------- seconds : int A time of day by the number of seconds passed since midnight. Returns ------- hour : int The hour component of the given time of day. minut : int The minute componen...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/time/time.py#L10-L35
null
"""dateime.time-related utility functions.""" from datetime import time from ..constants import ( SECONDS_IN_DAY, ) def seconds_in_day_to_time(seconds): """Decomposes atime of day into hour, minute and seconds components. Arguments --------- seconds : int A time of day by the number of...
shaypal5/utilitime
utilitime/time/time.py
seconds_in_day_to_time
python
def seconds_in_day_to_time(seconds): try: return time(*decompose_seconds_in_day(seconds)) except ValueError: print("Seconds = {}".format(seconds)) print("H = {}, M={}, S={}".format(*decompose_seconds_in_day(seconds))) raise
Decomposes atime of day into hour, minute and seconds components. Arguments --------- seconds : int A time of day by the number of seconds passed since midnight. Returns ------- datetime.time The corresponding time of day as a datetime.time object. Example ------- ...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/time/time.py#L38-L61
[ "def decompose_seconds_in_day(seconds):\n \"\"\"Decomposes seconds in day into hour, minute and second components.\n\n Arguments\n ---------\n seconds : int\n A time of day by the number of seconds passed since midnight.\n\n Returns\n -------\n hour : int\n The hour component of t...
"""dateime.time-related utility functions.""" from datetime import time from ..constants import ( SECONDS_IN_DAY, ) def decompose_seconds_in_day(seconds): """Decomposes seconds in day into hour, minute and second components. Arguments --------- seconds : int A time of day by the number ...
shaypal5/utilitime
utilitime/dateint/dateint.py
decompose_dateint
python
def decompose_dateint(dateint): year = int(dateint / 10000) leftover = dateint - year * 10000 month = int(leftover / 100) day = leftover - month * 100 return year, month, day
Decomposes the given dateint into its year, month and day components. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- year : int The year component of the given dateint. month : int The month co...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L16-L37
null
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def dateint_to_date(dateint): """Converts the given integer to a...
shaypal5/utilitime
utilitime/dateint/dateint.py
dateint_to_datetime
python
def dateint_to_datetime(dateint): if len(str(dateint)) != 8: raise ValueError( 'Dateints must have exactly 8 digits; the first four representing ' 'the year, the next two the months, and the last two the days.') year, month, day = decompose_dateint(dateint) return datetime(ye...
Converts the given dateint to a datetime object, in local timezone. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- datetime.datetime A timezone-unaware datetime object representing the start of the given ...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L114-L133
[ "def decompose_dateint(dateint):\n \"\"\"Decomposes the given dateint into its year, month and day components.\n\n Arguments\n ---------\n dateint : int\n An integer object decipting a specific calendaric day; e.g. 20161225.\n\n Returns\n -------\n year : int\n The year component ...
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def decompose_dateint(dateint): """Decomposes the given dateint i...
shaypal5/utilitime
utilitime/dateint/dateint.py
dateint_to_weekday
python
def dateint_to_weekday(dateint, first_day='Monday'): weekday_ix = dateint_to_datetime(dateint).weekday() return (weekday_ix - WEEKDAYS.index(first_day)) % 7
Returns the weekday of the given dateint. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. first_day : str, default 'Monday' The first day of the week. Returns ------- int The weekday of the given dateint, when ...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L136-L166
[ "def dateint_to_datetime(dateint):\n \"\"\"Converts the given dateint to a datetime object, in local timezone.\n\n Arguments\n ---------\n dateint : int\n An integer object decipting a specific calendaric day; e.g. 20161225.\n\n Returns\n -------\n datetime.datetime\n A timezone-u...
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def decompose_dateint(dateint): """Decomposes the given dateint i...
shaypal5/utilitime
utilitime/dateint/dateint.py
shift_dateint
python
def shift_dateint(dateint, day_shift): dtime = dateint_to_datetime(dateint) delta = timedelta(days=abs(day_shift)) if day_shift > 0: dtime = dtime + delta else: dtime = dtime - delta return datetime_to_dateint(dtime)
Shifts the given dateint by the given amount of days. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. days : int The number of days to shift the given dateint by. A negative number shifts the dateint backwards. Returns...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L194-L226
[ "def datetime_to_dateint(datetime_obj):\n \"\"\"Converts the given datetime object to the corresponding dateint.\n\n Arguments\n ---------\n datetime_obj : datetime.datetime\n A datetime object decipting a specific point in time.\n\n Returns\n -------\n int\n An integer represetin...
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def decompose_dateint(dateint): """Decomposes the given dateint i...
shaypal5/utilitime
utilitime/dateint/dateint.py
dateint_range
python
def dateint_range(first_dateint, last_dateint): first_datetime = dateint_to_datetime(first_dateint) last_datetime = dateint_to_datetime(last_dateint) delta = last_datetime - first_datetime delta_in_hours = math.ceil(delta.total_seconds() / 3600) delta_in_days = math.ceil(delta_in_hours / 24) + 1 ...
Returns all dateints in the given dateint range. Arguments --------- first_dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. last_dateint : int An integer object decipting a specific calendaric day; e.g. 20170108. Returns ------- iterable ...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L229-L262
[ "def datetime_to_dateint(datetime_obj):\n \"\"\"Converts the given datetime object to the corresponding dateint.\n\n Arguments\n ---------\n datetime_obj : datetime.datetime\n A datetime object decipting a specific point in time.\n\n Returns\n -------\n int\n An integer represetin...
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def decompose_dateint(dateint): """Decomposes the given dateint i...
shaypal5/utilitime
utilitime/dateint/dateint.py
dateint_week_by_dateint
python
def dateint_week_by_dateint(dateint, first_day='Monday'): weekday_ix = dateint_to_weekday(dateint, first_day) first_day_dateint = shift_dateint(dateint, -weekday_ix) last_day_dateint = shift_dateint(first_day_dateint, 6) return dateint_range(first_day_dateint, last_day_dateint)
Return a dateint range of the week the given dateint belongs to. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. first_day : str, default 'Monday' The first day of the week. Returns ------- iterable An iterable...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L270-L289
[ "def dateint_to_weekday(dateint, first_day='Monday'):\n \"\"\"Returns the weekday of the given dateint.\n\n Arguments\n ---------\n dateint : int\n An integer object decipting a specific calendaric day; e.g. 20161225.\n first_day : str, default 'Monday'\n The first day of the week.\n\n ...
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def decompose_dateint(dateint): """Decomposes the given dateint i...
shaypal5/utilitime
utilitime/dateint/dateint.py
dateint_difference
python
def dateint_difference(dateint1, dateint2): dt1 = dateint_to_datetime(dateint1) dt2 = dateint_to_datetime(dateint2) delta = dt1 - dt2 return abs(delta.days)
Return the difference between two dateints in days. Arguments --------- dateint1 : int An integer object decipting a specific calendaric day; e.g. 20161225. dateint2 : int An integer object decipting a specific calendaric day; e.g. 20161225. Returns ------- int The ...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/dateint/dateint.py#L292-L310
[ "def dateint_to_datetime(dateint):\n \"\"\"Converts the given dateint to a datetime object, in local timezone.\n\n Arguments\n ---------\n dateint : int\n An integer object decipting a specific calendaric day; e.g. 20161225.\n\n Returns\n -------\n datetime.datetime\n A timezone-u...
"""Datetime-related utility functions.""" from datetime import datetime, timedelta, date import math from ..timestamp import get_timestamp from ..datetime import ( utc_time, datetime_to_dateint, ) from ..constants import ( WEEKDAYS, ) def decompose_dateint(dateint): """Decomposes the given dateint i...
shaypal5/utilitime
utilitime/time_interval.py
TimeInterval.from_timedelta
python
def from_timedelta(cls, datetime_obj, duration): if duration.total_seconds() > 0: return TimeInterval(datetime_obj, datetime_obj + duration) else: return TimeInterval(datetime_obj + duration, datetime_obj)
Create a new TimeInterval object from a start point and a duration. If duration is positive, datetime_obj is the start of the interval; if duration is negative, datetime_obj is the end of the interval. Parameters ---------- datetime_obj : datetime.datetime duration : da...
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/time_interval.py#L19-L37
null
class TimeInterval: """A class that represents a time interval, based on a start and end point. """ def __init__(self, start, end): """Create a new TimeInterval object from a start and end point. Parameters ---------- start, end : datetime.datetime """ assert...
shaypal5/utilitime
utilitime/weekday/weekday.py
next_weekday
python
def next_weekday(weekday): ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+1]
Returns the name of the weekday after the given weekday name.
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L12-L17
null
"""Weekday-related utility functions.""" from decore import lazy_property from ..constants import ( WEEKDAYS, ) # === weekday-related functions === def prev_weekday(weekday): """Returns the name of the weekday before the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == 0: retu...
shaypal5/utilitime
utilitime/weekday/weekday.py
prev_weekday
python
def prev_weekday(weekday): ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-1]
Returns the name of the weekday before the given weekday name.
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L20-L25
null
"""Weekday-related utility functions.""" from decore import lazy_property from ..constants import ( WEEKDAYS, ) # === weekday-related functions === def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: ...
shaypal5/utilitime
utilitime/weekday/weekday.py
workdays
python
def workdays(first_day=None): if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+5]
Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names.
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L38-L55
null
"""Weekday-related utility functions.""" from decore import lazy_property from ..constants import ( WEEKDAYS, ) # === weekday-related functions === def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: ...
shaypal5/utilitime
utilitime/weekday/weekday.py
weekdays
python
def weekdays(first_day=None): if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+7]
Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names.
train
https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/weekday/weekday.py#L58-L74
null
"""Weekday-related utility functions.""" from decore import lazy_property from ..constants import ( WEEKDAYS, ) # === weekday-related functions === def next_weekday(weekday): """Returns the name of the weekday after the given weekday name.""" ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: ...
thespacedoctor/transientNamer
transientNamer/search.py
search.sources
python
def sources( self): sourceResultsList = [] sourceResultsList[:] = [dict(l) for l in self.sourceResultsList] return sourceResultsList
*The results of the search returned as a python list of dictionaries* **Usage:** .. code-block:: python sources = tns.sources
train
https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L152-L164
null
class search(): """ *The worker class for the transient namer search module* **Key Arguments:** - ``log`` -- logger - ``settings`` -- the settings dictionary - ``ra`` -- RA of the location being checked - ``dec`` -- DEC of the location being searched - ``radiusArcsec...
thespacedoctor/transientNamer
transientNamer/search.py
search.spectra
python
def spectra( self): specResultsList = [] specResultsList[:] = [dict(l) for l in self.specResultsList] return specResultsList
*The associated source spectral data* **Usage:** .. code-block:: python sourceSpectra = tns.spectra
train
https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L167-L179
null
class search(): """ *The worker class for the transient namer search module* **Key Arguments:** - ``log`` -- logger - ``settings`` -- the settings dictionary - ``ra`` -- RA of the location being checked - ``dec`` -- DEC of the location being searched - ``radiusArcsec...