_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33800
arrow_get
train
def arrow_get(string): '''this function exists because ICS uses ISO 8601 without dashes or colons, i.e. not ISO 8601 at all.''' # replace slashes with dashes if '/' in string: string = string.replace('/', '-') # if string contains dashes, assume it to be proper ISO 8601 if '-' in strin...
python
{ "resource": "" }
q33801
parse_duration
train
def parse_duration(line): """ Return a timedelta object from a string in the DURATION property format """ DAYS, SECS = {'D': 1, 'W': 7}, {'S': 1, 'M': 60, 'H': 3600} sign, i = 1, 0 if line[i] in '-+': if line[i] == '-': sign = -1 i += 1 if line[i] != 'P': ...
python
{ "resource": "" }
q33802
timedelta_to_duration
train
def timedelta_to_duration(dt): """ Return a string according to the DURATION property format from a timedelta object """ days, secs = dt.days, dt.seconds res = 'P' if days // 7: res += str(days // 7) + 'W' days %= 7 if days: res += str(days) + 'D' if secs: ...
python
{ "resource": "" }
q33803
Event.end
train
def end(self): """Get or set the end of the event. | Will return an :class:`Arrow` object. | May be set to anything that :func:`Arrow.get` understands. | If set to a non null value, removes any already existing duration. | Setting to None will have unexpected beh...
python
{ "resource": "" }
q33804
Event.duration
train
def duration(self): """Get or set the duration of the event. | Will return a timedelta object. | May be set to anything that timedelta() understands. | May be set with a dict ({"days":2, "hours":6}). | If set to a non null value, removes any already existing end ...
python
{ "resource": "" }
q33805
Event.make_all_day
train
def make_all_day(self): """Transforms self to an all-day event. The event will span all the days from the begin to the end day. """ if self.all_day: # Do nothing if we already are a all day event return begin_day = self.begin.floor('day') end_day...
python
{ "resource": "" }
q33806
Event.join
train
def join(self, other, *args, **kwarg): """Create a new event which covers the time range of two intersecting events All extra parameters are passed to the Event constructor. Args: other: the other event Returns: a new Event instance """ event = ...
python
{ "resource": "" }
q33807
timezone
train
def timezone(calendar, vtimezones): """Receives a list of VTIMEZONE blocks. Parses them and adds them to calendar._timezones. """ for vtimezone in vtimezones: remove_x(vtimezone) # Remove non standard lines from the block fake_file = StringIO() fake_file.write(str(vtimezone)) ...
python
{ "resource": "" }
q33808
Todo.due
train
def due(self): """Get or set the end of the todo. | Will return an :class:`Arrow` object. | May be set to anything that :func:`Arrow.get` understands. | If set to a non null value, removes any already existing duration. | Setting to None will have unexpected beha...
python
{ "resource": "" }
q33809
Todo.duration
train
def duration(self): """Get or set the duration of the todo. | Will return a timedelta object. | May be set to anything that timedelta() understands. | May be set with a dict ({"days":2, "hours":6}). | If set to a non null value, removes any already existing end t...
python
{ "resource": "" }
q33810
APIAuth.login
train
def login(self, email, password, android_id): """Authenticate to Google with the provided credentials. Args: email (str): The account to use. password (str): The account password. android_id (str): An identifier for this client. Raises: LoginExce...
python
{ "resource": "" }
q33811
APIAuth.load
train
def load(self, email, master_token, android_id): """Authenticate to Google with the provided master token. Args: email (str): The account to use. master_token (str): The master token. android_id (str): An identifier for this client. Raises: Login...
python
{ "resource": "" }
q33812
APIAuth.refresh
train
def refresh(self): """Refresh the OAuth token. Returns: string: The auth token. Raises: LoginException: If there was a problem refreshing the OAuth token. """ res = gpsoauth.perform_oauth( self._email, self._master_token, self._android_id, ...
python
{ "resource": "" }
q33813
APIAuth.logout
train
def logout(self): """Log out of the account.""" self._master_token = None self._auth_token = None self._email = None self._android_id = None
python
{ "resource": "" }
q33814
API.send
train
def send(self, **req_kwargs): """Send an authenticated request to a Google API. Automatically retries if the access token has expired. Args: **req_kwargs: Arbitrary keyword arguments to pass to Requests. Return: dict: The parsed JSON response. Raises: ...
python
{ "resource": "" }
q33815
API._send
train
def _send(self, **req_kwargs): """Send an authenticated request to a Google API. Args: **req_kwargs: Arbitrary keyword arguments to pass to Requests. Return: requests.Response: The raw response. Raises: LoginException: If :py:meth:`login` has not be...
python
{ "resource": "" }
q33816
MediaAPI.get
train
def get(self, blob): """Get the canonical link to a media blob. Args: blob (gkeepapi.node.Blob): The blob. Returns: str: A link to the media. """ return self._send( url=self._base_url + blob.parent.server_id + '/' + blob.server_id + '?s=0', ...
python
{ "resource": "" }
q33817
RemindersAPI.create
train
def create(self): """Create a new reminder. """ params = {} return self.send( url=self._base_url + 'create', method='POST', json=params )
python
{ "resource": "" }
q33818
RemindersAPI.list
train
def list(self, master=True): """List current reminders. """ params = {} params.update(self.static_params) if master: params.update({ "recurrenceOptions": { "collapseMode": "MASTER_ONLY", }, "includeA...
python
{ "resource": "" }
q33819
RemindersAPI.history
train
def history(self, storage_version): """Get reminder changes. """ params = { "storageVersion": storage_version, "includeSnoozePresetUpdates": True, } params.update(self.static_params) return self.send( url=self._base_url + 'history', ...
python
{ "resource": "" }
q33820
RemindersAPI.update
train
def update(self): """Sync up changes to reminders. """ params = {} return self.send( url=self._base_url + 'update', method='POST', json=params )
python
{ "resource": "" }
q33821
Keep.login
train
def login(self, username, password, state=None, sync=True): """Authenticate to Google with the provided credentials & sync. Args: email (str): The account to use. password (str): The account password. state (dict): Serialized state to load. Raises: ...
python
{ "resource": "" }
q33822
Keep.resume
train
def resume(self, email, master_token, state=None, sync=True): """Authenticate to Google with the provided master token & sync. Args: email (str): The account to use. master_token (str): The master token. state (dict): Serialized state to load. Raises: ...
python
{ "resource": "" }
q33823
Keep.dump
train
def dump(self): """Serialize note data. Args: state (dict): Serialized state to load. """ # Find all nodes manually, as the Keep object isn't aware of new ListItems # until they've been synced to the server. nodes = [] for node in self.all(): ...
python
{ "resource": "" }
q33824
Keep.restore
train
def restore(self, state): """Unserialize saved note data. Args: state (dict): Serialized state to load. """ self._clear() self._parseUserInfo({'labels': state['labels']}) self._parseNodes(state['nodes']) self._keep_version = state['keep_version']
python
{ "resource": "" }
q33825
Keep.get
train
def get(self, node_id): """Get a note with the given ID. Args: node_id (str): The note ID. Returns: gkeepapi.node.TopLevelNode: The Note or None if not found. """ return \ self._nodes[_node.Root.ID].get(node_id) or \ self._nodes[_...
python
{ "resource": "" }
q33826
Keep.find
train
def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): # pylint: disable=too-many-arguments """Find Notes based on the specified criteria. Args: query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the ...
python
{ "resource": "" }
q33827
Keep.findLabel
train
def findLabel(self, query, create=False): """Find a label with the given name. Args: name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name. create (bool): Whether to create the label if it doesn't exist (only if name is a str). Retur...
python
{ "resource": "" }
q33828
Keep.deleteLabel
train
def deleteLabel(self, label_id): """Deletes a label. Args: label_id (str): Label id. """ if label_id not in self._labels: return label = self._labels[label_id] label.delete() for node in self.all(): node.labels.remove(label)
python
{ "resource": "" }
q33829
Keep.sync
train
def sync(self, resync=False): """Sync the local Keep tree with the server. If resyncing, local changes will be detroyed. Otherwise, local changes to notes, labels and reminders will be detected and synced up. Args: resync (bool): Whether to resync data. Raises: SyncExce...
python
{ "resource": "" }
q33830
Keep._clean
train
def _clean(self): """Recursively check that all nodes are reachable.""" found_ids = {} nodes = [self._nodes[_node.Root.ID]] while nodes: node = nodes.pop() found_ids[node.id] = None nodes = nodes + node.children for node_id in self._nodes: ...
python
{ "resource": "" }
q33831
from_json
train
def from_json(raw): """Helper to construct a node from a dict. Args: raw (dict): Raw node representation. Returns: Node: A Node object or None. """ ncls = None _type = raw.get('type') try: ncls = _type_map[NodeType(_type)] except (KeyError, ValueError) as e: ...
python
{ "resource": "" }
q33832
Element.save
train
def save(self, clean=True): """Serialize into raw representation. Clears the dirty bit by default. Args: clean (bool): Whether to clear the dirty bit. Returns: dict: Raw. """ ret = {} if clean: self._dirty = False else: ...
python
{ "resource": "" }
q33833
NodeAnnotations.from_json
train
def from_json(cls, raw): """Helper to construct an annotation from a dict. Args: raw (dict): Raw annotation representation. Returns: Node: An Annotation object or None. """ bcls = None if 'webLink' in raw: bcls = WebLink elif ...
python
{ "resource": "" }
q33834
NodeAnnotations.links
train
def links(self): """Get all links. Returns: list[gkeepapi.node.WebLink]: A list of links. """ return [annotation for annotation in self._annotations.values() if isinstance(annotation, WebLink) ]
python
{ "resource": "" }
q33835
NodeAnnotations.append
train
def append(self, annotation): """Add an annotation. Args: annotation (gkeepapi.node.Annotation): An Annotation object. Returns: gkeepapi.node.Annotation: The Annotation. """ self._annotations[annotation.id] = annotation self._dirty = True ...
python
{ "resource": "" }
q33836
NodeAnnotations.remove
train
def remove(self, annotation): """Removes an annotation. Args: annotation (gkeepapi.node.Annotation): An Annotation object. Returns: gkeepapi.node.Annotation: The Annotation. """ if annotation.id in self._annotations: del self._annotations[ann...
python
{ "resource": "" }
q33837
NodeCollaborators.add
train
def add(self, email): """Add a collaborator. Args: str : Collaborator email address. """ if email not in self._collaborators: self._collaborators[email] = ShareRequestValue.Add self._dirty = True
python
{ "resource": "" }
q33838
NodeCollaborators.remove
train
def remove(self, email): """Remove a Collaborator. Args: str : Collaborator email address. """ if email in self._collaborators: if self._collaborators[email] == ShareRequestValue.Add: del self._collaborators[email] else: ...
python
{ "resource": "" }
q33839
NodeCollaborators.all
train
def all(self): """Get all collaborators. Returns: List[str]: Collaborators. """ return [email for email, action in self._collaborators.items() if action in [RoleValue.Owner, RoleValue.User, ShareRequestValue.Add]]
python
{ "resource": "" }
q33840
NodeLabels.add
train
def add(self, label): """Add a label. Args: label (gkeepapi.node.Label): The Label object. """ self._labels[label.id] = label self._dirty = True
python
{ "resource": "" }
q33841
NodeLabels.remove
train
def remove(self, label): """Remove a label. Args: label (gkeepapi.node.Label): The Label object. """ if label.id in self._labels: self._labels[label.id] = None self._dirty = True
python
{ "resource": "" }
q33842
TimestampsMixin.touch
train
def touch(self, edited=False): """Mark the node as dirty. Args: edited (bool): Whether to set the edited time. """ self._dirty = True dt = datetime.datetime.utcnow() self.timestamps.updated = dt if edited: self.timestamps.edited = dt
python
{ "resource": "" }
q33843
TimestampsMixin.trashed
train
def trashed(self): """Get the trashed state. Returns: bool: Whether this item is trashed. """ return self.timestamps.trashed is not None and self.timestamps.trashed > NodeTimestamps.int_to_dt(0)
python
{ "resource": "" }
q33844
TimestampsMixin.deleted
train
def deleted(self): """Get the deleted state. Returns: bool: Whether this item is deleted. """ return self.timestamps.deleted is not None and self.timestamps.deleted > NodeTimestamps.int_to_dt(0)
python
{ "resource": "" }
q33845
Node.text
train
def text(self, value): """Set the text value. Args: value (str): Text value. """ self._text = value self.timestamps.edited = datetime.datetime.utcnow() self.touch(True)
python
{ "resource": "" }
q33846
Node.append
train
def append(self, node, dirty=True): """Add a new child node. Args: node (gkeepapi.Node): Node to add. dirty (bool): Whether this node should be marked dirty. """ self._children[node.id] = node node.parent = self if dirty: self.touch() ...
python
{ "resource": "" }
q33847
Node.remove
train
def remove(self, node, dirty=True): """Remove the given child node. Args: node (gkeepapi.Node): Node to remove. dirty (bool): Whether this node should be marked dirty. """ if node.id in self._children: self._children[node.id].parent = None ...
python
{ "resource": "" }
q33848
List.add
train
def add(self, text, checked=False, sort=None): """Add a new item to the list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting. """ node = ListItem(parent_id=self.id, parent_server_id=self.serve...
python
{ "resource": "" }
q33849
List.items_sort
train
def items_sort(cls, items): """Sort list items, taking into account parent items. Args: items (list[gkeepapi.node.ListItem]): Items to sort. Returns: list[gkeepapi.node.ListItem]: Sorted items. """ class t(tuple): """Tuple with element-based s...
python
{ "resource": "" }
q33850
ListItem.add
train
def add(self, text, checked=False, sort=None): """Add a new sub item to the list. This item must already be attached to a list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting. """ if self.pare...
python
{ "resource": "" }
q33851
ListItem.indent
train
def indent(self, node, dirty=True): """Indent an item. Does nothing if the target has subitems. Args: node (gkeepapi.node.ListItem): Item to indent. dirty (bool): Whether this node should be marked dirty. """ if node.subitems: return self._su...
python
{ "resource": "" }
q33852
ListItem.dedent
train
def dedent(self, node, dirty=True): """Dedent an item. Does nothing if the target is not indented under this item. Args: node (gkeepapi.node.ListItem): Item to dedent. dirty (bool): Whether this node should be marked dirty. """ if node.id not in self._subitems: ...
python
{ "resource": "" }
q33853
Blob.from_json
train
def from_json(cls, raw): """Helper to construct a blob from a dict. Args: raw (dict): Raw blob representation. Returns: NodeBlob: A NodeBlob object or None. """ if raw is None: return None bcls = None _type = raw.get('type') ...
python
{ "resource": "" }
q33854
Google.check_prompt_code
train
def check_prompt_code(response): """ Sometimes there is an additional numerical code on the response page that needs to be selected on the prompt from a list of multiple choice. Print it if it's there. """ num_code = response.find("div", {"jsname": "EKvSSd"}) if num_code:...
python
{ "resource": "" }
q33855
get_short_module_name
train
def get_short_module_name(module_name, obj_name): """ Get the shortest possible module name """ scope = {} try: # Find out what the real object is supposed to be. exec('from %s import %s' % (module_name, obj_name), scope, scope) real_obj = scope[obj_name] except Exception: ...
python
{ "resource": "" }
q33856
identify_names
train
def identify_names(filename): """Builds a codeobj summary by identifying and resolving used names.""" node, _ = parse_source_file(filename) if node is None: return {} # Get matches from the code (AST) finder = NameFinder() finder.visit(node) names = list(finder.get_mapping()) na...
python
{ "resource": "" }
q33857
scan_used_functions
train
def scan_used_functions(example_file, gallery_conf): """save variables so we can later add links to the documentation""" example_code_obj = identify_names(example_file) if example_code_obj: codeobj_fname = example_file[:-3] + '_codeobj.pickle.new' with open(codeobj_fname, 'wb') as fid: ...
python
{ "resource": "" }
q33858
_thumbnail_div
train
def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False, check=True): """Generates RST to place a thumbnail in a gallery""" thumb, _ = _find_image_ext( os.path.join(target_dir, 'images', 'thumb', 'sphx_glr_%s_thumb.png' % fname[:-3])) if check...
python
{ "resource": "" }
q33859
write_backreferences
train
def write_backreferences(seen_backrefs, gallery_conf, target_dir, fname, snippet): """Writes down back reference files, which include a thumbnail list of examples using a certain module""" if gallery_conf['backreferences_dir'] is None: return example_file = os.path.join...
python
{ "resource": "" }
q33860
finalize_backreferences
train
def finalize_backreferences(seen_backrefs, gallery_conf): """Replace backref files only if necessary.""" logger = sphinx_compatibility.getLogger('sphinx-gallery') if gallery_conf['backreferences_dir'] is None: return for backref in seen_backrefs: path = os.path.join(gallery_conf['src_di...
python
{ "resource": "" }
q33861
jupyter_notebook_skeleton
train
def jupyter_notebook_skeleton(): """Returns a dictionary with the elements of a Jupyter notebook""" py_version = sys.version_info notebook_skeleton = { "cells": [], "metadata": { "kernelspec": { "display_name": "Python " + str(py_version[0]), "lang...
python
{ "resource": "" }
q33862
directive_fun
train
def directive_fun(match, directive): """Helper to fill in directives""" directive_to_alert = dict(note="info", warning="danger") return ('<div class="alert alert-{0}"><h4>{1}</h4><p>{2}</p></div>' .format(directive_to_alert[directive], directive.capitalize(), match.group(1).s...
python
{ "resource": "" }
q33863
rst2md
train
def rst2md(text): """Converts the RST text from the examples docstrigs and comments into markdown text for the Jupyter notebooks""" top_heading = re.compile(r'^=+$\s^([\w\s-]+)^=+$', flags=re.M) text = re.sub(top_heading, r'# \1', text) math_eq = re.compile(r'^\.\. math::((?:.+)?(?:\n+^ .+)*)', f...
python
{ "resource": "" }
q33864
jupyter_notebook
train
def jupyter_notebook(script_blocks, gallery_conf): """Generate a Jupyter notebook file cell-by-cell Parameters ---------- script_blocks : list Script execution cells. gallery_conf : dict The sphinx-gallery configuration dictionary. """ first_cell = gallery_conf.get("first_no...
python
{ "resource": "" }
q33865
add_code_cell
train
def add_code_cell(work_notebook, code): """Add a code cell to the notebook Parameters ---------- code : str Cell content """ code_cell = { "cell_type": "code", "execution_count": None, "metadata": {"collapsed": False}, "outputs": [], "source": [c...
python
{ "resource": "" }
q33866
fill_notebook
train
def fill_notebook(work_notebook, script_blocks): """Writes the Jupyter notebook cells Parameters ---------- script_blocks : list Each list element should be a tuple of (label, content, lineno). """ for blabel, bcontent, lineno in script_blocks: if blabel == 'code': ...
python
{ "resource": "" }
q33867
save_notebook
train
def save_notebook(work_notebook, write_file): """Saves the Jupyter work_notebook to write_file""" with open(write_file, 'w') as out_nb: json.dump(work_notebook, out_nb, indent=2)
python
{ "resource": "" }
q33868
python_to_jupyter_cli
train
def python_to_jupyter_cli(args=None, namespace=None): """Exposes the jupyter notebook renderer to the command line Takes the same arguments as ArgumentParser.parse_args """ from . import gen_gallery # To avoid circular import parser = argparse.ArgumentParser( description='Sphinx-Gallery No...
python
{ "resource": "" }
q33869
_import_matplotlib
train
def _import_matplotlib(): """Import matplotlib safely.""" # make sure that the Agg backend is set before importing any # matplotlib import matplotlib matplotlib.use('agg') matplotlib_backend = matplotlib.get_backend().lower() if matplotlib_backend != 'agg': raise ValueError( ...
python
{ "resource": "" }
q33870
matplotlib_scraper
train
def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs): """Scrape Matplotlib images. Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Contains ...
python
{ "resource": "" }
q33871
mayavi_scraper
train
def mayavi_scraper(block, block_vars, gallery_conf): """Scrape Mayavi images. Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Contains the configuration ...
python
{ "resource": "" }
q33872
_find_image_ext
train
def _find_image_ext(path, number=None): """Find an image, tolerant of different file extensions.""" if number is not None: path = path.format(number) path = os.path.splitext(path)[0] for ext in _KNOWN_IMG_EXTS: this_path = '%s.%s' % (path, ext) if os.path.isfile(this_path): ...
python
{ "resource": "" }
q33873
save_figures
train
def save_figures(block, block_vars, gallery_conf): """Save all open figures of the example code-block. Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Co...
python
{ "resource": "" }
q33874
figure_rst
train
def figure_rst(figure_list, sources_dir): """Generate RST for a list of PNG filenames. Depending on whether we have one or more figures, we use a single rst call to 'image' or a horizontal list. Parameters ---------- figure_list : list List of strings of the figures' absolute paths. ...
python
{ "resource": "" }
q33875
_reset_seaborn
train
def _reset_seaborn(gallery_conf, fname): """Reset seaborn.""" # Horrible code to 'unload' seaborn, so that it resets # its default when is load # Python does not support unloading of modules # https://bugs.python.org/issue9072 for module in list(sys.modules.keys()): if 'seaborn' in modul...
python
{ "resource": "" }
q33876
python_zip
train
def python_zip(file_list, gallery_path, extension='.py'): """Stores all files in file_list into an zip file Parameters ---------- file_list : list Holds all the file names to be included in zip file gallery_path : str path to where the zipfile is stored extension : str '...
python
{ "resource": "" }
q33877
list_downloadable_sources
train
def list_downloadable_sources(target_dir): """Returns a list of python source files is target_dir Parameters ---------- target_dir : str path to the directory where python source file are Returns ------- list list of paths to all Python source files in `target_dir` """ ...
python
{ "resource": "" }
q33878
generate_zipfiles
train
def generate_zipfiles(gallery_dir): """ Collects all Python source files and Jupyter notebooks in gallery_dir and makes zipfiles of them Parameters ---------- gallery_dir : str path of the gallery to collect downloadable sources Return ------ download_rst: str Restr...
python
{ "resource": "" }
q33879
codestr2rst
train
def codestr2rst(codestr, lang='python', lineno=None): """Return reStructuredText code block from code string""" if lineno is not None: if LooseVersion(sphinx.__version__) >= '1.3': # Sphinx only starts numbering from the first non-empty line. blank_lines = codestr.count('\n', 0, ...
python
{ "resource": "" }
q33880
md5sum_is_current
train
def md5sum_is_current(src_file): """Checks whether src_file has the same md5 hash as the one on disk""" src_md5 = get_md5sum(src_file) src_md5_file = src_file + '.md5' if os.path.exists(src_md5_file): with open(src_md5_file, 'r') as file_checksum: ref_md5 = file_checksum.read() ...
python
{ "resource": "" }
q33881
save_thumbnail
train
def save_thumbnail(image_path_template, src_file, file_conf, gallery_conf): """Generate and Save the thumbnail image Parameters ---------- image_path_template : str holds the template where to save and how to name the image src_file : str path to source python file gallery_conf ...
python
{ "resource": "" }
q33882
_memory_usage
train
def _memory_usage(func, gallery_conf): """Get memory usage of a function call.""" if gallery_conf['show_memory']: from memory_profiler import memory_usage assert callable(func) mem, out = memory_usage(func, max_usage=True, retval=True, multiprocess=True) ...
python
{ "resource": "" }
q33883
_get_memory_base
train
def _get_memory_base(gallery_conf): """Get the base amount of memory used by running a Python process.""" if not gallery_conf['show_memory']: memory_base = 0 else: # There might be a cleaner way to do this at some point from memory_profiler import memory_usage sleep, timeout ...
python
{ "resource": "" }
q33884
execute_code_block
train
def execute_code_block(compiler, block, example_globals, script_vars, gallery_conf): """Executes the code block of the example file""" blabel, bcontent, lineno = block # If example is not suitable to run, skip executing its blocks if not script_vars['execute_script'] or blabel == ...
python
{ "resource": "" }
q33885
executable_script
train
def executable_script(src_file, gallery_conf): """Validate if script has to be run according to gallery configuration Parameters ---------- src_file : str path to python script gallery_conf : dict Contains the configuration of Sphinx-Gallery Returns ------- bool ...
python
{ "resource": "" }
q33886
execute_script
train
def execute_script(script_blocks, script_vars, gallery_conf): """Execute and capture output from python script already in block structure Parameters ---------- script_blocks : list (label, content, line_number) List where each element is a tuple with the label ('text' or 'code'), ...
python
{ "resource": "" }
q33887
rst_blocks
train
def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf): """Generates the rst string containing the script prose, code and output Parameters ---------- script_blocks : list (label, content, line_number) List where each element is a tuple with the label ('text' or 'code'), ...
python
{ "resource": "" }
q33888
save_rst_example
train
def save_rst_example(example_rst, example_file, time_elapsed, memory_used, gallery_conf): """Saves the rst notebook to example_file including header & footer Parameters ---------- example_rst : str rst containing the executed file content example_file : str File...
python
{ "resource": "" }
q33889
get_data
train
def get_data(url, gallery_dir): """Persistent dictionary usage to retrieve the search indexes""" # shelve keys need to be str in python 2 if sys.version_info[0] == 2 and isinstance(url, unicode): url = url.encode('utf-8') cached_file = os.path.join(gallery_dir, 'searchindex') search_index ...
python
{ "resource": "" }
q33890
parse_sphinx_docopts
train
def parse_sphinx_docopts(index): """ Parse the Sphinx index for documentation options. Parameters ---------- index : str The Sphinx index page Returns ------- docopts : dict The documentation options from the page. """ pos = index.find('var DOCUMENTATION_OPTION...
python
{ "resource": "" }
q33891
embed_code_links
train
def embed_code_links(app, exception): """Embed hyperlinks to documentation into example code""" if exception is not None: return # No need to waste time embedding hyperlinks when not running the examples # XXX: also at the time of writing this fixes make html-noplot # for some reason I don'...
python
{ "resource": "" }
q33892
SphinxDocLinkResolver._get_link
train
def _get_link(self, cobj): """Get a valid link, False if not found""" fullname = cobj['module_short'] + '.' + cobj['name'] try: value = self._searchindex['objects'][cobj['module_short']] match = value[cobj['name']] except KeyError: link = False ...
python
{ "resource": "" }
q33893
SphinxDocLinkResolver.resolve
train
def resolve(self, cobj, this_url): """Resolve the link to the documentation, returns None if not found Parameters ---------- cobj : dict Dict with information about the "code object" for which we are resolving a link. cobj['name'] : function or class ...
python
{ "resource": "" }
q33894
glr_path_static
train
def glr_path_static(): """Returns path to packaged static files""" return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))
python
{ "resource": "" }
q33895
gen_binder_url
train
def gen_binder_url(fpath, binder_conf, gallery_conf): """Generate a Binder URL according to the configuration in conf.py. Parameters ---------- fpath: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict or None The Binder configuration dictio...
python
{ "resource": "" }
q33896
gen_binder_rst
train
def gen_binder_rst(fpath, binder_conf, gallery_conf): """Generate the RST + link for the Binder badge. Parameters ---------- fpath: str The path to the `.py` file for which a Binder badge will be generated. binder_conf: dict or None If a dictionary it must have the following keys: ...
python
{ "resource": "" }
q33897
copy_binder_files
train
def copy_binder_files(app, exception): """Copy all Binder requirements and notebooks files.""" if exception is not None: return if app.builder.name not in ['html', 'readthedocs']: return gallery_conf = app.config.sphinx_gallery_conf binder_conf = check_binder_conf(gallery_conf.get(...
python
{ "resource": "" }
q33898
_copy_binder_reqs
train
def _copy_binder_reqs(app, binder_conf): """Copy Binder requirements files to a "binder" folder in the docs.""" path_reqs = binder_conf.get('dependencies') for path in path_reqs: if not os.path.exists(os.path.join(app.srcdir, path)): raise ValueError(("Couldn't find the Binder requiremen...
python
{ "resource": "" }
q33899
_remove_ipynb_files
train
def _remove_ipynb_files(path, contents): """Given a list of files in `contents`, remove all files named `ipynb` or directories named `images` and return the result. Used with the `shutil` "ignore" keyword to filter out non-ipynb files.""" contents_return = [] for entry in contents: if entry...
python
{ "resource": "" }