Search is not available for this dataset
text
stringlengths
75
104k
async def update_bikes(delta: Optional[timedelta] = None): """ A background task that retrieves bike data. :param delta: The amount of time to wait between checks. """ async def update(delta: timedelta): logger.info("Fetching bike data.") if await should_update_bikes(delta): ...
async def should_update_bikes(delta: timedelta): """ Checks the most recently cached bike and returns true if it either doesn't exist or :return: Whether the cache should be updated. todo what if there are no bikes added for a week? ... every request will be triggered. """ bike = Bike.get_m...
async def get_bikes(postcode: PostCodeLike, kilometers=1) -> Optional[List[Bike]]: """ Gets stolen bikes from the database within a certain radius (km) of a given postcode. Selects a square from the database and then filters out the corners of the square. :param postcode: The postcode to look up...
async def get_postcode_random() -> Postcode: """ Gets a random postcode object.. Acts as a middleware between us and the API, caching results. :return: The PostCode object else None if the postcode does not exist. """ try: postcode = await fetch_postcode_random() except (ApiError, Ci...
async def get_postcode(postcode_like: PostCodeLike) -> Optional[Postcode]: """ Gets the postcode object for a given postcode string. Acts as a middleware between us and the API, caching results. :param postcode_like: The either a string postcode or PostCode object. :return: The PostCode object else ...
async def get_neighbourhood(postcode_like: PostCodeLike) -> Optional[Neighbourhood]: """ Gets a police neighbourhood from the database. Acts as a middleware between us and the API, caching results. :param postcode_like: The UK postcode to look up. :return: The Neighbourhood or None if the postcode d...
def get_cdata(self, *args): ''' all args-->_cffi_backend.buffer Returns-->cdata (if a SINGLE argument was provided) LIST of cdata (if a args was a tuple or list) ''' res = tuple([ self.from_buffer(x) for x in args ]) if len(res) == 0...
def get_buffer(self, *args): ''' all args-->_cffi_backend.CDataOwn Must be a pointer or an array Returns-->buffer (if a SINGLE argument was provided) LIST of buffer (if a args was a tuple or list) ''' res = tuple([ self.buffer(x) for x in arg...
def get_bytes(self, *args): ''' all args-->_cffi_backend.CDataOwn Must be a pointer or an array Returns-->bytes (if a SINGLE argument was provided) LIST of bytes (if a args was a tuple or list) ''' res = tuple([ bytes(self.buffer(x)) for x in...
def get_brightness(self): """ Return the average brightness of the image. """ # Only download the image if it has changed if not self.connection.has_changed(): return self.image_brightness image_path = self.connection.download_image() converted_image...
def write_file (filename, contents): """Create a file with the specified name and write 'contents' (a sequence of strings without line terminators) to it. """ contents = "\n".join(contents) if sys.version_info >= (3,): contents = contents.encode("utf-8") f = open(filename, "wb") #...
def write_file(self, what, filename, data): """Write `data` to `filename` (if not a dry run) after announcing it `what` is used in a log message to identify what is being written to the file. """ log.info("writing %s to %s", what, filename) if sys.version_info >= (3,): ...
def write_manifest (self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ # The manifest must be UTF-8 encodable. See #303. if sys.version_info >= (3,): ...
def match(self, *args): """ Indicate whether or not to enter a case suite. usage: ``` py for case in switch(value): if case('A'): pass elif case(1, 3): pass # for mulit-match. else: pass # for d...
def _find_match(self, position): """ Given a valid position in the text document, try to find the position of the matching bracket. Returns -1 if unsuccessful. """ # Decide what character to search for and what direction to search in. document = self._text_edit.document() ...
def _selection_for_character(self, position): """ Convenience method for selecting a character. """ selection = QtGui.QTextEdit.ExtraSelection() cursor = self._text_edit.textCursor() cursor.setPosition(position) cursor.movePosition(QtGui.QTextCursor.NextCharacter, ...
def _cursor_position_changed(self): """ Updates the document formatting based on the new cursor position. """ # Clear out the old formatting. self._text_edit.setExtraSelections([]) # Attempt to match a bracket for the new cursor position. cursor = self._text_edit.textCur...
def _exc_info(self): """Bottleneck to fix up IronPython string exceptions """ e = self.exc_info() if sys.platform == 'cli': if isinstance(e[0], StringException): # IronPython throws these StringExceptions, but # traceback checks type(etype) == ...
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) #import pdb #pdb.set_trace() if self.resultProxy: result, orig = self...
def ancestry(self, context): """Return the ancestry of the context (that is, all of the packages and modules containing the context), in order of descent with the outermost ancestor last. This method is a generator. """ log.debug("get ancestry %s", context) if con...
def mixedSuites(self, tests): """The complex case where there are tests that don't all share the same context. Groups tests into suites with common ancestors, according to the following (essentially tail-recursive) procedure: Starting with the context of the first test, if it is not ...
def options(self, parser, env): """Register commandline options. """ parser.add_option('--collect-only', action='store_true', dest=self.enableOpt, default=env.get('NOSE_COLLECT_ONLY'), help="E...
def create_inputhook_qt4(mgr, app=None): """Create an input hook for running the Qt4 application event loop. Parameters ---------- mgr : an InputHookManager app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, an...
def get(cls, name=__name__): """Return a Mapper instance with the given name. If the name already exist return its instance. Does not work if a Mapper was created via its constructor. Using `Mapper.get()`_ is the prefered way. Args: name (str, optional): N...
def url(self, pattern, method=None, type_cast=None): """Decorator for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits yo...
def s_url(self, path, method=None, type_cast=None): """Decorator for registering a simple path. Args: path (str): Path to be matched. method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever fits your situation though. ...
def add(self, pattern, function, method=None, type_cast=None): """Function for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path. function (function): Function to associate with this path. method (str, optional): Usually used to d...
def s_add(self, path, function, method=None, type_cast=None): """Function for registering a simple path. Args: path (str): Path to be matched. function (function): Function to associate with this path. method (str, optional): Usually used to define one of GET, POST, ...
def call(self, url, method=None, args=None): """Calls the first function matching the urls pattern and method. Args: url (str): Url for which to call a matching function. method (str, optional): The method used while registering a function. Defaul...
def execute(self, source=None, hidden=False, interactive=False): """ Reimplemented to the store history. """ if not hidden: history = self.input_buffer if source is None else source executed = super(HistoryConsoleWidget, self).execute( source, hidden, interactive...
def _up_pressed(self, shift_modifier): """ Called when the up key is pressed. Returns whether to continue processing the event. """ prompt_cursor = self._get_prompt_cursor() if self._get_cursor().blockNumber() == prompt_cursor.blockNumber(): # Bail out if we're lo...
def _down_pressed(self, shift_modifier): """ Called when the down key is pressed. Returns whether to continue processing the event. """ end_cursor = self._get_end_cursor() if self._get_cursor().blockNumber() == end_cursor.blockNumber(): # Bail out if we're locked....
def history_previous(self, substring='', as_prefix=True): """ If possible, set the input buffer to a previous history item. Parameters: ----------- substring : str, optional If specified, search for an item with this substring. as_prefix : bool, optional ...
def history_next(self, substring='', as_prefix=True): """ If possible, set the input buffer to a subsequent history item. Parameters: ----------- substring : str, optional If specified, search for an item with this substring. as_prefix : bool, optional If...
def _handle_execute_reply(self, msg): """ Handles replies for code execution, here only session history length """ msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].pop(msg_id,None) if info and info.kind == 'save_magic' and not self._hidden: ...
def _history_locked(self): """ Returns whether history movement is locked. """ return (self.history_lock and (self._get_edited_history(self._history_index) != self.input_buffer) and (self._get_prompt_cursor().blockNumber() != self...
def _get_edited_history(self, index): """ Retrieves a history item, possibly with temporary edits. """ if index in self._history_edits: return self._history_edits[index] elif index == len(self._history): return unicode() return self._history[index]
def _set_history(self, history): """ Replace the current history with a sequence of history items. """ self._history = list(history) self._history_edits = {} self._history_index = len(self._history)
def _store_edits(self): """ If there are edits to the current input buffer, store them. """ current = self.input_buffer if self._history_index == len(self._history) or \ self._history[self._history_index] != current: self._history_edits[self._history_index] = ...
def t_NAME(t): r'[A-Za-z_][A-Za-z0-9_]*' # to simplify lexing, we match identifiers and keywords as a single thing # if it's a keyword, we change the type to the name of that keyword if t.value.upper() in reserved: t.type = t.value.upper() t.value = t.value.upper() return t
def t_STRING(t): r"'([^'\\]+|\\'|\\\\)*'" t.value = t.value.replace(r'\\', chr(92)).replace(r"\'", r"'")[1:-1] return t
def p_postpositions(p): ''' postpositions : LIMIT NUMBER postpositions | ORDER BY colspec postpositions | empty ''' if len(p) > 2: if p[1] == "LIMIT": postposition = { "limit": p[2] } rest = p[3] if p[3] else...
def p_colspec(p): ''' colspec : STAR | NAME | function | NAME COMMA colspec | function COMMA colspec ''' rest = p[3] if len(p) > 3 else [] if p[1] == "*": p[0] = [{"type": "star"}] elif isinstance(p[1], dict) and p[1].get("type") == "functi...
def p_expression(p): ''' expression : value | expression AND expression | expression OR expression | expression EQUALS expression | NOT expression | LPAREN expression RPAREN ''' if len(p) < 3: p[0] = p[1] elif len(p) ...
def OnTimeToClose(self, evt): """Event handler for the button click.""" print("See ya later!") sys.stdout.flush() self.cleanup_consoles(evt) self.Close() # Not sure why, but our IPython kernel seems to prevent normal WX # shutdown, so an explicit exit() call is ne...
def upgrade_dir(srcdir, tgtdir): """ Copy over all files in srcdir to tgtdir w/ native line endings Creates .upgrade_report in tgtdir that stores md5sums of all files to notice changed files b/w upgrades. """ def pr(s): print s junk = ['.svn','ipythonrc*','*.pyc', '*.pyo', '*~', '.hg']...
def prepare_files(self, finder): """ Prepare process. Create temp directories, download and/or unpack files. """ from pip.index import Link unnamed = list(self.unnamed_requirements) reqs = list(self.requirements.values()) while reqs or unnamed: if unn...
def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source() if self._pip_has_created_build_dir(): logger.debug('Removing tem...
def install(self, install_options, global_options=(), *args, **kwargs): """ Install everything in this set (after having downloaded and unpacked the packages) """ to_install = [r for r in self.requirements.values()[::-1] if not r.satisfied_by] # DIS...
def load_record(index_series_tuple, kwargs): ''' Generates an instance of Record() from a tuple of the form (index, pandas.Series) with associated parameters kwargs Paremeters ---------- index_series_tuple : tuple tuple consisting of (index, pandas.Series) kwargs : dict adi...
def build_collection(df, **kwargs): ''' Generates a list of Record objects given a DataFrame. Each Record instance has a series attribute which is a pandas.Series of the same attributes in the DataFrame. Optional data can be passed in through kwargs which will be included by the name of each object...
def collection_to_df(collection): ''' Converts a collection back into a pandas DataFrame parameters ---------- collection : list list of Record objects where each Record represents one row from a dataframe Returns ------- df : pandas.DataFrame DataFrame of length=len(c...
def spin_frame(df, method): ''' Runs the full turntable process on a pandas DataFrame parameters ---------- df : pandas.DataFrame each row represents a record method : def method(record) function used to process each row Returns ------- df : pandas.DataFrame ...
def set_attributes(self, kwargs): ''' Initalizes the given argument structure as properties of the class to be used by name in specific method execution. Parameters ---------- kwargs : dictionary Dictionary of extra attributes, where keys are attr...
def subscribe(self): """Update our SUB socket's subscriptions.""" self.stream.setsockopt(zmq.UNSUBSCRIBE, '') if '' in self.topics: self.log.debug("Subscribing to: everything") self.stream.setsockopt(zmq.SUBSCRIBE, '') else: for topic in self.topics: ...
def _extract_level(self, topic_str): """Turn 'engine.0.INFO.extra' into (logging.INFO, 'engine.0.extra')""" topics = topic_str.split('.') for idx,t in enumerate(topics): level = getattr(logging, t, None) if level is not None: break if leve...
def log_message(self, raw): """receive and parse a message, then log it.""" if len(raw) != 2 or '.' not in raw[0]: self.log.error("Invalid log message: %s"%raw) return else: topic, msg = raw # don't newline, since log messages always newline: ...
def mergesort(list_of_lists, key=None): """ Perform an N-way merge operation on sorted lists. @param list_of_lists: (really iterable of iterable) of sorted elements (either by naturally or by C{key}) @param key: specify sort key function (like C{sort()}, C{sorted()}) Yields tuples of the form C{(i...
def remote_iterator(view,name): """Return an iterator on an object living on a remote engine. """ view.execute('it%s=iter(%s)'%(name,name), block=True) while True: try: result = view.apply_sync(lambda x: x.next(), Reference('it'+name)) # This causes the StopIteration exceptio...
def convert_to_this_nbformat(nb, orig_version=1): """Convert a notebook to the v2 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. """ if orig_version == ...
def get_supported_platform(): """Return this platform's maximum compatible version. distutils.util.get_platform() normally reports the minimum version of Mac OS X that would be required to *use* extensions produced by distutils. But what we want when checking compatibility is to know the version o...
def get_importer(path_item): """Retrieve a PEP 302 "importer" for the given path item If there is no importer, this returns a wrapper around the builtin import machinery. The returned importer is only cached if it was created by a path hook. """ try: importer = sys.path_importer_cache[...
def StringIO(*args, **kw): """Thunk to load the real StringIO on demand""" global StringIO try: from cStringIO import StringIO except ImportError: from StringIO import StringIO return StringIO(*args,**kw)
def parse_version(s): """Convert a version string to a chronologically-sortable key This is a rough cross between distutils' StrictVersion and LooseVersion; if you give it versions that would work with StrictVersion, then it behaves the same; otherwise it acts like a slightly-smarter LooseVersion. It i...
def _override_setuptools(req): """Return True when distribute wants to override a setuptools dependency. We want to override when the requirement is setuptools and the version is a variant of 0.6. """ if req.project_name == 'setuptools': if not len(req.specs): # Just setuptools...
def add(self, dist, entry=None, insert=True, replace=False): """Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set's ``.entries`` (if it wasn'...
def resolve(self, requirements, env=None, installer=None, replacement=True, replace_conflicting=False): """List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environ...
def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True ): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) map(w...
def add(self,dist): """Add `dist` if we ``can_add()`` it and it isn't already added""" if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key,[]) if dist not in dists: dists.append(dist) if dist.key in self._cache: ...
def get_cache_path(self, archive_name, names=()): """Return absolute location in cache for `archive_name` and `names` The parent directory of the resulting path will be created if it does not already exist. `archive_name` should be the base filename of the enclosing egg (which may not ...
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1,extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional ""...
def activate(self,path=None): """Ensure distribution is importable on `path` (default=sys.path)""" if path is None: path = sys.path self.insert_on(path) if path is sys.path: fixup_namespace_packages(self.location) map(declare_namespace, self._get_metadata('namespa...
def insert_on(self, path, loc = None): """Insert self.location in path before its nearest parent directory""" loc = loc or self.location if self.project_name == 'setuptools': try: version = self.version except ValueError: version = '' ...
def _parsed_pkg_info(self): """Parse and cache metadata""" try: return self._pkg_info except AttributeError: from email.parser import Parser self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO)) return self._pkg_info
def _compute_dependencies(self): """Recompute this distribution's dependencies.""" from _markerlib import compile as compile_marker dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') ...
def parse_filename(fname): """Parse a notebook filename. This function takes a notebook filename and returns the notebook format (json/py) and the notebook name. This logic can be summarized as follows: * notebook.ipynb -> (notebook.ipynb, notebook, json) * notebook.json -> (notebook.json, no...
def _collapse_leading_ws(header, txt): """ ``Description`` header must preserve newlines; all others need not """ if header.lower() == 'description': # preserve newlines return '\n'.join([x[8:] if x.startswith(' ' * 8) else x for x in txt.strip().splitlines()]) els...
def get_refs(self, location): """Return map of named refs (branches or tags) to commit hashes.""" output = call_subprocess([self.cmd, 'show-ref'], show_stdout=False, cwd=location) rv = {} for line in output.strip().splitlines(): commit, ref = ...
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key, text = event.key(), eve...
def hideEvent(self, event): """ Reimplemented to disconnect signal handlers and event filter. """ super(CompletionWidget, self).hideEvent(event) self._text_edit.cursorPositionChanged.disconnect(self._update_current) self._text_edit.removeEventFilter(self)
def showEvent(self, event): """ Reimplemented to connect signal handlers and event filter. """ super(CompletionWidget, self).showEvent(event) self._text_edit.cursorPositionChanged.connect(self._update_current) self._text_edit.installEventFilter(self)
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ text_edit = self._text_edit point = text_edit.cursorRect(cursor).bottomRight() point = text_edit.mapToGlobal(point) height = self.sizeH...
def _complete_current(self): """ Perform the completion with the currently selected item. """ self._current_text_cursor().insertText(self.currentItem().text()) self.hide()
def _current_text_cursor(self): """ Returns a cursor with text between the start position and the current position selected. """ cursor = self._text_edit.textCursor() if cursor.position() >= self._start_position: cursor.setPosition(self._start_position, ...
def _update_current(self): """ Updates the current item based on the current text. """ prefix = self._current_text_cursor().selection().toPlainText() if prefix: items = self.findItems(prefix, (QtCore.Qt.MatchStartsWith | QtCore.Qt.M...
def registerAdminSite(appName, excludeModels=[]): """Registers the models of the app with the given "appName" for the admin site""" for model in apps.get_app_config(appName).get_models(): if model not in excludeModels: admin.site.register(model)
def virtual_memory(): """System virtual memory as a namedtuple.""" mem = _psutil_mswindows.get_virtual_mem() totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem # total = totphys avail = availphys free = availphys used = total - avail percent = usage_percent((total - av...
def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" mem = _psutil_mswindows.get_virtual_mem() total = mem[2] free = mem[3] used = total - free percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, 0, 0)
def get_disk_usage(path): """Return disk usage associated with path.""" try: total, free = _psutil_mswindows.get_disk_usage(path) except WindowsError: err = sys.exc_info()[1] if not os.path.exists(path): raise OSError(errno.ENOENT, "No such file or directory: '%s'" % path...
def disk_partitions(all): """Return disk partitions.""" rawlist = _psutil_mswindows.get_disk_partitions(all) return [nt_partition(*x) for x in rawlist]
def get_system_cpu_times(): """Return system CPU times as a named tuple.""" user, system, idle = 0, 0, 0 # computes system global times summing each processor value for cpu_time in _psutil_mswindows.get_system_cpu_times(): user += cpu_time[0] system += cpu_time[1] idle += cpu_tim...
def get_system_per_cpu_times(): """Return system per-CPU times as a list of named tuples.""" ret = [] for cpu_t in _psutil_mswindows.get_system_cpu_times(): user, system, idle = cpu_t item = _cputimes_ntuple(user, system, idle) ret.append(item) return ret
def get_system_users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = _psutil_mswindows.get_system_users() for item in rawlist: user, hostname, tstamp = item nt = nt_user(user, None, hostname, tstamp) retlist.append(nt) return retlist
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT ret...
def run(self, stdout_func = None, stdin_func = None, stderr_func = None): """Runs the process, using the provided functions for I/O. The function stdin_func should return strings whenever a character or characters become available. The functions stdout_func and stderr_func are called wh...
def _stdin_raw_nonblock(self): """Use the raw Win32 handle of sys.stdin to do non-blocking reads""" # WARNING: This is experimental, and produces inconsistent results. # It's possible for the handle not to be appropriate for use # with WaitForSingleObject, among other t...
def _stdin_raw_block(self): """Use a blocking stdin read""" # The big problem with the blocking read is that it doesn't # exit when it's supposed to in all contexts. An extra # key-press may be required to trigger the exit. try: data = sys.stdin.read(1) da...
def _stdout_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stdout) sys.stdout.flush()
def _stderr_raw(self, s): """Writes the string to stdout""" print(s, end='', file=sys.stderr) sys.stderr.flush()
def _run_stdio(self): """Runs the process using the system standard I/O. IMPORTANT: stdin needs to be asynchronous, so the Python sys.stdin object is not used. Instead, msvcrt.kbhit/getwch are used asynchronously. """ # Disable Line and Echo mode ...