id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
238,200
bcbio/bcbio-nextgen
bcbio/illumina/samplesheet.py
_read_input_csv
def _read_input_csv(in_file): """Parse useful details from SampleSheet CSV file. """ with io.open(in_file, newline=None) as in_handle: reader = csv.reader(in_handle) next(reader) # header for line in reader: if line: # empty lines (fc_id, lane, sample_id, genome, barcode) = line[:5] yield fc_id, lane, sample_id, genome, barcode
python
def _read_input_csv(in_file): with io.open(in_file, newline=None) as in_handle: reader = csv.reader(in_handle) next(reader) # header for line in reader: if line: # empty lines (fc_id, lane, sample_id, genome, barcode) = line[:5] yield fc_id, lane, sample_id, genome, barcode
[ "def", "_read_input_csv", "(", "in_file", ")", ":", "with", "io", ".", "open", "(", "in_file", ",", "newline", "=", "None", ")", "as", "in_handle", ":", "reader", "=", "csv", ".", "reader", "(", "in_handle", ")", "next", "(", "reader", ")", "# header",...
Parse useful details from SampleSheet CSV file.
[ "Parse", "useful", "details", "from", "SampleSheet", "CSV", "file", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L81-L90
238,201
bcbio/bcbio-nextgen
bcbio/illumina/samplesheet.py
_get_flowcell_id
def _get_flowcell_id(in_file, require_single=True): """Retrieve the unique flowcell id represented in the SampleSheet. """ fc_ids = set([x[0] for x in _read_input_csv(in_file)]) if require_single and len(fc_ids) > 1: raise ValueError("There are several FCIDs in the same samplesheet file: %s" % in_file) else: return fc_ids
python
def _get_flowcell_id(in_file, require_single=True): fc_ids = set([x[0] for x in _read_input_csv(in_file)]) if require_single and len(fc_ids) > 1: raise ValueError("There are several FCIDs in the same samplesheet file: %s" % in_file) else: return fc_ids
[ "def", "_get_flowcell_id", "(", "in_file", ",", "require_single", "=", "True", ")", ":", "fc_ids", "=", "set", "(", "[", "x", "[", "0", "]", "for", "x", "in", "_read_input_csv", "(", "in_file", ")", "]", ")", "if", "require_single", "and", "len", "(", ...
Retrieve the unique flowcell id represented in the SampleSheet.
[ "Retrieve", "the", "unique", "flowcell", "id", "represented", "in", "the", "SampleSheet", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L92-L99
238,202
bcbio/bcbio-nextgen
bcbio/illumina/samplesheet.py
csv2yaml
def csv2yaml(in_file, out_file=None): """Convert a CSV SampleSheet to YAML run_info format. """ if out_file is None: out_file = "%s.yaml" % os.path.splitext(in_file)[0] barcode_ids = _generate_barcode_ids(_read_input_csv(in_file)) lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids) with open(out_file, "w") as out_handle: out_handle.write(yaml.safe_dump(lanes, default_flow_style=False)) return out_file
python
def csv2yaml(in_file, out_file=None): if out_file is None: out_file = "%s.yaml" % os.path.splitext(in_file)[0] barcode_ids = _generate_barcode_ids(_read_input_csv(in_file)) lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids) with open(out_file, "w") as out_handle: out_handle.write(yaml.safe_dump(lanes, default_flow_style=False)) return out_file
[ "def", "csv2yaml", "(", "in_file", ",", "out_file", "=", "None", ")", ":", "if", "out_file", "is", "None", ":", "out_file", "=", "\"%s.yaml\"", "%", "os", ".", "path", ".", "splitext", "(", "in_file", ")", "[", "0", "]", "barcode_ids", "=", "_generate_...
Convert a CSV SampleSheet to YAML run_info format.
[ "Convert", "a", "CSV", "SampleSheet", "to", "YAML", "run_info", "format", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L101-L110
238,203
bcbio/bcbio-nextgen
bcbio/illumina/samplesheet.py
run_has_samplesheet
def run_has_samplesheet(fc_dir, config, require_single=True): """Checks if there's a suitable SampleSheet.csv present for the run """ fc_name, _ = flowcell.parse_dirname(fc_dir) sheet_dirs = config.get("samplesheet_directories", []) fcid_sheet = {} for ss_dir in (s for s in sheet_dirs if os.path.exists(s)): with utils.chdir(ss_dir): for ss in glob.glob("*.csv"): fc_ids = _get_flowcell_id(ss, require_single) for fcid in fc_ids: if fcid: fcid_sheet[fcid] = os.path.join(ss_dir, ss) # difflib handles human errors while entering data on the SampleSheet. # Only one best candidate is returned (if any). 0.85 cutoff allows for # maximum of 2 mismatches in fcid potential_fcids = difflib.get_close_matches(fc_name, fcid_sheet.keys(), 1, 0.85) if len(potential_fcids) > 0 and potential_fcids[0] in fcid_sheet: return fcid_sheet[potential_fcids[0]] else: return None
python
def run_has_samplesheet(fc_dir, config, require_single=True): fc_name, _ = flowcell.parse_dirname(fc_dir) sheet_dirs = config.get("samplesheet_directories", []) fcid_sheet = {} for ss_dir in (s for s in sheet_dirs if os.path.exists(s)): with utils.chdir(ss_dir): for ss in glob.glob("*.csv"): fc_ids = _get_flowcell_id(ss, require_single) for fcid in fc_ids: if fcid: fcid_sheet[fcid] = os.path.join(ss_dir, ss) # difflib handles human errors while entering data on the SampleSheet. # Only one best candidate is returned (if any). 0.85 cutoff allows for # maximum of 2 mismatches in fcid potential_fcids = difflib.get_close_matches(fc_name, fcid_sheet.keys(), 1, 0.85) if len(potential_fcids) > 0 and potential_fcids[0] in fcid_sheet: return fcid_sheet[potential_fcids[0]] else: return None
[ "def", "run_has_samplesheet", "(", "fc_dir", ",", "config", ",", "require_single", "=", "True", ")", ":", "fc_name", ",", "_", "=", "flowcell", ".", "parse_dirname", "(", "fc_dir", ")", "sheet_dirs", "=", "config", ".", "get", "(", "\"samplesheet_directories\"...
Checks if there's a suitable SampleSheet.csv present for the run
[ "Checks", "if", "there", "s", "a", "suitable", "SampleSheet", ".", "csv", "present", "for", "the", "run" ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/samplesheet.py#L112-L133
238,204
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
combine_bam
def combine_bam(in_files, out_file, config): """Parallel target to combine multiple BAM files. """ runner = broad.runner_from_path("picard", config) runner.run_fn("picard_merge", in_files, out_file) for in_file in in_files: save_diskspace(in_file, "Merged into {0}".format(out_file), config) bam.index(out_file, config) return out_file
python
def combine_bam(in_files, out_file, config): runner = broad.runner_from_path("picard", config) runner.run_fn("picard_merge", in_files, out_file) for in_file in in_files: save_diskspace(in_file, "Merged into {0}".format(out_file), config) bam.index(out_file, config) return out_file
[ "def", "combine_bam", "(", "in_files", ",", "out_file", ",", "config", ")", ":", "runner", "=", "broad", ".", "runner_from_path", "(", "\"picard\"", ",", "config", ")", "runner", ".", "run_fn", "(", "\"picard_merge\"", ",", "in_files", ",", "out_file", ")", ...
Parallel target to combine multiple BAM files.
[ "Parallel", "target", "to", "combine", "multiple", "BAM", "files", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L25-L33
238,205
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
write_nochr_reads
def write_nochr_reads(in_file, out_file, config): """Write a BAM file of reads that are not mapped on a reference chromosome. This is useful for maintaining non-mapped reads in parallel processes that split processing by chromosome. """ if not file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: samtools = config_utils.get_program("samtools", config) cmd = "{samtools} view -b -f 4 {in_file} > {tx_out_file}" do.run(cmd.format(**locals()), "Select unmapped reads") return out_file
python
def write_nochr_reads(in_file, out_file, config): if not file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: samtools = config_utils.get_program("samtools", config) cmd = "{samtools} view -b -f 4 {in_file} > {tx_out_file}" do.run(cmd.format(**locals()), "Select unmapped reads") return out_file
[ "def", "write_nochr_reads", "(", "in_file", ",", "out_file", ",", "config", ")", ":", "if", "not", "file_exists", "(", "out_file", ")", ":", "with", "file_transaction", "(", "config", ",", "out_file", ")", "as", "tx_out_file", ":", "samtools", "=", "config_u...
Write a BAM file of reads that are not mapped on a reference chromosome. This is useful for maintaining non-mapped reads in parallel processes that split processing by chromosome.
[ "Write", "a", "BAM", "file", "of", "reads", "that", "are", "not", "mapped", "on", "a", "reference", "chromosome", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L57-L68
238,206
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
write_noanalysis_reads
def write_noanalysis_reads(in_file, region_file, out_file, config): """Write a BAM file of reads in the specified region file that are not analyzed. We want to get only reads not in analysis regions but also make use of the BAM index to perform well on large files. The tricky part is avoiding command line limits. There is a nice discussion on SeqAnswers: http://seqanswers.com/forums/showthread.php?t=29538 sambamba supports intersection via an input BED file so avoids command line length issues. """ if not file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: bedtools = config_utils.get_program("bedtools", config) sambamba = config_utils.get_program("sambamba", config) cl = ("{sambamba} view -f bam -l 0 -L {region_file} {in_file} | " "{bedtools} intersect -abam - -b {region_file} -f 1.0 -nonamecheck" "> {tx_out_file}") do.run(cl.format(**locals()), "Select unanalyzed reads") return out_file
python
def write_noanalysis_reads(in_file, region_file, out_file, config): if not file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: bedtools = config_utils.get_program("bedtools", config) sambamba = config_utils.get_program("sambamba", config) cl = ("{sambamba} view -f bam -l 0 -L {region_file} {in_file} | " "{bedtools} intersect -abam - -b {region_file} -f 1.0 -nonamecheck" "> {tx_out_file}") do.run(cl.format(**locals()), "Select unanalyzed reads") return out_file
[ "def", "write_noanalysis_reads", "(", "in_file", ",", "region_file", ",", "out_file", ",", "config", ")", ":", "if", "not", "file_exists", "(", "out_file", ")", ":", "with", "file_transaction", "(", "config", ",", "out_file", ")", "as", "tx_out_file", ":", "...
Write a BAM file of reads in the specified region file that are not analyzed. We want to get only reads not in analysis regions but also make use of the BAM index to perform well on large files. The tricky part is avoiding command line limits. There is a nice discussion on SeqAnswers: http://seqanswers.com/forums/showthread.php?t=29538 sambamba supports intersection via an input BED file so avoids command line length issues.
[ "Write", "a", "BAM", "file", "of", "reads", "in", "the", "specified", "region", "file", "that", "are", "not", "analyzed", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L70-L88
238,207
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
subset_bam_by_region
def subset_bam_by_region(in_file, region, config, out_file_base=None): """Subset BAM files based on specified chromosome region. """ if out_file_base is not None: base, ext = os.path.splitext(out_file_base) else: base, ext = os.path.splitext(in_file) out_file = "%s-subset%s%s" % (base, region, ext) if not file_exists(out_file): with pysam.Samfile(in_file, "rb") as in_bam: target_tid = in_bam.gettid(region) assert region is not None, \ "Did not find reference region %s in %s" % \ (region, in_file) with file_transaction(config, out_file) as tx_out_file: with pysam.Samfile(tx_out_file, "wb", template=in_bam) as out_bam: for read in in_bam: if read.tid == target_tid: out_bam.write(read) return out_file
python
def subset_bam_by_region(in_file, region, config, out_file_base=None): if out_file_base is not None: base, ext = os.path.splitext(out_file_base) else: base, ext = os.path.splitext(in_file) out_file = "%s-subset%s%s" % (base, region, ext) if not file_exists(out_file): with pysam.Samfile(in_file, "rb") as in_bam: target_tid = in_bam.gettid(region) assert region is not None, \ "Did not find reference region %s in %s" % \ (region, in_file) with file_transaction(config, out_file) as tx_out_file: with pysam.Samfile(tx_out_file, "wb", template=in_bam) as out_bam: for read in in_bam: if read.tid == target_tid: out_bam.write(read) return out_file
[ "def", "subset_bam_by_region", "(", "in_file", ",", "region", ",", "config", ",", "out_file_base", "=", "None", ")", ":", "if", "out_file_base", "is", "not", "None", ":", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "out_file_base", ...
Subset BAM files based on specified chromosome region.
[ "Subset", "BAM", "files", "based", "on", "specified", "chromosome", "region", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L90-L109
238,208
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
subset_bed_by_chrom
def subset_bed_by_chrom(in_file, chrom, data, out_dir=None): """Subset a BED file to only have items from the specified chromosome. """ if out_dir is None: out_dir = os.path.dirname(in_file) base, ext = os.path.splitext(os.path.basename(in_file)) out_file = os.path.join(out_dir, "%s-%s%s" % (base, chrom, ext)) if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: _rewrite_bed_with_chrom(in_file, tx_out_file, chrom) return out_file
python
def subset_bed_by_chrom(in_file, chrom, data, out_dir=None): if out_dir is None: out_dir = os.path.dirname(in_file) base, ext = os.path.splitext(os.path.basename(in_file)) out_file = os.path.join(out_dir, "%s-%s%s" % (base, chrom, ext)) if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: _rewrite_bed_with_chrom(in_file, tx_out_file, chrom) return out_file
[ "def", "subset_bed_by_chrom", "(", "in_file", ",", "chrom", ",", "data", ",", "out_dir", "=", "None", ")", ":", "if", "out_dir", "is", "None", ":", "out_dir", "=", "os", ".", "path", ".", "dirname", "(", "in_file", ")", "base", ",", "ext", "=", "os",...
Subset a BED file to only have items from the specified chromosome.
[ "Subset", "a", "BED", "file", "to", "only", "have", "items", "from", "the", "specified", "chromosome", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L111-L121
238,209
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
remove_lcr_regions
def remove_lcr_regions(orig_bed, items): """If configured and available, update a BED file to remove low complexity regions. """ lcr_bed = tz.get_in(["genome_resources", "variation", "lcr"], items[0]) if lcr_bed and os.path.exists(lcr_bed) and "lcr" in get_exclude_regions(items): return _remove_regions(orig_bed, [lcr_bed], "nolcr", items[0]) else: return orig_bed
python
def remove_lcr_regions(orig_bed, items): lcr_bed = tz.get_in(["genome_resources", "variation", "lcr"], items[0]) if lcr_bed and os.path.exists(lcr_bed) and "lcr" in get_exclude_regions(items): return _remove_regions(orig_bed, [lcr_bed], "nolcr", items[0]) else: return orig_bed
[ "def", "remove_lcr_regions", "(", "orig_bed", ",", "items", ")", ":", "lcr_bed", "=", "tz", ".", "get_in", "(", "[", "\"genome_resources\"", ",", "\"variation\"", ",", "\"lcr\"", "]", ",", "items", "[", "0", "]", ")", "if", "lcr_bed", "and", "os", ".", ...
If configured and available, update a BED file to remove low complexity regions.
[ "If", "configured", "and", "available", "update", "a", "BED", "file", "to", "remove", "low", "complexity", "regions", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L143-L150
238,210
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
remove_polyx_regions
def remove_polyx_regions(in_file, items): """Remove polyX stretches, contributing to long variant runtimes. """ ex_bed = tz.get_in(["genome_resources", "variation", "polyx"], items[0]) if ex_bed and os.path.exists(ex_bed): return _remove_regions(in_file, [ex_bed], "nopolyx", items[0]) else: return in_file
python
def remove_polyx_regions(in_file, items): ex_bed = tz.get_in(["genome_resources", "variation", "polyx"], items[0]) if ex_bed and os.path.exists(ex_bed): return _remove_regions(in_file, [ex_bed], "nopolyx", items[0]) else: return in_file
[ "def", "remove_polyx_regions", "(", "in_file", ",", "items", ")", ":", "ex_bed", "=", "tz", ".", "get_in", "(", "[", "\"genome_resources\"", ",", "\"variation\"", ",", "\"polyx\"", "]", ",", "items", "[", "0", "]", ")", "if", "ex_bed", "and", "os", ".", ...
Remove polyX stretches, contributing to long variant runtimes.
[ "Remove", "polyX", "stretches", "contributing", "to", "long", "variant", "runtimes", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L152-L159
238,211
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
add_highdepth_genome_exclusion
def add_highdepth_genome_exclusion(items): """Add exclusions to input items to avoid slow runtimes on whole genomes. """ out = [] for d in items: d = utils.deepish_copy(d) if dd.get_coverage_interval(d) == "genome": e = dd.get_exclude_regions(d) if "highdepth" not in e: e.append("highdepth") d = dd.set_exclude_regions(d, e) out.append(d) return out
python
def add_highdepth_genome_exclusion(items): out = [] for d in items: d = utils.deepish_copy(d) if dd.get_coverage_interval(d) == "genome": e = dd.get_exclude_regions(d) if "highdepth" not in e: e.append("highdepth") d = dd.set_exclude_regions(d, e) out.append(d) return out
[ "def", "add_highdepth_genome_exclusion", "(", "items", ")", ":", "out", "=", "[", "]", "for", "d", "in", "items", ":", "d", "=", "utils", ".", "deepish_copy", "(", "d", ")", "if", "dd", ".", "get_coverage_interval", "(", "d", ")", "==", "\"genome\"", "...
Add exclusions to input items to avoid slow runtimes on whole genomes.
[ "Add", "exclusions", "to", "input", "items", "to", "avoid", "slow", "runtimes", "on", "whole", "genomes", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L161-L173
238,212
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
remove_highdepth_regions
def remove_highdepth_regions(in_file, items): """Remove high depth regions from a BED file for analyzing a set of calls. Tries to avoid spurious errors and slow run times in collapsed repeat regions. Also adds ENCODE blacklist regions which capture additional collapsed repeats around centromeres. """ encode_bed = tz.get_in(["genome_resources", "variation", "encode_blacklist"], items[0]) if encode_bed and os.path.exists(encode_bed): return _remove_regions(in_file, [encode_bed], "glimit", items[0]) else: return in_file
python
def remove_highdepth_regions(in_file, items): encode_bed = tz.get_in(["genome_resources", "variation", "encode_blacklist"], items[0]) if encode_bed and os.path.exists(encode_bed): return _remove_regions(in_file, [encode_bed], "glimit", items[0]) else: return in_file
[ "def", "remove_highdepth_regions", "(", "in_file", ",", "items", ")", ":", "encode_bed", "=", "tz", ".", "get_in", "(", "[", "\"genome_resources\"", ",", "\"variation\"", ",", "\"encode_blacklist\"", "]", ",", "items", "[", "0", "]", ")", "if", "encode_bed", ...
Remove high depth regions from a BED file for analyzing a set of calls. Tries to avoid spurious errors and slow run times in collapsed repeat regions. Also adds ENCODE blacklist regions which capture additional collapsed repeats around centromeres.
[ "Remove", "high", "depth", "regions", "from", "a", "BED", "file", "for", "analyzing", "a", "set", "of", "calls", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L175-L187
238,213
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
_remove_regions
def _remove_regions(in_file, remove_beds, ext, data): """Subtract a list of BED files from an input BED. General approach handling none, one and more remove_beds. """ from bcbio.variation import bedutils out_file = "%s-%s.bed" % (utils.splitext_plus(in_file)[0], ext) if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: with bedtools_tmpdir(data): if len(remove_beds) == 0: to_remove = None elif len(remove_beds) == 1: to_remove = remove_beds[0] else: to_remove = "%s-all.bed" % utils.splitext_plus(tx_out_file)[0] with open(to_remove, "w") as out_handle: for b in remove_beds: with utils.open_gzipsafe(b) as in_handle: for line in in_handle: parts = line.split("\t") out_handle.write("\t".join(parts[:4]).rstrip() + "\n") if utils.file_exists(to_remove): to_remove = bedutils.sort_merge(to_remove, data) if to_remove and utils.file_exists(to_remove): cmd = "bedtools subtract -nonamecheck -a {in_file} -b {to_remove} > {tx_out_file}" do.run(cmd.format(**locals()), "Remove problematic regions: %s" % ext) else: utils.symlink_plus(in_file, out_file) return out_file
python
def _remove_regions(in_file, remove_beds, ext, data): from bcbio.variation import bedutils out_file = "%s-%s.bed" % (utils.splitext_plus(in_file)[0], ext) if not utils.file_uptodate(out_file, in_file): with file_transaction(data, out_file) as tx_out_file: with bedtools_tmpdir(data): if len(remove_beds) == 0: to_remove = None elif len(remove_beds) == 1: to_remove = remove_beds[0] else: to_remove = "%s-all.bed" % utils.splitext_plus(tx_out_file)[0] with open(to_remove, "w") as out_handle: for b in remove_beds: with utils.open_gzipsafe(b) as in_handle: for line in in_handle: parts = line.split("\t") out_handle.write("\t".join(parts[:4]).rstrip() + "\n") if utils.file_exists(to_remove): to_remove = bedutils.sort_merge(to_remove, data) if to_remove and utils.file_exists(to_remove): cmd = "bedtools subtract -nonamecheck -a {in_file} -b {to_remove} > {tx_out_file}" do.run(cmd.format(**locals()), "Remove problematic regions: %s" % ext) else: utils.symlink_plus(in_file, out_file) return out_file
[ "def", "_remove_regions", "(", "in_file", ",", "remove_beds", ",", "ext", ",", "data", ")", ":", "from", "bcbio", ".", "variation", "import", "bedutils", "out_file", "=", "\"%s-%s.bed\"", "%", "(", "utils", ".", "splitext_plus", "(", "in_file", ")", "[", "...
Subtract a list of BED files from an input BED. General approach handling none, one and more remove_beds.
[ "Subtract", "a", "list", "of", "BED", "files", "from", "an", "input", "BED", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L189-L218
238,214
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
get_exclude_regions
def get_exclude_regions(items): """Retrieve regions to exclude from a set of items. Includes back compatibility for older custom ways of specifying different exclusions. """ def _get_sample_excludes(d): excludes = dd.get_exclude_regions(d) # back compatible if tz.get_in(("config", "algorithm", "remove_lcr"), d, False): excludes.append("lcr") return excludes out = reduce(operator.add, [_get_sample_excludes(d) for d in items]) return sorted(list(set(out)))
python
def get_exclude_regions(items): def _get_sample_excludes(d): excludes = dd.get_exclude_regions(d) # back compatible if tz.get_in(("config", "algorithm", "remove_lcr"), d, False): excludes.append("lcr") return excludes out = reduce(operator.add, [_get_sample_excludes(d) for d in items]) return sorted(list(set(out)))
[ "def", "get_exclude_regions", "(", "items", ")", ":", "def", "_get_sample_excludes", "(", "d", ")", ":", "excludes", "=", "dd", ".", "get_exclude_regions", "(", "d", ")", "# back compatible", "if", "tz", ".", "get_in", "(", "(", "\"config\"", ",", "\"algorit...
Retrieve regions to exclude from a set of items. Includes back compatibility for older custom ways of specifying different exclusions.
[ "Retrieve", "regions", "to", "exclude", "from", "a", "set", "of", "items", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L231-L244
238,215
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
to_multiregion
def to_multiregion(region): """Convert a single region or multiple region specification into multiregion list. If a single region (chrom, start, end), returns [(chrom, start, end)] otherwise returns multiregion. """ assert isinstance(region, (list, tuple)), region if isinstance(region[0], (list, tuple)): return region else: assert len(region) == 3 return [tuple(region)]
python
def to_multiregion(region): assert isinstance(region, (list, tuple)), region if isinstance(region[0], (list, tuple)): return region else: assert len(region) == 3 return [tuple(region)]
[ "def", "to_multiregion", "(", "region", ")", ":", "assert", "isinstance", "(", "region", ",", "(", "list", ",", "tuple", ")", ")", ",", "region", "if", "isinstance", "(", "region", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "retu...
Convert a single region or multiple region specification into multiregion list. If a single region (chrom, start, end), returns [(chrom, start, end)] otherwise returns multiregion.
[ "Convert", "a", "single", "region", "or", "multiple", "region", "specification", "into", "multiregion", "list", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L261-L272
238,216
bcbio/bcbio-nextgen
bcbio/pipeline/shared.py
subset_variant_regions
def subset_variant_regions(variant_regions, region, out_file, items=None, do_merge=True, data=None): """Return BED file subset by a specified chromosome region. variant_regions is a BED file, region is a chromosome name or tuple of (name, start, end) for a genomic region. """ if region is None: return variant_regions elif variant_regions is None: return region elif not isinstance(region, (list, tuple)) and region.find(":") > 0: raise ValueError("Partial chromosome regions not supported") else: merge_text = "-unmerged" if not do_merge else "" subset_file = "{0}".format(utils.splitext_plus(out_file)[0]) subset_file += "%s-regions.bed" % (merge_text) if not os.path.exists(subset_file): data = items[0] if items else data with file_transaction(data, subset_file) as tx_subset_file: if isinstance(region, (list, tuple)): _subset_bed_by_region(variant_regions, tx_subset_file, to_multiregion(region), dd.get_ref_file(data), do_merge=do_merge) else: _rewrite_bed_with_chrom(variant_regions, tx_subset_file, region) if os.path.getsize(subset_file) == 0: return region else: return subset_file
python
def subset_variant_regions(variant_regions, region, out_file, items=None, do_merge=True, data=None): if region is None: return variant_regions elif variant_regions is None: return region elif not isinstance(region, (list, tuple)) and region.find(":") > 0: raise ValueError("Partial chromosome regions not supported") else: merge_text = "-unmerged" if not do_merge else "" subset_file = "{0}".format(utils.splitext_plus(out_file)[0]) subset_file += "%s-regions.bed" % (merge_text) if not os.path.exists(subset_file): data = items[0] if items else data with file_transaction(data, subset_file) as tx_subset_file: if isinstance(region, (list, tuple)): _subset_bed_by_region(variant_regions, tx_subset_file, to_multiregion(region), dd.get_ref_file(data), do_merge=do_merge) else: _rewrite_bed_with_chrom(variant_regions, tx_subset_file, region) if os.path.getsize(subset_file) == 0: return region else: return subset_file
[ "def", "subset_variant_regions", "(", "variant_regions", ",", "region", ",", "out_file", ",", "items", "=", "None", ",", "do_merge", "=", "True", ",", "data", "=", "None", ")", ":", "if", "region", "is", "None", ":", "return", "variant_regions", "elif", "v...
Return BED file subset by a specified chromosome region. variant_regions is a BED file, region is a chromosome name or tuple of (name, start, end) for a genomic region.
[ "Return", "BED", "file", "subset", "by", "a", "specified", "chromosome", "region", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/shared.py#L275-L302
238,217
bcbio/bcbio-nextgen
bcbio/structural/delly.py
_delly_exclude_file
def _delly_exclude_file(items, base_file, chrom): """Prepare a delly-specific exclude file eliminating chromosomes. Delly wants excluded chromosomes listed as just the chromosome, with no coordinates. """ base_exclude = sshared.prepare_exclude_file(items, base_file, chrom) out_file = "%s-delly%s" % utils.splitext_plus(base_exclude) with file_transaction(items[0], out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: with open(base_exclude) as in_handle: for line in in_handle: parts = line.split("\t") if parts[0] == chrom: out_handle.write(line) else: out_handle.write("%s\n" % parts[0]) return out_file
python
def _delly_exclude_file(items, base_file, chrom): base_exclude = sshared.prepare_exclude_file(items, base_file, chrom) out_file = "%s-delly%s" % utils.splitext_plus(base_exclude) with file_transaction(items[0], out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: with open(base_exclude) as in_handle: for line in in_handle: parts = line.split("\t") if parts[0] == chrom: out_handle.write(line) else: out_handle.write("%s\n" % parts[0]) return out_file
[ "def", "_delly_exclude_file", "(", "items", ",", "base_file", ",", "chrom", ")", ":", "base_exclude", "=", "sshared", ".", "prepare_exclude_file", "(", "items", ",", "base_file", ",", "chrom", ")", "out_file", "=", "\"%s-delly%s\"", "%", "utils", ".", "splitex...
Prepare a delly-specific exclude file eliminating chromosomes. Delly wants excluded chromosomes listed as just the chromosome, with no coordinates.
[ "Prepare", "a", "delly", "-", "specific", "exclude", "file", "eliminating", "chromosomes", ".", "Delly", "wants", "excluded", "chromosomes", "listed", "as", "just", "the", "chromosome", "with", "no", "coordinates", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/delly.py#L24-L39
238,218
bcbio/bcbio-nextgen
bcbio/structural/delly.py
_run_delly
def _run_delly(bam_files, chrom, ref_file, work_dir, items): """Run delly, calling structural variations for the specified type. """ batch = sshared.get_cur_batch(items) ext = "-%s-svs" % batch if batch else "-svs" out_file = os.path.join(work_dir, "%s%s-%s.bcf" % (os.path.splitext(os.path.basename(bam_files[0]))[0], ext, chrom)) final_file = "%s.vcf.gz" % (utils.splitext_plus(out_file)[0]) cores = min(utils.get_in(items[0], ("config", "algorithm", "num_cores"), 1), len(bam_files)) if not utils.file_exists(out_file) and not utils.file_exists(final_file): with file_transaction(items[0], out_file) as tx_out_file: if sshared.has_variant_regions(items, out_file, chrom): exclude = ["-x", _delly_exclude_file(items, out_file, chrom)] cmd = ["delly", "call", "-g", ref_file, "-o", tx_out_file] + exclude + bam_files multi_cmd = "export OMP_NUM_THREADS=%s && export LC_ALL=C && " % cores try: do.run(multi_cmd + " ".join(cmd), "delly structural variant") except subprocess.CalledProcessError as msg: # Small input samples, write an empty vcf if "Sample has not enough data to estimate library parameters" in str(msg): pass # delly returns an error exit code if there are no variants elif "No structural variants found" not in str(msg): raise return [_bgzip_and_clean(out_file, items)]
python
def _run_delly(bam_files, chrom, ref_file, work_dir, items): batch = sshared.get_cur_batch(items) ext = "-%s-svs" % batch if batch else "-svs" out_file = os.path.join(work_dir, "%s%s-%s.bcf" % (os.path.splitext(os.path.basename(bam_files[0]))[0], ext, chrom)) final_file = "%s.vcf.gz" % (utils.splitext_plus(out_file)[0]) cores = min(utils.get_in(items[0], ("config", "algorithm", "num_cores"), 1), len(bam_files)) if not utils.file_exists(out_file) and not utils.file_exists(final_file): with file_transaction(items[0], out_file) as tx_out_file: if sshared.has_variant_regions(items, out_file, chrom): exclude = ["-x", _delly_exclude_file(items, out_file, chrom)] cmd = ["delly", "call", "-g", ref_file, "-o", tx_out_file] + exclude + bam_files multi_cmd = "export OMP_NUM_THREADS=%s && export LC_ALL=C && " % cores try: do.run(multi_cmd + " ".join(cmd), "delly structural variant") except subprocess.CalledProcessError as msg: # Small input samples, write an empty vcf if "Sample has not enough data to estimate library parameters" in str(msg): pass # delly returns an error exit code if there are no variants elif "No structural variants found" not in str(msg): raise return [_bgzip_and_clean(out_file, items)]
[ "def", "_run_delly", "(", "bam_files", ",", "chrom", ",", "ref_file", ",", "work_dir", ",", "items", ")", ":", "batch", "=", "sshared", ".", "get_cur_batch", "(", "items", ")", "ext", "=", "\"-%s-svs\"", "%", "batch", "if", "batch", "else", "\"-svs\"", "...
Run delly, calling structural variations for the specified type.
[ "Run", "delly", "calling", "structural", "variations", "for", "the", "specified", "type", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/delly.py#L43-L68
238,219
bcbio/bcbio-nextgen
bcbio/structural/delly.py
_bgzip_and_clean
def _bgzip_and_clean(bcf_file, items): """Create a clean bgzipped VCF output file from bcf for downstream processing. Also corrects problems with missing likelihoods: https://github.com/dellytools/delly/issues/37 GATK does not like missing GLs like '.,.,.'. This converts them to the recognized '.' """ out_file = "%s.vcf.gz" % (utils.splitext_plus(bcf_file)[0]) if not utils.file_exists(out_file): with file_transaction(items[0], out_file) as tx_out_file: if not utils.file_exists(bcf_file): vcfutils.write_empty_vcf(tx_out_file, samples=[dd.get_sample_name(d) for d in items]) else: cmd = ("bcftools view {bcf_file} | sed 's/\.,\.,\././' | bgzip -c > {tx_out_file}") do.run(cmd.format(**locals()), "Convert and clean delly output") return vcfutils.bgzip_and_index(out_file, items[0]["config"])
python
def _bgzip_and_clean(bcf_file, items): out_file = "%s.vcf.gz" % (utils.splitext_plus(bcf_file)[0]) if not utils.file_exists(out_file): with file_transaction(items[0], out_file) as tx_out_file: if not utils.file_exists(bcf_file): vcfutils.write_empty_vcf(tx_out_file, samples=[dd.get_sample_name(d) for d in items]) else: cmd = ("bcftools view {bcf_file} | sed 's/\.,\.,\././' | bgzip -c > {tx_out_file}") do.run(cmd.format(**locals()), "Convert and clean delly output") return vcfutils.bgzip_and_index(out_file, items[0]["config"])
[ "def", "_bgzip_and_clean", "(", "bcf_file", ",", "items", ")", ":", "out_file", "=", "\"%s.vcf.gz\"", "%", "(", "utils", ".", "splitext_plus", "(", "bcf_file", ")", "[", "0", "]", ")", "if", "not", "utils", ".", "file_exists", "(", "out_file", ")", ":", ...
Create a clean bgzipped VCF output file from bcf for downstream processing. Also corrects problems with missing likelihoods: https://github.com/dellytools/delly/issues/37 GATK does not like missing GLs like '.,.,.'. This converts them to the recognized '.'
[ "Create", "a", "clean", "bgzipped", "VCF", "output", "file", "from", "bcf", "for", "downstream", "processing", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/delly.py#L70-L84
238,220
bcbio/bcbio-nextgen
bcbio/structural/delly.py
_prep_subsampled_bams
def _prep_subsampled_bams(data, work_dir): """Prepare a subsampled BAM file with discordants from samblaster and minimal correct pairs. This attempts to minimize run times by pre-extracting useful reads mixed with subsampled normal pairs to estimate paired end distributions: https://groups.google.com/d/msg/delly-users/xmia4lwOd1Q/uaajoBkahAIJ Subsamples correctly aligned reads to 100 million based on speedseq defaults and evaluations on NA12878 whole genome data: https://github.com/cc2qe/speedseq/blob/ca624ba9affb0bd0fb88834ca896e9122639ec94/bin/speedseq#L1102 XXX Currently not used as new versions of delly do not get good sensitivity with downsampled BAMs. """ sr_bam, disc_bam = sshared.get_split_discordants(data, work_dir) ds_bam = bam.downsample(dd.get_align_bam(data), data, 1e8, read_filter="-F 'not secondary_alignment and proper_pair'", always_run=True, work_dir=work_dir) out_bam = "%s-final%s" % utils.splitext_plus(ds_bam) if not utils.file_exists(out_bam): bam.merge([ds_bam, sr_bam, disc_bam], out_bam, data["config"]) bam.index(out_bam, data["config"]) return [out_bam]
python
def _prep_subsampled_bams(data, work_dir): sr_bam, disc_bam = sshared.get_split_discordants(data, work_dir) ds_bam = bam.downsample(dd.get_align_bam(data), data, 1e8, read_filter="-F 'not secondary_alignment and proper_pair'", always_run=True, work_dir=work_dir) out_bam = "%s-final%s" % utils.splitext_plus(ds_bam) if not utils.file_exists(out_bam): bam.merge([ds_bam, sr_bam, disc_bam], out_bam, data["config"]) bam.index(out_bam, data["config"]) return [out_bam]
[ "def", "_prep_subsampled_bams", "(", "data", ",", "work_dir", ")", ":", "sr_bam", ",", "disc_bam", "=", "sshared", ".", "get_split_discordants", "(", "data", ",", "work_dir", ")", "ds_bam", "=", "bam", ".", "downsample", "(", "dd", ".", "get_align_bam", "(",...
Prepare a subsampled BAM file with discordants from samblaster and minimal correct pairs. This attempts to minimize run times by pre-extracting useful reads mixed with subsampled normal pairs to estimate paired end distributions: https://groups.google.com/d/msg/delly-users/xmia4lwOd1Q/uaajoBkahAIJ Subsamples correctly aligned reads to 100 million based on speedseq defaults and evaluations on NA12878 whole genome data: https://github.com/cc2qe/speedseq/blob/ca624ba9affb0bd0fb88834ca896e9122639ec94/bin/speedseq#L1102 XXX Currently not used as new versions of delly do not get good sensitivity with downsampled BAMs.
[ "Prepare", "a", "subsampled", "BAM", "file", "with", "discordants", "from", "samblaster", "and", "minimal", "correct", "pairs", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/delly.py#L88-L112
238,221
bcbio/bcbio-nextgen
bcbio/structural/delly.py
run
def run(items): """Perform detection of structural variations with delly. Performs post-call filtering with a custom filter tuned based on NA12878 Moleculo and PacBio data, using calls prepared by @ryanlayer and @cc2qe Filters using the high quality variant pairs (DV) compared with high quality reference pairs (DR). """ work_dir = utils.safe_makedir(os.path.join(items[0]["dirs"]["work"], "structural", dd.get_sample_name(items[0]), "delly")) # Add core request for delly config = copy.deepcopy(items[0]["config"]) delly_config = utils.get_in(config, ("resources", "delly"), {}) delly_config["cores"] = 1 config["resources"]["delly"] = delly_config parallel = {"type": "local", "cores": config["algorithm"].get("num_cores", 1), "progs": ["delly"]} work_bams = [dd.get_align_bam(d) for d in items] ref_file = dd.get_ref_file(items[0]) exclude_file = _get_full_exclude_file(items, work_bams, work_dir) bytype_vcfs = run_multicore(_run_delly, [(work_bams, chrom, ref_file, work_dir, items) for chrom in sshared.get_sv_chroms(items, exclude_file)], config, parallel) out_file = "%s.vcf.gz" % sshared.outname_from_inputs(bytype_vcfs) combo_vcf = vcfutils.combine_variant_files(bytype_vcfs, out_file, ref_file, config) out = [] upload_counts = collections.defaultdict(int) for data in items: if "sv" not in data: data["sv"] = [] base, ext = utils.splitext_plus(combo_vcf) final_vcf = sshared.finalize_sv(combo_vcf, data, items) if final_vcf: delly_vcf = _delly_count_evidence_filter(final_vcf, data) data["sv"].append({"variantcaller": "delly", "vrn_file": delly_vcf, "do_upload": upload_counts[final_vcf] == 0, # only upload a single file per batch "exclude": exclude_file}) upload_counts[final_vcf] += 1 out.append(data) return out
python
def run(items): work_dir = utils.safe_makedir(os.path.join(items[0]["dirs"]["work"], "structural", dd.get_sample_name(items[0]), "delly")) # Add core request for delly config = copy.deepcopy(items[0]["config"]) delly_config = utils.get_in(config, ("resources", "delly"), {}) delly_config["cores"] = 1 config["resources"]["delly"] = delly_config parallel = {"type": "local", "cores": config["algorithm"].get("num_cores", 1), "progs": ["delly"]} work_bams = [dd.get_align_bam(d) for d in items] ref_file = dd.get_ref_file(items[0]) exclude_file = _get_full_exclude_file(items, work_bams, work_dir) bytype_vcfs = run_multicore(_run_delly, [(work_bams, chrom, ref_file, work_dir, items) for chrom in sshared.get_sv_chroms(items, exclude_file)], config, parallel) out_file = "%s.vcf.gz" % sshared.outname_from_inputs(bytype_vcfs) combo_vcf = vcfutils.combine_variant_files(bytype_vcfs, out_file, ref_file, config) out = [] upload_counts = collections.defaultdict(int) for data in items: if "sv" not in data: data["sv"] = [] base, ext = utils.splitext_plus(combo_vcf) final_vcf = sshared.finalize_sv(combo_vcf, data, items) if final_vcf: delly_vcf = _delly_count_evidence_filter(final_vcf, data) data["sv"].append({"variantcaller": "delly", "vrn_file": delly_vcf, "do_upload": upload_counts[final_vcf] == 0, # only upload a single file per batch "exclude": exclude_file}) upload_counts[final_vcf] += 1 out.append(data) return out
[ "def", "run", "(", "items", ")", ":", "work_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "items", "[", "0", "]", "[", "\"dirs\"", "]", "[", "\"work\"", "]", ",", "\"structural\"", ",", "dd", ".", "get_sample_name...
Perform detection of structural variations with delly. Performs post-call filtering with a custom filter tuned based on NA12878 Moleculo and PacBio data, using calls prepared by @ryanlayer and @cc2qe Filters using the high quality variant pairs (DV) compared with high quality reference pairs (DR).
[ "Perform", "detection", "of", "structural", "variations", "with", "delly", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/delly.py#L143-L185
238,222
bcbio/bcbio-nextgen
bcbio/rnaseq/oncofuse.py
_disambiguate_star_fusion_junctions
def _disambiguate_star_fusion_junctions(star_junction_file, contamination_bam, disambig_out_file, data): """ Disambiguate detected fusions based on alignments to another species. """ out_file = disambig_out_file fusiondict = {} with open(star_junction_file, "r") as in_handle: for my_line in in_handle: my_line_split = my_line.strip().split("\t") if len(my_line_split) < 10: continue fusiondict[my_line_split[9]] = my_line.strip("\n") with pysam.Samfile(contamination_bam, "rb") as samfile: for my_read in samfile: if my_read.is_unmapped or my_read.is_secondary: continue if my_read.qname in fusiondict: fusiondict.pop(my_read.qname) with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, 'w') as myhandle: for my_key in fusiondict: print(fusiondict[my_key], file=myhandle) return out_file
python
def _disambiguate_star_fusion_junctions(star_junction_file, contamination_bam, disambig_out_file, data): out_file = disambig_out_file fusiondict = {} with open(star_junction_file, "r") as in_handle: for my_line in in_handle: my_line_split = my_line.strip().split("\t") if len(my_line_split) < 10: continue fusiondict[my_line_split[9]] = my_line.strip("\n") with pysam.Samfile(contamination_bam, "rb") as samfile: for my_read in samfile: if my_read.is_unmapped or my_read.is_secondary: continue if my_read.qname in fusiondict: fusiondict.pop(my_read.qname) with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, 'w') as myhandle: for my_key in fusiondict: print(fusiondict[my_key], file=myhandle) return out_file
[ "def", "_disambiguate_star_fusion_junctions", "(", "star_junction_file", ",", "contamination_bam", ",", "disambig_out_file", ",", "data", ")", ":", "out_file", "=", "disambig_out_file", "fusiondict", "=", "{", "}", "with", "open", "(", "star_junction_file", ",", "\"r\...
Disambiguate detected fusions based on alignments to another species.
[ "Disambiguate", "detected", "fusions", "based", "on", "alignments", "to", "another", "species", "." ]
6a9348c0054ccd5baffd22f1bb7d0422f6978b20
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/oncofuse.py#L167-L189
238,223
dylanaraps/pywal
pywal/wallpaper.py
get_desktop_env
def get_desktop_env(): """Identify the current running desktop environment.""" desktop = os.environ.get("XDG_CURRENT_DESKTOP") if desktop: return desktop desktop = os.environ.get("DESKTOP_SESSION") if desktop: return desktop desktop = os.environ.get("GNOME_DESKTOP_SESSION_ID") if desktop: return "GNOME" desktop = os.environ.get("MATE_DESKTOP_SESSION_ID") if desktop: return "MATE" desktop = os.environ.get("SWAYSOCK") if desktop: return "SWAY" desktop = os.environ.get("DESKTOP_STARTUP_ID") if desktop and "awesome" in desktop: return "AWESOME" return None
python
def get_desktop_env(): desktop = os.environ.get("XDG_CURRENT_DESKTOP") if desktop: return desktop desktop = os.environ.get("DESKTOP_SESSION") if desktop: return desktop desktop = os.environ.get("GNOME_DESKTOP_SESSION_ID") if desktop: return "GNOME" desktop = os.environ.get("MATE_DESKTOP_SESSION_ID") if desktop: return "MATE" desktop = os.environ.get("SWAYSOCK") if desktop: return "SWAY" desktop = os.environ.get("DESKTOP_STARTUP_ID") if desktop and "awesome" in desktop: return "AWESOME" return None
[ "def", "get_desktop_env", "(", ")", ":", "desktop", "=", "os", ".", "environ", ".", "get", "(", "\"XDG_CURRENT_DESKTOP\"", ")", "if", "desktop", ":", "return", "desktop", "desktop", "=", "os", ".", "environ", ".", "get", "(", "\"DESKTOP_SESSION\"", ")", "i...
Identify the current running desktop environment.
[ "Identify", "the", "current", "running", "desktop", "environment", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L13-L39
238,224
dylanaraps/pywal
pywal/wallpaper.py
set_wm_wallpaper
def set_wm_wallpaper(img): """Set the wallpaper for non desktop environments.""" if shutil.which("feh"): util.disown(["feh", "--bg-fill", img]) elif shutil.which("nitrogen"): util.disown(["nitrogen", "--set-zoom-fill", img]) elif shutil.which("bgs"): util.disown(["bgs", "-z", img]) elif shutil.which("hsetroot"): util.disown(["hsetroot", "-fill", img]) elif shutil.which("habak"): util.disown(["habak", "-mS", img]) elif shutil.which("display"): util.disown(["display", "-backdrop", "-window", "root", img]) else: logging.error("No wallpaper setter found.") return
python
def set_wm_wallpaper(img): if shutil.which("feh"): util.disown(["feh", "--bg-fill", img]) elif shutil.which("nitrogen"): util.disown(["nitrogen", "--set-zoom-fill", img]) elif shutil.which("bgs"): util.disown(["bgs", "-z", img]) elif shutil.which("hsetroot"): util.disown(["hsetroot", "-fill", img]) elif shutil.which("habak"): util.disown(["habak", "-mS", img]) elif shutil.which("display"): util.disown(["display", "-backdrop", "-window", "root", img]) else: logging.error("No wallpaper setter found.") return
[ "def", "set_wm_wallpaper", "(", "img", ")", ":", "if", "shutil", ".", "which", "(", "\"feh\"", ")", ":", "util", ".", "disown", "(", "[", "\"feh\"", ",", "\"--bg-fill\"", ",", "img", "]", ")", "elif", "shutil", ".", "which", "(", "\"nitrogen\"", ")", ...
Set the wallpaper for non desktop environments.
[ "Set", "the", "wallpaper", "for", "non", "desktop", "environments", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L48-L70
238,225
dylanaraps/pywal
pywal/wallpaper.py
set_desktop_wallpaper
def set_desktop_wallpaper(desktop, img): """Set the wallpaper for the desktop environment.""" desktop = str(desktop).lower() if "xfce" in desktop or "xubuntu" in desktop: # XFCE requires two commands since they differ between versions. xfconf("/backdrop/screen0/monitor0/image-path", img) xfconf("/backdrop/screen0/monitor0/workspace0/last-image", img) elif "muffin" in desktop or "cinnamon" in desktop: util.disown(["gsettings", "set", "org.cinnamon.desktop.background", "picture-uri", "file://" + urllib.parse.quote(img)]) elif "gnome" in desktop or "unity" in desktop: util.disown(["gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://" + urllib.parse.quote(img)]) elif "mate" in desktop: util.disown(["gsettings", "set", "org.mate.background", "picture-filename", img]) elif "sway" in desktop: util.disown(["swaymsg", "output", "*", "bg", img, "fill"]) elif "awesome" in desktop: util.disown(["awesome-client", "require('gears').wallpaper.maximized('{img}')" .format(**locals())]) else: set_wm_wallpaper(img)
python
def set_desktop_wallpaper(desktop, img): desktop = str(desktop).lower() if "xfce" in desktop or "xubuntu" in desktop: # XFCE requires two commands since they differ between versions. xfconf("/backdrop/screen0/monitor0/image-path", img) xfconf("/backdrop/screen0/monitor0/workspace0/last-image", img) elif "muffin" in desktop or "cinnamon" in desktop: util.disown(["gsettings", "set", "org.cinnamon.desktop.background", "picture-uri", "file://" + urllib.parse.quote(img)]) elif "gnome" in desktop or "unity" in desktop: util.disown(["gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://" + urllib.parse.quote(img)]) elif "mate" in desktop: util.disown(["gsettings", "set", "org.mate.background", "picture-filename", img]) elif "sway" in desktop: util.disown(["swaymsg", "output", "*", "bg", img, "fill"]) elif "awesome" in desktop: util.disown(["awesome-client", "require('gears').wallpaper.maximized('{img}')" .format(**locals())]) else: set_wm_wallpaper(img)
[ "def", "set_desktop_wallpaper", "(", "desktop", ",", "img", ")", ":", "desktop", "=", "str", "(", "desktop", ")", ".", "lower", "(", ")", "if", "\"xfce\"", "in", "desktop", "or", "\"xubuntu\"", "in", "desktop", ":", "# XFCE requires two commands since they diffe...
Set the wallpaper for the desktop environment.
[ "Set", "the", "wallpaper", "for", "the", "desktop", "environment", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L73-L105
238,226
dylanaraps/pywal
pywal/wallpaper.py
set_mac_wallpaper
def set_mac_wallpaper(img): """Set the wallpaper on macOS.""" db_file = "Library/Application Support/Dock/desktoppicture.db" db_path = os.path.join(HOME, db_file) img_dir, _ = os.path.split(img) # Clear the existing picture data and write the image paths sql = "delete from data; " sql += "insert into data values(\"%s\"); " % img_dir sql += "insert into data values(\"%s\"); " % img # Set all monitors/workspaces to the selected image sql += "update preferences set data_id=2 where key=1 or key=2 or key=3; " sql += "update preferences set data_id=1 where key=10 or key=20 or key=30;" subprocess.call(["sqlite3", db_path, sql]) # Kill the dock to fix issues with cached wallpapers. # macOS caches wallpapers and if a wallpaper is set that shares # the filename with a cached wallpaper, the cached wallpaper is # used instead. subprocess.call(["killall", "Dock"])
python
def set_mac_wallpaper(img): db_file = "Library/Application Support/Dock/desktoppicture.db" db_path = os.path.join(HOME, db_file) img_dir, _ = os.path.split(img) # Clear the existing picture data and write the image paths sql = "delete from data; " sql += "insert into data values(\"%s\"); " % img_dir sql += "insert into data values(\"%s\"); " % img # Set all monitors/workspaces to the selected image sql += "update preferences set data_id=2 where key=1 or key=2 or key=3; " sql += "update preferences set data_id=1 where key=10 or key=20 or key=30;" subprocess.call(["sqlite3", db_path, sql]) # Kill the dock to fix issues with cached wallpapers. # macOS caches wallpapers and if a wallpaper is set that shares # the filename with a cached wallpaper, the cached wallpaper is # used instead. subprocess.call(["killall", "Dock"])
[ "def", "set_mac_wallpaper", "(", "img", ")", ":", "db_file", "=", "\"Library/Application Support/Dock/desktoppicture.db\"", "db_path", "=", "os", ".", "path", ".", "join", "(", "HOME", ",", "db_file", ")", "img_dir", ",", "_", "=", "os", ".", "path", ".", "s...
Set the wallpaper on macOS.
[ "Set", "the", "wallpaper", "on", "macOS", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L108-L129
238,227
dylanaraps/pywal
pywal/wallpaper.py
set_win_wallpaper
def set_win_wallpaper(img): """Set the wallpaper on Windows.""" # There's a different command depending on the architecture # of Windows. We check the PROGRAMFILES envar since using # platform is unreliable. if "x86" in os.environ["PROGRAMFILES"]: ctypes.windll.user32.SystemParametersInfoW(20, 0, img, 3) else: ctypes.windll.user32.SystemParametersInfoA(20, 0, img, 3)
python
def set_win_wallpaper(img): # There's a different command depending on the architecture # of Windows. We check the PROGRAMFILES envar since using # platform is unreliable. if "x86" in os.environ["PROGRAMFILES"]: ctypes.windll.user32.SystemParametersInfoW(20, 0, img, 3) else: ctypes.windll.user32.SystemParametersInfoA(20, 0, img, 3)
[ "def", "set_win_wallpaper", "(", "img", ")", ":", "# There's a different command depending on the architecture", "# of Windows. We check the PROGRAMFILES envar since using", "# platform is unreliable.", "if", "\"x86\"", "in", "os", ".", "environ", "[", "\"PROGRAMFILES\"", "]", ":...
Set the wallpaper on Windows.
[ "Set", "the", "wallpaper", "on", "Windows", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L132-L140
238,228
dylanaraps/pywal
pywal/wallpaper.py
change
def change(img): """Set the wallpaper.""" if not os.path.isfile(img): return desktop = get_desktop_env() if OS == "Darwin": set_mac_wallpaper(img) elif OS == "Windows": set_win_wallpaper(img) else: set_desktop_wallpaper(desktop, img) logging.info("Set the new wallpaper.")
python
def change(img): if not os.path.isfile(img): return desktop = get_desktop_env() if OS == "Darwin": set_mac_wallpaper(img) elif OS == "Windows": set_win_wallpaper(img) else: set_desktop_wallpaper(desktop, img) logging.info("Set the new wallpaper.")
[ "def", "change", "(", "img", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "img", ")", ":", "return", "desktop", "=", "get_desktop_env", "(", ")", "if", "OS", "==", "\"Darwin\"", ":", "set_mac_wallpaper", "(", "img", ")", "elif", "OS"...
Set the wallpaper.
[ "Set", "the", "wallpaper", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L143-L159
238,229
dylanaraps/pywal
pywal/wallpaper.py
get
def get(cache_dir=CACHE_DIR): """Get the current wallpaper.""" current_wall = os.path.join(cache_dir, "wal") if os.path.isfile(current_wall): return util.read_file(current_wall)[0] return "None"
python
def get(cache_dir=CACHE_DIR): current_wall = os.path.join(cache_dir, "wal") if os.path.isfile(current_wall): return util.read_file(current_wall)[0] return "None"
[ "def", "get", "(", "cache_dir", "=", "CACHE_DIR", ")", ":", "current_wall", "=", "os", ".", "path", ".", "join", "(", "cache_dir", ",", "\"wal\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "current_wall", ")", ":", "return", "util", ".", "rea...
Get the current wallpaper.
[ "Get", "the", "current", "wallpaper", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/wallpaper.py#L162-L169
238,230
dylanaraps/pywal
pywal/util.py
save_file_json
def save_file_json(data, export_file): """Write data to a json file.""" create_dir(os.path.dirname(export_file)) with open(export_file, "w") as file: json.dump(data, file, indent=4)
python
def save_file_json(data, export_file): create_dir(os.path.dirname(export_file)) with open(export_file, "w") as file: json.dump(data, file, indent=4)
[ "def", "save_file_json", "(", "data", ",", "export_file", ")", ":", "create_dir", "(", "os", ".", "path", ".", "dirname", "(", "export_file", ")", ")", "with", "open", "(", "export_file", ",", "\"w\"", ")", "as", "file", ":", "json", ".", "dump", "(", ...
Write data to a json file.
[ "Write", "data", "to", "a", "json", "file", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L90-L95
238,231
dylanaraps/pywal
pywal/util.py
setup_logging
def setup_logging(): """Logging config.""" logging.basicConfig(format=("[%(levelname)s\033[0m] " "\033[1;31m%(module)s\033[0m: " "%(message)s"), level=logging.INFO, stream=sys.stdout) logging.addLevelName(logging.ERROR, '\033[1;31mE') logging.addLevelName(logging.INFO, '\033[1;32mI') logging.addLevelName(logging.WARNING, '\033[1;33mW')
python
def setup_logging(): logging.basicConfig(format=("[%(levelname)s\033[0m] " "\033[1;31m%(module)s\033[0m: " "%(message)s"), level=logging.INFO, stream=sys.stdout) logging.addLevelName(logging.ERROR, '\033[1;31mE') logging.addLevelName(logging.INFO, '\033[1;32mI') logging.addLevelName(logging.WARNING, '\033[1;33mW')
[ "def", "setup_logging", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "(", "\"[%(levelname)s\\033[0m] \"", "\"\\033[1;31m%(module)s\\033[0m: \"", "\"%(message)s\"", ")", ",", "level", "=", "logging", ".", "INFO", ",", "stream", "=", "sys", ".",...
Logging config.
[ "Logging", "config", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L103-L112
238,232
dylanaraps/pywal
pywal/util.py
darken_color
def darken_color(color, amount): """Darken a hex color.""" color = [int(col * (1 - amount)) for col in hex_to_rgb(color)] return rgb_to_hex(color)
python
def darken_color(color, amount): color = [int(col * (1 - amount)) for col in hex_to_rgb(color)] return rgb_to_hex(color)
[ "def", "darken_color", "(", "color", ",", "amount", ")", ":", "color", "=", "[", "int", "(", "col", "*", "(", "1", "-", "amount", ")", ")", "for", "col", "in", "hex_to_rgb", "(", "color", ")", "]", "return", "rgb_to_hex", "(", "color", ")" ]
Darken a hex color.
[ "Darken", "a", "hex", "color", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L131-L134
238,233
dylanaraps/pywal
pywal/util.py
lighten_color
def lighten_color(color, amount): """Lighten a hex color.""" color = [int(col + (255 - col) * amount) for col in hex_to_rgb(color)] return rgb_to_hex(color)
python
def lighten_color(color, amount): color = [int(col + (255 - col) * amount) for col in hex_to_rgb(color)] return rgb_to_hex(color)
[ "def", "lighten_color", "(", "color", ",", "amount", ")", ":", "color", "=", "[", "int", "(", "col", "+", "(", "255", "-", "col", ")", "*", "amount", ")", "for", "col", "in", "hex_to_rgb", "(", "color", ")", "]", "return", "rgb_to_hex", "(", "color...
Lighten a hex color.
[ "Lighten", "a", "hex", "color", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L137-L140
238,234
dylanaraps/pywal
pywal/util.py
blend_color
def blend_color(color, color2): """Blend two colors together.""" r1, g1, b1 = hex_to_rgb(color) r2, g2, b2 = hex_to_rgb(color2) r3 = int(0.5 * r1 + 0.5 * r2) g3 = int(0.5 * g1 + 0.5 * g2) b3 = int(0.5 * b1 + 0.5 * b2) return rgb_to_hex((r3, g3, b3))
python
def blend_color(color, color2): r1, g1, b1 = hex_to_rgb(color) r2, g2, b2 = hex_to_rgb(color2) r3 = int(0.5 * r1 + 0.5 * r2) g3 = int(0.5 * g1 + 0.5 * g2) b3 = int(0.5 * b1 + 0.5 * b2) return rgb_to_hex((r3, g3, b3))
[ "def", "blend_color", "(", "color", ",", "color2", ")", ":", "r1", ",", "g1", ",", "b1", "=", "hex_to_rgb", "(", "color", ")", "r2", ",", "g2", ",", "b2", "=", "hex_to_rgb", "(", "color2", ")", "r3", "=", "int", "(", "0.5", "*", "r1", "+", "0.5...
Blend two colors together.
[ "Blend", "two", "colors", "together", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L143-L152
238,235
dylanaraps/pywal
pywal/util.py
saturate_color
def saturate_color(color, amount): """Saturate a hex color.""" r, g, b = hex_to_rgb(color) r, g, b = [x/255.0 for x in (r, g, b)] h, l, s = colorsys.rgb_to_hls(r, g, b) s = amount r, g, b = colorsys.hls_to_rgb(h, l, s) r, g, b = [x*255.0 for x in (r, g, b)] return rgb_to_hex((int(r), int(g), int(b)))
python
def saturate_color(color, amount): r, g, b = hex_to_rgb(color) r, g, b = [x/255.0 for x in (r, g, b)] h, l, s = colorsys.rgb_to_hls(r, g, b) s = amount r, g, b = colorsys.hls_to_rgb(h, l, s) r, g, b = [x*255.0 for x in (r, g, b)] return rgb_to_hex((int(r), int(g), int(b)))
[ "def", "saturate_color", "(", "color", ",", "amount", ")", ":", "r", ",", "g", ",", "b", "=", "hex_to_rgb", "(", "color", ")", "r", ",", "g", ",", "b", "=", "[", "x", "/", "255.0", "for", "x", "in", "(", "r", ",", "g", ",", "b", ")", "]", ...
Saturate a hex color.
[ "Saturate", "a", "hex", "color", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L155-L164
238,236
dylanaraps/pywal
pywal/util.py
disown
def disown(cmd): """Call a system command in the background, disown it and hide it's output.""" subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
python
def disown(cmd): subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
[ "def", "disown", "(", "cmd", ")", ":", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "DEVNULL", ",", "stderr", "=", "subprocess", ".", "DEVNULL", ")" ]
Call a system command in the background, disown it and hide it's output.
[ "Call", "a", "system", "command", "in", "the", "background", "disown", "it", "and", "hide", "it", "s", "output", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L172-L177
238,237
dylanaraps/pywal
pywal/util.py
get_pid
def get_pid(name): """Check if process is running by name.""" if not shutil.which("pidof"): return False try: subprocess.check_output(["pidof", "-s", name]) except subprocess.CalledProcessError: return False return True
python
def get_pid(name): if not shutil.which("pidof"): return False try: subprocess.check_output(["pidof", "-s", name]) except subprocess.CalledProcessError: return False return True
[ "def", "get_pid", "(", "name", ")", ":", "if", "not", "shutil", ".", "which", "(", "\"pidof\"", ")", ":", "return", "False", "try", ":", "subprocess", ".", "check_output", "(", "[", "\"pidof\"", ",", "\"-s\"", ",", "name", "]", ")", "except", "subproce...
Check if process is running by name.
[ "Check", "if", "process", "is", "running", "by", "name", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/util.py#L180-L190
238,238
dylanaraps/pywal
pywal/image.py
get_image_dir
def get_image_dir(img_dir): """Get all images in a directory.""" current_wall = wallpaper.get() current_wall = os.path.basename(current_wall) file_types = (".png", ".jpg", ".jpeg", ".jpe", ".gif") return [img.name for img in os.scandir(img_dir) if img.name.lower().endswith(file_types)], current_wall
python
def get_image_dir(img_dir): current_wall = wallpaper.get() current_wall = os.path.basename(current_wall) file_types = (".png", ".jpg", ".jpeg", ".jpe", ".gif") return [img.name for img in os.scandir(img_dir) if img.name.lower().endswith(file_types)], current_wall
[ "def", "get_image_dir", "(", "img_dir", ")", ":", "current_wall", "=", "wallpaper", ".", "get", "(", ")", "current_wall", "=", "os", ".", "path", ".", "basename", "(", "current_wall", ")", "file_types", "=", "(", "\".png\"", ",", "\".jpg\"", ",", "\".jpeg\...
Get all images in a directory.
[ "Get", "all", "images", "in", "a", "directory", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/image.py#L15-L23
238,239
dylanaraps/pywal
pywal/image.py
get_random_image
def get_random_image(img_dir): """Pick a random image file from a directory.""" images, current_wall = get_image_dir(img_dir) if len(images) > 2 and current_wall in images: images.remove(current_wall) elif not images: logging.error("No images found in directory.") sys.exit(1) random.shuffle(images) return os.path.join(img_dir, images[0])
python
def get_random_image(img_dir): images, current_wall = get_image_dir(img_dir) if len(images) > 2 and current_wall in images: images.remove(current_wall) elif not images: logging.error("No images found in directory.") sys.exit(1) random.shuffle(images) return os.path.join(img_dir, images[0])
[ "def", "get_random_image", "(", "img_dir", ")", ":", "images", ",", "current_wall", "=", "get_image_dir", "(", "img_dir", ")", "if", "len", "(", "images", ")", ">", "2", "and", "current_wall", "in", "images", ":", "images", ".", "remove", "(", "current_wal...
Pick a random image file from a directory.
[ "Pick", "a", "random", "image", "file", "from", "a", "directory", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/image.py#L26-L38
238,240
dylanaraps/pywal
pywal/image.py
get_next_image
def get_next_image(img_dir): """Get the next image in a dir.""" images, current_wall = get_image_dir(img_dir) images.sort(key=lambda img: [int(x) if x.isdigit() else x for x in re.split('([0-9]+)', img)]) try: next_index = images.index(current_wall) + 1 except ValueError: next_index = 0 try: image = images[next_index] except IndexError: image = images[0] return os.path.join(img_dir, image)
python
def get_next_image(img_dir): images, current_wall = get_image_dir(img_dir) images.sort(key=lambda img: [int(x) if x.isdigit() else x for x in re.split('([0-9]+)', img)]) try: next_index = images.index(current_wall) + 1 except ValueError: next_index = 0 try: image = images[next_index] except IndexError: image = images[0] return os.path.join(img_dir, image)
[ "def", "get_next_image", "(", "img_dir", ")", ":", "images", ",", "current_wall", "=", "get_image_dir", "(", "img_dir", ")", "images", ".", "sort", "(", "key", "=", "lambda", "img", ":", "[", "int", "(", "x", ")", "if", "x", ".", "isdigit", "(", ")",...
Get the next image in a dir.
[ "Get", "the", "next", "image", "in", "a", "dir", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/image.py#L41-L59
238,241
dylanaraps/pywal
pywal/image.py
get
def get(img, cache_dir=CACHE_DIR, iterative=False): """Validate image input.""" if os.path.isfile(img): wal_img = img elif os.path.isdir(img): if iterative: wal_img = get_next_image(img) else: wal_img = get_random_image(img) else: logging.error("No valid image file found.") sys.exit(1) wal_img = os.path.abspath(wal_img) # Cache the image file path. util.save_file(wal_img, os.path.join(cache_dir, "wal")) logging.info("Using image \033[1;37m%s\033[0m.", os.path.basename(wal_img)) return wal_img
python
def get(img, cache_dir=CACHE_DIR, iterative=False): if os.path.isfile(img): wal_img = img elif os.path.isdir(img): if iterative: wal_img = get_next_image(img) else: wal_img = get_random_image(img) else: logging.error("No valid image file found.") sys.exit(1) wal_img = os.path.abspath(wal_img) # Cache the image file path. util.save_file(wal_img, os.path.join(cache_dir, "wal")) logging.info("Using image \033[1;37m%s\033[0m.", os.path.basename(wal_img)) return wal_img
[ "def", "get", "(", "img", ",", "cache_dir", "=", "CACHE_DIR", ",", "iterative", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "img", ")", ":", "wal_img", "=", "img", "elif", "os", ".", "path", ".", "isdir", "(", "img", ")",...
Validate image input.
[ "Validate", "image", "input", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/image.py#L62-L84
238,242
dylanaraps/pywal
pywal/scripts/gtk_reload.py
gtk_reload
def gtk_reload(): """Reload GTK2 themes.""" events = gtk.gdk.Event(gtk.gdk.CLIENT_EVENT) data = gtk.gdk.atom_intern("_GTK_READ_RCFILES", False) events.data_format = 8 events.send_event = True events.message_type = data events.send_clientmessage_toall()
python
def gtk_reload(): events = gtk.gdk.Event(gtk.gdk.CLIENT_EVENT) data = gtk.gdk.atom_intern("_GTK_READ_RCFILES", False) events.data_format = 8 events.send_event = True events.message_type = data events.send_clientmessage_toall()
[ "def", "gtk_reload", "(", ")", ":", "events", "=", "gtk", ".", "gdk", ".", "Event", "(", "gtk", ".", "gdk", ".", "CLIENT_EVENT", ")", "data", "=", "gtk", ".", "gdk", ".", "atom_intern", "(", "\"_GTK_READ_RCFILES\"", ",", "False", ")", "events", ".", ...
Reload GTK2 themes.
[ "Reload", "GTK2", "themes", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/scripts/gtk_reload.py#L17-L24
238,243
dylanaraps/pywal
pywal/colors.py
list_backends
def list_backends(): """List color backends.""" return [b.name.replace(".py", "") for b in os.scandir(os.path.join(MODULE_DIR, "backends")) if "__" not in b.name]
python
def list_backends(): return [b.name.replace(".py", "") for b in os.scandir(os.path.join(MODULE_DIR, "backends")) if "__" not in b.name]
[ "def", "list_backends", "(", ")", ":", "return", "[", "b", ".", "name", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "for", "b", "in", "os", ".", "scandir", "(", "os", ".", "path", ".", "join", "(", "MODULE_DIR", ",", "\"backends\"", ")", ")",...
List color backends.
[ "List", "color", "backends", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L15-L19
238,244
dylanaraps/pywal
pywal/colors.py
colors_to_dict
def colors_to_dict(colors, img): """Convert list of colors to pywal format.""" return { "wallpaper": img, "alpha": util.Color.alpha_num, "special": { "background": colors[0], "foreground": colors[15], "cursor": colors[15] }, "colors": { "color0": colors[0], "color1": colors[1], "color2": colors[2], "color3": colors[3], "color4": colors[4], "color5": colors[5], "color6": colors[6], "color7": colors[7], "color8": colors[8], "color9": colors[9], "color10": colors[10], "color11": colors[11], "color12": colors[12], "color13": colors[13], "color14": colors[14], "color15": colors[15] } }
python
def colors_to_dict(colors, img): return { "wallpaper": img, "alpha": util.Color.alpha_num, "special": { "background": colors[0], "foreground": colors[15], "cursor": colors[15] }, "colors": { "color0": colors[0], "color1": colors[1], "color2": colors[2], "color3": colors[3], "color4": colors[4], "color5": colors[5], "color6": colors[6], "color7": colors[7], "color8": colors[8], "color9": colors[9], "color10": colors[10], "color11": colors[11], "color12": colors[12], "color13": colors[13], "color14": colors[14], "color15": colors[15] } }
[ "def", "colors_to_dict", "(", "colors", ",", "img", ")", ":", "return", "{", "\"wallpaper\"", ":", "img", ",", "\"alpha\"", ":", "util", ".", "Color", ".", "alpha_num", ",", "\"special\"", ":", "{", "\"background\"", ":", "colors", "[", "0", "]", ",", ...
Convert list of colors to pywal format.
[ "Convert", "list", "of", "colors", "to", "pywal", "format", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L22-L52
238,245
dylanaraps/pywal
pywal/colors.py
generic_adjust
def generic_adjust(colors, light): """Generic color adjustment for themers.""" if light: for color in colors: color = util.saturate_color(color, 0.60) color = util.darken_color(color, 0.5) colors[0] = util.lighten_color(colors[0], 0.95) colors[7] = util.darken_color(colors[0], 0.75) colors[8] = util.darken_color(colors[0], 0.25) colors[15] = colors[7] else: colors[0] = util.darken_color(colors[0], 0.80) colors[7] = util.lighten_color(colors[0], 0.75) colors[8] = util.lighten_color(colors[0], 0.25) colors[15] = colors[7] return colors
python
def generic_adjust(colors, light): if light: for color in colors: color = util.saturate_color(color, 0.60) color = util.darken_color(color, 0.5) colors[0] = util.lighten_color(colors[0], 0.95) colors[7] = util.darken_color(colors[0], 0.75) colors[8] = util.darken_color(colors[0], 0.25) colors[15] = colors[7] else: colors[0] = util.darken_color(colors[0], 0.80) colors[7] = util.lighten_color(colors[0], 0.75) colors[8] = util.lighten_color(colors[0], 0.25) colors[15] = colors[7] return colors
[ "def", "generic_adjust", "(", "colors", ",", "light", ")", ":", "if", "light", ":", "for", "color", "in", "colors", ":", "color", "=", "util", ".", "saturate_color", "(", "color", ",", "0.60", ")", "color", "=", "util", ".", "darken_color", "(", "color...
Generic color adjustment for themers.
[ "Generic", "color", "adjustment", "for", "themers", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L55-L73
238,246
dylanaraps/pywal
pywal/colors.py
saturate_colors
def saturate_colors(colors, amount): """Saturate all colors.""" if amount and float(amount) <= 1.0: for i, _ in enumerate(colors): if i not in [0, 7, 8, 15]: colors[i] = util.saturate_color(colors[i], float(amount)) return colors
python
def saturate_colors(colors, amount): if amount and float(amount) <= 1.0: for i, _ in enumerate(colors): if i not in [0, 7, 8, 15]: colors[i] = util.saturate_color(colors[i], float(amount)) return colors
[ "def", "saturate_colors", "(", "colors", ",", "amount", ")", ":", "if", "amount", "and", "float", "(", "amount", ")", "<=", "1.0", ":", "for", "i", ",", "_", "in", "enumerate", "(", "colors", ")", ":", "if", "i", "not", "in", "[", "0", ",", "7", ...
Saturate all colors.
[ "Saturate", "all", "colors", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L76-L83
238,247
dylanaraps/pywal
pywal/colors.py
get_backend
def get_backend(backend): """Figure out which backend to use.""" if backend == "random": backends = list_backends() random.shuffle(backends) return backends[0] return backend
python
def get_backend(backend): if backend == "random": backends = list_backends() random.shuffle(backends) return backends[0] return backend
[ "def", "get_backend", "(", "backend", ")", ":", "if", "backend", "==", "\"random\"", ":", "backends", "=", "list_backends", "(", ")", "random", ".", "shuffle", "(", "backends", ")", "return", "backends", "[", "0", "]", "return", "backend" ]
Figure out which backend to use.
[ "Figure", "out", "which", "backend", "to", "use", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L97-L104
238,248
dylanaraps/pywal
pywal/colors.py
palette
def palette(): """Generate a palette from the colors.""" for i in range(0, 16): if i % 8 == 0: print() if i > 7: i = "8;5;%s" % i print("\033[4%sm%s\033[0m" % (i, " " * (80 // 20)), end="") print("\n")
python
def palette(): for i in range(0, 16): if i % 8 == 0: print() if i > 7: i = "8;5;%s" % i print("\033[4%sm%s\033[0m" % (i, " " * (80 // 20)), end="") print("\n")
[ "def", "palette", "(", ")", ":", "for", "i", "in", "range", "(", "0", ",", "16", ")", ":", "if", "i", "%", "8", "==", "0", ":", "print", "(", ")", "if", "i", ">", "7", ":", "i", "=", "\"8;5;%s\"", "%", "i", "print", "(", "\"\\033[4%sm%s\\033[...
Generate a palette from the colors.
[ "Generate", "a", "palette", "from", "the", "colors", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/colors.py#L107-L118
238,249
dylanaraps/pywal
pywal/backends/colorthief.py
gen_colors
def gen_colors(img): """Loop until 16 colors are generated.""" color_cmd = ColorThief(img).get_palette for i in range(0, 10, 1): raw_colors = color_cmd(color_count=8 + i) if len(raw_colors) >= 8: break elif i == 10: logging.error("ColorThief couldn't generate a suitable palette.") sys.exit(1) else: logging.warning("ColorThief couldn't generate a palette.") logging.warning("Trying a larger palette size %s", 8 + i) return [util.rgb_to_hex(color) for color in raw_colors]
python
def gen_colors(img): color_cmd = ColorThief(img).get_palette for i in range(0, 10, 1): raw_colors = color_cmd(color_count=8 + i) if len(raw_colors) >= 8: break elif i == 10: logging.error("ColorThief couldn't generate a suitable palette.") sys.exit(1) else: logging.warning("ColorThief couldn't generate a palette.") logging.warning("Trying a larger palette size %s", 8 + i) return [util.rgb_to_hex(color) for color in raw_colors]
[ "def", "gen_colors", "(", "img", ")", ":", "color_cmd", "=", "ColorThief", "(", "img", ")", ".", "get_palette", "for", "i", "in", "range", "(", "0", ",", "10", ",", "1", ")", ":", "raw_colors", "=", "color_cmd", "(", "color_count", "=", "8", "+", "...
Loop until 16 colors are generated.
[ "Loop", "until", "16", "colors", "are", "generated", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/backends/colorthief.py#L18-L36
238,250
dylanaraps/pywal
pywal/theme.py
list_out
def list_out(): """List all themes in a pretty format.""" dark_themes = [theme.name.replace(".json", "") for theme in list_themes()] ligh_themes = [theme.name.replace(".json", "") for theme in list_themes(dark=False)] user_themes = [theme.name.replace(".json", "") for theme in list_themes_user()] if user_themes: print("\033[1;32mUser Themes\033[0m:") print(" -", "\n - ".join(sorted(user_themes))) print("\033[1;32mDark Themes\033[0m:") print(" -", "\n - ".join(sorted(dark_themes))) print("\033[1;32mLight Themes\033[0m:") print(" -", "\n - ".join(sorted(ligh_themes))) print("\033[1;32mExtra\033[0m:") print(" - random (select a random dark theme)") print(" - random_dark (select a random dark theme)") print(" - random_light (select a random light theme)")
python
def list_out(): dark_themes = [theme.name.replace(".json", "") for theme in list_themes()] ligh_themes = [theme.name.replace(".json", "") for theme in list_themes(dark=False)] user_themes = [theme.name.replace(".json", "") for theme in list_themes_user()] if user_themes: print("\033[1;32mUser Themes\033[0m:") print(" -", "\n - ".join(sorted(user_themes))) print("\033[1;32mDark Themes\033[0m:") print(" -", "\n - ".join(sorted(dark_themes))) print("\033[1;32mLight Themes\033[0m:") print(" -", "\n - ".join(sorted(ligh_themes))) print("\033[1;32mExtra\033[0m:") print(" - random (select a random dark theme)") print(" - random_dark (select a random dark theme)") print(" - random_light (select a random light theme)")
[ "def", "list_out", "(", ")", ":", "dark_themes", "=", "[", "theme", ".", "name", ".", "replace", "(", "\".json\"", ",", "\"\"", ")", "for", "theme", "in", "list_themes", "(", ")", "]", "ligh_themes", "=", "[", "theme", ".", "name", ".", "replace", "(...
List all themes in a pretty format.
[ "List", "all", "themes", "in", "a", "pretty", "format", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L13-L35
238,251
dylanaraps/pywal
pywal/theme.py
list_themes
def list_themes(dark=True): """List all installed theme files.""" dark = "dark" if dark else "light" themes = os.scandir(os.path.join(MODULE_DIR, "colorschemes", dark)) return [t for t in themes if os.path.isfile(t.path)]
python
def list_themes(dark=True): dark = "dark" if dark else "light" themes = os.scandir(os.path.join(MODULE_DIR, "colorschemes", dark)) return [t for t in themes if os.path.isfile(t.path)]
[ "def", "list_themes", "(", "dark", "=", "True", ")", ":", "dark", "=", "\"dark\"", "if", "dark", "else", "\"light\"", "themes", "=", "os", ".", "scandir", "(", "os", ".", "path", ".", "join", "(", "MODULE_DIR", ",", "\"colorschemes\"", ",", "dark", ")"...
List all installed theme files.
[ "List", "all", "installed", "theme", "files", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L38-L42
238,252
dylanaraps/pywal
pywal/theme.py
list_themes_user
def list_themes_user(): """List user theme files.""" themes = [*os.scandir(os.path.join(CONF_DIR, "colorschemes/dark/")), *os.scandir(os.path.join(CONF_DIR, "colorschemes/light/"))] return [t for t in themes if os.path.isfile(t.path)]
python
def list_themes_user(): themes = [*os.scandir(os.path.join(CONF_DIR, "colorschemes/dark/")), *os.scandir(os.path.join(CONF_DIR, "colorschemes/light/"))] return [t for t in themes if os.path.isfile(t.path)]
[ "def", "list_themes_user", "(", ")", ":", "themes", "=", "[", "*", "os", ".", "scandir", "(", "os", ".", "path", ".", "join", "(", "CONF_DIR", ",", "\"colorschemes/dark/\"", ")", ")", ",", "*", "os", ".", "scandir", "(", "os", ".", "path", ".", "jo...
List user theme files.
[ "List", "user", "theme", "files", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L45-L49
238,253
dylanaraps/pywal
pywal/theme.py
terminal_sexy_to_wal
def terminal_sexy_to_wal(data): """Convert terminal.sexy json schema to wal.""" data["colors"] = {} data["special"] = { "foreground": data["foreground"], "background": data["background"], "cursor": data["color"][9] } for i, color in enumerate(data["color"]): data["colors"]["color%s" % i] = color return data
python
def terminal_sexy_to_wal(data): data["colors"] = {} data["special"] = { "foreground": data["foreground"], "background": data["background"], "cursor": data["color"][9] } for i, color in enumerate(data["color"]): data["colors"]["color%s" % i] = color return data
[ "def", "terminal_sexy_to_wal", "(", "data", ")", ":", "data", "[", "\"colors\"", "]", "=", "{", "}", "data", "[", "\"special\"", "]", "=", "{", "\"foreground\"", ":", "data", "[", "\"foreground\"", "]", ",", "\"background\"", ":", "data", "[", "\"backgroun...
Convert terminal.sexy json schema to wal.
[ "Convert", "terminal", ".", "sexy", "json", "schema", "to", "wal", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L52-L64
238,254
dylanaraps/pywal
pywal/theme.py
parse
def parse(theme_file): """Parse the theme file.""" data = util.read_file_json(theme_file) if "wallpaper" not in data: data["wallpaper"] = "None" if "alpha" not in data: data["alpha"] = util.Color.alpha_num # Terminal.sexy format. if "color" in data: data = terminal_sexy_to_wal(data) return data
python
def parse(theme_file): data = util.read_file_json(theme_file) if "wallpaper" not in data: data["wallpaper"] = "None" if "alpha" not in data: data["alpha"] = util.Color.alpha_num # Terminal.sexy format. if "color" in data: data = terminal_sexy_to_wal(data) return data
[ "def", "parse", "(", "theme_file", ")", ":", "data", "=", "util", ".", "read_file_json", "(", "theme_file", ")", "if", "\"wallpaper\"", "not", "in", "data", ":", "data", "[", "\"wallpaper\"", "]", "=", "\"None\"", "if", "\"alpha\"", "not", "in", "data", ...
Parse the theme file.
[ "Parse", "the", "theme", "file", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L67-L81
238,255
dylanaraps/pywal
pywal/theme.py
get_random_theme
def get_random_theme(dark=True): """Get a random theme file.""" themes = [theme.path for theme in list_themes(dark)] random.shuffle(themes) return themes[0]
python
def get_random_theme(dark=True): themes = [theme.path for theme in list_themes(dark)] random.shuffle(themes) return themes[0]
[ "def", "get_random_theme", "(", "dark", "=", "True", ")", ":", "themes", "=", "[", "theme", ".", "path", "for", "theme", "in", "list_themes", "(", "dark", ")", "]", "random", ".", "shuffle", "(", "themes", ")", "return", "themes", "[", "0", "]" ]
Get a random theme file.
[ "Get", "a", "random", "theme", "file", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L84-L88
238,256
dylanaraps/pywal
pywal/theme.py
file
def file(input_file, light=False): """Import colorscheme from json file.""" util.create_dir(os.path.join(CONF_DIR, "colorschemes/light/")) util.create_dir(os.path.join(CONF_DIR, "colorschemes/dark/")) theme_name = ".".join((input_file, "json")) bri = "light" if light else "dark" user_theme_file = os.path.join(CONF_DIR, "colorschemes", bri, theme_name) theme_file = os.path.join(MODULE_DIR, "colorschemes", bri, theme_name) # Find the theme file. if input_file in ("random", "random_dark"): theme_file = get_random_theme() elif input_file == "random_light": theme_file = get_random_theme(light) elif os.path.isfile(user_theme_file): theme_file = user_theme_file elif os.path.isfile(input_file): theme_file = input_file # Parse the theme file. if os.path.isfile(theme_file): logging.info("Set theme to \033[1;37m%s\033[0m.", os.path.basename(theme_file)) return parse(theme_file) logging.error("No %s colorscheme file found.", bri) logging.error("Try adding '-l' to set light themes.") logging.error("Try removing '-l' to set dark themes.") sys.exit(1)
python
def file(input_file, light=False): util.create_dir(os.path.join(CONF_DIR, "colorschemes/light/")) util.create_dir(os.path.join(CONF_DIR, "colorschemes/dark/")) theme_name = ".".join((input_file, "json")) bri = "light" if light else "dark" user_theme_file = os.path.join(CONF_DIR, "colorschemes", bri, theme_name) theme_file = os.path.join(MODULE_DIR, "colorschemes", bri, theme_name) # Find the theme file. if input_file in ("random", "random_dark"): theme_file = get_random_theme() elif input_file == "random_light": theme_file = get_random_theme(light) elif os.path.isfile(user_theme_file): theme_file = user_theme_file elif os.path.isfile(input_file): theme_file = input_file # Parse the theme file. if os.path.isfile(theme_file): logging.info("Set theme to \033[1;37m%s\033[0m.", os.path.basename(theme_file)) return parse(theme_file) logging.error("No %s colorscheme file found.", bri) logging.error("Try adding '-l' to set light themes.") logging.error("Try removing '-l' to set dark themes.") sys.exit(1)
[ "def", "file", "(", "input_file", ",", "light", "=", "False", ")", ":", "util", ".", "create_dir", "(", "os", ".", "path", ".", "join", "(", "CONF_DIR", ",", "\"colorschemes/light/\"", ")", ")", "util", ".", "create_dir", "(", "os", ".", "path", ".", ...
Import colorscheme from json file.
[ "Import", "colorscheme", "from", "json", "file", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/theme.py#L91-L124
238,257
dylanaraps/pywal
pywal/backends/wal.py
imagemagick
def imagemagick(color_count, img, magick_command): """Call Imagemagick to generate a scheme.""" flags = ["-resize", "25%", "-colors", str(color_count), "-unique-colors", "txt:-"] img += "[0]" return subprocess.check_output([*magick_command, img, *flags]).splitlines()
python
def imagemagick(color_count, img, magick_command): flags = ["-resize", "25%", "-colors", str(color_count), "-unique-colors", "txt:-"] img += "[0]" return subprocess.check_output([*magick_command, img, *flags]).splitlines()
[ "def", "imagemagick", "(", "color_count", ",", "img", ",", "magick_command", ")", ":", "flags", "=", "[", "\"-resize\"", ",", "\"25%\"", ",", "\"-colors\"", ",", "str", "(", "color_count", ")", ",", "\"-unique-colors\"", ",", "\"txt:-\"", "]", "img", "+=", ...
Call Imagemagick to generate a scheme.
[ "Call", "Imagemagick", "to", "generate", "a", "scheme", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/backends/wal.py#L13-L19
238,258
dylanaraps/pywal
pywal/backends/wal.py
has_im
def has_im(): """Check to see if the user has im installed.""" if shutil.which("magick"): return ["magick", "convert"] if shutil.which("convert"): return ["convert"] logging.error("Imagemagick wasn't found on your system.") logging.error("Try another backend. (wal --backend)") sys.exit(1)
python
def has_im(): if shutil.which("magick"): return ["magick", "convert"] if shutil.which("convert"): return ["convert"] logging.error("Imagemagick wasn't found on your system.") logging.error("Try another backend. (wal --backend)") sys.exit(1)
[ "def", "has_im", "(", ")", ":", "if", "shutil", ".", "which", "(", "\"magick\"", ")", ":", "return", "[", "\"magick\"", ",", "\"convert\"", "]", "if", "shutil", ".", "which", "(", "\"convert\"", ")", ":", "return", "[", "\"convert\"", "]", "logging", "...
Check to see if the user has im installed.
[ "Check", "to", "see", "if", "the", "user", "has", "im", "installed", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/backends/wal.py#L22-L32
238,259
dylanaraps/pywal
pywal/backends/wal.py
gen_colors
def gen_colors(img): """Format the output from imagemagick into a list of hex colors.""" magick_command = has_im() for i in range(0, 20, 1): raw_colors = imagemagick(16 + i, img, magick_command) if len(raw_colors) > 16: break elif i == 19: logging.error("Imagemagick couldn't generate a suitable palette.") sys.exit(1) else: logging.warning("Imagemagick couldn't generate a palette.") logging.warning("Trying a larger palette size %s", 16 + i) return [re.search("#.{6}", str(col)).group(0) for col in raw_colors[1:]]
python
def gen_colors(img): magick_command = has_im() for i in range(0, 20, 1): raw_colors = imagemagick(16 + i, img, magick_command) if len(raw_colors) > 16: break elif i == 19: logging.error("Imagemagick couldn't generate a suitable palette.") sys.exit(1) else: logging.warning("Imagemagick couldn't generate a palette.") logging.warning("Trying a larger palette size %s", 16 + i) return [re.search("#.{6}", str(col)).group(0) for col in raw_colors[1:]]
[ "def", "gen_colors", "(", "img", ")", ":", "magick_command", "=", "has_im", "(", ")", "for", "i", "in", "range", "(", "0", ",", "20", ",", "1", ")", ":", "raw_colors", "=", "imagemagick", "(", "16", "+", "i", ",", "img", ",", "magick_command", ")",...
Format the output from imagemagick into a list of hex colors.
[ "Format", "the", "output", "from", "imagemagick", "into", "a", "list", "of", "hex", "colors", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/backends/wal.py#L35-L54
238,260
dylanaraps/pywal
pywal/backends/wal.py
adjust
def adjust(colors, light): """Adjust the generated colors and store them in a dict that we will later save in json format.""" raw_colors = colors[:1] + colors[8:16] + colors[8:-1] # Manually adjust colors. if light: for color in raw_colors: color = util.saturate_color(color, 0.5) raw_colors[0] = util.lighten_color(colors[-1], 0.85) raw_colors[7] = colors[0] raw_colors[8] = util.darken_color(colors[-1], 0.4) raw_colors[15] = colors[0] else: # Darken the background color slightly. if raw_colors[0][1] != "0": raw_colors[0] = util.darken_color(raw_colors[0], 0.40) raw_colors[7] = util.blend_color(raw_colors[7], "#EEEEEE") raw_colors[8] = util.darken_color(raw_colors[7], 0.30) raw_colors[15] = util.blend_color(raw_colors[15], "#EEEEEE") return raw_colors
python
def adjust(colors, light): raw_colors = colors[:1] + colors[8:16] + colors[8:-1] # Manually adjust colors. if light: for color in raw_colors: color = util.saturate_color(color, 0.5) raw_colors[0] = util.lighten_color(colors[-1], 0.85) raw_colors[7] = colors[0] raw_colors[8] = util.darken_color(colors[-1], 0.4) raw_colors[15] = colors[0] else: # Darken the background color slightly. if raw_colors[0][1] != "0": raw_colors[0] = util.darken_color(raw_colors[0], 0.40) raw_colors[7] = util.blend_color(raw_colors[7], "#EEEEEE") raw_colors[8] = util.darken_color(raw_colors[7], 0.30) raw_colors[15] = util.blend_color(raw_colors[15], "#EEEEEE") return raw_colors
[ "def", "adjust", "(", "colors", ",", "light", ")", ":", "raw_colors", "=", "colors", "[", ":", "1", "]", "+", "colors", "[", "8", ":", "16", "]", "+", "colors", "[", "8", ":", "-", "1", "]", "# Manually adjust colors.", "if", "light", ":", "for", ...
Adjust the generated colors and store them in a dict that we will later save in json format.
[ "Adjust", "the", "generated", "colors", "and", "store", "them", "in", "a", "dict", "that", "we", "will", "later", "save", "in", "json", "format", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/backends/wal.py#L57-L81
238,261
dylanaraps/pywal
pywal/__main__.py
parse_args_exit
def parse_args_exit(parser): """Process args that exit.""" args = parser.parse_args() if len(sys.argv) <= 1: parser.print_help() sys.exit(1) if args.v: parser.exit(0, "wal %s\n" % __version__) if args.preview: print("Current colorscheme:", sep='') colors.palette() sys.exit(0) if args.i and args.theme: parser.error("Conflicting arguments -i and -f.") if args.r: reload.colors() sys.exit(0) if args.c: scheme_dir = os.path.join(CACHE_DIR, "schemes") shutil.rmtree(scheme_dir, ignore_errors=True) sys.exit(0) if not args.i and \ not args.theme and \ not args.R and \ not args.backend: parser.error("No input specified.\n" "--backend, --theme, -i or -R are required.") if args.theme == "list_themes": theme.list_out() sys.exit(0) if args.backend == "list_backends": print("\n - ".join(["\033[1;32mBackends\033[0m:", *colors.list_backends()])) sys.exit(0)
python
def parse_args_exit(parser): args = parser.parse_args() if len(sys.argv) <= 1: parser.print_help() sys.exit(1) if args.v: parser.exit(0, "wal %s\n" % __version__) if args.preview: print("Current colorscheme:", sep='') colors.palette() sys.exit(0) if args.i and args.theme: parser.error("Conflicting arguments -i and -f.") if args.r: reload.colors() sys.exit(0) if args.c: scheme_dir = os.path.join(CACHE_DIR, "schemes") shutil.rmtree(scheme_dir, ignore_errors=True) sys.exit(0) if not args.i and \ not args.theme and \ not args.R and \ not args.backend: parser.error("No input specified.\n" "--backend, --theme, -i or -R are required.") if args.theme == "list_themes": theme.list_out() sys.exit(0) if args.backend == "list_backends": print("\n - ".join(["\033[1;32mBackends\033[0m:", *colors.list_backends()])) sys.exit(0)
[ "def", "parse_args_exit", "(", "parser", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "len", "(", "sys", ".", "argv", ")", "<=", "1", ":", "parser", ".", "print_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "if", "arg...
Process args that exit.
[ "Process", "args", "that", "exit", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/__main__.py#L105-L147
238,262
dylanaraps/pywal
pywal/__main__.py
parse_args
def parse_args(parser): """Process args.""" args = parser.parse_args() if args.q: logging.getLogger().disabled = True sys.stdout = sys.stderr = open(os.devnull, "w") if args.a: util.Color.alpha_num = args.a if args.i: image_file = image.get(args.i, iterative=args.iterative) colors_plain = colors.get(image_file, args.l, args.backend, sat=args.saturate) if args.theme: colors_plain = theme.file(args.theme, args.l) if args.R: colors_plain = theme.file(os.path.join(CACHE_DIR, "colors.json")) if args.b: args.b = "#%s" % (args.b.strip("#")) colors_plain["special"]["background"] = args.b colors_plain["colors"]["color0"] = args.b if not args.n: wallpaper.change(colors_plain["wallpaper"]) sequences.send(colors_plain, to_send=not args.s, vte_fix=args.vte) if sys.stdout.isatty(): colors.palette() export.every(colors_plain) if not args.e: reload.env(tty_reload=not args.t) if args.o: for cmd in args.o: util.disown([cmd]) if not args.e: reload.gtk()
python
def parse_args(parser): args = parser.parse_args() if args.q: logging.getLogger().disabled = True sys.stdout = sys.stderr = open(os.devnull, "w") if args.a: util.Color.alpha_num = args.a if args.i: image_file = image.get(args.i, iterative=args.iterative) colors_plain = colors.get(image_file, args.l, args.backend, sat=args.saturate) if args.theme: colors_plain = theme.file(args.theme, args.l) if args.R: colors_plain = theme.file(os.path.join(CACHE_DIR, "colors.json")) if args.b: args.b = "#%s" % (args.b.strip("#")) colors_plain["special"]["background"] = args.b colors_plain["colors"]["color0"] = args.b if not args.n: wallpaper.change(colors_plain["wallpaper"]) sequences.send(colors_plain, to_send=not args.s, vte_fix=args.vte) if sys.stdout.isatty(): colors.palette() export.every(colors_plain) if not args.e: reload.env(tty_reload=not args.t) if args.o: for cmd in args.o: util.disown([cmd]) if not args.e: reload.gtk()
[ "def", "parse_args", "(", "parser", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "q", ":", "logging", ".", "getLogger", "(", ")", ".", "disabled", "=", "True", "sys", ".", "stdout", "=", "sys", ".", "stderr", "="...
Process args.
[ "Process", "args", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/__main__.py#L150-L195
238,263
dylanaraps/pywal
pywal/sequences.py
set_special
def set_special(index, color, iterm_name="h", alpha=100): """Convert a hex color to a special sequence.""" if OS == "Darwin" and iterm_name: return "\033]P%s%s\033\\" % (iterm_name, color.strip("#")) if index in [11, 708] and alpha != "100": return "\033]%s;[%s]%s\033\\" % (index, alpha, color) return "\033]%s;%s\033\\" % (index, color)
python
def set_special(index, color, iterm_name="h", alpha=100): if OS == "Darwin" and iterm_name: return "\033]P%s%s\033\\" % (iterm_name, color.strip("#")) if index in [11, 708] and alpha != "100": return "\033]%s;[%s]%s\033\\" % (index, alpha, color) return "\033]%s;%s\033\\" % (index, color)
[ "def", "set_special", "(", "index", ",", "color", ",", "iterm_name", "=", "\"h\"", ",", "alpha", "=", "100", ")", ":", "if", "OS", "==", "\"Darwin\"", "and", "iterm_name", ":", "return", "\"\\033]P%s%s\\033\\\\\"", "%", "(", "iterm_name", ",", "color", "."...
Convert a hex color to a special sequence.
[ "Convert", "a", "hex", "color", "to", "a", "special", "sequence", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L12-L20
238,264
dylanaraps/pywal
pywal/sequences.py
set_color
def set_color(index, color): """Convert a hex color to a text color sequence.""" if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
python
def set_color(index, color): if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
[ "def", "set_color", "(", "index", ",", "color", ")", ":", "if", "OS", "==", "\"Darwin\"", "and", "index", "<", "20", ":", "return", "\"\\033]P%1x%s\\033\\\\\"", "%", "(", "index", ",", "color", ".", "strip", "(", "\"#\"", ")", ")", "return", "\"\\033]4;%...
Convert a hex color to a text color sequence.
[ "Convert", "a", "hex", "color", "to", "a", "text", "color", "sequence", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L23-L28
238,265
dylanaraps/pywal
pywal/sequences.py
create_sequences
def create_sequences(colors, vte_fix=False): """Create the escape sequences.""" alpha = colors["alpha"] # Colors 0-15. sequences = [set_color(index, colors["colors"]["color%s" % index]) for index in range(16)] # Special colors. # Source: https://goo.gl/KcoQgP # 10 = foreground, 11 = background, 12 = cursor foregound # 13 = mouse foreground, 708 = background border color. sequences.extend([ set_special(10, colors["special"]["foreground"], "g"), set_special(11, colors["special"]["background"], "h", alpha), set_special(12, colors["special"]["cursor"], "l"), set_special(13, colors["special"]["foreground"], "j"), set_special(17, colors["special"]["foreground"], "k"), set_special(19, colors["special"]["background"], "m"), set_color(232, colors["special"]["background"]), set_color(256, colors["special"]["foreground"]) ]) if not vte_fix: sequences.extend( set_special(708, colors["special"]["background"], "", alpha) ) if OS == "Darwin": sequences += set_iterm_tab_color(colors["special"]["background"]) return "".join(sequences)
python
def create_sequences(colors, vte_fix=False): alpha = colors["alpha"] # Colors 0-15. sequences = [set_color(index, colors["colors"]["color%s" % index]) for index in range(16)] # Special colors. # Source: https://goo.gl/KcoQgP # 10 = foreground, 11 = background, 12 = cursor foregound # 13 = mouse foreground, 708 = background border color. sequences.extend([ set_special(10, colors["special"]["foreground"], "g"), set_special(11, colors["special"]["background"], "h", alpha), set_special(12, colors["special"]["cursor"], "l"), set_special(13, colors["special"]["foreground"], "j"), set_special(17, colors["special"]["foreground"], "k"), set_special(19, colors["special"]["background"], "m"), set_color(232, colors["special"]["background"]), set_color(256, colors["special"]["foreground"]) ]) if not vte_fix: sequences.extend( set_special(708, colors["special"]["background"], "", alpha) ) if OS == "Darwin": sequences += set_iterm_tab_color(colors["special"]["background"]) return "".join(sequences)
[ "def", "create_sequences", "(", "colors", ",", "vte_fix", "=", "False", ")", ":", "alpha", "=", "colors", "[", "\"alpha\"", "]", "# Colors 0-15.", "sequences", "=", "[", "set_color", "(", "index", ",", "colors", "[", "\"colors\"", "]", "[", "\"color%s\"", ...
Create the escape sequences.
[ "Create", "the", "escape", "sequences", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L38-L69
238,266
dylanaraps/pywal
pywal/sequences.py
send
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False): """Send colors to all open terminals.""" if OS == "Darwin": tty_pattern = "/dev/ttys00[0-9]*" else: tty_pattern = "/dev/pts/[0-9]*" sequences = create_sequences(colors, vte_fix) # Writing to "/dev/pts/[0-9] lets you send data to open terminals. if to_send: for term in glob.glob(tty_pattern): util.save_file(sequences, term) util.save_file(sequences, os.path.join(cache_dir, "sequences")) logging.info("Set terminal colors.")
python
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False): if OS == "Darwin": tty_pattern = "/dev/ttys00[0-9]*" else: tty_pattern = "/dev/pts/[0-9]*" sequences = create_sequences(colors, vte_fix) # Writing to "/dev/pts/[0-9] lets you send data to open terminals. if to_send: for term in glob.glob(tty_pattern): util.save_file(sequences, term) util.save_file(sequences, os.path.join(cache_dir, "sequences")) logging.info("Set terminal colors.")
[ "def", "send", "(", "colors", ",", "cache_dir", "=", "CACHE_DIR", ",", "to_send", "=", "True", ",", "vte_fix", "=", "False", ")", ":", "if", "OS", "==", "\"Darwin\"", ":", "tty_pattern", "=", "\"/dev/ttys00[0-9]*\"", "else", ":", "tty_pattern", "=", "\"/de...
Send colors to all open terminals.
[ "Send", "colors", "to", "all", "open", "terminals", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/sequences.py#L72-L88
238,267
dylanaraps/pywal
pywal/export.py
template
def template(colors, input_file, output_file=None): """Read template file, substitute markers and save the file elsewhere.""" template_data = util.read_file_raw(input_file) try: template_data = "".join(template_data).format(**colors) except ValueError: logging.error("Syntax error in template file '%s'.", input_file) return util.save_file(template_data, output_file)
python
def template(colors, input_file, output_file=None): template_data = util.read_file_raw(input_file) try: template_data = "".join(template_data).format(**colors) except ValueError: logging.error("Syntax error in template file '%s'.", input_file) return util.save_file(template_data, output_file)
[ "def", "template", "(", "colors", ",", "input_file", ",", "output_file", "=", "None", ")", ":", "template_data", "=", "util", ".", "read_file_raw", "(", "input_file", ")", "try", ":", "template_data", "=", "\"\"", ".", "join", "(", "template_data", ")", "....
Read template file, substitute markers and save the file elsewhere.
[ "Read", "template", "file", "substitute", "markers", "and", "save", "the", "file", "elsewhere", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L11-L22
238,268
dylanaraps/pywal
pywal/export.py
every
def every(colors, output_dir=CACHE_DIR): """Export all template files.""" colors = flatten_colors(colors) template_dir = os.path.join(MODULE_DIR, "templates") template_dir_user = os.path.join(CONF_DIR, "templates") util.create_dir(template_dir_user) join = os.path.join # Minor optimization. for file in [*os.scandir(template_dir), *os.scandir(template_dir_user)]: if file.name != ".DS_Store" and not file.name.endswith(".swp"): template(colors, file.path, join(output_dir, file.name)) logging.info("Exported all files.") logging.info("Exported all user files.")
python
def every(colors, output_dir=CACHE_DIR): colors = flatten_colors(colors) template_dir = os.path.join(MODULE_DIR, "templates") template_dir_user = os.path.join(CONF_DIR, "templates") util.create_dir(template_dir_user) join = os.path.join # Minor optimization. for file in [*os.scandir(template_dir), *os.scandir(template_dir_user)]: if file.name != ".DS_Store" and not file.name.endswith(".swp"): template(colors, file.path, join(output_dir, file.name)) logging.info("Exported all files.") logging.info("Exported all user files.")
[ "def", "every", "(", "colors", ",", "output_dir", "=", "CACHE_DIR", ")", ":", "colors", "=", "flatten_colors", "(", "colors", ")", "template_dir", "=", "os", ".", "path", ".", "join", "(", "MODULE_DIR", ",", "\"templates\"", ")", "template_dir_user", "=", ...
Export all template files.
[ "Export", "all", "template", "files", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L62-L76
238,269
dylanaraps/pywal
pywal/export.py
color
def color(colors, export_type, output_file=None): """Export a single template file.""" all_colors = flatten_colors(colors) template_name = get_export_type(export_type) template_file = os.path.join(MODULE_DIR, "templates", template_name) output_file = output_file or os.path.join(CACHE_DIR, template_name) if os.path.isfile(template_file): template(all_colors, template_file, output_file) logging.info("Exported %s.", export_type) else: logging.warning("Template '%s' doesn't exist.", export_type)
python
def color(colors, export_type, output_file=None): all_colors = flatten_colors(colors) template_name = get_export_type(export_type) template_file = os.path.join(MODULE_DIR, "templates", template_name) output_file = output_file or os.path.join(CACHE_DIR, template_name) if os.path.isfile(template_file): template(all_colors, template_file, output_file) logging.info("Exported %s.", export_type) else: logging.warning("Template '%s' doesn't exist.", export_type)
[ "def", "color", "(", "colors", ",", "export_type", ",", "output_file", "=", "None", ")", ":", "all_colors", "=", "flatten_colors", "(", "colors", ")", "template_name", "=", "get_export_type", "(", "export_type", ")", "template_file", "=", "os", ".", "path", ...
Export a single template file.
[ "Export", "a", "single", "template", "file", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/export.py#L79-L91
238,270
dylanaraps/pywal
pywal/reload.py
tty
def tty(tty_reload): """Load colors in tty.""" tty_script = os.path.join(CACHE_DIR, "colors-tty.sh") term = os.environ.get("TERM") if tty_reload and term == "linux": subprocess.Popen(["sh", tty_script])
python
def tty(tty_reload): tty_script = os.path.join(CACHE_DIR, "colors-tty.sh") term = os.environ.get("TERM") if tty_reload and term == "linux": subprocess.Popen(["sh", tty_script])
[ "def", "tty", "(", "tty_reload", ")", ":", "tty_script", "=", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "\"colors-tty.sh\"", ")", "term", "=", "os", ".", "environ", ".", "get", "(", "\"TERM\"", ")", "if", "tty_reload", "and", "term", "==",...
Load colors in tty.
[ "Load", "colors", "in", "tty", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L13-L19
238,271
dylanaraps/pywal
pywal/reload.py
xrdb
def xrdb(xrdb_files=None): """Merge the colors into the X db so new terminals use them.""" xrdb_files = xrdb_files or \ [os.path.join(CACHE_DIR, "colors.Xresources")] if shutil.which("xrdb") and OS != "Darwin": for file in xrdb_files: subprocess.run(["xrdb", "-merge", "-quiet", file])
python
def xrdb(xrdb_files=None): xrdb_files = xrdb_files or \ [os.path.join(CACHE_DIR, "colors.Xresources")] if shutil.which("xrdb") and OS != "Darwin": for file in xrdb_files: subprocess.run(["xrdb", "-merge", "-quiet", file])
[ "def", "xrdb", "(", "xrdb_files", "=", "None", ")", ":", "xrdb_files", "=", "xrdb_files", "or", "[", "os", ".", "path", ".", "join", "(", "CACHE_DIR", ",", "\"colors.Xresources\"", ")", "]", "if", "shutil", ".", "which", "(", "\"xrdb\"", ")", "and", "O...
Merge the colors into the X db so new terminals use them.
[ "Merge", "the", "colors", "into", "the", "X", "db", "so", "new", "terminals", "use", "them", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L22-L29
238,272
dylanaraps/pywal
pywal/reload.py
gtk
def gtk(): """Reload GTK theme on the fly.""" # Here we call a Python 2 script to reload the GTK themes. # This is done because the Python 3 GTK/Gdk libraries don't # provide a way of doing this. if shutil.which("python2"): gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py") util.disown(["python2", gtk_reload]) else: logging.warning("GTK2 reload support requires Python 2.")
python
def gtk(): # Here we call a Python 2 script to reload the GTK themes. # This is done because the Python 3 GTK/Gdk libraries don't # provide a way of doing this. if shutil.which("python2"): gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py") util.disown(["python2", gtk_reload]) else: logging.warning("GTK2 reload support requires Python 2.")
[ "def", "gtk", "(", ")", ":", "# Here we call a Python 2 script to reload the GTK themes.", "# This is done because the Python 3 GTK/Gdk libraries don't", "# provide a way of doing this.", "if", "shutil", ".", "which", "(", "\"python2\"", ")", ":", "gtk_reload", "=", "os", ".", ...
Reload GTK theme on the fly.
[ "Reload", "GTK", "theme", "on", "the", "fly", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L32-L42
238,273
dylanaraps/pywal
pywal/reload.py
env
def env(xrdb_file=None, tty_reload=True): """Reload environment.""" xrdb(xrdb_file) i3() bspwm() kitty() sway() polybar() logging.info("Reloaded environment.") tty(tty_reload)
python
def env(xrdb_file=None, tty_reload=True): xrdb(xrdb_file) i3() bspwm() kitty() sway() polybar() logging.info("Reloaded environment.") tty(tty_reload)
[ "def", "env", "(", "xrdb_file", "=", "None", ",", "tty_reload", "=", "True", ")", ":", "xrdb", "(", "xrdb_file", ")", "i3", "(", ")", "bspwm", "(", ")", "kitty", "(", ")", "sway", "(", ")", "polybar", "(", ")", "logging", ".", "info", "(", "\"Rel...
Reload environment.
[ "Reload", "environment", "." ]
c823e3c9dbd0100ca09caf824e77d296685a1c1e
https://github.com/dylanaraps/pywal/blob/c823e3c9dbd0100ca09caf824e77d296685a1c1e/pywal/reload.py#L86-L95
238,274
IDSIA/sacred
sacred/run.py
Run.add_resource
def add_resource(self, filename): """Add a file as a resource. In Sacred terminology a resource is a file that the experiment needed to access during a run. In case of a MongoObserver that means making sure the file is stored in the database (but avoiding duplicates) along its path and md5 sum. See also :py:meth:`sacred.Experiment.add_resource`. Parameters ---------- filename : str name of the file to be stored as a resource """ filename = os.path.abspath(filename) self._emit_resource_added(filename)
python
def add_resource(self, filename): filename = os.path.abspath(filename) self._emit_resource_added(filename)
[ "def", "add_resource", "(", "self", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "self", ".", "_emit_resource_added", "(", "filename", ")" ]
Add a file as a resource. In Sacred terminology a resource is a file that the experiment needed to access during a run. In case of a MongoObserver that means making sure the file is stored in the database (but avoiding duplicates) along its path and md5 sum. See also :py:meth:`sacred.Experiment.add_resource`. Parameters ---------- filename : str name of the file to be stored as a resource
[ "Add", "a", "file", "as", "a", "resource", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/run.py#L142-L158
238,275
IDSIA/sacred
sacred/initialize.py
find_best_match
def find_best_match(path, prefixes): """Find the Ingredient that shares the longest prefix with path.""" path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
python
def find_best_match(path, prefixes): path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
[ "def", "find_best_match", "(", "path", ",", "prefixes", ")", ":", "path_parts", "=", "path", ".", "split", "(", "'.'", ")", "for", "p", "in", "prefixes", ":", "if", "len", "(", "p", ")", "<=", "len", "(", "path_parts", ")", "and", "p", "==", "path_...
Find the Ingredient that shares the longest prefix with path.
[ "Find", "the", "Ingredient", "that", "shares", "the", "longest", "prefix", "with", "path", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/initialize.py#L316-L322
238,276
IDSIA/sacred
sacred/commands.py
_non_unicode_repr
def _non_unicode_repr(objekt, context, maxlevels, level): """ Used to override the pprint format method to get rid of unicode prefixes. E.g.: 'John' instead of u'John'. """ repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context, maxlevels, level) if repr_string.startswith('u"') or repr_string.startswith("u'"): repr_string = repr_string[1:] return repr_string, isreadable, isrecursive
python
def _non_unicode_repr(objekt, context, maxlevels, level): repr_string, isreadable, isrecursive = pprint._safe_repr(objekt, context, maxlevels, level) if repr_string.startswith('u"') or repr_string.startswith("u'"): repr_string = repr_string[1:] return repr_string, isreadable, isrecursive
[ "def", "_non_unicode_repr", "(", "objekt", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "repr_string", ",", "isreadable", ",", "isrecursive", "=", "pprint", ".", "_safe_repr", "(", "objekt", ",", "context", ",", "maxlevels", ",", "level", ")", ...
Used to override the pprint format method to get rid of unicode prefixes. E.g.: 'John' instead of u'John'.
[ "Used", "to", "override", "the", "pprint", "format", "method", "to", "get", "rid", "of", "unicode", "prefixes", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L40-L50
238,277
IDSIA/sacred
sacred/commands.py
print_config
def print_config(_run): """ Print the updated configuration and exit. Text is highlighted: green: value modified blue: value added red: value modified but type changed """ final_config = _run.config config_mods = _run.config_modifications print(_format_config(final_config, config_mods))
python
def print_config(_run): final_config = _run.config config_mods = _run.config_modifications print(_format_config(final_config, config_mods))
[ "def", "print_config", "(", "_run", ")", ":", "final_config", "=", "_run", ".", "config", "config_mods", "=", "_run", ".", "config_modifications", "print", "(", "_format_config", "(", "final_config", ",", "config_mods", ")", ")" ]
Print the updated configuration and exit. Text is highlighted: green: value modified blue: value added red: value modified but type changed
[ "Print", "the", "updated", "configuration", "and", "exit", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L57-L68
238,278
IDSIA/sacred
sacred/commands.py
print_named_configs
def print_named_configs(ingredient): """ Returns a command function that prints the available named configs for the ingredient and all sub-ingredients and exits. The output is highlighted: white: config names grey: doc """ def print_named_configs(): """Print the available named configs and exit.""" named_configs = OrderedDict(ingredient.gather_named_configs()) print(_format_named_configs(named_configs, 2)) return print_named_configs
python
def print_named_configs(ingredient): def print_named_configs(): """Print the available named configs and exit.""" named_configs = OrderedDict(ingredient.gather_named_configs()) print(_format_named_configs(named_configs, 2)) return print_named_configs
[ "def", "print_named_configs", "(", "ingredient", ")", ":", "def", "print_named_configs", "(", ")", ":", "\"\"\"Print the available named configs and exit.\"\"\"", "named_configs", "=", "OrderedDict", "(", "ingredient", ".", "gather_named_configs", "(", ")", ")", "print", ...
Returns a command function that prints the available named configs for the ingredient and all sub-ingredients and exits. The output is highlighted: white: config names grey: doc
[ "Returns", "a", "command", "function", "that", "prints", "the", "available", "named", "configs", "for", "the", "ingredient", "and", "all", "sub", "-", "ingredients", "and", "exits", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L94-L109
238,279
IDSIA/sacred
sacred/commands.py
print_dependencies
def print_dependencies(_run): """Print the detected source-files and dependencies.""" print('Dependencies:') for dep in _run.experiment_info['dependencies']: pack, _, version = dep.partition('==') print(' {:<20} == {}'.format(pack, version)) print('\nSources:') for source, digest in _run.experiment_info['sources']: print(' {:<43} {}'.format(source, digest)) if _run.experiment_info['repositories']: repos = _run.experiment_info['repositories'] print('\nVersion Control:') for repo in repos: mod = COLOR_DIRTY + 'M' if repo['dirty'] else ' ' print('{} {:<43} {}'.format(mod, repo['url'], repo['commit']) + ENDC) print('')
python
def print_dependencies(_run): print('Dependencies:') for dep in _run.experiment_info['dependencies']: pack, _, version = dep.partition('==') print(' {:<20} == {}'.format(pack, version)) print('\nSources:') for source, digest in _run.experiment_info['sources']: print(' {:<43} {}'.format(source, digest)) if _run.experiment_info['repositories']: repos = _run.experiment_info['repositories'] print('\nVersion Control:') for repo in repos: mod = COLOR_DIRTY + 'M' if repo['dirty'] else ' ' print('{} {:<43} {}'.format(mod, repo['url'], repo['commit']) + ENDC) print('')
[ "def", "print_dependencies", "(", "_run", ")", ":", "print", "(", "'Dependencies:'", ")", "for", "dep", "in", "_run", ".", "experiment_info", "[", "'dependencies'", "]", ":", "pack", ",", "_", ",", "version", "=", "dep", ".", "partition", "(", "'=='", ")...
Print the detected source-files and dependencies.
[ "Print", "the", "detected", "source", "-", "files", "and", "dependencies", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L119-L137
238,280
IDSIA/sacred
sacred/commands.py
save_config
def save_config(_config, _log, config_filename='config.json'): """ Store the updated configuration in a file. By default uses the filename "config.json", but that can be changed by setting the config_filename config entry. """ if 'config_filename' in _config: del _config['config_filename'] _log.info('Saving config to "{}"'.format(config_filename)) save_config_file(flatten(_config), config_filename)
python
def save_config(_config, _log, config_filename='config.json'): if 'config_filename' in _config: del _config['config_filename'] _log.info('Saving config to "{}"'.format(config_filename)) save_config_file(flatten(_config), config_filename)
[ "def", "save_config", "(", "_config", ",", "_log", ",", "config_filename", "=", "'config.json'", ")", ":", "if", "'config_filename'", "in", "_config", ":", "del", "_config", "[", "'config_filename'", "]", "_log", ".", "info", "(", "'Saving config to \"{}\"'", "....
Store the updated configuration in a file. By default uses the filename "config.json", but that can be changed by setting the config_filename config entry.
[ "Store", "the", "updated", "configuration", "in", "a", "file", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commands.py#L140-L150
238,281
IDSIA/sacred
sacred/observers/file_storage.py
FileStorageObserver.log_metrics
def log_metrics(self, metrics_by_name, info): """Store new measurements into metrics.json. """ try: metrics_path = os.path.join(self.dir, "metrics.json") with open(metrics_path, 'r') as f: saved_metrics = json.load(f) except IOError: # We haven't recorded anything yet. Start Collecting. saved_metrics = {} for metric_name, metric_ptr in metrics_by_name.items(): if metric_name not in saved_metrics: saved_metrics[metric_name] = {"values": [], "steps": [], "timestamps": []} saved_metrics[metric_name]["values"] += metric_ptr["values"] saved_metrics[metric_name]["steps"] += metric_ptr["steps"] # Manually convert them to avoid passing a datetime dtype handler # when we're trying to convert into json. timestamps_norm = [ts.isoformat() for ts in metric_ptr["timestamps"]] saved_metrics[metric_name]["timestamps"] += timestamps_norm self.save_json(saved_metrics, 'metrics.json')
python
def log_metrics(self, metrics_by_name, info): try: metrics_path = os.path.join(self.dir, "metrics.json") with open(metrics_path, 'r') as f: saved_metrics = json.load(f) except IOError: # We haven't recorded anything yet. Start Collecting. saved_metrics = {} for metric_name, metric_ptr in metrics_by_name.items(): if metric_name not in saved_metrics: saved_metrics[metric_name] = {"values": [], "steps": [], "timestamps": []} saved_metrics[metric_name]["values"] += metric_ptr["values"] saved_metrics[metric_name]["steps"] += metric_ptr["steps"] # Manually convert them to avoid passing a datetime dtype handler # when we're trying to convert into json. timestamps_norm = [ts.isoformat() for ts in metric_ptr["timestamps"]] saved_metrics[metric_name]["timestamps"] += timestamps_norm self.save_json(saved_metrics, 'metrics.json')
[ "def", "log_metrics", "(", "self", ",", "metrics_by_name", ",", "info", ")", ":", "try", ":", "metrics_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dir", ",", "\"metrics.json\"", ")", "with", "open", "(", "metrics_path", ",", "'r'", "...
Store new measurements into metrics.json.
[ "Store", "new", "measurements", "into", "metrics", ".", "json", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/file_storage.py#L217-L244
238,282
IDSIA/sacred
sacred/config/custom_containers.py
is_different
def is_different(old_value, new_value): """Numpy aware comparison between two values.""" if opt.has_numpy: return not opt.np.array_equal(old_value, new_value) else: return old_value != new_value
python
def is_different(old_value, new_value): if opt.has_numpy: return not opt.np.array_equal(old_value, new_value) else: return old_value != new_value
[ "def", "is_different", "(", "old_value", ",", "new_value", ")", ":", "if", "opt", ".", "has_numpy", ":", "return", "not", "opt", ".", "np", ".", "array_equal", "(", "old_value", ",", "new_value", ")", "else", ":", "return", "old_value", "!=", "new_value" ]
Numpy aware comparison between two values.
[ "Numpy", "aware", "comparison", "between", "two", "values", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/custom_containers.py#L273-L278
238,283
IDSIA/sacred
sacred/experiment.py
Experiment.main
def main(self, function): """ Decorator to define the main function of the experiment. The main function of an experiment is the default command that is being run when no command is specified, or when calling the run() method. Usually it is more convenient to use ``automain`` instead. """ captured = self.command(function) self.default_command = captured.__name__ return captured
python
def main(self, function): captured = self.command(function) self.default_command = captured.__name__ return captured
[ "def", "main", "(", "self", ",", "function", ")", ":", "captured", "=", "self", ".", "command", "(", "function", ")", "self", ".", "default_command", "=", "captured", ".", "__name__", "return", "captured" ]
Decorator to define the main function of the experiment. The main function of an experiment is the default command that is being run when no command is specified, or when calling the run() method. Usually it is more convenient to use ``automain`` instead.
[ "Decorator", "to", "define", "the", "main", "function", "of", "the", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L96-L107
238,284
IDSIA/sacred
sacred/experiment.py
Experiment.option_hook
def option_hook(self, function): """ Decorator for adding an option hook function. An option hook is a function that is called right before a run is created. It receives (and potentially modifies) the options dictionary. That is, the dictionary of commandline options used for this run. .. note:: The decorated function MUST have an argument called options. The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries, but changing them has no effect. Only modification on flags (entries starting with ``'--'``) are considered. """ sig = Signature(function) if "options" not in sig.arguments: raise KeyError("option_hook functions must have an argument called" " 'options', but got {}".format(sig.arguments)) self.option_hooks.append(function) return function
python
def option_hook(self, function): sig = Signature(function) if "options" not in sig.arguments: raise KeyError("option_hook functions must have an argument called" " 'options', but got {}".format(sig.arguments)) self.option_hooks.append(function) return function
[ "def", "option_hook", "(", "self", ",", "function", ")", ":", "sig", "=", "Signature", "(", "function", ")", "if", "\"options\"", "not", "in", "sig", ".", "arguments", ":", "raise", "KeyError", "(", "\"option_hook functions must have an argument called\"", "\" 'op...
Decorator for adding an option hook function. An option hook is a function that is called right before a run is created. It receives (and potentially modifies) the options dictionary. That is, the dictionary of commandline options used for this run. .. note:: The decorated function MUST have an argument called options. The options also contain ``'COMMAND'`` and ``'UPDATE'`` entries, but changing them has no effect. Only modification on flags (entries starting with ``'--'``) are considered.
[ "Decorator", "for", "adding", "an", "option", "hook", "function", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L143-L164
238,285
IDSIA/sacred
sacred/experiment.py
Experiment.get_usage
def get_usage(self, program_name=None): """Get the commandline usage string for this experiment.""" program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy', self.base_dir) commands = OrderedDict(self.gather_commands()) options = gather_command_line_options() long_usage = format_usage(program_name, self.doc, commands, options) # internal usage is a workaround because docopt cannot handle spaces # in program names. So for parsing we use 'dummy' as the program name. # for printing help etc. we want to use the actual program name. internal_usage = format_usage('dummy', self.doc, commands, options) short_usage = printable_usage(long_usage) return short_usage, long_usage, internal_usage
python
def get_usage(self, program_name=None): program_name = os.path.relpath(program_name or sys.argv[0] or 'Dummy', self.base_dir) commands = OrderedDict(self.gather_commands()) options = gather_command_line_options() long_usage = format_usage(program_name, self.doc, commands, options) # internal usage is a workaround because docopt cannot handle spaces # in program names. So for parsing we use 'dummy' as the program name. # for printing help etc. we want to use the actual program name. internal_usage = format_usage('dummy', self.doc, commands, options) short_usage = printable_usage(long_usage) return short_usage, long_usage, internal_usage
[ "def", "get_usage", "(", "self", ",", "program_name", "=", "None", ")", ":", "program_name", "=", "os", ".", "path", ".", "relpath", "(", "program_name", "or", "sys", ".", "argv", "[", "0", "]", "or", "'Dummy'", ",", "self", ".", "base_dir", ")", "co...
Get the commandline usage string for this experiment.
[ "Get", "the", "commandline", "usage", "string", "for", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L168-L180
238,286
IDSIA/sacred
sacred/experiment.py
Experiment.run
def run(self, command_name=None, config_updates=None, named_configs=(), meta_info=None, options=None): """ Run the main function of the experiment or a given command. Parameters ---------- command_name : str, optional Name of the command to be run. Defaults to main function. config_updates : dict, optional Changes to the configuration as a nested dictionary named_configs : list[str], optional list of names of named_configs to use meta_info : dict, optional Additional meta information for this run. options : dict, optional Dictionary of options to use Returns ------- sacred.run.Run the Run object corresponding to the finished run """ run = self._create_run(command_name, config_updates, named_configs, meta_info, options) run() return run
python
def run(self, command_name=None, config_updates=None, named_configs=(), meta_info=None, options=None): run = self._create_run(command_name, config_updates, named_configs, meta_info, options) run() return run
[ "def", "run", "(", "self", ",", "command_name", "=", "None", ",", "config_updates", "=", "None", ",", "named_configs", "=", "(", ")", ",", "meta_info", "=", "None", ",", "options", "=", "None", ")", ":", "run", "=", "self", ".", "_create_run", "(", "...
Run the main function of the experiment or a given command. Parameters ---------- command_name : str, optional Name of the command to be run. Defaults to main function. config_updates : dict, optional Changes to the configuration as a nested dictionary named_configs : list[str], optional list of names of named_configs to use meta_info : dict, optional Additional meta information for this run. options : dict, optional Dictionary of options to use Returns ------- sacred.run.Run the Run object corresponding to the finished run
[ "Run", "the", "main", "function", "of", "the", "experiment", "or", "a", "given", "command", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L182-L213
238,287
IDSIA/sacred
sacred/experiment.py
Experiment.run_command
def run_command(self, command_name, config_updates=None, named_configs=(), args=(), meta_info=None): """Run the command with the given name. .. note:: Deprecated in Sacred 0.7 run_command() will be removed in Sacred 1.0. It is replaced by run() which can now also handle command_names. """ import warnings warnings.warn("run_command is deprecated. Use run instead", DeprecationWarning) return self.run(command_name, config_updates, named_configs, meta_info, args)
python
def run_command(self, command_name, config_updates=None, named_configs=(), args=(), meta_info=None): import warnings warnings.warn("run_command is deprecated. Use run instead", DeprecationWarning) return self.run(command_name, config_updates, named_configs, meta_info, args)
[ "def", "run_command", "(", "self", ",", "command_name", ",", "config_updates", "=", "None", ",", "named_configs", "=", "(", ")", ",", "args", "=", "(", ")", ",", "meta_info", "=", "None", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\...
Run the command with the given name. .. note:: Deprecated in Sacred 0.7 run_command() will be removed in Sacred 1.0. It is replaced by run() which can now also handle command_names.
[ "Run", "the", "command", "with", "the", "given", "name", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L215-L227
238,288
IDSIA/sacred
sacred/experiment.py
Experiment.run_commandline
def run_commandline(self, argv=None): """ Run the command-line interface of this experiment. If ``argv`` is omitted it defaults to ``sys.argv``. Parameters ---------- argv : list[str] or str, optional Command-line as string or list of strings like ``sys.argv``. Returns ------- sacred.run.Run The Run object corresponding to the finished run. """ argv = ensure_wellformed_argv(argv) short_usage, usage, internal_usage = self.get_usage() args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False) cmd_name = args.get('COMMAND') or self.default_command config_updates, named_configs = get_config_updates(args['UPDATE']) err = self._check_command(cmd_name) if not args['help'] and err: print(short_usage) print(err) exit(1) if self._handle_help(args, usage): exit() try: return self.run(cmd_name, config_updates, named_configs, {}, args) except Exception as e: if self.current_run: debug = self.current_run.debug else: # The usual command line options are applied after the run # object is built completely. Some exceptions (e.g. # ConfigAddedError) are raised before this. In these cases, # the debug flag must be checked manually. debug = args.get('--debug', False) if debug: # Debug: Don't change behaviour, just re-raise exception raise elif self.current_run and self.current_run.pdb: # Print exception and attach pdb debugger import traceback import pdb traceback.print_exception(*sys.exc_info()) pdb.post_mortem() else: # Handle pretty printing of exceptions. This includes # filtering the stacktrace and printing the usage, as # specified by the exceptions attributes if isinstance(e, SacredError): print(format_sacred_error(e, short_usage), file=sys.stderr) else: print_filtered_stacktrace() exit(1)
python
def run_commandline(self, argv=None): argv = ensure_wellformed_argv(argv) short_usage, usage, internal_usage = self.get_usage() args = docopt(internal_usage, [str(a) for a in argv[1:]], help=False) cmd_name = args.get('COMMAND') or self.default_command config_updates, named_configs = get_config_updates(args['UPDATE']) err = self._check_command(cmd_name) if not args['help'] and err: print(short_usage) print(err) exit(1) if self._handle_help(args, usage): exit() try: return self.run(cmd_name, config_updates, named_configs, {}, args) except Exception as e: if self.current_run: debug = self.current_run.debug else: # The usual command line options are applied after the run # object is built completely. Some exceptions (e.g. # ConfigAddedError) are raised before this. In these cases, # the debug flag must be checked manually. debug = args.get('--debug', False) if debug: # Debug: Don't change behaviour, just re-raise exception raise elif self.current_run and self.current_run.pdb: # Print exception and attach pdb debugger import traceback import pdb traceback.print_exception(*sys.exc_info()) pdb.post_mortem() else: # Handle pretty printing of exceptions. This includes # filtering the stacktrace and printing the usage, as # specified by the exceptions attributes if isinstance(e, SacredError): print(format_sacred_error(e, short_usage), file=sys.stderr) else: print_filtered_stacktrace() exit(1)
[ "def", "run_commandline", "(", "self", ",", "argv", "=", "None", ")", ":", "argv", "=", "ensure_wellformed_argv", "(", "argv", ")", "short_usage", ",", "usage", ",", "internal_usage", "=", "self", ".", "get_usage", "(", ")", "args", "=", "docopt", "(", "...
Run the command-line interface of this experiment. If ``argv`` is omitted it defaults to ``sys.argv``. Parameters ---------- argv : list[str] or str, optional Command-line as string or list of strings like ``sys.argv``. Returns ------- sacred.run.Run The Run object corresponding to the finished run.
[ "Run", "the", "command", "-", "line", "interface", "of", "this", "experiment", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L229-L291
238,289
IDSIA/sacred
sacred/experiment.py
Experiment.get_default_options
def get_default_options(self): """Get a dictionary of default options as used with run. Returns ------- dict A dictionary containing option keys of the form '--beat_interval'. Their values are boolean if the option is a flag, otherwise None or its default value. """ _, _, internal_usage = self.get_usage() args = docopt(internal_usage, []) return {k: v for k, v in args.items() if k.startswith('--')}
python
def get_default_options(self): _, _, internal_usage = self.get_usage() args = docopt(internal_usage, []) return {k: v for k, v in args.items() if k.startswith('--')}
[ "def", "get_default_options", "(", "self", ")", ":", "_", ",", "_", ",", "internal_usage", "=", "self", ".", "get_usage", "(", ")", "args", "=", "docopt", "(", "internal_usage", ",", "[", "]", ")", "return", "{", "k", ":", "v", "for", "k", ",", "v"...
Get a dictionary of default options as used with run. Returns ------- dict A dictionary containing option keys of the form '--beat_interval'. Their values are boolean if the option is a flag, otherwise None or its default value.
[ "Get", "a", "dictionary", "of", "default", "options", "as", "used", "with", "run", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L420-L433
238,290
IDSIA/sacred
sacred/config/signature.py
Signature.construct_arguments
def construct_arguments(self, args, kwargs, options, bound=False): """ Construct args list and kwargs dictionary for this signature. They are created such that: - the original explicit call arguments (args, kwargs) are preserved - missing arguments are filled in by name using options (if possible) - default arguments are overridden by options - TypeError is thrown if: * kwargs contains one or more unexpected keyword arguments * conflicting values for a parameter in both args and kwargs * there is an unfilled parameter at the end of this process """ expected_args = self._get_expected_args(bound) self._assert_no_unexpected_args(expected_args, args) self._assert_no_unexpected_kwargs(expected_args, kwargs) self._assert_no_duplicate_args(expected_args, args, kwargs) args, kwargs = self._fill_in_options(args, kwargs, options, bound) self._assert_no_missing_args(args, kwargs, bound) return args, kwargs
python
def construct_arguments(self, args, kwargs, options, bound=False): expected_args = self._get_expected_args(bound) self._assert_no_unexpected_args(expected_args, args) self._assert_no_unexpected_kwargs(expected_args, kwargs) self._assert_no_duplicate_args(expected_args, args, kwargs) args, kwargs = self._fill_in_options(args, kwargs, options, bound) self._assert_no_missing_args(args, kwargs, bound) return args, kwargs
[ "def", "construct_arguments", "(", "self", ",", "args", ",", "kwargs", ",", "options", ",", "bound", "=", "False", ")", ":", "expected_args", "=", "self", ".", "_get_expected_args", "(", "bound", ")", "self", ".", "_assert_no_unexpected_args", "(", "expected_a...
Construct args list and kwargs dictionary for this signature. They are created such that: - the original explicit call arguments (args, kwargs) are preserved - missing arguments are filled in by name using options (if possible) - default arguments are overridden by options - TypeError is thrown if: * kwargs contains one or more unexpected keyword arguments * conflicting values for a parameter in both args and kwargs * there is an unfilled parameter at the end of this process
[ "Construct", "args", "list", "and", "kwargs", "dictionary", "for", "this", "signature", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/signature.py#L83-L104
238,291
IDSIA/sacred
sacred/stdout_capturing.py
flush
def flush(): """Try to flush all stdio buffers, both from python and from C.""" try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass # unsupported try: libc.fflush(None) except (AttributeError, ValueError, IOError): pass
python
def flush(): try: sys.stdout.flush() sys.stderr.flush() except (AttributeError, ValueError, IOError): pass # unsupported try: libc.fflush(None) except (AttributeError, ValueError, IOError): pass
[ "def", "flush", "(", ")", ":", "try", ":", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "except", "(", "AttributeError", ",", "ValueError", ",", "IOError", ")", ":", "pass", "# unsupported", "try", ":", ...
Try to flush all stdio buffers, both from python and from C.
[ "Try", "to", "flush", "all", "stdio", "buffers", "both", "from", "python", "and", "from", "C", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L16-L26
238,292
IDSIA/sacred
sacred/stdout_capturing.py
tee_output_python
def tee_output_python(): """Duplicate sys.stdout and sys.stderr to new StringIO.""" buffer = StringIO() out = CapturedStdout(buffer) orig_stdout, orig_stderr = sys.stdout, sys.stderr flush() sys.stdout = TeeingStreamProxy(sys.stdout, buffer) sys.stderr = TeeingStreamProxy(sys.stderr, buffer) try: yield out finally: flush() out.finalize() sys.stdout, sys.stderr = orig_stdout, orig_stderr
python
def tee_output_python(): buffer = StringIO() out = CapturedStdout(buffer) orig_stdout, orig_stderr = sys.stdout, sys.stderr flush() sys.stdout = TeeingStreamProxy(sys.stdout, buffer) sys.stderr = TeeingStreamProxy(sys.stderr, buffer) try: yield out finally: flush() out.finalize() sys.stdout, sys.stderr = orig_stdout, orig_stderr
[ "def", "tee_output_python", "(", ")", ":", "buffer", "=", "StringIO", "(", ")", "out", "=", "CapturedStdout", "(", "buffer", ")", "orig_stdout", ",", "orig_stderr", "=", "sys", ".", "stdout", ",", "sys", ".", "stderr", "flush", "(", ")", "sys", ".", "s...
Duplicate sys.stdout and sys.stderr to new StringIO.
[ "Duplicate", "sys", ".", "stdout", "and", "sys", ".", "stderr", "to", "new", "StringIO", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L97-L110
238,293
IDSIA/sacred
sacred/stdout_capturing.py
tee_output_fd
def tee_output_fd(): """Duplicate stdout and stderr to a file on the file descriptor level.""" with NamedTemporaryFile(mode='w+') as target: original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target.fileno() # Save a copy of the original stdout and stderr file descriptors saved_stdout_fd = os.dup(original_stdout_fd) saved_stderr_fd = os.dup(original_stderr_fd) try: # we call os.setsid to move process to a new process group # this is done to avoid receiving KeyboardInterrupts (see #149) # in Python 3 we could just pass start_new_session=True tee_stdout = subprocess.Popen( ['tee', '-a', target.name], preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=1) tee_stderr = subprocess.Popen( ['tee', '-a', target.name], preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=2) except (FileNotFoundError, OSError, AttributeError): # No tee found in this operating system. Trying to use a python # implementation of tee. However this is slow and error-prone. tee_stdout = subprocess.Popen( [sys.executable, "-m", "sacred.pytee"], stdin=subprocess.PIPE, stderr=target_fd) tee_stderr = subprocess.Popen( [sys.executable, "-m", "sacred.pytee"], stdin=subprocess.PIPE, stdout=target_fd) flush() os.dup2(tee_stdout.stdin.fileno(), original_stdout_fd) os.dup2(tee_stderr.stdin.fileno(), original_stderr_fd) out = CapturedStdout(target) try: yield out # let the caller do their printing finally: flush() # then redirect stdout back to the saved fd tee_stdout.stdin.close() tee_stderr.stdin.close() # restore original fds os.dup2(saved_stdout_fd, original_stdout_fd) os.dup2(saved_stderr_fd, original_stderr_fd) # wait for completion of the tee processes with timeout # implemented using a timer because timeout support is py3 only def kill_tees(): tee_stdout.kill() tee_stderr.kill() tee_timer = Timer(1, kill_tees) try: tee_timer.start() tee_stdout.wait() tee_stderr.wait() finally: tee_timer.cancel() os.close(saved_stdout_fd) os.close(saved_stderr_fd) out.finalize()
python
def tee_output_fd(): with NamedTemporaryFile(mode='w+') as target: original_stdout_fd = 1 original_stderr_fd = 2 target_fd = target.fileno() # Save a copy of the original stdout and stderr file descriptors saved_stdout_fd = os.dup(original_stdout_fd) saved_stderr_fd = os.dup(original_stderr_fd) try: # we call os.setsid to move process to a new process group # this is done to avoid receiving KeyboardInterrupts (see #149) # in Python 3 we could just pass start_new_session=True tee_stdout = subprocess.Popen( ['tee', '-a', target.name], preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=1) tee_stderr = subprocess.Popen( ['tee', '-a', target.name], preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=2) except (FileNotFoundError, OSError, AttributeError): # No tee found in this operating system. Trying to use a python # implementation of tee. However this is slow and error-prone. tee_stdout = subprocess.Popen( [sys.executable, "-m", "sacred.pytee"], stdin=subprocess.PIPE, stderr=target_fd) tee_stderr = subprocess.Popen( [sys.executable, "-m", "sacred.pytee"], stdin=subprocess.PIPE, stdout=target_fd) flush() os.dup2(tee_stdout.stdin.fileno(), original_stdout_fd) os.dup2(tee_stderr.stdin.fileno(), original_stderr_fd) out = CapturedStdout(target) try: yield out # let the caller do their printing finally: flush() # then redirect stdout back to the saved fd tee_stdout.stdin.close() tee_stderr.stdin.close() # restore original fds os.dup2(saved_stdout_fd, original_stdout_fd) os.dup2(saved_stderr_fd, original_stderr_fd) # wait for completion of the tee processes with timeout # implemented using a timer because timeout support is py3 only def kill_tees(): tee_stdout.kill() tee_stderr.kill() tee_timer = Timer(1, kill_tees) try: tee_timer.start() tee_stdout.wait() tee_stderr.wait() finally: tee_timer.cancel() os.close(saved_stdout_fd) os.close(saved_stderr_fd) out.finalize()
[ "def", "tee_output_fd", "(", ")", ":", "with", "NamedTemporaryFile", "(", "mode", "=", "'w+'", ")", "as", "target", ":", "original_stdout_fd", "=", "1", "original_stderr_fd", "=", "2", "target_fd", "=", "target", ".", "fileno", "(", ")", "# Save a copy of the ...
Duplicate stdout and stderr to a file on the file descriptor level.
[ "Duplicate", "stdout", "and", "stderr", "to", "a", "file", "on", "the", "file", "descriptor", "level", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/stdout_capturing.py#L118-L183
238,294
IDSIA/sacred
sacred/arg_parser.py
get_config_updates
def get_config_updates(updates): """ Parse the UPDATES given on the commandline. Parameters ---------- updates (list[str]): list of update-strings of the form NAME=LITERAL or just NAME. Returns ------- (dict, list): Config updates and named configs to use """ config_updates = {} named_configs = [] if not updates: return config_updates, named_configs for upd in updates: if upd == '': continue path, sep, value = upd.partition('=') if sep == '=': path = path.strip() # get rid of surrounding whitespace value = value.strip() # get rid of surrounding whitespace set_by_dotted_path(config_updates, path, _convert_value(value)) else: named_configs.append(path) return config_updates, named_configs
python
def get_config_updates(updates): config_updates = {} named_configs = [] if not updates: return config_updates, named_configs for upd in updates: if upd == '': continue path, sep, value = upd.partition('=') if sep == '=': path = path.strip() # get rid of surrounding whitespace value = value.strip() # get rid of surrounding whitespace set_by_dotted_path(config_updates, path, _convert_value(value)) else: named_configs.append(path) return config_updates, named_configs
[ "def", "get_config_updates", "(", "updates", ")", ":", "config_updates", "=", "{", "}", "named_configs", "=", "[", "]", "if", "not", "updates", ":", "return", "config_updates", ",", "named_configs", "for", "upd", "in", "updates", ":", "if", "upd", "==", "'...
Parse the UPDATES given on the commandline. Parameters ---------- updates (list[str]): list of update-strings of the form NAME=LITERAL or just NAME. Returns ------- (dict, list): Config updates and named configs to use
[ "Parse", "the", "UPDATES", "given", "on", "the", "commandline", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L46-L75
238,295
IDSIA/sacred
sacred/arg_parser.py
_format_options_usage
def _format_options_usage(options): """ Format the Options-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a description for the commandline options """ options_usage = "" for op in options: short, long = op.get_flags() if op.arg: flag = "{short} {arg} {long}={arg}".format( short=short, long=long, arg=op.arg) else: flag = "{short} {long}".format(short=short, long=long) wrapped_description = textwrap.wrap(inspect.cleandoc(op.__doc__), width=79, initial_indent=' ' * 32, subsequent_indent=' ' * 32) wrapped_description = "\n".join(wrapped_description).strip() options_usage += " {0:28} {1}\n".format(flag, wrapped_description) return options_usage
python
def _format_options_usage(options): options_usage = "" for op in options: short, long = op.get_flags() if op.arg: flag = "{short} {arg} {long}={arg}".format( short=short, long=long, arg=op.arg) else: flag = "{short} {long}".format(short=short, long=long) wrapped_description = textwrap.wrap(inspect.cleandoc(op.__doc__), width=79, initial_indent=' ' * 32, subsequent_indent=' ' * 32) wrapped_description = "\n".join(wrapped_description).strip() options_usage += " {0:28} {1}\n".format(flag, wrapped_description) return options_usage
[ "def", "_format_options_usage", "(", "options", ")", ":", "options_usage", "=", "\"\"", "for", "op", "in", "options", ":", "short", ",", "long", "=", "op", ".", "get_flags", "(", ")", "if", "op", ".", "arg", ":", "flag", "=", "\"{short} {arg} {long}={arg}\...
Format the Options-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a description for the commandline options
[ "Format", "the", "Options", "-", "part", "of", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L78-L109
238,296
IDSIA/sacred
sacred/arg_parser.py
_format_arguments_usage
def _format_arguments_usage(options): """ Construct the Arguments-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a description of the arguments supported by the commandline options. """ argument_usage = "" for op in options: if op.arg and op.arg_description: wrapped_description = textwrap.wrap(op.arg_description, width=79, initial_indent=' ' * 12, subsequent_indent=' ' * 12) wrapped_description = "\n".join(wrapped_description).strip() argument_usage += " {0:8} {1}\n".format(op.arg, wrapped_description) return argument_usage
python
def _format_arguments_usage(options): argument_usage = "" for op in options: if op.arg and op.arg_description: wrapped_description = textwrap.wrap(op.arg_description, width=79, initial_indent=' ' * 12, subsequent_indent=' ' * 12) wrapped_description = "\n".join(wrapped_description).strip() argument_usage += " {0:8} {1}\n".format(op.arg, wrapped_description) return argument_usage
[ "def", "_format_arguments_usage", "(", "options", ")", ":", "argument_usage", "=", "\"\"", "for", "op", "in", "options", ":", "if", "op", ".", "arg", "and", "op", ".", "arg_description", ":", "wrapped_description", "=", "textwrap", ".", "wrap", "(", "op", ...
Construct the Arguments-part of the usage text. Parameters ---------- options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str Text formatted as a description of the arguments supported by the commandline options.
[ "Construct", "the", "Arguments", "-", "part", "of", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L112-L138
238,297
IDSIA/sacred
sacred/arg_parser.py
_format_command_usage
def _format_command_usage(commands): """ Construct the Commands-part of the usage text. Parameters ---------- commands : dict[str, func] dictionary of supported commands. Each entry should be a tuple of (name, function). Returns ------- str Text formatted as a description of the commands. """ if not commands: return "" command_usage = "\nCommands:\n" cmd_len = max([len(c) for c in commands] + [8]) command_doc = OrderedDict( [(cmd_name, _get_first_line_of_docstring(cmd_doc)) for cmd_name, cmd_doc in commands.items()]) for cmd_name, cmd_doc in command_doc.items(): command_usage += (" {:%d} {}\n" % cmd_len).format(cmd_name, cmd_doc) return command_usage
python
def _format_command_usage(commands): if not commands: return "" command_usage = "\nCommands:\n" cmd_len = max([len(c) for c in commands] + [8]) command_doc = OrderedDict( [(cmd_name, _get_first_line_of_docstring(cmd_doc)) for cmd_name, cmd_doc in commands.items()]) for cmd_name, cmd_doc in command_doc.items(): command_usage += (" {:%d} {}\n" % cmd_len).format(cmd_name, cmd_doc) return command_usage
[ "def", "_format_command_usage", "(", "commands", ")", ":", "if", "not", "commands", ":", "return", "\"\"", "command_usage", "=", "\"\\nCommands:\\n\"", "cmd_len", "=", "max", "(", "[", "len", "(", "c", ")", "for", "c", "in", "commands", "]", "+", "[", "8...
Construct the Commands-part of the usage text. Parameters ---------- commands : dict[str, func] dictionary of supported commands. Each entry should be a tuple of (name, function). Returns ------- str Text formatted as a description of the commands.
[ "Construct", "the", "Commands", "-", "part", "of", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L141-L166
238,298
IDSIA/sacred
sacred/arg_parser.py
format_usage
def format_usage(program_name, description, commands=None, options=()): """ Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usually the docstring). commands : dict[str, func] Dictionary of supported commands. Each entry should be a tuple of (name, function). options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str The complete formatted usage text for this experiment. It adheres to the structure required by ``docopt``. """ usage = USAGE_TEMPLATE.format( program_name=cmd_quote(program_name), description=description.strip() if description else '', options=_format_options_usage(options), arguments=_format_arguments_usage(options), commands=_format_command_usage(commands) ) return usage
python
def format_usage(program_name, description, commands=None, options=()): usage = USAGE_TEMPLATE.format( program_name=cmd_quote(program_name), description=description.strip() if description else '', options=_format_options_usage(options), arguments=_format_arguments_usage(options), commands=_format_command_usage(commands) ) return usage
[ "def", "format_usage", "(", "program_name", ",", "description", ",", "commands", "=", "None", ",", "options", "=", "(", ")", ")", ":", "usage", "=", "USAGE_TEMPLATE", ".", "format", "(", "program_name", "=", "cmd_quote", "(", "program_name", ")", ",", "des...
Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usually the docstring). commands : dict[str, func] Dictionary of supported commands. Each entry should be a tuple of (name, function). options : list[sacred.commandline_options.CommandLineOption] A list of all supported commandline options. Returns ------- str The complete formatted usage text for this experiment. It adheres to the structure required by ``docopt``.
[ "Construct", "the", "usage", "text", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L169-L199
238,299
IDSIA/sacred
sacred/arg_parser.py
_convert_value
def _convert_value(value): """Parse string as python literal if possible and fallback to string.""" try: return restore(ast.literal_eval(value)) except (ValueError, SyntaxError): if SETTINGS.COMMAND_LINE.STRICT_PARSING: raise # use as string if nothing else worked return value
python
def _convert_value(value): try: return restore(ast.literal_eval(value)) except (ValueError, SyntaxError): if SETTINGS.COMMAND_LINE.STRICT_PARSING: raise # use as string if nothing else worked return value
[ "def", "_convert_value", "(", "value", ")", ":", "try", ":", "return", "restore", "(", "ast", ".", "literal_eval", "(", "value", ")", ")", "except", "(", "ValueError", ",", "SyntaxError", ")", ":", "if", "SETTINGS", ".", "COMMAND_LINE", ".", "STRICT_PARSIN...
Parse string as python literal if possible and fallback to string.
[ "Parse", "string", "as", "python", "literal", "if", "possible", "and", "fallback", "to", "string", "." ]
72633776bed9b5bddf93ae7d215188e61970973a
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/arg_parser.py#L206-L214