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>castar...
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 trunca...
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>retur...
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...
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:<E...
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...
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>'<...
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 i...
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>'):<...
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>@c...
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>...
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 ...
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>...
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...
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 ro...
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...
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...
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 categ...
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><I...
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()<E...
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 th...
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><DEDE...
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,...
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 fro...
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...
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_empt...
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.is...
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....
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>:<EO...
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><D...
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...
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] *...
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>')...
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 = []<EO...
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>pi...
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...
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><IND...
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 wi...
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.thresh...
Makes sure arguments are valid, specified files exist, etc.
f13479:m3