signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def __setitem__(self, index, val): | offset = self.default_offset<EOL>try: index, offset = index<EOL>except TypeError: pass<EOL>try: head = self.heads[index] + self.offsets[offset]<EOL>except TypeError: pass<EOL>else:<EOL><INDENT>return self.filehandle.putline(head,<EOL>self.length,<EOL>self.stride,<EOL>len(self.offsets),<EOL>index,<EOL>offset,<EOL>castarray(val, dtype = self.dtype),<EOL>)<EOL><DEDENT>irange, orange = self.ranges(index, offset)<EOL>val = iter(val)<EOL>for line in irange:<EOL><INDENT>for off in orange:<EOL><INDENT>head = self.heads[line] + self.offsets[off]<EOL>try: self.filehandle.putline(head,<EOL>self.length,<EOL>self.stride,<EOL>len(self.offsets),<EOL>line,<EOL>off,<EOL>next(val),<EOL>)<EOL>except StopIteration: return<EOL><DEDENT><DEDENT> | line[i] = val or line[i, o] = val
Follows the same rules for indexing and slicing as ``line[i]``.
In either case, if the `val` iterable is exhausted before the line(s),
assignment stops with whatever is written so far. If `val` is longer
than an individual line, it's essentially truncated.
Parameters
----------
i : int or slice
offset : int or slice
val : array_like
Raises
------
KeyError
If `i` or `o` don't exist
Notes
-----
.. versionadded:: 1.1
Examples
--------
Copy a full line:
>>> line[2400] = other[2834]
Copy first half of the inlines from g to f:
>>> line[:] = other[:labels[len(labels) / 2]]
Copy every other line consecutively:
>>> line[:] = other[::2]
Copy every third offset:
>>> line[:,:] = other[:,::3]
Copy a line into a set line and offset:
>>> line[12, 200] = other[21] | f13387:c0:m3 |
def __len__(self): | return len(self.heads)<EOL> | x.__len__() <==> len(x) | f13387:c0:m4 |
def __iter__(self): | return self[:]<EOL> | x.__iter__() <==> iter(x) | f13387:c0:m5 |
def __contains__(self, key): | return key in self.heads<EOL> | x.__contains__(y) <==> y in x | f13387:c0:m6 |
def keys(self): | return sorted(self.heads.keys())<EOL> | D.keys() -> a set-like object providing a view on D's keys | f13387:c0:m7 |
def values(self): | return self[:]<EOL> | D.values() -> generator of D's values | f13387:c0:m8 |
def items(self): | return zip(self.keys(), self[:])<EOL> | D.values() -> generator of D's (key,values), as 2-tuples | f13387:c0:m9 |
def __getitem__(self, index): | offset = self.default_offset<EOL>try: index, offset = index<EOL>except TypeError: pass<EOL>try:<EOL><INDENT>start = self.heads[index] + self.offsets[offset]<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>step = self.stride * len(self.offsets)<EOL>stop = start + step * self.length<EOL>return self.header[start:stop:step]<EOL><DEDENT>def gen():<EOL><INDENT>irange, orange = self.ranges(index, offset)<EOL>for line in irange:<EOL><INDENT>for off in orange:<EOL><INDENT>yield self[line, off]<EOL><DEDENT><DEDENT><DEDENT>return gen()<EOL> | line[i] or line[i, o]
The line `i`, or the line `i` at a specific offset `o`. ``line[i]``
returns an iterable of `Field` objects, and changes to these *will* be
reflected on disk.
The `i` and `o` are *keys*, and should correspond to the line- and
offset labels in your file, and in the `ilines`, `xlines`, and
`offsets` attributes.
Slices can contain lines and offsets not in the file, and like with
list slicing, these are handled gracefully and ignored.
When `i` or `o` is a slice, a generator of iterables of headers are
returned.
When both `i` and `o` are slices, one generator is returned for the
product `i` and `o`, and the lines are yielded offsets-first, roughly
equivalent to the double for loop::
>>> for line in lines:
... for off in offsets:
... yield line[line, off]
...
Parameters
----------
i : int or slice
o : int or slice
Returns
-------
line : iterable of Field or generator of iterator of Field
Raises
------
KeyError
If `i` or `o` don't exist
Notes
-----
.. versionadded:: 1.1 | f13387:c1:m1 |
def __setitem__(self, index, val): | offset = self.default_offset<EOL>try: index, offset = index<EOL>except TypeError: pass<EOL>try: start = self.heads[index] + self.offsets[offset]<EOL>except TypeError: pass<EOL>else:<EOL><INDENT>try:<EOL><INDENT>if hasattr(val, '<STR_LIT>'):<EOL><INDENT>val = itertools.repeat(val)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>step = self.stride * len(self.offsets)<EOL>stop = start + step * self.length<EOL>self.header[start:stop:step] = val<EOL>return<EOL><DEDENT>irange, orange = self.ranges(index, offset)<EOL>val = iter(val)<EOL>for line in irange:<EOL><INDENT>for off in orange:<EOL><INDENT>try:<EOL><INDENT>self[line, off] = next(val)<EOL><DEDENT>except StopIteration:<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT> | line[i] = val or line[i, o] = val
Follows the same rules for indexing and slicing as ``line[i]``. If `i`
is an int, and `val` is a dict or Field, that value is replicated and
assigned to every trace header in the line, otherwise it's treated as
an iterable, and each trace in the line is assigned the ``next()``
yielded value.
If `i` or `o` is a slice, `val` must be an iterable.
In either case, if the `val` iterable is exhausted before the line(s),
assignment stops with whatever is written so far.
Parameters
----------
i : int or slice
offset : int or slice
val : dict_like or iterable of dict_like
Raises
------
KeyError
If `i` or `o` don't exist
Notes
-----
.. versionadded:: 1.1
Examples
--------
Rename the iline 3 to 4:
>>> line[3] = { TraceField.INLINE_3D: 4 }
>>> # please note that rewriting the header won't update the
>>> # file's interpretation of the file until you reload it, so
>>> # the new iline 4 will be considered iline 3 until the file
>>> # is reloaded
Set offset line 3 offset 3 to 5:
>>> line[3, 3] = { TraceField.offset: 5 } | f13387:c1:m2 |
def mkoutdir(self, clobber=True): | funcname = '<STR_LIT:.>'.join(self.id().split('<STR_LIT:.>')[-<NUM_LIT:3>:])<EOL>outdir = os.path.join(self.outputdir, funcname)<EOL>mkdir(outdir, clobber)<EOL>return outdir<EOL> | Create outdir as outpudir/module.class.method (destructively
if clobber is True). | f13405:c0:m0 |
def setup_logging(namespace): | loglevel = {<EOL><NUM_LIT:0>: logging.ERROR,<EOL><NUM_LIT:1>: logging.WARNING,<EOL><NUM_LIT:2>: logging.INFO,<EOL><NUM_LIT:3>: logging.DEBUG,<EOL>}.get(namespace.verbosity, logging.DEBUG)<EOL>if namespace.verbosity > <NUM_LIT:1>:<EOL><INDENT>logformat = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>logformat = '<STR_LIT>'<EOL><DEDENT>logging.basicConfig(stream=namespace.log, format=logformat, level=loglevel)<EOL> | setup global logging | f13416:m1 |
def parse_subcommands(parser, subcommands, argv): | subparsers = parser.add_subparsers(dest='<STR_LIT>')<EOL>parser_help = subparsers.add_parser(<EOL>'<STR_LIT>', help='<STR_LIT>')<EOL>parser_help.add_argument('<STR_LIT:action>', nargs=<NUM_LIT:1>)<EOL>modules = [<EOL>name for _, name, _ in pkgutil.iter_modules(subcommands.__path__)]<EOL>commands = [m for m in modules if m in argv]<EOL>actions = {}<EOL>for name in commands or modules:<EOL><INDENT>try:<EOL><INDENT>imp = '<STR_LIT>'.format(subcommands.__name__, name)<EOL>mod = importlib.import_module(imp)<EOL><DEDENT>except Exception as e:<EOL><INDENT>log.error(e)<EOL>continue<EOL><DEDENT>subparser = subparsers.add_parser(<EOL>name,<EOL>help=mod.__doc__.lstrip().split('<STR_LIT:\n>', <NUM_LIT:1>)[<NUM_LIT:0>],<EOL>description=mod.__doc__,<EOL>formatter_class=argparse.RawDescriptionHelpFormatter)<EOL>mod.build_parser(subparser)<EOL>subcommands.build_parser(subparser)<EOL>actions[name] = mod.action<EOL><DEDENT>return parser, actions<EOL> | Setup all sub-commands | f13416:m4 |
def opener(mode='<STR_LIT:r>'): | def open_file(f):<EOL><INDENT>if f is sys.stdout or f is sys.stdin:<EOL><INDENT>return f<EOL><DEDENT>elif f == '<STR_LIT:->':<EOL><INDENT>return sys.stdin if '<STR_LIT:r>' in mode else sys.stdout<EOL><DEDENT>elif f.endswith('<STR_LIT>'):<EOL><INDENT>return bz2.BZ2File(f, mode)<EOL><DEDENT>elif f.endswith('<STR_LIT>'):<EOL><INDENT>return gzip.open(f, mode)<EOL><DEDENT>else:<EOL><INDENT>return open(f, mode)<EOL><DEDENT><DEDENT>return open_file<EOL> | Factory for creating file objects
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function. | f13417:m0 |
@main.command()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.pass_context<EOL>def ls(ctx, available): | path = ctx.obj['<STR_LIT:path>']<EOL>global_ = ctx.obj['<STR_LIT>']<EOL>_ls(available=available, **ctx.obj)<EOL> | List installed datasets on path | f13428:m1 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def reqs(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>(print)(data(dataset, **ctx.obj).reqs(**kwargs))<EOL> | Get the dataset's pip requirements | f13428:m2 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def size(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>(print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size)<EOL> | Show dataset size | f13428:m3 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def get(ctx, dataset, rm, keep_compressed, dont_process, dont_download, keep_raw, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>process = not dont_process<EOL>rm_raw = not keep_raw<EOL>rm_compressed = not keep_compressed<EOL>download = not dont_download<EOL>data(dataset, **ctx.obj).get(download=download, rm=rm, rm_compressed=rm_compressed, process=process, rm_raw=rm_raw, **kwargs)<EOL> | performs the operations download, extract, rm_compressed, processes and rm_raw, in sequence. KWARGS must be in the form: key=value, and are fowarded to all opeartions. | f13428:m4 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def rm(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).rm(**kwargs)<EOL> | removes the dataset's folder if it exists | f13428:m5 |
@main.command("<STR_LIT>")<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def rm_subsets(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).rm_subsets(**kwargs)<EOL> | removes the dataset's training-set and test-set folders if they exists | f13428:m6 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True, help="<STR_LIT>")<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def download(ctx, dataset, rm, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).download(rm=rm, **kwargs)<EOL> | downloads the dataset's compressed files | f13428:m7 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def extract(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).extract(**kwargs)<EOL> | extracts the files from the compressed archives | f13428:m8 |
@main.command("<STR_LIT>")<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def rm_compressed(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).rm_compressed(**kwargs)<EOL> | removes the compressed files | f13428:m9 |
@main.command()<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def process(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).process(**kwargs)<EOL> | processes the data to a friendly format | f13428:m10 |
@main.command("<STR_LIT>")<EOL>@click.argument('<STR_LIT>')<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>)<EOL>@click.pass_context<EOL>def rm_raw(ctx, dataset, kwargs): | kwargs = parse_kwargs(kwargs)<EOL>data(dataset, **ctx.obj).rm_raw(**kwargs)<EOL> | removes the raw unprocessed data | f13428:m11 |
def recursive_iterator(func): | tee_store = {}<EOL>@_coconut.functools.wraps(func)<EOL>def recursive_iterator_func(*args, **kwargs):<EOL><INDENT>hashable_args_kwargs = _coconut.pickle.dumps((args, kwargs), _coconut.pickle.HIGHEST_PROTOCOL)<EOL>try:<EOL><INDENT>to_tee = tee_store[hashable_args_kwargs]<EOL><DEDENT>except _coconut.KeyError:<EOL><INDENT>to_tee = func(*args, **kwargs)<EOL><DEDENT>tee_store[hashable_args_kwargs], to_return = _coconut_tee(to_tee)<EOL>return to_return<EOL><DEDENT>return recursive_iterator_func<EOL> | Decorates a function by optimizing it for iterator recursion.
Requires function arguments to be pickleable. | f13431:m10 |
def addpattern(base_func): | def pattern_adder(func):<EOL><INDENT>@_coconut.functools.wraps(func)<EOL>@_coconut_tco<EOL>def add_pattern_func(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return base_func(*args, **kwargs)<EOL><DEDENT>except _coconut_MatchError:<EOL><INDENT>raise _coconut_tail_call(func, *args, **kwargs)<EOL><DEDENT><DEDENT>return add_pattern_func<EOL><DEDENT>return pattern_adder<EOL> | Decorator to add a new case to a pattern-matching function, where the new case is checked last. | f13431:m11 |
def prepattern(base_func): | def pattern_prepender(func):<EOL><INDENT>return addpattern(func)(base_func)<EOL><DEDENT>return pattern_prepender<EOL> | Decorator to add a new case to a pattern-matching function, where the new case is checked first. | f13431:m12 |
def consume(iterable, keep_last=<NUM_LIT:0>): | return _coconut.collections.deque(iterable, maxlen=keep_last) <EOL> | Fully exhaust iterable and return the last keep_last elements. | f13431:m13 |
def fmap(func, obj): | if _coconut.hasattr(obj, "<STR_LIT>"):<EOL><INDENT>return obj.__fmap__(func)<EOL><DEDENT>args = _coconut_map(func, obj)<EOL>if _coconut.isinstance(obj, _coconut.dict):<EOL><INDENT>args = _coconut_zip(args, obj.values())<EOL><DEDENT>if _coconut.isinstance(obj, _coconut.tuple) and _coconut.hasattr(obj, "<STR_LIT>"):<EOL><INDENT>return obj._make(args)<EOL><DEDENT>if _coconut.isinstance(obj, (_coconut.map, _coconut.range)):<EOL><INDENT>return args<EOL><DEDENT>if _coconut.isinstance(obj, _coconut.str):<EOL><INDENT>return "<STR_LIT>".join(args)<EOL><DEDENT>return obj.__class__(args)<EOL> | Creates a copy of obj with func applied to its contents. | f13431:m14 |
def count(self, elem): | return self._iter.count(elem)<EOL> | Count the number of times elem appears in the reversed iterator. | f13431:c4:m13 |
def index(self, elem): | return _coconut.len(self._iter) - self._iter.index(elem) - <NUM_LIT:1><EOL> | Find the index of elem in the reversed iterator. | f13431:c4:m14 |
def count(self, elem): | return int(elem in self)<EOL> | Count the number of times elem appears in the count. | f13431:c11:m4 |
def index(self, elem): | if elem not in self:<EOL><INDENT>raise _coconut.ValueError(_coconut.repr(elem) + "<STR_LIT>")<EOL><DEDENT>return (elem - self._start) // self._step<EOL> | Find the index of elem in the count. | f13431:c11:m5 |
def match_route(self, reqpath): | route_dicts = [routes for _, routes in self.api.http.routes.items()][<NUM_LIT:0>]<EOL>routes = [route for route, _ in route_dicts.items()]<EOL>if reqpath in routes:<EOL><INDENT>return reqpath<EOL><DEDENT>for route in routes:<EOL><INDENT>if re.match(re.sub(r'<STR_LIT>', '<STR_LIT>', route) + '<STR_LIT:$>', reqpath):<EOL><INDENT>return route<EOL><DEDENT><DEDENT>return reqpath<EOL> | match a request with parameter to it's corresponding route | f13443:c0:m1 |
def process_response(self, request, response, resource): | <EOL>response.set_header('<STR_LIT>', '<STR_LIT:U+002CU+0020>'.join(self.allow_origins))<EOL>response.set_header('<STR_LIT>', str(self.allow_credentials).lower())<EOL>if request.method == '<STR_LIT>':<EOL><INDENT>allowed_methods = set(<EOL>method<EOL>for _, routes in self.api.http.routes.items()<EOL>for method, _ in routes[self.match_route(request.path)].items()<EOL>)<EOL>allowed_methods.add('<STR_LIT>')<EOL>response.set_header('<STR_LIT>', '<STR_LIT:U+002CU+0020>'.join(allowed_methods))<EOL>response.set_header('<STR_LIT>', '<STR_LIT:U+002CU+0020>'.join(allowed_methods))<EOL>requested_headers = request.get_header('<STR_LIT>')<EOL>response.set_header('<STR_LIT>', requested_headers or '<STR_LIT>')<EOL>if self.max_age:<EOL><INDENT>response.set_header('<STR_LIT>', self.max_age)<EOL><DEDENT><DEDENT> | Add CORS headers to the response | f13443:c0:m2 |
def clean_data(self): | <EOL>if "<STR_LIT>" in self:<EOL><INDENT>self._check_timestamp()<EOL>if type(self["<STR_LIT>"]) == list:<EOL><INDENT>def datetime_to_string(dt):<EOL><INDENT>return fmt_datetime(dt) if type(dt) == datetime else dt<EOL><DEDENT>self["<STR_LIT>"] = list(map(datetime_to_string, self["<STR_LIT>"]))<EOL><DEDENT>elif type(self["<STR_LIT>"]) == datetime:<EOL><INDENT>self["<STR_LIT>"] = fmt_datetime(self["<STR_LIT>"])<EOL><DEDENT><DEDENT>if "<STR_LIT>" in self:<EOL><INDENT>self["<STR_LIT>"]["<STR_LIT>"] = self["<STR_LIT>"]["<STR_LIT>"].replace("<STR_LIT:l>", "<STR_LIT:L>")<EOL><DEDENT>if "<STR_LIT>" in self:<EOL><INDENT>if self["<STR_LIT>"]["<STR_LIT>"] in ["<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>self["<STR_LIT>"]["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT><DEDENT> | Ensures data is Zenobase compatible and patches it if possible,
if cleaning is not possible it'll raise an appropriate exception | f13450:c0:m1 |
def list_buckets(self, offset=<NUM_LIT:0>, limit=<NUM_LIT:100>): | <EOL>if limit > <NUM_LIT:100>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>return self._get("<STR_LIT>".format(self.client_id, offset, limit))<EOL> | Limit breaks above 100 | f13451:c0:m7 |
@staticmethod<EOL><INDENT>def get_dates(raw_table) -> "<STR_LIT>":<DEDENT> | dates = []<EOL>found_first = False<EOL>for i, dstr in enumerate([raw_table[i][<NUM_LIT:0>] for i in range(<NUM_LIT:0>, len(raw_table))]):<EOL><INDENT>if dstr:<EOL><INDENT>if len(dstr.split("<STR_LIT:/>")) == <NUM_LIT:3>:<EOL><INDENT>d = datetime.datetime.strptime(dstr, '<STR_LIT>')<EOL><DEDENT>elif len(dstr.split("<STR_LIT:->")) == <NUM_LIT:3>:<EOL><INDENT>d = datetime.datetime.strptime(dstr, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>logging.debug("<STR_LIT>".format(dstr))<EOL>continue<EOL><DEDENT>dates.append(d)<EOL>if not found_first:<EOL><INDENT>found_first = True<EOL>logging.debug("<STR_LIT>".format(d.isoformat(), i))<EOL><DEDENT><DEDENT>elif found_first:<EOL><INDENT>logging.debug("<STR_LIT>".format(d))<EOL>break<EOL><DEDENT><DEDENT>return dates<EOL> | Goes through the first column of input table and
returns the first sequence of dates it finds. | f13453:c0:m3 |
def get_main(self) -> '<STR_LIT>': | raw_table = self.get_raw_table("<STR_LIT:M>")<EOL>categories = raw_table[<NUM_LIT:0>]<EOL>labels = raw_table[<NUM_LIT:1>]<EOL>dates = self.get_dates(raw_table)<EOL>def next_cat_col(i):<EOL><INDENT>n = <NUM_LIT:1><EOL>while True:<EOL><INDENT>if i+n > len(categories)-<NUM_LIT:1>:<EOL><INDENT>return i<EOL><DEDENT>if categories[i+n]:<EOL><INDENT>return i+n<EOL><DEDENT>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>def get_category_labels(i):<EOL><INDENT>end_col = next_cat_col(i)<EOL>return zip(range(i, end_col), labels[i:end_col])<EOL><DEDENT>def get_label_cells(category, label):<EOL><INDENT>ci = categories.index(category)<EOL>i = labels.index(label, ci)<EOL>cells = {}<EOL>for j, d in enumerate(dates):<EOL><INDENT>cell = raw_table[j+<NUM_LIT:2>][i]<EOL>if cell and cell != "<STR_LIT>":<EOL><INDENT>cells[d] = cell<EOL><DEDENT><DEDENT>return cells<EOL><DEDENT>table = {}<EOL>for i, cat in enumerate(categories):<EOL><INDENT>if not cat:<EOL><INDENT>continue<EOL><DEDENT>table[cat] = {}<EOL>for i, label in get_category_labels(i):<EOL><INDENT>table[cat][label] = get_label_cells(cat, label)<EOL><DEDENT><DEDENT>return table<EOL> | Returns a table with the above typesignature | f13453:c0:m4 |
def upload_batterystats(filename, username, password, bucket_name=BUCKET_NAME, bucket_desc=BUCKET_DESC): | zapi = pyzenobase.ZenobaseAPI(username, password)<EOL>bucket = zapi.create_or_get_bucket(bucket_name, description=bucket_desc)<EOL>bucket_id = bucket["<STR_LIT>"]<EOL>events = []<EOL>with open(filename, newline="<STR_LIT>") as f:<EOL><INDENT>reader = csv.reader(f)<EOL>header = next(reader)<EOL>for row in reader:<EOL><INDENT>events.append({header[i]: row[i] for i in range(len(header))})<EOL><DEDENT><DEDENT>print("<STR_LIT>".format(len(events)))<EOL>for event in events:<EOL><INDENT>event["<STR_LIT>"] = pyzenobase.fmt_datetime(datetime.strptime(event.pop("<STR_LIT>"), "<STR_LIT>"), timezone="<STR_LIT>")<EOL>event["<STR_LIT>"] = event.pop("<STR_LIT:status>")<EOL>event["<STR_LIT>"] = float(event.pop("<STR_LIT>"))<EOL>event["<STR_LIT>"] = {"<STR_LIT>": float(event.pop("<STR_LIT>")), "<STR_LIT>": "<STR_LIT:C>"}<EOL>event.pop("<STR_LIT>")<EOL><DEDENT>print("<STR_LIT>")<EOL>events = [pyzenobase.ZenobaseEvent(event) for event in events]<EOL>print("<STR_LIT>")<EOL>zapi.create_events(bucket_id, events)<EOL>zapi.close()<EOL>print("<STR_LIT>")<EOL> | Works with CSVs generated by the Android app 'Battery Log' (https://play.google.com/store/apps/details?id=kr.hwangti.batterylog) | f13454:m0 |
def cli(self): | <EOL>init_parser = argparse.ArgumentParser(<EOL>description = __doc__,<EOL>formatter_class = argparse.RawDescriptionHelpFormatter,<EOL>add_help = False)<EOL>init_parser.add_argument("<STR_LIT:-c>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>help = "<STR_LIT>")<EOL>args, remaining_args = init_parser.parse_known_args()<EOL>reader = None<EOL>config_file = args.config or self.detect_config()<EOL>if config_file:<EOL><INDENT>with open(config_file, '<STR_LIT:r>') as f:<EOL><INDENT>reader = ConfigReader(f.read())<EOL><DEDENT><DEDENT>parser = argparse.ArgumentParser(<EOL>parents = [init_parser],<EOL>add_help = True,<EOL>description = "<STR_LIT>")<EOL>application_opts = reader.application if reader else {}<EOL>default_options = self.merge_with_default_options(application_opts)<EOL>parser.set_defaults(**default_options)<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:version>",<EOL>version="<STR_LIT>".format(__version__))<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", "<STR_LIT>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>if reader:<EOL><INDENT>self.config = reader.config<EOL><DEDENT>self.config['<STR_LIT>'] = vars(parser.parse_args(remaining_args))<EOL>if '<STR_LIT>' not in self.config:<EOL><INDENT>raise WigikiConfigError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT> | Read program parameters from command line and configuration files
We support both command line arguments and configuration files.
The command line arguments have always precedence over any
configuration file parameters. This allows us to have most of
our options in files but override them individually from the command
line. | f13458:c1:m1 |
def detect_config(self): | default_files = ("<STR_LIT>", "<STR_LIT>")<EOL>for file_ in default_files:<EOL><INDENT>if os.path.exists(file_):<EOL><INDENT>return file_<EOL><DEDENT><DEDENT> | check in the current working directory for configuration files | f13458:c1:m2 |
def merge_with_default_options(self, config_opts): | return dict(list(self.defaults.items()) + list(config_opts.items()))<EOL> | merge options from configuration file with the default options | f13458:c1:m3 |
@classmethod<EOL><INDENT>def gist(cls, gistid):<DEDENT> | url = "<STR_LIT>".format(gistid)<EOL>script = "<STR_LIT>".format(url)<EOL>return script<EOL> | gistid must be in a username/id form | f13459:c0:m0 |
@classmethod<EOL><INDENT>def page_list(cls, pages, base_url='<STR_LIT:/>'):<DEDENT> | plist = []<EOL>for page in pages:<EOL><INDENT>url = "<STR_LIT>".format(base_url, cls.slugify(page), page)<EOL>plist.append(url)<EOL><DEDENT>return plist<EOL> | transform a list of page titles in a list of html links | f13459:c0:m1 |
@classmethod<EOL><INDENT>def slugify(cls, s):<DEDENT> | slug = re.sub("<STR_LIT>", "<STR_LIT:->", s)<EOL>return re.sub("<STR_LIT>", "<STR_LIT:->", slug).strip('<STR_LIT:->')<EOL> | Return the slug version of the string ``s`` | f13459:c0:m2 |
def _save_file(self, filename, contents): | with open(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(contents)<EOL><DEDENT> | write the html file contents to disk | f13463:c0:m3 |
def _stick_device(self): | for evdev in glob.glob('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>with io.open(os.path.join(evdev, '<STR_LIT>', '<STR_LIT:name>'), '<STR_LIT:r>') as f:<EOL><INDENT>if f.read().strip() == self.SENSE_HAT_EVDEV_NAME:<EOL><INDENT>return os.path.join('<STR_LIT>', '<STR_LIT:input>', os.path.basename(evdev))<EOL><DEDENT><DEDENT><DEDENT>except IOError as e:<EOL><INDENT>if e.errno != errno.ENOENT:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL> | Discovers the filename of the evdev device that represents the Sense
HAT's joystick. | f13466:c0:m4 |
def _read(self): | event = self._stick_file.read(self.EVENT_SIZE)<EOL>(tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event)<EOL>if type == self.EV_KEY:<EOL><INDENT>return InputEvent(<EOL>timestamp=tv_sec + (tv_usec / <NUM_LIT>),<EOL>direction={<EOL>self.KEY_UP: DIRECTION_UP,<EOL>self.KEY_DOWN: DIRECTION_DOWN,<EOL>self.KEY_LEFT: DIRECTION_LEFT,<EOL>self.KEY_RIGHT: DIRECTION_RIGHT,<EOL>self.KEY_ENTER: DIRECTION_MIDDLE,<EOL>}[code],<EOL>action={<EOL>self.STATE_PRESS: ACTION_PRESSED,<EOL>self.STATE_RELEASE: ACTION_RELEASED,<EOL>self.STATE_HOLD: ACTION_HELD,<EOL>}[value])<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Reads a single event from the joystick, blocking until one is
available. Returns `None` if a non-key event was read, or an
`InputEvent` tuple describing the event otherwise. | f13466:c0:m5 |
def _wait(self, timeout=None): | r, w, x = select.select([self._stick_file], [], [], timeout)<EOL>return bool(r)<EOL> | Waits *timeout* seconds until an event is available from the
joystick. Returns `True` if an event became available, and `False`
if the timeout expired. | f13466:c0:m6 |
def wait_for_event(self, emptybuffer=False): | if emptybuffer:<EOL><INDENT>while self._wait(<NUM_LIT:0>):<EOL><INDENT>self._read()<EOL><DEDENT><DEDENT>while self._wait():<EOL><INDENT>event = self._read()<EOL>if event:<EOL><INDENT>return event<EOL><DEDENT><DEDENT> | Waits until a joystick event becomes available. Returns the event, as
an `InputEvent` tuple.
If *emptybuffer* is `True` (it defaults to `False`), any pending
events will be thrown away first. This is most useful if you are only
interested in "pressed" events. | f13466:c0:m10 |
def get_events(self): | result = []<EOL>while self._wait(<NUM_LIT:0>):<EOL><INDENT>event = self._read()<EOL>if event:<EOL><INDENT>result.append(event)<EOL><DEDENT><DEDENT>return result<EOL> | Returns a list of all joystick events that have occurred since the last
call to `get_events`. The list contains events in the order that they
occurred. If no events have occurred in the intervening time, the
result is an empty list. | f13466:c0:m11 |
@property<EOL><INDENT>def direction_up(self):<DEDENT> | return self._callbacks.get(DIRECTION_UP)<EOL> | The function to be called when the joystick is pushed up. The function
can either take a parameter which will be the `InputEvent` tuple that
has occurred, or the function can take no parameters at all. | f13466:c0:m12 |
@property<EOL><INDENT>def direction_down(self):<DEDENT> | return self._callbacks.get(DIRECTION_DOWN)<EOL> | The function to be called when the joystick is pushed down. The
function can either take a parameter which will be the `InputEvent`
tuple that has occurred, or the function can take no parameters at all.
Assign `None` to prevent this event from being fired. | f13466:c0:m14 |
@property<EOL><INDENT>def direction_left(self):<DEDENT> | return self._callbacks.get(DIRECTION_LEFT)<EOL> | The function to be called when the joystick is pushed left. The
function can either take a parameter which will be the `InputEvent`
tuple that has occurred, or the function can take no parameters at all.
Assign `None` to prevent this event from being fired. | f13466:c0:m16 |
@property<EOL><INDENT>def direction_right(self):<DEDENT> | return self._callbacks.get(DIRECTION_RIGHT)<EOL> | The function to be called when the joystick is pushed right. The
function can either take a parameter which will be the `InputEvent`
tuple that has occurred, or the function can take no parameters at all.
Assign `None` to prevent this event from being fired. | f13466:c0:m18 |
@property<EOL><INDENT>def direction_middle(self):<DEDENT> | return self._callbacks.get(DIRECTION_MIDDLE)<EOL> | The function to be called when the joystick middle click is pressed. The
function can either take a parameter which will be the `InputEvent` tuple
that has occurred, or the function can take no parameters at all.
Assign `None` to prevent this event from being fired. | f13466:c0:m20 |
@property<EOL><INDENT>def direction_any(self):<DEDENT> | return self._callbacks.get('<STR_LIT:*>')<EOL> | The function to be called when the joystick is used. The function
can either take a parameter which will be the `InputEvent` tuple that
has occurred, or the function can take no parameters at all.
This event will always be called *after* events associated with a
specific action. Assign `None` to prevent this event from being fired. | f13466:c0:m22 |
def _load_text_assets(self, text_image_file, text_file): | text_pixels = self.load_image(text_image_file, False)<EOL>with open(text_file, '<STR_LIT:r>') as f:<EOL><INDENT>loaded_text = f.read()<EOL><DEDENT>self._text_dict = {}<EOL>for index, s in enumerate(loaded_text):<EOL><INDENT>start = index * <NUM_LIT><EOL>end = start + <NUM_LIT><EOL>char = text_pixels[start:end]<EOL>self._text_dict[s] = char<EOL><DEDENT> | Internal. Builds a character indexed dictionary of pixels used by the
show_message function below | f13467:c0:m1 |
def _trim_whitespace(self, char): | psum = lambda x: sum(sum(x, []))<EOL>if psum(char) > <NUM_LIT:0>:<EOL><INDENT>is_empty = True<EOL>while is_empty: <EOL><INDENT>row = char[<NUM_LIT:0>:<NUM_LIT:8>]<EOL>is_empty = psum(row) == <NUM_LIT:0><EOL>if is_empty:<EOL><INDENT>del char[<NUM_LIT:0>:<NUM_LIT:8>]<EOL><DEDENT><DEDENT>is_empty = True<EOL>while is_empty: <EOL><INDENT>row = char[-<NUM_LIT:8>:]<EOL>is_empty = psum(row) == <NUM_LIT:0><EOL>if is_empty:<EOL><INDENT>del char[-<NUM_LIT:8>:]<EOL><DEDENT><DEDENT><DEDENT>return char<EOL> | Internal. Trims white space pixels from the front and back of loaded
text characters | f13467:c0:m2 |
def _get_settings_file(self, imu_settings_file): | ini_file = '<STR_LIT>' % imu_settings_file<EOL>home_dir = pwd.getpwuid(os.getuid())[<NUM_LIT:5>]<EOL>home_path = os.path.join(home_dir, self.SETTINGS_HOME_PATH)<EOL>if not os.path.exists(home_path):<EOL><INDENT>os.makedirs(home_path)<EOL><DEDENT>home_file = os.path.join(home_path, ini_file)<EOL>home_exists = os.path.isfile(home_file)<EOL>system_file = os.path.join('<STR_LIT>', ini_file)<EOL>system_exists = os.path.isfile(system_file)<EOL>if system_exists and not home_exists:<EOL><INDENT>shutil.copyfile(system_file, home_file)<EOL><DEDENT>return RTIMU.Settings(os.path.join(home_path, imu_settings_file))<EOL> | Internal. Logic to check for a system wide RTIMU ini file. This is
copied to the home folder if one is not already found there. | f13467:c0:m3 |
def _get_fb_device(self): | device = None<EOL>for fb in glob.glob('<STR_LIT>'):<EOL><INDENT>name_file = os.path.join(fb, '<STR_LIT:name>')<EOL>if os.path.isfile(name_file):<EOL><INDENT>with open(name_file, '<STR_LIT:r>') as f:<EOL><INDENT>name = f.read()<EOL><DEDENT>if name.strip() == self.SENSE_HAT_FB_NAME:<EOL><INDENT>fb_device = fb.replace(os.path.dirname(fb), '<STR_LIT>')<EOL>if os.path.exists(fb_device):<EOL><INDENT>device = fb_device<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return device<EOL> | Internal. Finds the correct frame buffer device for the sense HAT
and returns its /dev name. | f13467:c0:m4 |
def set_rotation(self, r=<NUM_LIT:0>, redraw=True): | if r in self._pix_map.keys():<EOL><INDENT>if redraw:<EOL><INDENT>pixel_list = self.get_pixels()<EOL><DEDENT>self._rotation = r<EOL>if redraw:<EOL><INDENT>self.set_pixels(pixel_list)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT> | Sets the LED matrix rotation for viewing, adjust if the Pi is upside
down or sideways. 0 is with the Pi HDMI port facing downwards | f13467:c0:m8 |
def _pack_bin(self, pix): | r = (pix[<NUM_LIT:0>] >> <NUM_LIT:3>) & <NUM_LIT><EOL>g = (pix[<NUM_LIT:1>] >> <NUM_LIT:2>) & <NUM_LIT><EOL>b = (pix[<NUM_LIT:2>] >> <NUM_LIT:3>) & <NUM_LIT><EOL>bits16 = (r << <NUM_LIT:11>) + (g << <NUM_LIT:5>) + b<EOL>return struct.pack('<STR_LIT:H>', bits16)<EOL> | Internal. Encodes python list [R,G,B] into 16 bit RGB565 | f13467:c0:m9 |
def _unpack_bin(self, packed): | output = struct.unpack('<STR_LIT:H>', packed)<EOL>bits16 = output[<NUM_LIT:0>]<EOL>r = (bits16 & <NUM_LIT>) >> <NUM_LIT:11><EOL>g = (bits16 & <NUM_LIT>) >> <NUM_LIT:5><EOL>b = (bits16 & <NUM_LIT>)<EOL>return [int(r << <NUM_LIT:3>), int(g << <NUM_LIT:2>), int(b << <NUM_LIT:3>)]<EOL> | Internal. Decodes 16 bit RGB565 into python list [R,G,B] | f13467:c0:m10 |
def flip_h(self, redraw=True): | pixel_list = self.get_pixels()<EOL>flipped = []<EOL>for i in range(<NUM_LIT:8>):<EOL><INDENT>offset = i * <NUM_LIT:8><EOL>flipped.extend(reversed(pixel_list[offset:offset + <NUM_LIT:8>]))<EOL><DEDENT>if redraw:<EOL><INDENT>self.set_pixels(flipped)<EOL><DEDENT>return flipped<EOL> | Flip LED matrix horizontal | f13467:c0:m11 |
def flip_v(self, redraw=True): | pixel_list = self.get_pixels()<EOL>flipped = []<EOL>for i in reversed(range(<NUM_LIT:8>)):<EOL><INDENT>offset = i * <NUM_LIT:8><EOL>flipped.extend(pixel_list[offset:offset + <NUM_LIT:8>])<EOL><DEDENT>if redraw:<EOL><INDENT>self.set_pixels(flipped)<EOL><DEDENT>return flipped<EOL> | Flip LED matrix vertical | f13467:c0:m12 |
def set_pixels(self, pixel_list): | if len(pixel_list) != <NUM_LIT:64>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for index, pix in enumerate(pixel_list):<EOL><INDENT>if len(pix) != <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>' % index)<EOL><DEDENT>for element in pix:<EOL><INDENT>if element > <NUM_LIT:255> or element < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % index)<EOL><DEDENT><DEDENT><DEDENT>with open(self._fb_device, '<STR_LIT:wb>') as f:<EOL><INDENT>map = self._pix_map[self._rotation]<EOL>for index, pix in enumerate(pixel_list):<EOL><INDENT>f.seek(map[index // <NUM_LIT:8>][index % <NUM_LIT:8>] * <NUM_LIT:2>) <EOL>f.write(self._pack_bin(pix))<EOL><DEDENT><DEDENT> | Accepts a list containing 64 smaller lists of [R,G,B] pixels and
updates the LED matrix. R,G,B elements must intergers between 0
and 255 | f13467:c0:m13 |
def get_pixels(self): | pixel_list = []<EOL>with open(self._fb_device, '<STR_LIT:rb>') as f:<EOL><INDENT>map = self._pix_map[self._rotation]<EOL>for row in range(<NUM_LIT:8>):<EOL><INDENT>for col in range(<NUM_LIT:8>):<EOL><INDENT>f.seek(map[row][col] * <NUM_LIT:2>) <EOL>pixel_list.append(self._unpack_bin(f.read(<NUM_LIT:2>)))<EOL><DEDENT><DEDENT><DEDENT>return pixel_list<EOL> | Returns a list containing 64 smaller lists of [R,G,B] pixels
representing what is currently displayed on the LED matrix | f13467:c0:m14 |
def set_pixel(self, x, y, *args): | pixel_error = '<STR_LIT>'<EOL>if len(args) == <NUM_LIT:1>:<EOL><INDENT>pixel = args[<NUM_LIT:0>]<EOL>if len(pixel) != <NUM_LIT:3>:<EOL><INDENT>raise ValueError(pixel_error)<EOL><DEDENT><DEDENT>elif len(args) == <NUM_LIT:3>:<EOL><INDENT>pixel = args<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(pixel_error)<EOL><DEDENT>if x > <NUM_LIT:7> or x < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if y > <NUM_LIT:7> or y < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for element in pixel:<EOL><INDENT>if element > <NUM_LIT:255> or element < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>with open(self._fb_device, '<STR_LIT:wb>') as f:<EOL><INDENT>map = self._pix_map[self._rotation]<EOL>f.seek(map[y][x] * <NUM_LIT:2>) <EOL>f.write(self._pack_bin(pixel))<EOL><DEDENT> | Updates the single [R,G,B] pixel specified by x and y on the LED matrix
Top left = 0,0 Bottom right = 7,7
e.g. ap.set_pixel(x, y, r, g, b)
or
pixel = (r, g, b)
ap.set_pixel(x, y, pixel) | f13467:c0:m15 |
def get_pixel(self, x, y): | if x > <NUM_LIT:7> or x < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if y > <NUM_LIT:7> or y < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>pix = None<EOL>with open(self._fb_device, '<STR_LIT:rb>') as f:<EOL><INDENT>map = self._pix_map[self._rotation]<EOL>f.seek(map[y][x] * <NUM_LIT:2>) <EOL>pix = self._unpack_bin(f.read(<NUM_LIT:2>))<EOL><DEDENT>return pix<EOL> | Returns a list of [R,G,B] representing the pixel specified by x and y
on the LED matrix. Top left = 0,0 Bottom right = 7,7 | f13467:c0:m16 |
def load_image(self, file_path, redraw=True): | if not os.path.exists(file_path):<EOL><INDENT>raise IOError('<STR_LIT>' % file_path)<EOL><DEDENT>img = Image.open(file_path).convert('<STR_LIT>')<EOL>pixel_list = list(map(list, img.getdata()))<EOL>if redraw:<EOL><INDENT>self.set_pixels(pixel_list)<EOL><DEDENT>return pixel_list<EOL> | Accepts a path to an 8 x 8 image file and updates the LED matrix with
the image | f13467:c0:m17 |
def clear(self, *args): | black = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>) <EOL>if len(args) == <NUM_LIT:0>:<EOL><INDENT>colour = black<EOL><DEDENT>elif len(args) == <NUM_LIT:1>:<EOL><INDENT>colour = args[<NUM_LIT:0>]<EOL><DEDENT>elif len(args) == <NUM_LIT:3>:<EOL><INDENT>colour = args<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.set_pixels([colour] * <NUM_LIT:64>)<EOL> | Clears the LED matrix with a single colour, default is black / off
e.g. ap.clear()
or
ap.clear(r, g, b)
or
colour = (r, g, b)
ap.clear(colour) | f13467:c0:m18 |
def _get_char_pixels(self, s): | if len(s) == <NUM_LIT:1> and s in self._text_dict.keys():<EOL><INDENT>return list(self._text_dict[s])<EOL><DEDENT>else:<EOL><INDENT>return list(self._text_dict['<STR_LIT:?>'])<EOL><DEDENT> | Internal. Safeguards the character indexed dictionary for the
show_message function below | f13467:c0:m19 |
def show_message(<EOL>self,<EOL>text_string,<EOL>scroll_speed=<NUM_LIT>,<EOL>text_colour=[<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>],<EOL>back_colour=[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]<EOL>): | <EOL>previous_rotation = self._rotation<EOL>self._rotation -= <NUM_LIT><EOL>if self._rotation < <NUM_LIT:0>:<EOL><INDENT>self._rotation = <NUM_LIT><EOL><DEDENT>dummy_colour = [None, None, None]<EOL>string_padding = [dummy_colour] * <NUM_LIT:64><EOL>letter_padding = [dummy_colour] * <NUM_LIT:8><EOL>scroll_pixels = []<EOL>scroll_pixels.extend(string_padding)<EOL>for s in text_string:<EOL><INDENT>scroll_pixels.extend(self._trim_whitespace(self._get_char_pixels(s)))<EOL>scroll_pixels.extend(letter_padding)<EOL><DEDENT>scroll_pixels.extend(string_padding)<EOL>coloured_pixels = [<EOL>text_colour if pixel == [<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>] else back_colour<EOL>for pixel in scroll_pixels<EOL>]<EOL>scroll_length = len(coloured_pixels) // <NUM_LIT:8><EOL>for i in range(scroll_length - <NUM_LIT:8>):<EOL><INDENT>start = i * <NUM_LIT:8><EOL>end = start + <NUM_LIT:64><EOL>self.set_pixels(coloured_pixels[start:end])<EOL>time.sleep(scroll_speed)<EOL><DEDENT>self._rotation = previous_rotation<EOL> | Scrolls a string of text across the LED matrix using the specified
speed and colours | f13467:c0:m20 |
def show_letter(<EOL>self,<EOL>s,<EOL>text_colour=[<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>],<EOL>back_colour=[<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>]<EOL>): | if len(s) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>previous_rotation = self._rotation<EOL>self._rotation -= <NUM_LIT><EOL>if self._rotation < <NUM_LIT:0>:<EOL><INDENT>self._rotation = <NUM_LIT><EOL><DEDENT>dummy_colour = [None, None, None]<EOL>pixel_list = [dummy_colour] * <NUM_LIT:8><EOL>pixel_list.extend(self._get_char_pixels(s))<EOL>pixel_list.extend([dummy_colour] * <NUM_LIT:16>)<EOL>coloured_pixels = [<EOL>text_colour if pixel == [<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>] else back_colour<EOL>for pixel in pixel_list<EOL>]<EOL>self.set_pixels(coloured_pixels)<EOL>self._rotation = previous_rotation<EOL> | Displays a single text character on the LED matrix using the specified
colours | f13467:c0:m21 |
def gamma_reset(self): | with open(self._fb_device) as f:<EOL><INDENT>fcntl.ioctl(f, self.SENSE_HAT_FB_FBIORESET_GAMMA, self.SENSE_HAT_FB_GAMMA_DEFAULT)<EOL><DEDENT> | Resets the LED matrix gamma correction to default | f13467:c0:m24 |
def _init_humidity(self): | if not self._humidity_init:<EOL><INDENT>self._humidity_init = self._humidity.humidityInit()<EOL>if not self._humidity_init:<EOL><INDENT>raise OSError('<STR_LIT>')<EOL><DEDENT><DEDENT> | Internal. Initialises the humidity sensor via RTIMU | f13467:c0:m27 |
def _init_pressure(self): | if not self._pressure_init:<EOL><INDENT>self._pressure_init = self._pressure.pressureInit()<EOL>if not self._pressure_init:<EOL><INDENT>raise OSError('<STR_LIT>')<EOL><DEDENT><DEDENT> | Internal. Initialises the pressure sensor via RTIMU | f13467:c0:m28 |
def get_humidity(self): | self._init_humidity() <EOL>humidity = <NUM_LIT:0><EOL>data = self._humidity.humidityRead()<EOL>if (data[<NUM_LIT:0>]): <EOL><INDENT>humidity = data[<NUM_LIT:1>]<EOL><DEDENT>return humidity<EOL> | Returns the percentage of relative humidity | f13467:c0:m29 |
def get_temperature_from_humidity(self): | self._init_humidity() <EOL>temp = <NUM_LIT:0><EOL>data = self._humidity.humidityRead()<EOL>if (data[<NUM_LIT:2>]): <EOL><INDENT>temp = data[<NUM_LIT:3>]<EOL><DEDENT>return temp<EOL> | Returns the temperature in Celsius from the humidity sensor | f13467:c0:m31 |
def get_temperature_from_pressure(self): | self._init_pressure() <EOL>temp = <NUM_LIT:0><EOL>data = self._pressure.pressureRead()<EOL>if (data[<NUM_LIT:2>]): <EOL><INDENT>temp = data[<NUM_LIT:3>]<EOL><DEDENT>return temp<EOL> | Returns the temperature in Celsius from the pressure sensor | f13467:c0:m32 |
def get_temperature(self): | return self.get_temperature_from_humidity()<EOL> | Returns the temperature in Celsius | f13467:c0:m33 |
def get_pressure(self): | self._init_pressure() <EOL>pressure = <NUM_LIT:0><EOL>data = self._pressure.pressureRead()<EOL>if (data[<NUM_LIT:0>]): <EOL><INDENT>pressure = data[<NUM_LIT:1>]<EOL><DEDENT>return pressure<EOL> | Returns the pressure in Millibars | f13467:c0:m36 |
def _init_imu(self): | if not self._imu_init:<EOL><INDENT>self._imu_init = self._imu.IMUInit()<EOL>if self._imu_init:<EOL><INDENT>self._imu_poll_interval = self._imu.IMUGetPollInterval() * <NUM_LIT><EOL>self.set_imu_config(True, True, True)<EOL><DEDENT>else:<EOL><INDENT>raise OSError('<STR_LIT>')<EOL><DEDENT><DEDENT> | Internal. Initialises the IMU sensor via RTIMU | f13467:c0:m38 |
def set_imu_config(self, compass_enabled, gyro_enabled, accel_enabled): | <EOL>self._init_imu() <EOL>if (not isinstance(compass_enabled, bool)<EOL>or not isinstance(gyro_enabled, bool)<EOL>or not isinstance(accel_enabled, bool)):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if self._compass_enabled != compass_enabled:<EOL><INDENT>self._compass_enabled = compass_enabled<EOL>self._imu.setCompassEnable(self._compass_enabled)<EOL><DEDENT>if self._gyro_enabled != gyro_enabled:<EOL><INDENT>self._gyro_enabled = gyro_enabled<EOL>self._imu.setGyroEnable(self._gyro_enabled)<EOL><DEDENT>if self._accel_enabled != accel_enabled:<EOL><INDENT>self._accel_enabled = accel_enabled<EOL>self._imu.setAccelEnable(self._accel_enabled)<EOL><DEDENT> | Enables and disables the gyroscope, accelerometer and/or magnetometer
input to the orientation functions | f13467:c0:m39 |
def _read_imu(self): | self._init_imu() <EOL>attempts = <NUM_LIT:0><EOL>success = False<EOL>while not success and attempts < <NUM_LIT:3>:<EOL><INDENT>success = self._imu.IMURead()<EOL>attempts += <NUM_LIT:1><EOL>time.sleep(self._imu_poll_interval)<EOL><DEDENT>return success<EOL> | Internal. Tries to read the IMU sensor three times before giving up | f13467:c0:m40 |
def _get_raw_data(self, is_valid_key, data_key): | result = None<EOL>if self._read_imu():<EOL><INDENT>data = self._imu.getIMUData()<EOL>if data[is_valid_key]:<EOL><INDENT>raw = data[data_key]<EOL>result = {<EOL>'<STR_LIT:x>': raw[<NUM_LIT:0>],<EOL>'<STR_LIT:y>': raw[<NUM_LIT:1>],<EOL>'<STR_LIT:z>': raw[<NUM_LIT:2>]<EOL>}<EOL><DEDENT><DEDENT>return result<EOL> | Internal. Returns the specified raw data from the IMU when valid | f13467:c0:m41 |
def get_orientation_radians(self): | raw = self._get_raw_data('<STR_LIT>', '<STR_LIT>')<EOL>if raw is not None:<EOL><INDENT>raw['<STR_LIT>'] = raw.pop('<STR_LIT:x>')<EOL>raw['<STR_LIT>'] = raw.pop('<STR_LIT:y>')<EOL>raw['<STR_LIT>'] = raw.pop('<STR_LIT:z>')<EOL>self._last_orientation = raw<EOL><DEDENT>return deepcopy(self._last_orientation)<EOL> | Returns a dictionary object to represent the current orientation in
radians using the aircraft principal axes of pitch, roll and yaw | f13467:c0:m42 |
def get_orientation_degrees(self): | orientation = self.get_orientation_radians()<EOL>for key, val in orientation.items():<EOL><INDENT>deg = math.degrees(val) <EOL>orientation[key] = deg + <NUM_LIT> if deg < <NUM_LIT:0> else deg<EOL><DEDENT>return orientation<EOL> | Returns a dictionary object to represent the current orientation
in degrees, 0 to 360, using the aircraft principal axes of
pitch, roll and yaw | f13467:c0:m44 |
def get_compass(self): | self.set_imu_config(True, False, False)<EOL>orientation = self.get_orientation_degrees()<EOL>if type(orientation) is dict and '<STR_LIT>' in orientation.keys():<EOL><INDENT>return orientation['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | Gets the direction of North from the magnetometer in degrees | f13467:c0:m47 |
def get_compass_raw(self): | raw = self._get_raw_data('<STR_LIT>', '<STR_LIT>')<EOL>if raw is not None:<EOL><INDENT>self._last_compass_raw = raw<EOL><DEDENT>return deepcopy(self._last_compass_raw)<EOL> | Magnetometer x y z raw data in uT (micro teslas) | f13467:c0:m49 |
def get_gyroscope(self): | self.set_imu_config(False, True, False)<EOL>return self.get_orientation_degrees()<EOL> | Gets the orientation in degrees from the gyroscope only | f13467:c0:m51 |
def get_gyroscope_raw(self): | raw = self._get_raw_data('<STR_LIT>', '<STR_LIT>')<EOL>if raw is not None:<EOL><INDENT>self._last_gyro_raw = raw<EOL><DEDENT>return deepcopy(self._last_gyro_raw)<EOL> | Gyroscope x y z raw data in radians per second | f13467:c0:m54 |
def get_accelerometer(self): | self.set_imu_config(False, False, True)<EOL>return self.get_orientation_degrees()<EOL> | Gets the orientation in degrees from the accelerometer only | f13467:c0:m57 |
def get_accelerometer_raw(self): | raw = self._get_raw_data('<STR_LIT>', '<STR_LIT>')<EOL>if raw is not None:<EOL><INDENT>self._last_accel_raw = raw<EOL><DEDENT>return deepcopy(self._last_accel_raw)<EOL> | Accelerometer x y z raw data in Gs | f13467:c0:m60 |
def print_table(table): | col_width = [max(len(str(x)) for x in col) for col in zip(*table)]<EOL>for line in table:<EOL><INDENT>print("<STR_LIT>" + "<STR_LIT>".join("<STR_LIT>".format(str(x), col_width[i])<EOL>for i, x in enumerate(line)) + "<STR_LIT>")<EOL><DEDENT> | Helper function for printing tables to screen.
:param table: List of tuples where each tuple contains the contents of a row,
and each entry in the tuple is the contents of a cell in that row.
:type table: List of tuples. | f13479:m0 |
def get_mean(list_in_question): | return sum(list_in_question) / float(len(list_in_question))<EOL> | Computes the mean of a list of numbers.
:param list list_in_question: list of numbers
:returns: mean of the list of numbers
:rtype : float | f13479:m1 |
def get_duration_measures(source_file_path,<EOL>output_path=None,<EOL>phonemic=False,<EOL>semantic=False,<EOL>quiet=False,<EOL>similarity_file = None,<EOL>threshold = None): | <EOL>args = Args()<EOL>args.output_path = output_path<EOL>args.phonemic = phonemic<EOL>args.semantic = semantic<EOL>args.source_file_path = source_file_path<EOL>args.quiet = quiet<EOL>args.similarity_file = similarity_file<EOL>args.threshold = threshold<EOL>args = validate_arguments(args)<EOL>if args.phonemic:<EOL><INDENT>response_category = args.phonemic<EOL>output_prefix = os.path.basename(args.source_file_path).split('<STR_LIT:.>')[<NUM_LIT:0>] + "<STR_LIT>" + args.phonemic<EOL><DEDENT>elif args.semantic:<EOL><INDENT>response_category = args.semantic<EOL>output_prefix = os.path.basename(args.source_file_path).split('<STR_LIT:.>')[<NUM_LIT:0>] + "<STR_LIT>" + args.semantic<EOL><DEDENT>else:<EOL><INDENT>response_category = "<STR_LIT>"<EOL>output_prefix = "<STR_LIT>"<EOL><DEDENT>if args.output_path:<EOL><INDENT>target_file_path = os.path.join(args.output_path, output_prefix + '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>target_file_path = False<EOL><DEDENT>engine = VFClustEngine(response_category=response_category,<EOL>response_file_path=args.source_file_path,<EOL>target_file_path=target_file_path,<EOL>quiet = args.quiet,<EOL>similarity_file = args.similarity_file,<EOL>threshold = args.threshold<EOL>)<EOL>return dict(engine.measures)<EOL> | Parses input arguments and runs clustering algorithm.
:param source_file_path: Required. Location of the .csv or .TextGrid file to be
analyzed.
:param output_path: Path to which to write the resultant csv file. If left None,
path will be set to the source_file_path. If set to False, no file will be
written.
:param phonemic: The letter used for phonetic clustering. Note: should be False if
semantic clustering is being used.
:param semantic: The word category used for semantic clustering. Note: should be
False if phonetic clustering is being used.
:param quiet: Set to True if you want to suppress output to the screen during processing.
:param similarity_file (optional): When doing semantic processing, this is the path of
a file containing custom term similarity scores that will be used for clustering.
If a custom file is used, the default LSA-based clustering will not be performed.
:param threshold (optional): When doing semantic processing, this threshold is used
in conjunction with a custom similarity file. The value is used as a semantic
similarity cutoff in clustering. This argument is required if a custom similarity
file is specified. This argument can also be used to override the built-in
cluster/chain thresholds.
:return data: A dictionary of measures derived by clustering the input response. | f13479:m2 |
def validate_arguments(args): | <EOL>print()<EOL>print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>semantic_tests = ["<STR_LIT>", "<STR_LIT>"]<EOL>phonemic_tests = ["<STR_LIT:a>", "<STR_LIT:p>", "<STR_LIT:s>", "<STR_LIT:f>"]<EOL>if args.similarity_file:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>args.semantic = "<STR_LIT>"<EOL><DEDENT>if args.threshold:<EOL><INDENT>try:<EOL><INDENT>args.threshold = float(args.threshold)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise VFClustException('<STR_LIT>')<EOL><DEDENT><DEDENT>if not (args.source_file_path.lower().endswith('<STR_LIT>') or args.source_file_path.lower().endswith('<STR_LIT>')):<EOL><INDENT>raise VFClustException('<STR_LIT>' + args.source_file_path.lower())<EOL><DEDENT>if not os.path.isfile(args.source_file_path):<EOL><INDENT>raise VFClustException('<STR_LIT>')<EOL><DEDENT>if args.output_path == None:<EOL><INDENT>args.output_path = args.source_path<EOL><DEDENT>elif args.output_path == False:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if len(args.output_path) == <NUM_LIT:0>:<EOL><INDENT>args.output_path = os.path.abspath(os.path.dirname(args.source_file_path))<EOL><DEDENT>try:<EOL><INDENT>if not os.path.isdir(args.output_path):<EOL><INDENT>os.mkdir(args.output_path)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>print("<STR_LIT>""<STR_LIT>""<STR_LIT>""<STR_LIT>")<EOL><DEDENT><DEDENT>if (args.semantic): args.semantic = args.semantic.lower()<EOL>if (args.phonemic): args.phonemic = args.phonemic.lower()<EOL>if not (args.semantic or args.phonemic):<EOL><INDENT>print("<STR_LIT>", args.semantic, args.similarity_file)<EOL>raise VFClustException(<EOL>'''<STR_LIT>''')<EOL><DEDENT>if args.semantic and args.semantic not in semantic_tests:<EOL><INDENT>raise VFClustException("<STR_LIT>" + "<STR_LIT:U+002C>".join(semantic_tests) + "<STR_LIT>""<STR_LIT>" + args.semantic)<EOL><DEDENT>if args.phonemic and args.phonemic not in phonemic_tests:<EOL><INDENT>raise VFClustException("<STR_LIT>" + "<STR_LIT:U+002C>".join(phonemic_tests) + "<STR_LIT>""<STR_LIT>" + args.phonemic)<EOL><DEDENT>if (args.phonemic and args.semantic):<EOL><INDENT>raise VFClustException("<STR_LIT>")<EOL><DEDENT>args.source_file_path = os.path.abspath(args.source_file_path)<EOL>if args.output_path:<EOL><INDENT>args.output_path = os.path.abspath(args.output_path)<EOL><DEDENT>if args.similarity_file: <EOL><INDENT>if not os.path.isfile(args.similarity_file):<EOL><INDENT>raise VFClustException('<STR_LIT>')<EOL><DEDENT>if not args.threshold:<EOL><INDENT>raise VFClustException('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>args.threshold = float(args.threshold)<EOL><DEDENT>except:<EOL><INDENT>raise VFClustException('<STR_LIT>')<EOL><DEDENT>args.similarity_file = os.path.abspath(args.similarity_file)<EOL><DEDENT>print("<STR_LIT>")<EOL>print()<EOL>print("<STR_LIT>")<EOL>print_table([(k, str(vars(args)[k])) for k in vars(args)])<EOL>return args<EOL> | Makes sure arguments are valid, specified files exist, etc. | f13479:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.