repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
paulgb/penkit | penkit/turtle.py | turtle_to_texture | def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_generator` for more details
turn_amount (float): amount to turn in degrees
initial_angle (float): initial orientation of the turtle
resolution (int): if provided, interpolation amount for visible lines
Returns:
texture: A texture.
"""
generator = branching_turtle_generator(
turtle_program, turn_amount, initial_angle, resolution)
return texture_from_generator(generator) | python | def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_generator` for more details
turn_amount (float): amount to turn in degrees
initial_angle (float): initial orientation of the turtle
resolution (int): if provided, interpolation amount for visible lines
Returns:
texture: A texture.
"""
generator = branching_turtle_generator(
turtle_program, turn_amount, initial_angle, resolution)
return texture_from_generator(generator) | [
"def",
"turtle_to_texture",
"(",
"turtle_program",
",",
"turn_amount",
"=",
"DEFAULT_TURN",
",",
"initial_angle",
"=",
"DEFAULT_INITIAL_ANGLE",
",",
"resolution",
"=",
"1",
")",
":",
"generator",
"=",
"branching_turtle_generator",
"(",
"turtle_program",
",",
"turn_amo... | Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_generator` for more details
turn_amount (float): amount to turn in degrees
initial_angle (float): initial orientation of the turtle
resolution (int): if provided, interpolation amount for visible lines
Returns:
texture: A texture. | [
"Makes",
"a",
"texture",
"from",
"a",
"turtle",
"program",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/turtle.py#L104-L120 | train |
paulgb/penkit | penkit/fractal/l_systems.py | transform_sequence | def transform_sequence(sequence, transformations):
"""Applies a given set of substitution rules to the given string or generator.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
Yields:
str: the next character in the output sequence.
Examples:
>>> ''.join(transform_sequence('ABC', {}))
'ABC'
>>> ''.join(transform_sequence('ABC', {'A': 'AC', 'C': 'D'}))
'ACBD'
"""
for c in sequence:
for k in transformations.get(c, c):
yield k | python | def transform_sequence(sequence, transformations):
"""Applies a given set of substitution rules to the given string or generator.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
Yields:
str: the next character in the output sequence.
Examples:
>>> ''.join(transform_sequence('ABC', {}))
'ABC'
>>> ''.join(transform_sequence('ABC', {'A': 'AC', 'C': 'D'}))
'ACBD'
"""
for c in sequence:
for k in transformations.get(c, c):
yield k | [
"def",
"transform_sequence",
"(",
"sequence",
",",
"transformations",
")",
":",
"for",
"c",
"in",
"sequence",
":",
"for",
"k",
"in",
"transformations",
".",
"get",
"(",
"c",
",",
"c",
")",
":",
"yield",
"k"
] | Applies a given set of substitution rules to the given string or generator.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
Yields:
str: the next character in the output sequence.
Examples:
>>> ''.join(transform_sequence('ABC', {}))
'ABC'
>>> ''.join(transform_sequence('ABC', {'A': 'AC', 'C': 'D'}))
'ACBD' | [
"Applies",
"a",
"given",
"set",
"of",
"substitution",
"rules",
"to",
"the",
"given",
"string",
"or",
"generator",
".",
"For",
"more",
"background",
"see",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"L",
"-",
"system"... | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/fractal/l_systems.py#L10-L31 | train |
paulgb/penkit | penkit/fractal/l_systems.py | transform_multiple | def transform_multiple(sequence, transformations, iterations):
"""Chains a transformation a given number of times.
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): how many times to repeat the transformation
Yields:
str: the next character in the output sequence.
"""
for _ in range(iterations):
sequence = transform_sequence(sequence, transformations)
return sequence | python | def transform_multiple(sequence, transformations, iterations):
"""Chains a transformation a given number of times.
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): how many times to repeat the transformation
Yields:
str: the next character in the output sequence.
"""
for _ in range(iterations):
sequence = transform_sequence(sequence, transformations)
return sequence | [
"def",
"transform_multiple",
"(",
"sequence",
",",
"transformations",
",",
"iterations",
")",
":",
"for",
"_",
"in",
"range",
"(",
"iterations",
")",
":",
"sequence",
"=",
"transform_sequence",
"(",
"sequence",
",",
"transformations",
")",
"return",
"sequence"
] | Chains a transformation a given number of times.
Args:
sequence (str): a string or generator onto which transformations are applied
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): how many times to repeat the transformation
Yields:
str: the next character in the output sequence. | [
"Chains",
"a",
"transformation",
"a",
"given",
"number",
"of",
"times",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/fractal/l_systems.py#L34-L48 | train |
paulgb/penkit | penkit/fractal/l_systems.py | l_system | def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
"""Generates a texture by running transformations on a turtle program.
First, the given transformations are applied to the axiom. This is
repeated `iterations` times. Then, the output is run as a turtle
program to get a texture, which is returned.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
axiom (str): the axiom of the Lindenmeyer system (a string)
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): the number of times to apply the transformations
angle (float): the angle to use for turns when interpreting the string
as a turtle graphics program
resolution (int): the number of midpoints to create in each turtle step
Returns:
A texture
"""
turtle_program = transform_multiple(axiom, transformations, iterations)
return turtle_to_texture(turtle_program, angle, resolution=resolution) | python | def l_system(axiom, transformations, iterations=1, angle=45, resolution=1):
"""Generates a texture by running transformations on a turtle program.
First, the given transformations are applied to the axiom. This is
repeated `iterations` times. Then, the output is run as a turtle
program to get a texture, which is returned.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
axiom (str): the axiom of the Lindenmeyer system (a string)
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): the number of times to apply the transformations
angle (float): the angle to use for turns when interpreting the string
as a turtle graphics program
resolution (int): the number of midpoints to create in each turtle step
Returns:
A texture
"""
turtle_program = transform_multiple(axiom, transformations, iterations)
return turtle_to_texture(turtle_program, angle, resolution=resolution) | [
"def",
"l_system",
"(",
"axiom",
",",
"transformations",
",",
"iterations",
"=",
"1",
",",
"angle",
"=",
"45",
",",
"resolution",
"=",
"1",
")",
":",
"turtle_program",
"=",
"transform_multiple",
"(",
"axiom",
",",
"transformations",
",",
"iterations",
")",
... | Generates a texture by running transformations on a turtle program.
First, the given transformations are applied to the axiom. This is
repeated `iterations` times. Then, the output is run as a turtle
program to get a texture, which is returned.
For more background see: https://en.wikipedia.org/wiki/L-system
Args:
axiom (str): the axiom of the Lindenmeyer system (a string)
transformations (dict): a dictionary mapping each char to the string that is
substituted for it when the rule is applied
iterations (int): the number of times to apply the transformations
angle (float): the angle to use for turns when interpreting the string
as a turtle graphics program
resolution (int): the number of midpoints to create in each turtle step
Returns:
A texture | [
"Generates",
"a",
"texture",
"by",
"running",
"transformations",
"on",
"a",
"turtle",
"program",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/fractal/l_systems.py#L51-L73 | train |
paulgb/penkit | optimizer/penkit_optimize/path_graph.py | PathGraph.get_path | def get_path(self, i):
"""Returns the path corresponding to the node i."""
index = (i - 1) // 2
reverse = (i - 1) % 2
path = self.paths[index]
if reverse:
return path.reversed()
else:
return path | python | def get_path(self, i):
"""Returns the path corresponding to the node i."""
index = (i - 1) // 2
reverse = (i - 1) % 2
path = self.paths[index]
if reverse:
return path.reversed()
else:
return path | [
"def",
"get_path",
"(",
"self",
",",
"i",
")",
":",
"index",
"=",
"(",
"i",
"-",
"1",
")",
"//",
"2",
"reverse",
"=",
"(",
"i",
"-",
"1",
")",
"%",
"2",
"path",
"=",
"self",
".",
"paths",
"[",
"index",
"]",
"if",
"reverse",
":",
"return",
"... | Returns the path corresponding to the node i. | [
"Returns",
"the",
"path",
"corresponding",
"to",
"the",
"node",
"i",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L22-L30 | train |
paulgb/penkit | optimizer/penkit_optimize/path_graph.py | PathGraph.cost | def cost(self, i, j):
"""Returns the distance between the end of path i
and the start of path j."""
return dist(self.endpoints[i][1], self.endpoints[j][0]) | python | def cost(self, i, j):
"""Returns the distance between the end of path i
and the start of path j."""
return dist(self.endpoints[i][1], self.endpoints[j][0]) | [
"def",
"cost",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"return",
"dist",
"(",
"self",
".",
"endpoints",
"[",
"i",
"]",
"[",
"1",
"]",
",",
"self",
".",
"endpoints",
"[",
"j",
"]",
"[",
"0",
"]",
")"
] | Returns the distance between the end of path i
and the start of path j. | [
"Returns",
"the",
"distance",
"between",
"the",
"end",
"of",
"path",
"i",
"and",
"the",
"start",
"of",
"path",
"j",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L32-L35 | train |
paulgb/penkit | optimizer/penkit_optimize/path_graph.py | PathGraph.get_coordinates | def get_coordinates(self, i, end=False):
"""Returns the starting coordinates of node i as a pair,
or the end coordinates iff end is True."""
if end:
endpoint = self.endpoints[i][1]
else:
endpoint = self.endpoints[i][0]
return (endpoint.real, endpoint.imag) | python | def get_coordinates(self, i, end=False):
"""Returns the starting coordinates of node i as a pair,
or the end coordinates iff end is True."""
if end:
endpoint = self.endpoints[i][1]
else:
endpoint = self.endpoints[i][0]
return (endpoint.real, endpoint.imag) | [
"def",
"get_coordinates",
"(",
"self",
",",
"i",
",",
"end",
"=",
"False",
")",
":",
"if",
"end",
":",
"endpoint",
"=",
"self",
".",
"endpoints",
"[",
"i",
"]",
"[",
"1",
"]",
"else",
":",
"endpoint",
"=",
"self",
".",
"endpoints",
"[",
"i",
"]",... | Returns the starting coordinates of node i as a pair,
or the end coordinates iff end is True. | [
"Returns",
"the",
"starting",
"coordinates",
"of",
"node",
"i",
"as",
"a",
"pair",
"or",
"the",
"end",
"coordinates",
"iff",
"end",
"is",
"True",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L37-L44 | train |
paulgb/penkit | optimizer/penkit_optimize/path_graph.py | PathGraph.iter_starts_with_index | def iter_starts_with_index(self):
"""Returns a generator over (index, start coordinate) pairs,
excluding the origin."""
for i in range(1, len(self.endpoints)):
yield i, self.get_coordinates(i) | python | def iter_starts_with_index(self):
"""Returns a generator over (index, start coordinate) pairs,
excluding the origin."""
for i in range(1, len(self.endpoints)):
yield i, self.get_coordinates(i) | [
"def",
"iter_starts_with_index",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"endpoints",
")",
")",
":",
"yield",
"i",
",",
"self",
".",
"get_coordinates",
"(",
"i",
")"
] | Returns a generator over (index, start coordinate) pairs,
excluding the origin. | [
"Returns",
"a",
"generator",
"over",
"(",
"index",
"start",
"coordinate",
")",
"pairs",
"excluding",
"the",
"origin",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L46-L50 | train |
paulgb/penkit | optimizer/penkit_optimize/path_graph.py | PathGraph.iter_disjunctions | def iter_disjunctions(self):
"""Returns a generator over 2-element lists of indexes which must
be mutually exclusive in a solution (i.e. pairs of nodes which represent
the same path in opposite directions.)"""
for i in range(1, len(self.endpoints), 2):
yield [i, self.get_disjoint(i)] | python | def iter_disjunctions(self):
"""Returns a generator over 2-element lists of indexes which must
be mutually exclusive in a solution (i.e. pairs of nodes which represent
the same path in opposite directions.)"""
for i in range(1, len(self.endpoints), 2):
yield [i, self.get_disjoint(i)] | [
"def",
"iter_disjunctions",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"endpoints",
")",
",",
"2",
")",
":",
"yield",
"[",
"i",
",",
"self",
".",
"get_disjoint",
"(",
"i",
")",
"]"
] | Returns a generator over 2-element lists of indexes which must
be mutually exclusive in a solution (i.e. pairs of nodes which represent
the same path in opposite directions.) | [
"Returns",
"a",
"generator",
"over",
"2",
"-",
"element",
"lists",
"of",
"indexes",
"which",
"must",
"be",
"mutually",
"exclusive",
"in",
"a",
"solution",
"(",
"i",
".",
"e",
".",
"pairs",
"of",
"nodes",
"which",
"represent",
"the",
"same",
"path",
"in",... | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/path_graph.py#L57-L62 | train |
paulgb/penkit | penkit/preview.py | show_plot | def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""Preview a plot in a jupyter notebook.
Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview
Returns:
An object that renders in Jupyter as the provided plot
"""
return SVG(data=plot_to_svg(plot, width, height)) | python | def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):
"""Preview a plot in a jupyter notebook.
Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview
Returns:
An object that renders in Jupyter as the provided plot
"""
return SVG(data=plot_to_svg(plot, width, height)) | [
"def",
"show_plot",
"(",
"plot",
",",
"width",
"=",
"PREVIEW_WIDTH",
",",
"height",
"=",
"PREVIEW_HEIGHT",
")",
":",
"return",
"SVG",
"(",
"data",
"=",
"plot_to_svg",
"(",
"plot",
",",
"width",
",",
"height",
")",
")"
] | Preview a plot in a jupyter notebook.
Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview
Returns:
An object that renders in Jupyter as the provided plot | [
"Preview",
"a",
"plot",
"in",
"a",
"jupyter",
"notebook",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/preview.py#L28-L39 | train |
paulgb/penkit | penkit/write.py | calculate_view_box | def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
"""Calculates the size of the SVG viewBox to use.
Args:
layers (list): the layers in the image
aspect_ratio (float): the height of the output divided by the width
margin (float): minimum amount of buffer to add around the image, relative
to the total dimensions
Returns:
tuple: a 4-tuple of floats representing the viewBox according to SVG
specifications ``(x, y, width, height)``.
"""
min_x = min(np.nanmin(x) for x, y in layers)
max_x = max(np.nanmax(x) for x, y in layers)
min_y = min(np.nanmin(y) for x, y in layers)
max_y = max(np.nanmax(y) for x, y in layers)
height = max_y - min_y
width = max_x - min_x
if height > width * aspect_ratio:
adj_height = height * (1. + margin)
adj_width = adj_height / aspect_ratio
else:
adj_width = width * (1. + margin)
adj_height = adj_width * aspect_ratio
width_buffer = (adj_width - width) / 2.
height_buffer = (adj_height - height) / 2.
return (
min_x - width_buffer,
min_y - height_buffer,
adj_width,
adj_height
) | python | def calculate_view_box(layers, aspect_ratio, margin=DEFAULT_VIEW_BOX_MARGIN):
"""Calculates the size of the SVG viewBox to use.
Args:
layers (list): the layers in the image
aspect_ratio (float): the height of the output divided by the width
margin (float): minimum amount of buffer to add around the image, relative
to the total dimensions
Returns:
tuple: a 4-tuple of floats representing the viewBox according to SVG
specifications ``(x, y, width, height)``.
"""
min_x = min(np.nanmin(x) for x, y in layers)
max_x = max(np.nanmax(x) for x, y in layers)
min_y = min(np.nanmin(y) for x, y in layers)
max_y = max(np.nanmax(y) for x, y in layers)
height = max_y - min_y
width = max_x - min_x
if height > width * aspect_ratio:
adj_height = height * (1. + margin)
adj_width = adj_height / aspect_ratio
else:
adj_width = width * (1. + margin)
adj_height = adj_width * aspect_ratio
width_buffer = (adj_width - width) / 2.
height_buffer = (adj_height - height) / 2.
return (
min_x - width_buffer,
min_y - height_buffer,
adj_width,
adj_height
) | [
"def",
"calculate_view_box",
"(",
"layers",
",",
"aspect_ratio",
",",
"margin",
"=",
"DEFAULT_VIEW_BOX_MARGIN",
")",
":",
"min_x",
"=",
"min",
"(",
"np",
".",
"nanmin",
"(",
"x",
")",
"for",
"x",
",",
"y",
"in",
"layers",
")",
"max_x",
"=",
"max",
"(",... | Calculates the size of the SVG viewBox to use.
Args:
layers (list): the layers in the image
aspect_ratio (float): the height of the output divided by the width
margin (float): minimum amount of buffer to add around the image, relative
to the total dimensions
Returns:
tuple: a 4-tuple of floats representing the viewBox according to SVG
specifications ``(x, y, width, height)``. | [
"Calculates",
"the",
"size",
"of",
"the",
"SVG",
"viewBox",
"to",
"use",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L15-L50 | train |
paulgb/penkit | penkit/write.py | _layer_to_path_gen | def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer.
Args:
layer (layer): the layer to convert
Yields:
str: the next component of the path
"""
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
elif not draw:
yield 'M {} {}'.format(x, y)
draw = True
else:
yield 'L {} {}'.format(x, y) | python | def _layer_to_path_gen(layer):
"""Generates an SVG path from a given layer.
Args:
layer (layer): the layer to convert
Yields:
str: the next component of the path
"""
draw = False
for x, y in zip(*layer):
if np.isnan(x) or np.isnan(y):
draw = False
elif not draw:
yield 'M {} {}'.format(x, y)
draw = True
else:
yield 'L {} {}'.format(x, y) | [
"def",
"_layer_to_path_gen",
"(",
"layer",
")",
":",
"draw",
"=",
"False",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"*",
"layer",
")",
":",
"if",
"np",
".",
"isnan",
"(",
"x",
")",
"or",
"np",
".",
"isnan",
"(",
"y",
")",
":",
"draw",
"=",
"Fa... | Generates an SVG path from a given layer.
Args:
layer (layer): the layer to convert
Yields:
str: the next component of the path | [
"Generates",
"an",
"SVG",
"path",
"from",
"a",
"given",
"layer",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L53-L70 | train |
paulgb/penkit | penkit/write.py | plot_to_svg | def plot_to_svg(plot, width, height, unit=''):
"""Converts a plot (list of layers) into an SVG document.
Args:
plot (list): list of layers that make up the plot
width (float): the width of the resulting image
height (float): the height of the resulting image
unit (str): the units of the resulting image if not pixels
Returns:
str: A stringified XML document representing the image
"""
flipped_plot = [(x, -y) for x, y in plot]
aspect_ratio = height / width
view_box = calculate_view_box(flipped_plot, aspect_ratio=aspect_ratio)
view_box_str = '{} {} {} {}'.format(*view_box)
stroke_thickness = STROKE_THICKNESS * (view_box[2])
svg = ET.Element('svg', attrib={
'xmlns': 'http://www.w3.org/2000/svg',
'xmlns:inkscape': 'http://www.inkscape.org/namespaces/inkscape',
'width': '{}{}'.format(width, unit),
'height': '{}{}'.format(height, unit),
'viewBox': view_box_str})
for i, layer in enumerate(flipped_plot):
group = ET.SubElement(svg, 'g', attrib={
'inkscape:label': '{}-layer'.format(i),
'inkscape:groupmode': 'layer',
})
color = PLOT_COLORS[i % len(PLOT_COLORS)]
ET.SubElement(group, 'path', attrib={
'style': 'stroke-width: {}; stroke: {};'.format(stroke_thickness, color),
'fill': 'none',
'd': layer_to_path(layer)
})
try:
return ET.tostring(svg, encoding='unicode')
except LookupError:
# Python 2.x
return ET.tostring(svg) | python | def plot_to_svg(plot, width, height, unit=''):
"""Converts a plot (list of layers) into an SVG document.
Args:
plot (list): list of layers that make up the plot
width (float): the width of the resulting image
height (float): the height of the resulting image
unit (str): the units of the resulting image if not pixels
Returns:
str: A stringified XML document representing the image
"""
flipped_plot = [(x, -y) for x, y in plot]
aspect_ratio = height / width
view_box = calculate_view_box(flipped_plot, aspect_ratio=aspect_ratio)
view_box_str = '{} {} {} {}'.format(*view_box)
stroke_thickness = STROKE_THICKNESS * (view_box[2])
svg = ET.Element('svg', attrib={
'xmlns': 'http://www.w3.org/2000/svg',
'xmlns:inkscape': 'http://www.inkscape.org/namespaces/inkscape',
'width': '{}{}'.format(width, unit),
'height': '{}{}'.format(height, unit),
'viewBox': view_box_str})
for i, layer in enumerate(flipped_plot):
group = ET.SubElement(svg, 'g', attrib={
'inkscape:label': '{}-layer'.format(i),
'inkscape:groupmode': 'layer',
})
color = PLOT_COLORS[i % len(PLOT_COLORS)]
ET.SubElement(group, 'path', attrib={
'style': 'stroke-width: {}; stroke: {};'.format(stroke_thickness, color),
'fill': 'none',
'd': layer_to_path(layer)
})
try:
return ET.tostring(svg, encoding='unicode')
except LookupError:
# Python 2.x
return ET.tostring(svg) | [
"def",
"plot_to_svg",
"(",
"plot",
",",
"width",
",",
"height",
",",
"unit",
"=",
"''",
")",
":",
"flipped_plot",
"=",
"[",
"(",
"x",
",",
"-",
"y",
")",
"for",
"x",
",",
"y",
"in",
"plot",
"]",
"aspect_ratio",
"=",
"height",
"/",
"width",
"view_... | Converts a plot (list of layers) into an SVG document.
Args:
plot (list): list of layers that make up the plot
width (float): the width of the resulting image
height (float): the height of the resulting image
unit (str): the units of the resulting image if not pixels
Returns:
str: A stringified XML document representing the image | [
"Converts",
"a",
"plot",
"(",
"list",
"of",
"layers",
")",
"into",
"an",
"SVG",
"document",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L85-L127 | train |
paulgb/penkit | penkit/write.py | write_plot | def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
"""Writes a plot SVG to a file.
Args:
plot (list): a list of layers to plot
filename (str): the name of the file to write
width (float): the width of the output SVG
height (float): the height of the output SVG
unit (str): the unit of the height and width
"""
svg = plot_to_svg(plot, width, height, unit)
with open(filename, 'w') as outfile:
outfile.write(svg) | python | def write_plot(plot, filename, width=DEFAULT_PAGE_WIDTH, height=DEFAULT_PAGE_HEIGHT, unit=DEFAULT_PAGE_UNIT):
"""Writes a plot SVG to a file.
Args:
plot (list): a list of layers to plot
filename (str): the name of the file to write
width (float): the width of the output SVG
height (float): the height of the output SVG
unit (str): the unit of the height and width
"""
svg = plot_to_svg(plot, width, height, unit)
with open(filename, 'w') as outfile:
outfile.write(svg) | [
"def",
"write_plot",
"(",
"plot",
",",
"filename",
",",
"width",
"=",
"DEFAULT_PAGE_WIDTH",
",",
"height",
"=",
"DEFAULT_PAGE_HEIGHT",
",",
"unit",
"=",
"DEFAULT_PAGE_UNIT",
")",
":",
"svg",
"=",
"plot_to_svg",
"(",
"plot",
",",
"width",
",",
"height",
",",
... | Writes a plot SVG to a file.
Args:
plot (list): a list of layers to plot
filename (str): the name of the file to write
width (float): the width of the output SVG
height (float): the height of the output SVG
unit (str): the unit of the height and width | [
"Writes",
"a",
"plot",
"SVG",
"to",
"a",
"file",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/write.py#L147-L159 | train |
paulgb/penkit | penkit/mpl_preview.py | draw_layer | def draw_layer(ax, layer):
"""Draws a layer on the given matplotlib axis.
Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot
"""
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') | python | def draw_layer(ax, layer):
"""Draws a layer on the given matplotlib axis.
Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot
"""
ax.set_aspect('equal', 'datalim')
ax.plot(*layer)
ax.axis('off') | [
"def",
"draw_layer",
"(",
"ax",
",",
"layer",
")",
":",
"ax",
".",
"set_aspect",
"(",
"'equal'",
",",
"'datalim'",
")",
"ax",
".",
"plot",
"(",
"*",
"layer",
")",
"ax",
".",
"axis",
"(",
"'off'",
")"
] | Draws a layer on the given matplotlib axis.
Args:
ax (axis): the matplotlib axis to draw on
layer (layer): the layers to plot | [
"Draws",
"a",
"layer",
"on",
"the",
"given",
"matplotlib",
"axis",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/mpl_preview.py#L9-L18 | train |
paulgb/penkit | penkit/projection.py | map_texture_to_surface | def map_texture_to_surface(texture, surface):
"""Returns values on a surface for points on a texture.
Args:
texture (texture): the texture to trace over the surface
surface (surface): the surface to trace along
Returns:
an array of surface heights for each point in the
texture. Line separators (i.e. values that are ``nan`` in
the texture) will be ``nan`` in the output, so the output
will have the same dimensions as the x/y axes in the
input texture.
"""
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)
surface_z = surface[surface_y, surface_x]
return surface_z | python | def map_texture_to_surface(texture, surface):
"""Returns values on a surface for points on a texture.
Args:
texture (texture): the texture to trace over the surface
surface (surface): the surface to trace along
Returns:
an array of surface heights for each point in the
texture. Line separators (i.e. values that are ``nan`` in
the texture) will be ``nan`` in the output, so the output
will have the same dimensions as the x/y axes in the
input texture.
"""
texture_x, texture_y = texture
surface_h, surface_w = surface.shape
surface_x = np.clip(
np.int32(surface_w * texture_x - 1e-9), 0, surface_w - 1)
surface_y = np.clip(
np.int32(surface_h * texture_y - 1e-9), 0, surface_h - 1)
surface_z = surface[surface_y, surface_x]
return surface_z | [
"def",
"map_texture_to_surface",
"(",
"texture",
",",
"surface",
")",
":",
"texture_x",
",",
"texture_y",
"=",
"texture",
"surface_h",
",",
"surface_w",
"=",
"surface",
".",
"shape",
"surface_x",
"=",
"np",
".",
"clip",
"(",
"np",
".",
"int32",
"(",
"surfa... | Returns values on a surface for points on a texture.
Args:
texture (texture): the texture to trace over the surface
surface (surface): the surface to trace along
Returns:
an array of surface heights for each point in the
texture. Line separators (i.e. values that are ``nan`` in
the texture) will be ``nan`` in the output, so the output
will have the same dimensions as the x/y axes in the
input texture. | [
"Returns",
"values",
"on",
"a",
"surface",
"for",
"points",
"on",
"a",
"texture",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L10-L33 | train |
paulgb/penkit | penkit/projection.py | project_texture | def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
"""Creates a texture by adding z-values to an existing texture and projecting.
When working with surfaces there are two ways to accomplish the same thing:
1. project the surface and map a texture to the projected surface
2. map a texture to the surface, and then project the result
The first method, which does not use this function, is preferred because
it is easier to do occlusion removal that way. This function is provided
for cases where you do not wish to generate a surface (and don't care about
occlusion removal.)
Args:
texture_xy (texture): the texture to project
texture_z (np.array): the Z-values to use in the projection
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer.
"""
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_x, surface_y = texture
return (surface_x, -surface_y * y_coef + surface_z * z_coef) | python | def project_texture(texture_xy, texture_z, angle=DEFAULT_ANGLE):
"""Creates a texture by adding z-values to an existing texture and projecting.
When working with surfaces there are two ways to accomplish the same thing:
1. project the surface and map a texture to the projected surface
2. map a texture to the surface, and then project the result
The first method, which does not use this function, is preferred because
it is easier to do occlusion removal that way. This function is provided
for cases where you do not wish to generate a surface (and don't care about
occlusion removal.)
Args:
texture_xy (texture): the texture to project
texture_z (np.array): the Z-values to use in the projection
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer.
"""
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_x, surface_y = texture
return (surface_x, -surface_y * y_coef + surface_z * z_coef) | [
"def",
"project_texture",
"(",
"texture_xy",
",",
"texture_z",
",",
"angle",
"=",
"DEFAULT_ANGLE",
")",
":",
"z_coef",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"angle",
")",
")",
"y_coef",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians... | Creates a texture by adding z-values to an existing texture and projecting.
When working with surfaces there are two ways to accomplish the same thing:
1. project the surface and map a texture to the projected surface
2. map a texture to the surface, and then project the result
The first method, which does not use this function, is preferred because
it is easier to do occlusion removal that way. This function is provided
for cases where you do not wish to generate a surface (and don't care about
occlusion removal.)
Args:
texture_xy (texture): the texture to project
texture_z (np.array): the Z-values to use in the projection
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer. | [
"Creates",
"a",
"texture",
"by",
"adding",
"z",
"-",
"values",
"to",
"an",
"existing",
"texture",
"and",
"projecting",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L36-L60 | train |
paulgb/penkit | penkit/projection.py | project_surface | def project_surface(surface, angle=DEFAULT_ANGLE):
"""Returns the height of the surface when projected at the given angle.
Args:
surface (surface): the surface to project
angle (float): the angle at which to project the surface
Returns:
surface: A projected surface.
"""
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_height, surface_width = surface.shape
slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T
return slope * y_coef + surface * z_coef | python | def project_surface(surface, angle=DEFAULT_ANGLE):
"""Returns the height of the surface when projected at the given angle.
Args:
surface (surface): the surface to project
angle (float): the angle at which to project the surface
Returns:
surface: A projected surface.
"""
z_coef = np.sin(np.radians(angle))
y_coef = np.cos(np.radians(angle))
surface_height, surface_width = surface.shape
slope = np.tile(np.linspace(0., 1., surface_height), [surface_width, 1]).T
return slope * y_coef + surface * z_coef | [
"def",
"project_surface",
"(",
"surface",
",",
"angle",
"=",
"DEFAULT_ANGLE",
")",
":",
"z_coef",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"angle",
")",
")",
"y_coef",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"angle",
")... | Returns the height of the surface when projected at the given angle.
Args:
surface (surface): the surface to project
angle (float): the angle at which to project the surface
Returns:
surface: A projected surface. | [
"Returns",
"the",
"height",
"of",
"the",
"surface",
"when",
"projected",
"at",
"the",
"given",
"angle",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L63-L79 | train |
paulgb/penkit | penkit/projection.py | project_texture_on_surface | def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
"""Maps a texture onto a surface, then projects to 2D and returns a layer.
Args:
texture (texture): the texture to project
surface (surface): the surface to project onto
angle (float): the projection angle in degrees (0 = top-down, 90 = side view)
Returns:
layer: A layer.
"""
projected_surface = project_surface(surface, angle)
texture_x, _ = texture
texture_y = map_texture_to_surface(texture, projected_surface)
return texture_x, texture_y | python | def project_texture_on_surface(texture, surface, angle=DEFAULT_ANGLE):
"""Maps a texture onto a surface, then projects to 2D and returns a layer.
Args:
texture (texture): the texture to project
surface (surface): the surface to project onto
angle (float): the projection angle in degrees (0 = top-down, 90 = side view)
Returns:
layer: A layer.
"""
projected_surface = project_surface(surface, angle)
texture_x, _ = texture
texture_y = map_texture_to_surface(texture, projected_surface)
return texture_x, texture_y | [
"def",
"project_texture_on_surface",
"(",
"texture",
",",
"surface",
",",
"angle",
"=",
"DEFAULT_ANGLE",
")",
":",
"projected_surface",
"=",
"project_surface",
"(",
"surface",
",",
"angle",
")",
"texture_x",
",",
"_",
"=",
"texture",
"texture_y",
"=",
"map_textu... | Maps a texture onto a surface, then projects to 2D and returns a layer.
Args:
texture (texture): the texture to project
surface (surface): the surface to project onto
angle (float): the projection angle in degrees (0 = top-down, 90 = side view)
Returns:
layer: A layer. | [
"Maps",
"a",
"texture",
"onto",
"a",
"surface",
"then",
"projects",
"to",
"2D",
"and",
"returns",
"a",
"layer",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L82-L96 | train |
paulgb/penkit | penkit/projection.py | _remove_hidden_parts | def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface.
"""
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(projected_surface)] = np.nan
return surface | python | def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface.
"""
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(projected_surface)] = np.nan
return surface | [
"def",
"_remove_hidden_parts",
"(",
"projected_surface",
")",
":",
"surface",
"=",
"np",
".",
"copy",
"(",
"projected_surface",
")",
"surface",
"[",
"~",
"_make_occlusion_mask",
"(",
"projected_surface",
")",
"]",
"=",
"np",
".",
"nan",
"return",
"surface"
] | Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface. | [
"Removes",
"parts",
"of",
"a",
"projected",
"surface",
"that",
"are",
"not",
"visible",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L114-L125 | train |
paulgb/penkit | penkit/projection.py | project_and_occlude_texture | def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
"""Projects a texture onto a surface with occluded areas removed.
Args:
texture (texture): the texture to map to the projected surface
surface (surface): the surface to project
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer.
"""
projected_surface = project_surface(surface, angle)
projected_surface = _remove_hidden_parts(projected_surface)
texture_y = map_texture_to_surface(texture, projected_surface)
texture_x, _ = texture
return texture_x, texture_y | python | def project_and_occlude_texture(texture, surface, angle=DEFAULT_ANGLE):
"""Projects a texture onto a surface with occluded areas removed.
Args:
texture (texture): the texture to map to the projected surface
surface (surface): the surface to project
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer.
"""
projected_surface = project_surface(surface, angle)
projected_surface = _remove_hidden_parts(projected_surface)
texture_y = map_texture_to_surface(texture, projected_surface)
texture_x, _ = texture
return texture_x, texture_y | [
"def",
"project_and_occlude_texture",
"(",
"texture",
",",
"surface",
",",
"angle",
"=",
"DEFAULT_ANGLE",
")",
":",
"projected_surface",
"=",
"project_surface",
"(",
"surface",
",",
"angle",
")",
"projected_surface",
"=",
"_remove_hidden_parts",
"(",
"projected_surfac... | Projects a texture onto a surface with occluded areas removed.
Args:
texture (texture): the texture to map to the projected surface
surface (surface): the surface to project
angle (float): the angle to project at, in degrees (0 = overhead, 90 = side view)
Returns:
layer: A layer. | [
"Projects",
"a",
"texture",
"onto",
"a",
"surface",
"with",
"occluded",
"areas",
"removed",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/projection.py#L128-L143 | train |
paulgb/penkit | penkit/textures/__init__.py | make_lines_texture | def make_lines_texture(num_lines=10, resolution=50):
"""Makes a texture consisting of a given number of horizontal lines.
Args:
num_lines (int): the number of lines to draw
resolution (int): the number of midpoints on each line
Returns:
A texture.
"""
x, y = np.meshgrid(
np.hstack([np.linspace(0, 1, resolution), np.nan]),
np.linspace(0, 1, num_lines),
)
y[np.isnan(x)] = np.nan
return x.flatten(), y.flatten() | python | def make_lines_texture(num_lines=10, resolution=50):
"""Makes a texture consisting of a given number of horizontal lines.
Args:
num_lines (int): the number of lines to draw
resolution (int): the number of midpoints on each line
Returns:
A texture.
"""
x, y = np.meshgrid(
np.hstack([np.linspace(0, 1, resolution), np.nan]),
np.linspace(0, 1, num_lines),
)
y[np.isnan(x)] = np.nan
return x.flatten(), y.flatten() | [
"def",
"make_lines_texture",
"(",
"num_lines",
"=",
"10",
",",
"resolution",
"=",
"50",
")",
":",
"x",
",",
"y",
"=",
"np",
".",
"meshgrid",
"(",
"np",
".",
"hstack",
"(",
"[",
"np",
".",
"linspace",
"(",
"0",
",",
"1",
",",
"resolution",
")",
",... | Makes a texture consisting of a given number of horizontal lines.
Args:
num_lines (int): the number of lines to draw
resolution (int): the number of midpoints on each line
Returns:
A texture. | [
"Makes",
"a",
"texture",
"consisting",
"of",
"a",
"given",
"number",
"of",
"horizontal",
"lines",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L9-L25 | train |
paulgb/penkit | penkit/textures/__init__.py | make_grid_texture | def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50):
"""Makes a texture consisting of a grid of vertical and horizontal lines.
Args:
num_h_lines (int): the number of horizontal lines to draw
num_v_lines (int): the number of vertical lines to draw
resolution (int): the number of midpoints to draw on each line
Returns:
A texture.
"""
x_h, y_h = make_lines_texture(num_h_lines, resolution)
y_v, x_v = make_lines_texture(num_v_lines, resolution)
return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v]) | python | def make_grid_texture(num_h_lines=10, num_v_lines=10, resolution=50):
"""Makes a texture consisting of a grid of vertical and horizontal lines.
Args:
num_h_lines (int): the number of horizontal lines to draw
num_v_lines (int): the number of vertical lines to draw
resolution (int): the number of midpoints to draw on each line
Returns:
A texture.
"""
x_h, y_h = make_lines_texture(num_h_lines, resolution)
y_v, x_v = make_lines_texture(num_v_lines, resolution)
return np.concatenate([x_h, x_v]), np.concatenate([y_h, y_v]) | [
"def",
"make_grid_texture",
"(",
"num_h_lines",
"=",
"10",
",",
"num_v_lines",
"=",
"10",
",",
"resolution",
"=",
"50",
")",
":",
"x_h",
",",
"y_h",
"=",
"make_lines_texture",
"(",
"num_h_lines",
",",
"resolution",
")",
"y_v",
",",
"x_v",
"=",
"make_lines_... | Makes a texture consisting of a grid of vertical and horizontal lines.
Args:
num_h_lines (int): the number of horizontal lines to draw
num_v_lines (int): the number of vertical lines to draw
resolution (int): the number of midpoints to draw on each line
Returns:
A texture. | [
"Makes",
"a",
"texture",
"consisting",
"of",
"a",
"grid",
"of",
"vertical",
"and",
"horizontal",
"lines",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L28-L41 | train |
paulgb/penkit | penkit/textures/__init__.py | make_spiral_texture | def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):
"""Makes a texture consisting of a spiral from the origin.
Args:
spirals (float): the number of rotations to make
ccw (bool): make spirals counter-clockwise (default is clockwise)
offset (float): if non-zero, spirals start offset by this amount
resolution (int): number of midpoints along the spiral
Returns:
A texture.
"""
dist = np.sqrt(np.linspace(0., 1., resolution))
if ccw:
direction = 1.
else:
direction = -1.
angle = dist * spirals * np.pi * 2. * direction
spiral_texture = (
(np.cos(angle) * dist / 2.) + 0.5,
(np.sin(angle) * dist / 2.) + 0.5
)
return spiral_texture | python | def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000):
"""Makes a texture consisting of a spiral from the origin.
Args:
spirals (float): the number of rotations to make
ccw (bool): make spirals counter-clockwise (default is clockwise)
offset (float): if non-zero, spirals start offset by this amount
resolution (int): number of midpoints along the spiral
Returns:
A texture.
"""
dist = np.sqrt(np.linspace(0., 1., resolution))
if ccw:
direction = 1.
else:
direction = -1.
angle = dist * spirals * np.pi * 2. * direction
spiral_texture = (
(np.cos(angle) * dist / 2.) + 0.5,
(np.sin(angle) * dist / 2.) + 0.5
)
return spiral_texture | [
"def",
"make_spiral_texture",
"(",
"spirals",
"=",
"6.0",
",",
"ccw",
"=",
"False",
",",
"offset",
"=",
"0.0",
",",
"resolution",
"=",
"1000",
")",
":",
"dist",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"linspace",
"(",
"0.",
",",
"1.",
",",
"resolut... | Makes a texture consisting of a spiral from the origin.
Args:
spirals (float): the number of rotations to make
ccw (bool): make spirals counter-clockwise (default is clockwise)
offset (float): if non-zero, spirals start offset by this amount
resolution (int): number of midpoints along the spiral
Returns:
A texture. | [
"Makes",
"a",
"texture",
"consisting",
"of",
"a",
"spiral",
"from",
"the",
"origin",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L44-L66 | train |
paulgb/penkit | penkit/textures/__init__.py | make_hex_texture | def make_hex_texture(grid_size = 2, resolution=1):
"""Makes a texture consisting on a grid of hexagons.
Args:
grid_size (int): the number of hexagons along each dimension of the grid
resolution (int): the number of midpoints along the line of each hexagon
Returns:
A texture.
"""
grid_x, grid_y = np.meshgrid(
np.arange(grid_size),
np.arange(grid_size)
)
ROOT_3_OVER_2 = np.sqrt(3) / 2
ONE_HALF = 0.5
grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten()
grid_y = grid_y.flatten() * 1.5
grid_points = grid_x.shape[0]
x_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
ROOT_3_OVER_2,
0.,
-ROOT_3_OVER_2,
-ROOT_3_OVER_2,
])
y_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
-ONE_HALF,
-1.,
-ONE_HALF,
ONE_HALF
])
tmx = 4 * resolution
x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1))
y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1))
x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))])
y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))])
return fit_texture((x_t.flatten('F'), y_t.flatten('F'))) | python | def make_hex_texture(grid_size = 2, resolution=1):
"""Makes a texture consisting on a grid of hexagons.
Args:
grid_size (int): the number of hexagons along each dimension of the grid
resolution (int): the number of midpoints along the line of each hexagon
Returns:
A texture.
"""
grid_x, grid_y = np.meshgrid(
np.arange(grid_size),
np.arange(grid_size)
)
ROOT_3_OVER_2 = np.sqrt(3) / 2
ONE_HALF = 0.5
grid_x = (grid_x * np.sqrt(3) + (grid_y % 2) * ROOT_3_OVER_2).flatten()
grid_y = grid_y.flatten() * 1.5
grid_points = grid_x.shape[0]
x_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
ROOT_3_OVER_2,
0.,
-ROOT_3_OVER_2,
-ROOT_3_OVER_2,
])
y_offsets = np.interp(np.arange(4 * resolution),
np.arange(4) * resolution, [
-ONE_HALF,
-1.,
-ONE_HALF,
ONE_HALF
])
tmx = 4 * resolution
x_t = np.tile(grid_x, (tmx, 1)) + x_offsets.reshape((tmx, 1))
y_t = np.tile(grid_y, (tmx, 1)) + y_offsets.reshape((tmx, 1))
x_t = np.vstack([x_t, np.tile(np.nan, (1, grid_x.size))])
y_t = np.vstack([y_t, np.tile(np.nan, (1, grid_y.size))])
return fit_texture((x_t.flatten('F'), y_t.flatten('F'))) | [
"def",
"make_hex_texture",
"(",
"grid_size",
"=",
"2",
",",
"resolution",
"=",
"1",
")",
":",
"grid_x",
",",
"grid_y",
"=",
"np",
".",
"meshgrid",
"(",
"np",
".",
"arange",
"(",
"grid_size",
")",
",",
"np",
".",
"arange",
"(",
"grid_size",
")",
")",
... | Makes a texture consisting on a grid of hexagons.
Args:
grid_size (int): the number of hexagons along each dimension of the grid
resolution (int): the number of midpoints along the line of each hexagon
Returns:
A texture. | [
"Makes",
"a",
"texture",
"consisting",
"on",
"a",
"grid",
"of",
"hexagons",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/textures/__init__.py#L69-L113 | train |
paulgb/penkit | penkit/surfaces.py | make_noise_surface | def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
"""Makes a surface by generating random noise and blurring it.
Args:
dims (pair): the dimensions of the surface to create
blur (float): the amount of Gaussian blur to apply
seed (int): a random seed to use (optional)
Returns:
surface: A surface.
"""
if seed is not None:
np.random.seed(seed)
return gaussian_filter(np.random.normal(size=dims), blur) | python | def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):
"""Makes a surface by generating random noise and blurring it.
Args:
dims (pair): the dimensions of the surface to create
blur (float): the amount of Gaussian blur to apply
seed (int): a random seed to use (optional)
Returns:
surface: A surface.
"""
if seed is not None:
np.random.seed(seed)
return gaussian_filter(np.random.normal(size=dims), blur) | [
"def",
"make_noise_surface",
"(",
"dims",
"=",
"DEFAULT_DIMS",
",",
"blur",
"=",
"10",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"return",
"gaussian_filter",
"(",
"... | Makes a surface by generating random noise and blurring it.
Args:
dims (pair): the dimensions of the surface to create
blur (float): the amount of Gaussian blur to apply
seed (int): a random seed to use (optional)
Returns:
surface: A surface. | [
"Makes",
"a",
"surface",
"by",
"generating",
"random",
"noise",
"and",
"blurring",
"it",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L10-L24 | train |
paulgb/penkit | penkit/surfaces.py | make_gradients | def make_gradients(dims=DEFAULT_DIMS):
"""Makes a pair of gradients to generate textures from numpy primitives.
Args:
dims (pair): the dimensions of the surface to create
Returns:
pair: A pair of surfaces.
"""
return np.meshgrid(
np.linspace(0.0, 1.0, dims[0]),
np.linspace(0.0, 1.0, dims[1])
) | python | def make_gradients(dims=DEFAULT_DIMS):
"""Makes a pair of gradients to generate textures from numpy primitives.
Args:
dims (pair): the dimensions of the surface to create
Returns:
pair: A pair of surfaces.
"""
return np.meshgrid(
np.linspace(0.0, 1.0, dims[0]),
np.linspace(0.0, 1.0, dims[1])
) | [
"def",
"make_gradients",
"(",
"dims",
"=",
"DEFAULT_DIMS",
")",
":",
"return",
"np",
".",
"meshgrid",
"(",
"np",
".",
"linspace",
"(",
"0.0",
",",
"1.0",
",",
"dims",
"[",
"0",
"]",
")",
",",
"np",
".",
"linspace",
"(",
"0.0",
",",
"1.0",
",",
"d... | Makes a pair of gradients to generate textures from numpy primitives.
Args:
dims (pair): the dimensions of the surface to create
Returns:
pair: A pair of surfaces. | [
"Makes",
"a",
"pair",
"of",
"gradients",
"to",
"generate",
"textures",
"from",
"numpy",
"primitives",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L27-L39 | train |
paulgb/penkit | penkit/surfaces.py | make_sine_surface | def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
"""Makes a surface from the 3D sine function.
Args:
dims (pair): the dimensions of the surface to create
offset (float): an offset applied to the function
scale (float): a scale applied to the sine frequency
Returns:
surface: A surface.
"""
gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
return np.sin(np.linalg.norm(gradients, axis=0)) | python | def make_sine_surface(dims=DEFAULT_DIMS, offset=0.5, scale=1.0):
"""Makes a surface from the 3D sine function.
Args:
dims (pair): the dimensions of the surface to create
offset (float): an offset applied to the function
scale (float): a scale applied to the sine frequency
Returns:
surface: A surface.
"""
gradients = (np.array(make_gradients(dims)) - offset) * scale * np.pi
return np.sin(np.linalg.norm(gradients, axis=0)) | [
"def",
"make_sine_surface",
"(",
"dims",
"=",
"DEFAULT_DIMS",
",",
"offset",
"=",
"0.5",
",",
"scale",
"=",
"1.0",
")",
":",
"gradients",
"=",
"(",
"np",
".",
"array",
"(",
"make_gradients",
"(",
"dims",
")",
")",
"-",
"offset",
")",
"*",
"scale",
"*... | Makes a surface from the 3D sine function.
Args:
dims (pair): the dimensions of the surface to create
offset (float): an offset applied to the function
scale (float): a scale applied to the sine frequency
Returns:
surface: A surface. | [
"Makes",
"a",
"surface",
"from",
"the",
"3D",
"sine",
"function",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L42-L54 | train |
paulgb/penkit | penkit/surfaces.py | make_bubble_surface | def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
"""Makes a surface from the product of sine functions on each axis.
Args:
dims (pair): the dimensions of the surface to create
repeat (int): the frequency of the waves is set to ensure this many
repetitions of the function
Returns:
surface: A surface.
"""
gradients = make_gradients(dims)
return (
np.sin((gradients[0] - 0.5) * repeat * np.pi) *
np.sin((gradients[1] - 0.5) * repeat * np.pi)) | python | def make_bubble_surface(dims=DEFAULT_DIMS, repeat=3):
"""Makes a surface from the product of sine functions on each axis.
Args:
dims (pair): the dimensions of the surface to create
repeat (int): the frequency of the waves is set to ensure this many
repetitions of the function
Returns:
surface: A surface.
"""
gradients = make_gradients(dims)
return (
np.sin((gradients[0] - 0.5) * repeat * np.pi) *
np.sin((gradients[1] - 0.5) * repeat * np.pi)) | [
"def",
"make_bubble_surface",
"(",
"dims",
"=",
"DEFAULT_DIMS",
",",
"repeat",
"=",
"3",
")",
":",
"gradients",
"=",
"make_gradients",
"(",
"dims",
")",
"return",
"(",
"np",
".",
"sin",
"(",
"(",
"gradients",
"[",
"0",
"]",
"-",
"0.5",
")",
"*",
"rep... | Makes a surface from the product of sine functions on each axis.
Args:
dims (pair): the dimensions of the surface to create
repeat (int): the frequency of the waves is set to ensure this many
repetitions of the function
Returns:
surface: A surface. | [
"Makes",
"a",
"surface",
"from",
"the",
"product",
"of",
"sine",
"functions",
"on",
"each",
"axis",
"."
] | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/penkit/surfaces.py#L57-L71 | train |
paulgb/penkit | optimizer/penkit_optimize/vrp_solver.py | vrp_solver | def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60):
"""Solve a path using or-tools' Vehicle Routing Problem solver.
Params:
path_graph the PathGraph representing the problem
initial_solution a solution to start with (list of indices, not
including the origin)
runtime_seconds how long to search before returning
Returns: an ordered list of indices in the graph representing a
solution.
"""
# Create the VRP routing model. The 1 means we are only looking
# for a single path.
routing = pywrapcp.RoutingModel(path_graph.num_nodes(),
1, path_graph.ORIGIN)
# For every path node, add a disjunction so that we do not also
# draw its reverse.
for disjunction in path_graph.iter_disjunctions():
routing.AddDisjunction(disjunction)
# Wrap the distance function so that it converts to an integer,
# as or-tools requires. Values are multiplied by COST_MULTIPLIER
# prior to conversion to reduce the loss of precision.
COST_MULTIPLIER = 1e4
def distance(i, j):
return int(path_graph.cost(i, j) * COST_MULTIPLIER)
routing.SetArcCostEvaluatorOfAllVehicles(distance)
start_time = time()
def found_solution():
t = time() - start_time
cost = routing.CostVar().Max() / COST_MULTIPLIER
print('\rBest solution at {} seconds has cost {} '.format(
int(t), cost), end='')
routing.AddAtSolutionCallback(found_solution)
# If we weren't supplied with a solution initially, construct one by taking
# all of the paths in their original direction, in their original order.
if not initial_solution:
initial_solution = [i for i, _ in path_graph.iter_disjunctions()]
# Compute the cost of the initial solution. This is the number we hope to
# improve on.
initial_assignment = routing.ReadAssignmentFromRoutes([initial_solution],
True)
# print('Initial distance:',
# initial_assignment.ObjectiveValue() / COST_MULTIPLIER)
# Set the parameters of the search.
search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
search_parameters.time_limit_ms = runtime_seconds * 1000
search_parameters.local_search_metaheuristic = (
routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
# Run the optimizer and report the final distance.
assignment = routing.SolveFromAssignmentWithParameters(initial_assignment,
search_parameters)
print()
#print('Final distance:', assignment.ObjectiveValue() / COST_MULTIPLIER)
# Iterate over the result to produce a list to return as the solution.
solution = []
index = routing.Start(0)
while not routing.IsEnd(index):
index = assignment.Value(routing.NextVar(index))
node = routing.IndexToNode(index)
if node != 0:
# For compatibility with the greedy solution, exclude the origin.
solution.append(node)
return solution | python | def vrp_solver(path_graph, initial_solution=None, runtime_seconds=60):
"""Solve a path using or-tools' Vehicle Routing Problem solver.
Params:
path_graph the PathGraph representing the problem
initial_solution a solution to start with (list of indices, not
including the origin)
runtime_seconds how long to search before returning
Returns: an ordered list of indices in the graph representing a
solution.
"""
# Create the VRP routing model. The 1 means we are only looking
# for a single path.
routing = pywrapcp.RoutingModel(path_graph.num_nodes(),
1, path_graph.ORIGIN)
# For every path node, add a disjunction so that we do not also
# draw its reverse.
for disjunction in path_graph.iter_disjunctions():
routing.AddDisjunction(disjunction)
# Wrap the distance function so that it converts to an integer,
# as or-tools requires. Values are multiplied by COST_MULTIPLIER
# prior to conversion to reduce the loss of precision.
COST_MULTIPLIER = 1e4
def distance(i, j):
return int(path_graph.cost(i, j) * COST_MULTIPLIER)
routing.SetArcCostEvaluatorOfAllVehicles(distance)
start_time = time()
def found_solution():
t = time() - start_time
cost = routing.CostVar().Max() / COST_MULTIPLIER
print('\rBest solution at {} seconds has cost {} '.format(
int(t), cost), end='')
routing.AddAtSolutionCallback(found_solution)
# If we weren't supplied with a solution initially, construct one by taking
# all of the paths in their original direction, in their original order.
if not initial_solution:
initial_solution = [i for i, _ in path_graph.iter_disjunctions()]
# Compute the cost of the initial solution. This is the number we hope to
# improve on.
initial_assignment = routing.ReadAssignmentFromRoutes([initial_solution],
True)
# print('Initial distance:',
# initial_assignment.ObjectiveValue() / COST_MULTIPLIER)
# Set the parameters of the search.
search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
search_parameters.time_limit_ms = runtime_seconds * 1000
search_parameters.local_search_metaheuristic = (
routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
# Run the optimizer and report the final distance.
assignment = routing.SolveFromAssignmentWithParameters(initial_assignment,
search_parameters)
print()
#print('Final distance:', assignment.ObjectiveValue() / COST_MULTIPLIER)
# Iterate over the result to produce a list to return as the solution.
solution = []
index = routing.Start(0)
while not routing.IsEnd(index):
index = assignment.Value(routing.NextVar(index))
node = routing.IndexToNode(index)
if node != 0:
# For compatibility with the greedy solution, exclude the origin.
solution.append(node)
return solution | [
"def",
"vrp_solver",
"(",
"path_graph",
",",
"initial_solution",
"=",
"None",
",",
"runtime_seconds",
"=",
"60",
")",
":",
"# Create the VRP routing model. The 1 means we are only looking",
"# for a single path.",
"routing",
"=",
"pywrapcp",
".",
"RoutingModel",
"(",
"pat... | Solve a path using or-tools' Vehicle Routing Problem solver.
Params:
path_graph the PathGraph representing the problem
initial_solution a solution to start with (list of indices, not
including the origin)
runtime_seconds how long to search before returning
Returns: an ordered list of indices in the graph representing a
solution. | [
"Solve",
"a",
"path",
"using",
"or",
"-",
"tools",
"Vehicle",
"Routing",
"Problem",
"solver",
".",
"Params",
":",
"path_graph",
"the",
"PathGraph",
"representing",
"the",
"problem",
"initial_solution",
"a",
"solution",
"to",
"start",
"with",
"(",
"list",
"of",... | da451a30f62cfefbab285b9d6979b8dec3ac4957 | https://github.com/paulgb/penkit/blob/da451a30f62cfefbab285b9d6979b8dec3ac4957/optimizer/penkit_optimize/vrp_solver.py#L6-L78 | train |
pavoni/pyvera | pyvera/__init__.py | init_controller | def init_controller(url):
"""Initialize a controller.
Provides a single global controller for applications that can't do this
themselves
"""
# pylint: disable=global-statement
global _VERA_CONTROLLER
created = False
if _VERA_CONTROLLER is None:
_VERA_CONTROLLER = VeraController(url)
created = True
_VERA_CONTROLLER.start()
return [_VERA_CONTROLLER, created] | python | def init_controller(url):
"""Initialize a controller.
Provides a single global controller for applications that can't do this
themselves
"""
# pylint: disable=global-statement
global _VERA_CONTROLLER
created = False
if _VERA_CONTROLLER is None:
_VERA_CONTROLLER = VeraController(url)
created = True
_VERA_CONTROLLER.start()
return [_VERA_CONTROLLER, created] | [
"def",
"init_controller",
"(",
"url",
")",
":",
"# pylint: disable=global-statement",
"global",
"_VERA_CONTROLLER",
"created",
"=",
"False",
"if",
"_VERA_CONTROLLER",
"is",
"None",
":",
"_VERA_CONTROLLER",
"=",
"VeraController",
"(",
"url",
")",
"created",
"=",
"Tru... | Initialize a controller.
Provides a single global controller for applications that can't do this
themselves | [
"Initialize",
"a",
"controller",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L55-L68 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.data_request | def data_request(self, payload, timeout=TIMEOUT):
"""Perform a data_request and return the result."""
request_url = self.base_url + "/data_request"
return requests.get(request_url, timeout=timeout, params=payload) | python | def data_request(self, payload, timeout=TIMEOUT):
"""Perform a data_request and return the result."""
request_url = self.base_url + "/data_request"
return requests.get(request_url, timeout=timeout, params=payload) | [
"def",
"data_request",
"(",
"self",
",",
"payload",
",",
"timeout",
"=",
"TIMEOUT",
")",
":",
"request_url",
"=",
"self",
".",
"base_url",
"+",
"\"/data_request\"",
"return",
"requests",
".",
"get",
"(",
"request_url",
",",
"timeout",
"=",
"timeout",
",",
... | Perform a data_request and return the result. | [
"Perform",
"a",
"data_request",
"and",
"return",
"the",
"result",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L99-L102 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.get_simple_devices_info | def get_simple_devices_info(self):
"""Get basic device info from Vera."""
j = self.data_request({'id': 'sdata'}).json()
self.scenes = []
items = j.get('scenes')
for item in items:
self.scenes.append(VeraScene(item, self))
if j.get('temperature'):
self.temperature_units = j.get('temperature')
self.categories = {}
cats = j.get('categories')
for cat in cats:
self.categories[cat.get('id')] = cat.get('name')
self.device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = self.categories.get(dev.get('category'))
self.device_id_map[dev.get('id')] = dev | python | def get_simple_devices_info(self):
"""Get basic device info from Vera."""
j = self.data_request({'id': 'sdata'}).json()
self.scenes = []
items = j.get('scenes')
for item in items:
self.scenes.append(VeraScene(item, self))
if j.get('temperature'):
self.temperature_units = j.get('temperature')
self.categories = {}
cats = j.get('categories')
for cat in cats:
self.categories[cat.get('id')] = cat.get('name')
self.device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = self.categories.get(dev.get('category'))
self.device_id_map[dev.get('id')] = dev | [
"def",
"get_simple_devices_info",
"(",
"self",
")",
":",
"j",
"=",
"self",
".",
"data_request",
"(",
"{",
"'id'",
":",
"'sdata'",
"}",
")",
".",
"json",
"(",
")",
"self",
".",
"scenes",
"=",
"[",
"]",
"items",
"=",
"j",
".",
"get",
"(",
"'scenes'",... | Get basic device info from Vera. | [
"Get",
"basic",
"device",
"info",
"from",
"Vera",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L104-L128 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.get_device_by_name | def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is the string name of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.name == device_name:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_name))
return found_device | python | def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is the string name of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.name == device_name:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_name))
return found_device | [
"def",
"get_device_by_name",
"(",
"self",
",",
"device_name",
")",
":",
"# Find the device for the vera device name we are interested in",
"found_device",
"=",
"None",
"for",
"device",
"in",
"self",
".",
"get_devices",
"(",
")",
":",
"if",
"device",
".",
"name",
"==... | Search the list of connected devices by name.
device_name param is the string name of the device | [
"Search",
"the",
"list",
"of",
"connected",
"devices",
"by",
"name",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L137-L154 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.get_device_by_id | def get_device_by_id(self, device_id):
"""Search the list of connected devices by ID.
device_id param is the integer ID of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.device_id == device_id:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_id))
return found_device | python | def get_device_by_id(self, device_id):
"""Search the list of connected devices by ID.
device_id param is the integer ID of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
if device.device_id == device_id:
found_device = device
# found the first (and should be only) one so we will finish
break
if found_device is None:
logger.debug('Did not find device with {}'.format(device_id))
return found_device | [
"def",
"get_device_by_id",
"(",
"self",
",",
"device_id",
")",
":",
"# Find the device for the vera device name we are interested in",
"found_device",
"=",
"None",
"for",
"device",
"in",
"self",
".",
"get_devices",
"(",
")",
":",
"if",
"device",
".",
"device_id",
"=... | Search the list of connected devices by ID.
device_id param is the integer ID of the device | [
"Search",
"the",
"list",
"of",
"connected",
"devices",
"by",
"ID",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L156-L173 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.get_devices | def get_devices(self, category_filter=''):
"""Get list of connected devices.
category_filter param is an array of strings
"""
# pylint: disable=too-many-branches
# the Vera rest API is a bit rough so we need to make 2 calls to get
# all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
self.devices = []
items = j.get('devices')
for item in items:
item['deviceInfo'] = self.device_id_map.get(item.get('id'))
if item.get('deviceInfo'):
device_category = item.get('deviceInfo').get('category')
if device_category == CATEGORY_DIMMER:
device = VeraDimmer(item, self)
elif ( device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN):
device = VeraSwitch(item, self)
elif device_category == CATEGORY_THERMOSTAT:
device = VeraThermostat(item, self)
elif device_category == CATEGORY_LOCK:
device = VeraLock(item, self)
elif device_category == CATEGORY_CURTAIN:
device = VeraCurtain(item, self)
elif device_category == CATEGORY_ARMABLE:
device = VeraBinarySensor(item, self)
elif (device_category == CATEGORY_SENSOR or
device_category == CATEGORY_HUMIDITY_SENSOR or
device_category == CATEGORY_TEMPERATURE_SENSOR or
device_category == CATEGORY_LIGHT_SENSOR or
device_category == CATEGORY_POWER_METER or
device_category == CATEGORY_UV_SENSOR):
device = VeraSensor(item, self)
elif (device_category == CATEGORY_SCENE_CONTROLLER or
device_category == CATEGORY_REMOTE):
device = VeraSceneController(item, self)
elif device_category == CATEGORY_GARAGE_DOOR:
device = VeraGarageDoor(item, self)
else:
device = VeraDevice(item, self)
self.devices.append(device)
if (device.is_armable and not (
device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN or
device_category == CATEGORY_CURTAIN or
device_category == CATEGORY_GARAGE_DOOR)):
self.devices.append(VeraArmableDevice(item, self))
else:
self.devices.append(VeraDevice(item, self))
if not category_filter:
return self.devices
devices = []
for device in self.devices:
if (device.category_name is not None and
device.category_name != '' and
device.category_name in category_filter):
devices.append(device)
return devices | python | def get_devices(self, category_filter=''):
"""Get list of connected devices.
category_filter param is an array of strings
"""
# pylint: disable=too-many-branches
# the Vera rest API is a bit rough so we need to make 2 calls to get
# all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
self.devices = []
items = j.get('devices')
for item in items:
item['deviceInfo'] = self.device_id_map.get(item.get('id'))
if item.get('deviceInfo'):
device_category = item.get('deviceInfo').get('category')
if device_category == CATEGORY_DIMMER:
device = VeraDimmer(item, self)
elif ( device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN):
device = VeraSwitch(item, self)
elif device_category == CATEGORY_THERMOSTAT:
device = VeraThermostat(item, self)
elif device_category == CATEGORY_LOCK:
device = VeraLock(item, self)
elif device_category == CATEGORY_CURTAIN:
device = VeraCurtain(item, self)
elif device_category == CATEGORY_ARMABLE:
device = VeraBinarySensor(item, self)
elif (device_category == CATEGORY_SENSOR or
device_category == CATEGORY_HUMIDITY_SENSOR or
device_category == CATEGORY_TEMPERATURE_SENSOR or
device_category == CATEGORY_LIGHT_SENSOR or
device_category == CATEGORY_POWER_METER or
device_category == CATEGORY_UV_SENSOR):
device = VeraSensor(item, self)
elif (device_category == CATEGORY_SCENE_CONTROLLER or
device_category == CATEGORY_REMOTE):
device = VeraSceneController(item, self)
elif device_category == CATEGORY_GARAGE_DOOR:
device = VeraGarageDoor(item, self)
else:
device = VeraDevice(item, self)
self.devices.append(device)
if (device.is_armable and not (
device_category == CATEGORY_SWITCH or
device_category == CATEGORY_VERA_SIREN or
device_category == CATEGORY_CURTAIN or
device_category == CATEGORY_GARAGE_DOOR)):
self.devices.append(VeraArmableDevice(item, self))
else:
self.devices.append(VeraDevice(item, self))
if not category_filter:
return self.devices
devices = []
for device in self.devices:
if (device.category_name is not None and
device.category_name != '' and
device.category_name in category_filter):
devices.append(device)
return devices | [
"def",
"get_devices",
"(",
"self",
",",
"category_filter",
"=",
"''",
")",
":",
"# pylint: disable=too-many-branches",
"# the Vera rest API is a bit rough so we need to make 2 calls to get",
"# all the info e need",
"self",
".",
"get_simple_devices_info",
"(",
")",
"j",
"=",
... | Get list of connected devices.
category_filter param is an array of strings | [
"Get",
"list",
"of",
"connected",
"devices",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L175-L241 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.refresh_data | def refresh_data(self):
"""Refresh data from Vera device."""
j = self.data_request({'id': 'sdata'}).json()
self.temperature_units = j.get('temperature', 'C')
self.model = j.get('model')
self.version = j.get('version')
self.serial_number = j.get('serial_number')
categories = {}
cats = j.get('categories')
for cat in cats:
categories[cat.get('id')] = cat.get('name')
device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = categories.get(dev.get('category'))
device_id_map[dev.get('id')] = dev
return device_id_map | python | def refresh_data(self):
"""Refresh data from Vera device."""
j = self.data_request({'id': 'sdata'}).json()
self.temperature_units = j.get('temperature', 'C')
self.model = j.get('model')
self.version = j.get('version')
self.serial_number = j.get('serial_number')
categories = {}
cats = j.get('categories')
for cat in cats:
categories[cat.get('id')] = cat.get('name')
device_id_map = {}
devs = j.get('devices')
for dev in devs:
dev['categoryName'] = categories.get(dev.get('category'))
device_id_map[dev.get('id')] = dev
return device_id_map | [
"def",
"refresh_data",
"(",
"self",
")",
":",
"j",
"=",
"self",
".",
"data_request",
"(",
"{",
"'id'",
":",
"'sdata'",
"}",
")",
".",
"json",
"(",
")",
"self",
".",
"temperature_units",
"=",
"j",
".",
"get",
"(",
"'temperature'",
",",
"'C'",
")",
"... | Refresh data from Vera device. | [
"Refresh",
"data",
"from",
"Vera",
"device",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L243-L265 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.map_services | def map_services(self):
"""Get full Vera device service info."""
# the Vera rest API is a bit rough so we need to make 2 calls
# to get all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
service_map = {}
items = j.get('devices')
for item in items:
service_map[item.get('id')] = item.get('states')
self.device_services_map = service_map | python | def map_services(self):
"""Get full Vera device service info."""
# the Vera rest API is a bit rough so we need to make 2 calls
# to get all the info e need
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
service_map = {}
items = j.get('devices')
for item in items:
service_map[item.get('id')] = item.get('states')
self.device_services_map = service_map | [
"def",
"map_services",
"(",
"self",
")",
":",
"# the Vera rest API is a bit rough so we need to make 2 calls",
"# to get all the info e need",
"self",
".",
"get_simple_devices_info",
"(",
")",
"j",
"=",
"self",
".",
"data_request",
"(",
"{",
"'id'",
":",
"'status'",
","... | Get full Vera device service info. | [
"Get",
"full",
"Vera",
"device",
"service",
"info",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L267-L282 | train |
pavoni/pyvera | pyvera/__init__.py | VeraController.get_changed_devices | def get_changed_devices(self, timestamp):
"""Get data since last timestamp.
This is done via a blocking call, pass NONE for initial state.
"""
if timestamp is None:
payload = {}
else:
payload = {
'timeout': SUBSCRIPTION_WAIT,
'minimumdelay': SUBSCRIPTION_MIN_WAIT
}
payload.update(timestamp)
# double the timeout here so requests doesn't timeout before vera
payload.update({
'id': 'lu_sdata',
})
logger.debug("get_changed_devices() requesting payload %s", str(payload))
r = self.data_request(payload, TIMEOUT*2)
r.raise_for_status()
# If the Vera disconnects before writing a full response (as lu_sdata
# will do when interrupted by a Luup reload), the requests module will
# happily return 200 with an empty string. So, test for empty response,
# so we don't rely on the JSON parser to throw an exception.
if r.text == "":
raise PyveraError("Empty response from Vera")
# Catch a wide swath of what the JSON parser might throw, within
# reason. Unfortunately, some parsers don't specifically return
# json.decode.JSONDecodeError, but so far most seem to derive what
# they do throw from ValueError, so that's helpful.
try:
result = r.json()
except ValueError as ex:
raise PyveraError("JSON decode error: " + str(ex))
if not ( type(result) is dict
and 'loadtime' in result and 'dataversion' in result ):
raise PyveraError("Unexpected/garbled response from Vera")
# At this point, all good. Update timestamp and return change data.
device_data = result.get('devices')
timestamp = {
'loadtime': result.get('loadtime'),
'dataversion': result.get('dataversion')
}
return [device_data, timestamp] | python | def get_changed_devices(self, timestamp):
"""Get data since last timestamp.
This is done via a blocking call, pass NONE for initial state.
"""
if timestamp is None:
payload = {}
else:
payload = {
'timeout': SUBSCRIPTION_WAIT,
'minimumdelay': SUBSCRIPTION_MIN_WAIT
}
payload.update(timestamp)
# double the timeout here so requests doesn't timeout before vera
payload.update({
'id': 'lu_sdata',
})
logger.debug("get_changed_devices() requesting payload %s", str(payload))
r = self.data_request(payload, TIMEOUT*2)
r.raise_for_status()
# If the Vera disconnects before writing a full response (as lu_sdata
# will do when interrupted by a Luup reload), the requests module will
# happily return 200 with an empty string. So, test for empty response,
# so we don't rely on the JSON parser to throw an exception.
if r.text == "":
raise PyveraError("Empty response from Vera")
# Catch a wide swath of what the JSON parser might throw, within
# reason. Unfortunately, some parsers don't specifically return
# json.decode.JSONDecodeError, but so far most seem to derive what
# they do throw from ValueError, so that's helpful.
try:
result = r.json()
except ValueError as ex:
raise PyveraError("JSON decode error: " + str(ex))
if not ( type(result) is dict
and 'loadtime' in result and 'dataversion' in result ):
raise PyveraError("Unexpected/garbled response from Vera")
# At this point, all good. Update timestamp and return change data.
device_data = result.get('devices')
timestamp = {
'loadtime': result.get('loadtime'),
'dataversion': result.get('dataversion')
}
return [device_data, timestamp] | [
"def",
"get_changed_devices",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"payload",
"=",
"{",
"}",
"else",
":",
"payload",
"=",
"{",
"'timeout'",
":",
"SUBSCRIPTION_WAIT",
",",
"'minimumdelay'",
":",
"SUBSCRIPTION_MIN_WAIT",... | Get data since last timestamp.
This is done via a blocking call, pass NONE for initial state. | [
"Get",
"data",
"since",
"last",
"timestamp",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L284-L332 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.vera_request | def vera_request(self, **kwargs):
"""Perfom a vera_request for this device."""
request_payload = {
'output_format': 'json',
'DeviceNum': self.device_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | python | def vera_request(self, **kwargs):
"""Perfom a vera_request for this device."""
request_payload = {
'output_format': 'json',
'DeviceNum': self.device_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | [
"def",
"vera_request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"request_payload",
"=",
"{",
"'output_format'",
":",
"'json'",
",",
"'DeviceNum'",
":",
"self",
".",
"device_id",
",",
"}",
"request_payload",
".",
"update",
"(",
"kwargs",
")",
"return... | Perfom a vera_request for this device. | [
"Perfom",
"a",
"vera_request",
"for",
"this",
"device",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L445-L453 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.set_service_value | def set_service_value(self, service_id, set_name, parameter_name, value):
"""Set a variable on the vera device.
This will call the Vera api to change device state.
"""
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,
parameter_name: value
}
result = self.vera_request(**payload)
logger.debug("set_service_value: "
"result of vera_request with payload %s: %s",
payload, result.text) | python | def set_service_value(self, service_id, set_name, parameter_name, value):
"""Set a variable on the vera device.
This will call the Vera api to change device state.
"""
payload = {
'id': 'lu_action',
'action': 'Set' + set_name,
'serviceId': service_id,
parameter_name: value
}
result = self.vera_request(**payload)
logger.debug("set_service_value: "
"result of vera_request with payload %s: %s",
payload, result.text) | [
"def",
"set_service_value",
"(",
"self",
",",
"service_id",
",",
"set_name",
",",
"parameter_name",
",",
"value",
")",
":",
"payload",
"=",
"{",
"'id'",
":",
"'lu_action'",
",",
"'action'",
":",
"'Set'",
"+",
"set_name",
",",
"'serviceId'",
":",
"service_id"... | Set a variable on the vera device.
This will call the Vera api to change device state. | [
"Set",
"a",
"variable",
"on",
"the",
"vera",
"device",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L455-L469 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.call_service | def call_service(self, service_id, action):
"""Call a Vera service.
This will call the Vera api to change device state.
"""
result = self.vera_request(id='action', serviceId=service_id,
action=action)
logger.debug("call_service: "
"result of vera_request with id %s: %s", service_id,
result.text)
return result | python | def call_service(self, service_id, action):
"""Call a Vera service.
This will call the Vera api to change device state.
"""
result = self.vera_request(id='action', serviceId=service_id,
action=action)
logger.debug("call_service: "
"result of vera_request with id %s: %s", service_id,
result.text)
return result | [
"def",
"call_service",
"(",
"self",
",",
"service_id",
",",
"action",
")",
":",
"result",
"=",
"self",
".",
"vera_request",
"(",
"id",
"=",
"'action'",
",",
"serviceId",
"=",
"service_id",
",",
"action",
"=",
"action",
")",
"logger",
".",
"debug",
"(",
... | Call a Vera service.
This will call the Vera api to change device state. | [
"Call",
"a",
"Vera",
"service",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L471-L481 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.set_cache_value | def set_cache_value(self, name, value):
"""Set a variable in the local state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated drom
Vera.
"""
dev_info = self.json_state.get('deviceInfo')
if dev_info.get(name.lower()) is None:
logger.error("Could not set %s for %s (key does not exist).",
name, self.name)
logger.error("- dictionary %s", dev_info)
return
dev_info[name.lower()] = str(value) | python | def set_cache_value(self, name, value):
"""Set a variable in the local state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated drom
Vera.
"""
dev_info = self.json_state.get('deviceInfo')
if dev_info.get(name.lower()) is None:
logger.error("Could not set %s for %s (key does not exist).",
name, self.name)
logger.error("- dictionary %s", dev_info)
return
dev_info[name.lower()] = str(value) | [
"def",
"set_cache_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"dev_info",
"=",
"self",
".",
"json_state",
".",
"get",
"(",
"'deviceInfo'",
")",
"if",
"dev_info",
".",
"get",
"(",
"name",
".",
"lower",
"(",
")",
")",
"is",
"None",
":",
... | Set a variable in the local state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated drom
Vera. | [
"Set",
"a",
"variable",
"in",
"the",
"local",
"state",
"dictionary",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L483-L496 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.set_cache_complex_value | def set_cache_complex_value(self, name, value):
"""Set a variable in the local complex state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated from
Vera.
"""
for item in self.json_state.get('states'):
if item.get('variable') == name:
item['value'] = str(value) | python | def set_cache_complex_value(self, name, value):
"""Set a variable in the local complex state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated from
Vera.
"""
for item in self.json_state.get('states'):
if item.get('variable') == name:
item['value'] = str(value) | [
"def",
"set_cache_complex_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"for",
"item",
"in",
"self",
".",
"json_state",
".",
"get",
"(",
"'states'",
")",
":",
"if",
"item",
".",
"get",
"(",
"'variable'",
")",
"==",
"name",
":",
"item",
"[... | Set a variable in the local complex state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated from
Vera. | [
"Set",
"a",
"variable",
"in",
"the",
"local",
"complex",
"state",
"dictionary",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L498-L507 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.get_complex_value | def get_complex_value(self, name):
"""Get a value from the service dictionaries.
It's best to use get_value if it has the data you require since
the vera subscription only updates data in dev_info.
"""
for item in self.json_state.get('states'):
if item.get('variable') == name:
return item.get('value')
return None | python | def get_complex_value(self, name):
"""Get a value from the service dictionaries.
It's best to use get_value if it has the data you require since
the vera subscription only updates data in dev_info.
"""
for item in self.json_state.get('states'):
if item.get('variable') == name:
return item.get('value')
return None | [
"def",
"get_complex_value",
"(",
"self",
",",
"name",
")",
":",
"for",
"item",
"in",
"self",
".",
"json_state",
".",
"get",
"(",
"'states'",
")",
":",
"if",
"item",
".",
"get",
"(",
"'variable'",
")",
"==",
"name",
":",
"return",
"item",
".",
"get",
... | Get a value from the service dictionaries.
It's best to use get_value if it has the data you require since
the vera subscription only updates data in dev_info. | [
"Get",
"a",
"value",
"from",
"the",
"service",
"dictionaries",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L509-L518 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.get_strict_value | def get_strict_value(self, name):
"""Get a case-sensitive keys value from the dev_info area.
"""
dev_info = self.json_state.get('deviceInfo')
return dev_info.get(name, None) | python | def get_strict_value(self, name):
"""Get a case-sensitive keys value from the dev_info area.
"""
dev_info = self.json_state.get('deviceInfo')
return dev_info.get(name, None) | [
"def",
"get_strict_value",
"(",
"self",
",",
"name",
")",
":",
"dev_info",
"=",
"self",
".",
"json_state",
".",
"get",
"(",
"'deviceInfo'",
")",
"return",
"dev_info",
".",
"get",
"(",
"name",
",",
"None",
")"
] | Get a case-sensitive keys value from the dev_info area. | [
"Get",
"a",
"case",
"-",
"sensitive",
"keys",
"value",
"from",
"the",
"dev_info",
"area",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L537-L541 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.refresh_complex_value | def refresh_complex_value(self, name):
"""Refresh a value from the service dictionaries.
It's best to use get_value / refresh if it has the data you need.
"""
for item in self.json_state.get('states'):
if item.get('variable') == name:
service_id = item.get('service')
result = self.vera_request(**{
'id': 'variableget',
'output_format': 'json',
'DeviceNum': self.device_id,
'serviceId': service_id,
'Variable': name
})
item['value'] = result.text
return item.get('value')
return None | python | def refresh_complex_value(self, name):
"""Refresh a value from the service dictionaries.
It's best to use get_value / refresh if it has the data you need.
"""
for item in self.json_state.get('states'):
if item.get('variable') == name:
service_id = item.get('service')
result = self.vera_request(**{
'id': 'variableget',
'output_format': 'json',
'DeviceNum': self.device_id,
'serviceId': service_id,
'Variable': name
})
item['value'] = result.text
return item.get('value')
return None | [
"def",
"refresh_complex_value",
"(",
"self",
",",
"name",
")",
":",
"for",
"item",
"in",
"self",
".",
"json_state",
".",
"get",
"(",
"'states'",
")",
":",
"if",
"item",
".",
"get",
"(",
"'variable'",
")",
"==",
"name",
":",
"service_id",
"=",
"item",
... | Refresh a value from the service dictionaries.
It's best to use get_value / refresh if it has the data you need. | [
"Refresh",
"a",
"value",
"from",
"the",
"service",
"dictionaries",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L543-L560 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.refresh | def refresh(self):
"""Refresh the dev_info data used by get_value.
Only needed if you're not using subscriptions.
"""
j = self.vera_request(id='sdata', output_format='json').json()
devices = j.get('devices')
for device_data in devices:
if device_data.get('id') == self.device_id:
self.update(device_data) | python | def refresh(self):
"""Refresh the dev_info data used by get_value.
Only needed if you're not using subscriptions.
"""
j = self.vera_request(id='sdata', output_format='json').json()
devices = j.get('devices')
for device_data in devices:
if device_data.get('id') == self.device_id:
self.update(device_data) | [
"def",
"refresh",
"(",
"self",
")",
":",
"j",
"=",
"self",
".",
"vera_request",
"(",
"id",
"=",
"'sdata'",
",",
"output_format",
"=",
"'json'",
")",
".",
"json",
"(",
")",
"devices",
"=",
"j",
".",
"get",
"(",
"'devices'",
")",
"for",
"device_data",
... | Refresh the dev_info data used by get_value.
Only needed if you're not using subscriptions. | [
"Refresh",
"the",
"dev_info",
"data",
"used",
"by",
"get_value",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L562-L571 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.update | def update(self, params):
"""Update the dev_info data from a dictionary.
Only updates if it already exists in the device.
"""
dev_info = self.json_state.get('deviceInfo')
dev_info.update({k: params[k] for k in params if dev_info.get(k)}) | python | def update(self, params):
"""Update the dev_info data from a dictionary.
Only updates if it already exists in the device.
"""
dev_info = self.json_state.get('deviceInfo')
dev_info.update({k: params[k] for k in params if dev_info.get(k)}) | [
"def",
"update",
"(",
"self",
",",
"params",
")",
":",
"dev_info",
"=",
"self",
".",
"json_state",
".",
"get",
"(",
"'deviceInfo'",
")",
"dev_info",
".",
"update",
"(",
"{",
"k",
":",
"params",
"[",
"k",
"]",
"for",
"k",
"in",
"params",
"if",
"dev_... | Update the dev_info data from a dictionary.
Only updates if it already exists in the device. | [
"Update",
"the",
"dev_info",
"data",
"from",
"a",
"dictionary",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L573-L579 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDevice.level | def level(self):
"""Get level from vera."""
# Used for dimmers, curtains
# Have seen formats of 10, 0.0 and "0%"!
level = self.get_value('level')
try:
return int(float(level))
except (TypeError, ValueError):
pass
try:
return int(level.strip('%'))
except (TypeError, AttributeError, ValueError):
pass
return 0 | python | def level(self):
"""Get level from vera."""
# Used for dimmers, curtains
# Have seen formats of 10, 0.0 and "0%"!
level = self.get_value('level')
try:
return int(float(level))
except (TypeError, ValueError):
pass
try:
return int(level.strip('%'))
except (TypeError, AttributeError, ValueError):
pass
return 0 | [
"def",
"level",
"(",
"self",
")",
":",
"# Used for dimmers, curtains",
"# Have seen formats of 10, 0.0 and \"0%\"!",
"level",
"=",
"self",
".",
"get_value",
"(",
"'level'",
")",
"try",
":",
"return",
"int",
"(",
"float",
"(",
"level",
")",
")",
"except",
"(",
... | Get level from vera. | [
"Get",
"level",
"from",
"vera",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L628-L641 | train |
pavoni/pyvera | pyvera/__init__.py | VeraSwitch.set_switch_state | def set_switch_state(self, state):
"""Set the switch state, also update local state."""
self.set_service_value(
self.switch_service,
'Target',
'newTargetValue',
state)
self.set_cache_value('Status', state) | python | def set_switch_state(self, state):
"""Set the switch state, also update local state."""
self.set_service_value(
self.switch_service,
'Target',
'newTargetValue',
state)
self.set_cache_value('Status', state) | [
"def",
"set_switch_state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"set_service_value",
"(",
"self",
".",
"switch_service",
",",
"'Target'",
",",
"'newTargetValue'",
",",
"state",
")",
"self",
".",
"set_cache_value",
"(",
"'Status'",
",",
"state",
... | Set the switch state, also update local state. | [
"Set",
"the",
"switch",
"state",
"also",
"update",
"local",
"state",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L690-L697 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDimmer.is_switched_on | def is_switched_on(self, refresh=False):
"""Get dimmer state.
Refresh data from Vera if refresh is True,
otherwise use local cache. Refresh is only needed if you're
not using subscriptions.
"""
if refresh:
self.refresh()
return self.get_brightness(refresh) > 0 | python | def is_switched_on(self, refresh=False):
"""Get dimmer state.
Refresh data from Vera if refresh is True,
otherwise use local cache. Refresh is only needed if you're
not using subscriptions.
"""
if refresh:
self.refresh()
return self.get_brightness(refresh) > 0 | [
"def",
"is_switched_on",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"return",
"self",
".",
"get_brightness",
"(",
"refresh",
")",
">",
"0"
] | Get dimmer state.
Refresh data from Vera if refresh is True,
otherwise use local cache. Refresh is only needed if you're
not using subscriptions. | [
"Get",
"dimmer",
"state",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L730-L739 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDimmer.get_brightness | def get_brightness(self, refresh=False):
"""Get dimmer brightness.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA.
"""
if refresh:
self.refresh()
brightness = 0
percent = self.level
if percent > 0:
brightness = round(percent * 2.55)
return int(brightness) | python | def get_brightness(self, refresh=False):
"""Get dimmer brightness.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA.
"""
if refresh:
self.refresh()
brightness = 0
percent = self.level
if percent > 0:
brightness = round(percent * 2.55)
return int(brightness) | [
"def",
"get_brightness",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"brightness",
"=",
"0",
"percent",
"=",
"self",
".",
"level",
"if",
"percent",
">",
"0",
":",
"brightness",
"=",
"ro... | Get dimmer brightness.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA. | [
"Get",
"dimmer",
"brightness",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L741-L755 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDimmer.set_brightness | def set_brightness(self, brightness):
"""Set dimmer brightness.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA.
"""
percent = 0
if brightness > 0:
percent = round(brightness / 2.55)
self.set_service_value(
self.dimmer_service,
'LoadLevelTarget',
'newLoadlevelTarget',
percent)
self.set_cache_value('level', percent) | python | def set_brightness(self, brightness):
"""Set dimmer brightness.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA.
"""
percent = 0
if brightness > 0:
percent = round(brightness / 2.55)
self.set_service_value(
self.dimmer_service,
'LoadLevelTarget',
'newLoadlevelTarget',
percent)
self.set_cache_value('level', percent) | [
"def",
"set_brightness",
"(",
"self",
",",
"brightness",
")",
":",
"percent",
"=",
"0",
"if",
"brightness",
">",
"0",
":",
"percent",
"=",
"round",
"(",
"brightness",
"/",
"2.55",
")",
"self",
".",
"set_service_value",
"(",
"self",
".",
"dimmer_service",
... | Set dimmer brightness.
Converts the Vera level property for dimmable lights from a percentage
to the 0 - 255 scale used by HA. | [
"Set",
"dimmer",
"brightness",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L757-L772 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDimmer.get_color_index | def get_color_index(self, colors, refresh=False):
"""Get color index.
Refresh data from Vera if refresh is True, otherwise use local cache.
"""
if refresh:
self.refresh_complex_value('SupportedColors')
sup = self.get_complex_value('SupportedColors')
if sup is None:
return None
sup = sup.split(',')
if not set(colors).issubset(sup):
return None
return [sup.index(c) for c in colors] | python | def get_color_index(self, colors, refresh=False):
"""Get color index.
Refresh data from Vera if refresh is True, otherwise use local cache.
"""
if refresh:
self.refresh_complex_value('SupportedColors')
sup = self.get_complex_value('SupportedColors')
if sup is None:
return None
sup = sup.split(',')
if not set(colors).issubset(sup):
return None
return [sup.index(c) for c in colors] | [
"def",
"get_color_index",
"(",
"self",
",",
"colors",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh_complex_value",
"(",
"'SupportedColors'",
")",
"sup",
"=",
"self",
".",
"get_complex_value",
"(",
"'SupportedColors'",
")"... | Get color index.
Refresh data from Vera if refresh is True, otherwise use local cache. | [
"Get",
"color",
"index",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L774-L790 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDimmer.get_color | def get_color(self, refresh=False):
"""Get color.
Refresh data from Vera if refresh is True, otherwise use local cache.
"""
if refresh:
self.refresh_complex_value('CurrentColor')
ci = self.get_color_index(['R', 'G', 'B'], refresh)
cur = self.get_complex_value('CurrentColor')
if ci is None or cur is None:
return None
try:
val = [cur.split(',')[c] for c in ci]
return [int(v.split('=')[1]) for v in val]
except IndexError:
return None | python | def get_color(self, refresh=False):
"""Get color.
Refresh data from Vera if refresh is True, otherwise use local cache.
"""
if refresh:
self.refresh_complex_value('CurrentColor')
ci = self.get_color_index(['R', 'G', 'B'], refresh)
cur = self.get_complex_value('CurrentColor')
if ci is None or cur is None:
return None
try:
val = [cur.split(',')[c] for c in ci]
return [int(v.split('=')[1]) for v in val]
except IndexError:
return None | [
"def",
"get_color",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh_complex_value",
"(",
"'CurrentColor'",
")",
"ci",
"=",
"self",
".",
"get_color_index",
"(",
"[",
"'R'",
",",
"'G'",
",",
"'B'",
"]",
",... | Get color.
Refresh data from Vera if refresh is True, otherwise use local cache. | [
"Get",
"color",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L792-L809 | train |
pavoni/pyvera | pyvera/__init__.py | VeraDimmer.set_color | def set_color(self, rgb):
"""Set dimmer color.
"""
target = ','.join([str(c) for c in rgb])
self.set_service_value(
self.color_service,
'ColorRGB',
'newColorRGBTarget',
target)
rgbi = self.get_color_index(['R', 'G', 'B'])
if rgbi is None:
return
target = ('0=0,1=0,' +
str(rgbi[0]) + '=' + str(rgb[0]) + ',' +
str(rgbi[1]) + '=' + str(rgb[1]) + ',' +
str(rgbi[2]) + '=' + str(rgb[2]))
self.set_cache_complex_value("CurrentColor", target) | python | def set_color(self, rgb):
"""Set dimmer color.
"""
target = ','.join([str(c) for c in rgb])
self.set_service_value(
self.color_service,
'ColorRGB',
'newColorRGBTarget',
target)
rgbi = self.get_color_index(['R', 'G', 'B'])
if rgbi is None:
return
target = ('0=0,1=0,' +
str(rgbi[0]) + '=' + str(rgb[0]) + ',' +
str(rgbi[1]) + '=' + str(rgb[1]) + ',' +
str(rgbi[2]) + '=' + str(rgb[2]))
self.set_cache_complex_value("CurrentColor", target) | [
"def",
"set_color",
"(",
"self",
",",
"rgb",
")",
":",
"target",
"=",
"','",
".",
"join",
"(",
"[",
"str",
"(",
"c",
")",
"for",
"c",
"in",
"rgb",
"]",
")",
"self",
".",
"set_service_value",
"(",
"self",
".",
"color_service",
",",
"'ColorRGB'",
","... | Set dimmer color. | [
"Set",
"dimmer",
"color",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L811-L830 | train |
pavoni/pyvera | pyvera/__init__.py | VeraArmableDevice.set_armed_state | def set_armed_state(self, state):
"""Set the armed state, also update local state."""
self.set_service_value(
self.security_sensor_service,
'Armed',
'newArmedValue',
state)
self.set_cache_value('Armed', state) | python | def set_armed_state(self, state):
"""Set the armed state, also update local state."""
self.set_service_value(
self.security_sensor_service,
'Armed',
'newArmedValue',
state)
self.set_cache_value('Armed', state) | [
"def",
"set_armed_state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"set_service_value",
"(",
"self",
".",
"security_sensor_service",
",",
"'Armed'",
",",
"'newArmedValue'",
",",
"state",
")",
"self",
".",
"set_cache_value",
"(",
"'Armed'",
",",
"state... | Set the armed state, also update local state. | [
"Set",
"the",
"armed",
"state",
"also",
"update",
"local",
"state",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L836-L843 | train |
pavoni/pyvera | pyvera/__init__.py | VeraArmableDevice.is_switched_on | def is_switched_on(self, refresh=False):
"""Get armed state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh()
val = self.get_value('Armed')
return val == '1' | python | def is_switched_on(self, refresh=False):
"""Get armed state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh()
val = self.get_value('Armed')
return val == '1' | [
"def",
"is_switched_on",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"val",
"=",
"self",
".",
"get_value",
"(",
"'Armed'",
")",
"return",
"val",
"==",
"'1'"
] | Get armed state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions. | [
"Get",
"armed",
"state",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L853-L862 | train |
pavoni/pyvera | pyvera/__init__.py | VeraCurtain.is_open | def is_open(self, refresh=False):
"""Get curtains state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh()
return self.get_level(refresh) > 0 | python | def is_open(self, refresh=False):
"""Get curtains state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh()
return self.get_level(refresh) > 0 | [
"def",
"is_open",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"return",
"self",
".",
"get_level",
"(",
"refresh",
")",
">",
"0"
] | Get curtains state.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions. | [
"Get",
"curtains",
"state",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L902-L910 | train |
pavoni/pyvera | pyvera/__init__.py | VeraCurtain.set_level | def set_level(self, level):
"""Set open level of the curtains.
Scale is 0-100
"""
self.set_service_value(
self.dimmer_service,
'LoadLevelTarget',
'newLoadlevelTarget',
level)
self.set_cache_value('level', level) | python | def set_level(self, level):
"""Set open level of the curtains.
Scale is 0-100
"""
self.set_service_value(
self.dimmer_service,
'LoadLevelTarget',
'newLoadlevelTarget',
level)
self.set_cache_value('level', level) | [
"def",
"set_level",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"set_service_value",
"(",
"self",
".",
"dimmer_service",
",",
"'LoadLevelTarget'",
",",
"'newLoadlevelTarget'",
",",
"level",
")",
"self",
".",
"set_cache_value",
"(",
"'level'",
",",
"level... | Set open level of the curtains.
Scale is 0-100 | [
"Set",
"open",
"level",
"of",
"the",
"curtains",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L923-L934 | train |
pavoni/pyvera | pyvera/__init__.py | VeraLock.get_last_user | def get_last_user(self, refresh=False):
"""Get the last used PIN user id"""
if refresh:
self.refresh_complex_value('sl_UserCode')
val = self.get_complex_value("sl_UserCode")
# Syntax string: UserID="<pin_slot>" UserName="<pin_code_name>"
# See http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1
try:
# Get the UserID="" and UserName="" fields separately
raw_userid, raw_username = val.split(' ')
# Get the right hand value without quotes of UserID="<here>"
userid = raw_userid.split('=')[1].split('"')[1]
# Get the right hand value without quotes of UserName="<here>"
username = raw_username.split('=')[1].split('"')[1]
except Exception as ex:
logger.error('Got unsupported user string {}: {}'.format(val, ex))
return None
return ( userid, username ) | python | def get_last_user(self, refresh=False):
"""Get the last used PIN user id"""
if refresh:
self.refresh_complex_value('sl_UserCode')
val = self.get_complex_value("sl_UserCode")
# Syntax string: UserID="<pin_slot>" UserName="<pin_code_name>"
# See http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1
try:
# Get the UserID="" and UserName="" fields separately
raw_userid, raw_username = val.split(' ')
# Get the right hand value without quotes of UserID="<here>"
userid = raw_userid.split('=')[1].split('"')[1]
# Get the right hand value without quotes of UserName="<here>"
username = raw_username.split('=')[1].split('"')[1]
except Exception as ex:
logger.error('Got unsupported user string {}: {}'.format(val, ex))
return None
return ( userid, username ) | [
"def",
"get_last_user",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh_complex_value",
"(",
"'sl_UserCode'",
")",
"val",
"=",
"self",
".",
"get_complex_value",
"(",
"\"sl_UserCode\"",
")",
"# Syntax string: UserI... | Get the last used PIN user id | [
"Get",
"the",
"last",
"used",
"PIN",
"user",
"id"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L967-L986 | train |
pavoni/pyvera | pyvera/__init__.py | VeraLock.get_pin_codes | def get_pin_codes(self, refresh=False):
"""Get the list of PIN codes
Codes can also be found with self.get_complex_value('PinCodes')
"""
if refresh:
self.refresh()
val = self.get_value("pincodes")
# val syntax string: <VERSION=3>next_available_user_code_id\tuser_code_id,active,date_added,date_used,PIN_code,name;\t...
# See (outdated) http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1
# Remove the trailing tab
# ignore the version and next available at the start
# and split out each set of code attributes
raw_code_list = []
try:
raw_code_list = val.rstrip().split('\t')[1:]
except Exception as ex:
logger.error('Got unsupported string {}: {}'.format(val, ex))
# Loop to create a list of codes
codes = []
for code in raw_code_list:
try:
# Strip off trailing semicolon
# Create a list from csv
code_addrs = code.split(';')[0].split(',')
# Get the code ID (slot) and see if it should have values
slot, active = code_addrs[:2]
if active != '0':
# Since it has additional attributes, get the remaining ones
_, _, pin, name = code_addrs[2:]
# And add them as a tuple to the list
codes.append((slot, name, pin))
except Exception as ex:
logger.error('Problem parsing pin code string {}: {}'.format(code, ex))
return codes | python | def get_pin_codes(self, refresh=False):
"""Get the list of PIN codes
Codes can also be found with self.get_complex_value('PinCodes')
"""
if refresh:
self.refresh()
val = self.get_value("pincodes")
# val syntax string: <VERSION=3>next_available_user_code_id\tuser_code_id,active,date_added,date_used,PIN_code,name;\t...
# See (outdated) http://wiki.micasaverde.com/index.php/Luup_UPnP_Variables_and_Actions#DoorLock1
# Remove the trailing tab
# ignore the version and next available at the start
# and split out each set of code attributes
raw_code_list = []
try:
raw_code_list = val.rstrip().split('\t')[1:]
except Exception as ex:
logger.error('Got unsupported string {}: {}'.format(val, ex))
# Loop to create a list of codes
codes = []
for code in raw_code_list:
try:
# Strip off trailing semicolon
# Create a list from csv
code_addrs = code.split(';')[0].split(',')
# Get the code ID (slot) and see if it should have values
slot, active = code_addrs[:2]
if active != '0':
# Since it has additional attributes, get the remaining ones
_, _, pin, name = code_addrs[2:]
# And add them as a tuple to the list
codes.append((slot, name, pin))
except Exception as ex:
logger.error('Problem parsing pin code string {}: {}'.format(code, ex))
return codes | [
"def",
"get_pin_codes",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"val",
"=",
"self",
".",
"get_value",
"(",
"\"pincodes\"",
")",
"# val syntax string: <VERSION=3>next_available_user_code_id\\tuser... | Get the list of PIN codes
Codes can also be found with self.get_complex_value('PinCodes') | [
"Get",
"the",
"list",
"of",
"PIN",
"codes"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1006-L1046 | train |
pavoni/pyvera | pyvera/__init__.py | VeraThermostat.set_temperature | def set_temperature(self, temp):
"""Set current goal temperature / setpoint"""
self.set_service_value(
self.thermostat_setpoint,
'CurrentSetpoint',
'NewCurrentSetpoint',
temp)
self.set_cache_value('setpoint', temp) | python | def set_temperature(self, temp):
"""Set current goal temperature / setpoint"""
self.set_service_value(
self.thermostat_setpoint,
'CurrentSetpoint',
'NewCurrentSetpoint',
temp)
self.set_cache_value('setpoint', temp) | [
"def",
"set_temperature",
"(",
"self",
",",
"temp",
")",
":",
"self",
".",
"set_service_value",
"(",
"self",
".",
"thermostat_setpoint",
",",
"'CurrentSetpoint'",
",",
"'NewCurrentSetpoint'",
",",
"temp",
")",
"self",
".",
"set_cache_value",
"(",
"'setpoint'",
"... | Set current goal temperature / setpoint | [
"Set",
"current",
"goal",
"temperature",
"/",
"setpoint"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1056-L1065 | train |
pavoni/pyvera | pyvera/__init__.py | VeraThermostat.get_current_goal_temperature | def get_current_goal_temperature(self, refresh=False):
"""Get current goal temperature / setpoint"""
if refresh:
self.refresh()
try:
return float(self.get_value('setpoint'))
except (TypeError, ValueError):
return None | python | def get_current_goal_temperature(self, refresh=False):
"""Get current goal temperature / setpoint"""
if refresh:
self.refresh()
try:
return float(self.get_value('setpoint'))
except (TypeError, ValueError):
return None | [
"def",
"get_current_goal_temperature",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"try",
":",
"return",
"float",
"(",
"self",
".",
"get_value",
"(",
"'setpoint'",
")",
")",
"except",
"(",
... | Get current goal temperature / setpoint | [
"Get",
"current",
"goal",
"temperature",
"/",
"setpoint"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1067-L1074 | train |
pavoni/pyvera | pyvera/__init__.py | VeraThermostat.get_current_temperature | def get_current_temperature(self, refresh=False):
"""Get current temperature"""
if refresh:
self.refresh()
try:
return float(self.get_value('temperature'))
except (TypeError, ValueError):
return None | python | def get_current_temperature(self, refresh=False):
"""Get current temperature"""
if refresh:
self.refresh()
try:
return float(self.get_value('temperature'))
except (TypeError, ValueError):
return None | [
"def",
"get_current_temperature",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh",
"(",
")",
"try",
":",
"return",
"float",
"(",
"self",
".",
"get_value",
"(",
"'temperature'",
")",
")",
"except",
"(",
... | Get current temperature | [
"Get",
"current",
"temperature"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1076-L1083 | train |
pavoni/pyvera | pyvera/__init__.py | VeraThermostat.set_hvac_mode | def set_hvac_mode(self, mode):
"""Set the hvac mode"""
self.set_service_value(
self.thermostat_operating_service,
'ModeTarget',
'NewModeTarget',
mode)
self.set_cache_value('mode', mode) | python | def set_hvac_mode(self, mode):
"""Set the hvac mode"""
self.set_service_value(
self.thermostat_operating_service,
'ModeTarget',
'NewModeTarget',
mode)
self.set_cache_value('mode', mode) | [
"def",
"set_hvac_mode",
"(",
"self",
",",
"mode",
")",
":",
"self",
".",
"set_service_value",
"(",
"self",
".",
"thermostat_operating_service",
",",
"'ModeTarget'",
",",
"'NewModeTarget'",
",",
"mode",
")",
"self",
".",
"set_cache_value",
"(",
"'mode'",
",",
"... | Set the hvac mode | [
"Set",
"the",
"hvac",
"mode"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1085-L1092 | train |
pavoni/pyvera | pyvera/__init__.py | VeraThermostat.set_fan_mode | def set_fan_mode(self, mode):
"""Set the fan mode"""
self.set_service_value(
self.thermostat_fan_service,
'Mode',
'NewMode',
mode)
self.set_cache_value('fanmode', mode) | python | def set_fan_mode(self, mode):
"""Set the fan mode"""
self.set_service_value(
self.thermostat_fan_service,
'Mode',
'NewMode',
mode)
self.set_cache_value('fanmode', mode) | [
"def",
"set_fan_mode",
"(",
"self",
",",
"mode",
")",
":",
"self",
".",
"set_service_value",
"(",
"self",
".",
"thermostat_fan_service",
",",
"'Mode'",
",",
"'NewMode'",
",",
"mode",
")",
"self",
".",
"set_cache_value",
"(",
"'fanmode'",
",",
"mode",
")"
] | Set the fan mode | [
"Set",
"the",
"fan",
"mode"
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1116-L1123 | train |
pavoni/pyvera | pyvera/__init__.py | VeraSceneController.get_last_scene_id | def get_last_scene_id(self, refresh=False):
"""Get last scene id.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh_complex_value('LastSceneID')
self.refresh_complex_value('sl_CentralScene')
val = self.get_complex_value('LastSceneID') or self.get_complex_value('sl_CentralScene')
return val | python | def get_last_scene_id(self, refresh=False):
"""Get last scene id.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh_complex_value('LastSceneID')
self.refresh_complex_value('sl_CentralScene')
val = self.get_complex_value('LastSceneID') or self.get_complex_value('sl_CentralScene')
return val | [
"def",
"get_last_scene_id",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh_complex_value",
"(",
"'LastSceneID'",
")",
"self",
".",
"refresh_complex_value",
"(",
"'sl_CentralScene'",
")",
"val",
"=",
"self",
"."... | Get last scene id.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions. | [
"Get",
"last",
"scene",
"id",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1157-L1167 | train |
pavoni/pyvera | pyvera/__init__.py | VeraSceneController.get_last_scene_time | def get_last_scene_time(self, refresh=False):
"""Get last scene time.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh_complex_value('LastSceneTime')
val = self.get_complex_value('LastSceneTime')
return val | python | def get_last_scene_time(self, refresh=False):
"""Get last scene time.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions.
"""
if refresh:
self.refresh_complex_value('LastSceneTime')
val = self.get_complex_value('LastSceneTime')
return val | [
"def",
"get_last_scene_time",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
":",
"self",
".",
"refresh_complex_value",
"(",
"'LastSceneTime'",
")",
"val",
"=",
"self",
".",
"get_complex_value",
"(",
"'LastSceneTime'",
")",
"return",
"va... | Get last scene time.
Refresh data from Vera if refresh is True, otherwise use local cache.
Refresh is only needed if you're not using subscriptions. | [
"Get",
"last",
"scene",
"time",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1169-L1178 | train |
pavoni/pyvera | pyvera/__init__.py | VeraScene.vera_request | def vera_request(self, **kwargs):
"""Perfom a vera_request for this scene."""
request_payload = {
'output_format': 'json',
'SceneNum': self.scene_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | python | def vera_request(self, **kwargs):
"""Perfom a vera_request for this scene."""
request_payload = {
'output_format': 'json',
'SceneNum': self.scene_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | [
"def",
"vera_request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"request_payload",
"=",
"{",
"'output_format'",
":",
"'json'",
",",
"'SceneNum'",
":",
"self",
".",
"scene_id",
",",
"}",
"request_payload",
".",
"update",
"(",
"kwargs",
")",
"return",... | Perfom a vera_request for this scene. | [
"Perfom",
"a",
"vera_request",
"for",
"this",
"scene",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1225-L1233 | train |
pavoni/pyvera | pyvera/__init__.py | VeraScene.activate | def activate(self):
"""Activate a Vera scene.
This will call the Vera api to activate a scene.
"""
payload = {
'id': 'lu_action',
'action': 'RunScene',
'serviceId': self.scene_service
}
result = self.vera_request(**payload)
logger.debug("activate: "
"result of vera_request with payload %s: %s",
payload, result.text)
self._active = True | python | def activate(self):
"""Activate a Vera scene.
This will call the Vera api to activate a scene.
"""
payload = {
'id': 'lu_action',
'action': 'RunScene',
'serviceId': self.scene_service
}
result = self.vera_request(**payload)
logger.debug("activate: "
"result of vera_request with payload %s: %s",
payload, result.text)
self._active = True | [
"def",
"activate",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'id'",
":",
"'lu_action'",
",",
"'action'",
":",
"'RunScene'",
",",
"'serviceId'",
":",
"self",
".",
"scene_service",
"}",
"result",
"=",
"self",
".",
"vera_request",
"(",
"*",
"*",
"payload... | Activate a Vera scene.
This will call the Vera api to activate a scene. | [
"Activate",
"a",
"Vera",
"scene",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1235-L1250 | train |
pavoni/pyvera | pyvera/__init__.py | VeraScene.refresh | def refresh(self):
"""Refresh the data used by get_value.
Only needed if you're not using subscriptions.
"""
j = self.vera_request(id='sdata', output_format='json').json()
scenes = j.get('scenes')
for scene_data in scenes:
if scene_data.get('id') == self.scene_id:
self.update(scene_data) | python | def refresh(self):
"""Refresh the data used by get_value.
Only needed if you're not using subscriptions.
"""
j = self.vera_request(id='sdata', output_format='json').json()
scenes = j.get('scenes')
for scene_data in scenes:
if scene_data.get('id') == self.scene_id:
self.update(scene_data) | [
"def",
"refresh",
"(",
"self",
")",
":",
"j",
"=",
"self",
".",
"vera_request",
"(",
"id",
"=",
"'sdata'",
",",
"output_format",
"=",
"'json'",
")",
".",
"json",
"(",
")",
"scenes",
"=",
"j",
".",
"get",
"(",
"'scenes'",
")",
"for",
"scene_data",
"... | Refresh the data used by get_value.
Only needed if you're not using subscriptions. | [
"Refresh",
"the",
"data",
"used",
"by",
"get_value",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/__init__.py#L1255-L1264 | train |
pavoni/pyvera | pyvera/subscribe.py | SubscriptionRegistry.register | def register(self, device, callback):
"""Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debug("Subscribing to events for %s", device.name)
self._devices[device.vera_device_id].append(device)
self._callbacks[device].append(callback) | python | def register(self, device, callback):
"""Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debug("Subscribing to events for %s", device.name)
self._devices[device.vera_device_id].append(device)
self._callbacks[device].append(callback) | [
"def",
"register",
"(",
"self",
",",
"device",
",",
"callback",
")",
":",
"if",
"not",
"device",
":",
"logger",
".",
"error",
"(",
"\"Received an invalid device: %r\"",
",",
"device",
")",
"return",
"logger",
".",
"debug",
"(",
"\"Subscribing to events for %s\""... | Register a callback.
device: device to be updated by subscription
callback: callback for notification of changes | [
"Register",
"a",
"callback",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L41-L53 | train |
pavoni/pyvera | pyvera/subscribe.py | SubscriptionRegistry.unregister | def unregister(self, device, callback):
"""Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debug("Removing subscription for {}".format(device.name))
self._callbacks[device].remove(callback)
self._devices[device.vera_device_id].remove(device) | python | def unregister(self, device, callback):
"""Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration
"""
if not device:
logger.error("Received an invalid device: %r", device)
return
logger.debug("Removing subscription for {}".format(device.name))
self._callbacks[device].remove(callback)
self._devices[device.vera_device_id].remove(device) | [
"def",
"unregister",
"(",
"self",
",",
"device",
",",
"callback",
")",
":",
"if",
"not",
"device",
":",
"logger",
".",
"error",
"(",
"\"Received an invalid device: %r\"",
",",
"device",
")",
"return",
"logger",
".",
"debug",
"(",
"\"Removing subscription for {}\... | Remove a registered a callback.
device: device that has the subscription
callback: callback used in original registration | [
"Remove",
"a",
"registered",
"a",
"callback",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L55-L67 | train |
pavoni/pyvera | pyvera/subscribe.py | SubscriptionRegistry.start | def start(self):
"""Start a thread to handle Vera blocked polling."""
self._poll_thread = threading.Thread(target=self._run_poll_server,
name='Vera Poll Thread')
self._poll_thread.deamon = True
self._poll_thread.start() | python | def start(self):
"""Start a thread to handle Vera blocked polling."""
self._poll_thread = threading.Thread(target=self._run_poll_server,
name='Vera Poll Thread')
self._poll_thread.deamon = True
self._poll_thread.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_poll_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_run_poll_server",
",",
"name",
"=",
"'Vera Poll Thread'",
")",
"self",
".",
"_poll_thread",
".",
"deamon",
"=",
"True",
... | Start a thread to handle Vera blocked polling. | [
"Start",
"a",
"thread",
"to",
"handle",
"Vera",
"blocked",
"polling",
"."
] | e05e3d13f76153444787d31948feb5419d77a8c8 | https://github.com/pavoni/pyvera/blob/e05e3d13f76153444787d31948feb5419d77a8c8/pyvera/subscribe.py#L129-L134 | train |
macbre/data-flow-graph | sources/elasticsearch/logs2dataflow.py | format_timestamp | def format_timestamp(ts):
"""
Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
"""
tz_info = tz.tzutc()
return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.000Z") | python | def format_timestamp(ts):
"""
Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
"""
tz_info = tz.tzutc()
return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.000Z") | [
"def",
"format_timestamp",
"(",
"ts",
")",
":",
"tz_info",
"=",
"tz",
".",
"tzutc",
"(",
")",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"ts",
",",
"tz",
"=",
"tz_info",
")",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S.000Z\"",
")"
] | Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime | [
"Format",
"the",
"UTC",
"timestamp",
"for",
"Elasticsearch",
"eg",
".",
"2014",
"-",
"07",
"-",
"09T08",
":",
"37",
":",
"18",
".",
"000Z"
] | 16164c3860f3defe3354c19b8536ed01b3bfdb61 | https://github.com/macbre/data-flow-graph/blob/16164c3860f3defe3354c19b8536ed01b3bfdb61/sources/elasticsearch/logs2dataflow.py#L45-L52 | train |
dursk/bitcoin-price-api | exchanges/coinapult.py | Coinapult._pick_level | def _pick_level(cls, btc_amount):
"""
Choose between small, medium, large, ... depending on the
amount specified.
"""
for size, level in cls.TICKER_LEVEL:
if btc_amount < size:
return level
return cls.TICKER_LEVEL[-1][1] | python | def _pick_level(cls, btc_amount):
"""
Choose between small, medium, large, ... depending on the
amount specified.
"""
for size, level in cls.TICKER_LEVEL:
if btc_amount < size:
return level
return cls.TICKER_LEVEL[-1][1] | [
"def",
"_pick_level",
"(",
"cls",
",",
"btc_amount",
")",
":",
"for",
"size",
",",
"level",
"in",
"cls",
".",
"TICKER_LEVEL",
":",
"if",
"btc_amount",
"<",
"size",
":",
"return",
"level",
"return",
"cls",
".",
"TICKER_LEVEL",
"[",
"-",
"1",
"]",
"[",
... | Choose between small, medium, large, ... depending on the
amount specified. | [
"Choose",
"between",
"small",
"medium",
"large",
"...",
"depending",
"on",
"the",
"amount",
"specified",
"."
] | abc186041d7041c9465f476bade589da042f6d6d | https://github.com/dursk/bitcoin-price-api/blob/abc186041d7041c9465f476bade589da042f6d6d/exchanges/coinapult.py#L41-L49 | train |
macbre/data-flow-graph | data_flow_graph.py | format_tsv_line | def format_tsv_line(source, edge, target, value=None, metadata=None):
"""
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
"""
return '{source}\t{edge}\t{target}\t{value}\t{metadata}'.format(
source=source,
edge=edge,
target=target,
value='{:.4f}'.format(value) if value is not None else '',
metadata=metadata or ''
).rstrip(' \t') | python | def format_tsv_line(source, edge, target, value=None, metadata=None):
"""
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
"""
return '{source}\t{edge}\t{target}\t{value}\t{metadata}'.format(
source=source,
edge=edge,
target=target,
value='{:.4f}'.format(value) if value is not None else '',
metadata=metadata or ''
).rstrip(' \t') | [
"def",
"format_tsv_line",
"(",
"source",
",",
"edge",
",",
"target",
",",
"value",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"'{source}\\t{edge}\\t{target}\\t{value}\\t{metadata}'",
".",
"format",
"(",
"source",
"=",
"source",
",",
"edge",
... | Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str | [
"Render",
"a",
"single",
"line",
"for",
"TSV",
"file",
"with",
"data",
"flow",
"described"
] | 16164c3860f3defe3354c19b8536ed01b3bfdb61 | https://github.com/macbre/data-flow-graph/blob/16164c3860f3defe3354c19b8536ed01b3bfdb61/data_flow_graph.py#L7-L24 | train |
macbre/data-flow-graph | data_flow_graph.py | format_graphviz_lines | def format_graphviz_lines(lines):
"""
Render a .dot file with graph definition from a given set of data
:type lines list[dict]
:rtype: str
"""
# first, prepare the unique list of all nodes (sources and targets)
lines_nodes = set()
for line in lines:
lines_nodes.add(line['source'])
lines_nodes.add(line['target'])
# generate a list of all nodes and their names for graphviz graph
nodes = OrderedDict()
for i, node in enumerate(sorted(lines_nodes)):
nodes[node] = 'n{}'.format(i+1)
# print(lines_nodes, nodes)
graph = list()
# some basic style definition
# https://graphviz.gitlab.io/_pages/doc/info/lang.html
graph.append('digraph G {')
# https://graphviz.gitlab.io/_pages/doc/info/shapes.html#record
graph.append('\tgraph [ center=true, margin=0.75, nodesep=0.5, ranksep=0.75, rankdir=LR ];')
graph.append('\tnode [ shape=box, style="rounded,filled" width=0, height=0, '
'fontname=Helvetica, fontsize=11 ];')
graph.append('\tedge [ fontname=Helvetica, fontsize=9 ];')
# emit nodes definition
graph.append('\n\t// nodes')
# https://www.graphviz.org/doc/info/colors.html#brewer
group_colors = dict()
for label, name in nodes.items():
if ':' in label:
(group, label) = str(label).split(':', 1)
# register a new group for coloring
if group not in group_colors:
group_colors[group] = len(group_colors.keys()) + 1
else:
group = None
label = escape_graphviz_entry(label)
graph.append('\t{name} [label="{label}"{group}];'.format(
name=name,
label="{}\\n{}".format(group, label) if group is not None else label,
group=' group="{}" colorscheme=pastel28 color={}'.format(
group, group_colors[group]) if group is not None else ''
))
# now, connect the nodes
graph.append('\n\t// edges')
for line in lines:
label = line.get('metadata', '')
graph.append('\t{source} -> {target} [{label}];'.format(
source=nodes[line['source']],
target=nodes[line['target']],
label='label="{}"'.format(escape_graphviz_entry(label)) if label != '' else ''
))
graph.append('}')
return '\n'.join(graph) | python | def format_graphviz_lines(lines):
"""
Render a .dot file with graph definition from a given set of data
:type lines list[dict]
:rtype: str
"""
# first, prepare the unique list of all nodes (sources and targets)
lines_nodes = set()
for line in lines:
lines_nodes.add(line['source'])
lines_nodes.add(line['target'])
# generate a list of all nodes and their names for graphviz graph
nodes = OrderedDict()
for i, node in enumerate(sorted(lines_nodes)):
nodes[node] = 'n{}'.format(i+1)
# print(lines_nodes, nodes)
graph = list()
# some basic style definition
# https://graphviz.gitlab.io/_pages/doc/info/lang.html
graph.append('digraph G {')
# https://graphviz.gitlab.io/_pages/doc/info/shapes.html#record
graph.append('\tgraph [ center=true, margin=0.75, nodesep=0.5, ranksep=0.75, rankdir=LR ];')
graph.append('\tnode [ shape=box, style="rounded,filled" width=0, height=0, '
'fontname=Helvetica, fontsize=11 ];')
graph.append('\tedge [ fontname=Helvetica, fontsize=9 ];')
# emit nodes definition
graph.append('\n\t// nodes')
# https://www.graphviz.org/doc/info/colors.html#brewer
group_colors = dict()
for label, name in nodes.items():
if ':' in label:
(group, label) = str(label).split(':', 1)
# register a new group for coloring
if group not in group_colors:
group_colors[group] = len(group_colors.keys()) + 1
else:
group = None
label = escape_graphviz_entry(label)
graph.append('\t{name} [label="{label}"{group}];'.format(
name=name,
label="{}\\n{}".format(group, label) if group is not None else label,
group=' group="{}" colorscheme=pastel28 color={}'.format(
group, group_colors[group]) if group is not None else ''
))
# now, connect the nodes
graph.append('\n\t// edges')
for line in lines:
label = line.get('metadata', '')
graph.append('\t{source} -> {target} [{label}];'.format(
source=nodes[line['source']],
target=nodes[line['target']],
label='label="{}"'.format(escape_graphviz_entry(label)) if label != '' else ''
))
graph.append('}')
return '\n'.join(graph) | [
"def",
"format_graphviz_lines",
"(",
"lines",
")",
":",
"# first, prepare the unique list of all nodes (sources and targets)",
"lines_nodes",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"lines_nodes",
".",
"add",
"(",
"line",
"[",
"'source'",
"]",
")",
... | Render a .dot file with graph definition from a given set of data
:type lines list[dict]
:rtype: str | [
"Render",
"a",
".",
"dot",
"file",
"with",
"graph",
"definition",
"from",
"a",
"given",
"set",
"of",
"data"
] | 16164c3860f3defe3354c19b8536ed01b3bfdb61 | https://github.com/macbre/data-flow-graph/blob/16164c3860f3defe3354c19b8536ed01b3bfdb61/data_flow_graph.py#L45-L117 | train |
macbre/data-flow-graph | data_flow_graph.py | logs_map_and_reduce | def logs_map_and_reduce(logs, _map, _reduce):
"""
:type logs str[]
:type _map (list) -> str
:type _reduce (list) -> obj
"""
keys = []
mapped_count = Counter()
mapped = defaultdict(list)
# first map all entries
for log in logs:
key = _map(log)
mapped[key].append(log)
mapped_count[key] += 1
if key not in keys:
keys.append(key)
# the most common mapped item
top_count = mapped_count.most_common(1).pop()[1]
# now reduce mapped items
reduced = []
# keep the order under control
for key in keys:
entries = mapped[key]
# print(key, entries)
# add "value" field to each reduced item (1.0 will be assigned to the most "common" item)
item = _reduce(entries)
item['value'] = 1. * len(entries) / top_count
reduced.append(item)
# print(mapped)
return reduced | python | def logs_map_and_reduce(logs, _map, _reduce):
"""
:type logs str[]
:type _map (list) -> str
:type _reduce (list) -> obj
"""
keys = []
mapped_count = Counter()
mapped = defaultdict(list)
# first map all entries
for log in logs:
key = _map(log)
mapped[key].append(log)
mapped_count[key] += 1
if key not in keys:
keys.append(key)
# the most common mapped item
top_count = mapped_count.most_common(1).pop()[1]
# now reduce mapped items
reduced = []
# keep the order under control
for key in keys:
entries = mapped[key]
# print(key, entries)
# add "value" field to each reduced item (1.0 will be assigned to the most "common" item)
item = _reduce(entries)
item['value'] = 1. * len(entries) / top_count
reduced.append(item)
# print(mapped)
return reduced | [
"def",
"logs_map_and_reduce",
"(",
"logs",
",",
"_map",
",",
"_reduce",
")",
":",
"keys",
"=",
"[",
"]",
"mapped_count",
"=",
"Counter",
"(",
")",
"mapped",
"=",
"defaultdict",
"(",
"list",
")",
"# first map all entries",
"for",
"log",
"in",
"logs",
":",
... | :type logs str[]
:type _map (list) -> str
:type _reduce (list) -> obj | [
":",
"type",
"logs",
"str",
"[]",
":",
"type",
"_map",
"(",
"list",
")",
"-",
">",
"str",
":",
"type",
"_reduce",
"(",
"list",
")",
"-",
">",
"obj"
] | 16164c3860f3defe3354c19b8536ed01b3bfdb61 | https://github.com/macbre/data-flow-graph/blob/16164c3860f3defe3354c19b8536ed01b3bfdb61/data_flow_graph.py#L120-L157 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.close_chromium | def close_chromium(self):
'''
Close the remote chromium instance.
This command is normally executed as part of the class destructor.
It can be called early without issue, but calling ANY class functions
after the remote chromium instance is shut down will have unknown effects.
Note that if you are rapidly creating and destroying ChromeController instances,
you may need to *explicitly* call this before destruction.
'''
if self.cr_proc:
try:
if 'win' in sys.platform:
self.__close_internal_windows()
else:
self.__close_internal_linux()
except Exception as e:
for line in traceback.format_exc().split("\n"):
self.log.error(line)
ACTIVE_PORTS.discard(self.port) | python | def close_chromium(self):
'''
Close the remote chromium instance.
This command is normally executed as part of the class destructor.
It can be called early without issue, but calling ANY class functions
after the remote chromium instance is shut down will have unknown effects.
Note that if you are rapidly creating and destroying ChromeController instances,
you may need to *explicitly* call this before destruction.
'''
if self.cr_proc:
try:
if 'win' in sys.platform:
self.__close_internal_windows()
else:
self.__close_internal_linux()
except Exception as e:
for line in traceback.format_exc().split("\n"):
self.log.error(line)
ACTIVE_PORTS.discard(self.port) | [
"def",
"close_chromium",
"(",
"self",
")",
":",
"if",
"self",
".",
"cr_proc",
":",
"try",
":",
"if",
"'win'",
"in",
"sys",
".",
"platform",
":",
"self",
".",
"__close_internal_windows",
"(",
")",
"else",
":",
"self",
".",
"__close_internal_linux",
"(",
"... | Close the remote chromium instance.
This command is normally executed as part of the class destructor.
It can be called early without issue, but calling ANY class functions
after the remote chromium instance is shut down will have unknown effects.
Note that if you are rapidly creating and destroying ChromeController instances,
you may need to *explicitly* call this before destruction. | [
"Close",
"the",
"remote",
"chromium",
"instance",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L235-L258 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.connect | def connect(self, tab_key):
"""
Open a websocket connection to remote browser, determined by
self.host and self.port. Each tab has it's own websocket
endpoint.
"""
assert self.tablist is not None
tab_idx = self._get_tab_idx_for_key(tab_key)
if not self.tablist:
self.tablist = self.fetch_tablist()
for fails in range(9999):
try:
# If we're one past the end of the tablist, we need to create a new tab
if tab_idx is None:
self.log.debug("Creating new tab (%s active)", len(self.tablist))
self.__create_new_tab(tab_key)
self.__connect_to_tab(tab_key)
break
except cr_exceptions.ChromeConnectFailure as e:
if fails > 6:
self.log.error("Failed to fetch tab websocket URL after %s retries. Aborting!", fails)
raise e
self.log.info("Tab may not have started yet (%s tabs active). Recreating.", len(self.tablist))
# self.log.info("Tag: %s", self.tablist[tab_idx])
# For reasons I don't understand, sometimes a new tab doesn't get a websocket
# debugger URL. Anyways, we close and re-open the tab if that happens.
# TODO: Handle the case when this happens on the first tab. I think closing the first
# tab will kill chromium.
self.__close_tab(tab_key) | python | def connect(self, tab_key):
"""
Open a websocket connection to remote browser, determined by
self.host and self.port. Each tab has it's own websocket
endpoint.
"""
assert self.tablist is not None
tab_idx = self._get_tab_idx_for_key(tab_key)
if not self.tablist:
self.tablist = self.fetch_tablist()
for fails in range(9999):
try:
# If we're one past the end of the tablist, we need to create a new tab
if tab_idx is None:
self.log.debug("Creating new tab (%s active)", len(self.tablist))
self.__create_new_tab(tab_key)
self.__connect_to_tab(tab_key)
break
except cr_exceptions.ChromeConnectFailure as e:
if fails > 6:
self.log.error("Failed to fetch tab websocket URL after %s retries. Aborting!", fails)
raise e
self.log.info("Tab may not have started yet (%s tabs active). Recreating.", len(self.tablist))
# self.log.info("Tag: %s", self.tablist[tab_idx])
# For reasons I don't understand, sometimes a new tab doesn't get a websocket
# debugger URL. Anyways, we close and re-open the tab if that happens.
# TODO: Handle the case when this happens on the first tab. I think closing the first
# tab will kill chromium.
self.__close_tab(tab_key) | [
"def",
"connect",
"(",
"self",
",",
"tab_key",
")",
":",
"assert",
"self",
".",
"tablist",
"is",
"not",
"None",
"tab_idx",
"=",
"self",
".",
"_get_tab_idx_for_key",
"(",
"tab_key",
")",
"if",
"not",
"self",
".",
"tablist",
":",
"self",
".",
"tablist",
... | Open a websocket connection to remote browser, determined by
self.host and self.port. Each tab has it's own websocket
endpoint. | [
"Open",
"a",
"websocket",
"connection",
"to",
"remote",
"browser",
"determined",
"by",
"self",
".",
"host",
"and",
"self",
".",
"port",
".",
"Each",
"tab",
"has",
"it",
"s",
"own",
"websocket",
"endpoint",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L300-L337 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.close_websockets | def close_websockets(self):
""" Close websocket connection to remote browser."""
self.log.info("Websocket Teardown called")
for key in list(self.soclist.keys()):
if self.soclist[key]:
self.soclist[key].close()
self.soclist.pop(key) | python | def close_websockets(self):
""" Close websocket connection to remote browser."""
self.log.info("Websocket Teardown called")
for key in list(self.soclist.keys()):
if self.soclist[key]:
self.soclist[key].close()
self.soclist.pop(key) | [
"def",
"close_websockets",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Websocket Teardown called\"",
")",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"soclist",
".",
"keys",
"(",
")",
")",
":",
"if",
"self",
".",
"soclist",
"[",
... | Close websocket connection to remote browser. | [
"Close",
"websocket",
"connection",
"to",
"remote",
"browser",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L423-L429 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.fetch_tablist | def fetch_tablist(self):
"""Connect to host:port and request list of tabs
return list of dicts of data about open tabs."""
# find websocket endpoint
try:
response = requests.get("http://%s:%s/json" % (self.host, self.port))
except requests.exceptions.ConnectionError:
raise cr_exceptions.ChromeConnectFailure("Failed to fetch configuration json from browser!")
tablist = json.loads(response.text)
return tablist | python | def fetch_tablist(self):
"""Connect to host:port and request list of tabs
return list of dicts of data about open tabs."""
# find websocket endpoint
try:
response = requests.get("http://%s:%s/json" % (self.host, self.port))
except requests.exceptions.ConnectionError:
raise cr_exceptions.ChromeConnectFailure("Failed to fetch configuration json from browser!")
tablist = json.loads(response.text)
return tablist | [
"def",
"fetch_tablist",
"(",
"self",
")",
":",
"# find websocket endpoint",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"\"http://%s:%s/json\"",
"%",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"except",
"requests",
".",
"ex... | Connect to host:port and request list of tabs
return list of dicts of data about open tabs. | [
"Connect",
"to",
"host",
":",
"port",
"and",
"request",
"list",
"of",
"tabs",
"return",
"list",
"of",
"dicts",
"of",
"data",
"about",
"open",
"tabs",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L432-L443 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.synchronous_command | def synchronous_command(self, command, tab_key, **params):
"""
Synchronously execute command `command` with params `params` in the
remote chrome instance, returning the response from the chrome instance.
"""
self.log.debug("Synchronous_command to tab %s (%s):", tab_key, self._get_cr_tab_meta_for_key(tab_key))
self.log.debug(" command: '%s'", command)
self.log.debug(" params: '%s'", params)
self.log.debug(" tab_key: '%s'", tab_key)
send_id = self.send(command=command, tab_key=tab_key, params=params)
resp = self.recv(message_id=send_id, tab_key=tab_key)
self.log.debug(" Response: '%s'", str(resp).encode("ascii", 'ignore').decode("ascii"))
# self.log.debug(" resolved tab idx %s:", self.tab_id_map[tab_key])
return resp | python | def synchronous_command(self, command, tab_key, **params):
"""
Synchronously execute command `command` with params `params` in the
remote chrome instance, returning the response from the chrome instance.
"""
self.log.debug("Synchronous_command to tab %s (%s):", tab_key, self._get_cr_tab_meta_for_key(tab_key))
self.log.debug(" command: '%s'", command)
self.log.debug(" params: '%s'", params)
self.log.debug(" tab_key: '%s'", tab_key)
send_id = self.send(command=command, tab_key=tab_key, params=params)
resp = self.recv(message_id=send_id, tab_key=tab_key)
self.log.debug(" Response: '%s'", str(resp).encode("ascii", 'ignore').decode("ascii"))
# self.log.debug(" resolved tab idx %s:", self.tab_id_map[tab_key])
return resp | [
"def",
"synchronous_command",
"(",
"self",
",",
"command",
",",
"tab_key",
",",
"*",
"*",
"params",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Synchronous_command to tab %s (%s):\"",
",",
"tab_key",
",",
"self",
".",
"_get_cr_tab_meta_for_key",
"(",
"... | Synchronously execute command `command` with params `params` in the
remote chrome instance, returning the response from the chrome instance. | [
"Synchronously",
"execute",
"command",
"command",
"with",
"params",
"params",
"in",
"the",
"remote",
"chrome",
"instance",
"returning",
"the",
"response",
"from",
"the",
"chrome",
"instance",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L455-L472 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.send | def send(self, command, tab_key, params=None):
'''
Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response.
'''
self.__check_open_socket(tab_key)
sent_id = self.msg_id
command = {
"id": self.msg_id,
"method": command,
}
if params:
command["params"] = params
navcom = json.dumps(command)
# self.log.debug(" Sending: '%s'", navcom)
try:
self.soclist[tab_key].send(navcom)
except (socket.timeout, websocket.WebSocketTimeoutException):
raise cr_exceptions.ChromeCommunicationsError("Failure sending command to chromium.")
except websocket.WebSocketConnectionClosedException:
raise cr_exceptions.ChromeCommunicationsError("Websocket appears to have been closed. Is the"
" remote chromium instance dead?")
self.msg_id += 1
return sent_id | python | def send(self, command, tab_key, params=None):
'''
Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response.
'''
self.__check_open_socket(tab_key)
sent_id = self.msg_id
command = {
"id": self.msg_id,
"method": command,
}
if params:
command["params"] = params
navcom = json.dumps(command)
# self.log.debug(" Sending: '%s'", navcom)
try:
self.soclist[tab_key].send(navcom)
except (socket.timeout, websocket.WebSocketTimeoutException):
raise cr_exceptions.ChromeCommunicationsError("Failure sending command to chromium.")
except websocket.WebSocketConnectionClosedException:
raise cr_exceptions.ChromeCommunicationsError("Websocket appears to have been closed. Is the"
" remote chromium instance dead?")
self.msg_id += 1
return sent_id | [
"def",
"send",
"(",
"self",
",",
"command",
",",
"tab_key",
",",
"params",
"=",
"None",
")",
":",
"self",
".",
"__check_open_socket",
"(",
"tab_key",
")",
"sent_id",
"=",
"self",
".",
"msg_id",
"command",
"=",
"{",
"\"id\"",
":",
"self",
".",
"msg_id",... | Send command `command` with optional parameters `params` to the
remote chrome instance.
The command `id` is automatically added to the outgoing message.
return value is the command id, which can be used to match a command
to it's associated response. | [
"Send",
"command",
"command",
"with",
"optional",
"parameters",
"params",
"to",
"the",
"remote",
"chrome",
"instance",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L474-L509 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.recv_filtered | def recv_filtered(self, keycheck, tab_key, timeout=30, message=None):
'''
Receive a filtered message, using the callable `keycheck` to filter received messages
for content.
`keycheck` is expected to be a callable that takes a single parameter (the decoded response
from chromium), and returns a boolean (true, if the command is the one filtered for, or false
if the command is not the one filtered for).
This is used internally, for example, by `recv()`, to filter the response for a specific ID:
```
def check_func(message):
if message_id is None:
return True
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, timeout)
```
Note that the function is defined dynamically, and `message_id` is captured via closure.
'''
self.__check_open_socket(tab_key)
# First, check if the message has already been received.
for idx in range(len(self.messages[tab_key])):
if keycheck(self.messages[tab_key][idx]):
return self.messages[tab_key].pop(idx)
timeout_at = time.time() + timeout
while 1:
tmp = self.___recv(tab_key)
if keycheck(tmp):
return tmp
else:
self.messages[tab_key].append(tmp)
if time.time() > timeout_at:
if message:
raise cr_exceptions.ChromeResponseNotReceived("Failed to receive response in recv_filtered() (%s)" % message)
else:
raise cr_exceptions.ChromeResponseNotReceived("Failed to receive response in recv_filtered()")
else:
time.sleep(0.005) | python | def recv_filtered(self, keycheck, tab_key, timeout=30, message=None):
'''
Receive a filtered message, using the callable `keycheck` to filter received messages
for content.
`keycheck` is expected to be a callable that takes a single parameter (the decoded response
from chromium), and returns a boolean (true, if the command is the one filtered for, or false
if the command is not the one filtered for).
This is used internally, for example, by `recv()`, to filter the response for a specific ID:
```
def check_func(message):
if message_id is None:
return True
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, timeout)
```
Note that the function is defined dynamically, and `message_id` is captured via closure.
'''
self.__check_open_socket(tab_key)
# First, check if the message has already been received.
for idx in range(len(self.messages[tab_key])):
if keycheck(self.messages[tab_key][idx]):
return self.messages[tab_key].pop(idx)
timeout_at = time.time() + timeout
while 1:
tmp = self.___recv(tab_key)
if keycheck(tmp):
return tmp
else:
self.messages[tab_key].append(tmp)
if time.time() > timeout_at:
if message:
raise cr_exceptions.ChromeResponseNotReceived("Failed to receive response in recv_filtered() (%s)" % message)
else:
raise cr_exceptions.ChromeResponseNotReceived("Failed to receive response in recv_filtered()")
else:
time.sleep(0.005) | [
"def",
"recv_filtered",
"(",
"self",
",",
"keycheck",
",",
"tab_key",
",",
"timeout",
"=",
"30",
",",
"message",
"=",
"None",
")",
":",
"self",
".",
"__check_open_socket",
"(",
"tab_key",
")",
"# First, check if the message has already been received.",
"for",
"idx... | Receive a filtered message, using the callable `keycheck` to filter received messages
for content.
`keycheck` is expected to be a callable that takes a single parameter (the decoded response
from chromium), and returns a boolean (true, if the command is the one filtered for, or false
if the command is not the one filtered for).
This is used internally, for example, by `recv()`, to filter the response for a specific ID:
```
def check_func(message):
if message_id is None:
return True
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, timeout)
```
Note that the function is defined dynamically, and `message_id` is captured via closure. | [
"Receive",
"a",
"filtered",
"message",
"using",
"the",
"callable",
"keycheck",
"to",
"filter",
"received",
"messages",
"for",
"content",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L531-L579 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.recv_all_filtered | def recv_all_filtered(self, keycheck, tab_key, timeout=0.5):
'''
Receive a all messages matching a filter, using the callable `keycheck` to filter received messages
for content.
This function will *ALWAY* block for at least `timeout` seconds.
If chromium is for some reason continuously streaming responses, it may block forever!
`keycheck` is expected to be a callable that takes a single parameter (the decoded response
from chromium), and returns a boolean (true, if the command is the one filtered for, or false
if the command is not the one filtered for).
```
def check_func(message):
if message_id is None:
return True
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, timeout)
```
Note that the function is defined dynamically, and `message_id` is captured via closure.
'''
self.__check_open_socket(tab_key)
# First, check if the message has already been received.
ret = [tmp for tmp in self.messages[tab_key] if keycheck(tmp)]
self.messages[tab_key] = [tmp for tmp in self.messages[tab_key] if not keycheck(tmp)]
self.log.debug("Waiting for all messages from the socket")
timeout_at = time.time() + timeout
while 1:
tmp = self.___recv(tab_key, timeout=timeout)
if keycheck(tmp):
ret.append(tmp)
else:
self.messages[tab_key].append(tmp)
if time.time() > timeout_at:
return ret
else:
self.log.debug("Sleeping: %s, %s" % (timeout_at, time.time()))
time.sleep(0.005) | python | def recv_all_filtered(self, keycheck, tab_key, timeout=0.5):
'''
Receive a all messages matching a filter, using the callable `keycheck` to filter received messages
for content.
This function will *ALWAY* block for at least `timeout` seconds.
If chromium is for some reason continuously streaming responses, it may block forever!
`keycheck` is expected to be a callable that takes a single parameter (the decoded response
from chromium), and returns a boolean (true, if the command is the one filtered for, or false
if the command is not the one filtered for).
```
def check_func(message):
if message_id is None:
return True
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, timeout)
```
Note that the function is defined dynamically, and `message_id` is captured via closure.
'''
self.__check_open_socket(tab_key)
# First, check if the message has already been received.
ret = [tmp for tmp in self.messages[tab_key] if keycheck(tmp)]
self.messages[tab_key] = [tmp for tmp in self.messages[tab_key] if not keycheck(tmp)]
self.log.debug("Waiting for all messages from the socket")
timeout_at = time.time() + timeout
while 1:
tmp = self.___recv(tab_key, timeout=timeout)
if keycheck(tmp):
ret.append(tmp)
else:
self.messages[tab_key].append(tmp)
if time.time() > timeout_at:
return ret
else:
self.log.debug("Sleeping: %s, %s" % (timeout_at, time.time()))
time.sleep(0.005) | [
"def",
"recv_all_filtered",
"(",
"self",
",",
"keycheck",
",",
"tab_key",
",",
"timeout",
"=",
"0.5",
")",
":",
"self",
".",
"__check_open_socket",
"(",
"tab_key",
")",
"# First, check if the message has already been received.",
"ret",
"=",
"[",
"tmp",
"for",
"tmp... | Receive a all messages matching a filter, using the callable `keycheck` to filter received messages
for content.
This function will *ALWAY* block for at least `timeout` seconds.
If chromium is for some reason continuously streaming responses, it may block forever!
`keycheck` is expected to be a callable that takes a single parameter (the decoded response
from chromium), and returns a boolean (true, if the command is the one filtered for, or false
if the command is not the one filtered for).
```
def check_func(message):
if message_id is None:
return True
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, timeout)
```
Note that the function is defined dynamically, and `message_id` is captured via closure. | [
"Receive",
"a",
"all",
"messages",
"matching",
"a",
"filter",
"using",
"the",
"callable",
"keycheck",
"to",
"filter",
"received",
"messages",
"for",
"content",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L581-L628 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.recv | def recv(self, tab_key, message_id=None, timeout=30):
'''
Recieve a message, optionally filtering for a specified message id.
If `message_id` is none, the first command in the receive queue is returned.
If `message_id` is not none, the command waits untill a message is received with
the specified id, or it times out.
Timeout is the number of seconds to wait for a response, or `None` if the timeout
has expired with no response.
'''
self.__check_open_socket(tab_key)
# First, check if the message has already been received.
for idx in range(len(self.messages[tab_key])):
if self.messages[tab_key][idx]:
if "id" in self.messages[tab_key][idx] and message_id:
if self.messages[tab_key][idx]['id'] == message_id:
return self.messages[tab_key].pop(idx)
# Then spin untill we either have the message,
# or have timed out.
def check_func(message):
if message_id is None:
return True
if not message:
self.log.debug("Message is not true (%s)!", message)
return False
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, tab_key, timeout) | python | def recv(self, tab_key, message_id=None, timeout=30):
'''
Recieve a message, optionally filtering for a specified message id.
If `message_id` is none, the first command in the receive queue is returned.
If `message_id` is not none, the command waits untill a message is received with
the specified id, or it times out.
Timeout is the number of seconds to wait for a response, or `None` if the timeout
has expired with no response.
'''
self.__check_open_socket(tab_key)
# First, check if the message has already been received.
for idx in range(len(self.messages[tab_key])):
if self.messages[tab_key][idx]:
if "id" in self.messages[tab_key][idx] and message_id:
if self.messages[tab_key][idx]['id'] == message_id:
return self.messages[tab_key].pop(idx)
# Then spin untill we either have the message,
# or have timed out.
def check_func(message):
if message_id is None:
return True
if not message:
self.log.debug("Message is not true (%s)!", message)
return False
if "id" in message:
return message['id'] == message_id
return False
return self.recv_filtered(check_func, tab_key, timeout) | [
"def",
"recv",
"(",
"self",
",",
"tab_key",
",",
"message_id",
"=",
"None",
",",
"timeout",
"=",
"30",
")",
":",
"self",
".",
"__check_open_socket",
"(",
"tab_key",
")",
"# First, check if the message has already been received.",
"for",
"idx",
"in",
"range",
"("... | Recieve a message, optionally filtering for a specified message id.
If `message_id` is none, the first command in the receive queue is returned.
If `message_id` is not none, the command waits untill a message is received with
the specified id, or it times out.
Timeout is the number of seconds to wait for a response, or `None` if the timeout
has expired with no response. | [
"Recieve",
"a",
"message",
"optionally",
"filtering",
"for",
"a",
"specified",
"message",
"id",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L630-L664 | train |
fake-name/ChromeController | ChromeController/transport.py | ChromeExecutionManager.drain | def drain(self, tab_key):
'''
Return all messages in waiting for the websocket connection.
'''
self.log.debug("Draining transport")
ret = []
while len(self.messages[tab_key]):
ret.append(self.messages[tab_key].pop(0))
self.log.debug("Polling socket")
tmp = self.___recv(tab_key)
while tmp is not None:
ret.append(tmp)
tmp = self.___recv(tab_key)
self.log.debug("Drained %s messages", len(ret))
return ret | python | def drain(self, tab_key):
'''
Return all messages in waiting for the websocket connection.
'''
self.log.debug("Draining transport")
ret = []
while len(self.messages[tab_key]):
ret.append(self.messages[tab_key].pop(0))
self.log.debug("Polling socket")
tmp = self.___recv(tab_key)
while tmp is not None:
ret.append(tmp)
tmp = self.___recv(tab_key)
self.log.debug("Drained %s messages", len(ret))
return ret | [
"def",
"drain",
"(",
"self",
",",
"tab_key",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Draining transport\"",
")",
"ret",
"=",
"[",
"]",
"while",
"len",
"(",
"self",
".",
"messages",
"[",
"tab_key",
"]",
")",
":",
"ret",
".",
"append",
"(... | Return all messages in waiting for the websocket connection. | [
"Return",
"all",
"messages",
"in",
"waiting",
"for",
"the",
"websocket",
"connection",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/transport.py#L674-L691 | train |
fake-name/ChromeController | ChromeController/__main__.py | cli | def cli(verbose, silent):
'''
ChromeController
\b
Usage: python3 -m ChromeController [-s | --silent] [-v | --verbose]
python3 -m ChromeController fetch <url> [--binary <bin_name>] [--outfile <out_file_name>]
python3 -m ChromeController update
python3 -m ChromeController (-h | --help)
python3 -m ChromeController --version
\b
Options:
-s --silent Suppress all output aside from the fetched content
This basically makes ChromeController act like a alternative to curl
-v --verbose The opposite of silent. Causes the internal logging to output
all traffic over the chromium control interface. VERY noisy.
--version Show version.
fetch Fetch a specified URL's content, and output it to the console.
'''
if verbose:
logging.basicConfig(level=logging.DEBUG)
elif silent:
logging.basicConfig(level=logging.ERROR)
else:
logging.basicConfig(level=logging.INFO) | python | def cli(verbose, silent):
'''
ChromeController
\b
Usage: python3 -m ChromeController [-s | --silent] [-v | --verbose]
python3 -m ChromeController fetch <url> [--binary <bin_name>] [--outfile <out_file_name>]
python3 -m ChromeController update
python3 -m ChromeController (-h | --help)
python3 -m ChromeController --version
\b
Options:
-s --silent Suppress all output aside from the fetched content
This basically makes ChromeController act like a alternative to curl
-v --verbose The opposite of silent. Causes the internal logging to output
all traffic over the chromium control interface. VERY noisy.
--version Show version.
fetch Fetch a specified URL's content, and output it to the console.
'''
if verbose:
logging.basicConfig(level=logging.DEBUG)
elif silent:
logging.basicConfig(level=logging.ERROR)
else:
logging.basicConfig(level=logging.INFO) | [
"def",
"cli",
"(",
"verbose",
",",
"silent",
")",
":",
"if",
"verbose",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"elif",
"silent",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"ERROR... | ChromeController
\b
Usage: python3 -m ChromeController [-s | --silent] [-v | --verbose]
python3 -m ChromeController fetch <url> [--binary <bin_name>] [--outfile <out_file_name>]
python3 -m ChromeController update
python3 -m ChromeController (-h | --help)
python3 -m ChromeController --version
\b
Options:
-s --silent Suppress all output aside from the fetched content
This basically makes ChromeController act like a alternative to curl
-v --verbose The opposite of silent. Causes the internal logging to output
all traffic over the chromium control interface. VERY noisy.
--version Show version.
fetch Fetch a specified URL's content, and output it to the console. | [
"ChromeController"
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/__main__.py#L17-L43 | train |
fake-name/ChromeController | ChromeController/__main__.py | fetch | def fetch(url, binary, outfile, noprint, rendered):
'''
Fetch a specified URL's content, and output it to the console.
'''
with chrome_context.ChromeContext(binary=binary) as cr:
resp = cr.blocking_navigate_and_get_source(url)
if rendered:
resp['content'] = cr.get_rendered_page_source()
resp['binary'] = False
resp['mimie'] = 'text/html'
if not noprint:
if resp['binary'] is False:
print(resp['content'])
else:
print("Response is a binary file")
print("Cannot print!")
if outfile:
with open(outfile, "wb") as fp:
if resp['binary']:
fp.write(resp['content'])
else:
fp.write(resp['content'].encode("UTF-8")) | python | def fetch(url, binary, outfile, noprint, rendered):
'''
Fetch a specified URL's content, and output it to the console.
'''
with chrome_context.ChromeContext(binary=binary) as cr:
resp = cr.blocking_navigate_and_get_source(url)
if rendered:
resp['content'] = cr.get_rendered_page_source()
resp['binary'] = False
resp['mimie'] = 'text/html'
if not noprint:
if resp['binary'] is False:
print(resp['content'])
else:
print("Response is a binary file")
print("Cannot print!")
if outfile:
with open(outfile, "wb") as fp:
if resp['binary']:
fp.write(resp['content'])
else:
fp.write(resp['content'].encode("UTF-8")) | [
"def",
"fetch",
"(",
"url",
",",
"binary",
",",
"outfile",
",",
"noprint",
",",
"rendered",
")",
":",
"with",
"chrome_context",
".",
"ChromeContext",
"(",
"binary",
"=",
"binary",
")",
"as",
"cr",
":",
"resp",
"=",
"cr",
".",
"blocking_navigate_and_get_sou... | Fetch a specified URL's content, and output it to the console. | [
"Fetch",
"a",
"specified",
"URL",
"s",
"content",
"and",
"output",
"it",
"to",
"the",
"console",
"."
] | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/__main__.py#L68-L91 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Memory_setPressureNotificationsSuppressed | def Memory_setPressureNotificationsSuppressed(self, suppressed):
"""
Function path: Memory.setPressureNotificationsSuppressed
Domain: Memory
Method name: setPressureNotificationsSuppressed
Parameters:
Required arguments:
'suppressed' (type: boolean) -> If true, memory pressure notifications will be suppressed.
No return value.
Description: Enable/disable suppressing memory pressure notifications in all processes.
"""
assert isinstance(suppressed, (bool,)
), "Argument 'suppressed' must be of type '['bool']'. Received type: '%s'" % type(
suppressed)
subdom_funcs = self.synchronous_command(
'Memory.setPressureNotificationsSuppressed', suppressed=suppressed)
return subdom_funcs | python | def Memory_setPressureNotificationsSuppressed(self, suppressed):
"""
Function path: Memory.setPressureNotificationsSuppressed
Domain: Memory
Method name: setPressureNotificationsSuppressed
Parameters:
Required arguments:
'suppressed' (type: boolean) -> If true, memory pressure notifications will be suppressed.
No return value.
Description: Enable/disable suppressing memory pressure notifications in all processes.
"""
assert isinstance(suppressed, (bool,)
), "Argument 'suppressed' must be of type '['bool']'. Received type: '%s'" % type(
suppressed)
subdom_funcs = self.synchronous_command(
'Memory.setPressureNotificationsSuppressed', suppressed=suppressed)
return subdom_funcs | [
"def",
"Memory_setPressureNotificationsSuppressed",
"(",
"self",
",",
"suppressed",
")",
":",
"assert",
"isinstance",
"(",
"suppressed",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'suppressed' must be of type '['bool']'. Received type: '%s'\"",
"%",
"type",
"(",
... | Function path: Memory.setPressureNotificationsSuppressed
Domain: Memory
Method name: setPressureNotificationsSuppressed
Parameters:
Required arguments:
'suppressed' (type: boolean) -> If true, memory pressure notifications will be suppressed.
No return value.
Description: Enable/disable suppressing memory pressure notifications in all processes. | [
"Function",
"path",
":",
"Memory",
".",
"setPressureNotificationsSuppressed",
"Domain",
":",
"Memory",
"Method",
"name",
":",
"setPressureNotificationsSuppressed",
"Parameters",
":",
"Required",
"arguments",
":",
"suppressed",
"(",
"type",
":",
"boolean",
")",
"-",
... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L66-L84 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Page_addScriptToEvaluateOnLoad | def Page_addScriptToEvaluateOnLoad(self, scriptSource):
"""
Function path: Page.addScriptToEvaluateOnLoad
Domain: Page
Method name: addScriptToEvaluateOnLoad
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'scriptSource' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> Identifier of the added script.
Description: Deprecated, please use addScriptToEvaluateOnNewDocument instead.
"""
assert isinstance(scriptSource, (str,)
), "Argument 'scriptSource' must be of type '['str']'. Received type: '%s'" % type(
scriptSource)
subdom_funcs = self.synchronous_command('Page.addScriptToEvaluateOnLoad',
scriptSource=scriptSource)
return subdom_funcs | python | def Page_addScriptToEvaluateOnLoad(self, scriptSource):
"""
Function path: Page.addScriptToEvaluateOnLoad
Domain: Page
Method name: addScriptToEvaluateOnLoad
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'scriptSource' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> Identifier of the added script.
Description: Deprecated, please use addScriptToEvaluateOnNewDocument instead.
"""
assert isinstance(scriptSource, (str,)
), "Argument 'scriptSource' must be of type '['str']'. Received type: '%s'" % type(
scriptSource)
subdom_funcs = self.synchronous_command('Page.addScriptToEvaluateOnLoad',
scriptSource=scriptSource)
return subdom_funcs | [
"def",
"Page_addScriptToEvaluateOnLoad",
"(",
"self",
",",
"scriptSource",
")",
":",
"assert",
"isinstance",
"(",
"scriptSource",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'scriptSource' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"script... | Function path: Page.addScriptToEvaluateOnLoad
Domain: Page
Method name: addScriptToEvaluateOnLoad
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'scriptSource' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> Identifier of the added script.
Description: Deprecated, please use addScriptToEvaluateOnNewDocument instead. | [
"Function",
"path",
":",
"Page",
".",
"addScriptToEvaluateOnLoad",
"Domain",
":",
"Page",
"Method",
"name",
":",
"addScriptToEvaluateOnLoad",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"arguments",
":",
... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L169-L190 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Page_addScriptToEvaluateOnNewDocument | def Page_addScriptToEvaluateOnNewDocument(self, source):
"""
Function path: Page.addScriptToEvaluateOnNewDocument
Domain: Page
Method name: addScriptToEvaluateOnNewDocument
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'source' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> Identifier of the added script.
Description: Evaluates given script in every frame upon creation (before loading frame's scripts).
"""
assert isinstance(source, (str,)
), "Argument 'source' must be of type '['str']'. Received type: '%s'" % type(
source)
subdom_funcs = self.synchronous_command(
'Page.addScriptToEvaluateOnNewDocument', source=source)
return subdom_funcs | python | def Page_addScriptToEvaluateOnNewDocument(self, source):
"""
Function path: Page.addScriptToEvaluateOnNewDocument
Domain: Page
Method name: addScriptToEvaluateOnNewDocument
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'source' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> Identifier of the added script.
Description: Evaluates given script in every frame upon creation (before loading frame's scripts).
"""
assert isinstance(source, (str,)
), "Argument 'source' must be of type '['str']'. Received type: '%s'" % type(
source)
subdom_funcs = self.synchronous_command(
'Page.addScriptToEvaluateOnNewDocument', source=source)
return subdom_funcs | [
"def",
"Page_addScriptToEvaluateOnNewDocument",
"(",
"self",
",",
"source",
")",
":",
"assert",
"isinstance",
"(",
"source",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'source' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"source",
")",
... | Function path: Page.addScriptToEvaluateOnNewDocument
Domain: Page
Method name: addScriptToEvaluateOnNewDocument
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'source' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> Identifier of the added script.
Description: Evaluates given script in every frame upon creation (before loading frame's scripts). | [
"Function",
"path",
":",
"Page",
".",
"addScriptToEvaluateOnNewDocument",
"Domain",
":",
"Page",
"Method",
"name",
":",
"addScriptToEvaluateOnNewDocument",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"argumen... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L211-L232 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Page_setAutoAttachToCreatedPages | def Page_setAutoAttachToCreatedPages(self, autoAttach):
"""
Function path: Page.setAutoAttachToCreatedPages
Domain: Page
Method name: setAutoAttachToCreatedPages
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'autoAttach' (type: boolean) -> If true, browser will open a new inspector window for every page created from this one.
No return value.
Description: Controls whether browser will open a new inspector window for connected pages.
"""
assert isinstance(autoAttach, (bool,)
), "Argument 'autoAttach' must be of type '['bool']'. Received type: '%s'" % type(
autoAttach)
subdom_funcs = self.synchronous_command('Page.setAutoAttachToCreatedPages',
autoAttach=autoAttach)
return subdom_funcs | python | def Page_setAutoAttachToCreatedPages(self, autoAttach):
"""
Function path: Page.setAutoAttachToCreatedPages
Domain: Page
Method name: setAutoAttachToCreatedPages
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'autoAttach' (type: boolean) -> If true, browser will open a new inspector window for every page created from this one.
No return value.
Description: Controls whether browser will open a new inspector window for connected pages.
"""
assert isinstance(autoAttach, (bool,)
), "Argument 'autoAttach' must be of type '['bool']'. Received type: '%s'" % type(
autoAttach)
subdom_funcs = self.synchronous_command('Page.setAutoAttachToCreatedPages',
autoAttach=autoAttach)
return subdom_funcs | [
"def",
"Page_setAutoAttachToCreatedPages",
"(",
"self",
",",
"autoAttach",
")",
":",
"assert",
"isinstance",
"(",
"autoAttach",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'autoAttach' must be of type '['bool']'. Received type: '%s'\"",
"%",
"type",
"(",
"autoAtta... | Function path: Page.setAutoAttachToCreatedPages
Domain: Page
Method name: setAutoAttachToCreatedPages
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'autoAttach' (type: boolean) -> If true, browser will open a new inspector window for every page created from this one.
No return value.
Description: Controls whether browser will open a new inspector window for connected pages. | [
"Function",
"path",
":",
"Page",
".",
"setAutoAttachToCreatedPages",
"Domain",
":",
"Page",
"Method",
"name",
":",
"setAutoAttachToCreatedPages",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"arguments",
":"... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L253-L273 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Page_setAdBlockingEnabled | def Page_setAdBlockingEnabled(self, enabled):
"""
Function path: Page.setAdBlockingEnabled
Domain: Page
Method name: setAdBlockingEnabled
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'enabled' (type: boolean) -> Whether to block ads.
No return value.
Description: Enable Chrome's experimental ad filter on all sites.
"""
assert isinstance(enabled, (bool,)
), "Argument 'enabled' must be of type '['bool']'. Received type: '%s'" % type(
enabled)
subdom_funcs = self.synchronous_command('Page.setAdBlockingEnabled',
enabled=enabled)
return subdom_funcs | python | def Page_setAdBlockingEnabled(self, enabled):
"""
Function path: Page.setAdBlockingEnabled
Domain: Page
Method name: setAdBlockingEnabled
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'enabled' (type: boolean) -> Whether to block ads.
No return value.
Description: Enable Chrome's experimental ad filter on all sites.
"""
assert isinstance(enabled, (bool,)
), "Argument 'enabled' must be of type '['bool']'. Received type: '%s'" % type(
enabled)
subdom_funcs = self.synchronous_command('Page.setAdBlockingEnabled',
enabled=enabled)
return subdom_funcs | [
"def",
"Page_setAdBlockingEnabled",
"(",
"self",
",",
"enabled",
")",
":",
"assert",
"isinstance",
"(",
"enabled",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'enabled' must be of type '['bool']'. Received type: '%s'\"",
"%",
"type",
"(",
"enabled",
")",
"subd... | Function path: Page.setAdBlockingEnabled
Domain: Page
Method name: setAdBlockingEnabled
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'enabled' (type: boolean) -> Whether to block ads.
No return value.
Description: Enable Chrome's experimental ad filter on all sites. | [
"Function",
"path",
":",
"Page",
".",
"setAdBlockingEnabled",
"Domain",
":",
"Page",
"Method",
"name",
":",
"setAdBlockingEnabled",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"arguments",
":",
"enabled",... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L304-L324 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Page_navigateToHistoryEntry | def Page_navigateToHistoryEntry(self, entryId):
"""
Function path: Page.navigateToHistoryEntry
Domain: Page
Method name: navigateToHistoryEntry
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'entryId' (type: integer) -> Unique id of the entry to navigate to.
No return value.
Description: Navigates current page to the given history entry.
"""
assert isinstance(entryId, (int,)
), "Argument 'entryId' must be of type '['int']'. Received type: '%s'" % type(
entryId)
subdom_funcs = self.synchronous_command('Page.navigateToHistoryEntry',
entryId=entryId)
return subdom_funcs | python | def Page_navigateToHistoryEntry(self, entryId):
"""
Function path: Page.navigateToHistoryEntry
Domain: Page
Method name: navigateToHistoryEntry
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'entryId' (type: integer) -> Unique id of the entry to navigate to.
No return value.
Description: Navigates current page to the given history entry.
"""
assert isinstance(entryId, (int,)
), "Argument 'entryId' must be of type '['int']'. Received type: '%s'" % type(
entryId)
subdom_funcs = self.synchronous_command('Page.navigateToHistoryEntry',
entryId=entryId)
return subdom_funcs | [
"def",
"Page_navigateToHistoryEntry",
"(",
"self",
",",
"entryId",
")",
":",
"assert",
"isinstance",
"(",
"entryId",
",",
"(",
"int",
",",
")",
")",
",",
"\"Argument 'entryId' must be of type '['int']'. Received type: '%s'\"",
"%",
"type",
"(",
"entryId",
")",
"subd... | Function path: Page.navigateToHistoryEntry
Domain: Page
Method name: navigateToHistoryEntry
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'entryId' (type: integer) -> Unique id of the entry to navigate to.
No return value.
Description: Navigates current page to the given history entry. | [
"Function",
"path",
":",
"Page",
".",
"navigateToHistoryEntry",
"Domain",
":",
"Page",
"Method",
"name",
":",
"navigateToHistoryEntry",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"arguments",
":",
"entry... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L389-L409 | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | ChromeRemoteDebugInterface.Page_deleteCookie | def Page_deleteCookie(self, cookieName, url):
"""
Function path: Page.deleteCookie
Domain: Page
Method name: deleteCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'cookieName' (type: string) -> Name of the cookie to remove.
'url' (type: string) -> URL to match cooke domain and path.
No return value.
Description: Deletes browser cookie with given name, domain and path.
"""
assert isinstance(cookieName, (str,)
), "Argument 'cookieName' must be of type '['str']'. Received type: '%s'" % type(
cookieName)
assert isinstance(url, (str,)
), "Argument 'url' must be of type '['str']'. Received type: '%s'" % type(
url)
subdom_funcs = self.synchronous_command('Page.deleteCookie', cookieName=
cookieName, url=url)
return subdom_funcs | python | def Page_deleteCookie(self, cookieName, url):
"""
Function path: Page.deleteCookie
Domain: Page
Method name: deleteCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'cookieName' (type: string) -> Name of the cookie to remove.
'url' (type: string) -> URL to match cooke domain and path.
No return value.
Description: Deletes browser cookie with given name, domain and path.
"""
assert isinstance(cookieName, (str,)
), "Argument 'cookieName' must be of type '['str']'. Received type: '%s'" % type(
cookieName)
assert isinstance(url, (str,)
), "Argument 'url' must be of type '['str']'. Received type: '%s'" % type(
url)
subdom_funcs = self.synchronous_command('Page.deleteCookie', cookieName=
cookieName, url=url)
return subdom_funcs | [
"def",
"Page_deleteCookie",
"(",
"self",
",",
"cookieName",
",",
"url",
")",
":",
"assert",
"isinstance",
"(",
"cookieName",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'cookieName' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"cookieNam... | Function path: Page.deleteCookie
Domain: Page
Method name: deleteCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'cookieName' (type: string) -> Name of the cookie to remove.
'url' (type: string) -> URL to match cooke domain and path.
No return value.
Description: Deletes browser cookie with given name, domain and path. | [
"Function",
"path",
":",
"Page",
".",
"deleteCookie",
"Domain",
":",
"Page",
"Method",
"name",
":",
"deleteCookie",
"WARNING",
":",
"This",
"function",
"is",
"marked",
"Experimental",
"!",
"Parameters",
":",
"Required",
"arguments",
":",
"cookieName",
"(",
"ty... | 914dd136184e8f1165c7aa6ef30418aaf10c61f0 | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L427-L451 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.