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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
224,400 | 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):
"""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 | [
"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 |
224,401 | 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):
"""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 | [
"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 |
224,402 | 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):
"""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)] | [
"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 |
224,403 | 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):
"""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"]) | [
"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 |
224,404 | 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):
"""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] | [
"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 |
224,405 | 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):
"""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 | [
"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 |
224,406 | 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):
""" 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 | [
"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 |
224,407 | 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():
"""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 | [
"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 |
224,408 | 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):
"""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 | [
"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 |
224,409 | 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):
"""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) | [
"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 |
224,410 | 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):
"""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"]) | [
"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 |
224,411 | 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):
"""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) | [
"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 |
224,412 | 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):
"""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.") | [
"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 |
224,413 | 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):
"""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" | [
"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 |
224,414 | 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):
"""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) | [
"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 |
224,415 | 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 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') | [
"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 |
224,416 | 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):
"""Darken a hex color."""
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 |
224,417 | 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):
"""Lighten a hex color."""
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 |
224,418 | 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):
"""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)) | [
"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 |
224,419 | 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):
"""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))) | [
"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 |
224,420 | 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):
"""Call a system command in the background,
disown it and hide it's output."""
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 |
224,421 | 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):
"""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 | [
"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 |
224,422 | 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):
"""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 | [
"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 |
224,423 | 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):
"""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]) | [
"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 |
224,424 | 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):
"""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) | [
"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 |
224,425 | 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):
"""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 | [
"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 |
224,426 | 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():
"""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() | [
"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 |
224,427 | 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():
"""List color 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 |
224,428 | 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):
"""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]
}
} | [
"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 |
224,429 | 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):
"""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 | [
"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 |
224,430 | 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):
"""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 | [
"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 |
224,431 | 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):
"""Figure out which backend to use."""
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 |
224,432 | 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():
"""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") | [
"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 |
224,433 | 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):
"""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] | [
"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 |
224,434 | 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():
"""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)") | [
"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 |
224,435 | 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):
"""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)] | [
"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 |
224,436 | 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():
"""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)] | [
"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 |
224,437 | 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):
"""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 | [
"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 |
224,438 | 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):
"""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 | [
"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 |
224,439 | 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):
"""Get a random theme file."""
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 |
224,440 | 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):
"""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) | [
"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 |
224,441 | 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):
"""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() | [
"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 |
224,442 | 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():
"""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) | [
"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 |
224,443 | 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):
"""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:]] | [
"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 |
224,444 | 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):
"""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 | [
"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 |
224,445 | 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):
"""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) | [
"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 |
224,446 | 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):
"""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() | [
"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 |
224,447 | 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):
"""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) | [
"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 |
224,448 | 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):
"""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) | [
"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 |
224,449 | 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):
"""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) | [
"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 |
224,450 | 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):
"""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.") | [
"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 |
224,451 | 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):
"""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) | [
"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 |
224,452 | 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):
"""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.") | [
"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 |
224,453 | 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):
"""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) | [
"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 |
224,454 | 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):
"""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]) | [
"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 |
224,455 | 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):
"""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]) | [
"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 |
224,456 | 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():
"""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.") | [
"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 |
224,457 | 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):
"""Reload environment."""
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 |
224,458 | 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):
"""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) | [
"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 |
224,459 | 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):
"""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 | [
"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 |
224,460 | 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):
"""
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 | [
"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 |
224,461 | 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):
"""
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)) | [
"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 |
224,462 | 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):
"""
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 | [
"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 |
224,463 | 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 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('') | [
"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 |
224,464 | 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'):
"""
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) | [
"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 |
224,465 | 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):
"""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') | [
"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 |
224,466 | 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):
"""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 | [
"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 |
224,467 | 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):
"""
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 | [
"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 |
224,468 | 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):
"""
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 | [
"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 |
224,469 | 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):
"""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 | [
"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 |
224,470 | 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 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 | [
"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 |
224,471 | 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):
"""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) | [
"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 |
224,472 | 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):
"""
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) | [
"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 |
224,473 | 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):
"""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('--')} | [
"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 |
224,474 | 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):
"""
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 | [
"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 |
224,475 | 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 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 | [
"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 |
224,476 | 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():
"""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 | [
"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 |
224,477 | 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():
"""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() | [
"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 |
224,478 | 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):
"""
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 | [
"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 |
224,479 | 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):
"""
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 | [
"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 |
224,480 | 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):
"""
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 | [
"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 |
224,481 | 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):
"""
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 | [
"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 |
224,482 | 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=()):
"""
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 | [
"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 |
224,483 | 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):
"""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 | [
"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 |
224,484 | IDSIA/sacred | sacred/utils.py | iterate_flattened_separately | def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
"""
Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf.
"""
if manually_sorted_keys is None:
manually_sorted_keys = []
for key in manually_sorted_keys:
if key in dictionary:
yield key, dictionary[key]
single_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(not dictionary[key] or
not isinstance(dictionary[key], dict))]
for key in sorted(single_line_keys):
yield key, dictionary[key]
multi_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(dictionary[key] and
isinstance(dictionary[key], dict))]
for key in sorted(multi_line_keys):
yield key, PATHCHANGE
for k, val in iterate_flattened_separately(dictionary[key],
manually_sorted_keys):
yield join_paths(key, k), val | python | def iterate_flattened_separately(dictionary, manually_sorted_keys=None):
"""
Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf.
"""
if manually_sorted_keys is None:
manually_sorted_keys = []
for key in manually_sorted_keys:
if key in dictionary:
yield key, dictionary[key]
single_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(not dictionary[key] or
not isinstance(dictionary[key], dict))]
for key in sorted(single_line_keys):
yield key, dictionary[key]
multi_line_keys = [key for key in dictionary.keys() if
key not in manually_sorted_keys and
(dictionary[key] and
isinstance(dictionary[key], dict))]
for key in sorted(multi_line_keys):
yield key, PATHCHANGE
for k, val in iterate_flattened_separately(dictionary[key],
manually_sorted_keys):
yield join_paths(key, k), val | [
"def",
"iterate_flattened_separately",
"(",
"dictionary",
",",
"manually_sorted_keys",
"=",
"None",
")",
":",
"if",
"manually_sorted_keys",
"is",
"None",
":",
"manually_sorted_keys",
"=",
"[",
"]",
"for",
"key",
"in",
"manually_sorted_keys",
":",
"if",
"key",
"in"... | Recursively iterate over the items of a dictionary in a special order.
First iterate over manually sorted keys and then over all items that are
non-dictionary values (sorted by keys), then over the rest
(sorted by keys), providing full dotted paths for every leaf. | [
"Recursively",
"iterate",
"over",
"the",
"items",
"of",
"a",
"dictionary",
"in",
"a",
"special",
"order",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L325-L354 |
224,485 | IDSIA/sacred | sacred/utils.py | iterate_flattened | def iterate_flattened(d):
"""
Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf.
"""
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict) and value:
for k, v in iterate_flattened(d[key]):
yield join_paths(key, k), v
else:
yield key, value | python | def iterate_flattened(d):
"""
Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf.
"""
for key in sorted(d.keys()):
value = d[key]
if isinstance(value, dict) and value:
for k, v in iterate_flattened(d[key]):
yield join_paths(key, k), v
else:
yield key, value | [
"def",
"iterate_flattened",
"(",
"d",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"d",
".",
"keys",
"(",
")",
")",
":",
"value",
"=",
"d",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"value",
":",
"for",
"k",
",... | Recursively iterate over the items of a dictionary.
Provides a full dotted paths for every leaf. | [
"Recursively",
"iterate",
"over",
"the",
"items",
"of",
"a",
"dictionary",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L357-L369 |
224,486 | IDSIA/sacred | sacred/utils.py | set_by_dotted_path | def set_by_dotted_path(d, path, value):
"""
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'baz': 3}}}
"""
split_path = path.split('.')
current_option = d
for p in split_path[:-1]:
if p not in current_option:
current_option[p] = dict()
current_option = current_option[p]
current_option[split_path[-1]] = value | python | def set_by_dotted_path(d, path, value):
"""
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'baz': 3}}}
"""
split_path = path.split('.')
current_option = d
for p in split_path[:-1]:
if p not in current_option:
current_option[p] = dict()
current_option = current_option[p]
current_option[split_path[-1]] = value | [
"def",
"set_by_dotted_path",
"(",
"d",
",",
"path",
",",
"value",
")",
":",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_option",
"=",
"d",
"for",
"p",
"in",
"split_path",
"[",
":",
"-",
"1",
"]",
":",
"if",
"p",
"not",
"in",
... | Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'baz': 3}}} | [
"Set",
"an",
"entry",
"in",
"a",
"nested",
"dict",
"using",
"a",
"dotted",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L372-L395 |
224,487 | IDSIA/sacred | sacred/utils.py | get_by_dotted_path | def get_by_dotted_path(d, path, default=None):
"""
Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12
"""
if not path:
return d
split_path = path.split('.')
current_option = d
for p in split_path:
if p not in current_option:
return default
current_option = current_option[p]
return current_option | python | def get_by_dotted_path(d, path, default=None):
"""
Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12
"""
if not path:
return d
split_path = path.split('.')
current_option = d
for p in split_path:
if p not in current_option:
return default
current_option = current_option[p]
return current_option | [
"def",
"get_by_dotted_path",
"(",
"d",
",",
"path",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"d",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"current_option",
"=",
"d",
"for",
"p",
"in",
"split_path",
... | Get an entry from nested dictionaries using a dotted path.
Example:
>>> get_by_dotted_path({'foo': {'a': 12}}, 'foo.a')
12 | [
"Get",
"an",
"entry",
"from",
"nested",
"dictionaries",
"using",
"a",
"dotted",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L398-L414 |
224,488 | IDSIA/sacred | sacred/utils.py | iter_path_splits | def iter_path_splits(path):
"""
Iterate over possible splits of a dotted path.
The first part can be empty the second should not be.
Example:
>>> list(iter_path_splits('foo.bar.baz'))
[('', 'foo.bar.baz'),
('foo', 'bar.baz'),
('foo.bar', 'baz')]
"""
split_path = path.split('.')
for i in range(len(split_path)):
p1 = join_paths(*split_path[:i])
p2 = join_paths(*split_path[i:])
yield p1, p2 | python | def iter_path_splits(path):
"""
Iterate over possible splits of a dotted path.
The first part can be empty the second should not be.
Example:
>>> list(iter_path_splits('foo.bar.baz'))
[('', 'foo.bar.baz'),
('foo', 'bar.baz'),
('foo.bar', 'baz')]
"""
split_path = path.split('.')
for i in range(len(split_path)):
p1 = join_paths(*split_path[:i])
p2 = join_paths(*split_path[i:])
yield p1, p2 | [
"def",
"iter_path_splits",
"(",
"path",
")",
":",
"split_path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"split_path",
")",
")",
":",
"p1",
"=",
"join_paths",
"(",
"*",
"split_path",
"[",
":",
"i",
"]"... | Iterate over possible splits of a dotted path.
The first part can be empty the second should not be.
Example:
>>> list(iter_path_splits('foo.bar.baz'))
[('', 'foo.bar.baz'),
('foo', 'bar.baz'),
('foo.bar', 'baz')] | [
"Iterate",
"over",
"possible",
"splits",
"of",
"a",
"dotted",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L417-L433 |
224,489 | IDSIA/sacred | sacred/utils.py | is_prefix | def is_prefix(pre_path, path):
"""Return True if pre_path is a path-prefix of path."""
pre_path = pre_path.strip('.')
path = path.strip('.')
return not pre_path or path.startswith(pre_path + '.') | python | def is_prefix(pre_path, path):
"""Return True if pre_path is a path-prefix of path."""
pre_path = pre_path.strip('.')
path = path.strip('.')
return not pre_path or path.startswith(pre_path + '.') | [
"def",
"is_prefix",
"(",
"pre_path",
",",
"path",
")",
":",
"pre_path",
"=",
"pre_path",
".",
"strip",
"(",
"'.'",
")",
"path",
"=",
"path",
".",
"strip",
"(",
"'.'",
")",
"return",
"not",
"pre_path",
"or",
"path",
".",
"startswith",
"(",
"pre_path",
... | Return True if pre_path is a path-prefix of path. | [
"Return",
"True",
"if",
"pre_path",
"is",
"a",
"path",
"-",
"prefix",
"of",
"path",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L454-L458 |
224,490 | IDSIA/sacred | sacred/utils.py | rel_path | def rel_path(base, path):
"""Return path relative to base."""
if base == path:
return ''
assert is_prefix(base, path), "{} not a prefix of {}".format(base, path)
return path[len(base):].strip('.') | python | def rel_path(base, path):
"""Return path relative to base."""
if base == path:
return ''
assert is_prefix(base, path), "{} not a prefix of {}".format(base, path)
return path[len(base):].strip('.') | [
"def",
"rel_path",
"(",
"base",
",",
"path",
")",
":",
"if",
"base",
"==",
"path",
":",
"return",
"''",
"assert",
"is_prefix",
"(",
"base",
",",
"path",
")",
",",
"\"{} not a prefix of {}\"",
".",
"format",
"(",
"base",
",",
"path",
")",
"return",
"pat... | Return path relative to base. | [
"Return",
"path",
"relative",
"to",
"base",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L461-L466 |
224,491 | IDSIA/sacred | sacred/utils.py | convert_to_nested_dict | def convert_to_nested_dict(dotted_dict):
"""Convert a dict with dotted path keys to corresponding nested dict."""
nested_dict = {}
for k, v in iterate_flattened(dotted_dict):
set_by_dotted_path(nested_dict, k, v)
return nested_dict | python | def convert_to_nested_dict(dotted_dict):
"""Convert a dict with dotted path keys to corresponding nested dict."""
nested_dict = {}
for k, v in iterate_flattened(dotted_dict):
set_by_dotted_path(nested_dict, k, v)
return nested_dict | [
"def",
"convert_to_nested_dict",
"(",
"dotted_dict",
")",
":",
"nested_dict",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iterate_flattened",
"(",
"dotted_dict",
")",
":",
"set_by_dotted_path",
"(",
"nested_dict",
",",
"k",
",",
"v",
")",
"return",
"nested_d... | Convert a dict with dotted path keys to corresponding nested dict. | [
"Convert",
"a",
"dict",
"with",
"dotted",
"path",
"keys",
"to",
"corresponding",
"nested",
"dict",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L469-L474 |
224,492 | IDSIA/sacred | sacred/utils.py | format_filtered_stacktrace | def format_filtered_stacktrace(filter_traceback='default'):
"""
Returns the traceback as `string`.
`filter_traceback` can be one of:
- 'always': always filter out sacred internals
- 'default': Default behaviour: filter out sacred internals
if the exception did not originate from within sacred, and
print just the internal stack trace otherwise
- 'never': don't filter, always print full traceback
- All other values will fall back to 'never'.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
# determine if last exception is from sacred
current_tb = exc_traceback
while current_tb.tb_next is not None:
current_tb = current_tb.tb_next
if filter_traceback == 'default' \
and _is_sacred_frame(current_tb.tb_frame):
# just print sacred internal trace
header = ["Exception originated from within Sacred.\n"
"Traceback (most recent calls):\n"]
texts = tb.format_exception(exc_type, exc_value, current_tb)
return ''.join(header + texts[1:]).strip()
elif filter_traceback in ('default', 'always'):
# print filtered stacktrace
if sys.version_info >= (3, 5):
tb_exception = \
tb.TracebackException(exc_type, exc_value, exc_traceback,
limit=None)
return ''.join(filtered_traceback_format(tb_exception))
else:
s = "Traceback (most recent calls WITHOUT Sacred internals):"
current_tb = exc_traceback
while current_tb is not None:
if not _is_sacred_frame(current_tb.tb_frame):
tb.print_tb(current_tb, 1)
current_tb = current_tb.tb_next
s += "\n".join(tb.format_exception_only(exc_type,
exc_value)).strip()
return s
elif filter_traceback == 'never':
# print full stacktrace
return '\n'.join(
tb.format_exception(exc_type, exc_value, exc_traceback))
else:
raise ValueError('Unknown value for filter_traceback: ' +
filter_traceback) | python | def format_filtered_stacktrace(filter_traceback='default'):
"""
Returns the traceback as `string`.
`filter_traceback` can be one of:
- 'always': always filter out sacred internals
- 'default': Default behaviour: filter out sacred internals
if the exception did not originate from within sacred, and
print just the internal stack trace otherwise
- 'never': don't filter, always print full traceback
- All other values will fall back to 'never'.
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
# determine if last exception is from sacred
current_tb = exc_traceback
while current_tb.tb_next is not None:
current_tb = current_tb.tb_next
if filter_traceback == 'default' \
and _is_sacred_frame(current_tb.tb_frame):
# just print sacred internal trace
header = ["Exception originated from within Sacred.\n"
"Traceback (most recent calls):\n"]
texts = tb.format_exception(exc_type, exc_value, current_tb)
return ''.join(header + texts[1:]).strip()
elif filter_traceback in ('default', 'always'):
# print filtered stacktrace
if sys.version_info >= (3, 5):
tb_exception = \
tb.TracebackException(exc_type, exc_value, exc_traceback,
limit=None)
return ''.join(filtered_traceback_format(tb_exception))
else:
s = "Traceback (most recent calls WITHOUT Sacred internals):"
current_tb = exc_traceback
while current_tb is not None:
if not _is_sacred_frame(current_tb.tb_frame):
tb.print_tb(current_tb, 1)
current_tb = current_tb.tb_next
s += "\n".join(tb.format_exception_only(exc_type,
exc_value)).strip()
return s
elif filter_traceback == 'never':
# print full stacktrace
return '\n'.join(
tb.format_exception(exc_type, exc_value, exc_traceback))
else:
raise ValueError('Unknown value for filter_traceback: ' +
filter_traceback) | [
"def",
"format_filtered_stacktrace",
"(",
"filter_traceback",
"=",
"'default'",
")",
":",
"exc_type",
",",
"exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"# determine if last exception is from sacred",
"current_tb",
"=",
"exc_traceback",
"whil... | Returns the traceback as `string`.
`filter_traceback` can be one of:
- 'always': always filter out sacred internals
- 'default': Default behaviour: filter out sacred internals
if the exception did not originate from within sacred, and
print just the internal stack trace otherwise
- 'never': don't filter, always print full traceback
- All other values will fall back to 'never'. | [
"Returns",
"the",
"traceback",
"as",
"string",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L485-L533 |
224,493 | IDSIA/sacred | sacred/utils.py | get_inheritors | def get_inheritors(cls):
"""Get a set of all classes that inherit from the given class."""
subclasses = set()
work = [cls]
while work:
parent = work.pop()
for child in parent.__subclasses__():
if child not in subclasses:
subclasses.add(child)
work.append(child)
return subclasses | python | def get_inheritors(cls):
"""Get a set of all classes that inherit from the given class."""
subclasses = set()
work = [cls]
while work:
parent = work.pop()
for child in parent.__subclasses__():
if child not in subclasses:
subclasses.add(child)
work.append(child)
return subclasses | [
"def",
"get_inheritors",
"(",
"cls",
")",
":",
"subclasses",
"=",
"set",
"(",
")",
"work",
"=",
"[",
"cls",
"]",
"while",
"work",
":",
"parent",
"=",
"work",
".",
"pop",
"(",
")",
"for",
"child",
"in",
"parent",
".",
"__subclasses__",
"(",
")",
":"... | Get a set of all classes that inherit from the given class. | [
"Get",
"a",
"set",
"of",
"all",
"classes",
"that",
"inherit",
"from",
"the",
"given",
"class",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L593-L603 |
224,494 | IDSIA/sacred | sacred/utils.py | apply_backspaces_and_linefeeds | def apply_backspaces_and_linefeeds(text):
"""
Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
output chunk.
"""
orig_lines = text.split('\n')
orig_lines_len = len(orig_lines)
new_lines = []
for orig_line_idx, orig_line in enumerate(orig_lines):
chars, cursor = [], 0
orig_line_len = len(orig_line)
for orig_char_idx, orig_char in enumerate(orig_line):
if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or
orig_line_idx != orig_lines_len - 1):
cursor = 0
elif orig_char == '\b':
cursor = max(0, cursor - 1)
else:
if (orig_char == '\r' and
orig_char_idx == orig_line_len - 1 and
orig_line_idx == orig_lines_len - 1):
cursor = len(chars)
if cursor == len(chars):
chars.append(orig_char)
else:
chars[cursor] = orig_char
cursor += 1
new_lines.append(''.join(chars))
return '\n'.join(new_lines) | python | def apply_backspaces_and_linefeeds(text):
"""
Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
output chunk.
"""
orig_lines = text.split('\n')
orig_lines_len = len(orig_lines)
new_lines = []
for orig_line_idx, orig_line in enumerate(orig_lines):
chars, cursor = [], 0
orig_line_len = len(orig_line)
for orig_char_idx, orig_char in enumerate(orig_line):
if orig_char == '\r' and (orig_char_idx != orig_line_len - 1 or
orig_line_idx != orig_lines_len - 1):
cursor = 0
elif orig_char == '\b':
cursor = max(0, cursor - 1)
else:
if (orig_char == '\r' and
orig_char_idx == orig_line_len - 1 and
orig_line_idx == orig_lines_len - 1):
cursor = len(chars)
if cursor == len(chars):
chars.append(orig_char)
else:
chars[cursor] = orig_char
cursor += 1
new_lines.append(''.join(chars))
return '\n'.join(new_lines) | [
"def",
"apply_backspaces_and_linefeeds",
"(",
"text",
")",
":",
"orig_lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"orig_lines_len",
"=",
"len",
"(",
"orig_lines",
")",
"new_lines",
"=",
"[",
"]",
"for",
"orig_line_idx",
",",
"orig_line",
"in",
"enu... | Interpret backspaces and linefeeds in text like a terminal would.
Interpret text like a terminal by removing backspace and linefeed
characters and applying them line by line.
If final line ends with a carriage it keeps it to be concatenable with next
output chunk. | [
"Interpret",
"backspaces",
"and",
"linefeeds",
"in",
"text",
"like",
"a",
"terminal",
"would",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L614-L647 |
224,495 | IDSIA/sacred | sacred/utils.py | module_is_imported | def module_is_imported(modname, scope=None):
"""Checks if a module is imported within the current namespace."""
# return early if modname is not even cached
if not module_is_in_cache(modname):
return False
if scope is None: # use globals() of the caller by default
scope = inspect.stack()[1][0].f_globals
for m in scope.values():
if isinstance(m, type(sys)) and m.__name__ == modname:
return True
return False | python | def module_is_imported(modname, scope=None):
"""Checks if a module is imported within the current namespace."""
# return early if modname is not even cached
if not module_is_in_cache(modname):
return False
if scope is None: # use globals() of the caller by default
scope = inspect.stack()[1][0].f_globals
for m in scope.values():
if isinstance(m, type(sys)) and m.__name__ == modname:
return True
return False | [
"def",
"module_is_imported",
"(",
"modname",
",",
"scope",
"=",
"None",
")",
":",
"# return early if modname is not even cached",
"if",
"not",
"module_is_in_cache",
"(",
"modname",
")",
":",
"return",
"False",
"if",
"scope",
"is",
"None",
":",
"# use globals() of th... | Checks if a module is imported within the current namespace. | [
"Checks",
"if",
"a",
"module",
"is",
"imported",
"within",
"the",
"current",
"namespace",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/utils.py#L664-L677 |
224,496 | IDSIA/sacred | sacred/observers/telegram_obs.py | TelegramObserver.from_config | def from_config(cls, filename):
"""
Create a TelegramObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``token`` and a ``chat_id`` and can optionally set
``silent_completion``,``completed_text``, ``interrupted_text``, and
``failed_text``.
"""
import telegram
d = load_config_file(filename)
request = cls.get_proxy_request(d) if 'proxy_url' in d else None
if 'token' in d and 'chat_id' in d:
bot = telegram.Bot(d['token'], request=request)
obs = cls(bot, **d)
else:
raise ValueError("Telegram configuration file must contain "
"entries for 'token' and 'chat_id'!")
for k in ['completed_text', 'interrupted_text', 'failed_text']:
if k in d:
setattr(obs, k, d[k])
return obs | python | def from_config(cls, filename):
"""
Create a TelegramObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``token`` and a ``chat_id`` and can optionally set
``silent_completion``,``completed_text``, ``interrupted_text``, and
``failed_text``.
"""
import telegram
d = load_config_file(filename)
request = cls.get_proxy_request(d) if 'proxy_url' in d else None
if 'token' in d and 'chat_id' in d:
bot = telegram.Bot(d['token'], request=request)
obs = cls(bot, **d)
else:
raise ValueError("Telegram configuration file must contain "
"entries for 'token' and 'chat_id'!")
for k in ['completed_text', 'interrupted_text', 'failed_text']:
if k in d:
setattr(obs, k, d[k])
return obs | [
"def",
"from_config",
"(",
"cls",
",",
"filename",
")",
":",
"import",
"telegram",
"d",
"=",
"load_config_file",
"(",
"filename",
")",
"request",
"=",
"cls",
".",
"get_proxy_request",
"(",
"d",
")",
"if",
"'proxy_url'",
"in",
"d",
"else",
"None",
"if",
"... | Create a TelegramObserver from a given configuration file.
The file can be in any format supported by Sacred
(.json, .pickle, [.yaml]).
It has to specify a ``token`` and a ``chat_id`` and can optionally set
``silent_completion``,``completed_text``, ``interrupted_text``, and
``failed_text``. | [
"Create",
"a",
"TelegramObserver",
"from",
"a",
"given",
"configuration",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/telegram_obs.py#L73-L96 |
224,497 | IDSIA/sacred | sacred/observers/mongo.py | MongoObserver.log_metrics | def log_metrics(self, metrics_by_name, info):
"""Store new measurements to the database.
Take measurements and store them into
the metrics collection in the database.
Additionally, reference the metrics
in the info["metrics"] dictionary.
"""
if self.metrics is None:
# If, for whatever reason, the metrics collection has not been set
# do not try to save anything there.
return
for key in metrics_by_name:
query = {"run_id": self.run_entry['_id'],
"name": key}
push = {"steps": {"$each": metrics_by_name[key]["steps"]},
"values": {"$each": metrics_by_name[key]["values"]},
"timestamps": {"$each": metrics_by_name[key]["timestamps"]}
}
update = {"$push": push}
result = self.metrics.update_one(query, update, upsert=True)
if result.upserted_id is not None:
# This is the first time we are storing this metric
info.setdefault("metrics", []) \
.append({"name": key, "id": str(result.upserted_id)}) | python | def log_metrics(self, metrics_by_name, info):
"""Store new measurements to the database.
Take measurements and store them into
the metrics collection in the database.
Additionally, reference the metrics
in the info["metrics"] dictionary.
"""
if self.metrics is None:
# If, for whatever reason, the metrics collection has not been set
# do not try to save anything there.
return
for key in metrics_by_name:
query = {"run_id": self.run_entry['_id'],
"name": key}
push = {"steps": {"$each": metrics_by_name[key]["steps"]},
"values": {"$each": metrics_by_name[key]["values"]},
"timestamps": {"$each": metrics_by_name[key]["timestamps"]}
}
update = {"$push": push}
result = self.metrics.update_one(query, update, upsert=True)
if result.upserted_id is not None:
# This is the first time we are storing this metric
info.setdefault("metrics", []) \
.append({"name": key, "id": str(result.upserted_id)}) | [
"def",
"log_metrics",
"(",
"self",
",",
"metrics_by_name",
",",
"info",
")",
":",
"if",
"self",
".",
"metrics",
"is",
"None",
":",
"# If, for whatever reason, the metrics collection has not been set",
"# do not try to save anything there.",
"return",
"for",
"key",
"in",
... | Store new measurements to the database.
Take measurements and store them into
the metrics collection in the database.
Additionally, reference the metrics
in the info["metrics"] dictionary. | [
"Store",
"new",
"measurements",
"to",
"the",
"database",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/observers/mongo.py#L220-L244 |
224,498 | IDSIA/sacred | sacred/dependencies.py | get_digest | def get_digest(filename):
"""Compute the MD5 hash for a given file."""
h = hashlib.md5()
with open(filename, 'rb') as f:
data = f.read(1 * MB)
while data:
h.update(data)
data = f.read(1 * MB)
return h.hexdigest() | python | def get_digest(filename):
"""Compute the MD5 hash for a given file."""
h = hashlib.md5()
with open(filename, 'rb') as f:
data = f.read(1 * MB)
while data:
h.update(data)
data = f.read(1 * MB)
return h.hexdigest() | [
"def",
"get_digest",
"(",
"filename",
")",
":",
"h",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
"1",
"*",
"MB",
")",
"while",
"data",
":",
"h",
... | Compute the MD5 hash for a given file. | [
"Compute",
"the",
"MD5",
"hash",
"for",
"a",
"given",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L102-L110 |
224,499 | IDSIA/sacred | sacred/dependencies.py | get_commit_if_possible | def get_commit_if_possible(filename):
"""Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
The commit hash
is_dirty: bool
True if there are uncommitted changes in the repository
"""
# git
if opt.has_gitpython:
from git import Repo, InvalidGitRepositoryError
try:
directory = os.path.dirname(filename)
repo = Repo(directory, search_parent_directories=True)
try:
path = repo.remote().url
except ValueError:
path = 'git:/' + repo.working_dir
is_dirty = repo.is_dirty()
commit = repo.head.commit.hexsha
return path, commit, is_dirty
except (InvalidGitRepositoryError, ValueError):
pass
return None, None, None | python | def get_commit_if_possible(filename):
"""Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
The commit hash
is_dirty: bool
True if there are uncommitted changes in the repository
"""
# git
if opt.has_gitpython:
from git import Repo, InvalidGitRepositoryError
try:
directory = os.path.dirname(filename)
repo = Repo(directory, search_parent_directories=True)
try:
path = repo.remote().url
except ValueError:
path = 'git:/' + repo.working_dir
is_dirty = repo.is_dirty()
commit = repo.head.commit.hexsha
return path, commit, is_dirty
except (InvalidGitRepositoryError, ValueError):
pass
return None, None, None | [
"def",
"get_commit_if_possible",
"(",
"filename",
")",
":",
"# git",
"if",
"opt",
".",
"has_gitpython",
":",
"from",
"git",
"import",
"Repo",
",",
"InvalidGitRepositoryError",
"try",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
... | Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
The commit hash
is_dirty: bool
True if there are uncommitted changes in the repository | [
"Try",
"to",
"retrieve",
"VCS",
"information",
"for",
"a",
"given",
"file",
"."
] | 72633776bed9b5bddf93ae7d215188e61970973a | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/dependencies.py#L113-L146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.