repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
anomaly/prestans | prestans/ext/appengine.py | AppEngineAuthContextProvider.get_current_user | def get_current_user(self):
"""
Override get_current_user for Google AppEngine
Checks for oauth capable request first, if this fails fall back to standard users API
"""
from google.appengine.api import users
if _IS_DEVELOPMENT_SERVER:
return users.get_current_user()
else:
from google.appengine.api import oauth
try:
user = oauth.get_current_user()
except oauth.OAuthRequestError:
user = users.get_current_user()
return user | python | def get_current_user(self):
"""
Override get_current_user for Google AppEngine
Checks for oauth capable request first, if this fails fall back to standard users API
"""
from google.appengine.api import users
if _IS_DEVELOPMENT_SERVER:
return users.get_current_user()
else:
from google.appengine.api import oauth
try:
user = oauth.get_current_user()
except oauth.OAuthRequestError:
user = users.get_current_user()
return user | [
"def",
"get_current_user",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
"import",
"users",
"if",
"_IS_DEVELOPMENT_SERVER",
":",
"return",
"users",
".",
"get_current_user",
"(",
")",
"else",
":",
"from",
"google",
".",
"appengine",
"... | Override get_current_user for Google AppEngine
Checks for oauth capable request first, if this fails fall back to standard users API | [
"Override",
"get_current_user",
"for",
"Google",
"AppEngine",
"Checks",
"for",
"oauth",
"capable",
"request",
"first",
"if",
"this",
"fails",
"fall",
"back",
"to",
"standard",
"users",
"API"
] | train | https://github.com/anomaly/prestans/blob/13f5b2467bfd403dcd2d085f15cbf4644044f105/prestans/ext/appengine.py#L60-L76 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.bam2es | def bam2es(
bam_fn,
es_fo,
allowed_delta,
):
"""Convert BAM file to ES file.
Args:
bam_fn (str): File name of the BAM file.
bam_fo (file): File object of the ES file.
allowed_delta (int): Maximal allowed coordinates difference for correct reads.
"""
es_fo.write("# RN: read name" + os.linesep)
es_fo.write("# Q: is mapped with quality" + os.linesep)
es_fo.write("# Chr: chr id" + os.linesep)
es_fo.write("# D: direction" + os.linesep)
es_fo.write("# L: leftmost nucleotide" + os.linesep)
es_fo.write("# R: rightmost nucleotide" + os.linesep)
es_fo.write("# Cat: category of alignment assigned by LAVEnder" + os.linesep)
es_fo.write("# M_i i-th segment is correctly mapped" + os.linesep)
es_fo.write("# m segment should be unmapped but it is mapped" + os.linesep)
es_fo.write("# w segment is mapped to a wrong location" + os.linesep)
es_fo.write("# U segment is unmapped and should be unmapped" + os.linesep)
es_fo.write("# u segment is unmapped and should be mapped" + os.linesep)
es_fo.write("# Segs: number of segments" + os.linesep)
es_fo.write("# " + os.linesep)
es_fo.write("# RN\tQ\tChr\tD\tL\tR\tCat\tSegs" + os.linesep)
with pysam.AlignmentFile(bam_fn, "rb") as sam:
references_dict = {}
for i in range(len(sam.references)):
references_dict[sam.references[i]] = i + 1
for read in sam:
rnf_read_tuple = rnftools.rnfformat.ReadTuple()
rnf_read_tuple.destringize(read.query_name)
left = read.reference_start + 1
right = read.reference_end
chrom_id = references_dict[sam.references[read.reference_id]]
nb_of_segments = len(rnf_read_tuple.segments)
if rnf_read_tuple.segments[0].genome_id == 1:
should_be_mapped = True
else:
should_be_mapped = False
# read is unmapped
if read.is_unmapped:
# read should be mapped
if should_be_mapped:
category = "u"
# read should be unmapped
else:
category = "U"
# read is mapped
else:
# read should be mapped
if should_be_mapped:
exists_corresponding_segment = False
for j in range(len(rnf_read_tuple.segments)):
segment = rnf_read_tuple.segments[j]
if (
(segment.left == 0 or abs(segment.left - left) <= allowed_delta)
and (segment.right == 0 or abs(segment.right - right) <= allowed_delta)
and (segment.left != 0 or segment.right == 0)
and (chrom_id == 0 or chrom_id == segment.chr_id)
):
exists_corresponding_segment = True
segment = str(j + 1)
break
# read was mapped to correct location
if exists_corresponding_segment: # exists ok location?
category = "M_" + segment
# read was mapped to incorrect location
else:
category = "w"
# read should be unmapped
else:
category = "m"
es_fo.write(
"\t".join(
map(
str,
[
# read name
read.query_name,
# aligned?
"unmapped" if read.is_unmapped else "mapped_" + str(read.mapping_quality),
# reference id
chrom_id,
# direction
"R" if read.is_reverse else "F",
# left
left,
# right
right,
# assigned category
category,
# count of segments
nb_of_segments
]
)
) + os.linesep
) | python | def bam2es(
bam_fn,
es_fo,
allowed_delta,
):
"""Convert BAM file to ES file.
Args:
bam_fn (str): File name of the BAM file.
bam_fo (file): File object of the ES file.
allowed_delta (int): Maximal allowed coordinates difference for correct reads.
"""
es_fo.write("# RN: read name" + os.linesep)
es_fo.write("# Q: is mapped with quality" + os.linesep)
es_fo.write("# Chr: chr id" + os.linesep)
es_fo.write("# D: direction" + os.linesep)
es_fo.write("# L: leftmost nucleotide" + os.linesep)
es_fo.write("# R: rightmost nucleotide" + os.linesep)
es_fo.write("# Cat: category of alignment assigned by LAVEnder" + os.linesep)
es_fo.write("# M_i i-th segment is correctly mapped" + os.linesep)
es_fo.write("# m segment should be unmapped but it is mapped" + os.linesep)
es_fo.write("# w segment is mapped to a wrong location" + os.linesep)
es_fo.write("# U segment is unmapped and should be unmapped" + os.linesep)
es_fo.write("# u segment is unmapped and should be mapped" + os.linesep)
es_fo.write("# Segs: number of segments" + os.linesep)
es_fo.write("# " + os.linesep)
es_fo.write("# RN\tQ\tChr\tD\tL\tR\tCat\tSegs" + os.linesep)
with pysam.AlignmentFile(bam_fn, "rb") as sam:
references_dict = {}
for i in range(len(sam.references)):
references_dict[sam.references[i]] = i + 1
for read in sam:
rnf_read_tuple = rnftools.rnfformat.ReadTuple()
rnf_read_tuple.destringize(read.query_name)
left = read.reference_start + 1
right = read.reference_end
chrom_id = references_dict[sam.references[read.reference_id]]
nb_of_segments = len(rnf_read_tuple.segments)
if rnf_read_tuple.segments[0].genome_id == 1:
should_be_mapped = True
else:
should_be_mapped = False
# read is unmapped
if read.is_unmapped:
# read should be mapped
if should_be_mapped:
category = "u"
# read should be unmapped
else:
category = "U"
# read is mapped
else:
# read should be mapped
if should_be_mapped:
exists_corresponding_segment = False
for j in range(len(rnf_read_tuple.segments)):
segment = rnf_read_tuple.segments[j]
if (
(segment.left == 0 or abs(segment.left - left) <= allowed_delta)
and (segment.right == 0 or abs(segment.right - right) <= allowed_delta)
and (segment.left != 0 or segment.right == 0)
and (chrom_id == 0 or chrom_id == segment.chr_id)
):
exists_corresponding_segment = True
segment = str(j + 1)
break
# read was mapped to correct location
if exists_corresponding_segment: # exists ok location?
category = "M_" + segment
# read was mapped to incorrect location
else:
category = "w"
# read should be unmapped
else:
category = "m"
es_fo.write(
"\t".join(
map(
str,
[
# read name
read.query_name,
# aligned?
"unmapped" if read.is_unmapped else "mapped_" + str(read.mapping_quality),
# reference id
chrom_id,
# direction
"R" if read.is_reverse else "F",
# left
left,
# right
right,
# assigned category
category,
# count of segments
nb_of_segments
]
)
) + os.linesep
) | [
"def",
"bam2es",
"(",
"bam_fn",
",",
"es_fo",
",",
"allowed_delta",
",",
")",
":",
"es_fo",
".",
"write",
"(",
"\"# RN: read name\"",
"+",
"os",
".",
"linesep",
")",
"es_fo",
".",
"write",
"(",
"\"# Q: is mapped with quality\"",
"+",
"os",
".",
"linesep... | Convert BAM file to ES file.
Args:
bam_fn (str): File name of the BAM file.
bam_fo (file): File object of the ES file.
allowed_delta (int): Maximal allowed coordinates difference for correct reads. | [
"Convert",
"BAM",
"file",
"to",
"ES",
"file",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L127-L237 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.create_es | def create_es(self):
"""Create an ES (intermediate) file for this BAM file.
This is the function which asses if an alignment is correct
"""
with (gzip.open(self._es_fn, "tw+") if self.compress_intermediate_files else open(self._es_fn, "w+")) as es_fo:
self.bam2es(
bam_fn=self._bam_fn,
es_fo=es_fo,
allowed_delta=self.report.allowed_delta,
) | python | def create_es(self):
"""Create an ES (intermediate) file for this BAM file.
This is the function which asses if an alignment is correct
"""
with (gzip.open(self._es_fn, "tw+") if self.compress_intermediate_files else open(self._es_fn, "w+")) as es_fo:
self.bam2es(
bam_fn=self._bam_fn,
es_fo=es_fo,
allowed_delta=self.report.allowed_delta,
) | [
"def",
"create_es",
"(",
"self",
")",
":",
"with",
"(",
"gzip",
".",
"open",
"(",
"self",
".",
"_es_fn",
",",
"\"tw+\"",
")",
"if",
"self",
".",
"compress_intermediate_files",
"else",
"open",
"(",
"self",
".",
"_es_fn",
",",
"\"w+\"",
")",
")",
"as",
... | Create an ES (intermediate) file for this BAM file.
This is the function which asses if an alignment is correct | [
"Create",
"an",
"ES",
"(",
"intermediate",
")",
"file",
"for",
"this",
"BAM",
"file",
".",
"This",
"is",
"the",
"function",
"which",
"asses",
"if",
"an",
"alignment",
"is",
"correct"
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L239-L249 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam._vector_of_categories | def _vector_of_categories(srs, read_tuple_name, parts):
"""Create vector of categories (voc[q] ... assigned category for given quality level)
srs ... single read statistics ... for every q ... dictionary
read_tuple_name ... read name
parts ... number of segments
"""
# default value
vec = ["x" for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)]
assert len(srs) <= rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1, srs
should_be_mapped = bool(srs[0]["m"] + srs[0]["U"] == 0)
for q in range(len(srs)):
#####
# M # - all parts correctly aligned
#####
if len(srs[q]["M"]
) == parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q]["u"] == 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "M"
#####
# w # - at least one segment is incorrectly aligned
#####
if srs[q]["w"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "w"
#####
# m # - at least one segment was aligned but should not be aligned
#####
if srs[q]["w"] == 0 and srs[q]["m"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "m"
#####
# U # - all segments should be unaligned but are unaligned
#####
if srs[q]["U"] > 0 and srs[q]["u"] == 0 and srs[q]["m"] == 0 and srs[q]["w"] == 0 and len(srs[q]["M"]) == 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "U"
#####
# u # - at least one segment was unaligned but should be aligned
#####
if srs[q]["w"] == 0 and srs[q]["u"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "u"
#####
# t # - at least one segment was thresholded
#####
if len(srs[q]["M"]) != parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q][
"u"] == 0 and srs[q]["t"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "t"
#####
# T # - at least one segment was thresholded
#####
if len(srs[q]["M"]) != parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q][
"u"] == 0 and srs[q]["T"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "T"
#####
# P # - multimapped, M + w + m > parts
#####
# only this one can rewrite some older assignment
if len(srs[q]["M"]) + srs[q]["w"] + srs[q]["m"] > parts and srs[q]["U"] == 0 and srs[q]["u"] == 0:
# assert vec[q]=="x",str((q,srs[q]))
vec[q] = "P"
return vec | python | def _vector_of_categories(srs, read_tuple_name, parts):
"""Create vector of categories (voc[q] ... assigned category for given quality level)
srs ... single read statistics ... for every q ... dictionary
read_tuple_name ... read name
parts ... number of segments
"""
# default value
vec = ["x" for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)]
assert len(srs) <= rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1, srs
should_be_mapped = bool(srs[0]["m"] + srs[0]["U"] == 0)
for q in range(len(srs)):
#####
# M # - all parts correctly aligned
#####
if len(srs[q]["M"]
) == parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q]["u"] == 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "M"
#####
# w # - at least one segment is incorrectly aligned
#####
if srs[q]["w"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "w"
#####
# m # - at least one segment was aligned but should not be aligned
#####
if srs[q]["w"] == 0 and srs[q]["m"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "m"
#####
# U # - all segments should be unaligned but are unaligned
#####
if srs[q]["U"] > 0 and srs[q]["u"] == 0 and srs[q]["m"] == 0 and srs[q]["w"] == 0 and len(srs[q]["M"]) == 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "U"
#####
# u # - at least one segment was unaligned but should be aligned
#####
if srs[q]["w"] == 0 and srs[q]["u"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "u"
#####
# t # - at least one segment was thresholded
#####
if len(srs[q]["M"]) != parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q][
"u"] == 0 and srs[q]["t"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "t"
#####
# T # - at least one segment was thresholded
#####
if len(srs[q]["M"]) != parts and srs[q]["w"] == 0 and srs[q]["m"] == 0 and srs[q]["U"] == 0 and srs[q][
"u"] == 0 and srs[q]["T"] > 0:
assert vec[q] == "x", str((q, srs[q]))
vec[q] = "T"
#####
# P # - multimapped, M + w + m > parts
#####
# only this one can rewrite some older assignment
if len(srs[q]["M"]) + srs[q]["w"] + srs[q]["m"] > parts and srs[q]["U"] == 0 and srs[q]["u"] == 0:
# assert vec[q]=="x",str((q,srs[q]))
vec[q] = "P"
return vec | [
"def",
"_vector_of_categories",
"(",
"srs",
",",
"read_tuple_name",
",",
"parts",
")",
":",
"# default value",
"vec",
"=",
"[",
"\"x\"",
"for",
"i",
"in",
"range",
"(",
"rnftools",
".",
"lavender",
".",
"MAXIMAL_MAPPING_QUALITY",
"+",
"1",
")",
"]",
"assert"... | Create vector of categories (voc[q] ... assigned category for given quality level)
srs ... single read statistics ... for every q ... dictionary
read_tuple_name ... read name
parts ... number of segments | [
"Create",
"vector",
"of",
"categories",
"(",
"voc",
"[",
"q",
"]",
"...",
"assigned",
"category",
"for",
"given",
"quality",
"level",
")"
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L260-L337 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.es2et | def es2et(
es_fo,
et_fo,
):
"""Convert ES to ET.
Args:
es_fo (file): File object for the ES file.
et_fo (file): File object for the ET file.
"""
et_fo.write("# Mapping information for read tuples" + os.linesep)
et_fo.write("#" + os.linesep)
et_fo.write("# RN: read name" + os.linesep)
et_fo.write("# I: intervals with asigned categories" + os.linesep)
et_fo.write("#" + os.linesep)
et_fo.write("# RN I" + os.linesep)
last_rname = ""
for line in es_fo:
line = line.strip()
if line == "" or line[0] == "#":
continue
else:
(rname, mapped, ref, direction, left, right, category, nb_of_segments) = line.split("\t")
nb_of_segments = int(nb_of_segments)
# print(rname,last_rname,mapped)
# new read
if rname != last_rname:
# update
if last_rname != "":
voc = Bam._vector_of_categories(single_reads_statistics, rname, nb_of_segments)
et_fo.write(Bam._et_line(readname=rname, vector_of_categories=voc))
et_fo.write(os.linesep)
# nulling
single_reads_statistics = [
{
"U": 0,
"u": 0,
"M": [],
"m": 0,
"w": 0,
"T": 0,
"t": 0,
} for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)
]
last_rname = rname
####################
# Unmapped segment #
####################
#####
# U #
#####
if category == "U":
for q in range(len(single_reads_statistics)):
single_reads_statistics[q]["U"] += 1
#####
# u #
#####
elif category == "u":
for q in range(len(single_reads_statistics)):
single_reads_statistics[q]["u"] += 1
##################
# Mapped segment #
##################
else:
mapping_quality = int(mapped.replace("mapped_", ""))
assert 0 <= mapping_quality and mapping_quality <= rnftools.lavender.MAXIMAL_MAPPING_QUALITY, mapping_quality
#####
# m #
#####
if category == "m":
for q in range(mapping_quality + 1):
single_reads_statistics[q]["m"] += 1
for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
single_reads_statistics[q]["T"] += 1
#####
# w #
#####
elif category == "w":
for q in range(mapping_quality + 1):
single_reads_statistics[q]["w"] += 1
for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
single_reads_statistics[q]["t"] += 1
#####
# M #
#####
else:
assert category[0] == "M", category
segment_id = int(category.replace("M_", ""))
for q in range(mapping_quality + 1):
single_reads_statistics[q]["M"].append(segment_id)
for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
single_reads_statistics[q]["t"] += 1
# last read
voc = Bam._vector_of_categories(single_reads_statistics, rname, nb_of_segments)
et_fo.write(Bam._et_line(readname=rname, vector_of_categories=voc))
et_fo.write(os.linesep) | python | def es2et(
es_fo,
et_fo,
):
"""Convert ES to ET.
Args:
es_fo (file): File object for the ES file.
et_fo (file): File object for the ET file.
"""
et_fo.write("# Mapping information for read tuples" + os.linesep)
et_fo.write("#" + os.linesep)
et_fo.write("# RN: read name" + os.linesep)
et_fo.write("# I: intervals with asigned categories" + os.linesep)
et_fo.write("#" + os.linesep)
et_fo.write("# RN I" + os.linesep)
last_rname = ""
for line in es_fo:
line = line.strip()
if line == "" or line[0] == "#":
continue
else:
(rname, mapped, ref, direction, left, right, category, nb_of_segments) = line.split("\t")
nb_of_segments = int(nb_of_segments)
# print(rname,last_rname,mapped)
# new read
if rname != last_rname:
# update
if last_rname != "":
voc = Bam._vector_of_categories(single_reads_statistics, rname, nb_of_segments)
et_fo.write(Bam._et_line(readname=rname, vector_of_categories=voc))
et_fo.write(os.linesep)
# nulling
single_reads_statistics = [
{
"U": 0,
"u": 0,
"M": [],
"m": 0,
"w": 0,
"T": 0,
"t": 0,
} for i in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)
]
last_rname = rname
####################
# Unmapped segment #
####################
#####
# U #
#####
if category == "U":
for q in range(len(single_reads_statistics)):
single_reads_statistics[q]["U"] += 1
#####
# u #
#####
elif category == "u":
for q in range(len(single_reads_statistics)):
single_reads_statistics[q]["u"] += 1
##################
# Mapped segment #
##################
else:
mapping_quality = int(mapped.replace("mapped_", ""))
assert 0 <= mapping_quality and mapping_quality <= rnftools.lavender.MAXIMAL_MAPPING_QUALITY, mapping_quality
#####
# m #
#####
if category == "m":
for q in range(mapping_quality + 1):
single_reads_statistics[q]["m"] += 1
for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
single_reads_statistics[q]["T"] += 1
#####
# w #
#####
elif category == "w":
for q in range(mapping_quality + 1):
single_reads_statistics[q]["w"] += 1
for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
single_reads_statistics[q]["t"] += 1
#####
# M #
#####
else:
assert category[0] == "M", category
segment_id = int(category.replace("M_", ""))
for q in range(mapping_quality + 1):
single_reads_statistics[q]["M"].append(segment_id)
for q in range(mapping_quality + 1, rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1):
single_reads_statistics[q]["t"] += 1
# last read
voc = Bam._vector_of_categories(single_reads_statistics, rname, nb_of_segments)
et_fo.write(Bam._et_line(readname=rname, vector_of_categories=voc))
et_fo.write(os.linesep) | [
"def",
"es2et",
"(",
"es_fo",
",",
"et_fo",
",",
")",
":",
"et_fo",
".",
"write",
"(",
"\"# Mapping information for read tuples\"",
"+",
"os",
".",
"linesep",
")",
"et_fo",
".",
"write",
"(",
"\"#\"",
"+",
"os",
".",
"linesep",
")",
"et_fo",
".",
"write"... | Convert ES to ET.
Args:
es_fo (file): File object for the ES file.
et_fo (file): File object for the ET file. | [
"Convert",
"ES",
"to",
"ET",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L352-L460 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.create_et | def create_et(self):
"""Create a et file for this BAM file (mapping information about read tuples).
raises: ValueError
"""
with (gzip.open(self._es_fn, "tr") if self.compress_intermediate_files else open(self._es_fn, "r")) as es_fo:
with (gzip.open(self._et_fn, "tw+")
if self.compress_intermediate_files else open(self._et_fn, "w+")) as et_fo:
self.es2et(
es_fo=es_fo,
et_fo=et_fo,
) | python | def create_et(self):
"""Create a et file for this BAM file (mapping information about read tuples).
raises: ValueError
"""
with (gzip.open(self._es_fn, "tr") if self.compress_intermediate_files else open(self._es_fn, "r")) as es_fo:
with (gzip.open(self._et_fn, "tw+")
if self.compress_intermediate_files else open(self._et_fn, "w+")) as et_fo:
self.es2et(
es_fo=es_fo,
et_fo=et_fo,
) | [
"def",
"create_et",
"(",
"self",
")",
":",
"with",
"(",
"gzip",
".",
"open",
"(",
"self",
".",
"_es_fn",
",",
"\"tr\"",
")",
"if",
"self",
".",
"compress_intermediate_files",
"else",
"open",
"(",
"self",
".",
"_es_fn",
",",
"\"r\"",
")",
")",
"as",
"... | Create a et file for this BAM file (mapping information about read tuples).
raises: ValueError | [
"Create",
"a",
"et",
"file",
"for",
"this",
"BAM",
"file",
"(",
"mapping",
"information",
"about",
"read",
"tuples",
")",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L462-L475 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.et2roc | def et2roc(et_fo, roc_fo):
"""ET to ROC conversion.
Args:
et_fo (file): File object for the ET file.
roc_fo (file): File object for the ROC file.
raises: ValueError
"""
stats_dicts = [
{
"q": q,
"M": 0,
"w": 0,
"m": 0,
"P": 0,
"U": 0,
"u": 0,
"T": 0,
"t": 0,
"x": 0
} for q in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)
]
for line in et_fo:
line = line.strip()
if line != "" and line[0] != "#":
(read_tuple_name, tab, info_categories) = line.partition("\t")
intervals = info_categories.split(",")
for interval in intervals:
category = interval[0]
(left, colon, right) = interval[2:].partition("-")
for q in range(int(left), int(right) + 1):
stats_dicts[q][category] += 1
roc_fo.write("# Numbers of reads in several categories in dependence" + os.linesep)
roc_fo.write("# on the applied threshold on mapping quality q" + os.linesep)
roc_fo.write("# " + os.linesep)
roc_fo.write("# Categories:" + os.linesep)
roc_fo.write("# M: Mapped correctly." + os.linesep)
roc_fo.write("# w: Mapped to a wrong position." + os.linesep)
roc_fo.write("# m: Mapped but should be unmapped." + os.linesep)
roc_fo.write("# P: Multimapped." + os.linesep)
roc_fo.write("# U: Unmapped and should be unmapped." + os.linesep)
roc_fo.write("# u: Unmapped but should be mapped." + os.linesep)
roc_fo.write("# T: Thresholded correctly." + os.linesep)
roc_fo.write("# t: Thresholded incorrectly." + os.linesep)
roc_fo.write("# x: Unknown." + os.linesep)
roc_fo.write("#" + os.linesep)
roc_fo.write("# q\tM\tw\tm\tP\tU\tu\tT\tt\tx\tall" + os.linesep)
l_numbers = []
for line in stats_dicts:
numbers = [
line["M"], line["w"], line["m"], line["P"], line["U"], line["u"], line["T"], line["t"], line["x"]
]
if numbers != l_numbers:
roc_fo.write("\t".join([str(line["q"])] + list(map(str, numbers)) + [str(sum(numbers))]) + os.linesep)
l_numbers = numbers | python | def et2roc(et_fo, roc_fo):
"""ET to ROC conversion.
Args:
et_fo (file): File object for the ET file.
roc_fo (file): File object for the ROC file.
raises: ValueError
"""
stats_dicts = [
{
"q": q,
"M": 0,
"w": 0,
"m": 0,
"P": 0,
"U": 0,
"u": 0,
"T": 0,
"t": 0,
"x": 0
} for q in range(rnftools.lavender.MAXIMAL_MAPPING_QUALITY + 1)
]
for line in et_fo:
line = line.strip()
if line != "" and line[0] != "#":
(read_tuple_name, tab, info_categories) = line.partition("\t")
intervals = info_categories.split(",")
for interval in intervals:
category = interval[0]
(left, colon, right) = interval[2:].partition("-")
for q in range(int(left), int(right) + 1):
stats_dicts[q][category] += 1
roc_fo.write("# Numbers of reads in several categories in dependence" + os.linesep)
roc_fo.write("# on the applied threshold on mapping quality q" + os.linesep)
roc_fo.write("# " + os.linesep)
roc_fo.write("# Categories:" + os.linesep)
roc_fo.write("# M: Mapped correctly." + os.linesep)
roc_fo.write("# w: Mapped to a wrong position." + os.linesep)
roc_fo.write("# m: Mapped but should be unmapped." + os.linesep)
roc_fo.write("# P: Multimapped." + os.linesep)
roc_fo.write("# U: Unmapped and should be unmapped." + os.linesep)
roc_fo.write("# u: Unmapped but should be mapped." + os.linesep)
roc_fo.write("# T: Thresholded correctly." + os.linesep)
roc_fo.write("# t: Thresholded incorrectly." + os.linesep)
roc_fo.write("# x: Unknown." + os.linesep)
roc_fo.write("#" + os.linesep)
roc_fo.write("# q\tM\tw\tm\tP\tU\tu\tT\tt\tx\tall" + os.linesep)
l_numbers = []
for line in stats_dicts:
numbers = [
line["M"], line["w"], line["m"], line["P"], line["U"], line["u"], line["T"], line["t"], line["x"]
]
if numbers != l_numbers:
roc_fo.write("\t".join([str(line["q"])] + list(map(str, numbers)) + [str(sum(numbers))]) + os.linesep)
l_numbers = numbers | [
"def",
"et2roc",
"(",
"et_fo",
",",
"roc_fo",
")",
":",
"stats_dicts",
"=",
"[",
"{",
"\"q\"",
":",
"q",
",",
"\"M\"",
":",
"0",
",",
"\"w\"",
":",
"0",
",",
"\"m\"",
":",
"0",
",",
"\"P\"",
":",
"0",
",",
"\"U\"",
":",
"0",
",",
"\"u\"",
":"... | ET to ROC conversion.
Args:
et_fo (file): File object for the ET file.
roc_fo (file): File object for the ROC file.
raises: ValueError | [
"ET",
"to",
"ROC",
"conversion",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L486-L546 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.create_roc | def create_roc(self):
"""Create a ROC file for this BAM file.
raises: ValueError
"""
with (gzip.open(self._et_fn, "tr") if self.compress_intermediate_files else open(self._et_fn, "r")) as et_fo:
with open(self._roc_fn, "w+") as roc_fo:
self.et2roc(
et_fo=et_fo,
roc_fo=roc_fo,
) | python | def create_roc(self):
"""Create a ROC file for this BAM file.
raises: ValueError
"""
with (gzip.open(self._et_fn, "tr") if self.compress_intermediate_files else open(self._et_fn, "r")) as et_fo:
with open(self._roc_fn, "w+") as roc_fo:
self.et2roc(
et_fo=et_fo,
roc_fo=roc_fo,
) | [
"def",
"create_roc",
"(",
"self",
")",
":",
"with",
"(",
"gzip",
".",
"open",
"(",
"self",
".",
"_et_fn",
",",
"\"tr\"",
")",
"if",
"self",
".",
"compress_intermediate_files",
"else",
"open",
"(",
"self",
".",
"_et_fn",
",",
"\"r\"",
")",
")",
"as",
... | Create a ROC file for this BAM file.
raises: ValueError | [
"Create",
"a",
"ROC",
"file",
"for",
"this",
"BAM",
"file",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L548-L559 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.create_gp | def create_gp(self):
"""Create a GnuPlot file for this BAM file."""
categories_order = [
("{U}", "#ee82ee", 'Unmapped correctly'),
("{u}", "#ff0000", 'Unmapped incorrectly'),
("{T}", "#00ff00", 'Thresholded correctly'),
("{t}", "#008800", 'Thresholded incorrectly'),
("{P}", "#ffff00", 'Multimapped'),
("{w}+{x}", "#7f7f7f", 'Mapped, should be unmapped'),
("{m}", "#000000", 'Mapped to wrong position'),
("{M}", "#0000ff", 'Mapped correctly'),
]
plot_lines = [
'"{roc_fn}" using (( ({x}) )):({y}) lt rgb "{color}" with filledcurve x1 title "{title}", \\'.format(
roc_fn=self._roc_fn,
x=rnftools.lavender._format_xxx(self.default_x_axis),
y=rnftools.lavender._format_xxx(
'({sum})*100/{{all}}'.format(sum="+".join([c[0] for c in categories_order[i:]]))
),
color=categories_order[i][1],
title=categories_order[i][2],
) for i in range(len(categories_order))
]
plot = os.linesep.join((["plot \\"] + plot_lines + [""]))
with open(self._gp_fn, "w+") as gp:
gp_content = """
set title "{{/:Bold=16 {title}}}"
set x2lab "{x_lab}"
set log x
set log x2
set format x "10^{{%L}}"
set format x2 "10^{{%L}}"
set xran [{xran}]
set x2ran [{xran}]
set x2tics
unset xtics
set ylab "Part of all reads (%)"
set format y "%g %%"
set yran [{yran}]
set y2ran [{yran}]
set pointsize 1.5
set grid ytics lc rgb "#777777" lw 1 lt 0 front
set grid x2tics lc rgb "#777777" lw 1 lt 0 front
set datafile separator "\\t"
set palette negative
set termin svg size {svg_size} enhanced
set out "{svg_fn}"
set key spacing 0.8 opaque width -5
""".format(
svg_fn=self._svg_fn,
xran="{:.10f}:{:.10f}".format(self.report.default_x_run[0], self.report.default_x_run[1]),
yran="{:.10f}:{:.10f}".format(self.report.default_y_run[0], self.report.default_y_run[1]),
svg_size="{},{}".format(self.report.default_svg_size_px[0], self.report.default_svg_size_px[1]),
title=os.path.basename(self._bam_fn)[:-4],
x_lab=self.default_x_label,
)
gp_content = textwrap.dedent(gp_content) + "\n" + plot
# gp_lines=gp_content.split("\n")
# gp_lines=[x.strip() for x in gp_lines]
# gp_content=gp_lines.join("\n")
gp.write(gp_content) | python | def create_gp(self):
"""Create a GnuPlot file for this BAM file."""
categories_order = [
("{U}", "#ee82ee", 'Unmapped correctly'),
("{u}", "#ff0000", 'Unmapped incorrectly'),
("{T}", "#00ff00", 'Thresholded correctly'),
("{t}", "#008800", 'Thresholded incorrectly'),
("{P}", "#ffff00", 'Multimapped'),
("{w}+{x}", "#7f7f7f", 'Mapped, should be unmapped'),
("{m}", "#000000", 'Mapped to wrong position'),
("{M}", "#0000ff", 'Mapped correctly'),
]
plot_lines = [
'"{roc_fn}" using (( ({x}) )):({y}) lt rgb "{color}" with filledcurve x1 title "{title}", \\'.format(
roc_fn=self._roc_fn,
x=rnftools.lavender._format_xxx(self.default_x_axis),
y=rnftools.lavender._format_xxx(
'({sum})*100/{{all}}'.format(sum="+".join([c[0] for c in categories_order[i:]]))
),
color=categories_order[i][1],
title=categories_order[i][2],
) for i in range(len(categories_order))
]
plot = os.linesep.join((["plot \\"] + plot_lines + [""]))
with open(self._gp_fn, "w+") as gp:
gp_content = """
set title "{{/:Bold=16 {title}}}"
set x2lab "{x_lab}"
set log x
set log x2
set format x "10^{{%L}}"
set format x2 "10^{{%L}}"
set xran [{xran}]
set x2ran [{xran}]
set x2tics
unset xtics
set ylab "Part of all reads (%)"
set format y "%g %%"
set yran [{yran}]
set y2ran [{yran}]
set pointsize 1.5
set grid ytics lc rgb "#777777" lw 1 lt 0 front
set grid x2tics lc rgb "#777777" lw 1 lt 0 front
set datafile separator "\\t"
set palette negative
set termin svg size {svg_size} enhanced
set out "{svg_fn}"
set key spacing 0.8 opaque width -5
""".format(
svg_fn=self._svg_fn,
xran="{:.10f}:{:.10f}".format(self.report.default_x_run[0], self.report.default_x_run[1]),
yran="{:.10f}:{:.10f}".format(self.report.default_y_run[0], self.report.default_y_run[1]),
svg_size="{},{}".format(self.report.default_svg_size_px[0], self.report.default_svg_size_px[1]),
title=os.path.basename(self._bam_fn)[:-4],
x_lab=self.default_x_label,
)
gp_content = textwrap.dedent(gp_content) + "\n" + plot
# gp_lines=gp_content.split("\n")
# gp_lines=[x.strip() for x in gp_lines]
# gp_content=gp_lines.join("\n")
gp.write(gp_content) | [
"def",
"create_gp",
"(",
"self",
")",
":",
"categories_order",
"=",
"[",
"(",
"\"{U}\"",
",",
"\"#ee82ee\"",
",",
"'Unmapped correctly'",
")",
",",
"(",
"\"{u}\"",
",",
"\"#ff0000\"",
",",
"'Unmapped incorrectly'",
")",
",",
"(",
"\"{T}\"",
",",
"\"#00ff00\"",... | Create a GnuPlot file for this BAM file. | [
"Create",
"a",
"GnuPlot",
"file",
"for",
"this",
"BAM",
"file",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L569-L641 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.create_graphics | def create_graphics(self):
"""Create images related to this BAM file using GnuPlot."""
rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn))
if self.render_pdf_method is not None:
svg_fn = self._svg_fn
pdf_fn = self._pdf_fn
svg42pdf(svg_fn, pdf_fn, method=self.render_pdf_method) | python | def create_graphics(self):
"""Create images related to this BAM file using GnuPlot."""
rnftools.utils.shell('"{}" "{}"'.format("gnuplot", self._gp_fn))
if self.render_pdf_method is not None:
svg_fn = self._svg_fn
pdf_fn = self._pdf_fn
svg42pdf(svg_fn, pdf_fn, method=self.render_pdf_method) | [
"def",
"create_graphics",
"(",
"self",
")",
":",
"rnftools",
".",
"utils",
".",
"shell",
"(",
"'\"{}\" \"{}\"'",
".",
"format",
"(",
"\"gnuplot\"",
",",
"self",
".",
"_gp_fn",
")",
")",
"if",
"self",
".",
"render_pdf_method",
"is",
"not",
"None",
":",
"s... | Create images related to this BAM file using GnuPlot. | [
"Create",
"images",
"related",
"to",
"this",
"BAM",
"file",
"using",
"GnuPlot",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L643-L651 |
karel-brinda/rnftools | rnftools/lavender/Bam.py | Bam.create_html | def create_html(self):
"""Create a HTML page for this BAM file."""
roc_dicts = []
with open(self._roc_fn, "r") as roc:
for line in roc:
line = line.strip()
if line != "" and line[0] != "#":
(q, M, w, m, P, U, u, T, t, x, a) = map(int, line.split("\t"))
roc_dict = {
"q": q,
"M": M,
"w": w,
"m": m,
"P": P,
"U": U,
"u": u,
"T": T,
"t": t,
"x": x,
"a": a,
"mapped": M + w + m + P,
"unmapped": U + u + T + t + x,
}
roc_dicts.append(roc_dict)
tbody = os.linesep.join(
[
"""
<tr>
<td> {quality} </td>
<td> {mapped} </td>
<td><small> {mapped_proc:.2f} </small></td>
<td> {M} </td>
<td><small> {M_proc:.2f} </small></td>
<td> {w} </td>
<td><small> {w_proc:.2f} </small></td>
<td> {m} </td>
<td><small> {m_proc:.2f} </small></td>
<td> {P} </td>
<td><small> {P_proc:.2f} </small></td>
<td> {unmapped} </td>
<td><small> {unmapped_proc:.2f} </small></td>
<td> {U} </td>
<td><small> {U_proc:.2f} </small></td>
<td> {u} </td>
<td><small> {u_proc:.2f} </small></td>
<td> {T} </td>
<td><small> {T_proc:.2f} </small></td>
<td> {t} </td>
<td><small> {t_proc:.2f} </small></td>
<td> {x} </td>
<td><small> {x_proc:.2f} </small></td>
<td> {sum} </td>
<td> {prec_proc:.3f} </td>
</tr>
""".format(
quality=roc_dict["q"],
mapped=roc_dict["mapped"],
mapped_proc=100.0 * (roc_dict["mapped"]) / roc_dict["a"],
M=roc_dict["M"],
M_proc=100.0 * (roc_dict["M"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
w=roc_dict["w"],
w_proc=100.0 * (roc_dict["w"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
m=roc_dict["m"],
m_proc=100.0 * (roc_dict["m"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
P=roc_dict["P"],
P_proc=100.0 * (roc_dict["P"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
unmapped=roc_dict["unmapped"],
unmapped_proc=100.0 * (roc_dict["unmapped"]) / roc_dict["a"],
U=roc_dict["U"],
U_proc=100.0 * (roc_dict["U"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
u=roc_dict["u"],
u_proc=100.0 * (roc_dict["u"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
T=roc_dict["T"],
T_proc=100.0 * (roc_dict["T"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
t=roc_dict["t"],
t_proc=100.0 * (roc_dict["t"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
x=roc_dict["x"],
x_proc=100.0 * (roc_dict["x"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
sum=roc_dict["a"],
prec_proc=100.0 * (roc_dict["M"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
) for roc_dict in roc_dicts
]
)
with open(self._html_fn, "w+") as html:
program_info = ["No information available (PG header is essing)."]
for x in rnftools.utils.shell(
'"{samtools}" view -H "{bam}"'.format(
samtools="samtools",
bam=self._bam_fn,
), iterable=True
):
x = x.strip()
if x[:3] == "@PG":
pg_header = x[4:].strip()
parts = pg_header.split("\t")
program_info = ["<table>"]
for part in parts:
(lvalue, _, rvalue) = part.partition(":")
program_info.append(
'<tr><td style="font-weight:bold">{}:</td><td style="text-align:left">{}</td></tr>'.format(
lvalue, rvalue
)
)
program_info.append("</table>")
eval_info = ["<table>"]
for (lvalue, rvalue) in [
("BAM file", self._bam_fn),
("Allowed delta", self.report.allowed_delta),
]:
eval_info.append(
'<tr><td style="font-weight:bold">{}:</td><td style="text-align:left">{}</td></tr>'.format(
lvalue, rvalue
)
)
eval_info.append("</table>")
css_src = textwrap.dedent(
"""
table {border-collapse:collapse;}
td {border: solid #aaaaff 1px;padding:4px;text-align:right;}
colgroup, thead {border: solid black 2px;padding 2px;}
.link_to_top {font-size:10pt;}
.desc {color:#aaa;}
.formats {text-align:left;margin-bottom:20px;}
"""
)
html_src = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{name}</title>
<style type="text/css">
{css}
</style>
</head>
<body>
<h1 id="top">
{name}
<span class="link_to_top">
[<a href="{homepage}">Back to main report</a>]
</span>
</h1>
<p>
<a href="#info_eval">Information about evaluation</a> -
<a href="#info_prog">Information about program</a> -
<a href="#roctable">ROC table</a> -
<a href="#graphs">Graphs</a>
</p>
<h2 id="info_eval">
Information about evaluation
{headline_links}
</h2>
{eval_info}
<h2 id="info_prog">
Information about program
{headline_links}
</h2>
{program_info}
<h2 id="roctable">
ROC table
{headline_links}
</h2>
<p style="font-size:80%">
<strong>M</strong>:
mapped correctly
<span class="desc">
(all segments of tuple are mapped once and correctly),
</span>
<strong>w</strong>:
mapped to wrong position
<span class="desc">
(at least one segment was mapped to a wrong position),
</span>
<strong>m</strong>:
mapped but should be unmapped
<span class="desc">
(at least one segment was mapped but the read should not be mapped),
</span>
<strong>P</strong>:
multimapped
<span class="desc">
(read should be mapped but it at least one segment was mapped several
times and all segments were mapped correctly at least once),
</span>
<strong>U</strong>:
unmapped correctly
<span class="desc">
(all segments of the read were correctly marked as unmapped),
</span>
<strong>u</strong>:
unmapped but should be mapped
<span class="desc">
(at least one segment was mapped but entire read should be unmapped),
</span>
<strong>T</strong>:
thresholded correctly
<span class="desc">
(read shoud not be mapped),
</span>
<strong>t</strong>:
thresholded incorrectly
<span class="desc">
(read should be mapped),
</span>
<strong>x</strong>:
unknown
<span class="desc">
(read is probably not reported by mapper)
</span>
</p>
<table>
<colgroup span="1" style="">
<colgroup span="2" style="background-color:#ddd">
<colgroup span="8" style="">
<colgroup span="2" style="background-color:#ddd">
<colgroup span="10" style="">
<colgroup span="1" style="background-color:#ddd">
<colgroup span="1" style="">
<thead style="font-weight:bold;background-color:#ddddff">
<tr style="font-weight:bold;background-color:#ddddff">
<td>q</td>
<td>mapped</td>
<td>%</td>
<td>M</td>
<td>%</td>
<td>w</td>
<td>%</td>
<td>m</td>
<td>%</td>
<td>P</td>
<td>%</td>
<td>unmapped</td>
<td>%</td>
<td>U</td>
<td>%</td>
<td>u</td>
<td>%</td>
<td>T</td>
<td>%</td>
<td>t</td>
<td>%</td>
<td>x</td>
<td>%</td>
<td>sum</td>
<td>prec. (%)</td>
</tr>
</thead>
<tbody>
{tbody}
</tbody>
</table>
<h2 id="graphs">
Graphs
{headline_links}
</h2>
<div class="formats">
<img src="{svg}" />
<br />
<a href="{svg}">SVG version</a>
|
<a href="{roc}" type="text/csv">ROC file</a>
|
<a href="{gp}" type="text/plain">GP file</a>
</div>
</body>
</html>
""".format(
name=self.name, tbody=tbody, css=css_src,
svg=os.path.relpath(self._svg_fn, os.path.dirname(self._html_fn)),
roc=os.path.relpath(self._roc_fn, os.path.dirname(self._html_fn)),
gp=os.path.relpath(self._gp_fn, os.path.dirname(self._html_fn)), eval_info=os.linesep.join(eval_info),
program_info=os.linesep.join(program_info),
homepage=os.path.relpath(self.report.html_fn(), os.path.dirname(self._html_fn)), headline_links='''
<span class="link_to_top">
[<a href="#top">Top of this page</a>]
[<a href="{homepage}">Back to main report</a>]
</span>
'''.format(homepage=os.path.relpath(self.report.html_fn(), os.path.dirname(self._html_fn)), )
)
tidy_html_src = bs4.BeautifulSoup(html_src).prettify()
html.write(tidy_html_src) | python | def create_html(self):
"""Create a HTML page for this BAM file."""
roc_dicts = []
with open(self._roc_fn, "r") as roc:
for line in roc:
line = line.strip()
if line != "" and line[0] != "#":
(q, M, w, m, P, U, u, T, t, x, a) = map(int, line.split("\t"))
roc_dict = {
"q": q,
"M": M,
"w": w,
"m": m,
"P": P,
"U": U,
"u": u,
"T": T,
"t": t,
"x": x,
"a": a,
"mapped": M + w + m + P,
"unmapped": U + u + T + t + x,
}
roc_dicts.append(roc_dict)
tbody = os.linesep.join(
[
"""
<tr>
<td> {quality} </td>
<td> {mapped} </td>
<td><small> {mapped_proc:.2f} </small></td>
<td> {M} </td>
<td><small> {M_proc:.2f} </small></td>
<td> {w} </td>
<td><small> {w_proc:.2f} </small></td>
<td> {m} </td>
<td><small> {m_proc:.2f} </small></td>
<td> {P} </td>
<td><small> {P_proc:.2f} </small></td>
<td> {unmapped} </td>
<td><small> {unmapped_proc:.2f} </small></td>
<td> {U} </td>
<td><small> {U_proc:.2f} </small></td>
<td> {u} </td>
<td><small> {u_proc:.2f} </small></td>
<td> {T} </td>
<td><small> {T_proc:.2f} </small></td>
<td> {t} </td>
<td><small> {t_proc:.2f} </small></td>
<td> {x} </td>
<td><small> {x_proc:.2f} </small></td>
<td> {sum} </td>
<td> {prec_proc:.3f} </td>
</tr>
""".format(
quality=roc_dict["q"],
mapped=roc_dict["mapped"],
mapped_proc=100.0 * (roc_dict["mapped"]) / roc_dict["a"],
M=roc_dict["M"],
M_proc=100.0 * (roc_dict["M"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
w=roc_dict["w"],
w_proc=100.0 * (roc_dict["w"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
m=roc_dict["m"],
m_proc=100.0 * (roc_dict["m"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
P=roc_dict["P"],
P_proc=100.0 * (roc_dict["P"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
unmapped=roc_dict["unmapped"],
unmapped_proc=100.0 * (roc_dict["unmapped"]) / roc_dict["a"],
U=roc_dict["U"],
U_proc=100.0 * (roc_dict["U"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
u=roc_dict["u"],
u_proc=100.0 * (roc_dict["u"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
T=roc_dict["T"],
T_proc=100.0 * (roc_dict["T"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
t=roc_dict["t"],
t_proc=100.0 * (roc_dict["t"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
x=roc_dict["x"],
x_proc=100.0 * (roc_dict["x"]) / (roc_dict["unmapped"]) if (roc_dict["unmapped"]) != 0 else 0,
sum=roc_dict["a"],
prec_proc=100.0 * (roc_dict["M"]) / (roc_dict["mapped"]) if (roc_dict["mapped"]) != 0 else 0,
) for roc_dict in roc_dicts
]
)
with open(self._html_fn, "w+") as html:
program_info = ["No information available (PG header is essing)."]
for x in rnftools.utils.shell(
'"{samtools}" view -H "{bam}"'.format(
samtools="samtools",
bam=self._bam_fn,
), iterable=True
):
x = x.strip()
if x[:3] == "@PG":
pg_header = x[4:].strip()
parts = pg_header.split("\t")
program_info = ["<table>"]
for part in parts:
(lvalue, _, rvalue) = part.partition(":")
program_info.append(
'<tr><td style="font-weight:bold">{}:</td><td style="text-align:left">{}</td></tr>'.format(
lvalue, rvalue
)
)
program_info.append("</table>")
eval_info = ["<table>"]
for (lvalue, rvalue) in [
("BAM file", self._bam_fn),
("Allowed delta", self.report.allowed_delta),
]:
eval_info.append(
'<tr><td style="font-weight:bold">{}:</td><td style="text-align:left">{}</td></tr>'.format(
lvalue, rvalue
)
)
eval_info.append("</table>")
css_src = textwrap.dedent(
"""
table {border-collapse:collapse;}
td {border: solid #aaaaff 1px;padding:4px;text-align:right;}
colgroup, thead {border: solid black 2px;padding 2px;}
.link_to_top {font-size:10pt;}
.desc {color:#aaa;}
.formats {text-align:left;margin-bottom:20px;}
"""
)
html_src = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{name}</title>
<style type="text/css">
{css}
</style>
</head>
<body>
<h1 id="top">
{name}
<span class="link_to_top">
[<a href="{homepage}">Back to main report</a>]
</span>
</h1>
<p>
<a href="#info_eval">Information about evaluation</a> -
<a href="#info_prog">Information about program</a> -
<a href="#roctable">ROC table</a> -
<a href="#graphs">Graphs</a>
</p>
<h2 id="info_eval">
Information about evaluation
{headline_links}
</h2>
{eval_info}
<h2 id="info_prog">
Information about program
{headline_links}
</h2>
{program_info}
<h2 id="roctable">
ROC table
{headline_links}
</h2>
<p style="font-size:80%">
<strong>M</strong>:
mapped correctly
<span class="desc">
(all segments of tuple are mapped once and correctly),
</span>
<strong>w</strong>:
mapped to wrong position
<span class="desc">
(at least one segment was mapped to a wrong position),
</span>
<strong>m</strong>:
mapped but should be unmapped
<span class="desc">
(at least one segment was mapped but the read should not be mapped),
</span>
<strong>P</strong>:
multimapped
<span class="desc">
(read should be mapped but it at least one segment was mapped several
times and all segments were mapped correctly at least once),
</span>
<strong>U</strong>:
unmapped correctly
<span class="desc">
(all segments of the read were correctly marked as unmapped),
</span>
<strong>u</strong>:
unmapped but should be mapped
<span class="desc">
(at least one segment was mapped but entire read should be unmapped),
</span>
<strong>T</strong>:
thresholded correctly
<span class="desc">
(read shoud not be mapped),
</span>
<strong>t</strong>:
thresholded incorrectly
<span class="desc">
(read should be mapped),
</span>
<strong>x</strong>:
unknown
<span class="desc">
(read is probably not reported by mapper)
</span>
</p>
<table>
<colgroup span="1" style="">
<colgroup span="2" style="background-color:#ddd">
<colgroup span="8" style="">
<colgroup span="2" style="background-color:#ddd">
<colgroup span="10" style="">
<colgroup span="1" style="background-color:#ddd">
<colgroup span="1" style="">
<thead style="font-weight:bold;background-color:#ddddff">
<tr style="font-weight:bold;background-color:#ddddff">
<td>q</td>
<td>mapped</td>
<td>%</td>
<td>M</td>
<td>%</td>
<td>w</td>
<td>%</td>
<td>m</td>
<td>%</td>
<td>P</td>
<td>%</td>
<td>unmapped</td>
<td>%</td>
<td>U</td>
<td>%</td>
<td>u</td>
<td>%</td>
<td>T</td>
<td>%</td>
<td>t</td>
<td>%</td>
<td>x</td>
<td>%</td>
<td>sum</td>
<td>prec. (%)</td>
</tr>
</thead>
<tbody>
{tbody}
</tbody>
</table>
<h2 id="graphs">
Graphs
{headline_links}
</h2>
<div class="formats">
<img src="{svg}" />
<br />
<a href="{svg}">SVG version</a>
|
<a href="{roc}" type="text/csv">ROC file</a>
|
<a href="{gp}" type="text/plain">GP file</a>
</div>
</body>
</html>
""".format(
name=self.name, tbody=tbody, css=css_src,
svg=os.path.relpath(self._svg_fn, os.path.dirname(self._html_fn)),
roc=os.path.relpath(self._roc_fn, os.path.dirname(self._html_fn)),
gp=os.path.relpath(self._gp_fn, os.path.dirname(self._html_fn)), eval_info=os.linesep.join(eval_info),
program_info=os.linesep.join(program_info),
homepage=os.path.relpath(self.report.html_fn(), os.path.dirname(self._html_fn)), headline_links='''
<span class="link_to_top">
[<a href="#top">Top of this page</a>]
[<a href="{homepage}">Back to main report</a>]
</span>
'''.format(homepage=os.path.relpath(self.report.html_fn(), os.path.dirname(self._html_fn)), )
)
tidy_html_src = bs4.BeautifulSoup(html_src).prettify()
html.write(tidy_html_src) | [
"def",
"create_html",
"(",
"self",
")",
":",
"roc_dicts",
"=",
"[",
"]",
"with",
"open",
"(",
"self",
".",
"_roc_fn",
",",
"\"r\"",
")",
"as",
"roc",
":",
"for",
"line",
"in",
"roc",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",... | Create a HTML page for this BAM file. | [
"Create",
"a",
"HTML",
"page",
"for",
"this",
"BAM",
"file",
"."
] | train | https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/lavender/Bam.py#L661-L962 |
BDNYC/astrodbkit | astrodbkit/votools.py | dict_tovot | def dict_tovot(tabdata, tabname='votable.xml', phot=False, binary=True):
"""
Converts dictionary table **tabdata** to a VOTable with name **tabname**
Parameters
----------
tabdata: list
SQL query dictionary list from running query_dict.execute()
tabname: str
The name of the VOTable to be created
phot: bool
Parameter specifying if the table contains photometry to be merged
binary: bool
Parameter specifying if the VOTable should be saved as a binary.
This is necessary for tables with lots of text columns.
"""
# Check if input is a dictionary
if not isinstance(tabdata[0], dict):
raise TypeError('Table must be a dictionary. Call the SQL query with query_dict.execute()')
# Create an empty table to store the data
t = Table()
colnames = tabdata[0].keys()
# If this is a photometry table, parse it and make sure to have the full list of columns
if phot:
tabdata = photparse(tabdata)
colnames = tabdata[0].keys()
for i in range(len(tabdata)):
tmpcol = tabdata[i].keys()
for elem in tmpcol:
if elem not in colnames:
colnames.append(elem)
# No need for band column any more
try:
colnames.remove('band')
except ValueError:
pass
# Run through all the columns and create them
for elem in colnames:
table_add(t, tabdata, elem)
# Output to a file
print('Creating table...')
votable = from_table(t)
# Required in some cases (ie, for lots of text columns)
if binary:
votable.set_all_tables_format('binary')
votable.to_xml(tabname)
print('Table created: {}'.format(tabname)) | python | def dict_tovot(tabdata, tabname='votable.xml', phot=False, binary=True):
"""
Converts dictionary table **tabdata** to a VOTable with name **tabname**
Parameters
----------
tabdata: list
SQL query dictionary list from running query_dict.execute()
tabname: str
The name of the VOTable to be created
phot: bool
Parameter specifying if the table contains photometry to be merged
binary: bool
Parameter specifying if the VOTable should be saved as a binary.
This is necessary for tables with lots of text columns.
"""
# Check if input is a dictionary
if not isinstance(tabdata[0], dict):
raise TypeError('Table must be a dictionary. Call the SQL query with query_dict.execute()')
# Create an empty table to store the data
t = Table()
colnames = tabdata[0].keys()
# If this is a photometry table, parse it and make sure to have the full list of columns
if phot:
tabdata = photparse(tabdata)
colnames = tabdata[0].keys()
for i in range(len(tabdata)):
tmpcol = tabdata[i].keys()
for elem in tmpcol:
if elem not in colnames:
colnames.append(elem)
# No need for band column any more
try:
colnames.remove('band')
except ValueError:
pass
# Run through all the columns and create them
for elem in colnames:
table_add(t, tabdata, elem)
# Output to a file
print('Creating table...')
votable = from_table(t)
# Required in some cases (ie, for lots of text columns)
if binary:
votable.set_all_tables_format('binary')
votable.to_xml(tabname)
print('Table created: {}'.format(tabname)) | [
"def",
"dict_tovot",
"(",
"tabdata",
",",
"tabname",
"=",
"'votable.xml'",
",",
"phot",
"=",
"False",
",",
"binary",
"=",
"True",
")",
":",
"# Check if input is a dictionary",
"if",
"not",
"isinstance",
"(",
"tabdata",
"[",
"0",
"]",
",",
"dict",
")",
":",... | Converts dictionary table **tabdata** to a VOTable with name **tabname**
Parameters
----------
tabdata: list
SQL query dictionary list from running query_dict.execute()
tabname: str
The name of the VOTable to be created
phot: bool
Parameter specifying if the table contains photometry to be merged
binary: bool
Parameter specifying if the VOTable should be saved as a binary.
This is necessary for tables with lots of text columns. | [
"Converts",
"dictionary",
"table",
"**",
"tabdata",
"**",
"to",
"a",
"VOTable",
"with",
"name",
"**",
"tabname",
"**"
] | train | https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/votools.py#L11-L70 |
BDNYC/astrodbkit | astrodbkit/votools.py | photaddline | def photaddline(tab, sourceid):
"""
Loop through the dictionary list **tab** creating a line for the source specified in **sourceid**
Parameters
----------
tab:
Dictionary list of all the photometry data
sourceid:
ID of source in the photometry table (source_id)
Returns
-------
tmpdict: dict
Dictionary with all the data for the specified source
"""
colnames = tab[0].keys()
tmpdict = dict()
for i in range(len(tab)):
# If not working on the same source, continue
if tab[i]['source_id'] != sourceid:
continue
# Check column names and create new ones for band-specific ones
for elem in colnames:
if elem not in ['comments', 'epoch', 'instrument_id', 'magnitude', 'magnitude_unc', 'publication_id',
'system', 'telescope_id']:
tmpdict[elem] = tab[i][elem]
elif elem == 'band':
continue
else:
tmpstr = tab[i]['band']+'.'+elem
tmpdict[tmpstr] = tab[i][elem]
return tmpdict | python | def photaddline(tab, sourceid):
"""
Loop through the dictionary list **tab** creating a line for the source specified in **sourceid**
Parameters
----------
tab:
Dictionary list of all the photometry data
sourceid:
ID of source in the photometry table (source_id)
Returns
-------
tmpdict: dict
Dictionary with all the data for the specified source
"""
colnames = tab[0].keys()
tmpdict = dict()
for i in range(len(tab)):
# If not working on the same source, continue
if tab[i]['source_id'] != sourceid:
continue
# Check column names and create new ones for band-specific ones
for elem in colnames:
if elem not in ['comments', 'epoch', 'instrument_id', 'magnitude', 'magnitude_unc', 'publication_id',
'system', 'telescope_id']:
tmpdict[elem] = tab[i][elem]
elif elem == 'band':
continue
else:
tmpstr = tab[i]['band']+'.'+elem
tmpdict[tmpstr] = tab[i][elem]
return tmpdict | [
"def",
"photaddline",
"(",
"tab",
",",
"sourceid",
")",
":",
"colnames",
"=",
"tab",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"tmpdict",
"=",
"dict",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tab",
")",
")",
":",
"# If not working on the ... | Loop through the dictionary list **tab** creating a line for the source specified in **sourceid**
Parameters
----------
tab:
Dictionary list of all the photometry data
sourceid:
ID of source in the photometry table (source_id)
Returns
-------
tmpdict: dict
Dictionary with all the data for the specified source | [
"Loop",
"through",
"the",
"dictionary",
"list",
"**",
"tab",
"**",
"creating",
"a",
"line",
"for",
"the",
"source",
"specified",
"in",
"**",
"sourceid",
"**"
] | train | https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/votools.py#L73-L110 |
BDNYC/astrodbkit | astrodbkit/votools.py | photparse | def photparse(tab):
"""
Parse through a photometry table to group by source_id
Parameters
----------
tab: list
SQL query dictionary list from running query_dict.execute()
Returns
-------
newtab: list
Dictionary list after parsing to group together sources
"""
# Check that source_id column is present
if 'source_id' not in tab[0].keys():
raise KeyError('phot=TRUE requires the source_id columb be included')
# Loop through the table and grab unique band names and source IDs
uniqueid = []
for i in range(len(tab)):
tmpid = tab[i]['source_id']
if tmpid not in uniqueid:
uniqueid.append(tmpid)
# Loop over unique id and create a new table for each element in it
newtab = []
for sourceid in uniqueid:
tmpdict = photaddline(tab, sourceid)
newtab.append(tmpdict)
return newtab | python | def photparse(tab):
"""
Parse through a photometry table to group by source_id
Parameters
----------
tab: list
SQL query dictionary list from running query_dict.execute()
Returns
-------
newtab: list
Dictionary list after parsing to group together sources
"""
# Check that source_id column is present
if 'source_id' not in tab[0].keys():
raise KeyError('phot=TRUE requires the source_id columb be included')
# Loop through the table and grab unique band names and source IDs
uniqueid = []
for i in range(len(tab)):
tmpid = tab[i]['source_id']
if tmpid not in uniqueid:
uniqueid.append(tmpid)
# Loop over unique id and create a new table for each element in it
newtab = []
for sourceid in uniqueid:
tmpdict = photaddline(tab, sourceid)
newtab.append(tmpdict)
return newtab | [
"def",
"photparse",
"(",
"tab",
")",
":",
"# Check that source_id column is present",
"if",
"'source_id'",
"not",
"in",
"tab",
"[",
"0",
"]",
".",
"keys",
"(",
")",
":",
"raise",
"KeyError",
"(",
"'phot=TRUE requires the source_id columb be included'",
")",
"# Loop ... | Parse through a photometry table to group by source_id
Parameters
----------
tab: list
SQL query dictionary list from running query_dict.execute()
Returns
-------
newtab: list
Dictionary list after parsing to group together sources | [
"Parse",
"through",
"a",
"photometry",
"table",
"to",
"group",
"by",
"source_id"
] | train | https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/votools.py#L113-L147 |
BDNYC/astrodbkit | astrodbkit/votools.py | table_add | def table_add(tab, data, col):
"""
Function to parse dictionary list **data** and add the data to table **tab** for column **col**
Parameters
----------
tab: Table class
Table to store values
data: list
Dictionary list from the SQL query
col: str
Column name (ie, dictionary key) for the column to add
"""
x = []
for i in range(len(data)):
# If the particular key is not present, use a place-holder value (used for photometry tables)
if col not in data[i]:
temp = ''
else:
temp = data[i][col]
# Fix up None elements
if temp is None: temp = ''
x.append(temp)
print('Adding column {}'.format(col))
tab.add_column(Column(x, name=col)) | python | def table_add(tab, data, col):
"""
Function to parse dictionary list **data** and add the data to table **tab** for column **col**
Parameters
----------
tab: Table class
Table to store values
data: list
Dictionary list from the SQL query
col: str
Column name (ie, dictionary key) for the column to add
"""
x = []
for i in range(len(data)):
# If the particular key is not present, use a place-holder value (used for photometry tables)
if col not in data[i]:
temp = ''
else:
temp = data[i][col]
# Fix up None elements
if temp is None: temp = ''
x.append(temp)
print('Adding column {}'.format(col))
tab.add_column(Column(x, name=col)) | [
"def",
"table_add",
"(",
"tab",
",",
"data",
",",
"col",
")",
":",
"x",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")",
":",
"# If the particular key is not present, use a place-holder value (used for photometry tables)",
"if",
"col"... | Function to parse dictionary list **data** and add the data to table **tab** for column **col**
Parameters
----------
tab: Table class
Table to store values
data: list
Dictionary list from the SQL query
col: str
Column name (ie, dictionary key) for the column to add | [
"Function",
"to",
"parse",
"dictionary",
"list",
"**",
"data",
"**",
"and",
"add",
"the",
"data",
"to",
"table",
"**",
"tab",
"**",
"for",
"column",
"**",
"col",
"**"
] | train | https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/votools.py#L150-L180 |
praekelt/django-order | order/managers.py | user_order_by | def user_order_by(self, field):
"""
Queryset method ordering objects by user ordering field.
"""
# Get ordering model.
model_label = order.utils.resolve_labels('.'.join(\
[self.model._meta.app_label, self.model._meta.object_name]))
orderitem_set = getattr(self.model, \
order.utils.resolve_order_item_related_set_name(model_label))
order_model = orderitem_set.related.model
# Resolve ordering model table name.
db_table = order_model._meta.db_table
# Add ordering field as extra queryset fields.
pk_name = self.model._meta.pk.attname
# If we have a descending query remove '-' from field name when quering.
sanitized_field = field.lstrip('-')
extra_select = {
sanitized_field: '(SELECT %s from %s WHERE item_id=%s.%s)' % \
(sanitized_field, db_table, self.model._meta.db_table, pk_name)
}
# Use original field name when ordering to allow for descending.
return self.extra(select=extra_select).all().order_by(field) | python | def user_order_by(self, field):
"""
Queryset method ordering objects by user ordering field.
"""
# Get ordering model.
model_label = order.utils.resolve_labels('.'.join(\
[self.model._meta.app_label, self.model._meta.object_name]))
orderitem_set = getattr(self.model, \
order.utils.resolve_order_item_related_set_name(model_label))
order_model = orderitem_set.related.model
# Resolve ordering model table name.
db_table = order_model._meta.db_table
# Add ordering field as extra queryset fields.
pk_name = self.model._meta.pk.attname
# If we have a descending query remove '-' from field name when quering.
sanitized_field = field.lstrip('-')
extra_select = {
sanitized_field: '(SELECT %s from %s WHERE item_id=%s.%s)' % \
(sanitized_field, db_table, self.model._meta.db_table, pk_name)
}
# Use original field name when ordering to allow for descending.
return self.extra(select=extra_select).all().order_by(field) | [
"def",
"user_order_by",
"(",
"self",
",",
"field",
")",
":",
"# Get ordering model.",
"model_label",
"=",
"order",
".",
"utils",
".",
"resolve_labels",
"(",
"'.'",
".",
"join",
"(",
"[",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
... | Queryset method ordering objects by user ordering field. | [
"Queryset",
"method",
"ordering",
"objects",
"by",
"user",
"ordering",
"field",
"."
] | train | https://github.com/praekelt/django-order/blob/dcffeb5b28d460872f7d47675c4bfc8a32c807a3/order/managers.py#L4-L30 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.list_enabled_features_accounts | def list_enabled_features_accounts(self, account_id):
"""
List enabled features.
List all features that are enabled on a given Account, Course, or User.
Only the feature names are returned.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
self.logger.debug("GET /api/v1/accounts/{account_id}/features/enabled with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/features/enabled".format(**path), data=data, params=params, no_data=True) | python | def list_enabled_features_accounts(self, account_id):
"""
List enabled features.
List all features that are enabled on a given Account, Course, or User.
Only the feature names are returned.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
self.logger.debug("GET /api/v1/accounts/{account_id}/features/enabled with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/features/enabled".format(**path), data=data, params=params, no_data=True) | [
"def",
"list_enabled_features_accounts",
"(",
"self",
",",
"account_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_id\"",
"]",
"=",
"account_id",... | List enabled features.
List all features that are enabled on a given Account, Course, or User.
Only the feature names are returned. | [
"List",
"enabled",
"features",
".",
"List",
"all",
"features",
"that",
"are",
"enabled",
"on",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"Only",
"the",
"feature",
"names",
"are",
"returned",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L88-L104 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.set_feature_flag_courses | def set_feature_flag_courses(self, feature, course_id, state=None):
"""
Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
# OPTIONAL - state
""""off":: The feature is not available for the course, user, or account and sub-accounts.
"allowed":: (valid only on accounts) The feature is off in the account, but may be enabled in
sub-accounts and courses by setting a feature flag on the sub-account or course.
"on":: The feature is turned on unconditionally for the user, course, or account and sub-accounts."""
if state is not None:
self._validate_enum(state, ["off", "allowed", "on"])
data["state"] = state
self.logger.debug("PUT /api/v1/courses/{course_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/courses/{course_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | python | def set_feature_flag_courses(self, feature, course_id, state=None):
"""
Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
# OPTIONAL - state
""""off":: The feature is not available for the course, user, or account and sub-accounts.
"allowed":: (valid only on accounts) The feature is off in the account, but may be enabled in
sub-accounts and courses by setting a feature flag on the sub-account or course.
"on":: The feature is turned on unconditionally for the user, course, or account and sub-accounts."""
if state is not None:
self._validate_enum(state, ["off", "allowed", "on"])
data["state"] = state
self.logger.debug("PUT /api/v1/courses/{course_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/courses/{course_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | [
"def",
"set_feature_flag_courses",
"(",
"self",
",",
"feature",
",",
"course_id",
",",
"state",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
... | Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed". | [
"Set",
"feature",
"flag",
".",
"Set",
"a",
"feature",
"flag",
"for",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"This",
"call",
"will",
"fail",
"if",
"a",
"parent",
"account",
"sets",
"a",
"feature",
"flag",
"for",
"the",
"same",
"feature",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L199-L228 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.set_feature_flag_accounts | def set_feature_flag_accounts(self, feature, account_id, state=None):
"""
Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
# OPTIONAL - state
""""off":: The feature is not available for the course, user, or account and sub-accounts.
"allowed":: (valid only on accounts) The feature is off in the account, but may be enabled in
sub-accounts and courses by setting a feature flag on the sub-account or course.
"on":: The feature is turned on unconditionally for the user, course, or account and sub-accounts."""
if state is not None:
self._validate_enum(state, ["off", "allowed", "on"])
data["state"] = state
self.logger.debug("PUT /api/v1/accounts/{account_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/accounts/{account_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | python | def set_feature_flag_accounts(self, feature, account_id, state=None):
"""
Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
# OPTIONAL - state
""""off":: The feature is not available for the course, user, or account and sub-accounts.
"allowed":: (valid only on accounts) The feature is off in the account, but may be enabled in
sub-accounts and courses by setting a feature flag on the sub-account or course.
"on":: The feature is turned on unconditionally for the user, course, or account and sub-accounts."""
if state is not None:
self._validate_enum(state, ["off", "allowed", "on"])
data["state"] = state
self.logger.debug("PUT /api/v1/accounts/{account_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/accounts/{account_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | [
"def",
"set_feature_flag_accounts",
"(",
"self",
",",
"feature",
",",
"account_id",
",",
"state",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",... | Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed". | [
"Set",
"feature",
"flag",
".",
"Set",
"a",
"feature",
"flag",
"for",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"This",
"call",
"will",
"fail",
"if",
"a",
"parent",
"account",
"sets",
"a",
"feature",
"flag",
"for",
"the",
"same",
"feature",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L230-L259 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.set_feature_flag_users | def set_feature_flag_users(self, user_id, feature, state=None):
"""
Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
# OPTIONAL - state
""""off":: The feature is not available for the course, user, or account and sub-accounts.
"allowed":: (valid only on accounts) The feature is off in the account, but may be enabled in
sub-accounts and courses by setting a feature flag on the sub-account or course.
"on":: The feature is turned on unconditionally for the user, course, or account and sub-accounts."""
if state is not None:
self._validate_enum(state, ["off", "allowed", "on"])
data["state"] = state
self.logger.debug("PUT /api/v1/users/{user_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/users/{user_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | python | def set_feature_flag_users(self, user_id, feature, state=None):
"""
Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed".
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
# OPTIONAL - state
""""off":: The feature is not available for the course, user, or account and sub-accounts.
"allowed":: (valid only on accounts) The feature is off in the account, but may be enabled in
sub-accounts and courses by setting a feature flag on the sub-account or course.
"on":: The feature is turned on unconditionally for the user, course, or account and sub-accounts."""
if state is not None:
self._validate_enum(state, ["off", "allowed", "on"])
data["state"] = state
self.logger.debug("PUT /api/v1/users/{user_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/users/{user_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | [
"def",
"set_feature_flag_users",
"(",
"self",
",",
"user_id",
",",
"feature",
",",
"state",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"use... | Set feature flag.
Set a feature flag for a given Account, Course, or User. This call will fail if a parent account sets
a feature flag for the same feature in any state other than "allowed". | [
"Set",
"feature",
"flag",
".",
"Set",
"a",
"feature",
"flag",
"for",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"This",
"call",
"will",
"fail",
"if",
"a",
"parent",
"account",
"sets",
"a",
"feature",
"flag",
"for",
"the",
"same",
"feature",
... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L261-L290 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.remove_feature_flag_courses | def remove_feature_flag_courses(self, feature, course_id):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
self.logger.debug("DELETE /api/v1/courses/{course_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | python | def remove_feature_flag_courses(self, feature, course_id):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
self.logger.debug("DELETE /api/v1/courses/{course_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | [
"def",
"remove_feature_flag_courses",
"(",
"self",
",",
"feature",
",",
"course_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]",
"=",
... | Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again. | [
"Remove",
"feature",
"flag",
".",
"Remove",
"feature",
"flag",
"for",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"(",
"Note",
"that",
"the",
"flag",
"must",
"be",
"defined",
"on",
"the",
"Account",
"Course",
"or",
"User",
"directly",
".",
")",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L292-L314 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.remove_feature_flag_accounts | def remove_feature_flag_accounts(self, feature, account_id):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
self.logger.debug("DELETE /api/v1/accounts/{account_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/accounts/{account_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | python | def remove_feature_flag_accounts(self, feature, account_id):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
self.logger.debug("DELETE /api/v1/accounts/{account_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/accounts/{account_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | [
"def",
"remove_feature_flag_accounts",
"(",
"self",
",",
"feature",
",",
"account_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_id\"",
"]",
"=... | Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again. | [
"Remove",
"feature",
"flag",
".",
"Remove",
"feature",
"flag",
"for",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"(",
"Note",
"that",
"the",
"flag",
"must",
"be",
"defined",
"on",
"the",
"Account",
"Course",
"or",
"User",
"directly",
".",
")",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L316-L338 |
PGower/PyCanvas | pycanvas/apis/feature_flags.py | FeatureFlagsAPI.remove_feature_flag_users | def remove_feature_flag_users(self, user_id, feature):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
self.logger.debug("DELETE /api/v1/users/{user_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/{user_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | python | def remove_feature_flag_users(self, user_id, feature):
"""
Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# REQUIRED - PATH - feature
"""ID"""
path["feature"] = feature
self.logger.debug("DELETE /api/v1/users/{user_id}/features/flags/{feature} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/users/{user_id}/features/flags/{feature}".format(**path), data=data, params=params, single_item=True) | [
"def",
"remove_feature_flag_users",
"(",
"self",
",",
"user_id",
",",
"feature",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"user_id\"",
"]",
"=",
"user_i... | Remove feature flag.
Remove feature flag for a given Account, Course, or User. (Note that the flag must
be defined on the Account, Course, or User directly.) The object will then inherit
the feature flags from a higher account, if any exist. If this flag was 'on' or 'off',
then lower-level account flags that were masked by this one will apply again. | [
"Remove",
"feature",
"flag",
".",
"Remove",
"feature",
"flag",
"for",
"a",
"given",
"Account",
"Course",
"or",
"User",
".",
"(",
"Note",
"that",
"the",
"flag",
"must",
"be",
"defined",
"on",
"the",
"Account",
"Course",
"or",
"User",
"directly",
".",
")",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/feature_flags.py#L340-L362 |
jfilter/deep-plots | deep_plots/plot.py | plot_accuracy | def plot_accuracy(data, output_dir_path='.', output_filename='accuracy.png',
width=10, height=8):
"""Plot accuracy.
Args:
data: Panda dataframe in *the* format.
"""
output_path = os.path.join(output_dir_path, output_filename)
max_val_data = get_epoch_max_val_acc(data)
max_val_label = round(max_val_data['acc'].values[0], 4)
# max_val_epoch = max_val_data['epoch'].values[0]
max_epoch_data = data[data['epoch'] == data['epoch'].max()]
plot = ggplot(data, aes('epoch', 'acc', color='factor(data)')) + \
geom_line(size=1, show_legend=False) + \
geom_vline(aes(xintercept='epoch', color='data'),
data=max_val_data, alpha=0.5, show_legend=False) + \
geom_label(aes('epoch', 'acc'), data=max_val_data,
label=max_val_label, nudge_y=-0.02, va='top', label_size=0,
show_legend=False) + \
geom_text(aes('epoch', 'acc', label='data'), data=max_epoch_data,
nudge_x=2, ha='center', show_legend=False) + \
geom_point(aes('epoch', 'acc'), data=max_val_data,
show_legend=False) + \
labs(y='Accuracy', x='Epochs') + \
theme_bw(base_family='Arial', base_size=15) + \
scale_color_manual(['#ef8a62', '#67a9cf', "#f7f7f7"])
plot.save(output_path, width=width, height=height) | python | def plot_accuracy(data, output_dir_path='.', output_filename='accuracy.png',
width=10, height=8):
"""Plot accuracy.
Args:
data: Panda dataframe in *the* format.
"""
output_path = os.path.join(output_dir_path, output_filename)
max_val_data = get_epoch_max_val_acc(data)
max_val_label = round(max_val_data['acc'].values[0], 4)
# max_val_epoch = max_val_data['epoch'].values[0]
max_epoch_data = data[data['epoch'] == data['epoch'].max()]
plot = ggplot(data, aes('epoch', 'acc', color='factor(data)')) + \
geom_line(size=1, show_legend=False) + \
geom_vline(aes(xintercept='epoch', color='data'),
data=max_val_data, alpha=0.5, show_legend=False) + \
geom_label(aes('epoch', 'acc'), data=max_val_data,
label=max_val_label, nudge_y=-0.02, va='top', label_size=0,
show_legend=False) + \
geom_text(aes('epoch', 'acc', label='data'), data=max_epoch_data,
nudge_x=2, ha='center', show_legend=False) + \
geom_point(aes('epoch', 'acc'), data=max_val_data,
show_legend=False) + \
labs(y='Accuracy', x='Epochs') + \
theme_bw(base_family='Arial', base_size=15) + \
scale_color_manual(['#ef8a62', '#67a9cf', "#f7f7f7"])
plot.save(output_path, width=width, height=height) | [
"def",
"plot_accuracy",
"(",
"data",
",",
"output_dir_path",
"=",
"'.'",
",",
"output_filename",
"=",
"'accuracy.png'",
",",
"width",
"=",
"10",
",",
"height",
"=",
"8",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir_path",
... | Plot accuracy.
Args:
data: Panda dataframe in *the* format. | [
"Plot",
"accuracy",
".",
"Args",
":",
"data",
":",
"Panda",
"dataframe",
"in",
"*",
"the",
"*",
"format",
"."
] | train | https://github.com/jfilter/deep-plots/blob/8b0af5c1e44336068c2f8c883ffa158bbb34ba5e/deep_plots/plot.py#L25-L54 |
jfilter/deep-plots | deep_plots/plot.py | plot | def plot(data, output_dir_path='.', width=10, height=8):
"""Create two plots: 1) loss 2) accuracy.
Args:
data: Panda dataframe in *the* format.
"""
if not isinstance(data, pd.DataFrame):
data = pd.DataFrame(data)
plot_accuracy(data, output_dir_path=output_dir_path,
width=width, height=height)
plot_loss(data, output_dir_path, width=width, height=height) | python | def plot(data, output_dir_path='.', width=10, height=8):
"""Create two plots: 1) loss 2) accuracy.
Args:
data: Panda dataframe in *the* format.
"""
if not isinstance(data, pd.DataFrame):
data = pd.DataFrame(data)
plot_accuracy(data, output_dir_path=output_dir_path,
width=width, height=height)
plot_loss(data, output_dir_path, width=width, height=height) | [
"def",
"plot",
"(",
"data",
",",
"output_dir_path",
"=",
"'.'",
",",
"width",
"=",
"10",
",",
"height",
"=",
"8",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"pd",
".",
"DataFrame",
")",
":",
"data",
"=",
"pd",
".",
"DataFrame",
"(",
"... | Create two plots: 1) loss 2) accuracy.
Args:
data: Panda dataframe in *the* format. | [
"Create",
"two",
"plots",
":",
"1",
")",
"loss",
"2",
")",
"accuracy",
".",
"Args",
":",
"data",
":",
"Panda",
"dataframe",
"in",
"*",
"the",
"*",
"format",
"."
] | train | https://github.com/jfilter/deep-plots/blob/8b0af5c1e44336068c2f8c883ffa158bbb34ba5e/deep_plots/plot.py#L100-L109 |
jneight/django-xadmin-extras | xadmin_extras/views.py | AppConfigViewMixin.get_apps_menu | def get_apps_menu(self):
"""Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered
"""
menu = {}
for model, model_admin in self.admin_site._registry.items():
if hasattr(model_admin, 'app_config'):
if model_admin.app_config.has_menu_permission(obj=self.user):
menu.update({
'app:' + model_admin.app_config.name: {
'title': model_admin.app_config.verbose_name,
'menus': model_admin.app_config.init_menu(),
'first_icon': model_admin.app_config.icon}})
return menu | python | def get_apps_menu(self):
"""Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered
"""
menu = {}
for model, model_admin in self.admin_site._registry.items():
if hasattr(model_admin, 'app_config'):
if model_admin.app_config.has_menu_permission(obj=self.user):
menu.update({
'app:' + model_admin.app_config.name: {
'title': model_admin.app_config.verbose_name,
'menus': model_admin.app_config.init_menu(),
'first_icon': model_admin.app_config.icon}})
return menu | [
"def",
"get_apps_menu",
"(",
"self",
")",
":",
"menu",
"=",
"{",
"}",
"for",
"model",
",",
"model_admin",
"in",
"self",
".",
"admin_site",
".",
"_registry",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"model_admin",
",",
"'app_config'",
")",
":"... | Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered | [
"Temporal",
"code",
"will",
"change",
"to",
"apps",
".",
"get_app_configs",
"()",
"for",
"django",
"1",
".",
"7"
] | train | https://github.com/jneight/django-xadmin-extras/blob/a7909a3a4c1620b550202d3f0aa357503cc15a29/xadmin_extras/views.py#L29-L43 |
jneight/django-xadmin-extras | xadmin_extras/views.py | AppConfigViewMixin.get_nav_menu | def get_nav_menu(self):
"""Method to generate the menu"""
_menu = self.get_site_menu()
if _menu:
site_menu = list(_menu)
else:
site_menu = []
had_urls = []
def get_url(menu, had_urls):
if 'url' in menu:
had_urls.append(menu['url'])
if 'menus' in menu:
for m in menu['menus']:
get_url(m, had_urls)
get_url({'menus': site_menu}, had_urls)
# get base menu with apps already configurated
nav_menu = collections.OrderedDict(self.get_apps_menu())
for model, model_admin in self.admin_site._registry.items():
if getattr(model_admin, 'hidden_menu', False):
continue
app_config = getattr(model_admin, 'app_config', None)
app_label = app_config.name if app_config else model._meta.app_label
model_dict = {
'title': smart_text(capfirst(model._meta.verbose_name_plural)),
'url': self.get_model_url(model, "changelist"),
'icon': self.get_model_icon(model),
'perm': self.get_model_perm(model, 'view'),
'order': model_admin.order,
}
if model_dict['url'] in had_urls:
continue
app_key = "app:%s" % app_label
if app_key in nav_menu:
nav_menu[app_key]['menus'].append(model_dict)
else:
# first time the app is seen
# Find app title
if app_config:
app_title = model_admin.app_config.verbose_name
else:
app_title = smart_text(app_label.title())
if app_label.lower() in self.apps_label_title:
app_title = self.apps_label_title[app_label.lower()]
else:
mods = model.__module__.split('.')
if len(mods) > 1:
mod = '.'.join(mods[0:-1])
if mod in sys.modules:
mod = sys.modules[mod]
if 'verbose_name' in dir(mod):
app_title = getattr(mod, 'verbose_name')
elif 'app_title' in dir(mod):
app_title = getattr(mod, 'app_title')
nav_menu[app_key] = {
'title': app_title,
'menus': [model_dict],
}
app_menu = nav_menu[app_key]
if ('first_icon' not in app_menu or
app_menu['first_icon'] == self.default_model_icon) and model_dict.get('icon'):
app_menu['first_icon'] = model_dict['icon']
if 'first_url' not in app_menu and model_dict.get('url'):
app_menu['first_url'] = model_dict['url']
# after app menu is done, join it to the site menu
nav_menu = nav_menu.values()
site_menu.extend(nav_menu)
for menu in site_menu:
menu['menus'].sort(key=sortkeypicker(['order', 'title']))
site_menu.sort(key=lambda x: x['title'])
return site_menu | python | def get_nav_menu(self):
"""Method to generate the menu"""
_menu = self.get_site_menu()
if _menu:
site_menu = list(_menu)
else:
site_menu = []
had_urls = []
def get_url(menu, had_urls):
if 'url' in menu:
had_urls.append(menu['url'])
if 'menus' in menu:
for m in menu['menus']:
get_url(m, had_urls)
get_url({'menus': site_menu}, had_urls)
# get base menu with apps already configurated
nav_menu = collections.OrderedDict(self.get_apps_menu())
for model, model_admin in self.admin_site._registry.items():
if getattr(model_admin, 'hidden_menu', False):
continue
app_config = getattr(model_admin, 'app_config', None)
app_label = app_config.name if app_config else model._meta.app_label
model_dict = {
'title': smart_text(capfirst(model._meta.verbose_name_plural)),
'url': self.get_model_url(model, "changelist"),
'icon': self.get_model_icon(model),
'perm': self.get_model_perm(model, 'view'),
'order': model_admin.order,
}
if model_dict['url'] in had_urls:
continue
app_key = "app:%s" % app_label
if app_key in nav_menu:
nav_menu[app_key]['menus'].append(model_dict)
else:
# first time the app is seen
# Find app title
if app_config:
app_title = model_admin.app_config.verbose_name
else:
app_title = smart_text(app_label.title())
if app_label.lower() in self.apps_label_title:
app_title = self.apps_label_title[app_label.lower()]
else:
mods = model.__module__.split('.')
if len(mods) > 1:
mod = '.'.join(mods[0:-1])
if mod in sys.modules:
mod = sys.modules[mod]
if 'verbose_name' in dir(mod):
app_title = getattr(mod, 'verbose_name')
elif 'app_title' in dir(mod):
app_title = getattr(mod, 'app_title')
nav_menu[app_key] = {
'title': app_title,
'menus': [model_dict],
}
app_menu = nav_menu[app_key]
if ('first_icon' not in app_menu or
app_menu['first_icon'] == self.default_model_icon) and model_dict.get('icon'):
app_menu['first_icon'] = model_dict['icon']
if 'first_url' not in app_menu and model_dict.get('url'):
app_menu['first_url'] = model_dict['url']
# after app menu is done, join it to the site menu
nav_menu = nav_menu.values()
site_menu.extend(nav_menu)
for menu in site_menu:
menu['menus'].sort(key=sortkeypicker(['order', 'title']))
site_menu.sort(key=lambda x: x['title'])
return site_menu | [
"def",
"get_nav_menu",
"(",
"self",
")",
":",
"_menu",
"=",
"self",
".",
"get_site_menu",
"(",
")",
"if",
"_menu",
":",
"site_menu",
"=",
"list",
"(",
"_menu",
")",
"else",
":",
"site_menu",
"=",
"[",
"]",
"had_urls",
"=",
"[",
"]",
"def",
"get_url",... | Method to generate the menu | [
"Method",
"to",
"generate",
"the",
"menu"
] | train | https://github.com/jneight/django-xadmin-extras/blob/a7909a3a4c1620b550202d3f0aa357503cc15a29/xadmin_extras/views.py#L46-L120 |
Sanji-IO/sanji | sanji/connection/mqtt.py | Mqtt.connect | def connect(self):
"""
connect
"""
_logger.debug("Start connecting to broker")
while True:
try:
self.client.connect(self.broker_host, self.broker_port,
self.broker_keepalive)
break
except Exception:
_logger.debug(
"Connect failed. wait %s sec" % self.connect_delay)
sleep(self.connect_delay)
self.client.loop_forever() | python | def connect(self):
"""
connect
"""
_logger.debug("Start connecting to broker")
while True:
try:
self.client.connect(self.broker_host, self.broker_port,
self.broker_keepalive)
break
except Exception:
_logger.debug(
"Connect failed. wait %s sec" % self.connect_delay)
sleep(self.connect_delay)
self.client.loop_forever() | [
"def",
"connect",
"(",
"self",
")",
":",
"_logger",
".",
"debug",
"(",
"\"Start connecting to broker\"",
")",
"while",
"True",
":",
"try",
":",
"self",
".",
"client",
".",
"connect",
"(",
"self",
".",
"broker_host",
",",
"self",
".",
"broker_port",
",",
... | connect | [
"connect"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/connection/mqtt.py#L59-L74 |
Sanji-IO/sanji | sanji/connection/mqtt.py | Mqtt.set_tunnel | def set_tunnel(self, tunnel_type, tunnel, callback=None):
"""
set_tunnel(self, tunnel_type, tunnel, callback=None):
"""
orig_tunnel = self.tunnels.get(tunnel_type, (None, None))[0]
if orig_tunnel is not None:
_logger.debug("Unsubscribe: %s", (orig_tunnel,))
self.client.unsubscribe(str(orig_tunnel))
self.tunnels[tunnel_type] = (tunnel, callback)
if callback is not None:
self.message_callback_add(tunnel, callback)
self.client.subscribe(str(tunnel))
_logger.debug("Subscribe: %s", (tunnel,)) | python | def set_tunnel(self, tunnel_type, tunnel, callback=None):
"""
set_tunnel(self, tunnel_type, tunnel, callback=None):
"""
orig_tunnel = self.tunnels.get(tunnel_type, (None, None))[0]
if orig_tunnel is not None:
_logger.debug("Unsubscribe: %s", (orig_tunnel,))
self.client.unsubscribe(str(orig_tunnel))
self.tunnels[tunnel_type] = (tunnel, callback)
if callback is not None:
self.message_callback_add(tunnel, callback)
self.client.subscribe(str(tunnel))
_logger.debug("Subscribe: %s", (tunnel,)) | [
"def",
"set_tunnel",
"(",
"self",
",",
"tunnel_type",
",",
"tunnel",
",",
"callback",
"=",
"None",
")",
":",
"orig_tunnel",
"=",
"self",
".",
"tunnels",
".",
"get",
"(",
"tunnel_type",
",",
"(",
"None",
",",
"None",
")",
")",
"[",
"0",
"]",
"if",
"... | set_tunnel(self, tunnel_type, tunnel, callback=None): | [
"set_tunnel",
"(",
"self",
"tunnel_type",
"tunnel",
"callback",
"=",
"None",
")",
":"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/connection/mqtt.py#L83-L98 |
Sanji-IO/sanji | sanji/connection/mqtt.py | Mqtt.set_tunnels | def set_tunnels(self, tunnels):
"""
set_tunnels(self, tunnels):
"""
for tunnel_type, (tunnel, callback) in tunnels.iteritems():
if tunnel is None:
continue
self.set_tunnel(tunnel_type, tunnel, callback) | python | def set_tunnels(self, tunnels):
"""
set_tunnels(self, tunnels):
"""
for tunnel_type, (tunnel, callback) in tunnels.iteritems():
if tunnel is None:
continue
self.set_tunnel(tunnel_type, tunnel, callback) | [
"def",
"set_tunnels",
"(",
"self",
",",
"tunnels",
")",
":",
"for",
"tunnel_type",
",",
"(",
"tunnel",
",",
"callback",
")",
"in",
"tunnels",
".",
"iteritems",
"(",
")",
":",
"if",
"tunnel",
"is",
"None",
":",
"continue",
"self",
".",
"set_tunnel",
"("... | set_tunnels(self, tunnels): | [
"set_tunnels",
"(",
"self",
"tunnels",
")",
":"
] | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/connection/mqtt.py#L100-L107 |
Sanji-IO/sanji | sanji/connection/mqtt.py | Mqtt.publish | def publish(self, topic="/controller", qos=0, payload=None):
"""
publish(self, topic, payload=None, qos=0, retain=False)
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined.
"""
result = self.client.publish(topic,
payload=json.dumps(payload),
qos=qos)
if result[0] == mqtt.MQTT_ERR_NO_CONN:
raise RuntimeError("No connection")
return result[1] | python | def publish(self, topic="/controller", qos=0, payload=None):
"""
publish(self, topic, payload=None, qos=0, retain=False)
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined.
"""
result = self.client.publish(topic,
payload=json.dumps(payload),
qos=qos)
if result[0] == mqtt.MQTT_ERR_NO_CONN:
raise RuntimeError("No connection")
return result[1] | [
"def",
"publish",
"(",
"self",
",",
"topic",
"=",
"\"/controller\"",
",",
"qos",
"=",
"0",
",",
"payload",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"publish",
"(",
"topic",
",",
"payload",
"=",
"json",
".",
"dumps",
"(",
"p... | publish(self, topic, payload=None, qos=0, retain=False)
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the message ID for the publish request. The mid
value can be used to track the publish request by checking against the
mid argument in the on_publish() callback if it is defined. | [
"publish",
"(",
"self",
"topic",
"payload",
"=",
"None",
"qos",
"=",
"0",
"retain",
"=",
"False",
")",
"Returns",
"a",
"tuple",
"(",
"result",
"mid",
")",
"where",
"result",
"is",
"MQTT_ERR_SUCCESS",
"to",
"indicate",
"success",
"or",
"MQTT_ERR_NO_CONN",
"... | train | https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/connection/mqtt.py#L127-L141 |
Stranger6667/pyoffers | pyoffers/logging.py | get_logger | def get_logger(verbosity):
"""
Returns simple console logger.
"""
logger = logging.getLogger(__name__)
logger.setLevel({
0: DEFAULT_LOGGING_LEVEL,
1: logging.INFO,
2: logging.DEBUG
}.get(min(2, verbosity), DEFAULT_LOGGING_LEVEL))
logger.handlers = []
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
return logger | python | def get_logger(verbosity):
"""
Returns simple console logger.
"""
logger = logging.getLogger(__name__)
logger.setLevel({
0: DEFAULT_LOGGING_LEVEL,
1: logging.INFO,
2: logging.DEBUG
}.get(min(2, verbosity), DEFAULT_LOGGING_LEVEL))
logger.handlers = []
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
return logger | [
"def",
"get_logger",
"(",
"verbosity",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"setLevel",
"(",
"{",
"0",
":",
"DEFAULT_LOGGING_LEVEL",
",",
"1",
":",
"logging",
".",
"INFO",
",",
"2",
":",
"logging",
... | Returns simple console logger. | [
"Returns",
"simple",
"console",
"logger",
"."
] | train | https://github.com/Stranger6667/pyoffers/blob/9575d6cdc878096242268311a22cc5fdd4f64b37/pyoffers/logging.py#L9-L24 |
PGower/PyCanvas | pycanvas/apis/outcome_results.py | OutcomeResultsAPI.get_outcome_results | def get_outcome_results(self, course_id, include=None, outcome_ids=None, user_ids=None):
"""
Get outcome results.
Gets the outcome results for users and outcomes in the specified context.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - user_ids
"""If specified, only the users whose ids are given will be included in the
results. SIS ids can be used, prefixed by "sis_user_id:".
It is an error to specify an id for a user who is not a student in
the context."""
if user_ids is not None:
params["user_ids"] = user_ids
# OPTIONAL - outcome_ids
"""If specified, only the outcomes whose ids are given will be included in the
results. it is an error to specify an id for an outcome which is not linked
to the context."""
if outcome_ids is not None:
params["outcome_ids"] = outcome_ids
# OPTIONAL - include
"""[String, "alignments"|"outcomes"|"outcomes.alignments"|"outcome_groups"|"outcome_links"|"outcome_paths"|"users"]
Specify additional collections to be side loaded with the result.
"alignments" includes only the alignments referenced by the returned
results.
"outcomes.alignments" includes all alignments referenced by outcomes in the
context."""
if include is not None:
params["include"] = include
self.logger.debug("GET /api/v1/courses/{course_id}/outcome_results with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/outcome_results".format(**path), data=data, params=params, no_data=True) | python | def get_outcome_results(self, course_id, include=None, outcome_ids=None, user_ids=None):
"""
Get outcome results.
Gets the outcome results for users and outcomes in the specified context.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - user_ids
"""If specified, only the users whose ids are given will be included in the
results. SIS ids can be used, prefixed by "sis_user_id:".
It is an error to specify an id for a user who is not a student in
the context."""
if user_ids is not None:
params["user_ids"] = user_ids
# OPTIONAL - outcome_ids
"""If specified, only the outcomes whose ids are given will be included in the
results. it is an error to specify an id for an outcome which is not linked
to the context."""
if outcome_ids is not None:
params["outcome_ids"] = outcome_ids
# OPTIONAL - include
"""[String, "alignments"|"outcomes"|"outcomes.alignments"|"outcome_groups"|"outcome_links"|"outcome_paths"|"users"]
Specify additional collections to be side loaded with the result.
"alignments" includes only the alignments referenced by the returned
results.
"outcomes.alignments" includes all alignments referenced by outcomes in the
context."""
if include is not None:
params["include"] = include
self.logger.debug("GET /api/v1/courses/{course_id}/outcome_results with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/outcome_results".format(**path), data=data, params=params, no_data=True) | [
"def",
"get_outcome_results",
"(",
"self",
",",
"course_id",
",",
"include",
"=",
"None",
",",
"outcome_ids",
"=",
"None",
",",
"user_ids",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH... | Get outcome results.
Gets the outcome results for users and outcomes in the specified context. | [
"Get",
"outcome",
"results",
".",
"Gets",
"the",
"outcome",
"results",
"for",
"users",
"and",
"outcomes",
"in",
"the",
"specified",
"context",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/outcome_results.py#L19-L59 |
PGower/PyCanvas | pycanvas/apis/outcome_results.py | OutcomeResultsAPI.get_outcome_result_rollups | def get_outcome_result_rollups(self, course_id, aggregate=None, include=None, outcome_ids=None, user_ids=None):
"""
Get outcome result rollups.
Gets the outcome rollups for the users and outcomes in the specified
context.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - aggregate
"""If specified, instead of returning one rollup for each user, all the user
rollups will be combined into one rollup for the course that will contain
the average rollup score for each outcome."""
if aggregate is not None:
self._validate_enum(aggregate, ["course"])
params["aggregate"] = aggregate
# OPTIONAL - user_ids
"""If specified, only the users whose ids are given will be included in the
results or used in an aggregate result. it is an error to specify an id
for a user who is not a student in the context"""
if user_ids is not None:
params["user_ids"] = user_ids
# OPTIONAL - outcome_ids
"""If specified, only the outcomes whose ids are given will be included in the
results. it is an error to specify an id for an outcome which is not linked
to the context."""
if outcome_ids is not None:
params["outcome_ids"] = outcome_ids
# OPTIONAL - include
"""[String, "courses"|"outcomes"|"outcomes.alignments"|"outcome_groups"|"outcome_links"|"outcome_paths"|"users"]
Specify additional collections to be side loaded with the result."""
if include is not None:
params["include"] = include
self.logger.debug("GET /api/v1/courses/{course_id}/outcome_rollups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/outcome_rollups".format(**path), data=data, params=params, no_data=True) | python | def get_outcome_result_rollups(self, course_id, aggregate=None, include=None, outcome_ids=None, user_ids=None):
"""
Get outcome result rollups.
Gets the outcome rollups for the users and outcomes in the specified
context.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - aggregate
"""If specified, instead of returning one rollup for each user, all the user
rollups will be combined into one rollup for the course that will contain
the average rollup score for each outcome."""
if aggregate is not None:
self._validate_enum(aggregate, ["course"])
params["aggregate"] = aggregate
# OPTIONAL - user_ids
"""If specified, only the users whose ids are given will be included in the
results or used in an aggregate result. it is an error to specify an id
for a user who is not a student in the context"""
if user_ids is not None:
params["user_ids"] = user_ids
# OPTIONAL - outcome_ids
"""If specified, only the outcomes whose ids are given will be included in the
results. it is an error to specify an id for an outcome which is not linked
to the context."""
if outcome_ids is not None:
params["outcome_ids"] = outcome_ids
# OPTIONAL - include
"""[String, "courses"|"outcomes"|"outcomes.alignments"|"outcome_groups"|"outcome_links"|"outcome_paths"|"users"]
Specify additional collections to be side loaded with the result."""
if include is not None:
params["include"] = include
self.logger.debug("GET /api/v1/courses/{course_id}/outcome_rollups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/outcome_rollups".format(**path), data=data, params=params, no_data=True) | [
"def",
"get_outcome_result_rollups",
"(",
"self",
",",
"course_id",
",",
"aggregate",
"=",
"None",
",",
"include",
"=",
"None",
",",
"outcome_ids",
"=",
"None",
",",
"user_ids",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"para... | Get outcome result rollups.
Gets the outcome rollups for the users and outcomes in the specified
context. | [
"Get",
"outcome",
"result",
"rollups",
".",
"Gets",
"the",
"outcome",
"rollups",
"for",
"the",
"users",
"and",
"outcomes",
"in",
"the",
"specified",
"context",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/outcome_results.py#L61-L105 |
raags/ipmitool | ipmi/ipmi.py | ipmitool.execute | def execute(self, command):
"""Primary method to execute ipmitool commands
:param command: ipmi command to execute, str or list
e.g.
> ipmi = ipmitool('consolename.prod', 'secretpass')
> ipmi.execute('chassis status')
>
"""
if isinstance(command, str):
self.method(command.split())
elif isinstance(command, list):
self.method(command)
else:
raise TypeError("command should be either a string or list type")
if self.error:
raise IPMIError(self.error)
else:
return self.status | python | def execute(self, command):
"""Primary method to execute ipmitool commands
:param command: ipmi command to execute, str or list
e.g.
> ipmi = ipmitool('consolename.prod', 'secretpass')
> ipmi.execute('chassis status')
>
"""
if isinstance(command, str):
self.method(command.split())
elif isinstance(command, list):
self.method(command)
else:
raise TypeError("command should be either a string or list type")
if self.error:
raise IPMIError(self.error)
else:
return self.status | [
"def",
"execute",
"(",
"self",
",",
"command",
")",
":",
"if",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"self",
".",
"method",
"(",
"command",
".",
"split",
"(",
")",
")",
"elif",
"isinstance",
"(",
"command",
",",
"list",
")",
":",
"sel... | Primary method to execute ipmitool commands
:param command: ipmi command to execute, str or list
e.g.
> ipmi = ipmitool('consolename.prod', 'secretpass')
> ipmi.execute('chassis status')
> | [
"Primary",
"method",
"to",
"execute",
"ipmitool",
"commands",
":",
"param",
"command",
":",
"ipmi",
"command",
"to",
"execute",
"str",
"or",
"list",
"e",
".",
"g",
".",
">",
"ipmi",
"=",
"ipmitool",
"(",
"consolename",
".",
"prod",
"secretpass",
")",
">"... | train | https://github.com/raags/ipmitool/blob/830081623c0ec75d560123a559f0bb201f26cde6/ipmi/ipmi.py#L56-L75 |
raags/ipmitool | ipmi/ipmi.py | ipmitool._subprocess_method | def _subprocess_method(self, command):
"""Use the subprocess module to execute ipmitool commands
and and set status
"""
p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.output, self.error = p.communicate()
self.status = p.returncode | python | def _subprocess_method(self, command):
"""Use the subprocess module to execute ipmitool commands
and and set status
"""
p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.output, self.error = p.communicate()
self.status = p.returncode | [
"def",
"_subprocess_method",
"(",
"self",
",",
"command",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"_ipmitool_path",
"]",
"+",
"self",
".",
"args",
"+",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stder... | Use the subprocess module to execute ipmitool commands
and and set status | [
"Use",
"the",
"subprocess",
"module",
"to",
"execute",
"ipmitool",
"commands",
"and",
"and",
"set",
"status"
] | train | https://github.com/raags/ipmitool/blob/830081623c0ec75d560123a559f0bb201f26cde6/ipmi/ipmi.py#L77-L83 |
raags/ipmitool | ipmi/ipmi.py | ipmitool._expect_method | def _expect_method(self, command):
"""Use the expect module to execute ipmitool commands
and set status
"""
child = pexpect.spawn(self._ipmitool_path, self.args + command)
i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10)
if i == 0:
child.terminate()
self.error = 'ipmitool command timed out'
self.status = 1
else:
child.sendline(self.password)
i = child.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=10)
if i == 0:
child.terminate()
self.error = 'ipmitool command timed out'
self.status = 1
else:
if child.exitstatus:
self.error = child.before
else:
self.output = child.before
self.status = child.exitstatus
child.close() | python | def _expect_method(self, command):
"""Use the expect module to execute ipmitool commands
and set status
"""
child = pexpect.spawn(self._ipmitool_path, self.args + command)
i = child.expect([pexpect.TIMEOUT, 'Password: '], timeout=10)
if i == 0:
child.terminate()
self.error = 'ipmitool command timed out'
self.status = 1
else:
child.sendline(self.password)
i = child.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=10)
if i == 0:
child.terminate()
self.error = 'ipmitool command timed out'
self.status = 1
else:
if child.exitstatus:
self.error = child.before
else:
self.output = child.before
self.status = child.exitstatus
child.close() | [
"def",
"_expect_method",
"(",
"self",
",",
"command",
")",
":",
"child",
"=",
"pexpect",
".",
"spawn",
"(",
"self",
".",
"_ipmitool_path",
",",
"self",
".",
"args",
"+",
"command",
")",
"i",
"=",
"child",
".",
"expect",
"(",
"[",
"pexpect",
".",
"TIM... | Use the expect module to execute ipmitool commands
and set status | [
"Use",
"the",
"expect",
"module",
"to",
"execute",
"ipmitool",
"commands",
"and",
"set",
"status"
] | train | https://github.com/raags/ipmitool/blob/830081623c0ec75d560123a559f0bb201f26cde6/ipmi/ipmi.py#L85-L111 |
raags/ipmitool | ipmi/ipmi.py | ipmitool._get_ipmitool_path | def _get_ipmitool_path(self, cmd='ipmitool'):
"""Get full path to the ipmitool command using the unix
`which` command
"""
p = subprocess.Popen(["which", cmd],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out.strip() | python | def _get_ipmitool_path(self, cmd='ipmitool'):
"""Get full path to the ipmitool command using the unix
`which` command
"""
p = subprocess.Popen(["which", cmd],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return out.strip() | [
"def",
"_get_ipmitool_path",
"(",
"self",
",",
"cmd",
"=",
"'ipmitool'",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"which\"",
",",
"cmd",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE... | Get full path to the ipmitool command using the unix
`which` command | [
"Get",
"full",
"path",
"to",
"the",
"ipmitool",
"command",
"using",
"the",
"unix",
"which",
"command"
] | train | https://github.com/raags/ipmitool/blob/830081623c0ec75d560123a559f0bb201f26cde6/ipmi/ipmi.py#L113-L120 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/remove.py | Remove.truncate | def truncate(self, table):
"""Empty a table by deleting all of its rows."""
if isinstance(table, (list, set, tuple)):
for t in table:
self._truncate(t)
else:
self._truncate(table) | python | def truncate(self, table):
"""Empty a table by deleting all of its rows."""
if isinstance(table, (list, set, tuple)):
for t in table:
self._truncate(t)
else:
self._truncate(table) | [
"def",
"truncate",
"(",
"self",
",",
"table",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"for",
"t",
"in",
"table",
":",
"self",
".",
"_truncate",
"(",
"t",
")",
"else",
":",
"self",
"... | Empty a table by deleting all of its rows. | [
"Empty",
"a",
"table",
"by",
"deleting",
"all",
"of",
"its",
"rows",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L5-L11 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/remove.py | Remove._truncate | def _truncate(self, table):
"""
Remove all records from a table in MySQL
It performs the same function as a DELETE statement without a WHERE clause.
"""
statement = "TRUNCATE TABLE {0}".format(wrap(table))
self.execute(statement)
self._printer('\tTruncated table {0}'.format(table)) | python | def _truncate(self, table):
"""
Remove all records from a table in MySQL
It performs the same function as a DELETE statement without a WHERE clause.
"""
statement = "TRUNCATE TABLE {0}".format(wrap(table))
self.execute(statement)
self._printer('\tTruncated table {0}'.format(table)) | [
"def",
"_truncate",
"(",
"self",
",",
"table",
")",
":",
"statement",
"=",
"\"TRUNCATE TABLE {0}\"",
".",
"format",
"(",
"wrap",
"(",
"table",
")",
")",
"self",
".",
"execute",
"(",
"statement",
")",
"self",
".",
"_printer",
"(",
"'\\tTruncated table {0}'",
... | Remove all records from a table in MySQL
It performs the same function as a DELETE statement without a WHERE clause. | [
"Remove",
"all",
"records",
"from",
"a",
"table",
"in",
"MySQL"
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L13-L21 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/remove.py | Remove.truncate_database | def truncate_database(self, database=None):
"""Drop all tables in a database."""
# Change database if needed
if database in self.databases and database is not self.database:
self.change_db(database)
# Get list of tables
tables = self.tables if isinstance(self.tables, list) else [self.tables]
if len(tables) > 0:
self.drop(tables)
self._printer('\t' + str(len(tables)), 'tables truncated from', database)
return tables | python | def truncate_database(self, database=None):
"""Drop all tables in a database."""
# Change database if needed
if database in self.databases and database is not self.database:
self.change_db(database)
# Get list of tables
tables = self.tables if isinstance(self.tables, list) else [self.tables]
if len(tables) > 0:
self.drop(tables)
self._printer('\t' + str(len(tables)), 'tables truncated from', database)
return tables | [
"def",
"truncate_database",
"(",
"self",
",",
"database",
"=",
"None",
")",
":",
"# Change database if needed",
"if",
"database",
"in",
"self",
".",
"databases",
"and",
"database",
"is",
"not",
"self",
".",
"database",
":",
"self",
".",
"change_db",
"(",
"da... | Drop all tables in a database. | [
"Drop",
"all",
"tables",
"in",
"a",
"database",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L23-L34 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/remove.py | Remove.drop | def drop(self, table):
"""
Drop a table from a database.
Accepts either a string representing a table name or a list of strings
representing a table names.
"""
existing_tables = self.tables
if isinstance(table, (list, set, tuple)):
for t in table:
self._drop(t, existing_tables)
else:
self._drop(table, existing_tables)
return table | python | def drop(self, table):
"""
Drop a table from a database.
Accepts either a string representing a table name or a list of strings
representing a table names.
"""
existing_tables = self.tables
if isinstance(table, (list, set, tuple)):
for t in table:
self._drop(t, existing_tables)
else:
self._drop(table, existing_tables)
return table | [
"def",
"drop",
"(",
"self",
",",
"table",
")",
":",
"existing_tables",
"=",
"self",
".",
"tables",
"if",
"isinstance",
"(",
"table",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"for",
"t",
"in",
"table",
":",
"self",
".",
"_drop",
... | Drop a table from a database.
Accepts either a string representing a table name or a list of strings
representing a table names. | [
"Drop",
"a",
"table",
"from",
"a",
"database",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L36-L49 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/remove.py | Remove._drop | def _drop(self, table, existing_tables=None):
"""Private method for executing table drop commands."""
# Retrieve list of existing tables for comparison
existing_tables = existing_tables if existing_tables else self.tables
# Only drop table if it exists
if table in existing_tables:
# Set to avoid foreign key errorrs
self.execute('SET FOREIGN_KEY_CHECKS = 0')
query = 'DROP TABLE {0}'.format(wrap(table))
self.execute(query)
# Set again
self.execute('SET FOREIGN_KEY_CHECKS = 1')
self._printer('\tDropped table {0}'.format(table)) | python | def _drop(self, table, existing_tables=None):
"""Private method for executing table drop commands."""
# Retrieve list of existing tables for comparison
existing_tables = existing_tables if existing_tables else self.tables
# Only drop table if it exists
if table in existing_tables:
# Set to avoid foreign key errorrs
self.execute('SET FOREIGN_KEY_CHECKS = 0')
query = 'DROP TABLE {0}'.format(wrap(table))
self.execute(query)
# Set again
self.execute('SET FOREIGN_KEY_CHECKS = 1')
self._printer('\tDropped table {0}'.format(table)) | [
"def",
"_drop",
"(",
"self",
",",
"table",
",",
"existing_tables",
"=",
"None",
")",
":",
"# Retrieve list of existing tables for comparison",
"existing_tables",
"=",
"existing_tables",
"if",
"existing_tables",
"else",
"self",
".",
"tables",
"# Only drop table if it exist... | Private method for executing table drop commands. | [
"Private",
"method",
"for",
"executing",
"table",
"drop",
"commands",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L51-L66 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/remove.py | Remove.drop_empty_tables | def drop_empty_tables(self):
"""Drop all empty tables in a database."""
# Count number of rows in each table
counts = self.count_rows_all()
drops = []
# Loop through each table key and validate that rows count is not 0
for table, count in counts.items():
if count < 1:
# Drop table if it contains no rows
self.drop(table)
drops.append(table)
return drops | python | def drop_empty_tables(self):
"""Drop all empty tables in a database."""
# Count number of rows in each table
counts = self.count_rows_all()
drops = []
# Loop through each table key and validate that rows count is not 0
for table, count in counts.items():
if count < 1:
# Drop table if it contains no rows
self.drop(table)
drops.append(table)
return drops | [
"def",
"drop_empty_tables",
"(",
"self",
")",
":",
"# Count number of rows in each table",
"counts",
"=",
"self",
".",
"count_rows_all",
"(",
")",
"drops",
"=",
"[",
"]",
"# Loop through each table key and validate that rows count is not 0",
"for",
"table",
",",
"count",
... | Drop all empty tables in a database. | [
"Drop",
"all",
"empty",
"tables",
"in",
"a",
"database",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L68-L80 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/manipulate/update.py | Update.update | def update(self, table, columns, values, where):
"""
Update the values of a particular row where a value is met.
:param table: table name
:param columns: column(s) to update
:param values: updated values
:param where: tuple, (where_column, where_value)
"""
# Unpack WHERE clause dictionary into tuple
where_col, where_val = where
# Create column string from list of values
cols = get_col_val_str(columns, query_type='update')
# Concatenate statement
statement = "UPDATE {0} SET {1} WHERE {2}='{3}'".format(wrap(table), cols, where_col, where_val)
# Execute statement
self._cursor.execute(statement, values)
self._printer('\tMySQL cols (' + str(len(values)) + ') successfully UPDATED') | python | def update(self, table, columns, values, where):
"""
Update the values of a particular row where a value is met.
:param table: table name
:param columns: column(s) to update
:param values: updated values
:param where: tuple, (where_column, where_value)
"""
# Unpack WHERE clause dictionary into tuple
where_col, where_val = where
# Create column string from list of values
cols = get_col_val_str(columns, query_type='update')
# Concatenate statement
statement = "UPDATE {0} SET {1} WHERE {2}='{3}'".format(wrap(table), cols, where_col, where_val)
# Execute statement
self._cursor.execute(statement, values)
self._printer('\tMySQL cols (' + str(len(values)) + ') successfully UPDATED') | [
"def",
"update",
"(",
"self",
",",
"table",
",",
"columns",
",",
"values",
",",
"where",
")",
":",
"# Unpack WHERE clause dictionary into tuple",
"where_col",
",",
"where_val",
"=",
"where",
"# Create column string from list of values",
"cols",
"=",
"get_col_val_str",
... | Update the values of a particular row where a value is met.
:param table: table name
:param columns: column(s) to update
:param values: updated values
:param where: tuple, (where_column, where_value) | [
"Update",
"the",
"values",
"of",
"a",
"particular",
"row",
"where",
"a",
"value",
"is",
"met",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/update.py#L5-L25 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/manipulate/update.py | Update.update_many | def update_many(self, table, columns, values, where_col, where_index):
"""
Update the values of several rows.
:param table: Name of the MySQL table
:param columns: List of columns
:param values: 2D list of rows
:param where_col: Column name for where clause
:param where_index: Row index of value to be used for where comparison
:return:
"""
for row in values:
wi = row.pop(where_index)
self.update(table, columns, row, (where_col, wi)) | python | def update_many(self, table, columns, values, where_col, where_index):
"""
Update the values of several rows.
:param table: Name of the MySQL table
:param columns: List of columns
:param values: 2D list of rows
:param where_col: Column name for where clause
:param where_index: Row index of value to be used for where comparison
:return:
"""
for row in values:
wi = row.pop(where_index)
self.update(table, columns, row, (where_col, wi)) | [
"def",
"update_many",
"(",
"self",
",",
"table",
",",
"columns",
",",
"values",
",",
"where_col",
",",
"where_index",
")",
":",
"for",
"row",
"in",
"values",
":",
"wi",
"=",
"row",
".",
"pop",
"(",
"where_index",
")",
"self",
".",
"update",
"(",
"tab... | Update the values of several rows.
:param table: Name of the MySQL table
:param columns: List of columns
:param values: 2D list of rows
:param where_col: Column name for where clause
:param where_index: Row index of value to be used for where comparison
:return: | [
"Update",
"the",
"values",
"of",
"several",
"rows",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/manipulate/update.py#L27-L40 |
PGower/PyCanvas | pycanvas/apis/grading_standards.py | GradingStandardsAPI.create_new_grading_standard_accounts | def create_new_grading_standard_accounts(self, title, account_id, grading_scheme_entry_name, grading_scheme_entry_value):
"""
Create a new grading standard.
Create a new grading standard
If grading_scheme_entry arguments are omitted, then a default grading scheme
will be set. The default scheme is as follows:
"A" : 94,
"A-" : 90,
"B+" : 87,
"B" : 84,
"B-" : 80,
"C+" : 77,
"C" : 74,
"C-" : 70,
"D+" : 67,
"D" : 64,
"D-" : 61,
"F" : 0,
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - title
"""The title for the Grading Standard."""
data["title"] = title
# REQUIRED - grading_scheme_entry[name]
"""The name for an entry value within a GradingStandard that describes the range of the value
e.g. A-"""
data["grading_scheme_entry[name]"] = grading_scheme_entry_name
# REQUIRED - grading_scheme_entry[value]
"""The value for the name of the entry within a GradingStandard.
The entry represents the lower bound of the range for the entry.
This range includes the value up to the next entry in the GradingStandard,
or 100 if there is no upper bound. The lowest value will have a lower bound range of 0.
e.g. 93"""
data["grading_scheme_entry[value]"] = grading_scheme_entry_value
self.logger.debug("POST /api/v1/accounts/{account_id}/grading_standards with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/grading_standards".format(**path), data=data, params=params, single_item=True) | python | def create_new_grading_standard_accounts(self, title, account_id, grading_scheme_entry_name, grading_scheme_entry_value):
"""
Create a new grading standard.
Create a new grading standard
If grading_scheme_entry arguments are omitted, then a default grading scheme
will be set. The default scheme is as follows:
"A" : 94,
"A-" : 90,
"B+" : 87,
"B" : 84,
"B-" : 80,
"C+" : 77,
"C" : 74,
"C-" : 70,
"D+" : 67,
"D" : 64,
"D-" : 61,
"F" : 0,
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - title
"""The title for the Grading Standard."""
data["title"] = title
# REQUIRED - grading_scheme_entry[name]
"""The name for an entry value within a GradingStandard that describes the range of the value
e.g. A-"""
data["grading_scheme_entry[name]"] = grading_scheme_entry_name
# REQUIRED - grading_scheme_entry[value]
"""The value for the name of the entry within a GradingStandard.
The entry represents the lower bound of the range for the entry.
This range includes the value up to the next entry in the GradingStandard,
or 100 if there is no upper bound. The lowest value will have a lower bound range of 0.
e.g. 93"""
data["grading_scheme_entry[value]"] = grading_scheme_entry_value
self.logger.debug("POST /api/v1/accounts/{account_id}/grading_standards with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/grading_standards".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_new_grading_standard_accounts",
"(",
"self",
",",
"title",
",",
"account_id",
",",
"grading_scheme_entry_name",
",",
"grading_scheme_entry_value",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - ... | Create a new grading standard.
Create a new grading standard
If grading_scheme_entry arguments are omitted, then a default grading scheme
will be set. The default scheme is as follows:
"A" : 94,
"A-" : 90,
"B+" : 87,
"B" : 84,
"B-" : 80,
"C+" : 77,
"C" : 74,
"C-" : 70,
"D+" : 67,
"D" : 64,
"D-" : 61,
"F" : 0, | [
"Create",
"a",
"new",
"grading",
"standard",
".",
"Create",
"a",
"new",
"grading",
"standard",
"If",
"grading_scheme_entry",
"arguments",
"are",
"omitted",
"then",
"a",
"default",
"grading",
"scheme",
"will",
"be",
"set",
".",
"The",
"default",
"scheme",
"is",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/grading_standards.py#L19-L66 |
PGower/PyCanvas | pycanvas/apis/grading_standards.py | GradingStandardsAPI.create_new_grading_standard_courses | def create_new_grading_standard_courses(self, title, course_id, grading_scheme_entry_name, grading_scheme_entry_value):
"""
Create a new grading standard.
Create a new grading standard
If grading_scheme_entry arguments are omitted, then a default grading scheme
will be set. The default scheme is as follows:
"A" : 94,
"A-" : 90,
"B+" : 87,
"B" : 84,
"B-" : 80,
"C+" : 77,
"C" : 74,
"C-" : 70,
"D+" : 67,
"D" : 64,
"D-" : 61,
"F" : 0,
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - title
"""The title for the Grading Standard."""
data["title"] = title
# REQUIRED - grading_scheme_entry[name]
"""The name for an entry value within a GradingStandard that describes the range of the value
e.g. A-"""
data["grading_scheme_entry[name]"] = grading_scheme_entry_name
# REQUIRED - grading_scheme_entry[value]
"""The value for the name of the entry within a GradingStandard.
The entry represents the lower bound of the range for the entry.
This range includes the value up to the next entry in the GradingStandard,
or 100 if there is no upper bound. The lowest value will have a lower bound range of 0.
e.g. 93"""
data["grading_scheme_entry[value]"] = grading_scheme_entry_value
self.logger.debug("POST /api/v1/courses/{course_id}/grading_standards with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/grading_standards".format(**path), data=data, params=params, single_item=True) | python | def create_new_grading_standard_courses(self, title, course_id, grading_scheme_entry_name, grading_scheme_entry_value):
"""
Create a new grading standard.
Create a new grading standard
If grading_scheme_entry arguments are omitted, then a default grading scheme
will be set. The default scheme is as follows:
"A" : 94,
"A-" : 90,
"B+" : 87,
"B" : 84,
"B-" : 80,
"C+" : 77,
"C" : 74,
"C-" : 70,
"D+" : 67,
"D" : 64,
"D-" : 61,
"F" : 0,
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - title
"""The title for the Grading Standard."""
data["title"] = title
# REQUIRED - grading_scheme_entry[name]
"""The name for an entry value within a GradingStandard that describes the range of the value
e.g. A-"""
data["grading_scheme_entry[name]"] = grading_scheme_entry_name
# REQUIRED - grading_scheme_entry[value]
"""The value for the name of the entry within a GradingStandard.
The entry represents the lower bound of the range for the entry.
This range includes the value up to the next entry in the GradingStandard,
or 100 if there is no upper bound. The lowest value will have a lower bound range of 0.
e.g. 93"""
data["grading_scheme_entry[value]"] = grading_scheme_entry_value
self.logger.debug("POST /api/v1/courses/{course_id}/grading_standards with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/courses/{course_id}/grading_standards".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_new_grading_standard_courses",
"(",
"self",
",",
"title",
",",
"course_id",
",",
"grading_scheme_entry_name",
",",
"grading_scheme_entry_value",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - co... | Create a new grading standard.
Create a new grading standard
If grading_scheme_entry arguments are omitted, then a default grading scheme
will be set. The default scheme is as follows:
"A" : 94,
"A-" : 90,
"B+" : 87,
"B" : 84,
"B-" : 80,
"C+" : 77,
"C" : 74,
"C-" : 70,
"D+" : 67,
"D" : 64,
"D-" : 61,
"F" : 0, | [
"Create",
"a",
"new",
"grading",
"standard",
".",
"Create",
"a",
"new",
"grading",
"standard",
"If",
"grading_scheme_entry",
"arguments",
"are",
"omitted",
"then",
"a",
"default",
"grading",
"scheme",
"will",
"be",
"set",
".",
"The",
"default",
"scheme",
"is",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/grading_standards.py#L68-L115 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.list_groups_available_in_context_accounts | def list_groups_available_in_context_accounts(self, account_id, include=None, only_own_groups=None):
"""
List the groups available in a context.
Returns the list of active groups in the given context that are visible to user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - only_own_groups
"""Will only include groups that the user belongs to if this is set"""
if only_own_groups is not None:
params["only_own_groups"] = only_own_groups
# OPTIONAL - include
"""- "tabs": Include the list of tabs configured for each group. See the
{api:TabsController#index List available tabs API} for more information."""
if include is not None:
self._validate_enum(include, ["tabs"])
params["include"] = include
self.logger.debug("GET /api/v1/accounts/{account_id}/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/groups".format(**path), data=data, params=params, all_pages=True) | python | def list_groups_available_in_context_accounts(self, account_id, include=None, only_own_groups=None):
"""
List the groups available in a context.
Returns the list of active groups in the given context that are visible to user.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# OPTIONAL - only_own_groups
"""Will only include groups that the user belongs to if this is set"""
if only_own_groups is not None:
params["only_own_groups"] = only_own_groups
# OPTIONAL - include
"""- "tabs": Include the list of tabs configured for each group. See the
{api:TabsController#index List available tabs API} for more information."""
if include is not None:
self._validate_enum(include, ["tabs"])
params["include"] = include
self.logger.debug("GET /api/v1/accounts/{account_id}/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/groups".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_groups_available_in_context_accounts",
"(",
"self",
",",
"account_id",
",",
"include",
"=",
"None",
",",
"only_own_groups",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_... | List the groups available in a context.
Returns the list of active groups in the given context that are visible to user. | [
"List",
"the",
"groups",
"available",
"in",
"a",
"context",
".",
"Returns",
"the",
"list",
"of",
"active",
"groups",
"in",
"the",
"given",
"context",
"that",
"are",
"visible",
"to",
"user",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L45-L72 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.create_group_groups | def create_group_groups(self, description=None, is_public=None, join_level=None, name=None, storage_quota_mb=None):
"""
Create a group.
Creates a new group. Groups created using the "/api/v1/groups/"
endpoint will be community groups.
"""
path = {}
data = {}
params = {}
# OPTIONAL - name
"""The name of the group"""
if name is not None:
data["name"] = name
# OPTIONAL - description
"""A description of the group"""
if description is not None:
data["description"] = description
# OPTIONAL - is_public
"""whether the group is public (applies only to community groups)"""
if is_public is not None:
data["is_public"] = is_public
# OPTIONAL - join_level
"""no description"""
if join_level is not None:
self._validate_enum(join_level, ["parent_context_auto_join", "parent_context_request", "invitation_only"])
data["join_level"] = join_level
# OPTIONAL - storage_quota_mb
"""The allowed file storage for the group, in megabytes. This parameter is
ignored if the caller does not have the manage_storage_quotas permission."""
if storage_quota_mb is not None:
data["storage_quota_mb"] = storage_quota_mb
self.logger.debug("POST /api/v1/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups".format(**path), data=data, params=params, single_item=True) | python | def create_group_groups(self, description=None, is_public=None, join_level=None, name=None, storage_quota_mb=None):
"""
Create a group.
Creates a new group. Groups created using the "/api/v1/groups/"
endpoint will be community groups.
"""
path = {}
data = {}
params = {}
# OPTIONAL - name
"""The name of the group"""
if name is not None:
data["name"] = name
# OPTIONAL - description
"""A description of the group"""
if description is not None:
data["description"] = description
# OPTIONAL - is_public
"""whether the group is public (applies only to community groups)"""
if is_public is not None:
data["is_public"] = is_public
# OPTIONAL - join_level
"""no description"""
if join_level is not None:
self._validate_enum(join_level, ["parent_context_auto_join", "parent_context_request", "invitation_only"])
data["join_level"] = join_level
# OPTIONAL - storage_quota_mb
"""The allowed file storage for the group, in megabytes. This parameter is
ignored if the caller does not have the manage_storage_quotas permission."""
if storage_quota_mb is not None:
data["storage_quota_mb"] = storage_quota_mb
self.logger.debug("POST /api/v1/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups".format(**path), data=data, params=params, single_item=True) | [
"def",
"create_group_groups",
"(",
"self",
",",
"description",
"=",
"None",
",",
"is_public",
"=",
"None",
",",
"join_level",
"=",
"None",
",",
"name",
"=",
"None",
",",
"storage_quota_mb",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{"... | Create a group.
Creates a new group. Groups created using the "/api/v1/groups/"
endpoint will be community groups. | [
"Create",
"a",
"group",
".",
"Creates",
"a",
"new",
"group",
".",
"Groups",
"created",
"using",
"the",
"/",
"api",
"/",
"v1",
"/",
"groups",
"/",
"endpoint",
"will",
"be",
"community",
"groups",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L130-L169 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.edit_group | def edit_group(self, group_id, avatar_id=None, description=None, is_public=None, join_level=None, members=None, name=None, storage_quota_mb=None):
"""
Edit a group.
Modifies an existing group. Note that to set an avatar image for the
group, you must first upload the image file to the group, and the use the
id in the response as the argument to this function. See the
{file:file_uploads.html File Upload Documentation} for details on the file
upload workflow.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - name
"""The name of the group"""
if name is not None:
data["name"] = name
# OPTIONAL - description
"""A description of the group"""
if description is not None:
data["description"] = description
# OPTIONAL - is_public
"""Whether the group is public (applies only to community groups). Currently
you cannot set a group back to private once it has been made public."""
if is_public is not None:
data["is_public"] = is_public
# OPTIONAL - join_level
"""no description"""
if join_level is not None:
self._validate_enum(join_level, ["parent_context_auto_join", "parent_context_request", "invitation_only"])
data["join_level"] = join_level
# OPTIONAL - avatar_id
"""The id of the attachment previously uploaded to the group that you would
like to use as the avatar image for this group."""
if avatar_id is not None:
data["avatar_id"] = avatar_id
# OPTIONAL - storage_quota_mb
"""The allowed file storage for the group, in megabytes. This parameter is
ignored if the caller does not have the manage_storage_quotas permission."""
if storage_quota_mb is not None:
data["storage_quota_mb"] = storage_quota_mb
# OPTIONAL - members
"""An array of user ids for users you would like in the group.
Users not in the group will be sent invitations. Existing group
members who aren't in the list will be removed from the group."""
if members is not None:
data["members"] = members
self.logger.debug("PUT /api/v1/groups/{group_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/groups/{group_id}".format(**path), data=data, params=params, single_item=True) | python | def edit_group(self, group_id, avatar_id=None, description=None, is_public=None, join_level=None, members=None, name=None, storage_quota_mb=None):
"""
Edit a group.
Modifies an existing group. Note that to set an avatar image for the
group, you must first upload the image file to the group, and the use the
id in the response as the argument to this function. See the
{file:file_uploads.html File Upload Documentation} for details on the file
upload workflow.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - name
"""The name of the group"""
if name is not None:
data["name"] = name
# OPTIONAL - description
"""A description of the group"""
if description is not None:
data["description"] = description
# OPTIONAL - is_public
"""Whether the group is public (applies only to community groups). Currently
you cannot set a group back to private once it has been made public."""
if is_public is not None:
data["is_public"] = is_public
# OPTIONAL - join_level
"""no description"""
if join_level is not None:
self._validate_enum(join_level, ["parent_context_auto_join", "parent_context_request", "invitation_only"])
data["join_level"] = join_level
# OPTIONAL - avatar_id
"""The id of the attachment previously uploaded to the group that you would
like to use as the avatar image for this group."""
if avatar_id is not None:
data["avatar_id"] = avatar_id
# OPTIONAL - storage_quota_mb
"""The allowed file storage for the group, in megabytes. This parameter is
ignored if the caller does not have the manage_storage_quotas permission."""
if storage_quota_mb is not None:
data["storage_quota_mb"] = storage_quota_mb
# OPTIONAL - members
"""An array of user ids for users you would like in the group.
Users not in the group will be sent invitations. Existing group
members who aren't in the list will be removed from the group."""
if members is not None:
data["members"] = members
self.logger.debug("PUT /api/v1/groups/{group_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/groups/{group_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"edit_group",
"(",
"self",
",",
"group_id",
",",
"avatar_id",
"=",
"None",
",",
"description",
"=",
"None",
",",
"is_public",
"=",
"None",
",",
"join_level",
"=",
"None",
",",
"members",
"=",
"None",
",",
"name",
"=",
"None",
",",
"storage_quota_m... | Edit a group.
Modifies an existing group. Note that to set an avatar image for the
group, you must first upload the image file to the group, and the use the
id in the response as the argument to this function. See the
{file:file_uploads.html File Upload Documentation} for details on the file
upload workflow. | [
"Edit",
"a",
"group",
".",
"Modifies",
"an",
"existing",
"group",
".",
"Note",
"that",
"to",
"set",
"an",
"avatar",
"image",
"for",
"the",
"group",
"you",
"must",
"first",
"upload",
"the",
"image",
"file",
"to",
"the",
"group",
"and",
"the",
"use",
"th... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L216-L276 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.invite_others_to_group | def invite_others_to_group(self, group_id, invitees):
"""
Invite others to a group.
Sends an invitation to all supplied email addresses which will allow the
receivers to join the group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - invitees
"""An array of email addresses to be sent invitations."""
data["invitees"] = invitees
self.logger.debug("POST /api/v1/groups/{group_id}/invite with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/invite".format(**path), data=data, params=params, no_data=True) | python | def invite_others_to_group(self, group_id, invitees):
"""
Invite others to a group.
Sends an invitation to all supplied email addresses which will allow the
receivers to join the group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - invitees
"""An array of email addresses to be sent invitations."""
data["invitees"] = invitees
self.logger.debug("POST /api/v1/groups/{group_id}/invite with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/invite".format(**path), data=data, params=params, no_data=True) | [
"def",
"invite_others_to_group",
"(",
"self",
",",
"group_id",
",",
"invitees",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
"group... | Invite others to a group.
Sends an invitation to all supplied email addresses which will allow the
receivers to join the group. | [
"Invite",
"others",
"to",
"a",
"group",
".",
"Sends",
"an",
"invitation",
"to",
"all",
"supplied",
"email",
"addresses",
"which",
"will",
"allow",
"the",
"receivers",
"to",
"join",
"the",
"group",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L295-L315 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.list_group_s_users | def list_group_s_users(self, group_id, include=None, search_term=None):
"""
List group's users.
Returns a list of users in the group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - search_term
"""The partial name or full ID of the users to match and return in the
results list. Must be at least 3 characters."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - include
"""- "avatar_url": Include users' avatar_urls."""
if include is not None:
self._validate_enum(include, ["avatar_url"])
params["include"] = include
self.logger.debug("GET /api/v1/groups/{group_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/users".format(**path), data=data, params=params, all_pages=True) | python | def list_group_s_users(self, group_id, include=None, search_term=None):
"""
List group's users.
Returns a list of users in the group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - search_term
"""The partial name or full ID of the users to match and return in the
results list. Must be at least 3 characters."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - include
"""- "avatar_url": Include users' avatar_urls."""
if include is not None:
self._validate_enum(include, ["avatar_url"])
params["include"] = include
self.logger.debug("GET /api/v1/groups/{group_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/users".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_group_s_users",
"(",
"self",
",",
"group_id",
",",
"include",
"=",
"None",
",",
"search_term",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"p... | List group's users.
Returns a list of users in the group. | [
"List",
"group",
"s",
"users",
".",
"Returns",
"a",
"list",
"of",
"users",
"in",
"the",
"group",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L317-L344 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.preview_processed_html | def preview_processed_html(self, group_id, html=None):
"""
Preview processed html.
Preview html content processed for this group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - html
"""The html content to process"""
if html is not None:
data["html"] = html
self.logger.debug("POST /api/v1/groups/{group_id}/preview_html with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/preview_html".format(**path), data=data, params=params, no_data=True) | python | def preview_processed_html(self, group_id, html=None):
"""
Preview processed html.
Preview html content processed for this group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - html
"""The html content to process"""
if html is not None:
data["html"] = html
self.logger.debug("POST /api/v1/groups/{group_id}/preview_html with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/groups/{group_id}/preview_html".format(**path), data=data, params=params, no_data=True) | [
"def",
"preview_processed_html",
"(",
"self",
",",
"group_id",
",",
"html",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
... | Preview processed html.
Preview html content processed for this group | [
"Preview",
"processed",
"html",
".",
"Preview",
"html",
"content",
"processed",
"for",
"this",
"group"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L371-L391 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.list_group_memberships | def list_group_memberships(self, group_id, filter_states=None):
"""
List group memberships.
List the members of a group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - filter_states
"""Only list memberships with the given workflow_states. By default it will
return all memberships."""
if filter_states is not None:
self._validate_enum(filter_states, ["accepted", "invited", "requested"])
params["filter_states"] = filter_states
self.logger.debug("GET /api/v1/groups/{group_id}/memberships with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/memberships".format(**path), data=data, params=params, all_pages=True) | python | def list_group_memberships(self, group_id, filter_states=None):
"""
List group memberships.
List the members of a group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - filter_states
"""Only list memberships with the given workflow_states. By default it will
return all memberships."""
if filter_states is not None:
self._validate_enum(filter_states, ["accepted", "invited", "requested"])
params["filter_states"] = filter_states
self.logger.debug("GET /api/v1/groups/{group_id}/memberships with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/memberships".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_group_memberships",
"(",
"self",
",",
"group_id",
",",
"filter_states",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
... | List group memberships.
List the members of a group. | [
"List",
"group",
"memberships",
".",
"List",
"the",
"members",
"of",
"a",
"group",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L433-L455 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.get_single_group_membership_memberships | def get_single_group_membership_memberships(self, group_id, membership_id):
"""
Get a single group membership.
Returns the group membership with the given membership id or user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - membership_id
"""ID"""
path["membership_id"] = membership_id
self.logger.debug("GET /api/v1/groups/{group_id}/memberships/{membership_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/memberships/{membership_id}".format(**path), data=data, params=params, single_item=True) | python | def get_single_group_membership_memberships(self, group_id, membership_id):
"""
Get a single group membership.
Returns the group membership with the given membership id or user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - membership_id
"""ID"""
path["membership_id"] = membership_id
self.logger.debug("GET /api/v1/groups/{group_id}/memberships/{membership_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/memberships/{membership_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"get_single_group_membership_memberships",
"(",
"self",
",",
"group_id",
",",
"membership_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
... | Get a single group membership.
Returns the group membership with the given membership id or user id. | [
"Get",
"a",
"single",
"group",
"membership",
".",
"Returns",
"the",
"group",
"membership",
"with",
"the",
"given",
"membership",
"id",
"or",
"user",
"id",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L457-L476 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.get_single_group_membership_users | def get_single_group_membership_users(self, user_id, group_id):
"""
Get a single group membership.
Returns the group membership with the given membership id or user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("GET /api/v1/groups/{group_id}/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/users/{user_id}".format(**path), data=data, params=params, single_item=True) | python | def get_single_group_membership_users(self, user_id, group_id):
"""
Get a single group membership.
Returns the group membership with the given membership id or user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("GET /api/v1/groups/{group_id}/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/users/{user_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"get_single_group_membership_users",
"(",
"self",
",",
"user_id",
",",
"group_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"="... | Get a single group membership.
Returns the group membership with the given membership id or user id. | [
"Get",
"a",
"single",
"group",
"membership",
".",
"Returns",
"the",
"group",
"membership",
"with",
"the",
"given",
"membership",
"id",
"or",
"user",
"id",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L478-L497 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.update_membership_memberships | def update_membership_memberships(self, group_id, membership_id, moderator=None, workflow_state=None):
"""
Update a membership.
Accept a membership request, or add/remove moderator rights.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - membership_id
"""ID"""
path["membership_id"] = membership_id
# OPTIONAL - workflow_state
"""Currently, the only allowed value is "accepted""""
if workflow_state is not None:
self._validate_enum(workflow_state, ["accepted"])
data["workflow_state"] = workflow_state
# OPTIONAL - moderator
"""no description"""
if moderator is not None:
data["moderator"] = moderator
self.logger.debug("PUT /api/v1/groups/{group_id}/memberships/{membership_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/groups/{group_id}/memberships/{membership_id}".format(**path), data=data, params=params, single_item=True) | python | def update_membership_memberships(self, group_id, membership_id, moderator=None, workflow_state=None):
"""
Update a membership.
Accept a membership request, or add/remove moderator rights.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - membership_id
"""ID"""
path["membership_id"] = membership_id
# OPTIONAL - workflow_state
"""Currently, the only allowed value is "accepted""""
if workflow_state is not None:
self._validate_enum(workflow_state, ["accepted"])
data["workflow_state"] = workflow_state
# OPTIONAL - moderator
"""no description"""
if moderator is not None:
data["moderator"] = moderator
self.logger.debug("PUT /api/v1/groups/{group_id}/memberships/{membership_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/groups/{group_id}/memberships/{membership_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"update_membership_memberships",
"(",
"self",
",",
"group_id",
",",
"membership_id",
",",
"moderator",
"=",
"None",
",",
"workflow_state",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PA... | Update a membership.
Accept a membership request, or add/remove moderator rights. | [
"Update",
"a",
"membership",
".",
"Accept",
"a",
"membership",
"request",
"or",
"add",
"/",
"remove",
"moderator",
"rights",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L523-L553 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.update_membership_users | def update_membership_users(self, user_id, group_id, moderator=None, workflow_state=None):
"""
Update a membership.
Accept a membership request, or add/remove moderator rights.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# OPTIONAL - workflow_state
"""Currently, the only allowed value is "accepted""""
if workflow_state is not None:
self._validate_enum(workflow_state, ["accepted"])
data["workflow_state"] = workflow_state
# OPTIONAL - moderator
"""no description"""
if moderator is not None:
data["moderator"] = moderator
self.logger.debug("PUT /api/v1/groups/{group_id}/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/groups/{group_id}/users/{user_id}".format(**path), data=data, params=params, single_item=True) | python | def update_membership_users(self, user_id, group_id, moderator=None, workflow_state=None):
"""
Update a membership.
Accept a membership request, or add/remove moderator rights.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
# OPTIONAL - workflow_state
"""Currently, the only allowed value is "accepted""""
if workflow_state is not None:
self._validate_enum(workflow_state, ["accepted"])
data["workflow_state"] = workflow_state
# OPTIONAL - moderator
"""no description"""
if moderator is not None:
data["moderator"] = moderator
self.logger.debug("PUT /api/v1/groups/{group_id}/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/groups/{group_id}/users/{user_id}".format(**path), data=data, params=params, single_item=True) | [
"def",
"update_membership_users",
"(",
"self",
",",
"user_id",
",",
"group_id",
",",
"moderator",
"=",
"None",
",",
"workflow_state",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_i... | Update a membership.
Accept a membership request, or add/remove moderator rights. | [
"Update",
"a",
"membership",
".",
"Accept",
"a",
"membership",
"request",
"or",
"add",
"/",
"remove",
"moderator",
"rights",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L555-L585 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.leave_group_memberships | def leave_group_memberships(self, group_id, membership_id):
"""
Leave a group.
Leave a group if you are allowed to leave (some groups, such as sets of
course groups created by teachers, cannot be left). You may also use 'self'
in place of a membership_id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - membership_id
"""ID"""
path["membership_id"] = membership_id
self.logger.debug("DELETE /api/v1/groups/{group_id}/memberships/{membership_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/groups/{group_id}/memberships/{membership_id}".format(**path), data=data, params=params, no_data=True) | python | def leave_group_memberships(self, group_id, membership_id):
"""
Leave a group.
Leave a group if you are allowed to leave (some groups, such as sets of
course groups created by teachers, cannot be left). You may also use 'self'
in place of a membership_id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - membership_id
"""ID"""
path["membership_id"] = membership_id
self.logger.debug("DELETE /api/v1/groups/{group_id}/memberships/{membership_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/groups/{group_id}/memberships/{membership_id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"leave_group_memberships",
"(",
"self",
",",
"group_id",
",",
"membership_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
... | Leave a group.
Leave a group if you are allowed to leave (some groups, such as sets of
course groups created by teachers, cannot be left). You may also use 'self'
in place of a membership_id. | [
"Leave",
"a",
"group",
".",
"Leave",
"a",
"group",
"if",
"you",
"are",
"allowed",
"to",
"leave",
"(",
"some",
"groups",
"such",
"as",
"sets",
"of",
"course",
"groups",
"created",
"by",
"teachers",
"cannot",
"be",
"left",
")",
".",
"You",
"may",
"also",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L587-L608 |
PGower/PyCanvas | pycanvas/apis/groups.py | GroupsAPI.leave_group_users | def leave_group_users(self, user_id, group_id):
"""
Leave a group.
Leave a group if you are allowed to leave (some groups, such as sets of
course groups created by teachers, cannot be left). You may also use 'self'
in place of a membership_id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("DELETE /api/v1/groups/{group_id}/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/groups/{group_id}/users/{user_id}".format(**path), data=data, params=params, no_data=True) | python | def leave_group_users(self, user_id, group_id):
"""
Leave a group.
Leave a group if you are allowed to leave (some groups, such as sets of
course groups created by teachers, cannot be left). You may also use 'self'
in place of a membership_id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("DELETE /api/v1/groups/{group_id}/users/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/groups/{group_id}/users/{user_id}".format(**path), data=data, params=params, no_data=True) | [
"def",
"leave_group_users",
"(",
"self",
",",
"user_id",
",",
"group_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
"group_id",
... | Leave a group.
Leave a group if you are allowed to leave (some groups, such as sets of
course groups created by teachers, cannot be left). You may also use 'self'
in place of a membership_id. | [
"Leave",
"a",
"group",
".",
"Leave",
"a",
"group",
"if",
"you",
"are",
"allowed",
"to",
"leave",
"(",
"some",
"groups",
"such",
"as",
"sets",
"of",
"course",
"groups",
"created",
"by",
"teachers",
"cannot",
"be",
"left",
")",
".",
"You",
"may",
"also",... | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/groups.py#L610-L631 |
bioasp/caspo | caspo/core/clause.py | Clause.from_str | def from_str(cls, string):
"""
Creates a clause from a given string.
Parameters
----------
string: str
A string of the form `a+!b` which translates to `a AND NOT b`.
Returns
-------
caspo.core.clause.Clause
Created object instance
"""
return cls([Literal.from_str(lit) for lit in string.split('+')]) | python | def from_str(cls, string):
"""
Creates a clause from a given string.
Parameters
----------
string: str
A string of the form `a+!b` which translates to `a AND NOT b`.
Returns
-------
caspo.core.clause.Clause
Created object instance
"""
return cls([Literal.from_str(lit) for lit in string.split('+')]) | [
"def",
"from_str",
"(",
"cls",
",",
"string",
")",
":",
"return",
"cls",
"(",
"[",
"Literal",
".",
"from_str",
"(",
"lit",
")",
"for",
"lit",
"in",
"string",
".",
"split",
"(",
"'+'",
")",
"]",
")"
] | Creates a clause from a given string.
Parameters
----------
string: str
A string of the form `a+!b` which translates to `a AND NOT b`.
Returns
-------
caspo.core.clause.Clause
Created object instance | [
"Creates",
"a",
"clause",
"from",
"a",
"given",
"string",
"."
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/clause.py#L27-L41 |
bioasp/caspo | caspo/core/clause.py | Clause.bool | def bool(self, state):
"""
Returns the Boolean evaluation of the clause with respect to a given state
Parameters
----------
state : dict
Key-value mapping describing a Boolean state or assignment
Returns
-------
boolean
The evaluation of the clause with respect to the given state or assignment
"""
value = 1
for source, sign in self:
value = value and (state[source] if sign == 1 else not state[source])
if not value:
break
return value | python | def bool(self, state):
"""
Returns the Boolean evaluation of the clause with respect to a given state
Parameters
----------
state : dict
Key-value mapping describing a Boolean state or assignment
Returns
-------
boolean
The evaluation of the clause with respect to the given state or assignment
"""
value = 1
for source, sign in self:
value = value and (state[source] if sign == 1 else not state[source])
if not value:
break
return value | [
"def",
"bool",
"(",
"self",
",",
"state",
")",
":",
"value",
"=",
"1",
"for",
"source",
",",
"sign",
"in",
"self",
":",
"value",
"=",
"value",
"and",
"(",
"state",
"[",
"source",
"]",
"if",
"sign",
"==",
"1",
"else",
"not",
"state",
"[",
"source"... | Returns the Boolean evaluation of the clause with respect to a given state
Parameters
----------
state : dict
Key-value mapping describing a Boolean state or assignment
Returns
-------
boolean
The evaluation of the clause with respect to the given state or assignment | [
"Returns",
"the",
"Boolean",
"evaluation",
"of",
"the",
"clause",
"with",
"respect",
"to",
"a",
"given",
"state"
] | train | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/clause.py#L49-L69 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/compare.py | Compare.compare_dbs | def compare_dbs(self, db_x, db_y, show=True):
"""Compare the tables and row counts of two databases."""
# TODO: Improve method
self._printer("\tComparing database's {0} and {1}".format(db_x, db_y))
# Run compare_dbs_getter to get row counts
x = self._compare_dbs_getter(db_x)
y = self._compare_dbs_getter(db_y)
x_tbl_count = len(list(x.keys()))
y_tbl_count = len(list(y.keys()))
# Check that database does not have zero tables
if x_tbl_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_x))
self._printer('\tDatabase differencing was not run')
return None
elif y_tbl_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_y))
self._printer('\tDatabase differencing was not run')
return None
# Print comparisons
if show:
uniques_x = diff(x, y, x_only=True)
if len(uniques_x) > 0:
self._printer('\nUnique keys from {0} ({1} of {2}):'.format(db_x, len(uniques_x), x_tbl_count))
self._printer('------------------------------')
# print(uniques)
for k, v in sorted(uniques_x):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
uniques_y = diff(x, y, y_only=True)
if len(uniques_y) > 0:
self._printer('Unique keys from {0} ({1} of {2}):'.format(db_y, len(uniques_y), y_tbl_count))
self._printer('------------------------------')
for k, v in sorted(uniques_y):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
if len(uniques_y) == 0 and len(uniques_y) == 0:
self._printer("Databases's {0} and {1} are identical:".format(db_x, db_y))
self._printer('------------------------------')
return diff(x, y) | python | def compare_dbs(self, db_x, db_y, show=True):
"""Compare the tables and row counts of two databases."""
# TODO: Improve method
self._printer("\tComparing database's {0} and {1}".format(db_x, db_y))
# Run compare_dbs_getter to get row counts
x = self._compare_dbs_getter(db_x)
y = self._compare_dbs_getter(db_y)
x_tbl_count = len(list(x.keys()))
y_tbl_count = len(list(y.keys()))
# Check that database does not have zero tables
if x_tbl_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_x))
self._printer('\tDatabase differencing was not run')
return None
elif y_tbl_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_y))
self._printer('\tDatabase differencing was not run')
return None
# Print comparisons
if show:
uniques_x = diff(x, y, x_only=True)
if len(uniques_x) > 0:
self._printer('\nUnique keys from {0} ({1} of {2}):'.format(db_x, len(uniques_x), x_tbl_count))
self._printer('------------------------------')
# print(uniques)
for k, v in sorted(uniques_x):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
uniques_y = diff(x, y, y_only=True)
if len(uniques_y) > 0:
self._printer('Unique keys from {0} ({1} of {2}):'.format(db_y, len(uniques_y), y_tbl_count))
self._printer('------------------------------')
for k, v in sorted(uniques_y):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
if len(uniques_y) == 0 and len(uniques_y) == 0:
self._printer("Databases's {0} and {1} are identical:".format(db_x, db_y))
self._printer('------------------------------')
return diff(x, y) | [
"def",
"compare_dbs",
"(",
"self",
",",
"db_x",
",",
"db_y",
",",
"show",
"=",
"True",
")",
":",
"# TODO: Improve method",
"self",
".",
"_printer",
"(",
"\"\\tComparing database's {0} and {1}\"",
".",
"format",
"(",
"db_x",
",",
"db_y",
")",
")",
"# Run compar... | Compare the tables and row counts of two databases. | [
"Compare",
"the",
"tables",
"and",
"row",
"counts",
"of",
"two",
"databases",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/compare.py#L5-L49 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/compare.py | Compare._compare_dbs_getter | def _compare_dbs_getter(self, db):
"""Retrieve a dictionary of table_name, row count key value pairs for a DB."""
# Change DB connection if needed
if self.database != db:
self.change_db(db)
return self.count_rows_all() | python | def _compare_dbs_getter(self, db):
"""Retrieve a dictionary of table_name, row count key value pairs for a DB."""
# Change DB connection if needed
if self.database != db:
self.change_db(db)
return self.count_rows_all() | [
"def",
"_compare_dbs_getter",
"(",
"self",
",",
"db",
")",
":",
"# Change DB connection if needed",
"if",
"self",
".",
"database",
"!=",
"db",
":",
"self",
".",
"change_db",
"(",
"db",
")",
"return",
"self",
".",
"count_rows_all",
"(",
")"
] | Retrieve a dictionary of table_name, row count key value pairs for a DB. | [
"Retrieve",
"a",
"dictionary",
"of",
"table_name",
"row",
"count",
"key",
"value",
"pairs",
"for",
"a",
"DB",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/compare.py#L51-L56 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/compare.py | Compare.compare_schemas | def compare_schemas(self, db_x, db_y, show=True):
"""
Compare the structures of two databases.
Analysis's and compares the column definitions of each table
in both databases's. Identifies differences in column names,
data types and keys.
"""
# TODO: Improve method
self._printer("\tComparing database schema's {0} and {1}".format(db_x, db_y))
# Run compare_dbs_getter to get row counts
x = self._schema_getter(db_x)
y = self._schema_getter(db_y)
x_count = len(x)
y_count = len(y)
# Check that database does not have zero tables
if x_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_x))
self._printer('\tDatabase differencing was not run')
return None
elif y_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_y))
self._printer('\tDatabase differencing was not run')
return None
# Print comparisons
if show:
uniques_x = diff(x, y, x_only=True)
if len(uniques_x) > 0:
self._printer('\nUnique keys from {0} ({1} of {2}):'.format(db_x, len(uniques_x), x_count))
self._printer('------------------------------')
# print(uniques)
for k, v in sorted(uniques_x):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
uniques_y = diff(x, y, y_only=True)
if len(uniques_y) > 0:
self._printer('Unique keys from {0} ({1} of {2}):'.format(db_y, len(uniques_y), y_count))
self._printer('------------------------------')
for k, v in sorted(uniques_y):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
if len(uniques_y) == 0 and len(uniques_y) == 0:
self._printer("Databases's {0} and {1} are identical:".format(db_x, db_y))
self._printer('------------------------------')
return diff(x, y) | python | def compare_schemas(self, db_x, db_y, show=True):
"""
Compare the structures of two databases.
Analysis's and compares the column definitions of each table
in both databases's. Identifies differences in column names,
data types and keys.
"""
# TODO: Improve method
self._printer("\tComparing database schema's {0} and {1}".format(db_x, db_y))
# Run compare_dbs_getter to get row counts
x = self._schema_getter(db_x)
y = self._schema_getter(db_y)
x_count = len(x)
y_count = len(y)
# Check that database does not have zero tables
if x_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_x))
self._printer('\tDatabase differencing was not run')
return None
elif y_count == 0:
self._printer('\tThe database {0} has no tables'.format(db_y))
self._printer('\tDatabase differencing was not run')
return None
# Print comparisons
if show:
uniques_x = diff(x, y, x_only=True)
if len(uniques_x) > 0:
self._printer('\nUnique keys from {0} ({1} of {2}):'.format(db_x, len(uniques_x), x_count))
self._printer('------------------------------')
# print(uniques)
for k, v in sorted(uniques_x):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
uniques_y = diff(x, y, y_only=True)
if len(uniques_y) > 0:
self._printer('Unique keys from {0} ({1} of {2}):'.format(db_y, len(uniques_y), y_count))
self._printer('------------------------------')
for k, v in sorted(uniques_y):
self._printer('{0:25} {1}'.format(k, v))
self._printer('\n')
if len(uniques_y) == 0 and len(uniques_y) == 0:
self._printer("Databases's {0} and {1} are identical:".format(db_x, db_y))
self._printer('------------------------------')
return diff(x, y) | [
"def",
"compare_schemas",
"(",
"self",
",",
"db_x",
",",
"db_y",
",",
"show",
"=",
"True",
")",
":",
"# TODO: Improve method",
"self",
".",
"_printer",
"(",
"\"\\tComparing database schema's {0} and {1}\"",
".",
"format",
"(",
"db_x",
",",
"db_y",
")",
")",
"#... | Compare the structures of two databases.
Analysis's and compares the column definitions of each table
in both databases's. Identifies differences in column names,
data types and keys. | [
"Compare",
"the",
"structures",
"of",
"two",
"databases",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/compare.py#L58-L108 |
mrstephenneal/mysql-toolkit | mysql/toolkit/components/operations/compare.py | Compare._schema_getter | def _schema_getter(self, db):
"""Retrieve a dictionary representing a database's data schema."""
# Change DB connection if needed
if self.database != db:
self.change_db(db)
schema_dict = {tbl: self.get_schema(tbl) for tbl in self.tables}
schema_lst = []
for table, schema in schema_dict.items():
for col in schema:
col.insert(0, table)
schema_lst.append(col)
return schema_lst | python | def _schema_getter(self, db):
"""Retrieve a dictionary representing a database's data schema."""
# Change DB connection if needed
if self.database != db:
self.change_db(db)
schema_dict = {tbl: self.get_schema(tbl) for tbl in self.tables}
schema_lst = []
for table, schema in schema_dict.items():
for col in schema:
col.insert(0, table)
schema_lst.append(col)
return schema_lst | [
"def",
"_schema_getter",
"(",
"self",
",",
"db",
")",
":",
"# Change DB connection if needed",
"if",
"self",
".",
"database",
"!=",
"db",
":",
"self",
".",
"change_db",
"(",
"db",
")",
"schema_dict",
"=",
"{",
"tbl",
":",
"self",
".",
"get_schema",
"(",
... | Retrieve a dictionary representing a database's data schema. | [
"Retrieve",
"a",
"dictionary",
"representing",
"a",
"database",
"s",
"data",
"schema",
"."
] | train | https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/compare.py#L110-L122 |
bionikspoon/cache_requests | cache_requests/memoize.py | Memoize.put_cache_results | def put_cache_results(self, key, func_akw, set_cache_cb):
"""Put function results into cache."""
args, kwargs = func_akw
# get function results
func_results = self.func(*args, **kwargs)
# optionally add results to cache
if set_cache_cb(func_results):
self[key] = func_results
return func_results | python | def put_cache_results(self, key, func_akw, set_cache_cb):
"""Put function results into cache."""
args, kwargs = func_akw
# get function results
func_results = self.func(*args, **kwargs)
# optionally add results to cache
if set_cache_cb(func_results):
self[key] = func_results
return func_results | [
"def",
"put_cache_results",
"(",
"self",
",",
"key",
",",
"func_akw",
",",
"set_cache_cb",
")",
":",
"args",
",",
"kwargs",
"=",
"func_akw",
"# get function results",
"func_results",
"=",
"self",
".",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",... | Put function results into cache. | [
"Put",
"function",
"results",
"into",
"cache",
"."
] | train | https://github.com/bionikspoon/cache_requests/blob/d75f6f944bc5a72fef5d7811e4973e124d9921dd/cache_requests/memoize.py#L97-L107 |
PGower/PyCanvas | builder.py | service_param_string | def service_param_string(params):
"""Takes a param section from a metadata class and returns a param string for the service method"""
p = []
k = []
for param in params:
name = fix_param_name(param['name'])
if 'required' in param and param['required'] is True:
p.append(name)
else:
if 'default' in param:
k.append('{name}={default}'.format(name=name, default=param['default']))
else:
k.append('{name}=None'.format(name=name))
p.sort(lambda a, b: len(a) - len(b))
k.sort()
a = p + k
return ', '.join(a) | python | def service_param_string(params):
"""Takes a param section from a metadata class and returns a param string for the service method"""
p = []
k = []
for param in params:
name = fix_param_name(param['name'])
if 'required' in param and param['required'] is True:
p.append(name)
else:
if 'default' in param:
k.append('{name}={default}'.format(name=name, default=param['default']))
else:
k.append('{name}=None'.format(name=name))
p.sort(lambda a, b: len(a) - len(b))
k.sort()
a = p + k
return ', '.join(a) | [
"def",
"service_param_string",
"(",
"params",
")",
":",
"p",
"=",
"[",
"]",
"k",
"=",
"[",
"]",
"for",
"param",
"in",
"params",
":",
"name",
"=",
"fix_param_name",
"(",
"param",
"[",
"'name'",
"]",
")",
"if",
"'required'",
"in",
"param",
"and",
"para... | Takes a param section from a metadata class and returns a param string for the service method | [
"Takes",
"a",
"param",
"section",
"from",
"a",
"metadata",
"class",
"and",
"returns",
"a",
"param",
"string",
"for",
"the",
"service",
"method"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/builder.py#L71-L87 |
PGower/PyCanvas | builder.py | build_metadata_class | def build_metadata_class(specfile):
"""Generate a metadata class for the specified specfile."""
with open(specfile) as f:
spec = json.load(f)
name = os.path.basename(specfile).split('.')[0]
spec['name'] = name
env = get_jinja_env()
metadata_template = env.get_template('metadata.py.jinja2')
with open('pycanvas/meta/{}.py'.format(name), 'w') as t:
t.write(metadata_template.render(spec=spec)) | python | def build_metadata_class(specfile):
"""Generate a metadata class for the specified specfile."""
with open(specfile) as f:
spec = json.load(f)
name = os.path.basename(specfile).split('.')[0]
spec['name'] = name
env = get_jinja_env()
metadata_template = env.get_template('metadata.py.jinja2')
with open('pycanvas/meta/{}.py'.format(name), 'w') as t:
t.write(metadata_template.render(spec=spec)) | [
"def",
"build_metadata_class",
"(",
"specfile",
")",
":",
"with",
"open",
"(",
"specfile",
")",
"as",
"f",
":",
"spec",
"=",
"json",
".",
"load",
"(",
"f",
")",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"specfile",
")",
".",
"split",
"(... | Generate a metadata class for the specified specfile. | [
"Generate",
"a",
"metadata",
"class",
"for",
"the",
"specified",
"specfile",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/builder.py#L117-L128 |
PGower/PyCanvas | builder.py | build_model_classes | def build_model_classes(metadata):
"""Generate a model class for any models contained in the specified spec file."""
i = importlib.import_module(metadata)
env = get_jinja_env()
model_template = env.get_template('model.py.jinja2')
for model in i.models:
with open(model_path(model.name.lower()), 'w') as t:
t.write(model_template.render(model_md=model)) | python | def build_model_classes(metadata):
"""Generate a model class for any models contained in the specified spec file."""
i = importlib.import_module(metadata)
env = get_jinja_env()
model_template = env.get_template('model.py.jinja2')
for model in i.models:
with open(model_path(model.name.lower()), 'w') as t:
t.write(model_template.render(model_md=model)) | [
"def",
"build_model_classes",
"(",
"metadata",
")",
":",
"i",
"=",
"importlib",
".",
"import_module",
"(",
"metadata",
")",
"env",
"=",
"get_jinja_env",
"(",
")",
"model_template",
"=",
"env",
".",
"get_template",
"(",
"'model.py.jinja2'",
")",
"for",
"model",... | Generate a model class for any models contained in the specified spec file. | [
"Generate",
"a",
"model",
"class",
"for",
"any",
"models",
"contained",
"in",
"the",
"specified",
"spec",
"file",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/builder.py#L133-L140 |
PGower/PyCanvas | builder.py | build_service_class | def build_service_class(metadata):
"""Generate a service class for the service contained in the specified metadata class."""
i = importlib.import_module(metadata)
service = i.service
env = get_jinja_env()
service_template = env.get_template('service.py.jinja2')
with open(api_path(service.name.lower()), 'w') as t:
t.write(service_template.render(service_md=service)) | python | def build_service_class(metadata):
"""Generate a service class for the service contained in the specified metadata class."""
i = importlib.import_module(metadata)
service = i.service
env = get_jinja_env()
service_template = env.get_template('service.py.jinja2')
with open(api_path(service.name.lower()), 'w') as t:
t.write(service_template.render(service_md=service)) | [
"def",
"build_service_class",
"(",
"metadata",
")",
":",
"i",
"=",
"importlib",
".",
"import_module",
"(",
"metadata",
")",
"service",
"=",
"i",
".",
"service",
"env",
"=",
"get_jinja_env",
"(",
")",
"service_template",
"=",
"env",
".",
"get_template",
"(",
... | Generate a service class for the service contained in the specified metadata class. | [
"Generate",
"a",
"service",
"class",
"for",
"the",
"service",
"contained",
"in",
"the",
"specified",
"metadata",
"class",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/builder.py#L145-L152 |
PGower/PyCanvas | pycanvas/apis/account_reports.py | AccountReportsAPI.start_report | def start_report(self, report, account_id, _parameters=None):
"""
Start a Report.
Generates a report instance for the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - report
"""ID"""
path["report"] = report
# OPTIONAL - [parameters]
"""The parameters will vary for each report"""
if _parameters is not None:
data["[parameters]"] = _parameters
self.logger.debug("POST /api/v1/accounts/{account_id}/reports/{report} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/reports/{report}".format(**path), data=data, params=params, single_item=True) | python | def start_report(self, report, account_id, _parameters=None):
"""
Start a Report.
Generates a report instance for the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - report
"""ID"""
path["report"] = report
# OPTIONAL - [parameters]
"""The parameters will vary for each report"""
if _parameters is not None:
data["[parameters]"] = _parameters
self.logger.debug("POST /api/v1/accounts/{account_id}/reports/{report} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("POST", "/api/v1/accounts/{account_id}/reports/{report}".format(**path), data=data, params=params, single_item=True) | [
"def",
"start_report",
"(",
"self",
",",
"report",
",",
"account_id",
",",
"_parameters",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"ac... | Start a Report.
Generates a report instance for the account. | [
"Start",
"a",
"Report",
".",
"Generates",
"a",
"report",
"instance",
"for",
"the",
"account",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/account_reports.py#L36-L60 |
PGower/PyCanvas | pycanvas/apis/account_reports.py | AccountReportsAPI.index_of_reports | def index_of_reports(self, report, account_id):
"""
Index of Reports.
Shows all reports that have been run for the account of a specific type.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - report
"""ID"""
path["report"] = report
self.logger.debug("GET /api/v1/accounts/{account_id}/reports/{report} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/reports/{report}".format(**path), data=data, params=params, all_pages=True) | python | def index_of_reports(self, report, account_id):
"""
Index of Reports.
Shows all reports that have been run for the account of a specific type.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = account_id
# REQUIRED - PATH - report
"""ID"""
path["report"] = report
self.logger.debug("GET /api/v1/accounts/{account_id}/reports/{report} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/reports/{report}".format(**path), data=data, params=params, all_pages=True) | [
"def",
"index_of_reports",
"(",
"self",
",",
"report",
",",
"account_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - account_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"account_id\"",
"]",
"=",
"account... | Index of Reports.
Shows all reports that have been run for the account of a specific type. | [
"Index",
"of",
"Reports",
".",
"Shows",
"all",
"reports",
"that",
"have",
"been",
"run",
"for",
"the",
"account",
"of",
"a",
"specific",
"type",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/account_reports.py#L62-L81 |
theonion/django-bulbs | bulbs/recirc/mixins.py | BaseQueryMixin.clean_query | def clean_query(self):
"""
Removes any `None` value from an elasticsearch query.
"""
if self.query:
for key, value in self.query.items():
if isinstance(value, list) and None in value:
self.query[key] = [v for v in value if v is not None] | python | def clean_query(self):
"""
Removes any `None` value from an elasticsearch query.
"""
if self.query:
for key, value in self.query.items():
if isinstance(value, list) and None in value:
self.query[key] = [v for v in value if v is not None] | [
"def",
"clean_query",
"(",
"self",
")",
":",
"if",
"self",
".",
"query",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"query",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"None",
"in",
"value",
"... | Removes any `None` value from an elasticsearch query. | [
"Removes",
"any",
"None",
"value",
"from",
"an",
"elasticsearch",
"query",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/recirc/mixins.py#L29-L36 |
theonion/django-bulbs | bulbs/recirc/mixins.py | BaseQueryMixin.get_recirc_content | def get_recirc_content(self, published=True, count=3):
"""gets the first 3 content objects in the `included_ids`
"""
query = self.get_query()
# check if query has included_ids & if there are any ids in it,
# in case the ids have been removed from the array
if not query.get('included_ids'):
qs = Content.search_objects.search()
qs = qs.query(
TagBoost(slugs=self.tags.values_list("slug", flat=True))
).filter(
~Ids(values=[self.id])
).sort(
"_score"
)
return qs[:count]
# NOTE: set included_ids to just be the first 3 ids,
# otherwise search will return last 3 items
query['included_ids'] = query['included_ids'][:count]
search = custom_search_model(Content, query, published=published, field_map={
"feature_type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
})
return search | python | def get_recirc_content(self, published=True, count=3):
"""gets the first 3 content objects in the `included_ids`
"""
query = self.get_query()
# check if query has included_ids & if there are any ids in it,
# in case the ids have been removed from the array
if not query.get('included_ids'):
qs = Content.search_objects.search()
qs = qs.query(
TagBoost(slugs=self.tags.values_list("slug", flat=True))
).filter(
~Ids(values=[self.id])
).sort(
"_score"
)
return qs[:count]
# NOTE: set included_ids to just be the first 3 ids,
# otherwise search will return last 3 items
query['included_ids'] = query['included_ids'][:count]
search = custom_search_model(Content, query, published=published, field_map={
"feature_type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
})
return search | [
"def",
"get_recirc_content",
"(",
"self",
",",
"published",
"=",
"True",
",",
"count",
"=",
"3",
")",
":",
"query",
"=",
"self",
".",
"get_query",
"(",
")",
"# check if query has included_ids & if there are any ids in it,",
"# in case the ids have been removed from the ar... | gets the first 3 content objects in the `included_ids` | [
"gets",
"the",
"first",
"3",
"content",
"objects",
"in",
"the",
"included_ids"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/recirc/mixins.py#L42-L68 |
theonion/django-bulbs | bulbs/recirc/mixins.py | BaseQueryMixin.get_full_recirc_content | def get_full_recirc_content(self, published=True):
"""performs es search and gets all content objects
"""
q = self.get_query()
search = custom_search_model(Content, q, published=published, field_map={
"feature_type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
})
return search | python | def get_full_recirc_content(self, published=True):
"""performs es search and gets all content objects
"""
q = self.get_query()
search = custom_search_model(Content, q, published=published, field_map={
"feature_type": "feature_type.slug",
"tag": "tags.slug",
"content-type": "_type"
})
return search | [
"def",
"get_full_recirc_content",
"(",
"self",
",",
"published",
"=",
"True",
")",
":",
"q",
"=",
"self",
".",
"get_query",
"(",
")",
"search",
"=",
"custom_search_model",
"(",
"Content",
",",
"q",
",",
"published",
"=",
"published",
",",
"field_map",
"=",... | performs es search and gets all content objects | [
"performs",
"es",
"search",
"and",
"gets",
"all",
"content",
"objects"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/recirc/mixins.py#L70-L79 |
theonion/django-bulbs | bulbs/recirc/mixins.py | BaseQueryMixin.has_pinned_content | def has_pinned_content(self):
"""determines if the there is a pinned object in the search
"""
q = self.get_query()
if "pinned_ids" in q:
return bool(len(q.get("pinned_ids", [])))
return False | python | def has_pinned_content(self):
"""determines if the there is a pinned object in the search
"""
q = self.get_query()
if "pinned_ids" in q:
return bool(len(q.get("pinned_ids", [])))
return False | [
"def",
"has_pinned_content",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"get_query",
"(",
")",
"if",
"\"pinned_ids\"",
"in",
"q",
":",
"return",
"bool",
"(",
"len",
"(",
"q",
".",
"get",
"(",
"\"pinned_ids\"",
",",
"[",
"]",
")",
")",
")",
"retu... | determines if the there is a pinned object in the search | [
"determines",
"if",
"the",
"there",
"is",
"a",
"pinned",
"object",
"in",
"the",
"search"
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/recirc/mixins.py#L111-L117 |
TurboGears/backlash | backlash/tracing/slowrequests/timer.py | Timer.run_later | def run_later(self, callable_, timeout, *args, **kwargs):
"""Schedules the specified callable for delayed execution.
Returns a TimerTask instance that can be used to cancel pending
execution.
"""
self.lock.acquire()
try:
if self.die:
raise RuntimeError('This timer has been shut down and '
'does not accept new jobs.')
job = TimerTask(callable_, *args, **kwargs)
self._jobs.append((job, time.time() + timeout))
self._jobs.sort(key=lambda j: j[1]) # sort on time
self.lock.notify()
return job
finally:
self.lock.release() | python | def run_later(self, callable_, timeout, *args, **kwargs):
"""Schedules the specified callable for delayed execution.
Returns a TimerTask instance that can be used to cancel pending
execution.
"""
self.lock.acquire()
try:
if self.die:
raise RuntimeError('This timer has been shut down and '
'does not accept new jobs.')
job = TimerTask(callable_, *args, **kwargs)
self._jobs.append((job, time.time() + timeout))
self._jobs.sort(key=lambda j: j[1]) # sort on time
self.lock.notify()
return job
finally:
self.lock.release() | [
"def",
"run_later",
"(",
"self",
",",
"callable_",
",",
"timeout",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"die",
":",
"raise",
"RuntimeError",
"(",
"'This t... | Schedules the specified callable for delayed execution.
Returns a TimerTask instance that can be used to cancel pending
execution. | [
"Schedules",
"the",
"specified",
"callable",
"for",
"delayed",
"execution",
"."
] | train | https://github.com/TurboGears/backlash/blob/b8c73a6c8a203843f5a52c43b858ae5907fb2a4f/backlash/tracing/slowrequests/timer.py#L40-L60 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.show_front_page_groups | def show_front_page_groups(self, group_id):
"""
Show front page.
Retrieve the content of the front page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
self.logger.debug("GET /api/v1/groups/{group_id}/front_page with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/front_page".format(**path), data=data, params=params, single_item=True) | python | def show_front_page_groups(self, group_id):
"""
Show front page.
Retrieve the content of the front page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
self.logger.debug("GET /api/v1/groups/{group_id}/front_page with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/front_page".format(**path), data=data, params=params, single_item=True) | [
"def",
"show_front_page_groups",
"(",
"self",
",",
"group_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
"group_id",
"self",
"."... | Show front page.
Retrieve the content of the front page | [
"Show",
"front",
"page",
".",
"Retrieve",
"the",
"content",
"of",
"the",
"front",
"page"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L36-L51 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.update_create_front_page_courses | def update_create_front_page_courses(self, course_id, wiki_page_body=None, wiki_page_editing_roles=None, wiki_page_notify_of_update=None, wiki_page_published=None, wiki_page_title=None):
"""
Update/create front page.
Update the title or contents of the front page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - wiki_page[title]
"""The title for the new page. NOTE: changing a page's title will change its
url. The updated url will be returned in the result."""
if wiki_page_title is not None:
data["wiki_page[title]"] = wiki_page_title
# OPTIONAL - wiki_page[body]
"""The content for the new page."""
if wiki_page_body is not None:
data["wiki_page[body]"] = wiki_page_body
# OPTIONAL - wiki_page[editing_roles]
"""Which user roles are allowed to edit this page. Any combination
of these roles is allowed (separated by commas).
"teachers":: Allows editing by teachers in the course.
"students":: Allows editing by students in the course.
"members":: For group wikis, allows editing by members of the group.
"public":: Allows editing by any user."""
if wiki_page_editing_roles is not None:
self._validate_enum(wiki_page_editing_roles, ["teachers", "students", "members", "public"])
data["wiki_page[editing_roles]"] = wiki_page_editing_roles
# OPTIONAL - wiki_page[notify_of_update]
"""Whether participants should be notified when this page changes."""
if wiki_page_notify_of_update is not None:
data["wiki_page[notify_of_update]"] = wiki_page_notify_of_update
# OPTIONAL - wiki_page[published]
"""Whether the page is published (true) or draft state (false)."""
if wiki_page_published is not None:
data["wiki_page[published]"] = wiki_page_published
self.logger.debug("PUT /api/v1/courses/{course_id}/front_page with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/courses/{course_id}/front_page".format(**path), data=data, params=params, single_item=True) | python | def update_create_front_page_courses(self, course_id, wiki_page_body=None, wiki_page_editing_roles=None, wiki_page_notify_of_update=None, wiki_page_published=None, wiki_page_title=None):
"""
Update/create front page.
Update the title or contents of the front page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - wiki_page[title]
"""The title for the new page. NOTE: changing a page's title will change its
url. The updated url will be returned in the result."""
if wiki_page_title is not None:
data["wiki_page[title]"] = wiki_page_title
# OPTIONAL - wiki_page[body]
"""The content for the new page."""
if wiki_page_body is not None:
data["wiki_page[body]"] = wiki_page_body
# OPTIONAL - wiki_page[editing_roles]
"""Which user roles are allowed to edit this page. Any combination
of these roles is allowed (separated by commas).
"teachers":: Allows editing by teachers in the course.
"students":: Allows editing by students in the course.
"members":: For group wikis, allows editing by members of the group.
"public":: Allows editing by any user."""
if wiki_page_editing_roles is not None:
self._validate_enum(wiki_page_editing_roles, ["teachers", "students", "members", "public"])
data["wiki_page[editing_roles]"] = wiki_page_editing_roles
# OPTIONAL - wiki_page[notify_of_update]
"""Whether participants should be notified when this page changes."""
if wiki_page_notify_of_update is not None:
data["wiki_page[notify_of_update]"] = wiki_page_notify_of_update
# OPTIONAL - wiki_page[published]
"""Whether the page is published (true) or draft state (false)."""
if wiki_page_published is not None:
data["wiki_page[published]"] = wiki_page_published
self.logger.debug("PUT /api/v1/courses/{course_id}/front_page with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("PUT", "/api/v1/courses/{course_id}/front_page".format(**path), data=data, params=params, single_item=True) | [
"def",
"update_create_front_page_courses",
"(",
"self",
",",
"course_id",
",",
"wiki_page_body",
"=",
"None",
",",
"wiki_page_editing_roles",
"=",
"None",
",",
"wiki_page_notify_of_update",
"=",
"None",
",",
"wiki_page_published",
"=",
"None",
",",
"wiki_page_title",
... | Update/create front page.
Update the title or contents of the front page | [
"Update",
"/",
"create",
"front",
"page",
".",
"Update",
"the",
"title",
"or",
"contents",
"of",
"the",
"front",
"page"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L53-L101 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.list_pages_courses | def list_pages_courses(self, course_id, order=None, published=None, search_term=None, sort=None):
"""
List pages.
List the wiki pages associated with a course or group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - sort
"""Sort results by this field."""
if sort is not None:
self._validate_enum(sort, ["title", "created_at", "updated_at"])
params["sort"] = sort
# OPTIONAL - order
"""The sorting order. Defaults to 'asc'."""
if order is not None:
self._validate_enum(order, ["asc", "desc"])
params["order"] = order
# OPTIONAL - search_term
"""The partial title of the pages to match and return."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - published
"""If true, include only published paqes. If false, exclude published
pages. If not present, do not filter on published status."""
if published is not None:
params["published"] = published
self.logger.debug("GET /api/v1/courses/{course_id}/pages with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/pages".format(**path), data=data, params=params, all_pages=True) | python | def list_pages_courses(self, course_id, order=None, published=None, search_term=None, sort=None):
"""
List pages.
List the wiki pages associated with a course or group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# OPTIONAL - sort
"""Sort results by this field."""
if sort is not None:
self._validate_enum(sort, ["title", "created_at", "updated_at"])
params["sort"] = sort
# OPTIONAL - order
"""The sorting order. Defaults to 'asc'."""
if order is not None:
self._validate_enum(order, ["asc", "desc"])
params["order"] = order
# OPTIONAL - search_term
"""The partial title of the pages to match and return."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - published
"""If true, include only published paqes. If false, exclude published
pages. If not present, do not filter on published status."""
if published is not None:
params["published"] = published
self.logger.debug("GET /api/v1/courses/{course_id}/pages with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/pages".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_pages_courses",
"(",
"self",
",",
"course_id",
",",
"order",
"=",
"None",
",",
"published",
"=",
"None",
",",
"search_term",
"=",
"None",
",",
"sort",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
... | List pages.
List the wiki pages associated with a course or group | [
"List",
"pages",
".",
"List",
"the",
"wiki",
"pages",
"associated",
"with",
"a",
"course",
"or",
"group"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L153-L191 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.list_pages_groups | def list_pages_groups(self, group_id, order=None, published=None, search_term=None, sort=None):
"""
List pages.
List the wiki pages associated with a course or group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - sort
"""Sort results by this field."""
if sort is not None:
self._validate_enum(sort, ["title", "created_at", "updated_at"])
params["sort"] = sort
# OPTIONAL - order
"""The sorting order. Defaults to 'asc'."""
if order is not None:
self._validate_enum(order, ["asc", "desc"])
params["order"] = order
# OPTIONAL - search_term
"""The partial title of the pages to match and return."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - published
"""If true, include only published paqes. If false, exclude published
pages. If not present, do not filter on published status."""
if published is not None:
params["published"] = published
self.logger.debug("GET /api/v1/groups/{group_id}/pages with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/pages".format(**path), data=data, params=params, all_pages=True) | python | def list_pages_groups(self, group_id, order=None, published=None, search_term=None, sort=None):
"""
List pages.
List the wiki pages associated with a course or group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# OPTIONAL - sort
"""Sort results by this field."""
if sort is not None:
self._validate_enum(sort, ["title", "created_at", "updated_at"])
params["sort"] = sort
# OPTIONAL - order
"""The sorting order. Defaults to 'asc'."""
if order is not None:
self._validate_enum(order, ["asc", "desc"])
params["order"] = order
# OPTIONAL - search_term
"""The partial title of the pages to match and return."""
if search_term is not None:
params["search_term"] = search_term
# OPTIONAL - published
"""If true, include only published paqes. If false, exclude published
pages. If not present, do not filter on published status."""
if published is not None:
params["published"] = published
self.logger.debug("GET /api/v1/groups/{group_id}/pages with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/pages".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_pages_groups",
"(",
"self",
",",
"group_id",
",",
"order",
"=",
"None",
",",
"published",
"=",
"None",
",",
"search_term",
"=",
"None",
",",
"sort",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{... | List pages.
List the wiki pages associated with a course or group | [
"List",
"pages",
".",
"List",
"the",
"wiki",
"pages",
"associated",
"with",
"a",
"course",
"or",
"group"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L193-L231 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.show_page_courses | def show_page_courses(self, url, course_id):
"""
Show page.
Retrieve the content of a wiki page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/courses/{course_id}/pages/{url} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/pages/{url}".format(**path), data=data, params=params, single_item=True) | python | def show_page_courses(self, url, course_id):
"""
Show page.
Retrieve the content of a wiki page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/courses/{course_id}/pages/{url} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/pages/{url}".format(**path), data=data, params=params, single_item=True) | [
"def",
"show_page_courses",
"(",
"self",
",",
"url",
",",
"course_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]",
"=",
"course_id",
... | Show page.
Retrieve the content of a wiki page | [
"Show",
"page",
".",
"Retrieve",
"the",
"content",
"of",
"a",
"wiki",
"page"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L339-L358 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.show_page_groups | def show_page_groups(self, url, group_id):
"""
Show page.
Retrieve the content of a wiki page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/groups/{group_id}/pages/{url} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/pages/{url}".format(**path), data=data, params=params, single_item=True) | python | def show_page_groups(self, url, group_id):
"""
Show page.
Retrieve the content of a wiki page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/groups/{group_id}/pages/{url} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/pages/{url}".format(**path), data=data, params=params, single_item=True) | [
"def",
"show_page_groups",
"(",
"self",
",",
"url",
",",
"group_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
"group_id",
"# ... | Show page.
Retrieve the content of a wiki page | [
"Show",
"page",
".",
"Retrieve",
"the",
"content",
"of",
"a",
"wiki",
"page"
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L360-L379 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.list_revisions_courses | def list_revisions_courses(self, url, course_id):
"""
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/courses/{course_id}/pages/{url}/revisions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/pages/{url}/revisions".format(**path), data=data, params=params, all_pages=True) | python | def list_revisions_courses(self, url, course_id):
"""
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/courses/{course_id}/pages/{url}/revisions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/courses/{course_id}/pages/{url}/revisions".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_revisions_courses",
"(",
"self",
",",
"url",
",",
"course_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - course_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"course_id\"",
"]",
"=",
"course_... | List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history. | [
"List",
"revisions",
".",
"List",
"the",
"revisions",
"of",
"a",
"page",
".",
"Callers",
"must",
"have",
"update",
"rights",
"on",
"the",
"page",
"in",
"order",
"to",
"see",
"page",
"history",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L541-L560 |
PGower/PyCanvas | pycanvas/apis/pages.py | PagesAPI.list_revisions_groups | def list_revisions_groups(self, url, group_id):
"""
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/groups/{group_id}/pages/{url}/revisions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/pages/{url}/revisions".format(**path), data=data, params=params, all_pages=True) | python | def list_revisions_groups(self, url, group_id):
"""
List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
# REQUIRED - PATH - url
"""ID"""
path["url"] = url
self.logger.debug("GET /api/v1/groups/{group_id}/pages/{url}/revisions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/groups/{group_id}/pages/{url}/revisions".format(**path), data=data, params=params, all_pages=True) | [
"def",
"list_revisions_groups",
"(",
"self",
",",
"url",
",",
"group_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - group_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"group_id\"",
"]",
"=",
"group_id",
... | List revisions.
List the revisions of a page. Callers must have update rights on the page in order to see page history. | [
"List",
"revisions",
".",
"List",
"the",
"revisions",
"of",
"a",
"page",
".",
"Callers",
"must",
"have",
"update",
"rights",
"on",
"the",
"page",
"in",
"order",
"to",
"see",
"page",
"history",
"."
] | train | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/pages.py#L562-L581 |
theonion/django-bulbs | bulbs/content/serializers.py | ContentTypeField.to_representation | def to_representation(self, value):
"""Convert to natural key."""
content_type = ContentType.objects.get_for_id(value)
return "_".join(content_type.natural_key()) | python | def to_representation(self, value):
"""Convert to natural key."""
content_type = ContentType.objects.get_for_id(value)
return "_".join(content_type.natural_key()) | [
"def",
"to_representation",
"(",
"self",
",",
"value",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_id",
"(",
"value",
")",
"return",
"\"_\"",
".",
"join",
"(",
"content_type",
".",
"natural_key",
"(",
")",
")"
] | Convert to natural key. | [
"Convert",
"to",
"natural",
"key",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/serializers.py#L19-L22 |
theonion/django-bulbs | bulbs/content/serializers.py | ContentTypeField.to_internal_value | def to_internal_value(self, value):
"""Convert to integer id."""
natural_key = value.split("_")
content_type = ContentType.objects.get_by_natural_key(*natural_key)
return content_type.id | python | def to_internal_value(self, value):
"""Convert to integer id."""
natural_key = value.split("_")
content_type = ContentType.objects.get_by_natural_key(*natural_key)
return content_type.id | [
"def",
"to_internal_value",
"(",
"self",
",",
"value",
")",
":",
"natural_key",
"=",
"value",
".",
"split",
"(",
"\"_\"",
")",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_by_natural_key",
"(",
"*",
"natural_key",
")",
"return",
"content_type"... | Convert to integer id. | [
"Convert",
"to",
"integer",
"id",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/serializers.py#L24-L28 |
theonion/django-bulbs | bulbs/content/serializers.py | TagField.to_internal_value | def to_internal_value(self, value):
"""Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the Tag doesn't exist, and should be added."""
if "id" in value:
tag = Tag.objects.get(id=value["id"])
else:
if "name" not in value:
raise ValidationError("Tags must include an ID or a name.")
if len(slugify(value["name"])) > 50:
raise ValidationError("Maximum tag length is 50 characters.")
name = value["name"]
slug = value.get("slug", slugify(name))
try:
tag = Tag.objects.get(slug=slug)
except Tag.DoesNotExist:
tag, created = Tag.objects.get_or_create(name=name, slug=slug)
return tag | python | def to_internal_value(self, value):
"""Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the Tag doesn't exist, and should be added."""
if "id" in value:
tag = Tag.objects.get(id=value["id"])
else:
if "name" not in value:
raise ValidationError("Tags must include an ID or a name.")
if len(slugify(value["name"])) > 50:
raise ValidationError("Maximum tag length is 50 characters.")
name = value["name"]
slug = value.get("slug", slugify(name))
try:
tag = Tag.objects.get(slug=slug)
except Tag.DoesNotExist:
tag, created = Tag.objects.get_or_create(name=name, slug=slug)
return tag | [
"def",
"to_internal_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"\"id\"",
"in",
"value",
":",
"tag",
"=",
"Tag",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"value",
"[",
"\"id\"",
"]",
")",
"else",
":",
"if",
"\"name\"",
"not",
"in",
"value... | Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the Tag doesn't exist, and should be added. | [
"Basically",
"each",
"tag",
"dict",
"must",
"include",
"a",
"full",
"dict",
"with",
"id",
"name",
"and",
"slug",
"--",
"or",
"else",
"you",
"need",
"to",
"pass",
"in",
"a",
"dict",
"with",
"just",
"a",
"name",
"which",
"indicated",
"that",
"the",
"Tag"... | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/serializers.py#L106-L125 |
theonion/django-bulbs | bulbs/content/serializers.py | FeatureTypeField.to_internal_value | def to_internal_value(self, value):
"""Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the FeatureType doesn't exist, and should be added."""
if value == "":
return None
if isinstance(value, string_types):
slug = slugify(value)
feature_type, created = FeatureType.objects.get_or_create(
slug=slug,
defaults={"name": value}
)
else:
if "id" in value:
feature_type = FeatureType.objects.get(id=value["id"])
elif "slug" in value:
feature_type = FeatureType.objects.get(slug=value["slug"])
else:
raise ValidationError("Invalid feature type data")
return feature_type | python | def to_internal_value(self, value):
"""Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the FeatureType doesn't exist, and should be added."""
if value == "":
return None
if isinstance(value, string_types):
slug = slugify(value)
feature_type, created = FeatureType.objects.get_or_create(
slug=slug,
defaults={"name": value}
)
else:
if "id" in value:
feature_type = FeatureType.objects.get(id=value["id"])
elif "slug" in value:
feature_type = FeatureType.objects.get(slug=value["slug"])
else:
raise ValidationError("Invalid feature type data")
return feature_type | [
"def",
"to_internal_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"\"\"",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"slug",
"=",
"slugify",
"(",
"value",
")",
"feature_type",
",",
"created... | Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the FeatureType doesn't exist, and should be added. | [
"Basically",
"each",
"tag",
"dict",
"must",
"include",
"a",
"full",
"dict",
"with",
"id",
"name",
"and",
"slug",
"--",
"or",
"else",
"you",
"need",
"to",
"pass",
"in",
"a",
"dict",
"with",
"just",
"a",
"name",
"which",
"indicated",
"that",
"the",
"Feat... | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/serializers.py#L138-L158 |
theonion/django-bulbs | bulbs/content/serializers.py | DefaultUserSerializer.to_internal_value | def to_internal_value(self, data):
"""Basically, each author dict must include either a username or id."""
# model = get_user_model()
model = self.Meta.model
if "id" in data:
author = model.objects.get(id=data["id"])
else:
if "username" not in data:
raise ValidationError("Authors must include an ID or a username.")
username = data["username"]
author = model.objects.get(username=username)
return author | python | def to_internal_value(self, data):
"""Basically, each author dict must include either a username or id."""
# model = get_user_model()
model = self.Meta.model
if "id" in data:
author = model.objects.get(id=data["id"])
else:
if "username" not in data:
raise ValidationError("Authors must include an ID or a username.")
username = data["username"]
author = model.objects.get(username=username)
return author | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"# model = get_user_model()",
"model",
"=",
"self",
".",
"Meta",
".",
"model",
"if",
"\"id\"",
"in",
"data",
":",
"author",
"=",
"model",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"data",
... | Basically, each author dict must include either a username or id. | [
"Basically",
"each",
"author",
"dict",
"must",
"include",
"either",
"a",
"username",
"or",
"id",
"."
] | train | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/serializers.py#L184-L196 |
joeyespo/nosey | nosey/watcher.py | watch | def watch(directory=None, auto_clear=False, extensions=[]):
"""Starts a server to render the specified file or directory containing a README."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + directory)
directory = os.path.abspath(directory)
# Initial run
event_handler = ChangeHandler(directory, auto_clear, extensions)
event_handler.run()
# Setup watchdog
observer = Observer()
observer.schedule(event_handler, path=directory, recursive=True)
observer.start()
# Watch and run tests until interrupted by user
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join() | python | def watch(directory=None, auto_clear=False, extensions=[]):
"""Starts a server to render the specified file or directory containing a README."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + directory)
directory = os.path.abspath(directory)
# Initial run
event_handler = ChangeHandler(directory, auto_clear, extensions)
event_handler.run()
# Setup watchdog
observer = Observer()
observer.schedule(event_handler, path=directory, recursive=True)
observer.start()
# Watch and run tests until interrupted by user
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join() | [
"def",
"watch",
"(",
"directory",
"=",
"None",
",",
"auto_clear",
"=",
"False",
",",
"extensions",
"=",
"[",
"]",
")",
":",
"if",
"directory",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"'Di... | Starts a server to render the specified file or directory containing a README. | [
"Starts",
"a",
"server",
"to",
"render",
"the",
"specified",
"file",
"or",
"directory",
"containing",
"a",
"README",
"."
] | train | https://github.com/joeyespo/nosey/blob/8194c3e1b06d95ab623b561fd0f26b2d3017446c/nosey/watcher.py#L38-L59 |
joeyespo/nosey | nosey/watcher.py | ChangeHandler.run | def run(self):
"""Called when a file is changed to re-run the tests with nose."""
if self.auto_clear:
os.system('cls' if os.name == 'nt' else 'auto_clear')
else:
print
print 'Running unit tests...'
if self.auto_clear:
print
subprocess.call('nosetests', cwd=self.directory) | python | def run(self):
"""Called when a file is changed to re-run the tests with nose."""
if self.auto_clear:
os.system('cls' if os.name == 'nt' else 'auto_clear')
else:
print
print 'Running unit tests...'
if self.auto_clear:
print
subprocess.call('nosetests', cwd=self.directory) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"auto_clear",
":",
"os",
".",
"system",
"(",
"'cls'",
"if",
"os",
".",
"name",
"==",
"'nt'",
"else",
"'auto_clear'",
")",
"else",
":",
"print",
"print",
"'Running unit tests...'",
"if",
"self",
".... | Called when a file is changed to re-run the tests with nose. | [
"Called",
"when",
"a",
"file",
"is",
"changed",
"to",
"re",
"-",
"run",
"the",
"tests",
"with",
"nose",
"."
] | train | https://github.com/joeyespo/nosey/blob/8194c3e1b06d95ab623b561fd0f26b2d3017446c/nosey/watcher.py#L26-L35 |
LIVVkit/LIVVkit | livvkit/util/TexHelper.py | write_tex | def write_tex():
"""
Finds all of the output data files, and writes them out to .tex
"""
datadir = livvkit.index_dir
outdir = os.path.join(datadir, "tex")
print(outdir)
# functions.mkdir_p(outdir)
data_files = glob.glob(datadir + "/**/*.json", recursive=True)
for each in data_files:
data = functions.read_json(each)
tex = translate_page(data)
outfile = os.path.join(outdir, os.path.basename(each).replace('json', 'tex'))
with open(outfile, 'w') as f:
f.write(tex) | python | def write_tex():
"""
Finds all of the output data files, and writes them out to .tex
"""
datadir = livvkit.index_dir
outdir = os.path.join(datadir, "tex")
print(outdir)
# functions.mkdir_p(outdir)
data_files = glob.glob(datadir + "/**/*.json", recursive=True)
for each in data_files:
data = functions.read_json(each)
tex = translate_page(data)
outfile = os.path.join(outdir, os.path.basename(each).replace('json', 'tex'))
with open(outfile, 'w') as f:
f.write(tex) | [
"def",
"write_tex",
"(",
")",
":",
"datadir",
"=",
"livvkit",
".",
"index_dir",
"outdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"datadir",
",",
"\"tex\"",
")",
"print",
"(",
"outdir",
")",
"# functions.mkdir_p(outdir)",
"data_files",
"=",
"glob",
".",
... | Finds all of the output data files, and writes them out to .tex | [
"Finds",
"all",
"of",
"the",
"output",
"data",
"files",
"and",
"writes",
"them",
"out",
"to",
".",
"tex"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/TexHelper.py#L46-L62 |
LIVVkit/LIVVkit | livvkit/util/TexHelper.py | translate_page | def translate_page(data):
"""
Translates data elements with data['Type'] = 'page'. This is the
top level of translation that occurs, and delegates the translation
of other element types contained on a page to their proper functions.
"""
if "Page" != data["Type"]:
return ""
tex_str = ('\\documentclass{article}\\n' +
'\\usepackage{placeins}\\n' +
'\\title{LIVVkit}\\n' +
'\\author{$USER}\\n' +
'\\usepackage[parfill]{parskip}\\n' +
'\\begin{document}\\n' +
'\\maketitle\\n'
).replace('$USER', livvkit.user)
content = data["Data"]
for tag_name in ["Elements", "Tabs"]:
for tag in content.get(tag_name, []):
print("Translating " + tag["Type"])
tex_str += translate_map[tag["Type"]](tag)
tex_str += '\n\\end{document}'
return tex_str | python | def translate_page(data):
"""
Translates data elements with data['Type'] = 'page'. This is the
top level of translation that occurs, and delegates the translation
of other element types contained on a page to their proper functions.
"""
if "Page" != data["Type"]:
return ""
tex_str = ('\\documentclass{article}\\n' +
'\\usepackage{placeins}\\n' +
'\\title{LIVVkit}\\n' +
'\\author{$USER}\\n' +
'\\usepackage[parfill]{parskip}\\n' +
'\\begin{document}\\n' +
'\\maketitle\\n'
).replace('$USER', livvkit.user)
content = data["Data"]
for tag_name in ["Elements", "Tabs"]:
for tag in content.get(tag_name, []):
print("Translating " + tag["Type"])
tex_str += translate_map[tag["Type"]](tag)
tex_str += '\n\\end{document}'
return tex_str | [
"def",
"translate_page",
"(",
"data",
")",
":",
"if",
"\"Page\"",
"!=",
"data",
"[",
"\"Type\"",
"]",
":",
"return",
"\"\"",
"tex_str",
"=",
"(",
"'\\\\documentclass{article}\\\\n'",
"+",
"'\\\\usepackage{placeins}\\\\n'",
"+",
"'\\\\title{LIVVkit}\\\\n'",
"+",
"'\\... | Translates data elements with data['Type'] = 'page'. This is the
top level of translation that occurs, and delegates the translation
of other element types contained on a page to their proper functions. | [
"Translates",
"data",
"elements",
"with",
"data",
"[",
"Type",
"]",
"=",
"page",
".",
"This",
"is",
"the",
"top",
"level",
"of",
"translation",
"that",
"occurs",
"and",
"delegates",
"the",
"translation",
"of",
"other",
"element",
"types",
"contained",
"on",
... | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/TexHelper.py#L65-L90 |
LIVVkit/LIVVkit | livvkit/util/TexHelper.py | translate_section | def translate_section(data):
""" Translates data where data["Type"]=="Section" """
sect_str = ""
elements = data.get("Elements", [])
for elem in elements:
print(" Translating " + elem["Type"])
sect_str += translate_map[elem["Type"]](elem)
return sect_str | python | def translate_section(data):
""" Translates data where data["Type"]=="Section" """
sect_str = ""
elements = data.get("Elements", [])
for elem in elements:
print(" Translating " + elem["Type"])
sect_str += translate_map[elem["Type"]](elem)
return sect_str | [
"def",
"translate_section",
"(",
"data",
")",
":",
"sect_str",
"=",
"\"\"",
"elements",
"=",
"data",
".",
"get",
"(",
"\"Elements\"",
",",
"[",
"]",
")",
"for",
"elem",
"in",
"elements",
":",
"print",
"(",
"\" Translating \"",
"+",
"elem",
"[",
"\"Typ... | Translates data where data["Type"]=="Section" | [
"Translates",
"data",
"where",
"data",
"[",
"Type",
"]",
"==",
"Section"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/TexHelper.py#L93-L100 |
LIVVkit/LIVVkit | livvkit/util/TexHelper.py | translate_tab | def translate_tab(data):
""" Translates data where data["Type"]=="Tab" """
tab_str = ""
sections = data.get("Sections", [])
for section in sections:
print(" Translating " + section["Type"])
tab_str += translate_map[section["Type"]](section)
return tab_str | python | def translate_tab(data):
""" Translates data where data["Type"]=="Tab" """
tab_str = ""
sections = data.get("Sections", [])
for section in sections:
print(" Translating " + section["Type"])
tab_str += translate_map[section["Type"]](section)
return tab_str | [
"def",
"translate_tab",
"(",
"data",
")",
":",
"tab_str",
"=",
"\"\"",
"sections",
"=",
"data",
".",
"get",
"(",
"\"Sections\"",
",",
"[",
"]",
")",
"for",
"section",
"in",
"sections",
":",
"print",
"(",
"\" Translating \"",
"+",
"section",
"[",
"\"Type... | Translates data where data["Type"]=="Tab" | [
"Translates",
"data",
"where",
"data",
"[",
"Type",
"]",
"==",
"Tab"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/TexHelper.py#L103-L110 |
LIVVkit/LIVVkit | livvkit/util/TexHelper.py | translate_summary | def translate_summary(data):
""" Translates data where data["Type"]=="Summary" """
headers = sorted(data.get("Headers", []))
summary = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table"))
summary += ' \\begin{table}[!ht] \n \\begin{center}'
# Set the number of columns
n_cols = len(headers)
col_str = "l" + "c" * n_cols
summary += '\n \\begin{tabular}{$NCOLS} \n'.replace("$NCOLS", col_str)
spacer = ' &' * n_cols + r'\\[.5em]'
for header in headers:
summary += '& $HEADER '.replace('$HEADER', header).replace('%', '\%')
summary += ' \\\\ \hline \n'
names = sorted(six.iterkeys(data.get("Data", [])))
for name in names:
summary += '\n\n \\textbf{{{}}} {} \n'.format(name, spacer)
cases = data.get("Data", []).get(name, {})
for case, c_data in cases.items():
summary += ' $CASE & '.replace('$CASE', str(case))
for header in headers:
h_data = c_data.get(header, "")
if list is type(h_data) and len(h_data) == 2:
summary += (' $H_DATA_0 of $H_DATA_1 &'
.replace('$H_DATA_0', str(h_data[0]))
.replace('$H_DATA_1', str(h_data[1]))
.replace('%', '\%'))
else:
summary += ' $H_DATA &'.replace('$H_DATA', str(h_data)).replace('%', '\%')
# This takes care of the trailing & that comes from processing the headers.
summary = summary[:-1] + r' \\'
summary += '\n \end{tabular} \n \end{center} \n \end{table}\n'
return summary | python | def translate_summary(data):
""" Translates data where data["Type"]=="Summary" """
headers = sorted(data.get("Headers", []))
summary = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table"))
summary += ' \\begin{table}[!ht] \n \\begin{center}'
# Set the number of columns
n_cols = len(headers)
col_str = "l" + "c" * n_cols
summary += '\n \\begin{tabular}{$NCOLS} \n'.replace("$NCOLS", col_str)
spacer = ' &' * n_cols + r'\\[.5em]'
for header in headers:
summary += '& $HEADER '.replace('$HEADER', header).replace('%', '\%')
summary += ' \\\\ \hline \n'
names = sorted(six.iterkeys(data.get("Data", [])))
for name in names:
summary += '\n\n \\textbf{{{}}} {} \n'.format(name, spacer)
cases = data.get("Data", []).get(name, {})
for case, c_data in cases.items():
summary += ' $CASE & '.replace('$CASE', str(case))
for header in headers:
h_data = c_data.get(header, "")
if list is type(h_data) and len(h_data) == 2:
summary += (' $H_DATA_0 of $H_DATA_1 &'
.replace('$H_DATA_0', str(h_data[0]))
.replace('$H_DATA_1', str(h_data[1]))
.replace('%', '\%'))
else:
summary += ' $H_DATA &'.replace('$H_DATA', str(h_data)).replace('%', '\%')
# This takes care of the trailing & that comes from processing the headers.
summary = summary[:-1] + r' \\'
summary += '\n \end{tabular} \n \end{center} \n \end{table}\n'
return summary | [
"def",
"translate_summary",
"(",
"data",
")",
":",
"headers",
"=",
"sorted",
"(",
"data",
".",
"get",
"(",
"\"Headers\"",
",",
"[",
"]",
")",
")",
"summary",
"=",
"'\\\\FloatBarrier \\n \\\\section{$NAME} \\n'",
".",
"replace",
"(",
"'$NAME'",
",",
"data",
"... | Translates data where data["Type"]=="Summary" | [
"Translates",
"data",
"where",
"data",
"[",
"Type",
"]",
"==",
"Summary"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/TexHelper.py#L113-L149 |
LIVVkit/LIVVkit | livvkit/util/TexHelper.py | translate_table | def translate_table(data):
""" Translates data where data["Type"]=="Table" """
headers = sorted(data.get("Headers", []))
table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table"))
table += '\\begin{table}[!ht] \n \\begin{center}'
# Set the number of columns
n_cols = "c"*(len(headers)+1)
table += '\n \\begin{tabular}{$NCOLS} \n'.replace("$NCOLS", n_cols)
# Put in the headers
for header in headers:
table += ' $HEADER &'.replace('$HEADER', header).replace('%', '\%')
table = table[:-1] + ' \\\\ \n \hline \n'
# Put in the data
for header in headers:
table += ' $VAL &'.replace("$VAL", str(data["Data"][header]))
table = table[:-1] + ' \\\\ \n \hline'
table += '\n \end{tabular} \n \end{center} \n \end{table}\n'
return table | python | def translate_table(data):
""" Translates data where data["Type"]=="Table" """
headers = sorted(data.get("Headers", []))
table = '\\FloatBarrier \n \\section{$NAME} \n'.replace('$NAME', data.get("Title", "table"))
table += '\\begin{table}[!ht] \n \\begin{center}'
# Set the number of columns
n_cols = "c"*(len(headers)+1)
table += '\n \\begin{tabular}{$NCOLS} \n'.replace("$NCOLS", n_cols)
# Put in the headers
for header in headers:
table += ' $HEADER &'.replace('$HEADER', header).replace('%', '\%')
table = table[:-1] + ' \\\\ \n \hline \n'
# Put in the data
for header in headers:
table += ' $VAL &'.replace("$VAL", str(data["Data"][header]))
table = table[:-1] + ' \\\\ \n \hline'
table += '\n \end{tabular} \n \end{center} \n \end{table}\n'
return table | [
"def",
"translate_table",
"(",
"data",
")",
":",
"headers",
"=",
"sorted",
"(",
"data",
".",
"get",
"(",
"\"Headers\"",
",",
"[",
"]",
")",
")",
"table",
"=",
"'\\\\FloatBarrier \\n \\\\section{$NAME} \\n'",
".",
"replace",
"(",
"'$NAME'",
",",
"data",
".",
... | Translates data where data["Type"]=="Table" | [
"Translates",
"data",
"where",
"data",
"[",
"Type",
"]",
"==",
"Table"
] | train | https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/TexHelper.py#L152-L172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.