INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Read one cell from the given lines and return the cell plus the position of the next cell
def read(self, lines): """Read one cell from the given lines, and return the cell, plus the position of the next cell """ # Do we have an explicit code marker on the first line? self.metadata_and_language_from_option_line(lines[0]) if self.metadata and 'language' in sel...
Parse code options on the given line. When a start of a code cell is found self. metadata is set to a dictionary.
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(self.start_code_r...
Parse cell till its end and set content lines_to_next_cell. Return the position of next cell start
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, self.explicit_eoc = self.find_cell_end(lines) # Metadata to dict if self.metadata is None: ...
Return position of end of cell marker and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.in_region: self.cell_type = 'markdown' for i, line in enumerate(lines): if self.end_region_re.match(line): return...
Return position of end of cell marker and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata is None and lines[0].startswith("#'"): self.cell_type = 'markdown' for i, line in enumerate(lines): if not line.startswith("...
Return position of end of cell marker and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata is None and not (self.cell_marker_end and self.end_code_re.match(lines[0])) \ and paragraph_is_fully_commented(lines, self.comment, self.default_language): ...
Find the end of the region started with start and end markers
def find_region_end(self, lines): """Find the end of the region started with start and end markers""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' parser = StringParser(self.langu...
Parse code options on the given line. When a start of a code cell is found self. metadata is set to a dictionary.
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(line[line.find('%...
Parse cell till its end and set content lines_to_next_cell. Return the position of next cell start
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, explicit_eoc = self.find_cell_end(lines) # Metadata to dict if self.start_code_re.match(lines[0]) or se...
Return position of end of cell marker and position of first line after cell
def find_cell_end(self, lines): """Return position of end of cell marker, and position of first line after cell""" if self.metadata and 'cell_type' in self.metadata: self.cell_type = self.metadata.pop('cell_type') else: self.cell_type = 'code' next_cell ...
Does this line starts a new markdown cell? Then return the cell marker
def start_of_new_markdown_cell(self, line): """Does this line starts a new markdown cell? Then, return the cell marker""" for empty_markdown_cell in ['""', "''"]: if line == empty_markdown_cell: return empty_markdown_cell for triple_quote in ['"""', "'''"]: ...
Return position of end of cell and position of first line after cell and whether there was an explicit end of cell marker
def find_cell_end(self, lines): """Return position of end of cell, and position of first line after cell, and whether there was an explicit end of cell marker""" if self.cell_type == 'markdown': # Empty cell "" or '' if len(self.markdown_marker) <= 2: ...
Parse cell till its end and set content lines_to_next_cell. Return the position of next cell start
def find_cell_content(self, lines): """Parse cell till its end and set content, lines_to_next_cell. Return the position of next cell start""" cell_end_marker, next_cell_start, explicit_eoc = self.find_cell_end(lines) # Metadata to dict cell_start = 0 if self.cell_type ==...
Given a path and options for a format ( ext suffix prefix ) return the corresponding base path
def base_path(main_path, fmt): """Given a path and options for a format (ext, suffix, prefix), return the corresponding base path""" if not fmt: return os.path.splitext(main_path)[0] fmt = long_form_one_format(fmt) fmt_ext = fmt['extension'] suffix = fmt.get('suffix') prefix = fmt.get('...
Return the full path for the notebook given the base path
def full_path(base, fmt): """Return the full path for the notebook, given the base path""" ext = fmt['extension'] suffix = fmt.get('suffix') prefix = fmt.get('prefix') full = base if prefix: prefix_dir, prefix_file_name = os.path.split(prefix) notebook_dir, notebook_file_name =...
Return the base path and the format corresponding to the given path
def find_base_path_and_format(main_path, formats): """Return the base path and the format corresponding to the given path""" for fmt in formats: try: return base_path(main_path, fmt), fmt except InconsistentPath: continue raise InconsistentPath(u"Path '{}' matches no...
Return the list of paired notebooks given main path and the list of formats
def paired_paths(main_path, fmt, formats): """Return the list of paired notebooks, given main path, and the list of formats""" if not formats: return [(main_path, {'extension': os.path.splitext(main_path)[1]})] formats = long_form_multiple_formats(formats) # Is there a format that matches the ...
Convert language and metadata information to their rmd representation: param language:: param metadata:: return:
def metadata_to_rmd_options(language, metadata): """ Convert language and metadata information to their rmd representation :param language: :param metadata: :return: """ options = (language or 'R').lower() if 'name' in metadata: options += ' ' + metadata['name'] + ',' del...
Update metadata using the _BOOLEAN_OPTIONS_DICTIONARY mapping: param name: option name: param value: option value: param metadata:: return:
def update_metadata_from_rmd_options(name, value, metadata): """ Update metadata using the _BOOLEAN_OPTIONS_DICTIONARY mapping :param name: option name :param value: option value :param metadata: :return: """ for jupyter_option, rmd_option, rev in _BOOLEAN_OPTIONS_DICTIONARY: if ...
Given a R markdown option line returns a list of pairs name value: param line:: return:
def parse_rmd_options(line): """ Given a R markdown option line, returns a list of pairs name,value :param line: :return: """ parsing_context = ParsingContext(line) result = [] prev_char = '' name = '' value = '' for char in ',' + line + ',': if parsing_context.in_...
Parse rmd options and return a metadata dictionary: param options:: return:
def rmd_options_to_metadata(options): """ Parse rmd options and return a metadata dictionary :param options: :return: """ options = re.split(r'\s|,', options, 1) if len(options) == 1: language = options[0] chunk_options = [] else: language, others = options ...
Encode { class: None key: value } into class key = value
def metadata_to_md_options(metadata): """Encode {'class':None, 'key':'value'} into 'class key="value"' """ return ' '.join(["{}={}".format(key, dumps(metadata[key])) if metadata[key] is not None else key for key in metadata])
Parse python class key = value into [ ( python None ) ( class None ) ( key value ) ]
def parse_md_code_options(options): """Parse 'python class key="value"' into [('python', None), ('class', None), ('key', 'value')]""" metadata = [] while options: name_and_value = re.split(r'[\s=]+', options, maxsplit=1) name = name_and_value[0] # Equal sign in between name and wha...
Parse markdown options and return language and metadata
def md_options_to_metadata(options): """Parse markdown options and return language and metadata""" metadata = parse_md_code_options(options) if metadata: language = metadata[0][0] for lang in _JUPYTER_LANGUAGES + ['julia', 'scheme', 'c++']: if language.lower() == lang.lower(): ...
Evaluate given metadata to a python object if possible
def try_eval_metadata(metadata, name): """Evaluate given metadata to a python object, if possible""" value = metadata[name] if not isinstance(value, (str, unicode)): return if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")): if name in [...
Read metadata from its json representation
def json_options_to_metadata(options, add_brackets=True): """Read metadata from its json representation""" try: options = loads('{' + options + '}' if add_brackets else options) return options except ValueError: return {}
Is the cell active for the given file extension?
def is_active(ext, metadata): """Is the cell active for the given file extension?""" if metadata.get('run_control', {}).get('frozen') is True: return False if 'active' not in metadata: return True return ext.replace('.', '') in re.split('\\.|,', metadata['active'])
Parse double percent options
def double_percent_options_to_metadata(options): """Parse double percent options""" matches = _PERCENT_CELL.findall('# %%' + options) # Fail safe when regexp matching fails #116 # (occurs e.g. if square brackets are found in the title) if not matches: return {'title': options.strip()} ...
Metadata to double percent lines
def metadata_to_double_percent_options(metadata): """Metadata to double percent lines""" options = [] if 'cell_depth' in metadata: options.append('%' * metadata.pop('cell_depth')) if 'title' in metadata: options.append(metadata.pop('title')) if 'cell_type' in metadata: option...
Currently inside an expression
def in_global_expression(self): """Currently inside an expression""" return (self.parenthesis_count == 0 and self.curly_bracket_count == 0 and self.square_bracket_count == 0 and not self.in_single_quote and not self.in_double_quote)
Update parenthesis counters
def count_special_chars(self, char, prev_char): """Update parenthesis counters""" if char == '(': self.parenthesis_count += 1 elif char == ')': self.parenthesis_count -= 1 if self.parenthesis_count < 0: raise RMarkdownOptionParsingError( ...
Return the implementation for the desired format
def get_format_implementation(ext, format_name=None): """Return the implementation for the desired format""" # remove pre-extension if any ext = '.' + ext.split('.')[-1] formats_for_extension = [] for fmt in JUPYTEXT_FORMATS: if fmt.extension == ext: if fmt.format_name == format...
Return the header metadata
def read_metadata(text, ext): """Return the header metadata""" ext = '.' + ext.split('.')[-1] lines = text.splitlines() if ext in ['.md', '.Rmd']: comment = '' else: comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment', '#') metadata, _, _, _ = header_to_metadata_and_cell(li...
Return the format of the file when that information is available from the metadata
def read_format_from_metadata(text, ext): """Return the format of the file, when that information is available from the metadata""" metadata = read_metadata(text, ext) rearrange_jupytext_metadata(metadata) return format_name_for_ext(metadata, ext, explicit_default=False)
Guess the format and format options of the file given its extension and content
def guess_format(text, ext): """Guess the format and format options of the file, given its extension and content""" lines = text.splitlines() metadata = read_metadata(text, ext) if ('jupytext' in metadata and set(metadata['jupytext']) .difference(['encoding', 'executable', 'main_language']...
Guess the format of the notebook based on its content #148
def divine_format(text): """Guess the format of the notebook, based on its content #148""" try: nbformat.reads(text, as_version=4) return 'ipynb' except nbformat.reader.NotJSONError: pass lines = text.splitlines() for comment in ['', '#'] + _COMMENT_CHARS: metadata, ...
Raise if file version in source file would override outputs
def check_file_version(notebook, source_path, outputs_path): """Raise if file version in source file would override outputs""" if not insert_or_test_version_number(): return _, ext = os.path.splitext(source_path) if ext.endswith('.ipynb'): return version = notebook.metadata.get('jup...
Return the format name for that extension
def format_name_for_ext(metadata, ext, cm_default_formats=None, explicit_default=True): """Return the format name for that extension""" # Is the format information available in the text representation? text_repr = metadata.get('jupytext', {}).get('text_representation', {}) if text_repr.get('extension', ...
Do the two ( long representation ) of formats target the same file?
def identical_format_path(fmt1, fmt2): """Do the two (long representation) of formats target the same file?""" for key in ['extension', 'prefix', 'suffix']: if fmt1.get(key) != fmt2.get(key): return False return True
Update the jupytext_format metadata in the Jupyter notebook
def update_jupytext_formats_metadata(metadata, new_format): """Update the jupytext_format metadata in the Jupyter notebook""" new_format = long_form_one_format(new_format) formats = long_form_multiple_formats(metadata.get('jupytext', {}).get('formats', '')) if not formats: return for fmt in...
Convert the jupytext_formats metadata entry to jupytext/ formats etc. See #91
def rearrange_jupytext_metadata(metadata): """Convert the jupytext_formats metadata entry to jupytext/formats, etc. See #91""" # Backward compatibility with nbrmd for key in ['nbrmd_formats', 'nbrmd_format_version']: if key in metadata: metadata[key.replace('nbrmd', 'jupytext')] = metad...
Parse sfx. py: percent into { suffix: sfx extension: py format_name: percent }
def long_form_one_format(jupytext_format, metadata=None, update=None): """Parse 'sfx.py:percent' into {'suffix':'sfx', 'extension':'py', 'format_name':'percent'}""" if isinstance(jupytext_format, dict): if update: jupytext_format.update(update) return validate_one_format(jupytext_for...
Convert a concise encoding of jupytext. formats to a list of formats encoded as dictionaries
def long_form_multiple_formats(jupytext_formats, metadata=None): """Convert a concise encoding of jupytext.formats to a list of formats, encoded as dictionaries""" if not jupytext_formats: return [] if not isinstance(jupytext_formats, list): jupytext_formats = [fmt for fmt in jupytext_forma...
Represent one jupytext format as a string
def short_form_one_format(jupytext_format): """Represent one jupytext format as a string""" if not isinstance(jupytext_format, dict): return jupytext_format fmt = jupytext_format['extension'] if 'suffix' in jupytext_format: fmt = jupytext_format['suffix'] + fmt elif fmt.startswith('....
Convert jupytext formats represented as a list of dictionaries to a comma separated list
def short_form_multiple_formats(jupytext_formats): """Convert jupytext formats, represented as a list of dictionaries, to a comma separated list""" if not isinstance(jupytext_formats, list): return jupytext_formats jupytext_formats = [short_form_one_format(fmt) for fmt in jupytext_formats] retu...
Validate extension and options for the given format
def validate_one_format(jupytext_format): """Validate extension and options for the given format""" if not isinstance(jupytext_format, dict): raise JupytextFormatError('Jupytext format should be a dictionary') for key in jupytext_format: if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTI...
Remove characters that may be changed when reformatting the text with black
def black_invariant(text, chars=None): """Remove characters that may be changed when reformatting the text with black""" if chars is None: chars = [' ', '\t', '\n', ',', "'", '"', '(', ')', '\\'] for char in chars: text = text.replace(char, '') return text
Copy outputs of the second notebook into the first one for cells that have matching inputs
def combine_inputs_with_outputs(nb_source, nb_outputs, fmt=None): """Copy outputs of the second notebook into the first one, for cells that have matching inputs""" output_code_cells = [cell for cell in nb_outputs.cells if cell.cell_type == 'code'] output_other_cells = [cell for cell in nb_outputs.cells...
Return the kernel specification for the first kernel with a matching language
def kernelspec_from_language(language): """Return the kernel specification for the first kernel with a matching language""" try: for name in find_kernel_specs(): kernel_specs = get_kernel_spec(name) if kernel_specs.language == language or (language == 'c++' and kernel_specs.langu...
Return the preferred format for the given extension
def preferred_format(incomplete_format, preferred_formats): """Return the preferred format for the given extension""" incomplete_format = long_form_one_format(incomplete_format) if 'format_name' in incomplete_format: return incomplete_format for fmt in long_form_multiple_formats(preferred_forma...
Remove the current notebook from the list of paired notebooks
def drop_paired_notebook(self, path): """Remove the current notebook from the list of paired notebooks""" if path not in self.paired_notebooks: return fmt, formats = self.paired_notebooks.pop(path) prev_paired_paths = paired_paths(path, fmt, formats) for alt_path, _ ...
Update the list of paired notebooks to include/ update the current pair
def update_paired_notebooks(self, path, fmt, formats): """Update the list of paired notebooks to include/update the current pair""" if not formats: self.drop_paired_notebook(path) return new_paired_paths = paired_paths(path, fmt, formats) for alt_path, _ in new_p...
Set default format option
def set_default_format_options(self, format_options, read=False): """Set default format option""" if self.default_notebook_metadata_filter: format_options.setdefault('notebook_metadata_filter', self.default_notebook_metadata_filter) if self.default_cell_metadata_filter: f...
Return the default formats if they apply to the current path #157
def default_formats(self, path): """Return the default formats, if they apply to the current path #157""" formats = long_form_multiple_formats(self.default_jupytext_formats) for fmt in formats: try: base_path(path, fmt) return self.default_jupytext_for...
Create the prefix dir if missing
def create_prefix_dir(self, path, fmt): """Create the prefix dir, if missing""" create_prefix_dir(self._get_os_path(path.strip('/')), fmt)
Save the file model and return the model with no content.
def save(self, model, path=''): """Save the file model and return the model with no content.""" if model['type'] != 'notebook': return super(TextFileContentsManager, self).save(model, path) nbk = model['content'] try: metadata = nbk.get('metadata') re...
Takes a path for an entity and returns its model
def get(self, path, content=True, type=None, format=None, load_alternative_format=True): """ Takes a path for an entity and returns its model""" path = path.strip('/') ext = os.path.splitext(path)[1] # Not a notebook? if not self.exists(path) or (type != 'notebook' if type else ...
Trust the current notebook
def trust_notebook(self, path): """Trust the current notebook""" if path.endswith('.ipynb') or path not in self.paired_notebooks: super(TextFileContentsManager, self).trust_notebook(path) return fmt, formats = self.paired_notebooks[path] for alt_path, alt_fmt in ...
Rename the current notebook as well as its alternative representations
def rename_file(self, old_path, new_path): """Rename the current notebook, as well as its alternative representations""" if old_path not in self.paired_notebooks: try: # we do not know yet if this is a paired notebook (#190) # -> to get this information we ope...
Is the first non - empty non - commented line of the cell either a function or a class?
def next_instruction_is_function_or_class(lines): """Is the first non-empty, non-commented line of the cell either a function or a class?""" for i, line in enumerate(lines): if not line.strip(): # empty line if i > 0 and not lines[i - 1].strip(): return False con...
Does the last line of the cell belong to an indented code?
def cell_ends_with_function_or_class(lines): """Does the last line of the cell belong to an indented code?""" non_quoted_lines = [] parser = StringParser('python') for line in lines: if not parser.is_quoted(): non_quoted_lines.append(line) parser.read_line(line) # find t...
Is the last line of the cell a line with code?
def cell_ends_with_code(lines): """Is the last line of the cell a line with code?""" if not lines: return False if not lines[-1].strip(): return False if lines[-1].startswith('#'): return False return True
Is there any code in this cell?
def cell_has_code(lines): """Is there any code in this cell?""" for i, line in enumerate(lines): stripped_line = line.strip() if stripped_line.startswith('#'): continue # Two consecutive blank lines? if not stripped_line: if i > 0 and not lines[i - 1].str...
How many blank lines should be added between the two python paragraphs to make them pep8?
def pep8_lines_between_cells(prev_lines, next_lines, ext): """How many blank lines should be added between the two python paragraphs to make them pep8?""" if not next_lines: return 1 if not prev_lines: return 0 if ext != '.py': return 1 if cell_ends_with_function_or_class(pre...
Cell type metadata and source from given cell
def filtered_cell(cell, preserve_outputs, cell_metadata_filter): """Cell type, metadata and source from given cell""" metadata = copy(cell.metadata) filter_metadata(metadata, cell_metadata_filter, _IGNORE_CELL_METADATA) filtered = {'cell_type': cell.cell_type, 'source': cell.source, ...
Notebook metadata filtered for metadata added by Jupytext itself
def filtered_notebook_metadata(notebook): """Notebook metadata, filtered for metadata added by Jupytext itself""" metadata = copy(notebook.metadata) metadata = filter_metadata(metadata, notebook.metadata.get('jupytext', {}).get('notebook_metadata_filter'), ...
Is the content of two cells the same except for an optional final blank line?
def same_content(ref_source, test_source, allow_removed_final_blank_line): """Is the content of two cells the same, except for an optional final blank line?""" if ref_source == test_source: return True if not allow_removed_final_blank_line: return False # Is ref identical to test, plus...
Compare the two notebooks and raise with a meaningful message that explains the differences if any
def compare_notebooks(notebook_expected, notebook_actual, fmt=None, allow_expected_differences=True, raise_on_first_difference=True, compare_outputs=False): """Compare the two notebooks, and raise with a me...
Return the source of the current cell as an array of lines
def cell_source(cell): """Return the source of the current cell, as an array of lines""" source = cell.source if source == '': return [''] if source.endswith('\n'): return source.splitlines() + [''] return source.splitlines()
Issues #31 #38: does the cell contain a blank line? In that case we add an end - of - cell marker
def endofcell_marker(source, comment): """Issues #31 #38: does the cell contain a blank line? In that case we add an end-of-cell marker""" endofcell = '-' while True: endofcell_re = re.compile(r'^{}( )'.format(comment) + endofcell + r'\s*$') if list(filter(endofcell_re.match, source)): ...
Is this cell a code cell?
def is_code(self): """Is this cell a code cell?""" if self.cell_type == 'code': return True if self.cell_type == 'raw' and 'active' in self.metadata: return True return False
Return the text representation for the cell
def cell_to_text(self): """Return the text representation for the cell""" if self.is_code(): return self.code_to_text() source = copy(self.source) if not self.comment: escape_code_start(source, self.ext, None) return self.markdown_to_text(source)
Escape the given source for a markdown cell
def markdown_to_text(self, source): """Escape the given source, for a markdown cell""" if self.comment and self.comment != "#'": source = copy(source) comment_magic(source, self.language, self.comment_magics) return comment_lines(source, self.comment)
Return the text representation of a cell
def cell_to_text(self): """Return the text representation of a cell""" if self.cell_type == 'markdown': # Is an explicit region required? if self.metadata or self.cell_reader(self.fmt).read(self.source)[1] < len(self.source): if self.metadata: ...
Return the text representation of a code cell
def code_to_text(self): """Return the text representation of a code cell""" source = copy(self.source) comment_magic(source, self.language, self.comment_magics) options = [] if self.cell_type == 'code' and self.language: options.append(self.language) filtere...
Return the text representation of a code cell
def code_to_text(self): """Return the text representation of a code cell""" active = is_active(self.ext, self.metadata) if self.language != self.default_language and 'active' not in self.metadata: active = False source = copy(self.source) escape_code_start(source, se...
Does the python representation of this cell requires an explicit start of cell marker?
def explicit_start_marker(self, source): """Does the python representation of this cell requires an explicit start of cell marker?""" if not self.use_cell_markers: return False if self.metadata: return True if self.cell_marker_start: start_code...
Remove end of cell marker when next cell has an explicit start marker
def remove_eoc_marker(self, text, next_text): """Remove end of cell marker when next cell has an explicit start marker""" if self.cell_marker_start: return text if self.is_code() and text[-1] == self.comment + ' -': # remove end of cell marker when redundant with next ex...
Simplify start of cell marker when previous line is blank
def simplify_soc_marker(self, text, prev_text): """Simplify start of cell marker when previous line is blank""" if self.cell_marker_start: return text if self.is_code() and text and text[0] == self.comment + ' + {}': if not prev_text or not prev_text[-1].strip(): ...
Return the text representation of a code cell
def code_to_text(self): """Return the text representation of a code cell""" active = is_active(self.ext, self.metadata) source = copy(self.source) escape_code_start(source, self.ext, self.language) if active: comment_magic(source, self.language, self.comment_magics) ...
Return the text representation for the cell
def cell_to_text(self): """Return the text representation for the cell""" if self.cell_type != 'code': self.metadata['cell_type'] = self.cell_type active = is_active('py', self.metadata) if self.language != self.default_language and 'active' not in self.metadata: ...
Return the text representation for the cell
def cell_to_text(self): """Return the text representation for the cell""" if self.cell_type == 'code': source = copy(self.source) return comment_magic(source, self.language, self.comment_magics) if 'cell_marker' in self.metadata: cell_marker = self.metadata.p...
Execute pandoc with the given arguments
def pandoc(args, filein=None, fileout=None): """Execute pandoc with the given arguments""" cmd = [u'pandoc'] if filein: cmd.append(filein) if fileout: cmd.append('-o') cmd.append(fileout) cmd.extend(args.split()) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) ...
Pandoc s version number
def pandoc_version(): """Pandoc's version number""" version = pandoc(u'--version').splitlines()[0].split()[1] if parse_version(version) < parse_version('2.7.2'): raise PandocError('Please install pandoc>=2.7.2 (found version {})'.format(version)) return version
Convert a Markdown text to a Jupyter notebook using Pandoc
def md_to_notebook(text): """Convert a Markdown text to a Jupyter notebook, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(text.encode('utf-8')) tmp_file.close() pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name...
Convert a notebook to its Markdown representation using Pandoc
def notebook_to_md(notebook): """Convert a notebook to its Markdown representation, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(ipynb_writes(notebook).encode('utf-8')) tmp_file.close() pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pre...
Return the smallest size int that can store the value
def _int_size(x): """Return the smallest size int that can store the value""" if -0x80 <= x <= 0x7F: return 1 elif -0x8000 <= x <= 0x7FFF: return 2 elif -0x80000000 <= x <= 0x7FFFFFFF: return 4 elif long(-0x8000000000000000) <= x <= long(0x7FFFFFFFFFFFFFFF): return 8 ...
Deserialize a BSER - encoded blob.
def loads(buf, mutable=True, value_encoding=None, value_errors=None): """Deserialize a BSER-encoded blob. @param buf: The buffer to deserialize. @type buf: bytes @param mutable: Whether to return mutable results. @type mutable: bool @param value_encoding: Optional codec to use to decode value...
The stdout of most fbcode_builder utilities is meant to be parsed.
def run_command(*cmd, **kwargs): 'The stdout of most fbcode_builder utilities is meant to be parsed.' logging.debug('Running: {0} with {1}'.format(cmd, kwargs)) kwargs['stdout'] = sys.stderr subprocess.check_call(cmd, **kwargs)
Helper to read a named config file. The grossness with the global is a workaround for this python bug: https:// bugs. python. org/ issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below.
def _inner_read_config(path): ''' Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below. ...
Sets builder configuration and returns all the builder steps necessary to build spec and its dependencies.
def steps_for_spec(builder, spec, processed_modules=None): ''' Sets `builder` configuration, and returns all the builder steps necessary to build `spec` and its dependencies. Traverses the dependencies in depth-first order, honoring the sequencing in each 'depends_on' list. ''' if processed...
Figure out where vcpkg is installed. vcpkg - exported is populated in some flavors of FB internal builds. C:/ tools/ vcpkg is the appveyor location. C:/ open/ vcpkg is my local location.
def vcpkg_dir(): """ Figure out where vcpkg is installed. vcpkg-exported is populated in some flavors of FB internal builds. C:/tools/vcpkg is the appveyor location. C:/open/vcpkg is my local location. """ for p in ["vcpkg-exported", "C:/tools/vcpkg", "C:/open/vcpkg"]: if os.path.isdir(p...
Synthesize a capability enabled version response This is a very limited emulation for relatively recent feature sets
def synthesize(vers, opts): """ Synthesize a capability enabled version response This is a very limited emulation for relatively recent feature sets """ parsed_version = parse_version(vers["version"]) vers["capabilities"] = {} for name in opts["optional"]: vers["capabilities"][name] ...
Quotes a string if it is not already quoted
def shell_quote(s): 'Quotes a string if it is not already quoted' return s if isinstance(s, ShellQuoted) \ else ShellQuoted("'" + str(s).replace("'", "'\\''") + "'")
Not a member of ShellQuoted so we get a useful error for raw strings
def raw_shell(s): 'Not a member of ShellQuoted so we get a useful error for raw strings' if isinstance(s, ShellQuoted): return s.do_not_use_raw_str raise RuntimeError('{0} should have been ShellQuoted'.format(s))
Joins an iterable of ShellQuoted with a delimiter between each two
def shell_join(delim, it): 'Joins an iterable of ShellQuoted with a delimiter between each two' return ShellQuoted(delim.join(raw_shell(s) for s in it))
Joins ShellQuoted and raw pieces of paths to make a shell - quoted path
def path_join(*args): 'Joins ShellQuoted and raw pieces of paths to make a shell-quoted path' return ShellQuoted(os.path.join(*[ raw_shell(shell_quote(s)) for s in args ]))
Do not shell - escape raw strings in comments but do handle line breaks.
def shell_comment(c): 'Do not shell-escape raw strings in comments, but do handle line breaks.' return ShellQuoted('# {c}').format(c=ShellQuoted( (raw_shell(c) if isinstance(c, ShellQuoted) else c) .replace('\n', '\n# ') ))
Locate dep in the search path ; if found return its path. If not found in the search path and the dep is not a system - provided dep raise an error
def resolve_dep(self, depname): """ Locate dep in the search path; if found, return its path. If not found in the search path, and the dep is not a system-provided dep, raise an error """ for d in self._search_path: name = os.path.join(d, depname) if self._mock: ...
If we can find the dep in the PATH then we consider it to be a system dependency that we should not bundle in the package
def resolve_dep_from_path(self, depname): """ If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package """ if is_system_dep(depname): return True for d in self._path: name = os.path.join(d, depname...