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 |
|---|---|---|---|---|---|---|---|---|---|---|
SylvanasSun/FishFishJump | fish_core/bloomfilter.py | RedisBloomFilter.is_contains | def is_contains(self, data):
"""
Judge the data whether is already exist if each bit of hash code is 1 then data exist.
"""
if not data:
return False
data = self._compress_by_md5(data)
result = True
# cut the first two place,route to different block by block_num
name = self.key + str(int(data[0:2], 16) % self.block_num)
for h in self.hash_function:
local_hash = h.hash(data)
result = result & self.server.getbit(name, local_hash)
return result | python | def is_contains(self, data):
"""
Judge the data whether is already exist if each bit of hash code is 1 then data exist.
"""
if not data:
return False
data = self._compress_by_md5(data)
result = True
# cut the first two place,route to different block by block_num
name = self.key + str(int(data[0:2], 16) % self.block_num)
for h in self.hash_function:
local_hash = h.hash(data)
result = result & self.server.getbit(name, local_hash)
return result | [
"def",
"is_contains",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"False",
"data",
"=",
"self",
".",
"_compress_by_md5",
"(",
"data",
")",
"result",
"=",
"True",
"# cut the first two place,route to different block by block_num",
"name",... | Judge the data whether is already exist if each bit of hash code is 1 then data exist. | [
"Judge",
"the",
"data",
"whether",
"is",
"already",
"exist",
"if",
"each",
"bit",
"of",
"hash",
"code",
"is",
"1",
"then",
"data",
"exist",
"."
] | train | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/bloomfilter.py#L67-L80 |
SylvanasSun/FishFishJump | fish_core/bloomfilter.py | RedisBloomFilter.insert | def insert(self, data):
"""
Insert 1 into each bit by local_hash
"""
if not data:
return
data = self._compress_by_md5(data)
# cut the first two place,route to different block by block_num
name = self.key + str(int(data[0:2], 16) % self.block_num)
for h in self.hash_function:
local_hash = h.hash(data)
self.server.setbit(name, local_hash, 1) | python | def insert(self, data):
"""
Insert 1 into each bit by local_hash
"""
if not data:
return
data = self._compress_by_md5(data)
# cut the first two place,route to different block by block_num
name = self.key + str(int(data[0:2], 16) % self.block_num)
for h in self.hash_function:
local_hash = h.hash(data)
self.server.setbit(name, local_hash, 1) | [
"def",
"insert",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"data",
"=",
"self",
".",
"_compress_by_md5",
"(",
"data",
")",
"# cut the first two place,route to different block by block_num",
"name",
"=",
"self",
".",
"key",
"+",
"s... | Insert 1 into each bit by local_hash | [
"Insert",
"1",
"into",
"each",
"bit",
"by",
"local_hash"
] | train | https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/bloomfilter.py#L82-L93 |
wglass/lighthouse | lighthouse/haproxy/config.py | HAProxyConfig.generate | def generate(self, clusters, version=None):
"""
Generates HAProxy config file content based on a given list of
clusters.
"""
now = datetime.datetime.now()
sections = [
Section(
"Auto-generated by Lighthouse (%s)" % now.strftime("%c"),
self.global_stanza,
self.defaults_stanza
)
]
meta_stanzas = [
MetaFrontendStanza(
name, self.meta_clusters[name]["port"],
self.meta_clusters[name].get("frontend", []), members,
self.bind_address
)
for name, members
in six.iteritems(self.get_meta_clusters(clusters))
]
frontend_stanzas = [
FrontendStanza(cluster, self.bind_address)
for cluster in clusters
if "port" in cluster.haproxy
]
backend_stanzas = [BackendStanza(cluster) for cluster in clusters]
if version and version >= (1, 5, 0):
peers_stanzas = [PeersStanza(cluster) for cluster in clusters]
else:
peers_stanzas = []
sections.extend([
Section("Frontend stanzas for ACL meta clusters", *meta_stanzas),
Section("Per-cluster frontend definitions", *frontend_stanzas),
Section("Per-cluster backend definitions", *backend_stanzas),
Section("Per-cluster peer listings", *peers_stanzas),
Section("Individual proxy definitions", *self.proxy_stanzas),
])
if self.stats_stanza:
sections.append(
Section("Listener for stats web interface", self.stats_stanza)
)
return "\n\n\n".join([str(section) for section in sections]) + "\n" | python | def generate(self, clusters, version=None):
"""
Generates HAProxy config file content based on a given list of
clusters.
"""
now = datetime.datetime.now()
sections = [
Section(
"Auto-generated by Lighthouse (%s)" % now.strftime("%c"),
self.global_stanza,
self.defaults_stanza
)
]
meta_stanzas = [
MetaFrontendStanza(
name, self.meta_clusters[name]["port"],
self.meta_clusters[name].get("frontend", []), members,
self.bind_address
)
for name, members
in six.iteritems(self.get_meta_clusters(clusters))
]
frontend_stanzas = [
FrontendStanza(cluster, self.bind_address)
for cluster in clusters
if "port" in cluster.haproxy
]
backend_stanzas = [BackendStanza(cluster) for cluster in clusters]
if version and version >= (1, 5, 0):
peers_stanzas = [PeersStanza(cluster) for cluster in clusters]
else:
peers_stanzas = []
sections.extend([
Section("Frontend stanzas for ACL meta clusters", *meta_stanzas),
Section("Per-cluster frontend definitions", *frontend_stanzas),
Section("Per-cluster backend definitions", *backend_stanzas),
Section("Per-cluster peer listings", *peers_stanzas),
Section("Individual proxy definitions", *self.proxy_stanzas),
])
if self.stats_stanza:
sections.append(
Section("Listener for stats web interface", self.stats_stanza)
)
return "\n\n\n".join([str(section) for section in sections]) + "\n" | [
"def",
"generate",
"(",
"self",
",",
"clusters",
",",
"version",
"=",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"sections",
"=",
"[",
"Section",
"(",
"\"Auto-generated by Lighthouse (%s)\"",
"%",
"now",
".",
"strftime... | Generates HAProxy config file content based on a given list of
clusters. | [
"Generates",
"HAProxy",
"config",
"file",
"content",
"based",
"on",
"a",
"given",
"list",
"of",
"clusters",
"."
] | train | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/config.py#L38-L86 |
wglass/lighthouse | lighthouse/haproxy/config.py | HAProxyConfig.get_meta_clusters | def get_meta_clusters(self, clusters):
"""
Returns a dictionary keyed off of meta cluster names, where the values
are lists of clusters associated with the meta cluster name.
If a meta cluster name doesn't have a port defined in the
`meta_cluster_ports` attribute an error is given and the meta cluster
is removed from the mapping.
"""
meta_clusters = collections.defaultdict(list)
for cluster in clusters:
if not cluster.meta_cluster:
continue
meta_clusters[cluster.meta_cluster].append(cluster)
unconfigured_meta_clusters = [
name for name in meta_clusters.keys()
if name not in self.meta_clusters
]
for name in unconfigured_meta_clusters:
logger.error("Meta cluster %s not configured!")
del meta_clusters[name]
return meta_clusters | python | def get_meta_clusters(self, clusters):
"""
Returns a dictionary keyed off of meta cluster names, where the values
are lists of clusters associated with the meta cluster name.
If a meta cluster name doesn't have a port defined in the
`meta_cluster_ports` attribute an error is given and the meta cluster
is removed from the mapping.
"""
meta_clusters = collections.defaultdict(list)
for cluster in clusters:
if not cluster.meta_cluster:
continue
meta_clusters[cluster.meta_cluster].append(cluster)
unconfigured_meta_clusters = [
name for name in meta_clusters.keys()
if name not in self.meta_clusters
]
for name in unconfigured_meta_clusters:
logger.error("Meta cluster %s not configured!")
del meta_clusters[name]
return meta_clusters | [
"def",
"get_meta_clusters",
"(",
"self",
",",
"clusters",
")",
":",
"meta_clusters",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"cluster",
"in",
"clusters",
":",
"if",
"not",
"cluster",
".",
"meta_cluster",
":",
"continue",
"meta_clusters... | Returns a dictionary keyed off of meta cluster names, where the values
are lists of clusters associated with the meta cluster name.
If a meta cluster name doesn't have a port defined in the
`meta_cluster_ports` attribute an error is given and the meta cluster
is removed from the mapping. | [
"Returns",
"a",
"dictionary",
"keyed",
"off",
"of",
"meta",
"cluster",
"names",
"where",
"the",
"values",
"are",
"lists",
"of",
"clusters",
"associated",
"with",
"the",
"meta",
"cluster",
"name",
"."
] | train | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/config.py#L88-L113 |
honmaple/flask-avatar | flask_avatar/avatar.py | GenAvatar.generate | def generate(cls, size, string, filetype="JPEG"):
"""
Generates a squared avatar with random background color.
:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the image (i.e. JPEG, PNG)
"""
render_size = max(size, GenAvatar.MAX_RENDER_SIZE)
image = Image.new('RGB', (render_size, render_size),
cls._background_color(string))
draw = ImageDraw.Draw(image)
font = cls._font(render_size)
text = cls._text(string)
draw.text(
cls._text_position(render_size, text, font),
text,
fill=cls.FONT_COLOR,
font=font)
stream = BytesIO()
image = image.resize((size, size), Image.ANTIALIAS)
image.save(stream, format=filetype, optimize=True)
# return stream.getvalue()
return stream | python | def generate(cls, size, string, filetype="JPEG"):
"""
Generates a squared avatar with random background color.
:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the image (i.e. JPEG, PNG)
"""
render_size = max(size, GenAvatar.MAX_RENDER_SIZE)
image = Image.new('RGB', (render_size, render_size),
cls._background_color(string))
draw = ImageDraw.Draw(image)
font = cls._font(render_size)
text = cls._text(string)
draw.text(
cls._text_position(render_size, text, font),
text,
fill=cls.FONT_COLOR,
font=font)
stream = BytesIO()
image = image.resize((size, size), Image.ANTIALIAS)
image.save(stream, format=filetype, optimize=True)
# return stream.getvalue()
return stream | [
"def",
"generate",
"(",
"cls",
",",
"size",
",",
"string",
",",
"filetype",
"=",
"\"JPEG\"",
")",
":",
"render_size",
"=",
"max",
"(",
"size",
",",
"GenAvatar",
".",
"MAX_RENDER_SIZE",
")",
"image",
"=",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"(",
"... | Generates a squared avatar with random background color.
:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the image (i.e. JPEG, PNG) | [
"Generates",
"a",
"squared",
"avatar",
"with",
"random",
"background",
"color",
".",
":",
"param",
"size",
":",
"size",
"of",
"the",
"avatar",
"in",
"pixels",
":",
"param",
"string",
":",
"string",
"to",
"be",
"used",
"to",
"print",
"text",
"and",
"seed"... | train | https://github.com/honmaple/flask-avatar/blob/6269eb538c5e0c97268a01c0d35143cd5524bfa5/flask_avatar/avatar.py#L67-L89 |
honmaple/flask-avatar | flask_avatar/avatar.py | GenAvatar._background_color | def _background_color(s):
"""
Generate a random background color.
Brighter colors are dropped, because the text is white.
:param s: Seed used by the random generator
(same seed will produce the same color).
"""
seed(s)
r = v = b = 255
while r + v + b > 255 * 2:
r = randint(0, 255)
v = randint(0, 255)
b = randint(0, 255)
return (r, v, b) | python | def _background_color(s):
"""
Generate a random background color.
Brighter colors are dropped, because the text is white.
:param s: Seed used by the random generator
(same seed will produce the same color).
"""
seed(s)
r = v = b = 255
while r + v + b > 255 * 2:
r = randint(0, 255)
v = randint(0, 255)
b = randint(0, 255)
return (r, v, b) | [
"def",
"_background_color",
"(",
"s",
")",
":",
"seed",
"(",
"s",
")",
"r",
"=",
"v",
"=",
"b",
"=",
"255",
"while",
"r",
"+",
"v",
"+",
"b",
">",
"255",
"*",
"2",
":",
"r",
"=",
"randint",
"(",
"0",
",",
"255",
")",
"v",
"=",
"randint",
... | Generate a random background color.
Brighter colors are dropped, because the text is white.
:param s: Seed used by the random generator
(same seed will produce the same color). | [
"Generate",
"a",
"random",
"background",
"color",
".",
"Brighter",
"colors",
"are",
"dropped",
"because",
"the",
"text",
"is",
"white",
".",
":",
"param",
"s",
":",
"Seed",
"used",
"by",
"the",
"random",
"generator",
"(",
"same",
"seed",
"will",
"produce",... | train | https://github.com/honmaple/flask-avatar/blob/6269eb538c5e0c97268a01c0d35143cd5524bfa5/flask_avatar/avatar.py#L92-L105 |
honmaple/flask-avatar | flask_avatar/avatar.py | GenAvatar._font | def _font(size):
"""
Returns a PIL ImageFont instance.
:param size: size of the avatar, in pixels
"""
# path = '/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc'
path = os.path.join(
os.path.dirname(__file__), 'data', "wqy-microhei.ttc")
return ImageFont.truetype(path, size=int(0.65 * size), index=0) | python | def _font(size):
"""
Returns a PIL ImageFont instance.
:param size: size of the avatar, in pixels
"""
# path = '/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc'
path = os.path.join(
os.path.dirname(__file__), 'data', "wqy-microhei.ttc")
return ImageFont.truetype(path, size=int(0.65 * size), index=0) | [
"def",
"_font",
"(",
"size",
")",
":",
"# path = '/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc'",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'data'",
",",
"\"wqy-microhei.ttc\"",
"... | Returns a PIL ImageFont instance.
:param size: size of the avatar, in pixels | [
"Returns",
"a",
"PIL",
"ImageFont",
"instance",
".",
":",
"param",
"size",
":",
"size",
"of",
"the",
"avatar",
"in",
"pixels"
] | train | https://github.com/honmaple/flask-avatar/blob/6269eb538c5e0c97268a01c0d35143cd5524bfa5/flask_avatar/avatar.py#L108-L116 |
honmaple/flask-avatar | flask_avatar/avatar.py | GenAvatar._text_position | def _text_position(size, text, font):
"""
Returns the left-top point where the text should be positioned.
"""
width, height = font.getsize(text)
left = (size - width) / 2.0
top = (size - height) / 3.0
return left, top | python | def _text_position(size, text, font):
"""
Returns the left-top point where the text should be positioned.
"""
width, height = font.getsize(text)
left = (size - width) / 2.0
top = (size - height) / 3.0
return left, top | [
"def",
"_text_position",
"(",
"size",
",",
"text",
",",
"font",
")",
":",
"width",
",",
"height",
"=",
"font",
".",
"getsize",
"(",
"text",
")",
"left",
"=",
"(",
"size",
"-",
"width",
")",
"/",
"2.0",
"top",
"=",
"(",
"size",
"-",
"height",
")",... | Returns the left-top point where the text should be positioned. | [
"Returns",
"the",
"left",
"-",
"top",
"point",
"where",
"the",
"text",
"should",
"be",
"positioned",
"."
] | train | https://github.com/honmaple/flask-avatar/blob/6269eb538c5e0c97268a01c0d35143cd5524bfa5/flask_avatar/avatar.py#L129-L136 |
davebridges/mousedb | mousedb/animal/models.py | Animal.age | def age(self):
"""Calculates the animals age, relative to the current date (if alive) or the date of death (if not)."""
if self.Death:
age = self.Death - self.Born
else:
age = datetime.date.today() - self.Born
return age.days | python | def age(self):
"""Calculates the animals age, relative to the current date (if alive) or the date of death (if not)."""
if self.Death:
age = self.Death - self.Born
else:
age = datetime.date.today() - self.Born
return age.days | [
"def",
"age",
"(",
"self",
")",
":",
"if",
"self",
".",
"Death",
":",
"age",
"=",
"self",
".",
"Death",
"-",
"self",
".",
"Born",
"else",
":",
"age",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"self",
".",
"Born",
"return",
"age... | Calculates the animals age, relative to the current date (if alive) or the date of death (if not). | [
"Calculates",
"the",
"animals",
"age",
"relative",
"to",
"the",
"current",
"date",
"(",
"if",
"alive",
")",
"or",
"the",
"date",
"of",
"death",
"(",
"if",
"not",
")",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L220-L226 |
davebridges/mousedb | mousedb/animal/models.py | Animal.breeding_male_location_type | def breeding_male_location_type(self):
"""This attribute defines whether a male's current location is the same as the breeding cage to which it belongs.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
The location is relative to the first breeding cage an animal is assigned to."""
try:
self.breeding_males.all()[0].Cage
if int(self.breeding_males.all()[0].Cage) == int(self.Cage):
type = "resident-breeder"
else:
type = "non-resident-breeder"
except IndexError:
type = "unknown-breeder"
except ValueError:
type = "unknown-breeder"
return type | python | def breeding_male_location_type(self):
"""This attribute defines whether a male's current location is the same as the breeding cage to which it belongs.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
The location is relative to the first breeding cage an animal is assigned to."""
try:
self.breeding_males.all()[0].Cage
if int(self.breeding_males.all()[0].Cage) == int(self.Cage):
type = "resident-breeder"
else:
type = "non-resident-breeder"
except IndexError:
type = "unknown-breeder"
except ValueError:
type = "unknown-breeder"
return type | [
"def",
"breeding_male_location_type",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"breeding_males",
".",
"all",
"(",
")",
"[",
"0",
"]",
".",
"Cage",
"if",
"int",
"(",
"self",
".",
"breeding_males",
".",
"all",
"(",
")",
"[",
"0",
"]",
".",
"Ca... | This attribute defines whether a male's current location is the same as the breeding cage to which it belongs.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
The location is relative to the first breeding cage an animal is assigned to. | [
"This",
"attribute",
"defines",
"whether",
"a",
"male",
"s",
"current",
"location",
"is",
"the",
"same",
"as",
"the",
"breeding",
"cage",
"to",
"which",
"it",
"belongs",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L228-L243 |
davebridges/mousedb | mousedb/animal/models.py | Animal.breeding_female_location_type | def breeding_female_location_type(self):
"""This attribute defines whether a female's current location is the same as the breeding cage to which it belongs.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
The location is relative to the first breeding cage an animal is assigned to."""
try:
self.breeding_females.all()[0].Cage
if int(self.breeding_females.all()[0].Cage) == int(self.Cage):
type = "resident-breeder"
else:
type = "non-resident-breeder"
except IndexError:
type = "unknown-breeder"
except ValueError:
type = "unknown-breeder"
return type | python | def breeding_female_location_type(self):
"""This attribute defines whether a female's current location is the same as the breeding cage to which it belongs.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
The location is relative to the first breeding cage an animal is assigned to."""
try:
self.breeding_females.all()[0].Cage
if int(self.breeding_females.all()[0].Cage) == int(self.Cage):
type = "resident-breeder"
else:
type = "non-resident-breeder"
except IndexError:
type = "unknown-breeder"
except ValueError:
type = "unknown-breeder"
return type | [
"def",
"breeding_female_location_type",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"breeding_females",
".",
"all",
"(",
")",
"[",
"0",
"]",
".",
"Cage",
"if",
"int",
"(",
"self",
".",
"breeding_females",
".",
"all",
"(",
")",
"[",
"0",
"]",
".",... | This attribute defines whether a female's current location is the same as the breeding cage to which it belongs.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
The location is relative to the first breeding cage an animal is assigned to. | [
"This",
"attribute",
"defines",
"whether",
"a",
"female",
"s",
"current",
"location",
"is",
"the",
"same",
"as",
"the",
"breeding",
"cage",
"to",
"which",
"it",
"belongs",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L245-L260 |
davebridges/mousedb | mousedb/animal/models.py | Animal.save | def save(self):
"""The save method for Animal class is over-ridden to set Alive=False when a Death date is entered. This is not the case for a cause of death."""
if self.Death:
self.Alive = False
super(Animal, self).save() | python | def save(self):
"""The save method for Animal class is over-ridden to set Alive=False when a Death date is entered. This is not the case for a cause of death."""
if self.Death:
self.Alive = False
super(Animal, self).save() | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"Death",
":",
"self",
".",
"Alive",
"=",
"False",
"super",
"(",
"Animal",
",",
"self",
")",
".",
"save",
"(",
")"
] | The save method for Animal class is over-ridden to set Alive=False when a Death date is entered. This is not the case for a cause of death. | [
"The",
"save",
"method",
"for",
"Animal",
"class",
"is",
"over",
"-",
"ridden",
"to",
"set",
"Alive",
"=",
"False",
"when",
"a",
"Death",
"date",
"is",
"entered",
".",
"This",
"is",
"not",
"the",
"case",
"for",
"a",
"cause",
"of",
"death",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L267-L271 |
davebridges/mousedb | mousedb/animal/models.py | Breeding.duration | def duration(self):
"""Calculates the breeding cage's duration.
This is relative to the current date (if alive) or the date of inactivation (if not).
The duration is formatted in days."""
if self.End:
age = self.End - self.Start
else:
age = datetime.date.today() - self.Start
return age.days | python | def duration(self):
"""Calculates the breeding cage's duration.
This is relative to the current date (if alive) or the date of inactivation (if not).
The duration is formatted in days."""
if self.End:
age = self.End - self.Start
else:
age = datetime.date.today() - self.Start
return age.days | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"End",
":",
"age",
"=",
"self",
".",
"End",
"-",
"self",
".",
"Start",
"else",
":",
"age",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"self",
".",
"Start",
"return",
"... | Calculates the breeding cage's duration.
This is relative to the current date (if alive) or the date of inactivation (if not).
The duration is formatted in days. | [
"Calculates",
"the",
"breeding",
"cage",
"s",
"duration",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L299-L308 |
davebridges/mousedb | mousedb/animal/models.py | Breeding.unweaned | def unweaned(self):
"""This attribute generates a queryset of unweaned animals for this breeding cage. It is filtered for only Alive animals."""
return Animal.objects.filter(Breeding=self, Weaned__isnull=True, Alive=True) | python | def unweaned(self):
"""This attribute generates a queryset of unweaned animals for this breeding cage. It is filtered for only Alive animals."""
return Animal.objects.filter(Breeding=self, Weaned__isnull=True, Alive=True) | [
"def",
"unweaned",
"(",
"self",
")",
":",
"return",
"Animal",
".",
"objects",
".",
"filter",
"(",
"Breeding",
"=",
"self",
",",
"Weaned__isnull",
"=",
"True",
",",
"Alive",
"=",
"True",
")"
] | This attribute generates a queryset of unweaned animals for this breeding cage. It is filtered for only Alive animals. | [
"This",
"attribute",
"generates",
"a",
"queryset",
"of",
"unweaned",
"animals",
"for",
"this",
"breeding",
"cage",
".",
"It",
"is",
"filtered",
"for",
"only",
"Alive",
"animals",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L317-L319 |
davebridges/mousedb | mousedb/animal/models.py | Breeding.male_breeding_location_type | def male_breeding_location_type(self):
"""This attribute defines whether a breeding male's current location is the same as the breeding cage.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified."""
if int(self.Male.all()[0].Cage) == int(self.Cage):
type = "resident breeder"
else:
type = "non-resident breeder"
return type | python | def male_breeding_location_type(self):
"""This attribute defines whether a breeding male's current location is the same as the breeding cage.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified."""
if int(self.Male.all()[0].Cage) == int(self.Cage):
type = "resident breeder"
else:
type = "non-resident breeder"
return type | [
"def",
"male_breeding_location_type",
"(",
"self",
")",
":",
"if",
"int",
"(",
"self",
".",
"Male",
".",
"all",
"(",
")",
"[",
"0",
"]",
".",
"Cage",
")",
"==",
"int",
"(",
"self",
".",
"Cage",
")",
":",
"type",
"=",
"\"resident breeder\"",
"else",
... | This attribute defines whether a breeding male's current location is the same as the breeding cage.
This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified. | [
"This",
"attribute",
"defines",
"whether",
"a",
"breeding",
"male",
"s",
"current",
"location",
"is",
"the",
"same",
"as",
"the",
"breeding",
"cage",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L321-L329 |
davebridges/mousedb | mousedb/animal/models.py | Breeding.save | def save(self):
"""The save function for a breeding cage has to automatic over-rides, Active and the Cage for the Breeder.
In the case of Active, if an End field is specified, then the Active field is set to False.
In the case of Cage, if a Cage is provided, and animals are specified under Male or Females for a Breeding object, then the Cage field for those animals is set to that of the breeding cage. The same is true for both Rack and Rack Position."""
if self.End:
self.Active = False
#if self.Cage:
# if self.Females:
# for female_breeder in self.Females:
# female_breeder.Cage = self.Cage
# female_breeder.save()
# if self.Male:
# for male_breeder in self.Male:
# male_breeder.Cage = self.Cage
# male_breeder.save()
super(Breeding, self).save() | python | def save(self):
"""The save function for a breeding cage has to automatic over-rides, Active and the Cage for the Breeder.
In the case of Active, if an End field is specified, then the Active field is set to False.
In the case of Cage, if a Cage is provided, and animals are specified under Male or Females for a Breeding object, then the Cage field for those animals is set to that of the breeding cage. The same is true for both Rack and Rack Position."""
if self.End:
self.Active = False
#if self.Cage:
# if self.Females:
# for female_breeder in self.Females:
# female_breeder.Cage = self.Cage
# female_breeder.save()
# if self.Male:
# for male_breeder in self.Male:
# male_breeder.Cage = self.Cage
# male_breeder.save()
super(Breeding, self).save() | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"End",
":",
"self",
".",
"Active",
"=",
"False",
"#if self.Cage:",
"# if self.Females: ",
"# for female_breeder in self.Females:",
"# female_breeder.Cage = self.Cage",
"# fe... | The save function for a breeding cage has to automatic over-rides, Active and the Cage for the Breeder.
In the case of Active, if an End field is specified, then the Active field is set to False.
In the case of Cage, if a Cage is provided, and animals are specified under Male or Females for a Breeding object, then the Cage field for those animals is set to that of the breeding cage. The same is true for both Rack and Rack Position. | [
"The",
"save",
"function",
"for",
"a",
"breeding",
"cage",
"has",
"to",
"automatic",
"over",
"-",
"rides",
"Active",
"and",
"the",
"Cage",
"for",
"the",
"Breeder",
".",
"In",
"the",
"case",
"of",
"Active",
"if",
"an",
"End",
"field",
"is",
"specified",
... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/models.py#L331-L347 |
wglass/lighthouse | lighthouse/configs/monitor.py | ConfigFileMonitor.start | def start(self, on_add, on_update, on_delete):
"""
Starts monitoring the file path, passing along on_(add|update|delete)
callbacks to a watchdog observer.
Iterates over the files in the target path before starting the observer
and calls the on_created callback before starting the observer, so
that existing files aren't missed.
"""
handler = ConfigFileChangeHandler(
self.target_class, on_add, on_update, on_delete
)
for file_name in os.listdir(self.file_path):
if os.path.isdir(os.path.join(self.file_path, file_name)):
continue
if (
not self.target_class.config_subdirectory and
not (
file_name.endswith(".yaml") or file_name.endswith(".yml")
)
):
continue
handler.on_created(
events.FileCreatedEvent(
os.path.join(self.file_path, file_name)
)
)
observer = observers.Observer()
observer.schedule(handler, self.file_path)
observer.start()
return observer | python | def start(self, on_add, on_update, on_delete):
"""
Starts monitoring the file path, passing along on_(add|update|delete)
callbacks to a watchdog observer.
Iterates over the files in the target path before starting the observer
and calls the on_created callback before starting the observer, so
that existing files aren't missed.
"""
handler = ConfigFileChangeHandler(
self.target_class, on_add, on_update, on_delete
)
for file_name in os.listdir(self.file_path):
if os.path.isdir(os.path.join(self.file_path, file_name)):
continue
if (
not self.target_class.config_subdirectory and
not (
file_name.endswith(".yaml") or file_name.endswith(".yml")
)
):
continue
handler.on_created(
events.FileCreatedEvent(
os.path.join(self.file_path, file_name)
)
)
observer = observers.Observer()
observer.schedule(handler, self.file_path)
observer.start()
return observer | [
"def",
"start",
"(",
"self",
",",
"on_add",
",",
"on_update",
",",
"on_delete",
")",
":",
"handler",
"=",
"ConfigFileChangeHandler",
"(",
"self",
".",
"target_class",
",",
"on_add",
",",
"on_update",
",",
"on_delete",
")",
"for",
"file_name",
"in",
"os",
"... | Starts monitoring the file path, passing along on_(add|update|delete)
callbacks to a watchdog observer.
Iterates over the files in the target path before starting the observer
and calls the on_created callback before starting the observer, so
that existing files aren't missed. | [
"Starts",
"monitoring",
"the",
"file",
"path",
"passing",
"along",
"on_",
"(",
"add|update|delete",
")",
"callbacks",
"to",
"a",
"watchdog",
"observer",
"."
] | train | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/configs/monitor.py#L29-L63 |
rdireen/spherepy | spherepy/plot_sphere.py | matplotlibensure | def matplotlibensure(func):
"""If matplotlib isn't installed, this decorator alerts the user and
suggests how one might obtain the package."""
@wraps(func)
def wrap(*args):
if MPLINSTALLED == False:
raise ImportError(msg)
return func(*args)
return wrap | python | def matplotlibensure(func):
"""If matplotlib isn't installed, this decorator alerts the user and
suggests how one might obtain the package."""
@wraps(func)
def wrap(*args):
if MPLINSTALLED == False:
raise ImportError(msg)
return func(*args)
return wrap | [
"def",
"matplotlibensure",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrap",
"(",
"*",
"args",
")",
":",
"if",
"MPLINSTALLED",
"==",
"False",
":",
"raise",
"ImportError",
"(",
"msg",
")",
"return",
"func",
"(",
"*",
"args",
")",
... | If matplotlib isn't installed, this decorator alerts the user and
suggests how one might obtain the package. | [
"If",
"matplotlib",
"isn",
"t",
"installed",
"this",
"decorator",
"alerts",
"the",
"user",
"and",
"suggests",
"how",
"one",
"might",
"obtain",
"the",
"package",
"."
] | train | https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/plot_sphere.py#L62-L72 |
darkfeline/animanager | animanager/datets.py | to_ts | def to_ts(date: datetime.date) -> float:
"""Convert date to timestamp.
>>> to_ts(datetime.date(2001, 1, 2))
978393600.0
"""
return datetime.datetime(
date.year, date.month, date.day,
tzinfo=datetime.timezone.utc).timestamp() | python | def to_ts(date: datetime.date) -> float:
"""Convert date to timestamp.
>>> to_ts(datetime.date(2001, 1, 2))
978393600.0
"""
return datetime.datetime(
date.year, date.month, date.day,
tzinfo=datetime.timezone.utc).timestamp() | [
"def",
"to_ts",
"(",
"date",
":",
"datetime",
".",
"date",
")",
"->",
"float",
":",
"return",
"datetime",
".",
"datetime",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
",",
"tzinfo",
"=",
"datetime",
".",
"timezone",
... | Convert date to timestamp.
>>> to_ts(datetime.date(2001, 1, 2))
978393600.0 | [
"Convert",
"date",
"to",
"timestamp",
"."
] | train | https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/datets.py#L23-L31 |
darkfeline/animanager | animanager/datets.py | to_date | def to_date(ts: float) -> datetime.date:
"""Convert timestamp to date.
>>> to_date(978393600.0)
datetime.date(2001, 1, 2)
"""
return datetime.datetime.fromtimestamp(
ts, tz=datetime.timezone.utc).date() | python | def to_date(ts: float) -> datetime.date:
"""Convert timestamp to date.
>>> to_date(978393600.0)
datetime.date(2001, 1, 2)
"""
return datetime.datetime.fromtimestamp(
ts, tz=datetime.timezone.utc).date() | [
"def",
"to_date",
"(",
"ts",
":",
"float",
")",
"->",
"datetime",
".",
"date",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"ts",
",",
"tz",
"=",
"datetime",
".",
"timezone",
".",
"utc",
")",
".",
"date",
"(",
")"
] | Convert timestamp to date.
>>> to_date(978393600.0)
datetime.date(2001, 1, 2) | [
"Convert",
"timestamp",
"to",
"date",
"."
] | train | https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/datets.py#L34-L41 |
wglass/lighthouse | lighthouse/sockutils.py | get_response | def get_response(sock, buffer_size=4096):
"""
Helper method for retrieving a response from a given socket.
Returns two values in a tuple, the first is the reponse line and the second
is any extra data after the newline.
"""
response = ""
extra = ""
while True:
try:
chunk = sock.recv(buffer_size)
if chunk:
response += chunk
except socket.error as e:
if e.errno not in [errno.EAGAIN, errno.EINTR]:
raise
if not response:
break
if "\n" in response:
response, extra = response.split("\n", 1)
break
return response, extra | python | def get_response(sock, buffer_size=4096):
"""
Helper method for retrieving a response from a given socket.
Returns two values in a tuple, the first is the reponse line and the second
is any extra data after the newline.
"""
response = ""
extra = ""
while True:
try:
chunk = sock.recv(buffer_size)
if chunk:
response += chunk
except socket.error as e:
if e.errno not in [errno.EAGAIN, errno.EINTR]:
raise
if not response:
break
if "\n" in response:
response, extra = response.split("\n", 1)
break
return response, extra | [
"def",
"get_response",
"(",
"sock",
",",
"buffer_size",
"=",
"4096",
")",
":",
"response",
"=",
"\"\"",
"extra",
"=",
"\"\"",
"while",
"True",
":",
"try",
":",
"chunk",
"=",
"sock",
".",
"recv",
"(",
"buffer_size",
")",
"if",
"chunk",
":",
"response",
... | Helper method for retrieving a response from a given socket.
Returns two values in a tuple, the first is the reponse line and the second
is any extra data after the newline. | [
"Helper",
"method",
"for",
"retrieving",
"a",
"response",
"from",
"a",
"given",
"socket",
"."
] | train | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/sockutils.py#L5-L31 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.add_name_server | def add_name_server(self, server, filter=[], dynamic=None):
'''Parse a name server, adding its contents to the tree.
@param server The address of the name server, in standard
address format. e.g. 'localhost',
'localhost:2809', '59.7.0.1'.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent 'comp2.rtc' in the same naming context
from being parsed.
@param dynamic Override the tree-wide dynamic setting. If not provided,
the value given when the tree was created will be used.
'''
if dynamic == None:
dynamic = self._dynamic
self._parse_name_server(server, filter, dynamic=dynamic) | python | def add_name_server(self, server, filter=[], dynamic=None):
'''Parse a name server, adding its contents to the tree.
@param server The address of the name server, in standard
address format. e.g. 'localhost',
'localhost:2809', '59.7.0.1'.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent 'comp2.rtc' in the same naming context
from being parsed.
@param dynamic Override the tree-wide dynamic setting. If not provided,
the value given when the tree was created will be used.
'''
if dynamic == None:
dynamic = self._dynamic
self._parse_name_server(server, filter, dynamic=dynamic) | [
"def",
"add_name_server",
"(",
"self",
",",
"server",
",",
"filter",
"=",
"[",
"]",
",",
"dynamic",
"=",
"None",
")",
":",
"if",
"dynamic",
"==",
"None",
":",
"dynamic",
"=",
"self",
".",
"_dynamic",
"self",
".",
"_parse_name_server",
"(",
"server",
",... | Parse a name server, adding its contents to the tree.
@param server The address of the name server, in standard
address format. e.g. 'localhost',
'localhost:2809', '59.7.0.1'.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent 'comp2.rtc' in the same naming context
from being parsed.
@param dynamic Override the tree-wide dynamic setting. If not provided,
the value given when the tree was created will be used. | [
"Parse",
"a",
"name",
"server",
"adding",
"its",
"contents",
"to",
"the",
"tree",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L160-L177 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.is_component | def is_component(self, path):
'''Is the node pointed to by @ref path a component?'''
node = self.get_node(path)
if not node:
return False
return node.is_component | python | def is_component(self, path):
'''Is the node pointed to by @ref path a component?'''
node = self.get_node(path)
if not node:
return False
return node.is_component | [
"def",
"is_component",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"False",
"return",
"node",
".",
"is_component"
] | Is the node pointed to by @ref path a component? | [
"Is",
"the",
"node",
"pointed",
"to",
"by"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L199-L204 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.is_directory | def is_directory(self, path):
'''Is the node pointed to by @ref path a directory (name servers and
naming contexts)?
'''
node = self.get_node(path)
if not node:
return False
return node.is_directory | python | def is_directory(self, path):
'''Is the node pointed to by @ref path a directory (name servers and
naming contexts)?
'''
node = self.get_node(path)
if not node:
return False
return node.is_directory | [
"def",
"is_directory",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"False",
"return",
"node",
".",
"is_directory"
] | Is the node pointed to by @ref path a directory (name servers and
naming contexts)? | [
"Is",
"the",
"node",
"pointed",
"to",
"by",
"@ref",
"path",
"a",
"directory",
"(",
"name",
"servers",
"and",
"naming",
"contexts",
")",
"?"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L206-L214 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.is_manager | def is_manager(self, path):
'''Is the node pointed to by @ref path a manager?'''
node = self.get_node(path)
if not node:
return False
return node.is_manager | python | def is_manager(self, path):
'''Is the node pointed to by @ref path a manager?'''
node = self.get_node(path)
if not node:
return False
return node.is_manager | [
"def",
"is_manager",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"False",
"return",
"node",
".",
"is_manager"
] | Is the node pointed to by @ref path a manager? | [
"Is",
"the",
"node",
"pointed",
"to",
"by"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L216-L221 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.is_nameserver | def is_nameserver(self, path):
'''Is the node pointed to by @ref path a name server (specialisation
of directory nodes)?
'''
node = self.get_node(path)
if not node:
return False
return node.is_nameserver | python | def is_nameserver(self, path):
'''Is the node pointed to by @ref path a name server (specialisation
of directory nodes)?
'''
node = self.get_node(path)
if not node:
return False
return node.is_nameserver | [
"def",
"is_nameserver",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"False",
"return",
"node",
".",
"is_nameserver"
] | Is the node pointed to by @ref path a name server (specialisation
of directory nodes)? | [
"Is",
"the",
"node",
"pointed",
"to",
"by",
"@ref",
"path",
"a",
"name",
"server",
"(",
"specialisation",
"of",
"directory",
"nodes",
")",
"?"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L223-L231 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.is_unknown | def is_unknown(self, path):
'''Is the node pointed to by @ref path an unknown object?'''
node = self.get_node(path)
if not node:
return True
return node.is_unknown | python | def is_unknown(self, path):
'''Is the node pointed to by @ref path an unknown object?'''
node = self.get_node(path)
if not node:
return True
return node.is_unknown | [
"def",
"is_unknown",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"True",
"return",
"node",
".",
"is_unknown"
] | Is the node pointed to by @ref path an unknown object? | [
"Is",
"the",
"node",
"pointed",
"to",
"by"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L233-L238 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.is_zombie | def is_zombie(self, path):
'''Is the node pointed to by @ref path a zombie object?'''
node = self.get_node(path)
if not node:
return False
return node.is_zombie | python | def is_zombie(self, path):
'''Is the node pointed to by @ref path a zombie object?'''
node = self.get_node(path)
if not node:
return False
return node.is_zombie | [
"def",
"is_zombie",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"get_node",
"(",
"path",
")",
"if",
"not",
"node",
":",
"return",
"False",
"return",
"node",
".",
"is_zombie"
] | Is the node pointed to by @ref path a zombie object? | [
"Is",
"the",
"node",
"pointed",
"to",
"by"
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L240-L245 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.iterate | def iterate(self, func, args=None, filter=[]):
'''Call a function on the root node, and recursively all its children.
This is a depth-first iteration.
@param func The function to call. Its declaration must be
'def blag(node, args)', where 'node' is the current node
in the iteration and args is the value of @ref args.
@param args Extra arguments to pass to the function at each iteration.
Pass multiple arguments in as a tuple.
@param filter A list of filters to apply before calling func for each
node in the iteration. If the filter is not True,
@ref func will not be called for that node. Each filter
entry should be a string, representing on of the is_*
properties (is_component, etc), or a function object.
@return The results of the calls to @ref func in a list.
'''
return self._root.iterate(func, args, filter) | python | def iterate(self, func, args=None, filter=[]):
'''Call a function on the root node, and recursively all its children.
This is a depth-first iteration.
@param func The function to call. Its declaration must be
'def blag(node, args)', where 'node' is the current node
in the iteration and args is the value of @ref args.
@param args Extra arguments to pass to the function at each iteration.
Pass multiple arguments in as a tuple.
@param filter A list of filters to apply before calling func for each
node in the iteration. If the filter is not True,
@ref func will not be called for that node. Each filter
entry should be a string, representing on of the is_*
properties (is_component, etc), or a function object.
@return The results of the calls to @ref func in a list.
'''
return self._root.iterate(func, args, filter) | [
"def",
"iterate",
"(",
"self",
",",
"func",
",",
"args",
"=",
"None",
",",
"filter",
"=",
"[",
"]",
")",
":",
"return",
"self",
".",
"_root",
".",
"iterate",
"(",
"func",
",",
"args",
",",
"filter",
")"
] | Call a function on the root node, and recursively all its children.
This is a depth-first iteration.
@param func The function to call. Its declaration must be
'def blag(node, args)', where 'node' is the current node
in the iteration and args is the value of @ref args.
@param args Extra arguments to pass to the function at each iteration.
Pass multiple arguments in as a tuple.
@param filter A list of filters to apply before calling func for each
node in the iteration. If the filter is not True,
@ref func will not be called for that node. Each filter
entry should be a string, representing on of the is_*
properties (is_component, etc), or a function object.
@return The results of the calls to @ref func in a list. | [
"Call",
"a",
"function",
"on",
"the",
"root",
"node",
"and",
"recursively",
"all",
"its",
"children",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L247-L265 |
gbiggs/rtctree | rtctree/tree.py | RTCTree.load_servers_from_env | def load_servers_from_env(self, filter=[], dynamic=None):
'''Load the name servers environment variable and parse each server in
the list.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent 'comp2.rtc' in the same naming context
from being parsed.
@param dynamic Override the tree-wide dynamic setting. If not provided,
the value given when the tree was created will be used.
'''
if dynamic == None:
dynamic = self._dynamic
if NAMESERVERS_ENV_VAR in os.environ:
servers = [s for s in os.environ[NAMESERVERS_ENV_VAR].split(';') \
if s]
self._parse_name_servers(servers, filter, dynamic) | python | def load_servers_from_env(self, filter=[], dynamic=None):
'''Load the name servers environment variable and parse each server in
the list.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent 'comp2.rtc' in the same naming context
from being parsed.
@param dynamic Override the tree-wide dynamic setting. If not provided,
the value given when the tree was created will be used.
'''
if dynamic == None:
dynamic = self._dynamic
if NAMESERVERS_ENV_VAR in os.environ:
servers = [s for s in os.environ[NAMESERVERS_ENV_VAR].split(';') \
if s]
self._parse_name_servers(servers, filter, dynamic) | [
"def",
"load_servers_from_env",
"(",
"self",
",",
"filter",
"=",
"[",
"]",
",",
"dynamic",
"=",
"None",
")",
":",
"if",
"dynamic",
"==",
"None",
":",
"dynamic",
"=",
"self",
".",
"_dynamic",
"if",
"NAMESERVERS_ENV_VAR",
"in",
"os",
".",
"environ",
":",
... | Load the name servers environment variable and parse each server in
the list.
@param filter Restrict the parsed objects to only those in this
path. For example, setting filter to [['/',
'localhost', 'host.cxt', 'comp1.rtc']] will
prevent 'comp2.rtc' in the same naming context
from being parsed.
@param dynamic Override the tree-wide dynamic setting. If not provided,
the value given when the tree was created will be used. | [
"Load",
"the",
"name",
"servers",
"environment",
"variable",
"and",
"parse",
"each",
"server",
"in",
"the",
"list",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/tree.py#L267-L285 |
gbiggs/rtctree | rtctree/ports.py | parse_port | def parse_port(port_obj, owner):
'''Create a port object of the correct type.
The correct port object type is chosen based on the port.port_type
property of port_obj.
@param port_obj The CORBA PortService object to wrap.
@param owner The owner of this port. Should be a Component object or None.
@return The created port object.
'''
profile = port_obj.get_port_profile()
props = utils.nvlist_to_dict(profile.properties)
if props['port.port_type'] == 'DataInPort':
return DataInPort(port_obj, owner)
elif props['port.port_type'] == 'DataOutPort':
return DataOutPort(port_obj, owner)
elif props['port.port_type'] == 'CorbaPort':
return CorbaPort(port_obj, owner)
else:
return Port(port_obj, owner) | python | def parse_port(port_obj, owner):
'''Create a port object of the correct type.
The correct port object type is chosen based on the port.port_type
property of port_obj.
@param port_obj The CORBA PortService object to wrap.
@param owner The owner of this port. Should be a Component object or None.
@return The created port object.
'''
profile = port_obj.get_port_profile()
props = utils.nvlist_to_dict(profile.properties)
if props['port.port_type'] == 'DataInPort':
return DataInPort(port_obj, owner)
elif props['port.port_type'] == 'DataOutPort':
return DataOutPort(port_obj, owner)
elif props['port.port_type'] == 'CorbaPort':
return CorbaPort(port_obj, owner)
else:
return Port(port_obj, owner) | [
"def",
"parse_port",
"(",
"port_obj",
",",
"owner",
")",
":",
"profile",
"=",
"port_obj",
".",
"get_port_profile",
"(",
")",
"props",
"=",
"utils",
".",
"nvlist_to_dict",
"(",
"profile",
".",
"properties",
")",
"if",
"props",
"[",
"'port.port_type'",
"]",
... | Create a port object of the correct type.
The correct port object type is chosen based on the port.port_type
property of port_obj.
@param port_obj The CORBA PortService object to wrap.
@param owner The owner of this port. Should be a Component object or None.
@return The created port object. | [
"Create",
"a",
"port",
"object",
"of",
"the",
"correct",
"type",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L36-L56 |
gbiggs/rtctree | rtctree/ports.py | Port.connect | def connect(self, dests=[], name=None, id='', props={}):
'''Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Required values depend on
the type of the two ports being connected.
@raises IncompatibleDataPortConnectionPropsError, FailedToConnectError
'''
with self._mutex:
if self.porttype == 'DataInPort' or self.porttype == 'DataOutPort':
for prop in props:
if prop in self.properties:
if props[prop] not in [x.strip() for x in self.properties[prop].split(',')] and \
'any' not in self.properties[prop].lower():
# Invalid property selected
raise exceptions.IncompatibleDataPortConnectionPropsError
for d in dests:
if prop in d.properties:
if props[prop] not in [x.strip() for x in d.properties[prop].split(',')] and \
'any' not in d.properties[prop].lower():
# Invalid property selected
raise exceptions.IncompatibleDataPortConnectionPropsError
if not name:
name = self.name + '_'.join([d.name for d in dests])
props = utils.dict_to_nvlist(props)
profile = RTC.ConnectorProfile(name, id,
[self._obj] + [d._obj for d in dests], props)
return_code, profile = self._obj.connect(profile)
if return_code != RTC.RTC_OK:
raise exceptions.FailedToConnectError(return_code)
self.reparse_connections()
for d in dests:
d.reparse_connections() | python | def connect(self, dests=[], name=None, id='', props={}):
'''Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Required values depend on
the type of the two ports being connected.
@raises IncompatibleDataPortConnectionPropsError, FailedToConnectError
'''
with self._mutex:
if self.porttype == 'DataInPort' or self.porttype == 'DataOutPort':
for prop in props:
if prop in self.properties:
if props[prop] not in [x.strip() for x in self.properties[prop].split(',')] and \
'any' not in self.properties[prop].lower():
# Invalid property selected
raise exceptions.IncompatibleDataPortConnectionPropsError
for d in dests:
if prop in d.properties:
if props[prop] not in [x.strip() for x in d.properties[prop].split(',')] and \
'any' not in d.properties[prop].lower():
# Invalid property selected
raise exceptions.IncompatibleDataPortConnectionPropsError
if not name:
name = self.name + '_'.join([d.name for d in dests])
props = utils.dict_to_nvlist(props)
profile = RTC.ConnectorProfile(name, id,
[self._obj] + [d._obj for d in dests], props)
return_code, profile = self._obj.connect(profile)
if return_code != RTC.RTC_OK:
raise exceptions.FailedToConnectError(return_code)
self.reparse_connections()
for d in dests:
d.reparse_connections() | [
"def",
"connect",
"(",
"self",
",",
"dests",
"=",
"[",
"]",
",",
"name",
"=",
"None",
",",
"id",
"=",
"''",
",",
"props",
"=",
"{",
"}",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"porttype",
"==",
"'DataInPort'",
"or",
"s... | Connect this port to other ports.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Required values depend on
the type of the two ports being connected.
@raises IncompatibleDataPortConnectionPropsError, FailedToConnectError | [
"Connect",
"this",
"port",
"to",
"other",
"ports",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L83-L123 |
gbiggs/rtctree | rtctree/ports.py | Port.disconnect_all | def disconnect_all(self):
'''Disconnect all connections to this port.'''
with self._mutex:
for conn in self.connections:
self.object.disconnect(conn.id)
self.reparse_connections() | python | def disconnect_all(self):
'''Disconnect all connections to this port.'''
with self._mutex:
for conn in self.connections:
self.object.disconnect(conn.id)
self.reparse_connections() | [
"def",
"disconnect_all",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"conn",
"in",
"self",
".",
"connections",
":",
"self",
".",
"object",
".",
"disconnect",
"(",
"conn",
".",
"id",
")",
"self",
".",
"reparse_connections",
"(",
")... | Disconnect all connections to this port. | [
"Disconnect",
"all",
"connections",
"to",
"this",
"port",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L125-L130 |
gbiggs/rtctree | rtctree/ports.py | Port.get_connection_by_dest | def get_connection_by_dest(self, dest):
'''DEPRECATED. Search for a connection between this and another port.'''
with self._mutex:
for conn in self.connections:
if conn.has_port(self) and conn.has_port(dest):
return conn
return None | python | def get_connection_by_dest(self, dest):
'''DEPRECATED. Search for a connection between this and another port.'''
with self._mutex:
for conn in self.connections:
if conn.has_port(self) and conn.has_port(dest):
return conn
return None | [
"def",
"get_connection_by_dest",
"(",
"self",
",",
"dest",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"conn",
"in",
"self",
".",
"connections",
":",
"if",
"conn",
".",
"has_port",
"(",
"self",
")",
"and",
"conn",
".",
"has_port",
"(",
"dest",... | DEPRECATED. Search for a connection between this and another port. | [
"DEPRECATED",
".",
"Search",
"for",
"a",
"connection",
"between",
"this",
"and",
"another",
"port",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L132-L138 |
gbiggs/rtctree | rtctree/ports.py | Port.get_connections_by_dest | def get_connections_by_dest(self, dest):
'''Search for all connections between this and another port.'''
with self._mutex:
res = []
for c in self.connections:
if c.has_port(self) and c.has_port(dest):
res.append(c)
return res | python | def get_connections_by_dest(self, dest):
'''Search for all connections between this and another port.'''
with self._mutex:
res = []
for c in self.connections:
if c.has_port(self) and c.has_port(dest):
res.append(c)
return res | [
"def",
"get_connections_by_dest",
"(",
"self",
",",
"dest",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"connections",
":",
"if",
"c",
".",
"has_port",
"(",
"self",
")",
"and",
"c",
".",
"has_p... | Search for all connections between this and another port. | [
"Search",
"for",
"all",
"connections",
"between",
"this",
"and",
"another",
"port",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L140-L147 |
gbiggs/rtctree | rtctree/ports.py | Port.get_connections_by_dests | def get_connections_by_dests(self, dests):
'''Search for all connections involving this and all other ports.'''
with self._mutex:
res = []
for c in self.connections:
if not c.has_port(self):
continue
has_dest = False
for d in dests:
if c.has_port(d):
has_dest = True
break
if has_dest:
res.append(c)
return res | python | def get_connections_by_dests(self, dests):
'''Search for all connections involving this and all other ports.'''
with self._mutex:
res = []
for c in self.connections:
if not c.has_port(self):
continue
has_dest = False
for d in dests:
if c.has_port(d):
has_dest = True
break
if has_dest:
res.append(c)
return res | [
"def",
"get_connections_by_dests",
"(",
"self",
",",
"dests",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"connections",
":",
"if",
"not",
"c",
".",
"has_port",
"(",
"self",
")",
":",
"continue",... | Search for all connections involving this and all other ports. | [
"Search",
"for",
"all",
"connections",
"involving",
"this",
"and",
"all",
"other",
"ports",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L149-L163 |
gbiggs/rtctree | rtctree/ports.py | Port.get_connection_by_id | def get_connection_by_id(self, id):
'''Search for a connection on this port by its ID.'''
with self._mutex:
for conn in self.connections:
if conn.id == id:
return conn
return None | python | def get_connection_by_id(self, id):
'''Search for a connection on this port by its ID.'''
with self._mutex:
for conn in self.connections:
if conn.id == id:
return conn
return None | [
"def",
"get_connection_by_id",
"(",
"self",
",",
"id",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"conn",
"in",
"self",
".",
"connections",
":",
"if",
"conn",
".",
"id",
"==",
"id",
":",
"return",
"conn",
"return",
"None"
] | Search for a connection on this port by its ID. | [
"Search",
"for",
"a",
"connection",
"on",
"this",
"port",
"by",
"its",
"ID",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L165-L171 |
gbiggs/rtctree | rtctree/ports.py | Port.get_connection_by_name | def get_connection_by_name(self, name):
'''Search for a connection to or from this port by name.'''
with self._mutex:
for conn in self.connections:
if conn.name == name:
return conn
return None | python | def get_connection_by_name(self, name):
'''Search for a connection to or from this port by name.'''
with self._mutex:
for conn in self.connections:
if conn.name == name:
return conn
return None | [
"def",
"get_connection_by_name",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"conn",
"in",
"self",
".",
"connections",
":",
"if",
"conn",
".",
"name",
"==",
"name",
":",
"return",
"conn",
"return",
"None"
] | Search for a connection to or from this port by name. | [
"Search",
"for",
"a",
"connection",
"to",
"or",
"from",
"this",
"port",
"by",
"name",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L173-L179 |
gbiggs/rtctree | rtctree/ports.py | Port.connections | def connections(self):
'''A list of connections to or from this port.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered).
'''
with self._mutex:
if not self._connections:
self._connections = [Connection(cp, self) \
for cp in self._obj.get_connector_profiles()]
return self._connections | python | def connections(self):
'''A list of connections to or from this port.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered).
'''
with self._mutex:
if not self._connections:
self._connections = [Connection(cp, self) \
for cp in self._obj.get_connector_profiles()]
return self._connections | [
"def",
"connections",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_connections",
":",
"self",
".",
"_connections",
"=",
"[",
"Connection",
"(",
"cp",
",",
"self",
")",
"for",
"cp",
"in",
"self",
".",
"_obj",
... | A list of connections to or from this port.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered). | [
"A",
"list",
"of",
"connections",
"to",
"or",
"from",
"this",
"port",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L192-L205 |
gbiggs/rtctree | rtctree/ports.py | DataPort.connect | def connect(self, dests=[], name=None, id='', props={}):
'''Connect this port to other DataPorts.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Suitable defaults will be
set for required values if they are not already present.
@raises WrongPortTypeError
'''
# Data ports can only connect to opposite data ports
with self._mutex:
new_props = props.copy()
ptypes = [d.porttype for d in dests]
if self.porttype == 'DataInPort':
if 'DataOutPort' not in ptypes:
raise exceptions.WrongPortTypeError
if self.porttype == 'DataOutPort':
if 'DataInPort' not in ptypes:
raise exceptions.WrongPortTypeError
if 'dataport.dataflow_type' not in new_props:
new_props['dataport.dataflow_type'] = 'push'
if 'dataport.interface_type' not in new_props:
new_props['dataport.interface_type'] = 'corba_cdr'
if 'dataport.subscription_type' not in new_props:
new_props['dataport.subscription_type'] = 'new'
if 'dataport.data_type' not in new_props:
new_props['dataport.data_type'] = \
self.properties['dataport.data_type']
super(DataPort, self).connect(dests=dests, name=name, id=id,
props=new_props) | python | def connect(self, dests=[], name=None, id='', props={}):
'''Connect this port to other DataPorts.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Suitable defaults will be
set for required values if they are not already present.
@raises WrongPortTypeError
'''
# Data ports can only connect to opposite data ports
with self._mutex:
new_props = props.copy()
ptypes = [d.porttype for d in dests]
if self.porttype == 'DataInPort':
if 'DataOutPort' not in ptypes:
raise exceptions.WrongPortTypeError
if self.porttype == 'DataOutPort':
if 'DataInPort' not in ptypes:
raise exceptions.WrongPortTypeError
if 'dataport.dataflow_type' not in new_props:
new_props['dataport.dataflow_type'] = 'push'
if 'dataport.interface_type' not in new_props:
new_props['dataport.interface_type'] = 'corba_cdr'
if 'dataport.subscription_type' not in new_props:
new_props['dataport.subscription_type'] = 'new'
if 'dataport.data_type' not in new_props:
new_props['dataport.data_type'] = \
self.properties['dataport.data_type']
super(DataPort, self).connect(dests=dests, name=name, id=id,
props=new_props) | [
"def",
"connect",
"(",
"self",
",",
"dests",
"=",
"[",
"]",
",",
"name",
"=",
"None",
",",
"id",
"=",
"''",
",",
"props",
"=",
"{",
"}",
")",
":",
"# Data ports can only connect to opposite data ports",
"with",
"self",
".",
"_mutex",
":",
"new_props",
"=... | Connect this port to other DataPorts.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Suitable defaults will be
set for required values if they are not already present.
@raises WrongPortTypeError | [
"Connect",
"this",
"port",
"to",
"other",
"DataPorts",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L280-L316 |
gbiggs/rtctree | rtctree/ports.py | CorbaPort.connect | def connect(self, dests=None, name=None, id='', props={}):
'''Connect this port to other CorbaPorts.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Suitable defaults will be
set for required values if they are not already present.
@raises WrongPortTypeError, MismatchedInterfacesError,
MismatchedPolarityError
'''
with self._mutex:
# Corba ports can only connect to corba ports of the opposite
# polarity
for d in dests:
if not d.porttype == 'CorbaPort':
raise exceptions.WrongPortTypeError
# Check the interfaces and their respective polarities match
if self.interfaces:
for d in dests:
if not d.interfaces:
raise exceptions.MismatchedInterfacesError
for intf in self.interfaces:
for d in dests:
match = d.get_interface_by_instance_name(
intf.instance_name)
if not match:
raise exceptions.MismatchedInterfacesError
if intf.polarity == match.polarity:
# Polarity should be opposite
raise exceptions.MismatchedPolarityError
else:
for d in dests:
if d.interfaces:
raise exceptions.MismatchedInterfacesError
# Make the connection
new_props = props.copy()
if 'port.port_type' not in new_props:
new_props['port.port_type'] = 'CorbaPort'
super(CorbaPort, self).connect(dests=dests, name=name, id=id,
props=new_props) | python | def connect(self, dests=None, name=None, id='', props={}):
'''Connect this port to other CorbaPorts.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Suitable defaults will be
set for required values if they are not already present.
@raises WrongPortTypeError, MismatchedInterfacesError,
MismatchedPolarityError
'''
with self._mutex:
# Corba ports can only connect to corba ports of the opposite
# polarity
for d in dests:
if not d.porttype == 'CorbaPort':
raise exceptions.WrongPortTypeError
# Check the interfaces and their respective polarities match
if self.interfaces:
for d in dests:
if not d.interfaces:
raise exceptions.MismatchedInterfacesError
for intf in self.interfaces:
for d in dests:
match = d.get_interface_by_instance_name(
intf.instance_name)
if not match:
raise exceptions.MismatchedInterfacesError
if intf.polarity == match.polarity:
# Polarity should be opposite
raise exceptions.MismatchedPolarityError
else:
for d in dests:
if d.interfaces:
raise exceptions.MismatchedInterfacesError
# Make the connection
new_props = props.copy()
if 'port.port_type' not in new_props:
new_props['port.port_type'] = 'CorbaPort'
super(CorbaPort, self).connect(dests=dests, name=name, id=id,
props=new_props) | [
"def",
"connect",
"(",
"self",
",",
"dests",
"=",
"None",
",",
"name",
"=",
"None",
",",
"id",
"=",
"''",
",",
"props",
"=",
"{",
"}",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"# Corba ports can only connect to corba ports of the opposite",
"# polarity"... | Connect this port to other CorbaPorts.
After the connection has been made, a delayed reparse of the
connections for this and the destination port will be triggered.
@param dests A list of the destination Port objects. Must be provided.
@param name The name of the connection. If None, a suitable default
will be created based on the names of the two ports.
@param id The ID of this connection. If None, one will be generated by
the RTC implementation.
@param props Properties of the connection. Suitable defaults will be
set for required values if they are not already present.
@raises WrongPortTypeError, MismatchedInterfacesError,
MismatchedPolarityError | [
"Connect",
"this",
"port",
"to",
"other",
"CorbaPorts",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L358-L404 |
gbiggs/rtctree | rtctree/ports.py | CorbaPort.get_interface_by_instance_name | def get_interface_by_instance_name(self, name):
'''Get an interface of this port by instance name.'''
with self._mutex:
for intf in self.interfaces:
if intf.instance_name == name:
return intf
return None | python | def get_interface_by_instance_name(self, name):
'''Get an interface of this port by instance name.'''
with self._mutex:
for intf in self.interfaces:
if intf.instance_name == name:
return intf
return None | [
"def",
"get_interface_by_instance_name",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"intf",
"in",
"self",
".",
"interfaces",
":",
"if",
"intf",
".",
"instance_name",
"==",
"name",
":",
"return",
"intf",
"return",
"None"
... | Get an interface of this port by instance name. | [
"Get",
"an",
"interface",
"of",
"this",
"port",
"by",
"instance",
"name",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L406-L412 |
gbiggs/rtctree | rtctree/ports.py | CorbaPort.interfaces | def interfaces(self):
'''The list of interfaces this port provides or uses.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered).
'''
with self._mutex:
if not self._interfaces:
profile = self._obj.get_port_profile()
self._interfaces = [SvcInterface(intf) \
for intf in profile.interfaces]
return self._interfaces | python | def interfaces(self):
'''The list of interfaces this port provides or uses.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered).
'''
with self._mutex:
if not self._interfaces:
profile = self._obj.get_port_profile()
self._interfaces = [SvcInterface(intf) \
for intf in profile.interfaces]
return self._interfaces | [
"def",
"interfaces",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_interfaces",
":",
"profile",
"=",
"self",
".",
"_obj",
".",
"get_port_profile",
"(",
")",
"self",
".",
"_interfaces",
"=",
"[",
"SvcInterface",
... | The list of interfaces this port provides or uses.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered). | [
"The",
"list",
"of",
"interfaces",
"this",
"port",
"provides",
"or",
"uses",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L415-L429 |
gbiggs/rtctree | rtctree/ports.py | SvcInterface.polarity_as_string | def polarity_as_string(self, add_colour=True):
'''Get the polarity of this interface as a string.
@param add_colour If True, ANSI colour codes will be added to the
string.
@return A string describing the polarity of this interface.
'''
with self._mutex:
if self.polarity == self.PROVIDED:
result = 'Provided', ['reset']
elif self.polarity == self.REQUIRED:
result = 'Required', ['reset']
if add_colour:
return utils.build_attr_string(result[1], supported=add_colour) + \
result[0] + utils.build_attr_string('reset',
supported=add_colour)
else:
return result[0] | python | def polarity_as_string(self, add_colour=True):
'''Get the polarity of this interface as a string.
@param add_colour If True, ANSI colour codes will be added to the
string.
@return A string describing the polarity of this interface.
'''
with self._mutex:
if self.polarity == self.PROVIDED:
result = 'Provided', ['reset']
elif self.polarity == self.REQUIRED:
result = 'Required', ['reset']
if add_colour:
return utils.build_attr_string(result[1], supported=add_colour) + \
result[0] + utils.build_attr_string('reset',
supported=add_colour)
else:
return result[0] | [
"def",
"polarity_as_string",
"(",
"self",
",",
"add_colour",
"=",
"True",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"polarity",
"==",
"self",
".",
"PROVIDED",
":",
"result",
"=",
"'Provided'",
",",
"[",
"'reset'",
"]",
"elif",
"s... | Get the polarity of this interface as a string.
@param add_colour If True, ANSI colour codes will be added to the
string.
@return A string describing the polarity of this interface. | [
"Get",
"the",
"polarity",
"of",
"this",
"interface",
"as",
"a",
"string",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L448-L466 |
gbiggs/rtctree | rtctree/ports.py | Connection.disconnect | def disconnect(self):
'''Disconnect this connection.'''
with self._mutex:
if not self.ports:
raise exceptions.NotConnectedError
# Some of the connection participants may not be in the tree,
# causing the port search in self.ports to return ('Unknown', None)
# for those participants. Search the list to find the first
# participant that is in the tree (there must be at least one).
p = self.ports[0][1]
ii = 1
while not p and ii < len(self.ports):
p = self.ports[ii][1]
ii += 1
if not p:
raise exceptions.UnknownConnectionOwnerError
p.object.disconnect(self.id) | python | def disconnect(self):
'''Disconnect this connection.'''
with self._mutex:
if not self.ports:
raise exceptions.NotConnectedError
# Some of the connection participants may not be in the tree,
# causing the port search in self.ports to return ('Unknown', None)
# for those participants. Search the list to find the first
# participant that is in the tree (there must be at least one).
p = self.ports[0][1]
ii = 1
while not p and ii < len(self.ports):
p = self.ports[ii][1]
ii += 1
if not p:
raise exceptions.UnknownConnectionOwnerError
p.object.disconnect(self.id) | [
"def",
"disconnect",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"ports",
":",
"raise",
"exceptions",
".",
"NotConnectedError",
"# Some of the connection participants may not be in the tree,",
"# causing the port search in self.por... | Disconnect this connection. | [
"Disconnect",
"this",
"connection",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L536-L552 |
gbiggs/rtctree | rtctree/ports.py | Connection.has_port | def has_port(self, port):
'''Return True if this connection involves the given Port object.
@param port The Port object to search for in this connection's ports.
'''
with self._mutex:
for p in self.ports:
if not p[1]:
# Port owner not in tree, so unknown
continue
if port.object._is_equivalent(p[1].object):
return True
return False | python | def has_port(self, port):
'''Return True if this connection involves the given Port object.
@param port The Port object to search for in this connection's ports.
'''
with self._mutex:
for p in self.ports:
if not p[1]:
# Port owner not in tree, so unknown
continue
if port.object._is_equivalent(p[1].object):
return True
return False | [
"def",
"has_port",
"(",
"self",
",",
"port",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"for",
"p",
"in",
"self",
".",
"ports",
":",
"if",
"not",
"p",
"[",
"1",
"]",
":",
"# Port owner not in tree, so unknown",
"continue",
"if",
"port",
".",
"object... | Return True if this connection involves the given Port object.
@param port The Port object to search for in this connection's ports. | [
"Return",
"True",
"if",
"this",
"connection",
"involves",
"the",
"given",
"Port",
"object",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L554-L567 |
gbiggs/rtctree | rtctree/ports.py | Connection.ports | def ports(self):
'''The list of ports involved in this connection.
The result is a list of tuples, (port name, port object). Each port
name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if
this Connection object is owned by a Port, which is in turn owned by
a Component in the tree. Otherwise, only the port's name will be used
(in which case it will be the full port name, which will include the
component name, e.g. 'ConsoleIn0.in'). The full path can be used to
find ports in the tree.
If, for some reason, the owner node of a port cannot be found, that
entry in the list will contain ('Unknown', None). This typically means
that a component's name has been clobbered on the name server.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered).
'''
def has_port(node, args):
if node.get_port_by_ref(args):
return node
return None
with self._mutex:
if not self._ports:
self._ports = []
for p in self._obj.ports:
# My owner's owner is a component node in the tree
if self.owner and self.owner.owner:
root = self.owner.owner.root
owner_nodes = [n for n in root.iterate(has_port,
args=p, filter=['is_component']) if n]
if not owner_nodes:
self._ports.append(('Unknown', None))
else:
port_owner = owner_nodes[0]
port_owner_path = port_owner.full_path_str
port_name = p.get_port_profile().name
prefix = port_owner.instance_name + '.'
if port_name.startswith(prefix):
port_name = port_name[len(prefix):]
self._ports.append((port_owner_path + ':' + \
port_name, parse_port(p, self.owner.owner)))
else:
self._ports.append((p.get_port_profile().name,
parse_port(p, None)))
return self._ports | python | def ports(self):
'''The list of ports involved in this connection.
The result is a list of tuples, (port name, port object). Each port
name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if
this Connection object is owned by a Port, which is in turn owned by
a Component in the tree. Otherwise, only the port's name will be used
(in which case it will be the full port name, which will include the
component name, e.g. 'ConsoleIn0.in'). The full path can be used to
find ports in the tree.
If, for some reason, the owner node of a port cannot be found, that
entry in the list will contain ('Unknown', None). This typically means
that a component's name has been clobbered on the name server.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered).
'''
def has_port(node, args):
if node.get_port_by_ref(args):
return node
return None
with self._mutex:
if not self._ports:
self._ports = []
for p in self._obj.ports:
# My owner's owner is a component node in the tree
if self.owner and self.owner.owner:
root = self.owner.owner.root
owner_nodes = [n for n in root.iterate(has_port,
args=p, filter=['is_component']) if n]
if not owner_nodes:
self._ports.append(('Unknown', None))
else:
port_owner = owner_nodes[0]
port_owner_path = port_owner.full_path_str
port_name = p.get_port_profile().name
prefix = port_owner.instance_name + '.'
if port_name.startswith(prefix):
port_name = port_name[len(prefix):]
self._ports.append((port_owner_path + ':' + \
port_name, parse_port(p, self.owner.owner)))
else:
self._ports.append((p.get_port_profile().name,
parse_port(p, None)))
return self._ports | [
"def",
"ports",
"(",
"self",
")",
":",
"def",
"has_port",
"(",
"node",
",",
"args",
")",
":",
"if",
"node",
".",
"get_port_by_ref",
"(",
"args",
")",
":",
"return",
"node",
"return",
"None",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
... | The list of ports involved in this connection.
The result is a list of tuples, (port name, port object). Each port
name is a full path to the port (e.g. /localhost/Comp0.rtc:in) if
this Connection object is owned by a Port, which is in turn owned by
a Component in the tree. Otherwise, only the port's name will be used
(in which case it will be the full port name, which will include the
component name, e.g. 'ConsoleIn0.in'). The full path can be used to
find ports in the tree.
If, for some reason, the owner node of a port cannot be found, that
entry in the list will contain ('Unknown', None). This typically means
that a component's name has been clobbered on the name server.
This list will be created at the first reference to this property.
This means that the first reference may be delayed by CORBA calls,
but others will return quickly (unless a delayed reparse has been
triggered). | [
"The",
"list",
"of",
"ports",
"involved",
"in",
"this",
"connection",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/ports.py#L592-L641 |
ucbvislab/radiotool | radiotool/composer/song.py | Song.analysis | def analysis(self):
"""Get musical analysis of the song using the librosa library
"""
if self._analysis is not None:
return self._analysis
if self.cache_dir is not None:
path = os.path.join(self.cache_dir, self.checksum)
try:
if self.refresh_cache: raise IOError
with open(path + '.pickle', 'rb') as pickle_file:
self._analysis = pickle.load(pickle_file)
except IOError:
self._analysis = librosa_analysis.analyze_frames(self.all_as_mono(), self.samplerate)
with open(path + '.pickle', 'wb') as pickle_file:
pickle.dump(self._analysis, pickle_file, pickle.HIGHEST_PROTOCOL)
else:
self._analysis = librosa_analysis.analyze_frames(self.all_as_mono(), self.samplerate)
return self._analysis | python | def analysis(self):
"""Get musical analysis of the song using the librosa library
"""
if self._analysis is not None:
return self._analysis
if self.cache_dir is not None:
path = os.path.join(self.cache_dir, self.checksum)
try:
if self.refresh_cache: raise IOError
with open(path + '.pickle', 'rb') as pickle_file:
self._analysis = pickle.load(pickle_file)
except IOError:
self._analysis = librosa_analysis.analyze_frames(self.all_as_mono(), self.samplerate)
with open(path + '.pickle', 'wb') as pickle_file:
pickle.dump(self._analysis, pickle_file, pickle.HIGHEST_PROTOCOL)
else:
self._analysis = librosa_analysis.analyze_frames(self.all_as_mono(), self.samplerate)
return self._analysis | [
"def",
"analysis",
"(",
"self",
")",
":",
"if",
"self",
".",
"_analysis",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_analysis",
"if",
"self",
".",
"cache_dir",
"is",
"not",
"None",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sel... | Get musical analysis of the song using the librosa library | [
"Get",
"musical",
"analysis",
"of",
"the",
"song",
"using",
"the",
"librosa",
"library"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/song.py#L25-L43 |
davebridges/mousedb | mousedb/animal/views.py | breeding_pups | def breeding_pups(request, breeding_id):
"""This view is used to generate a form by which to add pups which belong to a particular breeding set.
This view is intended to be used to add initial information about pups, including eartag, genotype, gender and birth or weaning information.
It takes a request in the form /breeding/(breeding_id)/pups/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view is restricted to those with the permission animal.add_animal.
"""
breeding = get_object_or_404(Breeding, pk=breeding_id)
PupsFormSet = inlineformset_factory(Breeding, Animal, extra=10, exclude=('Notes','Alive', 'Death', 'Cause_of_Death', 'Father', 'Mother', 'Breeding'))
if request.method == "POST":
formset = PupsFormSet(request.POST, instance=breeding)
if formset.is_valid():
formset.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
formset = PupsFormSet(instance=breeding)
return render("breeding_pups.html", {"formset":formset, 'breeding':breeding}) | python | def breeding_pups(request, breeding_id):
"""This view is used to generate a form by which to add pups which belong to a particular breeding set.
This view is intended to be used to add initial information about pups, including eartag, genotype, gender and birth or weaning information.
It takes a request in the form /breeding/(breeding_id)/pups/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view is restricted to those with the permission animal.add_animal.
"""
breeding = get_object_or_404(Breeding, pk=breeding_id)
PupsFormSet = inlineformset_factory(Breeding, Animal, extra=10, exclude=('Notes','Alive', 'Death', 'Cause_of_Death', 'Father', 'Mother', 'Breeding'))
if request.method == "POST":
formset = PupsFormSet(request.POST, instance=breeding)
if formset.is_valid():
formset.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
formset = PupsFormSet(instance=breeding)
return render("breeding_pups.html", {"formset":formset, 'breeding':breeding}) | [
"def",
"breeding_pups",
"(",
"request",
",",
"breeding_id",
")",
":",
"breeding",
"=",
"get_object_or_404",
"(",
"Breeding",
",",
"pk",
"=",
"breeding_id",
")",
"PupsFormSet",
"=",
"inlineformset_factory",
"(",
"Breeding",
",",
"Animal",
",",
"extra",
"=",
"10... | This view is used to generate a form by which to add pups which belong to a particular breeding set.
This view is intended to be used to add initial information about pups, including eartag, genotype, gender and birth or weaning information.
It takes a request in the form /breeding/(breeding_id)/pups/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view is restricted to those with the permission animal.add_animal. | [
"This",
"view",
"is",
"used",
"to",
"generate",
"a",
"form",
"by",
"which",
"to",
"add",
"pups",
"which",
"belong",
"to",
"a",
"particular",
"breeding",
"set",
".",
"This",
"view",
"is",
"intended",
"to",
"be",
"used",
"to",
"add",
"initial",
"informatio... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L355-L371 |
davebridges/mousedb | mousedb/animal/views.py | breeding_change | def breeding_change(request, breeding_id):
"""This view is used to generate a form by which to change pups which belong to a particular breeding set.
This view typically is used to modify existing pups. This might include marking animals as sacrificed, entering genotype or marking information or entering movement of mice to another cage. It is used to show and modify several animals at once.
It takes a request in the form /breeding/(breeding_id)/change/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view returns a formset in which one row represents one animal. To add extra animals to a breeding set use /breeding/(breeding_id)/pups/.
This view is restricted to those with the permission animal.change_animal.
"""
breeding = Breeding.objects.select_related().get(id=breeding_id)
strain = breeding.Strain
PupsFormSet = inlineformset_factory(Breeding, Animal, extra=0, exclude=('Alive','Father', 'Mother', 'Breeding', 'Notes'))
if request.method =="POST":
formset = PupsFormSet(request.POST, instance=breeding)
if formset.is_valid():
formset.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
formset = PupsFormSet(instance=breeding,)
return render(request, "breeding_change.html", {"formset":formset, 'breeding':breeding}) | python | def breeding_change(request, breeding_id):
"""This view is used to generate a form by which to change pups which belong to a particular breeding set.
This view typically is used to modify existing pups. This might include marking animals as sacrificed, entering genotype or marking information or entering movement of mice to another cage. It is used to show and modify several animals at once.
It takes a request in the form /breeding/(breeding_id)/change/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view returns a formset in which one row represents one animal. To add extra animals to a breeding set use /breeding/(breeding_id)/pups/.
This view is restricted to those with the permission animal.change_animal.
"""
breeding = Breeding.objects.select_related().get(id=breeding_id)
strain = breeding.Strain
PupsFormSet = inlineformset_factory(Breeding, Animal, extra=0, exclude=('Alive','Father', 'Mother', 'Breeding', 'Notes'))
if request.method =="POST":
formset = PupsFormSet(request.POST, instance=breeding)
if formset.is_valid():
formset.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
formset = PupsFormSet(instance=breeding,)
return render(request, "breeding_change.html", {"formset":formset, 'breeding':breeding}) | [
"def",
"breeding_change",
"(",
"request",
",",
"breeding_id",
")",
":",
"breeding",
"=",
"Breeding",
".",
"objects",
".",
"select_related",
"(",
")",
".",
"get",
"(",
"id",
"=",
"breeding_id",
")",
"strain",
"=",
"breeding",
".",
"Strain",
"PupsFormSet",
"... | This view is used to generate a form by which to change pups which belong to a particular breeding set.
This view typically is used to modify existing pups. This might include marking animals as sacrificed, entering genotype or marking information or entering movement of mice to another cage. It is used to show and modify several animals at once.
It takes a request in the form /breeding/(breeding_id)/change/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view returns a formset in which one row represents one animal. To add extra animals to a breeding set use /breeding/(breeding_id)/pups/.
This view is restricted to those with the permission animal.change_animal. | [
"This",
"view",
"is",
"used",
"to",
"generate",
"a",
"form",
"by",
"which",
"to",
"change",
"pups",
"which",
"belong",
"to",
"a",
"particular",
"breeding",
"set",
".",
"This",
"view",
"typically",
"is",
"used",
"to",
"modify",
"existing",
"pups",
".",
"T... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L374-L392 |
davebridges/mousedb | mousedb/animal/views.py | breeding_wean | def breeding_wean(request, breeding_id):
"""This view is used to generate a form by which to wean pups which belong to a particular breeding set.
This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-change page.
It takes a request in the form /breeding/(breeding_id)/wean/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view returns a formset in which one row represents one animal. To add extra animals to a breeding set use /breeding/(breeding_id)/pups/.
This view is restricted to those with the permission animal.change_animal.
"""
breeding = Breeding.objects.get(id=breeding_id)
strain = breeding.Strain
PupsFormSet = inlineformset_factory(Breeding, Animal, extra=0, exclude=('Alive','Father', 'Mother', 'Breeding', 'Notes','Rack','Rack_Position','Strain','Background','Genotype','Death','Cause_of_Death','Backcross','Generation'))
if request.method =="POST":
formset = PupsFormSet(request.POST, instance=breeding, queryset=Animal.objects.filter(Alive=True, Weaned__isnull=True))
if formset.is_valid():
formset.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
formset = PupsFormSet(instance=breeding, queryset=Animal.objects.filter(Alive=True, Weaned__isnull=True))
return render(request, "breeding_wean.html", {"formset":formset, 'breeding':breeding}) | python | def breeding_wean(request, breeding_id):
"""This view is used to generate a form by which to wean pups which belong to a particular breeding set.
This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-change page.
It takes a request in the form /breeding/(breeding_id)/wean/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view returns a formset in which one row represents one animal. To add extra animals to a breeding set use /breeding/(breeding_id)/pups/.
This view is restricted to those with the permission animal.change_animal.
"""
breeding = Breeding.objects.get(id=breeding_id)
strain = breeding.Strain
PupsFormSet = inlineformset_factory(Breeding, Animal, extra=0, exclude=('Alive','Father', 'Mother', 'Breeding', 'Notes','Rack','Rack_Position','Strain','Background','Genotype','Death','Cause_of_Death','Backcross','Generation'))
if request.method =="POST":
formset = PupsFormSet(request.POST, instance=breeding, queryset=Animal.objects.filter(Alive=True, Weaned__isnull=True))
if formset.is_valid():
formset.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
formset = PupsFormSet(instance=breeding, queryset=Animal.objects.filter(Alive=True, Weaned__isnull=True))
return render(request, "breeding_wean.html", {"formset":formset, 'breeding':breeding}) | [
"def",
"breeding_wean",
"(",
"request",
",",
"breeding_id",
")",
":",
"breeding",
"=",
"Breeding",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"breeding_id",
")",
"strain",
"=",
"breeding",
".",
"Strain",
"PupsFormSet",
"=",
"inlineformset_factory",
"(",
"Br... | This view is used to generate a form by which to wean pups which belong to a particular breeding set.
This view typically is used to wean existing pups. This includes the MouseID, Cage, Markings, Gender and Wean Date fields. For other fields use the breeding-change page.
It takes a request in the form /breeding/(breeding_id)/wean/ and returns a form specific to the breeding set defined in breeding_id. breeding_id is the background identification number of the breeding set and does not refer to the barcode of any breeding cage.
This view returns a formset in which one row represents one animal. To add extra animals to a breeding set use /breeding/(breeding_id)/pups/.
This view is restricted to those with the permission animal.change_animal. | [
"This",
"view",
"is",
"used",
"to",
"generate",
"a",
"form",
"by",
"which",
"to",
"wean",
"pups",
"which",
"belong",
"to",
"a",
"particular",
"breeding",
"set",
".",
"This",
"view",
"typically",
"is",
"used",
"to",
"wean",
"existing",
"pups",
".",
"This"... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L395-L413 |
davebridges/mousedb | mousedb/animal/views.py | multiple_pups | def multiple_pups(request):
"""This view is used to enter multiple animals at the same time.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
"""
if request.method == "POST":
form = MultipleAnimalForm(request.POST)
if form.is_valid():
count = form.cleaned_data['count']
for i in range(count):
animal = Animal(
Strain = form.cleaned_data['Strain'],
Background = form.cleaned_data['Background'],
Breeding = form.cleaned_data['Breeding'],
Cage = form.cleaned_data['Cage'],
Rack = form.cleaned_data['Rack'],
Rack_Position = form.cleaned_data['Rack_Position'],
Genotype = form.cleaned_data['Genotype'],
Gender = form.cleaned_data['Gender'],
Born = form.cleaned_data['Born'],
Weaned = form.cleaned_data['Weaned'],
Backcross = form.cleaned_data['Backcross'],
Generation = form.cleaned_data['Generation'],
Father = form.cleaned_data['Father'],
Mother = form.cleaned_data['Mother'],
Markings = form.cleaned_data['Markings'],
Notes = form.cleaned_data['Notes'])
animal.save()
return HttpResponseRedirect( reverse('strain-list') )
else:
form = MultipleAnimalForm()
return render(request, "animal_multiple_form.html", {"form":form,}) | python | def multiple_pups(request):
"""This view is used to enter multiple animals at the same time.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
"""
if request.method == "POST":
form = MultipleAnimalForm(request.POST)
if form.is_valid():
count = form.cleaned_data['count']
for i in range(count):
animal = Animal(
Strain = form.cleaned_data['Strain'],
Background = form.cleaned_data['Background'],
Breeding = form.cleaned_data['Breeding'],
Cage = form.cleaned_data['Cage'],
Rack = form.cleaned_data['Rack'],
Rack_Position = form.cleaned_data['Rack_Position'],
Genotype = form.cleaned_data['Genotype'],
Gender = form.cleaned_data['Gender'],
Born = form.cleaned_data['Born'],
Weaned = form.cleaned_data['Weaned'],
Backcross = form.cleaned_data['Backcross'],
Generation = form.cleaned_data['Generation'],
Father = form.cleaned_data['Father'],
Mother = form.cleaned_data['Mother'],
Markings = form.cleaned_data['Markings'],
Notes = form.cleaned_data['Notes'])
animal.save()
return HttpResponseRedirect( reverse('strain-list') )
else:
form = MultipleAnimalForm()
return render(request, "animal_multiple_form.html", {"form":form,}) | [
"def",
"multiple_pups",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"MultipleAnimalForm",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"count",
"=",
"form",
".",
"clea... | This view is used to enter multiple animals at the same time.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes. | [
"This",
"view",
"is",
"used",
"to",
"enter",
"multiple",
"animals",
"at",
"the",
"same",
"time",
".",
"It",
"will",
"generate",
"a",
"form",
"containing",
"animal",
"information",
"and",
"a",
"number",
"of",
"mice",
".",
"It",
"is",
"intended",
"to",
"cr... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L415-L446 |
davebridges/mousedb | mousedb/animal/views.py | multiple_breeding_pups | def multiple_breeding_pups(request, breeding_id):
"""This view is used to enter multiple animals at the same time from a breeding cage.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
This view requres an input of a breeding_id to generate the correct form.
"""
breeding = Breeding.objects.get(id=breeding_id)
if request.method == "POST":
form = MultipleBreedingAnimalForm(request.POST)
if form.is_valid():
count = form.cleaned_data['count']
for i in range(count):
animal = Animal(
Strain = breeding.Strain,
Background = breeding.background,
Breeding = breeding,
Cage = breeding.Cage,
Rack = breeding.Rack,
Rack_Position = breeding.Rack_Position,
Genotype = breeding.genotype,
Gender = form.cleaned_data['Gender'],
Born = form.cleaned_data['Born'],
Weaned = form.cleaned_data['Weaned'],
Backcross = breeding.backcross,
Generation = breeding.generation)
animal.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
form = MultipleBreedingAnimalForm()
return render(request, "animal_multiple_form.html", {"form":form, "breeding":breeding}) | python | def multiple_breeding_pups(request, breeding_id):
"""This view is used to enter multiple animals at the same time from a breeding cage.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
This view requres an input of a breeding_id to generate the correct form.
"""
breeding = Breeding.objects.get(id=breeding_id)
if request.method == "POST":
form = MultipleBreedingAnimalForm(request.POST)
if form.is_valid():
count = form.cleaned_data['count']
for i in range(count):
animal = Animal(
Strain = breeding.Strain,
Background = breeding.background,
Breeding = breeding,
Cage = breeding.Cage,
Rack = breeding.Rack,
Rack_Position = breeding.Rack_Position,
Genotype = breeding.genotype,
Gender = form.cleaned_data['Gender'],
Born = form.cleaned_data['Born'],
Weaned = form.cleaned_data['Weaned'],
Backcross = breeding.backcross,
Generation = breeding.generation)
animal.save()
return HttpResponseRedirect( breeding.get_absolute_url() )
else:
form = MultipleBreedingAnimalForm()
return render(request, "animal_multiple_form.html", {"form":form, "breeding":breeding}) | [
"def",
"multiple_breeding_pups",
"(",
"request",
",",
"breeding_id",
")",
":",
"breeding",
"=",
"Breeding",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"breeding_id",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"MultipleBreedingA... | This view is used to enter multiple animals at the same time from a breeding cage.
It will generate a form containing animal information and a number of mice. It is intended to create several identical animals with the same attributes.
This view requres an input of a breeding_id to generate the correct form. | [
"This",
"view",
"is",
"used",
"to",
"enter",
"multiple",
"animals",
"at",
"the",
"same",
"time",
"from",
"a",
"breeding",
"cage",
".",
"It",
"will",
"generate",
"a",
"form",
"containing",
"animal",
"information",
"and",
"a",
"number",
"of",
"mice",
".",
... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L448-L477 |
davebridges/mousedb | mousedb/animal/views.py | date_archive_year | def date_archive_year(request):
"""This view will generate a table of the number of mice born on an annual basis.
This view is associated with the url name archive-home, and returns an dictionary of a date and a animal count."""
oldest_animal = Animal.objects.filter(Born__isnull=False).order_by('Born')[0]
archive_dict = {}
tested_year = oldest_animal.Born.year
while tested_year <= datetime.date.today().year:
archive_dict[tested_year] = Animal.objects.filter(Born__year=tested_year).count()
tested_year = tested_year + 1
return render(request, 'animal_archive.html', {"archive_dict": archive_dict}) | python | def date_archive_year(request):
"""This view will generate a table of the number of mice born on an annual basis.
This view is associated with the url name archive-home, and returns an dictionary of a date and a animal count."""
oldest_animal = Animal.objects.filter(Born__isnull=False).order_by('Born')[0]
archive_dict = {}
tested_year = oldest_animal.Born.year
while tested_year <= datetime.date.today().year:
archive_dict[tested_year] = Animal.objects.filter(Born__year=tested_year).count()
tested_year = tested_year + 1
return render(request, 'animal_archive.html', {"archive_dict": archive_dict}) | [
"def",
"date_archive_year",
"(",
"request",
")",
":",
"oldest_animal",
"=",
"Animal",
".",
"objects",
".",
"filter",
"(",
"Born__isnull",
"=",
"False",
")",
".",
"order_by",
"(",
"'Born'",
")",
"[",
"0",
"]",
"archive_dict",
"=",
"{",
"}",
"tested_year",
... | This view will generate a table of the number of mice born on an annual basis.
This view is associated with the url name archive-home, and returns an dictionary of a date and a animal count. | [
"This",
"view",
"will",
"generate",
"a",
"table",
"of",
"the",
"number",
"of",
"mice",
"born",
"on",
"an",
"annual",
"basis",
".",
"This",
"view",
"is",
"associated",
"with",
"the",
"url",
"name",
"archive",
"-",
"home",
"and",
"returns",
"an",
"dictiona... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L514-L525 |
davebridges/mousedb | mousedb/animal/views.py | todo | def todo(request):
"""This view generates a summary of the todo lists.
The login restricted view passes lists for ear tagging, genotyping and weaning and passes them to the template todo.html."""
eartag_list = Animal.objects.filter(Born__lt=(datetime.date.today() - datetime.timedelta(days=settings.WEAN_AGE))).filter(MouseID__isnull=True, Alive=True)
genotype_list = Animal.objects.filter(Q(Genotype='N.D.')|Q(Genotype__icontains='?')).filter(Alive=True, Born__lt=(datetime.date.today() - datetime.timedelta(days=settings.GENOTYPE_AGE)))
wean = datetime.date.today() - datetime.timedelta(days=settings.WEAN_AGE)
wean_list = Animal.objects.filter(Born__lt=wean).filter(Weaned=None,Alive=True).exclude(Strain=2).order_by('Strain','Background','Rack','Cage')
return render(request, 'todo.html', {'eartag_list':eartag_list, 'wean_list':wean_list, 'genotype_list':genotype_list}) | python | def todo(request):
"""This view generates a summary of the todo lists.
The login restricted view passes lists for ear tagging, genotyping and weaning and passes them to the template todo.html."""
eartag_list = Animal.objects.filter(Born__lt=(datetime.date.today() - datetime.timedelta(days=settings.WEAN_AGE))).filter(MouseID__isnull=True, Alive=True)
genotype_list = Animal.objects.filter(Q(Genotype='N.D.')|Q(Genotype__icontains='?')).filter(Alive=True, Born__lt=(datetime.date.today() - datetime.timedelta(days=settings.GENOTYPE_AGE)))
wean = datetime.date.today() - datetime.timedelta(days=settings.WEAN_AGE)
wean_list = Animal.objects.filter(Born__lt=wean).filter(Weaned=None,Alive=True).exclude(Strain=2).order_by('Strain','Background','Rack','Cage')
return render(request, 'todo.html', {'eartag_list':eartag_list, 'wean_list':wean_list, 'genotype_list':genotype_list}) | [
"def",
"todo",
"(",
"request",
")",
":",
"eartag_list",
"=",
"Animal",
".",
"objects",
".",
"filter",
"(",
"Born__lt",
"=",
"(",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"settings",
".",
"W... | This view generates a summary of the todo lists.
The login restricted view passes lists for ear tagging, genotyping and weaning and passes them to the template todo.html. | [
"This",
"view",
"generates",
"a",
"summary",
"of",
"the",
"todo",
"lists",
".",
"The",
"login",
"restricted",
"view",
"passes",
"lists",
"for",
"ear",
"tagging",
"genotyping",
"and",
"weaning",
"and",
"passes",
"them",
"to",
"the",
"template",
"todo",
".",
... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L528-L537 |
davebridges/mousedb | mousedb/animal/views.py | AnimalList.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalList, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalList, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalList",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L44-L46 |
davebridges/mousedb | mousedb/animal/views.py | AnimalListAlive.get_context_data | def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as Alive."""
context = super(AnimalListAlive, self).get_context_data(**kwargs)
context['list_type'] = 'Alive'
return context | python | def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as Alive."""
context = super(AnimalListAlive, self).get_context_data(**kwargs)
context['list_type'] = 'Alive'
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"AnimalListAlive",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'list_type'",
"]",
"=",
"'Alive'",
"retu... | This add in the context of list_type and returns this as Alive. | [
"This",
"add",
"in",
"the",
"context",
"of",
"list_type",
"and",
"returns",
"this",
"as",
"Alive",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L56-L61 |
davebridges/mousedb | mousedb/animal/views.py | AnimalCreate.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalCreate, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalCreate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalCreate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L86-L88 |
davebridges/mousedb | mousedb/animal/views.py | AnimalUpdate.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalUpdate, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalUpdate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalUpdate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L102-L104 |
davebridges/mousedb | mousedb/animal/views.py | AnimalDelete.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalDelete, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalDelete, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalDelete",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L118-L120 |
davebridges/mousedb | mousedb/animal/views.py | StrainList.get_context_data | def get_context_data(self, **kwargs):
"""This add in the context of strain_list_alive (which filters for all alive animals) and cages which filters for the number of current cages."""
context = super(StrainList, self).get_context_data(**kwargs)
context['strain_list_alive'] = Strain.objects.filter(animal__Alive=True).annotate(alive=Count('animal'))
context['cages'] = Animal.objects.filter(Alive=True).values("Cage")
return context | python | def get_context_data(self, **kwargs):
"""This add in the context of strain_list_alive (which filters for all alive animals) and cages which filters for the number of current cages."""
context = super(StrainList, self).get_context_data(**kwargs)
context['strain_list_alive'] = Strain.objects.filter(animal__Alive=True).annotate(alive=Count('animal'))
context['cages'] = Animal.objects.filter(Alive=True).values("Cage")
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"StrainList",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'strain_list_alive'",
"]",
"=",
"Strain",
"."... | This add in the context of strain_list_alive (which filters for all alive animals) and cages which filters for the number of current cages. | [
"This",
"add",
"in",
"the",
"context",
"of",
"strain_list_alive",
"(",
"which",
"filters",
"for",
"all",
"alive",
"animals",
")",
"and",
"cages",
"which",
"filters",
"for",
"the",
"number",
"of",
"current",
"cages",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L132-L138 |
davebridges/mousedb | mousedb/animal/views.py | StrainDetailAll.get_context_data | def get_context_data(self, **kwargs):
"""This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages."""
strain = super(StrainDetail, self).get_object()
context = super(StrainDetail, self).get_context_data(**kwargs)
context['breeding_cages'] = Breeding.objects.filter(Strain=strain)
context['animal_list'] = Animal.objects.filter(Strain=strain).order_by('Background','Genotype')
context['cages'] = Animal.objects.filter(Strain=strain).values("Cage").distinct()
context['active'] = False
return context | python | def get_context_data(self, **kwargs):
"""This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages."""
strain = super(StrainDetail, self).get_object()
context = super(StrainDetail, self).get_context_data(**kwargs)
context['breeding_cages'] = Breeding.objects.filter(Strain=strain)
context['animal_list'] = Animal.objects.filter(Strain=strain).order_by('Background','Genotype')
context['cages'] = Animal.objects.filter(Strain=strain).values("Cage").distinct()
context['active'] = False
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"strain",
"=",
"super",
"(",
"StrainDetail",
",",
"self",
")",
".",
"get_object",
"(",
")",
"context",
"=",
"super",
"(",
"StrainDetail",
",",
"self",
")",
".",
"get_context_data"... | This adds into the context of strain_list_all (which filters for all alive :class:`~mousedb.animal.models.Animal` objects and active cages) and cages which filters for the number of current cages. | [
"This",
"adds",
"into",
"the",
"context",
"of",
"strain_list_all",
"(",
"which",
"filters",
"for",
"all",
"alive",
":",
"class",
":",
"~mousedb",
".",
"animal",
".",
"models",
".",
"Animal",
"objects",
"and",
"active",
"cages",
")",
"and",
"cages",
"which"... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L173-L182 |
davebridges/mousedb | mousedb/animal/views.py | StrainCreate.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainCreate, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainCreate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"StrainCreate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L195-L197 |
davebridges/mousedb | mousedb/animal/views.py | StrainUpdate.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainUpdate, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainUpdate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"StrainUpdate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L213-L215 |
davebridges/mousedb | mousedb/animal/views.py | StrainDelete.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainDelete, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(StrainDelete, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"StrainDelete",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L231-L233 |
davebridges/mousedb | mousedb/animal/views.py | BreedingList.get_context_data | def get_context_data(self, **kwargs):
"""This adds into the context of breeding_type and sets it to Active."""
context = super(BreedingList, self).get_context_data(**kwargs)
context['breeding_type'] = "Active"
return context | python | def get_context_data(self, **kwargs):
"""This adds into the context of breeding_type and sets it to Active."""
context = super(BreedingList, self).get_context_data(**kwargs)
context['breeding_type'] = "Active"
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"BreedingList",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'breeding_type'",
"]",
"=",
"\"Active\"",
"... | This adds into the context of breeding_type and sets it to Active. | [
"This",
"adds",
"into",
"the",
"context",
"of",
"breeding_type",
"and",
"sets",
"it",
"to",
"Active",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L257-L262 |
davebridges/mousedb | mousedb/animal/views.py | BreedingSearch.get_context_data | def get_context_data(self, **kwargs):
"""This add in the context of breeding_type and sets it to Search it also returns the query and the queryset."""
query = self.request.GET.get('q', '')
context = super(BreedingSearch, self).get_context_data(**kwargs)
context['breeding_type'] = "Search"
context['query'] = query
if query:
context['results'] = Breeding.objects.filter(Cage__icontains=query).distinct()
else:
context['results'] = []
return context | python | def get_context_data(self, **kwargs):
"""This add in the context of breeding_type and sets it to Search it also returns the query and the queryset."""
query = self.request.GET.get('q', '')
context = super(BreedingSearch, self).get_context_data(**kwargs)
context['breeding_type'] = "Search"
context['query'] = query
if query:
context['results'] = Breeding.objects.filter(Cage__icontains=query).distinct()
else:
context['results'] = []
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'q'",
",",
"''",
")",
"context",
"=",
"super",
"(",
"BreedingSearch",
",",
"self",
")",
".",
"get_context_d... | This add in the context of breeding_type and sets it to Search it also returns the query and the queryset. | [
"This",
"add",
"in",
"the",
"context",
"of",
"breeding_type",
"and",
"sets",
"it",
"to",
"Search",
"it",
"also",
"returns",
"the",
"query",
"and",
"the",
"queryset",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L298-L308 |
davebridges/mousedb | mousedb/animal/views.py | BreedingCreate.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(BreedingCreate, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(BreedingCreate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"BreedingCreate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L320-L322 |
davebridges/mousedb | mousedb/animal/views.py | BreedingUpdate.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(BreedingUpdate, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(BreedingUpdate, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"BreedingUpdate",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L335-L337 |
davebridges/mousedb | mousedb/animal/views.py | BreedingDelete.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(BreedingDelete, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(BreedingDelete, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"BreedingDelete",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L350-L352 |
davebridges/mousedb | mousedb/animal/views.py | AnimalYearArchive.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalYearArchive, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalYearArchive, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalYearArchive",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L492-L494 |
davebridges/mousedb | mousedb/animal/views.py | AnimalMonthArchive.dispatch | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalMonthArchive, self).dispatch(*args, **kwargs) | python | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalMonthArchive, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalMonthArchive",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L510-L512 |
davebridges/mousedb | mousedb/animal/views.py | CrossTypeAnimalList.queryset | def queryset(self):
"""This function sets the queryset according to the keyword arguments.
For the crosstype, the input value is the the display value of CROSS_TYPE.
This is done because the spaces in HET vs HET are not recognized.
Therefore the queryset must be matched exactly (ie by case so Intercross not intercross).
The function also filters the strain by the strain_slug keyword argument.
"""
from mousedb.animal.models import CROSS_TYPE
crosstype_reverse = dict((v, k) for k, v in CROSS_TYPE)
try:
crosstype = crosstype_reverse[self.kwargs['breeding_type']]
except KeyError:
raise Http404
strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug'])
if strain:
return Animal.objects.filter(Strain=strain,Breeding__Crosstype=crosstype)
else:
raise Http404 | python | def queryset(self):
"""This function sets the queryset according to the keyword arguments.
For the crosstype, the input value is the the display value of CROSS_TYPE.
This is done because the spaces in HET vs HET are not recognized.
Therefore the queryset must be matched exactly (ie by case so Intercross not intercross).
The function also filters the strain by the strain_slug keyword argument.
"""
from mousedb.animal.models import CROSS_TYPE
crosstype_reverse = dict((v, k) for k, v in CROSS_TYPE)
try:
crosstype = crosstype_reverse[self.kwargs['breeding_type']]
except KeyError:
raise Http404
strain = get_object_or_404(Strain, Strain_slug=self.kwargs['strain_slug'])
if strain:
return Animal.objects.filter(Strain=strain,Breeding__Crosstype=crosstype)
else:
raise Http404 | [
"def",
"queryset",
"(",
"self",
")",
":",
"from",
"mousedb",
".",
"animal",
".",
"models",
"import",
"CROSS_TYPE",
"crosstype_reverse",
"=",
"dict",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"CROSS_TYPE",
")",
"try",
":",
"crosstype",
... | This function sets the queryset according to the keyword arguments.
For the crosstype, the input value is the the display value of CROSS_TYPE.
This is done because the spaces in HET vs HET are not recognized.
Therefore the queryset must be matched exactly (ie by case so Intercross not intercross).
The function also filters the strain by the strain_slug keyword argument. | [
"This",
"function",
"sets",
"the",
"queryset",
"according",
"to",
"the",
"keyword",
"arguments",
".",
"For",
"the",
"crosstype",
"the",
"input",
"value",
"is",
"the",
"the",
"display",
"value",
"of",
"CROSS_TYPE",
".",
"This",
"is",
"done",
"because",
"the",... | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L602-L620 |
davebridges/mousedb | mousedb/animal/views.py | CrossTypeAnimalList.get_context_data | def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as whatever the crosstype was."""
context = super(CrossTypeAnimalList, self).get_context_data(**kwargs)
context['list_type'] = self.kwargs['breeding_type']
return context | python | def get_context_data(self, **kwargs):
"""This add in the context of list_type and returns this as whatever the crosstype was."""
context = super(CrossTypeAnimalList, self).get_context_data(**kwargs)
context['list_type'] = self.kwargs['breeding_type']
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"CrossTypeAnimalList",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'list_type'",
"]",
"=",
"self",
".",... | This add in the context of list_type and returns this as whatever the crosstype was. | [
"This",
"add",
"in",
"the",
"context",
"of",
"list_type",
"and",
"returns",
"this",
"as",
"whatever",
"the",
"crosstype",
"was",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L622-L627 |
davebridges/mousedb | mousedb/veterinary/views.py | VeterinaryHome.get_context_data | def get_context_data(self, **kwargs):
'''Adds to the context all issues, conditions and treatments.'''
context = super(VeterinaryHome, self).get_context_data(**kwargs)
context['medical_issues'] = MedicalIssue.objects.all()
context['medical_conditions'] = MedicalCondition.objects.all()
context['medical_treatments'] = MedicalTreatment.objects.all()
return context | python | def get_context_data(self, **kwargs):
'''Adds to the context all issues, conditions and treatments.'''
context = super(VeterinaryHome, self).get_context_data(**kwargs)
context['medical_issues'] = MedicalIssue.objects.all()
context['medical_conditions'] = MedicalCondition.objects.all()
context['medical_treatments'] = MedicalTreatment.objects.all()
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"VeterinaryHome",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'medical_issues'",
"]",
"=",
"MedicalIssue"... | Adds to the context all issues, conditions and treatments. | [
"Adds",
"to",
"the",
"context",
"all",
"issues",
"conditions",
"and",
"treatments",
"."
] | train | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/veterinary/views.py#L28-L34 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.read_frames | def read_frames(self, n, channels=None):
"""Read ``n`` frames from the track, starting
with the current frame
:param integer n: Number of frames to read
:param integer channels: Number of channels to return (default
is number of channels in track)
:returns: Next ``n`` frames from the track, starting with ``current_frame``
:rtype: numpy array
"""
if channels is None:
channels = self.channels
if channels == 1:
out = np.zeros(n)
elif channels == 2:
out = np.zeros((n, 2))
else:
print "Input needs to be 1 or 2 channels"
return
if n > self.remaining_frames():
print "Trying to retrieve too many frames!"
print "Asked for", n
n = self.remaining_frames()
print "Returning", n
if self.channels == 1 and channels == 1:
out = self.sound.read_frames(n)
elif self.channels == 1 and channels == 2:
frames = self.sound.read_frames(n)
out = np.vstack((frames.copy(), frames.copy())).T
elif self.channels == 2 and channels == 1:
frames = self.sound.read_frames(n)
out = np.mean(frames, axis=1)
elif self.channels == 2 and channels == 2:
out[:n, :] = self.sound.read_frames(n)
self.current_frame += n
return out | python | def read_frames(self, n, channels=None):
"""Read ``n`` frames from the track, starting
with the current frame
:param integer n: Number of frames to read
:param integer channels: Number of channels to return (default
is number of channels in track)
:returns: Next ``n`` frames from the track, starting with ``current_frame``
:rtype: numpy array
"""
if channels is None:
channels = self.channels
if channels == 1:
out = np.zeros(n)
elif channels == 2:
out = np.zeros((n, 2))
else:
print "Input needs to be 1 or 2 channels"
return
if n > self.remaining_frames():
print "Trying to retrieve too many frames!"
print "Asked for", n
n = self.remaining_frames()
print "Returning", n
if self.channels == 1 and channels == 1:
out = self.sound.read_frames(n)
elif self.channels == 1 and channels == 2:
frames = self.sound.read_frames(n)
out = np.vstack((frames.copy(), frames.copy())).T
elif self.channels == 2 and channels == 1:
frames = self.sound.read_frames(n)
out = np.mean(frames, axis=1)
elif self.channels == 2 and channels == 2:
out[:n, :] = self.sound.read_frames(n)
self.current_frame += n
return out | [
"def",
"read_frames",
"(",
"self",
",",
"n",
",",
"channels",
"=",
"None",
")",
":",
"if",
"channels",
"is",
"None",
":",
"channels",
"=",
"self",
".",
"channels",
"if",
"channels",
"==",
"1",
":",
"out",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"... | Read ``n`` frames from the track, starting
with the current frame
:param integer n: Number of frames to read
:param integer channels: Number of channels to return (default
is number of channels in track)
:returns: Next ``n`` frames from the track, starting with ``current_frame``
:rtype: numpy array | [
"Read",
"n",
"frames",
"from",
"the",
"track",
"starting",
"with",
"the",
"current",
"frame"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L57-L96 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.current_frame | def current_frame(self, n):
"""Sets current frame to ``n``
:param integer n: Frame to set to ``current_frame``
"""
self.sound.seek(n)
self._current_frame = n | python | def current_frame(self, n):
"""Sets current frame to ``n``
:param integer n: Frame to set to ``current_frame``
"""
self.sound.seek(n)
self._current_frame = n | [
"def",
"current_frame",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"sound",
".",
"seek",
"(",
"n",
")",
"self",
".",
"_current_frame",
"=",
"n"
] | Sets current frame to ``n``
:param integer n: Frame to set to ``current_frame`` | [
"Sets",
"current",
"frame",
"to",
"n"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L104-L110 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.range_as_mono | def range_as_mono(self, start_sample, end_sample):
"""Get a range of frames as 1 combined channel
:param integer start_sample: First frame in range
:param integer end_sample: Last frame in range (exclusive)
:returns: Track frames in range as 1 combined channel
:rtype: 1d numpy array of length ``end_sample - start_sample``
"""
tmp_current = self.current_frame
self.current_frame = start_sample
tmp_frames = self.read_frames(end_sample - start_sample)
if self.channels == 2:
frames = np.mean(tmp_frames, axis=1)
elif self.channels == 1:
frames = tmp_frames
else:
raise IOError("Input audio must have either 1 or 2 channels")
self.current_frame = tmp_current
return frames | python | def range_as_mono(self, start_sample, end_sample):
"""Get a range of frames as 1 combined channel
:param integer start_sample: First frame in range
:param integer end_sample: Last frame in range (exclusive)
:returns: Track frames in range as 1 combined channel
:rtype: 1d numpy array of length ``end_sample - start_sample``
"""
tmp_current = self.current_frame
self.current_frame = start_sample
tmp_frames = self.read_frames(end_sample - start_sample)
if self.channels == 2:
frames = np.mean(tmp_frames, axis=1)
elif self.channels == 1:
frames = tmp_frames
else:
raise IOError("Input audio must have either 1 or 2 channels")
self.current_frame = tmp_current
return frames | [
"def",
"range_as_mono",
"(",
"self",
",",
"start_sample",
",",
"end_sample",
")",
":",
"tmp_current",
"=",
"self",
".",
"current_frame",
"self",
".",
"current_frame",
"=",
"start_sample",
"tmp_frames",
"=",
"self",
".",
"read_frames",
"(",
"end_sample",
"-",
"... | Get a range of frames as 1 combined channel
:param integer start_sample: First frame in range
:param integer end_sample: Last frame in range (exclusive)
:returns: Track frames in range as 1 combined channel
:rtype: 1d numpy array of length ``end_sample - start_sample`` | [
"Get",
"a",
"range",
"of",
"frames",
"as",
"1",
"combined",
"channel"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L125-L143 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.loudest_time | def loudest_time(self, start=0, duration=0):
"""Find the loudest time in the window given by start and duration
Returns frame number in context of entire track, not just the window.
:param integer start: Start frame
:param integer duration: Number of frames to consider from start
:returns: Frame number of loudest frame
:rtype: integer
"""
if duration == 0:
duration = self.sound.nframes
self.current_frame = start
arr = self.read_frames(duration)
# get the frame of the maximum amplitude
# different names for the same thing...
# max_amp_sample = a.argmax(axis=0)[a.max(axis=0).argmax()]
max_amp_sample = int(np.floor(arr.argmax()/2)) + start
return max_amp_sample | python | def loudest_time(self, start=0, duration=0):
"""Find the loudest time in the window given by start and duration
Returns frame number in context of entire track, not just the window.
:param integer start: Start frame
:param integer duration: Number of frames to consider from start
:returns: Frame number of loudest frame
:rtype: integer
"""
if duration == 0:
duration = self.sound.nframes
self.current_frame = start
arr = self.read_frames(duration)
# get the frame of the maximum amplitude
# different names for the same thing...
# max_amp_sample = a.argmax(axis=0)[a.max(axis=0).argmax()]
max_amp_sample = int(np.floor(arr.argmax()/2)) + start
return max_amp_sample | [
"def",
"loudest_time",
"(",
"self",
",",
"start",
"=",
"0",
",",
"duration",
"=",
"0",
")",
":",
"if",
"duration",
"==",
"0",
":",
"duration",
"=",
"self",
".",
"sound",
".",
"nframes",
"self",
".",
"current_frame",
"=",
"start",
"arr",
"=",
"self",
... | Find the loudest time in the window given by start and duration
Returns frame number in context of entire track, not just the window.
:param integer start: Start frame
:param integer duration: Number of frames to consider from start
:returns: Frame number of loudest frame
:rtype: integer | [
"Find",
"the",
"loudest",
"time",
"in",
"the",
"window",
"given",
"by",
"start",
"and",
"duration",
"Returns",
"frame",
"number",
"in",
"context",
"of",
"entire",
"track",
"not",
"just",
"the",
"window",
"."
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L165-L182 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.zero_crossing_before | def zero_crossing_before(self, n):
"""Find nearest zero crossing in waveform before frame ``n``"""
n_in_samples = int(n * self.samplerate)
search_start = n_in_samples - self.samplerate
if search_start < 0:
search_start = 0
frame = zero_crossing_last(
self.range_as_mono(search_start, n_in_samples)) + search_start
return frame / float(self.samplerate) | python | def zero_crossing_before(self, n):
"""Find nearest zero crossing in waveform before frame ``n``"""
n_in_samples = int(n * self.samplerate)
search_start = n_in_samples - self.samplerate
if search_start < 0:
search_start = 0
frame = zero_crossing_last(
self.range_as_mono(search_start, n_in_samples)) + search_start
return frame / float(self.samplerate) | [
"def",
"zero_crossing_before",
"(",
"self",
",",
"n",
")",
":",
"n_in_samples",
"=",
"int",
"(",
"n",
"*",
"self",
".",
"samplerate",
")",
"search_start",
"=",
"n_in_samples",
"-",
"self",
".",
"samplerate",
"if",
"search_start",
"<",
"0",
":",
"search_sta... | Find nearest zero crossing in waveform before frame ``n`` | [
"Find",
"nearest",
"zero",
"crossing",
"in",
"waveform",
"before",
"frame",
"n"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L187-L198 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.zero_crossing_after | def zero_crossing_after(self, n):
"""Find nearest zero crossing in waveform after frame ``n``"""
n_in_samples = int(n * self.samplerate)
search_end = n_in_samples + self.samplerate
if search_end > self.duration:
search_end = self.duration
frame = zero_crossing_first(
self.range_as_mono(n_in_samples, search_end)) + n_in_samples
return frame / float(self.samplerate) | python | def zero_crossing_after(self, n):
"""Find nearest zero crossing in waveform after frame ``n``"""
n_in_samples = int(n * self.samplerate)
search_end = n_in_samples + self.samplerate
if search_end > self.duration:
search_end = self.duration
frame = zero_crossing_first(
self.range_as_mono(n_in_samples, search_end)) + n_in_samples
return frame / float(self.samplerate) | [
"def",
"zero_crossing_after",
"(",
"self",
",",
"n",
")",
":",
"n_in_samples",
"=",
"int",
"(",
"n",
"*",
"self",
".",
"samplerate",
")",
"search_end",
"=",
"n_in_samples",
"+",
"self",
".",
"samplerate",
"if",
"search_end",
">",
"self",
".",
"duration",
... | Find nearest zero crossing in waveform after frame ``n`` | [
"Find",
"nearest",
"zero",
"crossing",
"in",
"waveform",
"after",
"frame",
"n"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L200-L210 |
ucbvislab/radiotool | radiotool/composer/track.py | Track.label | def label(self, t):
"""Get the label of the song at a given time in seconds
"""
if self.labels is None:
return None
prev_label = None
for l in self.labels:
if l.time > t:
break
prev_label = l
if prev_label is None:
return None
return prev_label.name | python | def label(self, t):
"""Get the label of the song at a given time in seconds
"""
if self.labels is None:
return None
prev_label = None
for l in self.labels:
if l.time > t:
break
prev_label = l
if prev_label is None:
return None
return prev_label.name | [
"def",
"label",
"(",
"self",
",",
"t",
")",
":",
"if",
"self",
".",
"labels",
"is",
"None",
":",
"return",
"None",
"prev_label",
"=",
"None",
"for",
"l",
"in",
"self",
".",
"labels",
":",
"if",
"l",
".",
"time",
">",
"t",
":",
"break",
"prev_labe... | Get the label of the song at a given time in seconds | [
"Get",
"the",
"label",
"of",
"the",
"song",
"at",
"a",
"given",
"time",
"in",
"seconds"
] | train | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/track.py#L223-L235 |
gbiggs/rtctree | rtctree/config_set.py | ConfigurationSet.set_param | def set_param(self, param, value):
'''Set a parameter in this configuration set.'''
self.data[param] = value
self._object.configuration_data = utils.dict_to_nvlist(self.data) | python | def set_param(self, param, value):
'''Set a parameter in this configuration set.'''
self.data[param] = value
self._object.configuration_data = utils.dict_to_nvlist(self.data) | [
"def",
"set_param",
"(",
"self",
",",
"param",
",",
"value",
")",
":",
"self",
".",
"data",
"[",
"param",
"]",
"=",
"value",
"self",
".",
"_object",
".",
"configuration_data",
"=",
"utils",
".",
"dict_to_nvlist",
"(",
"self",
".",
"data",
")"
] | Set a parameter in this configuration set. | [
"Set",
"a",
"parameter",
"in",
"this",
"configuration",
"set",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/config_set.py#L51-L54 |
gbiggs/rtctree | rtctree/config_set.py | ConfigurationSet._reload | def _reload(self, object, description, data):
'''Reload the configuration set data.'''
self._object = object
self._description = description
self._data = data | python | def _reload(self, object, description, data):
'''Reload the configuration set data.'''
self._object = object
self._description = description
self._data = data | [
"def",
"_reload",
"(",
"self",
",",
"object",
",",
"description",
",",
"data",
")",
":",
"self",
".",
"_object",
"=",
"object",
"self",
".",
"_description",
"=",
"description",
"self",
".",
"_data",
"=",
"data"
] | Reload the configuration set data. | [
"Reload",
"the",
"configuration",
"set",
"data",
"."
] | train | https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/config_set.py#L71-L75 |
sacherjj/array_devices | array_devices/array3710.py | ProgramStep.setting | def setting(self):
"""
Load setting (Amps, Watts, or Ohms depending on program mode)
"""
prog_type = self.__program.program_type
return self._setting / self.SETTING_DIVIDES[prog_type] | python | def setting(self):
"""
Load setting (Amps, Watts, or Ohms depending on program mode)
"""
prog_type = self.__program.program_type
return self._setting / self.SETTING_DIVIDES[prog_type] | [
"def",
"setting",
"(",
"self",
")",
":",
"prog_type",
"=",
"self",
".",
"__program",
".",
"program_type",
"return",
"self",
".",
"_setting",
"/",
"self",
".",
"SETTING_DIVIDES",
"[",
"prog_type",
"]"
] | Load setting (Amps, Watts, or Ohms depending on program mode) | [
"Load",
"setting",
"(",
"Amps",
"Watts",
"or",
"Ohms",
"depending",
"on",
"program",
"mode",
")"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L51-L56 |
sacherjj/array_devices | array_devices/array3710.py | Program.partial_steps_data | def partial_steps_data(self, start=0):
"""
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
"""
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
cnt += 1 | python | def partial_steps_data(self, start=0):
"""
Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration)
"""
cnt = 0
if len(self._prog_steps) >= start:
# yields actual steps for encoding
for step in self._prog_steps[start:start+5]:
yield((step.raw_data))
cnt += 1
while cnt < 5:
yield((0, 0))
cnt += 1 | [
"def",
"partial_steps_data",
"(",
"self",
",",
"start",
"=",
"0",
")",
":",
"cnt",
"=",
"0",
"if",
"len",
"(",
"self",
".",
"_prog_steps",
")",
">=",
"start",
":",
"# yields actual steps for encoding",
"for",
"step",
"in",
"self",
".",
"_prog_steps",
"[",
... | Iterates 5 steps from start position and
provides tuple for packing into buffer.
returns (0, 0) if stpe doesn't exist.
:param start: Position to start from (typically 0 or 5)
:yield: (setting, duration) | [
"Iterates",
"5",
"steps",
"from",
"start",
"position",
"and",
"provides",
"tuple",
"for",
"packing",
"into",
"buffer",
"."
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L136-L154 |
sacherjj/array_devices | array_devices/array3710.py | Program.add_step | def add_step(self, setting, duration):
"""
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
"""
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed") | python | def add_step(self, setting, duration):
"""
Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None
"""
if len(self._prog_steps) < 10:
self._prog_steps.append(ProgramStep(self, setting, duration))
else:
raise IndexError("Maximum of 10 steps are allowed") | [
"def",
"add_step",
"(",
"self",
",",
"setting",
",",
"duration",
")",
":",
"if",
"len",
"(",
"self",
".",
"_prog_steps",
")",
"<",
"10",
":",
"self",
".",
"_prog_steps",
".",
"append",
"(",
"ProgramStep",
"(",
"self",
",",
"setting",
",",
"duration",
... | Adds steps to a program.
:param setting: Current, Wattage or Resistance, depending on program mode.
:param duration: Length of step in seconds.
:return: None | [
"Adds",
"steps",
"to",
"a",
"program",
".",
":",
"param",
"setting",
":",
"Current",
"Wattage",
"or",
"Resistance",
"depending",
"on",
"program",
"mode",
".",
":",
"param",
"duration",
":",
"Length",
"of",
"step",
"in",
"seconds",
".",
":",
"return",
":"... | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L156-L166 |
sacherjj/array_devices | array_devices/array3710.py | Program.load_buffer_one_to_five | def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three bytes and checksum
"""
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1]) | python | def load_buffer_one_to_five(self, out_buffer):
"""
Loads first program buffer (0x93) with everything but
first three bytes and checksum
"""
struct.pack_into(b"< 2B", out_buffer, 3, self._program_type, len(self._prog_steps))
offset = 5
for ind, step in enumerate(self.partial_steps_data(0)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1]) | [
"def",
"load_buffer_one_to_five",
"(",
"self",
",",
"out_buffer",
")",
":",
"struct",
".",
"pack_into",
"(",
"b\"< 2B\"",
",",
"out_buffer",
",",
"3",
",",
"self",
".",
"_program_type",
",",
"len",
"(",
"self",
".",
"_prog_steps",
")",
")",
"offset",
"=",
... | Loads first program buffer (0x93) with everything but
first three bytes and checksum | [
"Loads",
"first",
"program",
"buffer",
"(",
"0x93",
")",
"with",
"everything",
"but",
"first",
"three",
"bytes",
"and",
"checksum"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L174-L182 |
sacherjj/array_devices | array_devices/array3710.py | Program.load_buffer_six_to_ten | def load_buffer_six_to_ten(self, out_buffer):
"""
Loads second program buffer (0x94) with everything but
first three bytes and checksum
"""
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode) | python | def load_buffer_six_to_ten(self, out_buffer):
"""
Loads second program buffer (0x94) with everything but
first three bytes and checksum
"""
offset = 3
for ind, step in enumerate(self.partial_steps_data(5)):
struct.pack_into(b"< 2H", out_buffer, offset + ind*4, step[0], step[1])
struct.pack_into(b"< B x", out_buffer, 23, self._program_mode) | [
"def",
"load_buffer_six_to_ten",
"(",
"self",
",",
"out_buffer",
")",
":",
"offset",
"=",
"3",
"for",
"ind",
",",
"step",
"in",
"enumerate",
"(",
"self",
".",
"partial_steps_data",
"(",
"5",
")",
")",
":",
"struct",
".",
"pack_into",
"(",
"b\"< 2H\"",
",... | Loads second program buffer (0x94) with everything but
first three bytes and checksum | [
"Loads",
"second",
"program",
"buffer",
"(",
"0x94",
")",
"with",
"everything",
"but",
"first",
"three",
"bytes",
"and",
"checksum"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L184-L192 |
sacherjj/array_devices | array_devices/array3710.py | Load.set_load_resistance | def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters() | python | def set_load_resistance(self, resistance):
"""
Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None
"""
new_val = int(round(resistance * 100))
if not 0 <= new_val <= 50000:
raise ValueError("Load Resistance should be between 0-500 ohms")
self._load_mode = self.SET_TYPE_RESISTANCE
self._load_value = new_val
self.__set_parameters() | [
"def",
"set_load_resistance",
"(",
"self",
",",
"resistance",
")",
":",
"new_val",
"=",
"int",
"(",
"round",
"(",
"resistance",
"*",
"100",
")",
")",
"if",
"not",
"0",
"<=",
"new_val",
"<=",
"50000",
":",
"raise",
"ValueError",
"(",
"\"Load Resistance shou... | Changes load to resistance mode and sets resistance value.
Rounds to nearest 0.01 Ohms
:param resistance: Load Resistance in Ohms (0-500 ohms)
:return: None | [
"Changes",
"load",
"to",
"resistance",
"mode",
"and",
"sets",
"resistance",
"value",
".",
"Rounds",
"to",
"nearest",
"0",
".",
"01",
"Ohms"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L309-L322 |
sacherjj/array_devices | array_devices/array3710.py | Load.set_load_power | def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters() | python | def set_load_power(self, power_watts):
"""
Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return:
"""
new_val = int(round(power_watts * 10))
if not 0 <= new_val <= 2000:
raise ValueError("Load Power should be between 0-200 W")
self._load_mode = self.SET_TYPE_POWER
self._load_value = new_val
self.__set_parameters() | [
"def",
"set_load_power",
"(",
"self",
",",
"power_watts",
")",
":",
"new_val",
"=",
"int",
"(",
"round",
"(",
"power_watts",
"*",
"10",
")",
")",
"if",
"not",
"0",
"<=",
"new_val",
"<=",
"2000",
":",
"raise",
"ValueError",
"(",
"\"Load Power should be betw... | Changes load to power mode and sets power value.
Rounds to nearest 0.1W.
:param power_watts: Power in Watts (0-200)
:return: | [
"Changes",
"load",
"to",
"power",
"mode",
"and",
"sets",
"power",
"value",
".",
"Rounds",
"to",
"nearest",
"0",
".",
"1W",
"."
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L324-L337 |
sacherjj/array_devices | array_devices/array3710.py | Load.set_load_current | def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters() | python | def set_load_current(self, current_amps):
"""
Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None
"""
new_val = int(round(current_amps * 1000))
if not 0 <= new_val <= 30000:
raise ValueError("Load Current should be between 0-30A")
self._load_mode = self.SET_TYPE_CURRENT
self._load_value = new_val
self.__set_parameters() | [
"def",
"set_load_current",
"(",
"self",
",",
"current_amps",
")",
":",
"new_val",
"=",
"int",
"(",
"round",
"(",
"current_amps",
"*",
"1000",
")",
")",
"if",
"not",
"0",
"<=",
"new_val",
"<=",
"30000",
":",
"raise",
"ValueError",
"(",
"\"Load Current shoul... | Changes load to current mode and sets current value.
Rounds to nearest mA.
:param current_amps: Current in Amps (0-30A)
:return: None | [
"Changes",
"load",
"to",
"current",
"mode",
"and",
"sets",
"current",
"value",
".",
"Rounds",
"to",
"nearest",
"mA",
"."
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L339-L352 |
sacherjj/array_devices | array_devices/array3710.py | Load.__set_buffer_start | def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command) | python | def __set_buffer_start(self, command):
"""
This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None
"""
self.STRUCT_FRONT.pack_into(self.__out_buffer, self.OFFSET_FRONT, 0xAA, self.address, command) | [
"def",
"__set_buffer_start",
"(",
"self",
",",
"command",
")",
":",
"self",
".",
"STRUCT_FRONT",
".",
"pack_into",
"(",
"self",
".",
"__out_buffer",
",",
"self",
".",
"OFFSET_FRONT",
",",
"0xAA",
",",
"self",
".",
"address",
",",
"command",
")"
] | This sets the first three bytes and clears the other 23 bytes.
:param command: Command Code to set
:return: None | [
"This",
"sets",
"the",
"first",
"three",
"bytes",
"and",
"clears",
"the",
"other",
"23",
"bytes",
".",
":",
"param",
"command",
":",
"Command",
"Code",
"to",
"set",
":",
"return",
":",
"None"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L414-L420 |
sacherjj/array_devices | array_devices/array3710.py | Load.__set_checksum | def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum) | python | def __set_checksum(self):
"""
Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None
"""
checksum = self.__get_checksum(self.__out_buffer.raw)
self.STRUCT_CHECKSUM.pack_into(self.__out_buffer, self.OFFSET_CHECKSUM, checksum) | [
"def",
"__set_checksum",
"(",
"self",
")",
":",
"checksum",
"=",
"self",
".",
"__get_checksum",
"(",
"self",
".",
"__out_buffer",
".",
"raw",
")",
"self",
".",
"STRUCT_CHECKSUM",
".",
"pack_into",
"(",
"self",
".",
"__out_buffer",
",",
"self",
".",
"OFFSET... | Sets the checksum on the last byte of buffer,
based on values in the buffer
:return: None | [
"Sets",
"the",
"checksum",
"on",
"the",
"last",
"byte",
"of",
"buffer",
"based",
"on",
"values",
"in",
"the",
"buffer",
":",
"return",
":",
"None"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L434-L441 |
sacherjj/array_devices | array_devices/array3710.py | Load.__clear_in_buffer | def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer)) | python | def __clear_in_buffer(self):
"""
Zeros out the in buffer
:return: None
"""
self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer)) | [
"def",
"__clear_in_buffer",
"(",
"self",
")",
":",
"self",
".",
"__in_buffer",
".",
"value",
"=",
"bytes",
"(",
"b'\\0'",
"*",
"len",
"(",
"self",
".",
"__in_buffer",
")",
")"
] | Zeros out the in buffer
:return: None | [
"Zeros",
"out",
"the",
"in",
"buffer",
":",
"return",
":",
"None"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L451-L456 |
sacherjj/array_devices | array_devices/array3710.py | Load.__send_buffer | def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written | python | def __send_buffer(self):
"""
Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written
"""
bytes_written = self.serial.write(self.__out_buffer.raw)
if self.DEBUG_MODE:
print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffer.raw)))
if bytes_written != len(self.__out_buffer):
raise IOError("{} bytes written for output buffer of size {}".format(bytes_written,
len(self.__out_buffer)))
return bytes_written | [
"def",
"__send_buffer",
"(",
"self",
")",
":",
"bytes_written",
"=",
"self",
".",
"serial",
".",
"write",
"(",
"self",
".",
"__out_buffer",
".",
"raw",
")",
"if",
"self",
".",
"DEBUG_MODE",
":",
"print",
"(",
"\"Wrote: '{}'\"",
".",
"format",
"(",
"binas... | Sends the contents of self.__out_buffer to serial device
:return: Number of bytes written | [
"Sends",
"the",
"contents",
"of",
"self",
".",
"__out_buffer",
"to",
"serial",
"device",
":",
"return",
":",
"Number",
"of",
"bytes",
"written"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L458-L469 |
sacherjj/array_devices | array_devices/array3710.py | Load.__send_receive_buffer | def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string | python | def __send_receive_buffer(self):
"""
Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None
"""
self.__clear_in_buffer()
self.__send_buffer()
read_string = self.serial.read(len(self.__in_buffer))
if self.DEBUG_MODE:
print("Read: '{}'".format(binascii.hexlify(read_string)))
if len(read_string) != len(self.__in_buffer):
raise IOError("{} bytes received for input buffer of size {}".format(len(read_string),
len(self.__in_buffer)))
if not self.__is_valid_checksum(read_string):
raise IOError("Checksum validation failed on received data")
self.__in_buffer.value = read_string | [
"def",
"__send_receive_buffer",
"(",
"self",
")",
":",
"self",
".",
"__clear_in_buffer",
"(",
")",
"self",
".",
"__send_buffer",
"(",
")",
"read_string",
"=",
"self",
".",
"serial",
".",
"read",
"(",
"len",
"(",
"self",
".",
"__in_buffer",
")",
")",
"if"... | Performs a send of self.__out_buffer and then an immediate read into self.__in_buffer
:return: None | [
"Performs",
"a",
"send",
"of",
"self",
".",
"__out_buffer",
"and",
"then",
"an",
"immediate",
"read",
"into",
"self",
".",
"__in_buffer"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L471-L487 |
sacherjj/array_devices | array_devices/array3710.py | Load.__set_parameters | def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status() | python | def __set_parameters(self):
"""
Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None
"""
self.__set_buffer_start(self.CMD_SET_PARAMETERS)
# Can I send 0xFF as address to not change it each time?
# Worry about writing to EEPROM or Flash with each address change.
# Would then implement a separate address only change function.
self.STRUCT_SET_PARAMETERS.pack_into(self.__out_buffer, self.OFFSET_PAYLOAD,
self._max_current, self._max_power, self.address,
self._load_mode, self._load_value)
self.__set_checksum()
self.__send_buffer()
self.update_status() | [
"def",
"__set_parameters",
"(",
"self",
")",
":",
"self",
".",
"__set_buffer_start",
"(",
"self",
".",
"CMD_SET_PARAMETERS",
")",
"# Can I send 0xFF as address to not change it each time?",
"# Worry about writing to EEPROM or Flash with each address change.",
"# Would then implement ... | Sets Load Parameters from class values, including:
Max Current, Max Power, Address, Load Mode, Load Value
:return: None | [
"Sets",
"Load",
"Parameters",
"from",
"class",
"values",
"including",
":",
"Max",
"Current",
"Max",
"Power",
"Address",
"Load",
"Mode",
"Load",
"Value"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L489-L505 |
sacherjj/array_devices | array_devices/array3710.py | Load.update_status | def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.") | python | def update_status(self, retry_count=2):
"""
Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None
"""
# I think retry should be in here.
# Throw exceptions in __update_status and handle here
cur_count = max(retry_count, 0)
while cur_count >= 0:
try:
self.__update_status()
except IOError as err:
if self.print_errors:
print("IOError: {}".format(err))
else:
if not self.__is_valid_checksum(self.__in_buffer.raw):
if self.print_errors:
raise IOError("Checksum validation failed.")
values = self.STRUCT_READ_VALUES_IN.unpack_from(self.__in_buffer, self.OFFSET_FRONT)
(self._current,
self._voltage,
self._power,
self._max_current,
self._max_power,
self._resistance,
output_state) = values[3:-1]
self._remote_control = (output_state & 0b00000001) > 0
self._load_on = (output_state & 0b00000010) > 0
self.wrong_polarity = (output_state & 0b00000100) > 0
self.excessive_temp = (output_state & 0b00001000) > 0
self.excessive_voltage = (output_state & 0b00010000) > 0
self.excessive_power = (output_state & 0b00100000) > 0
return None
cur_count -= 1
raise IOError("Retry count exceeded with serial IO.") | [
"def",
"update_status",
"(",
"self",
",",
"retry_count",
"=",
"2",
")",
":",
"# I think retry should be in here.",
"# Throw exceptions in __update_status and handle here",
"cur_count",
"=",
"max",
"(",
"retry_count",
",",
"0",
")",
"while",
"cur_count",
">=",
"0",
":"... | Updates current values from load.
Must be called to get latest values for the following properties of class:
current
voltage
power
max current
max power
resistance
local_control
load_on
wrong_polarity
excessive_temp
excessive_voltage
excessive_power
:param retry_count: Number of times to ignore IOErrors and retry update
:return: None | [
"Updates",
"current",
"values",
"from",
"load",
".",
"Must",
"be",
"called",
"to",
"get",
"latest",
"values",
"for",
"the",
"following",
"properties",
"of",
"class",
":",
"current",
"voltage",
"power",
"max",
"current",
"max",
"power",
"resistance",
"local_con... | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L507-L557 |
sacherjj/array_devices | array_devices/array3710.py | Load.set_program_sequence | def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer() | python | def set_program_sequence(self, array_program):
"""
Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None
"""
self.__set_buffer_start(self.CMD_DEFINE_PROG_1_5)
array_program.load_buffer_one_to_five(self.__out_buffer)
self.__set_checksum()
self.__send_buffer()
self.__set_buffer_start(self.CMD_DEFINE_PROG_6_10)
array_program.load_buffer_six_to_ten(self.__out_buffer)
self.__set_checksum()
self.__send_buffer() | [
"def",
"set_program_sequence",
"(",
"self",
",",
"array_program",
")",
":",
"self",
".",
"__set_buffer_start",
"(",
"self",
".",
"CMD_DEFINE_PROG_1_5",
")",
"array_program",
".",
"load_buffer_one_to_five",
"(",
"self",
".",
"__out_buffer",
")",
"self",
".",
"__set... | Sets program up in load.
:param array_program: Populated Array3710Program object
:return: None | [
"Sets",
"program",
"up",
"in",
"load",
".",
":",
"param",
"array_program",
":",
"Populated",
"Array3710Program",
"object",
":",
"return",
":",
"None"
] | train | https://github.com/sacherjj/array_devices/blob/ba93a081e555321125ead33cf6fc5197569ef08f/array_devices/array3710.py#L575-L589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.