code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Lookup a config field and return its value, first checking the route.config, then route.app.config.''' for conf in (self.config, self.app.conifg): if key in conf: return conf[key] return default
def get_config(self, key, default=None)
Lookup a config field and return its value, first checking the route.config, then route.app.config.
9.13737
3.534473
2.585214
''' Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request reg...
def add_hook(self, name, func)
Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request regardless of i...
6.895304
1.993617
3.458691
''' Remove a callback from a hook. ''' if name in self._hooks and func in self._hooks[name]: self._hooks[name].remove(func) return True
def remove_hook(self, name, func)
Remove a callback from a hook.
3.080582
3.342945
0.921517
''' Trigger a hook and return a list of results. ''' return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
def trigger_hook(self, __name, *args, **kwargs)
Trigger a hook and return a list of results.
6.279463
6.063673
1.035587
def decorator(func): self.add_hook(name, func) return func return decorator
def hook(self, name)
Return a decorator that attaches a callback to a hook. See :meth:`add_hook` for details.
3.134796
3.364015
0.931861
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an inst...
def mount(self, prefix, app, **options)
Mount an application (:class:`Bottle` or plain WSGI) to a specific URL prefix. Example:: root_app.mount('/admin/', admin_app) :param prefix: path prefix or `mount-point`. If it ends in a slash, that slash is mandatory. :param app: an instance of :cla...
4.29534
2.928246
1.466864
''' Merge the routes of another :class:`Bottle` application or a list of :class:`Route` objects into this application. The routes keep their 'owner', meaning that the :data:`Route.app` attribute is not changed. ''' if isinstance(routes, Bottle): routes = r...
def merge(self, routes)
Merge the routes of another :class:`Bottle` application or a list of :class:`Route` objects into this application. The routes keep their 'owner', meaning that the :data:`Route.app` attribute is not changed.
6.521138
1.845026
3.534442
''' Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected. ''' if route is None: routes = self.routes elif isinstance(route, Route): routes = [route] else: routes = [self.rou...
def reset(self, route=None)
Reset all routes (force plugins to be re-applied) and clear all caches. If an ID or route object is given, only that specific route is affected.
6.272878
2.953656
2.123767
''' Add a route object, but do not change the :data:`Route.app` attribute.''' self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare()
def add_route(self, route)
Add a route object, but do not change the :data:`Route.app` attribute.
9.43348
4.388918
2.149386
# Empty output is done here if not out: if 'Content-Length' not in response: response['Content-Length'] = 0 return [] # Join lists of byte or unicode strings. Mixed lists are NOT supported if isinstance(out, (tuple, list))\ and is...
def _cast(self, out, peek=None)
Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes
3.912827
3.694203
1.05918
try: out = self._cast(self._handle(environ)) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_r...
def wsgi(self, environ, start_response)
The bottle WSGI-interface.
3.051805
3.031854
1.00658
forms = FormsDict() for name, item in self.POST.allitems(): if not isinstance(item, FileUpload): forms[name] = item return forms
def forms(self)
Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is returned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`.
7.429091
4.903422
1.515083
params = FormsDict() for key, value in self.query.allitems(): params[key] = value for key, value in self.forms.allitems(): params[key] = value return params
def params(self)
A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.
4.196754
2.40275
1.746646
files = FormsDict() for name, item in self.POST.allitems(): if isinstance(item, FileUpload): files[name] = item return files
def files(self)
File uploads parsed from `multipart/form-data` encoded POST or PUT request body. The values are instances of :class:`FileUpload`.
7.724729
6.414871
1.204191
''' If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. ''' ctype = self.environ.get('CONTENT_TYPE', '').lower().sp...
def json(self)
If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.
4.913768
2.235601
2.197963
post = FormsDict() # We default to application/x-www-form-urlencoded for everything that # is not multipart and take the fast path (also: 3.1 workaround) if not self.content_type.startswith('multipart/'): pairs = _parse_qsl(tonat(self._get_body_string(), 'latin1')) ...
def POST(self)
The values of :attr:`forms` and :attr:`files` combined into a single :class:`FormsDict`. Values are either strings (form values) or instances of :class:`cgi.FieldStorage` (file uploads).
4.850572
4.483363
1.081905
''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple. The tuple contains (scheme, host, path, query_string and fragment), but the fragment is always empty because it is not visible to the server. ''' env = self.environ http = env.get('HTTP_X_FO...
def urlparts(self)
The :attr:`url` string as an :class:`urlparse.SplitResult` tuple. The tuple contains (scheme, host, path, query_string and fragment), but the fragment is always empty because it is not visible to the server.
3.006649
2.081186
1.444681
''' Returns a copy of self. ''' cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() ...
def copy(self, cls=None)
Returns a copy of self.
3.107872
3.213817
0.967034
''' Create a new response header, replacing any previously defined headers with the same name. ''' self._headers[_hkey(name)] = [str(value)]
def set_header(self, name, value)
Create a new response header, replacing any previously defined headers with the same name.
10.085917
5.238759
1.925249
''' WSGI conform list of (header, value) tuples. ''' out = [] headers = list(self._headers.items()) if 'Content-Type' not in self._headers: headers.append(('Content-Type', [self.default_content_type])) if self._status_code in self.bad_headers: bad_headers ...
def headerlist(self)
WSGI conform list of (header, value) tuples.
3.066374
2.594509
1.181871
if 'charset=' in self.content_type: return self.content_type.split('charset=')[-1].split(';')[0].strip() return default
def charset(self, default='UTF-8')
Return the charset specified in the content-type header (default: utf8).
3.131259
2.37399
1.318986
''' Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. ...
def set_cookie(self, name, value, secret=None, **options)
Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. A...
4.193153
1.525524
2.748664
''' Returns a copy with all keys and values de- or recoded to match :attr:`input_encoding`. Some libraries (e.g. WTForms) want a unicode dictionary. ''' copy = FormsDict() enc = copy.input_encoding = encoding or self.input_encoding copy.recode_unicode = False ...
def decode(self, encoding=None)
Returns a copy with all keys and values de- or recoded to match :attr:`input_encoding`. Some libraries (e.g. WTForms) want a unicode dictionary.
9.370241
3.335929
2.808885
''' Return the value as a unicode string, or the default. ''' try: return self._fix(self[name], encoding) except (UnicodeError, KeyError): return default
def getunicode(self, name, default=None, encoding=None)
Return the value as a unicode string, or the default.
6.176891
5.274115
1.171171
''' Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix). ''' conf = ConfigPars...
def load_config(self, filename)
Load values from an *.ini style config file. If the config file contains sections, their names are used as namespaces for the values within. The two special sections ``DEFAULT`` and ``bottle`` refer to the root namespace (no prefix).
5.158765
1.844942
2.796167
''' Import values from a dictionary structure. Nesting can be used to represent namespaces. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}}) {'name.space.key': 'value'} ''' stack = [(namespace, source)] while stack: prefix...
def load_dict(self, source, namespace='', make_namespaces=False)
Import values from a dictionary structure. Nesting can be used to represent namespaces. >>> ConfigDict().load_dict({'name': {'space': {'key': 'value'}}}) {'name.space.key': 'value'}
2.92609
2.013739
1.453063
''' Return the value of a meta field for a key. ''' return self._meta.get(key, {}).get(metafield, default)
def meta_get(self, key, metafield, default=None)
Return the value of a meta field for a key.
4.06922
4.137282
0.983549
''' Set the meta field for a key to a new value. This triggers the on-change handler for existing keys. ''' self._meta.setdefault(key, {})[metafield] = value if key in self: self[key] = self[key]
def meta_set(self, key, metafield, value)
Set the meta field for a key to a new value. This triggers the on-change handler for existing keys.
6.320916
2.975899
2.124036
''' Search for a resource and return an absolute file path, or `None`. The :attr:`path` list is searched in order. The first match is returend. Symlinks are followed. The result is cached to speed up future lookups. ''' if name not in self.cache or DEBUG: ...
def lookup(self, name)
Search for a resource and return an absolute file path, or `None`. The :attr:`path` list is searched in order. The first match is returend. Symlinks are followed. The result is cached to speed up future lookups.
4.201171
2.027472
2.072123
''' Find a resource and return a file object, or raise IOError. ''' fname = self.lookup(name) if not fname: raise IOError("Resource %r not found." % name) return self.opener(fname, mode=mode, *args, **kwargs)
def open(self, name, mode='r', *args, **kwargs)
Find a resource and return a file object, or raise IOError.
4.572617
3.37322
1.355565
''' Save file to disk or copy its content to an open file(-like) object. If *destination* is a directory, :attr:`filename` is added to the path. Existing files are not overwritten by default (IOError). :param destination: File path, directory or file(-like) object. ...
def save(self, destination, overwrite=False, chunk_size=2**16)
Save file to disk or copy its content to an open file(-like) object. If *destination* is a directory, :attr:`filename` is added to the path. Existing files are not overwritten by default (IOError). :param destination: File path, directory or file(-like) object. :param ov...
3.7896
1.71601
2.208379
env = {}; stdout = [] for dictarg in args: env.update(dictarg) env.update(kwargs) self.execute(stdout, env) return ''.join(stdout)
def render(self, *args, **kwargs)
Render the template using keyword arguments as local variables.
6.594427
6.60678
0.99813
rate_map = get_rates(map(itemgetter(1, 2), args_list)) value_map = {} for value, source, target in args_list: args = (value, source, target) if source == target: value_map[args] = value else: value_map[args] = value * rate_map[(source, target)] retur...
def convert_values(args_list)
convert_value in bulk. :param args_list: list of value, source, target currency pairs :return: map of converted values
3.392985
2.758277
1.23011
# If price currency and target currency is same # return given currency as is if source_currency == target_currency: return value rate = get_rate(source_currency, target_currency) return value * rate
def convert_value(value, source_currency, target_currency)
Converts the price of a currency to another one using exchange rates :param price: the price value :param type: decimal :param source_currency: source ISO-4217 currency code :param type: str :param target_currency: target ISO-4217 currency code :param type: str :returns: converted price ...
4.713858
5.881634
0.801454
# If price currency and target currency is same # return given currency as is value = convert_value(price.value, price.currency, currency) return Price(value, currency)
def convert(price, currency)
Shorthand function converts a price object instance of a source currency to target currency :param price: the price value :param type: decimal :param currency: target ISO-4217 currency code :param type: str :returns: converted price instance :rtype: ``Price``
9.412679
11.655186
0.807596
try: from django.utils.importlib import import_module module_name = '.'.join(class_path.split(".")[:-1]) mod = import_module(module_name) return getattr(mod, class_path.split(".")[-1]) except Exception, detail: raise ImportError(detail)
def import_class(class_path)
imports and returns given class string. :param class_path: Class path as string :type class_path: str :returns: Class that has given path :rtype: class :Example: >>> import_class('collections.OrderedDict').__name__ 'OrderedDict'
2.22326
2.498369
0.889885
if not objects: return import django.db.models from django.db import connections from django.db import transaction con = connections[using] model = objects[0].__class__ fields = [f for f in model._meta.fields if not isinstance(f, django.db.models.AutoField)] ...
def insert_many(objects, using="default")
Insert list of Django objects in one SQL query. Objects must be of the same Django model. Note that save is not called and signals on the model are not raised. Mostly from: http://people.iola.dk/olau/python/bulkops.py
2.122711
2.073069
1.023946
if not objects: return import django.db.models from django.db import connections from django.db import transaction con = connections[using] names = fields meta = objects[0]._meta fields = [f for f in meta.fields if not isinstance(f, django.db.models.AutoField...
def update_many(objects, fields=[], using="default")
Update list of Django objects in one SQL query, optionally only overwrite the given fields (as names, e.g. fields=["foo"]). Objects must be of the same Django model. Note that save is not called and signals on the model are not raised. Mostly from: http://people.iola.dk/olau/python/bulkops.py
2.609277
2.547305
1.024328
def decorator(obj): cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): now = datetime.now() key = str(args) + str(kwargs) if key not in cache: cache[key] = (obj(*args, **kwargs), now) value, last_u...
def memoize(ttl=None)
Cache the result of the function call with given args for until ttl (datetime.timedelta) expires.
1.818122
1.866255
0.974209
# We don't care about the date (only about the time) but Python # can substract only datetime objects, not time ones today = datetime.date.today() start_date = datetime.datetime.combine(today, start_time) end_date = datetime.datetime.combine(today, end_time) difference_minutes = (end_date ...
def round_to_quarter(start_time, end_time)
Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes.
3.665737
3.495433
1.048722
def call(*args, **kwargs): return_values = [] for timesheet in self: attr = getattr(timesheet, callback) if callable(attr): result = attr(*args, **kwargs) else: result = attr ...
def _timesheets_callback(self, callback)
Call a method on all the timesheets, aggregate the return values in a list and return it.
2.803087
2.499781
1.121333
if not parser: parser = TimesheetParser() timesheet_files = cls.get_files(file_pattern, nb_previous_files) timesheet_collection = cls() for file_path in timesheet_files: try: timesheet = Timesheet.load( file_path, par...
def load(cls, file_pattern, nb_previous_files=1, parser=None)
Load a collection of timesheet from the given `file_pattern`. `file_pattern` is a path to a timesheet file that will be expanded with :func:`datetime.date.strftime` and the current date. `nb_previous_files` is the number of other timesheets to load, depending on `file_pattern` this will result in either...
3.524428
3.308718
1.065194
date_units = ['m', 'Y'] smallest_unit = None if not from_date: from_date = datetime.date.today() for date_unit in date_units: if ('%' + date_unit) in file_pattern: smallest_unit = date_unit break if smallest_unit...
def get_files(cls, file_pattern, nb_previous_files, from_date=None)
Return an :class:`~taxi.utils.structures.OrderedSet` of file paths expanded from `filename`, with a maximum of `nb_previous_files`. See :func:`taxi.utils.file.expand_date` for more information about filename expansion. If `from_date` is set, it will be used as a starting date instead of the current date...
2.726587
2.39686
1.137566
popular_aliases = self.get_popular_aliases() template = ['# Recently used aliases:'] if popular_aliases: contents = '\n'.join(template + ['# ' + entry for entry, usage in popular_aliases]) else: contents = '' return contents
def get_new_timesheets_contents(self)
Return the initial text to be inserted in new timesheets.
7.040295
6.393534
1.101159
entries_list = self._timesheets_callback('entries')() return reduce(lambda x, y: x + y, entries_list)
def entries(self)
Return the entries (as a {date: entries} dict) of all timesheets in the collection.
12.889778
9.982553
1.291231
aliases_count_total = defaultdict(int) aliases_counts = self._timesheets_callback('get_popular_aliases')(*args, **kwargs) for aliases_count in aliases_counts: for alias, count in aliases_count: aliases_count_total[alias] += count sorted_aliases_coun...
def get_popular_aliases(self, *args, **kwargs)
Return the aggregated results of :meth:`Timesheet.get_popular_aliases`.
2.991123
2.566275
1.16555
matches = {'aliases': [], 'mappings': [], 'projects': []} projects_db = ctx.obj['projects_db'] matches = get_alias_matches(search, matches) matches = get_mapping_matches(search, matches, projects_db) matches = get_project_matches(search, matches, projects_db) ctx.obj['view'].show_command_...
def show(ctx, search)
Resolves any object passed to it (aliases, projects, etc). This will resolve the following: \b - Aliases (my_alias) - Mappings (123/456) - Project ids (123)
3.882269
3.853385
1.007496
try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) except ParseError as e: ctx.obj['view'].err(e) else: ctx.obj['view'].show_status( timesheet_collection.entries.filter( date, regroup=ctx.obj['settings']['regroup_entries'], ...
def status(ctx, date, f, pushed)
Shows the summary of what's going to be committed to the server.
5.9687
6.386143
0.934633
timesheet_collection = None autofill = not bool(file_to_edit) and previous_file == 0 if not file_to_edit: file_to_edit = ctx.obj['settings'].get_entries_file_path(False) # If the file was not specified and if it's the current file, autofill it if autofill: try: time...
def edit(ctx, file_to_edit, previous_file)
Opens your timesheet file in your favourite editor. The PREVIOUS_FILE argument can be used to specify which nth previous file to edit. A value of 1 will edit the previous file, 2 will edit the second-previous file, etc.
4.377621
4.403281
0.994173
return dict((v, k) for k, v in six.iteritems(self.aliases))
def get_reversed_aliases(self)
Return the reversed aliases dict. Instead of being in the form {'alias': mapping}, the dict is in the form {mapping: 'alias'}.
4.997903
3.8993
1.281744
def mapping_filter(key_item): key, item = key_item return ( (mapping is None or item.mapping == mapping or (mapping[1] is None and item.mapping is not None and item.mapping[0] == mapping[0])) and (backend is None or item.backe...
def filter_from_mapping(self, mapping, backend=None)
Return mappings that either exactly correspond to the given `mapping` tuple, or, if the second item of `mapping` is `None`, include mappings that only match the first item of `mapping` (useful to show all mappings for a given project).
3.780267
3.508747
1.077384
def alias_filter(key_item): key, item = key_item return ((alias is None or alias in key) and (backend is None or item.backend == backend)) items = six.moves.filter(alias_filter, six.iteritems(self)) aliases = collections.OrderedDict(sorted(...
def filter_from_alias(self, alias, backend=None)
Return aliases that start with the given `alias`, optionally filtered by backend.
4.330987
3.976116
1.089251
inactive_aliases = [] for (alias, mapping) in six.iteritems(aliases_database): # Ignore local aliases if mapping.mapping is None: continue project = ctx.obj['projects_db'].get(mapping.mapping[0], mapping.backend) if...
def clean_aliases(ctx, force_yes)
Removes aliases from your config file that point to inactive projects.
3.839773
3.704864
1.036414
url = 'https://pypi.python.org/pypi/{}/json'.format(plugin) try: resp = request.urlopen(url) except HTTPError as e: if e.code == 404: raise NameError("Plugin {} could not be found.".format(plugin)) else: raise ValueError( "Checking plugin...
def get_plugin_info(plugin)
Fetch information about the given package on PyPI and return it as a dict. If the package cannot be found on PyPI, :exc:`NameError` will be raised.
2.934845
2.823816
1.039319
return { # Strip the first five characters from the plugin name since all # plugins are expected to start with `taxi-` backend.dist.project_name[5:]: backend.dist.version for backend in backends_registry._entry_points.values() if backend.dist.project_name != 'taxi' }
def get_installed_plugins()
Return a dict {plugin_name: version} of installed plugins.
8.20129
7.464601
1.098691
plugins = plugins_registry.get_plugins() click.echo("\n".join( ["%s (%s)" % p for p in plugins.items()] ))
def list_(ctx)
Lists installed plugins.
6.287708
4.890055
1.285815
ensure_inside_venv(ctx) plugin_name = get_plugin_name(plugin) try: info = get_plugin_info(plugin_name) except NameError: echo_error("Plugin {} could not be found.".format(plugin)) sys.exit(1) except ValueError as e: echo_error("Unable to retrieve plugin info. " ...
def install(ctx, plugin)
Install the given plugin.
2.313465
2.299786
1.005948
ensure_inside_venv(ctx) if plugin not in get_installed_plugins(): echo_error("Plugin {} does not seem to be installed.".format(plugin)) sys.exit(1) plugin_name = get_plugin_name(plugin) try: run_command([sys.executable, '-m', 'pip', 'uninstall', '-y', ...
def uninstall(ctx, plugin)
Uninstall the given plugin.
2.516418
2.462774
1.021782
if not isinstance(self.duration, tuple): return self.duration if self.duration[1] is None: return 0 time_start = self.get_start_time() # This can happen if the previous entry has a non-tuple duration # and the current entry has a tuple duration...
def hours(self)
Return the number of hours this entry has lasted. If the duration is a tuple with a start and an end time, the difference between the two times will be calculated. If the duration is a number, it will be returned as-is.
2.727772
2.377569
1.147294
if not isinstance(self.duration, tuple): return None if self.duration[0] is not None: return self.duration[0] else: if (self.previous_entry and isinstance(self.previous_entry.duration, tuple) and self.previous_...
def get_start_time(self)
Return the start time of the entry as a :class:`datetime.time` object. If the start time is `None`, the end time of the previous entry will be returned instead. If the current entry doesn't have a duration in the form of a tuple, if there's no previous entry or if the previous entry has ...
2.85852
2.047219
1.396294
return u''.join([ self.alias, self.description, str(self.ignored), str(self.flags), ])
def hash(self)
Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the same hash.
8.817863
7.586008
1.162385
super(Entry, self).add_flag(flag) self._changed_attrs.add('flags')
def add_flag(self, flag)
Add flag to the flags and memorize this attribute has changed so we can regenerate it when outputting text.
6.560923
5.009248
1.309762
super(Entry, self).remove_flag(flag) self._changed_attrs.add('flags')
def remove_flag(self, flag)
Remove flag to the flags and memorize this attribute has changed so we can regenerate it when outputting text.
6.740537
5.34938
1.26006
in_date = False insert_at = 0 for (lineno, line) in enumerate(self.lines): # Search for the date of the entry if isinstance(line, DateLine) and line.date == date: in_date = True # Insert here if there is no existing Entry for this...
def add_entry(self, date, entry)
Add the given entry to the textual representation.
3.340615
3.232095
1.033576
self.lines = trim([ line for line in self.lines if not isinstance(line, Entry) or line not in entries ])
def delete_entries(self, entries)
Remove the given entries from the textual representation.
6.851112
5.521365
1.240837
self.lines = [ line for line in self.lines if not isinstance(line, DateLine) or line.date != date ] self.lines = trim(self.lines)
def delete_date(self, date)
Remove the date line from the textual representation. This doesn't remove any entry line.
4.370968
3.820785
1.143997
self.lines = self.parser.add_date(date, self.lines)
def add_date(self, date)
Add the given date to the textual representation.
7.862359
6.263948
1.255176
self.lines = self.parser.parse_text(entries) for line in self.lines: if isinstance(line, DateLine): current_date = line.date self[current_date] = self.default_factory(self, line.date) elif isinstance(line, Entry): if len(s...
def init_from_str(self, entries)
Initialize the structured and textual data based on a string representing the entries. For detailed information about the format of this string, refer to the :func:`~taxi.timesheet.parser.parse_text` function.
2.896374
2.762315
1.048531
def entry_filter(entry_date, entry): if ignored is not None and entry.ignored != ignored: return False if pushed is not None and entry.pushed != pushed: return False if unmapped is not None and entry.mapped == unmapped: ...
def filter(self, date=None, regroup=False, ignored=None, pushed=None, unmapped=None, current_workday=None)
Return the entries as a dict of {:class:`datetime.date`: :class:`~taxi.timesheet.lines.Entry`} items. `date` can either be a single :class:`datetime.date` object to filter only entries from the given date, or a tuple of :class:`datetime.date` objects representing `(from, to)`. `filter_callback`...
2.646805
2.490019
1.062966
super(EntriesList, self).append(x) if self.entries_collection is not None: self.entries_collection.add_entry(self.date, x)
def append(self, x)
Append the given element to the list and synchronize the textual representation.
6.163398
5.803975
1.061927
def show_aliases(aliases): for alias in aliases: mapping = aliases_after_update[alias] (project, activity) = projects_db.mapping_to_project(mapping) self.msg("%s\n\t%s / %s" % ( alias, project.name if project ...
def projects_database_update_success(self, aliases_after_update, projects_db)
Display the results of the projects/aliases database update. We need the projects db to extract the name of the projects / activities.
2.506968
2.45187
1.022472
date_lines = [ line for line in lines if hasattr(line, 'is_date_line') and line.is_date_line ] if len(date_lines) < 2 or date_lines[0].date == date_lines[1].date: return None else: return date_lines[1].date > date_lines[0].date
def is_top_down(lines)
Return `True` if dates in the given lines go in an ascending order, or `False` if they go in a descending order. If no order can be determined, return `None`. The given `lines` must be a list of lines, ie. :class:`~taxi.timesheet.lines.TextLine`, :class:`taxi.timesheet.lines.Entry` or :class:`~taxi.timeshee...
2.850424
2.447426
1.164662
trim_top = None trim_bottom = None _lines = lines[:] for (lineno, line) in enumerate(_lines): if hasattr(line, 'is_text_line') and line.is_text_line and not line.text.strip(): trim_top = lineno else: break for (lineno, line) in enumerate(reversed(_lines...
def trim(lines)
Remove lines at the start and at the end of the given `lines` that are :class:`~taxi.timesheet.lines.TextLine` instances and don't have any text.
2.033305
1.963251
1.035683
timesheet_collection = get_timesheet_collection_for_context(ctx, f) if not date and not force_yes: non_workday_entries = timesheet_collection.entries.filter(ignored=False, pushed=False, current_workday=False) if non_workday_entries: if not ctx.obj['view'].confirm_commit_entrie...
def commit(ctx, f, force_yes, date)
Commits your work to the server. The [date] option can be used either as a single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as a range with one of the dates omitted (eg. -22.01.2014).
3.931147
4.053619
0.969787
url = '{}{}'.format(self.base_url, path) data = None try: async with self.websession.get(url, auth=self._auth, timeout=self._timeout) as response: if response.status == 200: if response.headers['content-type'] == 'application/json': ...
async def _request(self, path)
Make the actual request and return the parsed response.
2.531325
2.454042
1.031492
status_data = await self._request('/status.json?show_avail=1') if status_data: self.status_data = status_data sensor_data = await self._request('/sensors.json') if sensor_data: self.sensor_data = sensor_data
async def update(self)
Fetch the latest data from IP Webcam.
4.387899
3.937814
1.114298
settings = {} if not self.status_data: return settings for (key, val) in self.status_data.get('curvals', {}).items(): try: val = float(val) except ValueError: val = val if val in ('on', 'off'): ...
def current_settings(self)
Return dict with all config include.
3.493622
3.374576
1.035277
available = {} if not self.status_data: return available for (key, val) in self.status_data.get('avail', {}).items(): available[key] = [] for subval in val: try: subval = float(subval) except ValueE...
def available_settings(self)
Return dict of lists with all available config settings.
3.3138
3.033859
1.092272
value = None unit = None try: container = self.sensor_data.get(sensor) unit = container.get('unit') data_point = container.get('data', [[0, [0.0]]]) if data_point and data_point[0]: value = data_point[0][-1][0] exce...
def export_sensor(self, sensor)
Return (value, unit) from a sensor node.
4.006268
3.307376
1.211313
if isinstance(val, bool): payload = 'on' if val else 'off' else: payload = val return self._request('/settings/{}?set={}'.format(key, payload))
def change_setting(self, key, val)
Change a setting. Return a coroutine.
4.229562
4.469573
0.946301
path = '/startvideo?force=1' if record else '/stopvideo?force=1' if record and tag is not None: path = '/startvideo?force=1&tag={}'.format(URL(tag).raw_path) return self._request(path)
def record(self, record=True, tag=None)
Enable/disable recording. Return a coroutine.
6.878059
6.800727
1.011371
if orientation not in ALLOWED_ORIENTATIONS: _LOGGER.debug('%s is not a valid orientation', orientation) return False return self.change_setting('orientation', orientation)
def set_orientation(self, orientation='landscape')
Set the video orientation. Return a coroutine.
4.618129
5.084689
0.908242
if scenemode not in self.available_settings['scenemode']: _LOGGER.debug('%s is not a valid scenemode', scenemode) return False return self.change_setting('scenemode', scenemode)
def set_scenemode(self, scenemode='auto')
Set the video scene mode. Return a coroutine.
3.196475
3.465218
0.922446
if not entries_file: entries_file = ctx.obj['settings'].get_entries_file_path(False) parser = TimesheetParser( date_format=ctx.obj['settings']['date_format'], add_date_to_bottom=ctx.obj['settings'].get_add_to_bottom(), flags_repr=ctx.obj['settings'].get_flags(), ) ...
def get_timesheet_collection_for_context(ctx, entries_file=None)
Return a :class:`~taxi.timesheet.TimesheetCollection` object with the current timesheet(s). Since this depends on the settings (to get the entries files path, the number of previous files, etc) this uses the settings object from the current command context. If `entries_file` is set, this forces the path of the ...
4.438193
3.759099
1.180654
import textwrap from six.moves.urllib import parse if not os.path.exists(filename): old_default_config_file = os.path.join(os.path.dirname(filename), '.tksrc') if os.path.exists(old_default_config_file): upgrade = click.confirm...
def create_config_file(filename)
Create main configuration file if it doesn't exist.
3.646869
3.62566
1.00585
@click.option( '--until', type=Date(), help="Only show entries until the given date." ) @click.option( '--since', type=Date(), help="Only show entries starting at the given date.", ) @click.option( '--today/--not-today', default=None, help="Only include today's entries (...
def date_options(func)
Decorator to add support for `--today/--not-today`, `--from` and `--to` options to the given command. The calculated date is then passed as a parameter named `date`.
2.439039
2.355094
1.035644
nb_years = nb_months // 12 nb_months = nb_months % 12 month_diff = date.month - nb_months if month_diff > 0: new_month = month_diff else: new_month = 12 + month_diff nb_years += 1 return date.replace(day=1, month=new_month, year=date.year - nb_years)
def months_ago(date, nb_months=1)
Return the given `date` with `nb_months` substracted from it.
2.011413
1.78669
1.125776
today = datetime.date.today() if value == 'today': return today elif value == 'yesterday': return today - datetime.timedelta(days=1) time_ago = re.match(r'(\d+) (days?|weeks?|months?|years?) ago', value) if time_ago: duration, unit = int(time_ago.group(1)), time_ago.g...
def time_ago_to_date(value)
Parse a date and return it as ``datetime.date`` objects. Examples of valid dates: * Relative: 2 days ago, today, yesterday, 1 week ago * Absolute: 25.10.2017
1.891178
1.898526
0.99613
if not reverse: list_aliases(ctx, search_string, backend, used, inactive=inactive) else: show_mapping(ctx, search_string, backend)
def list_(ctx, search_string, reverse, backend, used, inactive)
List configured aliases. Aliases in red belong to inactive projects and trying to push entries to these aliases will probably result in an error.
4.681111
4.727049
0.990282
if not backend: backends_list = ctx.obj['settings'].get_backends() if len(backends_list) > 1: raise click.UsageError( "You're using more than 1 backend. Please set the backend to " "add the alias to with the --backend option (choices are %s)" % ...
def add(ctx, alias, mapping, backend)
Add a new alias to your configuration file.
4.515411
4.434086
1.018341
from six.moves.urllib import parse if not self.config.has_section('backends'): self.config.add_section('backends') site = parse.urlparse(self.get('site', default_value='')) backend_uri = 'zebra://{username}:{password}@{hostname}'.format( username=self.g...
def convert_to_4(self)
Convert a pre-4.0 configuration file to a 4.0 configuration file.
2.08188
2.032499
1.024296
auto_fill_days = ctx.obj['settings']['auto_fill_days'] if not auto_fill_days: ctx.obj['view'].view.err("The parameter `auto_fill_days` must be set " "to use this command.") return today = datetime.date.today() last_day = calendar.monthrange(today.y...
def autofill(ctx, f)
Fills your timesheet up to today, for the defined auto_fill_days.
4.047655
3.581064
1.130294
projects = ctx.obj['projects_db'].search(search, backend=backend) projects = sorted(projects, key=lambda project: project.name.lower()) ctx.obj['view'].search_results(projects)
def list_(ctx, search, backend)
Searches for a project by its name. The letter in the first column indicates the status of the project: [N]ot started, [A]ctive, [F]inished, [C]ancelled.
4.983607
4.59007
1.085737
projects = ctx.obj['projects_db'].search(search, active_only=True) projects = sorted(projects, key=lambda project: project.name) if len(projects) == 0: ctx.obj['view'].msg( "No active project matches your search string '%s'." % ''.join(search) ) return ...
def alias(ctx, search, backend)
Searches for the given project and interactively add an alias for it.
3.477331
3.382087
1.028161
try: project = ctx.obj['projects_db'].get(project_id, backend) except IOError: raise Exception("Error: the projects database file doesn't exist. " "Please run `taxi update` to create it") if project is None: ctx.obj['view'].err( "Could not fi...
def show(ctx, project_id, backend)
Shows the details of the given project id.
5.280797
5.328549
0.991038
description = ' '.join(description) try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) current_timesheet = timesheet_collection.latest() current_timesheet.continue_entry( datetime.date.today(), datetime.datetime.now().time(), ...
def stop(ctx, description, f)
Use it when you stop working on the current task. You can add a description to what you've done.
3.944305
4.062378
0.970935
today = datetime.date.today() try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) except ParseError as e: ctx.obj['view'].err(e) return t = timesheet_collection.latest() # If there's a previous entry on the same date, check if we can use its #...
def start(ctx, alias, description, f)
Use it when you start working on the given activity. This will add the activity and the current time to your entries file. When you're finished, use the stop command.
3.665693
3.642526
1.00636
text = text.replace(':', '') if not re.match('^\d{3,}$', text): raise ValueError("Time must be numeric") minutes = int(text[-2:]) hours = int(text[0:2] if len(text) > 3 else text[0]) return datetime.time(hours, minutes)
def create_time_from_text(text)
Parse a time in the form ``hh:mm`` or ``hhmm`` (or even ``hmm``) and return a :class:`datetime.time` object. If no valid time can be extracted from the given string, :exc:`ValueError` will be raised.
3.437641
3.369253
1.020298
if isinstance(duration, tuple): start = (duration[0].strftime(self.ENTRY_DURATION_FORMAT) if duration[0] is not None else '') end = (duration[1].strftime(self.ENTRY_DURATION_FORMAT) if duration[1] is not None ...
def duration_to_text(self, duration)
Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a number.
2.810242
2.658669
1.057011
return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line)
def to_text(self, line)
Return the textual representation of the given `line`.
14.437358
11.263392
1.281795