_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13500 | NGSTk.merge_or_link | train | def merge_or_link(self, input_args, raw_folder, local_base="sample"):
"""
This function standardizes various input possibilities by converting
either .bam, .fastq, or .fastq.gz files into a local file; merging those
if multiple files given.
:param list input_args: This is a list... | python | {
"resource": ""
} |
q13501 | NGSTk.input_to_fastq | train | def input_to_fastq(
self, input_file, sample_name,
paired_end, fastq_folder, output_file=None, multiclass=False):
"""
Builds a command to convert input file to fastq, for various inputs.
Takes either .bam, .fastq.gz, or .fastq input and returns
commands that will create ... | python | {
"resource": ""
} |
q13502 | NGSTk.check_fastq | train | def check_fastq(self, input_files, output_files, paired_end):
"""
Returns a follow sanity-check function to be run after a fastq conversion.
Run following a command that will produce the fastq files.
This function will make sure any input files have the same number of reads as the
... | python | {
"resource": ""
} |
q13503 | NGSTk.check_trim | train | def check_trim(self, trimmed_fastq, paired_end, trimmed_fastq_R2=None, fastqc_folder=None):
"""
Build function to evaluate read trimming, and optionally run fastqc.
This is useful to construct an argument for the 'follow' parameter of
a PipelineManager's 'run' method.
:param st... | python | {
"resource": ""
} |
q13504 | NGSTk.validate_bam | train | def validate_bam(self, input_bam):
"""
Wrapper for Picard's ValidateSamFile.
:param str input_bam: Path to file to validate.
:return str: Command to run for the validation.
"""
cmd = self.tools.java + " -Xmx" + self.pm.javamem
cmd += " -jar " + self.tools.picard ... | python | {
"resource": ""
} |
q13505 | NGSTk.merge_bams | train | def merge_bams(self, input_bams, merged_bam, in_sorted="TRUE", tmp_dir=None):
"""
Combine multiple files into one.
The tmp_dir parameter is important because on poorly configured
systems, the default can sometimes fill up.
:param Iterable[str] input_bams: Paths to files to comb... | python | {
"resource": ""
} |
q13506 | NGSTk.count_lines | train | def count_lines(self, file_name):
"""
Uses the command-line utility wc to count the number of lines in a file. For MacOS, must strip leading whitespace from wc.
:param str file_name: name of file whose lines are to be counted
"""
x = subprocess.check_output("wc -l " + file_name ... | python | {
"resource": ""
} |
q13507 | NGSTk.get_chrs_from_bam | train | def get_chrs_from_bam(self, file_name):
"""
Uses samtools to grab the chromosomes from the header that are contained
in this bam file.
"""
x = subprocess.check_output(self.tools.samtools + " view -H " + file_name + " | grep '^@SQ' | cut -f2| sed s'/SN://'", shell=True)
# ... | python | {
"resource": ""
} |
q13508 | NGSTk.count_unique_mapped_reads | train | def count_unique_mapped_reads(self, file_name, paired_end):
"""
For a bam or sam file with paired or or single-end reads, returns the
number of mapped reads, counting each read only once, even if it appears
mapped at multiple locations.
:param str file_name: name of reads file
... | python | {
"resource": ""
} |
q13509 | NGSTk.count_flag_reads | train | def count_flag_reads(self, file_name, flag, paired_end):
"""
Counts the number of reads with the specified flag.
:param str file_name: name of reads file
:param str flag: sam flag value to be read
:param bool paired_end: This parameter is ignored; samtools automatically correctl... | python | {
"resource": ""
} |
q13510 | NGSTk.count_uniquelymapping_reads | train | def count_uniquelymapping_reads(self, file_name, paired_end):
"""
Counts the number of reads that mapped to a unique position.
:param str file_name: name of reads file
:param bool paired_end: This parameter is ignored.
"""
param = " -c -F256"
if file_name.endswit... | python | {
"resource": ""
} |
q13511 | NGSTk.samtools_view | train | def samtools_view(self, file_name, param, postpend=""):
"""
Run samtools view, with flexible parameters and post-processing.
This is used internally to implement the various count_reads functions.
:param str file_name: file_name
:param str param: String of parameters to pass to... | python | {
"resource": ""
} |
q13512 | NGSTk.count_reads | train | def count_reads(self, file_name, paired_end):
"""
Count reads in a file.
Paired-end reads count as 2 in this function.
For paired-end reads, this function assumes that the reads are split
into 2 files, so it divides line count by 2 instead of 4.
This will thus give an in... | python | {
"resource": ""
} |
q13513 | NGSTk.count_concordant | train | def count_concordant(self, aligned_bam):
"""
Count only reads that "aligned concordantly exactly 1 time."
:param str aligned_bam: File for which to count mapped reads.
"""
cmd = self.tools.samtools + " view " + aligned_bam + " | "
cmd += "grep 'YT:Z:CP'" + " | uniq -u | ... | python | {
"resource": ""
} |
q13514 | NGSTk.count_mapped_reads | train | def count_mapped_reads(self, file_name, paired_end):
"""
Mapped_reads are not in fastq format, so this one doesn't need to accommodate fastq,
and therefore, doesn't require a paired-end parameter because it only uses samtools view.
Therefore, it's ok that it has a default parameter, sinc... | python | {
"resource": ""
} |
q13515 | NGSTk.sam_conversions | train | def sam_conversions(self, sam_file, depth=True):
"""
Convert sam files to bam files, then sort and index them for later use.
:param bool depth: also calculate coverage over each position
"""
cmd = self.tools.samtools + " view -bS " + sam_file + " > " + sam_file.replace(".sam", "... | python | {
"resource": ""
} |
q13516 | NGSTk.bam_conversions | train | def bam_conversions(self, bam_file, depth=True):
"""
Sort and index bam files for later use.
:param bool depth: also calculate coverage over each position
"""
cmd = self.tools.samtools + " view -h " + bam_file + " > " + bam_file.replace(".bam", ".sam") + "\n"
cmd += self... | python | {
"resource": ""
} |
q13517 | NGSTk.fastqc | train | def fastqc(self, file, output_dir):
"""
Create command to run fastqc on a FASTQ file
:param str file: Path to file with sequencing reads
:param str output_dir: Path to folder in which to place output
:return str: Command with which to run fastqc
"""
# You can fin... | python | {
"resource": ""
} |
q13518 | NGSTk.fastqc_rename | train | def fastqc_rename(self, input_bam, output_dir, sample_name):
"""
Create pair of commands to run fastqc and organize files.
The first command returned is the one that actually runs fastqc when
it's executed; the second moves the output files to the output
folder for the sample in... | python | {
"resource": ""
} |
q13519 | NGSTk.samtools_index | train | def samtools_index(self, bam_file):
"""Index a bam file."""
cmd = self.tools.samtools + " index {0}".format(bam_file)
return cmd | python | {
"resource": ""
} |
q13520 | NGSTk.skewer | train | def skewer(
self, input_fastq1, output_prefix, output_fastq1,
log, cpus, adapters, input_fastq2=None, output_fastq2=None):
"""
Create commands with which to run skewer.
:param str input_fastq1: Path to input (read 1) FASTQ file
:param str output_prefix: Prefix fo... | python | {
"resource": ""
} |
q13521 | NGSTk.filter_reads | train | def filter_reads(self, input_bam, output_bam, metrics_file, paired=False, cpus=16, Q=30):
"""
Remove duplicates, filter for >Q, remove multiple mapping reads.
For paired-end reads, keep only proper pairs.
"""
nodups = re.sub("\.bam$", "", output_bam) + ".nodups.nofilter.bam"
... | python | {
"resource": ""
} |
q13522 | NGSTk.run_spp | train | def run_spp(self, input_bam, output, plot, cpus):
"""
Run the SPP read peak analysis tool.
:param str input_bam: Path to reads file
:param str output: Path to output file
:param str plot: Path to plot file
:param int cpus: Number of processors to use
:return str:... | python | {
"resource": ""
} |
q13523 | NGSTk.calc_frip | train | def calc_frip(self, input_bam, input_bed, threads=4):
"""
Calculate fraction of reads in peaks.
A file of with a pool of sequencing reads and a file with peak call
regions define the operation that will be performed. Thread count
for samtools can be specified as well.
:... | python | {
"resource": ""
} |
q13524 | NGSTk.macs2_call_peaks | train | def macs2_call_peaks(
self, treatment_bams, output_dir, sample_name, genome,
control_bams=None, broad=False, paired=False,
pvalue=None, qvalue=None, include_significance=None):
"""
Use MACS2 to call peaks.
:param str | Iterable[str] treatment_bams... | python | {
"resource": ""
} |
q13525 | NGSTk.spp_call_peaks | train | def spp_call_peaks(
self, treatment_bam, control_bam, treatment_name, control_name,
output_dir, broad, cpus, qvalue=None):
"""
Build command for R script to call peaks with SPP.
:param str treatment_bam: Path to file with data for treatment sample.
:param... | python | {
"resource": ""
} |
q13526 | NGSTk.parse_duplicate_stats | train | def parse_duplicate_stats(self, stats_file):
"""
Parses sambamba markdup output, returns series with values.
:param str stats_file: sambamba output file with duplicate statistics.
"""
import pandas as pd
series = pd.Series()
try:
with open(stats_file)... | python | {
"resource": ""
} |
q13527 | NGSTk.get_peak_number | train | def get_peak_number(self, sample):
"""
Counts number of peaks from a sample's peak file.
:param pipelines.Sample sample: Sample object with "peaks" attribute.
"""
proc = subprocess.Popen(["wc", "-l", sample.peaks], stdout=subprocess.PIPE)
out, err = proc.communicate()
... | python | {
"resource": ""
} |
q13528 | NGSTk.get_frip | train | def get_frip(self, sample):
"""
Calculates the fraction of reads in peaks for a given sample.
:param pipelines.Sample sample: Sample object with "peaks" attribute.
"""
import pandas as pd
with open(sample.frip, "r") as handle:
content = handle.readlines()
... | python | {
"resource": ""
} |
q13529 | PipelineManager._set_status_flag | train | def _set_status_flag(self, status):
"""
Configure state and files on disk to match current processing status.
:param str status: Name of new status designation for pipeline.
"""
# Remove previous status flag file.
flag_file_path = self._flag_file_path()
try:
... | python | {
"resource": ""
} |
q13530 | PipelineManager._flag_file_path | train | def _flag_file_path(self, status=None):
"""
Create path to flag file based on indicated or current status.
Internal variables used are the pipeline name and the designated
pipeline output folder path.
:param str status: flag file type to create, default to current status
... | python | {
"resource": ""
} |
q13531 | PipelineManager._attend_process | train | def _attend_process(self, proc, sleeptime):
"""
Waits on a process for a given time to see if it finishes, returns True
if it's still running after the given time or False as soon as it
returns.
:param psutil.Popen proc: Process object opened by psutil.Popen()
:param fl... | python | {
"resource": ""
} |
q13532 | PipelineManager._wait_for_process | train | def _wait_for_process(self, p, shell=False):
"""
Debug function used in unit tests.
:param p: A subprocess.Popen process.
:param bool shell: If command requires should be run in its own shell. Optional. Default: False.
"""
local_maxmem = -1
sleeptime = .5
... | python | {
"resource": ""
} |
q13533 | PipelineManager._wait_for_lock | train | def _wait_for_lock(self, lock_file):
"""
Just sleep until the lock_file does not exist or a lock_file-related dynamic recovery flag is spotted
:param str lock_file: Lock file to wait upon.
"""
sleeptime = .5
first_message_flag = False
dot_count = 0
recove... | python | {
"resource": ""
} |
q13534 | PipelineManager.timestamp | train | def timestamp(self, message="", checkpoint=None,
finished=False, raise_error=True):
"""
Print message, time, and time elapsed, perhaps creating checkpoint.
This prints your given message, along with the current time, and time
elapsed since the previous timestamp() call... | python | {
"resource": ""
} |
q13535 | PipelineManager._report_profile | train | def _report_profile(self, command, lock_name, elapsed_time, memory):
"""
Writes a string to self.pipeline_profile_file.
"""
message_raw = str(command) + "\t " + \
str(lock_name) + "\t" + \
str(datetime.timedelta(seconds = round(elapsed_time, 2))) + "\t " + \
... | python | {
"resource": ""
} |
q13536 | PipelineManager.report_object | train | def report_object(self, key, filename, anchor_text=None, anchor_image=None,
annotation=None):
"""
Writes a string to self.pipeline_objects_file. Used to report figures and others.
:param str key: name (key) of the object
:param str filename: relative path to the file (relative to... | python | {
"resource": ""
} |
q13537 | PipelineManager._create_file_racefree | train | def _create_file_racefree(self, file):
"""
Creates a file, but fails if the file already exists.
This function will thus only succeed if this process actually creates
the file; if the file already exists, it will cause an OSError,
solving race conditions.
:par... | python | {
"resource": ""
} |
q13538 | PipelineManager.make_sure_path_exists | train | def make_sure_path_exists(self, path):
"""
Creates all directories in a path if it does not exist.
:param str path: Path to create.
:raises Exception: if the path creation attempt hits an error with
a code indicating a cause other than pre-existence.
"""
try... | python | {
"resource": ""
} |
q13539 | PipelineManager._refresh_stats | train | def _refresh_stats(self):
"""
Loads up the stats sheet created for this pipeline run and reads
those stats into memory
"""
# regex identifies all possible stats files.
#regex = self.outfolder + "*_stats.tsv"
#stats_files = glob.glob(regex)
#stats_... | python | {
"resource": ""
} |
q13540 | PipelineManager._checkpoint | train | def _checkpoint(self, stage):
"""
Decide whether to stop processing of a pipeline. This is the hook
A pipeline can report various "checkpoints" as sort of status markers
that designate the logical processing phase that's just been completed.
The initiation of a pipeline can preo... | python | {
"resource": ""
} |
q13541 | PipelineManager._touch_checkpoint | train | def _touch_checkpoint(self, check_file):
"""
Alternative way for a pipeline to designate a checkpoint.
:param str check_file: Name or path of file to use as checkpoint.
:return bool: Whether a file was written (equivalent to whether the
checkpoint file already existed).
... | python | {
"resource": ""
} |
q13542 | PipelineManager.fail_pipeline | train | def fail_pipeline(self, e, dynamic_recover=False):
"""
If the pipeline does not complete, this function will stop the pipeline gracefully.
It sets the status flag to failed and skips the normal success completion procedure.
:param Exception e: Exception to raise.
:param bool dyn... | python | {
"resource": ""
} |
q13543 | PipelineManager.halt | train | def halt(self, checkpoint=None, finished=False, raise_error=True):
"""
Stop the pipeline before completion point.
:param str checkpoint: Name of stage just reached or just completed.
:param bool finished: Whether the indicated stage was just finished
(True), or just reached ... | python | {
"resource": ""
} |
q13544 | PipelineManager.stop_pipeline | train | def stop_pipeline(self, status=COMPLETE_FLAG):
"""
Terminate the pipeline.
This is the "healthy" pipeline completion function.
The normal pipeline completion function, to be run by the pipeline
at the end of the script. It sets status flag to completed and records
some ... | python | {
"resource": ""
} |
q13545 | PipelineManager._generic_signal_handler | train | def _generic_signal_handler(self, signal_type):
"""
Function for handling both SIGTERM and SIGINT
"""
print("</pre>")
message = "Got " + signal_type + ". Failing gracefully..."
self.timestamp(message)
self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_reco... | python | {
"resource": ""
} |
q13546 | PipelineManager._exit_handler | train | def _exit_handler(self):
"""
This function I register with atexit to run whenever the script is completing.
A catch-all for uncaught exceptions, setting status flag file to failed.
"""
# TODO: consider handling sys.stderr/sys.stdout exceptions related to
# TODO (cont.): ... | python | {
"resource": ""
} |
q13547 | PipelineManager._kill_child_process | train | def _kill_child_process(self, child_pid, proc_name=None):
"""
Pypiper spawns subprocesses. We need to kill them to exit gracefully,
in the event of a pipeline termination or interrupt signal.
By default, child processes are not automatically killed when python
terminates, so Pypi... | python | {
"resource": ""
} |
q13548 | PipelineManager._memory_usage | train | def _memory_usage(self, pid='self', category="hwm", container=None):
"""
Memory usage of the process in kilobytes.
:param str pid: Process ID of process to check
:param str category: Memory type to check. 'hwm' for high water mark.
"""
if container:
# TODO: P... | python | {
"resource": ""
} |
q13549 | PipelineManager._triage_error | train | def _triage_error(self, e, nofail):
""" Print a message and decide what to do about an error. """
if not nofail:
self.fail_pipeline(e)
elif self._failed:
print("This is a nofail process, but the pipeline was terminated for other reasons, so we fail.")
raise e... | python | {
"resource": ""
} |
q13550 | read_reqs_file | train | def read_reqs_file(reqs_name):
""" Read requirements file for given requirements group. """
path_reqs_file = os.path.join(
"requirements", "reqs-{}.txt".format(reqs_name))
with open(path_reqs_file, 'r') as reqs_file:
return [pkg.rstrip() for pkg in reqs_file.readlines()
i... | python | {
"resource": ""
} |
q13551 | _is_unordered | train | def _is_unordered(collection):
"""
Determine whether a collection appears to be unordered.
This is a conservative implementation, allowing for the possibility that
someone's implemented Mapping or Set, for example, and provided an
__iter__ implementation that defines a consistent ordering of the
... | python | {
"resource": ""
} |
q13552 | _parse_stage_spec | train | def _parse_stage_spec(stage_spec):
"""
Handle alternate Stage specifications, returning name and Stage.
Isolate this parsing logic from any iteration. TypeError as single
exception type funnel also provides a more uniform way for callers to
handle specification errors (e.g., skip a stage, warn, re-... | python | {
"resource": ""
} |
q13553 | Pipeline.checkpoint | train | def checkpoint(self, stage, msg=""):
"""
Touch checkpoint file for given stage and provide timestamp message.
:param pypiper.Stage stage: Stage for which to mark checkpoint
:param str msg: Message to embed in timestamp.
:return bool: Whether a checkpoint file was written.
... | python | {
"resource": ""
} |
q13554 | Pipeline.completed_stage | train | def completed_stage(self, stage):
"""
Determine whether the pipeline's completed the stage indicated.
:param pypiper.Stage stage: Stage to check for completion status.
:return bool: Whether this pipeline's completed the indicated stage.
:raises UnknownStageException: If the stag... | python | {
"resource": ""
} |
q13555 | Pipeline.list_flags | train | def list_flags(self, only_name=False):
"""
Determine the flag files associated with this pipeline.
:param bool only_name: Whether to return only flag file name(s) (True),
or full flag file paths (False); default False (paths)
:return list[str]: flag files associated with thi... | python | {
"resource": ""
} |
q13556 | Pipeline._start_index | train | def _start_index(self, start=None):
""" Seek to the first stage to run. """
if start is None:
return 0
start_stage = translate_stage_name(start)
internal_names = [translate_stage_name(s.name) for s in self._stages]
try:
return internal_names.index(start_st... | python | {
"resource": ""
} |
q13557 | to_ufo_font_attributes | train | def to_ufo_font_attributes(self, family_name):
"""Generate a list of UFOs with metadata loaded from .glyphs data.
Modifies the list of UFOs in the UFOBuilder (self) in-place.
"""
font = self.font
# "date" can be missing; Glyphs.app removes it on saving if it's empty:
# https://github.com/goog... | python | {
"resource": ""
} |
q13558 | to_glyphs_font_attributes | train | def to_glyphs_font_attributes(self, source, master, is_initial):
"""
Copy font attributes from `ufo` either to `self.font` or to `master`.
Arguments:
self -- The UFOBuilder
ufo -- The current UFO being read
master -- The current master being written
is_initial -- True iff this the first UFO... | python | {
"resource": ""
} |
q13559 | to_ufo_glyph_background | train | def to_ufo_glyph_background(self, glyph, layer):
"""Set glyph background."""
if not layer.hasBackground:
return
background = layer.background
ufo_layer = self.to_ufo_background_layer(glyph)
new_glyph = ufo_layer.newGlyph(glyph.name)
width = background.userData[BACKGROUND_WIDTH_KEY]
... | python | {
"resource": ""
} |
q13560 | to_designspace_instances | train | def to_designspace_instances(self):
"""Write instance data from self.font to self.designspace."""
for instance in self.font.instances:
if self.minimize_glyphs_diffs or (
is_instance_active(instance)
and _is_instance_included_in_family(self, instance)
):
_to_de... | python | {
"resource": ""
} |
q13561 | apply_instance_data | train | def apply_instance_data(designspace, include_filenames=None, Font=defcon.Font):
"""Open UFO instances referenced by designspace, apply Glyphs instance
data if present, re-save UFOs and return updated UFO Font objects.
Args:
designspace: DesignSpaceDocument object or path (str or PathLike) to
... | python | {
"resource": ""
} |
q13562 | _to_ufo_features | train | def _to_ufo_features(self, master, ufo):
"""Write an UFO's OpenType feature file."""
# Recover the original feature code if it was stored in the user data
original = master.userData[ORIGINAL_FEATURE_CODE_KEY]
if original is not None:
ufo.features.text = original
return
prefixes = [... | python | {
"resource": ""
} |
q13563 | FeatureFileProcessor._pop_comment | train | def _pop_comment(self, statements, comment_re):
"""Look for the comment that matches the given regex.
If it matches, return the regex match object and list of statements
without the special one.
"""
res = []
match = None
for st in statements:
if match ... | python | {
"resource": ""
} |
q13564 | FeatureFileProcessor._pop_comment_block | train | def _pop_comment_block(self, statements, header_re):
"""Look for a series of comments that start with one that matches the
regex. If the first comment is found, all subsequent comments are
popped from statements, concatenated and dedented and returned.
"""
res = []
commen... | python | {
"resource": ""
} |
q13565 | ApiViewDeclaration.get_marshmallow_schema_name | train | def get_marshmallow_schema_name(self, plugin, schema):
"""Get the schema name.
If the schema doesn't exist, create it.
"""
try:
return plugin.openapi.refs[schema]
except KeyError:
plugin.spec.definition(schema.__name__, schema=schema)
return s... | python | {
"resource": ""
} |
q13566 | to_ufo_components | train | def to_ufo_components(self, ufo_glyph, layer):
"""Draw .glyphs components onto a pen, adding them to the parent glyph."""
pen = ufo_glyph.getPointPen()
for index, component in enumerate(layer.components):
pen.addComponent(component.name, component.transform)
if component.anchor:
... | python | {
"resource": ""
} |
q13567 | ApiView.request_args | train | def request_args(self):
"""Use args_schema to parse request query arguments."""
args = flask.request.args
data_raw = {}
for field_name, field in self.args_schema.fields.items():
alternate_field_name = field.load_from if MA2 else field.data_key
if alternate_field... | python | {
"resource": ""
} |
q13568 | ModelView.query | train | def query(self):
"""The SQLAlchemy query for the view.
Override this to customize the query to fetch items in this view.
By default, this applies the filter from the view's `authorization` and
the query options from `base_query_options` and `query_options`.
"""
query = ... | python | {
"resource": ""
} |
q13569 | ModelView.query_options | train | def query_options(self):
"""Options to apply to the query for the view.
Set this to configure relationship and column loading.
By default, this calls the ``get_query_options`` method on the
serializer with a `Load` object bound to the model, if that serializer
method exists.
... | python | {
"resource": ""
} |
q13570 | to_ufo_paths | train | def to_ufo_paths(self, ufo_glyph, layer):
"""Draw .glyphs paths onto a pen."""
pen = ufo_glyph.getPointPen()
for path in layer.paths:
# the list is changed below, otherwise you can't draw more than once
# per session.
nodes = list(path.nodes)
for node in nodes:
s... | python | {
"resource": ""
} |
q13571 | request_cached_property | train | def request_cached_property(func):
"""Make the given method a per-request cached property.
This caches the value on the request context rather than on the object
itself, preventing problems if the object gets reused across multiple
requests.
"""
@property
@functools.wraps(func)
def wrap... | python | {
"resource": ""
} |
q13572 | _ufo_logging_ref | train | def _ufo_logging_ref(ufo):
"""Return a string that can identify this UFO in logs."""
if ufo.path:
return os.path.basename(ufo.path)
return ufo.info.styleName | python | {
"resource": ""
} |
q13573 | parse_datetime | train | def parse_datetime(src=None):
"""Parse a datetime object from a string."""
if src is None:
return None
string = src.replace('"', "")
# parse timezone ourselves, since %z is not always supported
# see: http://bugs.python.org/issue6641
m = UTC_OFFSET_RE.match(string)
if m:
sign... | python | {
"resource": ""
} |
q13574 | parse_color | train | def parse_color(src=None):
# type: (Optional[str]) -> Optional[Union[Tuple[int, ...], int]]
"""Parse a string representing a color value.
Color is either a fixed color (when coloring something from the UI, see
the GLYPHS_COLORS constant) or a list of the format [u8, u8, u8, u8],
Glyphs does not su... | python | {
"resource": ""
} |
q13575 | Parser.parse | train | def parse(self, text):
"""Do the parsing."""
text = tounicode(text, encoding="utf-8")
result, i = self._parse(text, 0)
if text[i:].strip():
self._fail("Unexpected trailing content", text, i)
return result | python | {
"resource": ""
} |
q13576 | Parser.parse_into_object | train | def parse_into_object(self, res, text):
"""Parse data into an existing GSFont instance."""
text = tounicode(text, encoding="utf-8")
m = self.start_dict_re.match(text, 0)
if m:
i = self._parse_dict_into_object(res, text, 1)
else:
self._fail("not correct f... | python | {
"resource": ""
} |
q13577 | Parser._parse | train | def _parse(self, text, i):
"""Recursive function to parse a single dictionary, list, or value."""
m = self.start_dict_re.match(text, i)
if m:
parsed = m.group(0)
i += len(parsed)
return self._parse_dict(text, i)
m = self.start_list_re.match(text, i)
... | python | {
"resource": ""
} |
q13578 | Parser._parse_dict | train | def _parse_dict(self, text, i):
"""Parse a dictionary from source text starting at i."""
old_current_type = self.current_type
new_type = self.current_type
if new_type is None:
# customparameter.value needs to be set from the found value
new_type = dict
eli... | python | {
"resource": ""
} |
q13579 | Parser._parse_list | train | def _parse_list(self, text, i):
"""Parse a list from source text starting at i."""
res = []
end_match = self.end_list_re.match(text, i)
old_current_type = self.current_type
while not end_match:
list_item, i = self._parse(text, i)
res.append(list_item)
... | python | {
"resource": ""
} |
q13580 | Parser._trim_value | train | def _trim_value(self, value):
"""Trim double quotes off the ends of a value, un-escaping inner
double quotes and literal backslashes. Also convert escapes to unicode.
If the string is not quoted, return it unmodified.
"""
if value[0] == '"':
assert value[-1] == '"'
... | python | {
"resource": ""
} |
q13581 | Parser._fail | train | def _fail(self, message, text, i):
"""Raise an exception with given message and text at i."""
raise ValueError("{}:\n{}".format(message, text[i : i + 79])) | python | {
"resource": ""
} |
q13582 | build_stylemap_names | train | def build_stylemap_names(
family_name, style_name, is_bold=False, is_italic=False, linked_style=None
):
"""Build UFO `styleMapFamilyName` and `styleMapStyleName` based on the
family and style names, and the entries in the "Style Linking" section
of the "Instances" tab in the "Font Info".
The value ... | python | {
"resource": ""
} |
q13583 | to_ufo_blue_values | train | def to_ufo_blue_values(self, ufo, master):
"""Set postscript blue values from Glyphs alignment zones."""
alignment_zones = master.alignmentZones
blue_values = []
other_blues = []
for zone in sorted(alignment_zones):
pos = zone.position
size = zone.size
val_list = blue_values... | python | {
"resource": ""
} |
q13584 | to_glyphs_blue_values | train | def to_glyphs_blue_values(self, ufo, master):
"""Sets the GSFontMaster alignmentZones from the postscript blue values."""
zones = []
blue_values = _pairs(ufo.info.postscriptBlueValues)
other_blues = _pairs(ufo.info.postscriptOtherBlues)
for y1, y2 in blue_values:
size = y2 - y1
if y... | python | {
"resource": ""
} |
q13585 | parse_glyphs_filter | train | def parse_glyphs_filter(filter_str, is_pre=False):
"""Parses glyphs custom filter string into a dict object that
ufo2ft can consume.
Reference:
ufo2ft: https://github.com/googlei18n/ufo2ft
Glyphs 2.3 Handbook July 2016, p184
Args:
filter_str - a string of... | python | {
"resource": ""
} |
q13586 | build_ufo_path | train | def build_ufo_path(out_dir, family_name, style_name):
"""Build string to use as a UFO path."""
return os.path.join(
out_dir,
"%s-%s.ufo"
% ((family_name or "").replace(" ", ""), (style_name or "").replace(" ", "")),
) | python | {
"resource": ""
} |
q13587 | write_ufo | train | def write_ufo(ufo, out_dir):
"""Write a UFO."""
out_path = build_ufo_path(out_dir, ufo.info.familyName, ufo.info.styleName)
logger.info("Writing %s" % out_path)
clean_ufo(out_path)
ufo.save(out_path) | python | {
"resource": ""
} |
q13588 | clean_ufo | train | def clean_ufo(path):
"""Make sure old UFO data is removed, as it may contain deleted glyphs."""
if path.endswith(".ufo") and os.path.exists(path):
shutil.rmtree(path) | python | {
"resource": ""
} |
q13589 | ufo_create_background_layer_for_all_glyphs | train | def ufo_create_background_layer_for_all_glyphs(ufo_font):
# type: (defcon.Font) -> None
"""Create a background layer for all glyphs in ufo_font if not present to
reduce roundtrip differences."""
if "public.background" in ufo_font.layers:
background = ufo_font.layers["public.background"]
els... | python | {
"resource": ""
} |
q13590 | cast_to_number_or_bool | train | def cast_to_number_or_bool(inputstr):
"""Cast a string to int, float or bool. Return original string if it can't be
converted.
Scientific expression is converted into float.
"""
if inputstr.strip().lower() == "true":
return True
elif inputstr.strip().lower() == "false":
return F... | python | {
"resource": ""
} |
q13591 | to_ufo_background_image | train | def to_ufo_background_image(self, ufo_glyph, layer):
"""Copy the backgound image from the GSLayer to the UFO Glyph."""
image = layer.backgroundImage
if image is None:
return
ufo_image = ufo_glyph.image
ufo_image.fileName = image.path
ufo_image.transformation = image.transform
ufo_gly... | python | {
"resource": ""
} |
q13592 | to_glyphs_background_image | train | def to_glyphs_background_image(self, ufo_glyph, layer):
"""Copy the background image from the UFO Glyph to the GSLayer."""
ufo_image = ufo_glyph.image
if ufo_image.fileName is None:
return
image = self.glyphs_module.GSBackgroundImage()
image.path = ufo_image.fileName
image.transform = Tr... | python | {
"resource": ""
} |
q13593 | Api.add_resource | train | def add_resource(
self,
base_rule,
base_view,
alternate_view=None,
alternate_rule=None,
id_rule=None,
app=None,
):
"""Add route or routes for a resource.
:param str base_rule: The URL rule for the resource. This will be
prefixed by... | python | {
"resource": ""
} |
q13594 | Api.add_ping | train | def add_ping(self, rule, status_code=200, app=None):
"""Add a ping route.
:param str rule: The URL rule. This will not use the API prefix, as the
ping endpoint is not really part of the API.
:param int status_code: The ping response status code. The default is
200 rather... | python | {
"resource": ""
} |
q13595 | UFOBuilder.masters | train | def masters(self):
"""Get an iterator over master UFOs that match the given family_name.
"""
if self._sources:
for source in self._sources.values():
yield source.font
return
# Store set of actually existing master (layer) ids. This helps with
... | python | {
"resource": ""
} |
q13596 | UFOBuilder.designspace | train | def designspace(self):
"""Get a designspace Document instance that links the masters together
and holds instance data.
"""
if self._designspace_is_complete:
return self._designspace
self._designspace_is_complete = True
list(self.masters) # Make sure that the... | python | {
"resource": ""
} |
q13597 | GlyphsBuilder.font | train | def font(self):
"""Get the GSFont built from the UFOs + designspace."""
if self._font is not None:
return self._font
# Sort UFOS in the original order from the Glyphs file
sorted_sources = self.to_glyphs_ordered_masters()
# Convert all full source UFOs to Glyphs mas... | python | {
"resource": ""
} |
q13598 | GlyphsBuilder._valid_designspace | train | def _valid_designspace(self, designspace):
"""Make sure that the user-provided designspace has loaded fonts and
that names are the same as those from the UFOs.
"""
# TODO: (jany) really make a copy to avoid modifying the original object
copy = designspace
# Load only full... | python | {
"resource": ""
} |
q13599 | GlyphsBuilder._fake_designspace | train | def _fake_designspace(self, ufos):
"""Build a fake designspace with the given UFOs as sources, so that all
builder functions can rely on the presence of a designspace.
"""
designspace = designspaceLib.DesignSpaceDocument()
ufo_to_location = defaultdict(dict)
# Make weig... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.