_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q228500 | mpl_color2xcolor | train | def mpl_color2xcolor(data, matplotlib_color):
"""Translates a matplotlib color specification into a proper LaTeX xcolor.
"""
# Convert it to RGBA.
my_col = numpy.array(mpl.colors.ColorConverter().to_rgba(matplotlib_color))
# If the alpha channel is exactly 0, then the color is really 'none'
# r... | python | {
"resource": ""
} |
q228501 | draw_patch | train | def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data,
obj,
obj.get_edgecolor(),
obj.get_facecolor(),
obj.get_linestyle(),
obj.get_linewidth(),
)
if is... | python | {
"resource": ""
} |
q228502 | _draw_rectangle | train | def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc). Even those without
# labels explicitly set have a label of "_nolegend_". Everything else should be
# skipped because they likely correspong t... | python | {
"resource": ""
} |
q228503 | _draw_ellipse | train | def _draw_ellipse(data, obj, draw_options):
"""Return the PGFPlots code for ellipses.
"""
if isinstance(obj, mpl.patches.Circle):
# circle specialization
return _draw_circle(data, obj, draw_options)
x, y = obj.center
ff = data["float format"]
if obj.angle != 0:
fmt = "ro... | python | {
"resource": ""
} |
q228504 | _draw_circle | train | def _draw_circle(data, obj, draw_options):
"""Return the PGFPlots code for circles.
"""
x, y = obj.center
ff = data["float format"]
cont = ("\\draw[{}] (axis cs:" + ff + "," + ff + ") circle (" + ff + ");\n").format(
",".join(draw_options), x, y, obj.get_radius()
)
return data, cont | python | {
"resource": ""
} |
q228505 | draw_image | train | def draw_image(data, obj):
"""Returns the PGFPlots code for an image environment.
"""
content = []
filename, rel_filepath = files.new_filename(data, "img", ".png")
# store the image as in a file
img_array = obj.get_array()
dims = img_array.shape
if len(dims) == 2: # the values are gi... | python | {
"resource": ""
} |
q228506 | get_legend_text | train | def get_legend_text(obj):
"""Check if line is in legend.
"""
leg = obj.axes.get_legend()
if leg is None:
return None
keys = [l.get_label() for l in leg.legendHandles if l is not None]
values = [l.get_text() for l in leg.texts]
label = obj.get_label()
d = dict(zip(keys, values))... | python | {
"resource": ""
} |
q228507 | _get_color_definitions | train | def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb... | python | {
"resource": ""
} |
q228508 | _print_pgfplot_libs_message | train | def _print_pgfplot_libs_message(data):
"""Prints message to screen indicating the use of PGFPlots and its
libraries."""
pgfplotslibs = ",".join(list(data["pgfplots libs"]))
tikzlibs = ",".join(list(data["tikz libs"]))
print(70 * "=")
print("Please add the following lines to your LaTeX preamble:... | python | {
"resource": ""
} |
q228509 | _ContentManager.extend | train | def extend(self, content, zorder):
""" Extends with a list and a z-order
"""
if zorder not in self._content:
self._content[zorder] = []
self._content[zorder].extend(content) | python | {
"resource": ""
} |
q228510 | draw_line2d | train | def draw_line2d(data, obj):
"""Returns the PGFPlots code for an Line2D environment.
"""
content = []
addplot_options = []
# If line is of length 0, do nothing. Otherwise, an empty \addplot table will be
# created, which will be interpreted as an external data source in either the file
# ''... | python | {
"resource": ""
} |
q228511 | draw_linecollection | train | def draw_linecollection(data, obj):
"""Returns Pgfplots code for a number of patch objects.
"""
content = []
edgecolors = obj.get_edgecolors()
linestyles = obj.get_linestyles()
linewidths = obj.get_linewidths()
paths = obj.get_paths()
for i, path in enumerate(paths):
color = ed... | python | {
"resource": ""
} |
q228512 | _mpl_marker2pgfp_marker | train | def _mpl_marker2pgfp_marker(data, mpl_marker, marker_face_color):
"""Translates a marker style of matplotlib to the corresponding style
in PGFPlots.
"""
# try default list
try:
pgfplots_marker = _MP_MARKER2PGF_MARKER[mpl_marker]
except KeyError:
pass
else:
if (marker_... | python | {
"resource": ""
} |
q228513 | draw_text | train | def draw_text(data, obj):
"""Paints text on the graph.
"""
content = []
properties = []
style = []
if isinstance(obj, mpl.text.Annotation):
_annotation(obj, data, content)
# 1: coordinates
# 2: properties (shapes, rotation, etc)
# 3: text style
# 4: the text
# ... | python | {
"resource": ""
} |
q228514 | _transform_positioning | train | def _transform_positioning(ha, va):
"""Converts matplotlib positioning to pgf node positioning.
Not quite accurate but the results are equivalent more or less."""
if ha == "center" and va == "center":
return None
ha_mpl_to_tikz = {"right": "east", "left": "west", "center": ""}
va_mpl_to_tik... | python | {
"resource": ""
} |
q228515 | import_from_json | train | def import_from_json(filename_or_fobj, encoding="utf-8", *args, **kwargs):
"""Import a JSON file or file-like object into a `rows.Table`.
If a file-like object is provided it MUST be open in text (non-binary) mode
on Python 3 and could be open in both binary or text mode on Python 2.
"""
source = ... | python | {
"resource": ""
} |
q228516 | export_to_json | train | def export_to_json(
table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs
):
"""Export a `rows.Table` to a JSON file or file-like object.
If a file-like object is provided it MUST be open in binary mode (like in
`open('myfile.json', mode='wb')`).
"""
# TODO: will work onl... | python | {
"resource": ""
} |
q228517 | plugin_name_by_uri | train | def plugin_name_by_uri(uri):
"Return the plugin name based on the URI"
# TODO: parse URIs like 'sqlite://' also
parsed = urlparse(uri)
basename = os.path.basename(parsed.path)
if not basename.strip():
raise RuntimeError("Could not identify file format.")
plugin_name = basename.split("... | python | {
"resource": ""
} |
q228518 | extension_by_source | train | def extension_by_source(source, mime_type):
"Return the file extension used by this plugin"
# TODO: should get this information from the plugin
extension = source.plugin_name
if extension:
return extension
if mime_type:
return mime_type.split("/")[-1] | python | {
"resource": ""
} |
q228519 | plugin_name_by_mime_type | train | def plugin_name_by_mime_type(mime_type, mime_name, file_extension):
"Return the plugin name based on the MIME type"
return MIME_TYPE_TO_PLUGIN_NAME.get(
normalize_mime_type(mime_type, mime_name, file_extension), None
) | python | {
"resource": ""
} |
q228520 | detect_source | train | def detect_source(uri, verify_ssl, progress, timeout=5):
"""Return a `rows.Source` with information for a given URI
If URI starts with "http" or "https" the file will be downloaded.
This function should only be used if the URI already exists because it's
going to download/open the file to detect its e... | python | {
"resource": ""
} |
q228521 | import_from_source | train | def import_from_source(source, default_encoding, *args, **kwargs):
"Import data described in a `rows.Source` into a `rows.Table`"
# TODO: test open_compressed
plugin_name = source.plugin_name
kwargs["encoding"] = (
kwargs.get("encoding", None) or source.encoding or default_encoding
)
t... | python | {
"resource": ""
} |
q228522 | import_from_uri | train | def import_from_uri(
uri, default_encoding="utf-8", verify_ssl=True, progress=False, *args, **kwargs
):
"Given an URI, detects plugin and encoding and imports into a `rows.Table`"
# TODO: support '-' also
# TODO: (optimization) if `kwargs.get('encoding', None) is not None` we can
# skip encod... | python | {
"resource": ""
} |
q228523 | open_compressed | train | def open_compressed(filename, mode="r", encoding=None):
"Return a text-based file object from a filename, even if compressed"
# TODO: integrate this function in the library itself, using
# get_filename_and_fobj
binary_mode = "b" in mode
extension = str(filename).split(".")[-1].lower()
if binary... | python | {
"resource": ""
} |
q228524 | csv_to_sqlite | train | def csv_to_sqlite(
input_filename,
output_filename,
samples=None,
dialect=None,
batch_size=10000,
encoding="utf-8",
callback=None,
force_types=None,
chunk_size=8388608,
table_name="table1",
schema=None,
):
"Export a CSV file to SQLite, based on field type detection from s... | python | {
"resource": ""
} |
q228525 | sqlite_to_csv | train | def sqlite_to_csv(
input_filename,
table_name,
output_filename,
dialect=csv.excel,
batch_size=10000,
encoding="utf-8",
callback=None,
query=None,
):
"""Export a table inside a SQLite database to CSV"""
# TODO: should be able to specify fields
# TODO: should be able to specif... | python | {
"resource": ""
} |
q228526 | execute_command | train | def execute_command(command):
"""Execute a command and return its output"""
command = shlex.split(command)
try:
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFou... | python | {
"resource": ""
} |
q228527 | uncompressed_size | train | def uncompressed_size(filename):
"""Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value.
"""
quoted_filename = shlex.quote(filename)
# TODO: get filetype from file-magic, if avail... | python | {
"resource": ""
} |
q228528 | pgimport | train | def pgimport(
filename,
database_uri,
table_name,
encoding="utf-8",
dialect=None,
create_table=True,
schema=None,
callback=None,
timeout=0.1,
chunk_size=8388608,
max_samples=10000,
):
"""Import data from CSV into PostgreSQL using the fastest method
Required: psql com... | python | {
"resource": ""
} |
q228529 | pgexport | train | def pgexport(
database_uri,
table_name,
filename,
encoding="utf-8",
dialect=csv.excel,
callback=None,
timeout=0.1,
chunk_size=8388608,
):
"""Export data from PostgreSQL into a CSV file using the fastest method
Required: psql command
"""
if isinstance(dialect, six.text_t... | python | {
"resource": ""
} |
q228530 | load_schema | train | def load_schema(filename, context=None):
"""Load schema from file in any of the supported formats
The table must have at least the fields `field_name` and `field_type`.
`context` is a `dict` with field_type as key pointing to field class, like:
{"text": rows.fields.TextField, "value": MyCustomField... | python | {
"resource": ""
} |
q228531 | slug | train | def slug(text, separator="_", permitted_chars=SLUG_CHARS):
"""Generate a slug for the `text`.
>>> slug(' ÁLVARO justen% ')
'alvaro_justen'
>>> slug(' ÁLVARO justen% ', separator='-')
'alvaro-justen'
"""
text = six.text_type(text or "")
# Strip non-ASCII characters
# Example: u' ... | python | {
"resource": ""
} |
q228532 | make_unique_name | train | def make_unique_name(name, existing_names, name_format="{name}_{index}", start=2):
"""Return a unique name based on `name_format` and `name`."""
index = start
new_name = name
while new_name in existing_names:
new_name = name_format.format(name=name, index=index)
index += 1
return ne... | python | {
"resource": ""
} |
q228533 | make_header | train | def make_header(field_names, permit_not=False):
"""Return unique and slugged field names."""
slug_chars = SLUG_CHARS if not permit_not else SLUG_CHARS + "^"
header = [
slug(field_name, permitted_chars=slug_chars) for field_name in field_names
]
result = []
for index, field_name in enume... | python | {
"resource": ""
} |
q228534 | Field.deserialize | train | def deserialize(cls, value, *args, **kwargs):
"""Deserialize a value just after importing it
`cls.deserialize` should always return a value of type `cls.TYPE` or
`None`.
"""
if isinstance(value, cls.TYPE):
return value
elif is_null(value):
return... | python | {
"resource": ""
} |
q228535 | ExtractionAlgorithm.selected_objects | train | def selected_objects(self):
"""Filter out objects outside table boundaries"""
return [
obj
for obj in self.text_objects
if contains_or_overlap(self.table_bbox, obj.bbox)
] | python | {
"resource": ""
} |
q228536 | transform | train | def transform(row, table):
'Extract links from "project" field and remove HTML from all'
data = row._asdict()
data["links"] = " ".join(extract_links(row.project))
for key, value in data.items():
if isinstance(value, six.text_type):
data[key] = extract_text(value)
return data | python | {
"resource": ""
} |
q228537 | transform | train | def transform(row, table):
'Transform row "link" into full URL and add "state" based on "name"'
data = row._asdict()
data["link"] = urljoin("https://pt.wikipedia.org", data["link"])
data["name"], data["state"] = regexp_city_state.findall(data["name"])[0]
return data | python | {
"resource": ""
} |
q228538 | import_from_parquet | train | def import_from_parquet(filename_or_fobj, *args, **kwargs):
"""Import data from a Parquet file and return with rows.Table."""
source = Source.from_file(filename_or_fobj, plugin_name="parquet", mode="rb")
# TODO: should look into `schema.converted_type` also
types = OrderedDict(
[
(s... | python | {
"resource": ""
} |
q228539 | import_from_dicts | train | def import_from_dicts(data, samples=None, *args, **kwargs):
"""Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
"""
data = iter(data)
cached_rows, headers = [], []
for in... | python | {
"resource": ""
} |
q228540 | export_to_dicts | train | def export_to_dicts(table, *args, **kwargs):
"""Export a `rows.Table` to a list of dicts"""
field_names = table.field_names
return [{key: getattr(row, key) for key in field_names} for row in table] | python | {
"resource": ""
} |
q228541 | cell_value | train | def cell_value(sheet, row, col):
"""Return the cell value of the table passed by argument, based in row and column."""
cell = sheet.cell(row, col)
field_type = CELL_TYPES[cell.ctype]
# TODO: this approach will not work if using locale
value = cell.value
if field_type is None:
return No... | python | {
"resource": ""
} |
q228542 | import_from_xls | train | def import_from_xls(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLS file."""
source = Source.from_file(filename_or_fobj, mode="rb", plugin... | python | {
"resource": ""
} |
q228543 | export_to_xls | train | def export_to_xls(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLS file and return the saved file."""
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(sheet_name)
prepared_table = prepare_to_export(table, *args, **kwargs)
field_names = next... | python | {
"resource": ""
} |
q228544 | _valid_table_name | train | def _valid_table_name(name):
"""Verify if a given table name is valid for `rows`
Rules:
- Should start with a letter or '_'
- Letters can be capitalized or not
- Accepts letters, numbers and _
"""
if name[0] not in "_" + string.ascii_letters or not set(name).issubset(
"_" + string.... | python | {
"resource": ""
} |
q228545 | _parse_col_positions | train | def _parse_col_positions(frame_style, header_line):
"""Find the position for each column separator in the given line
If frame_style is 'None', this won work
for column names that _start_ with whitespace
(which includes non-lefthand aligned column titles)
"""
separator = re.escape(FRAMES[frame_... | python | {
"resource": ""
} |
q228546 | import_from_txt | train | def import_from_txt(
filename_or_fobj, encoding="utf-8", frame_style=FRAME_SENTINEL, *args, **kwargs
):
"""Return a rows.Table created from imported TXT file."""
# TODO: (maybe)
# enable parsing of non-fixed-width-columns
# with old algorithm - that would just split columns
# at the vertical se... | python | {
"resource": ""
} |
q228547 | export_to_txt | train | def export_to_txt(
table,
filename_or_fobj=None,
encoding=None,
frame_style="ASCII",
safe_none_frame=True,
*args,
**kwargs
):
"""Export a `rows.Table` to text.
This function can return the result as a string or save into a file (via
filename or file-like object).
`encoding`... | python | {
"resource": ""
} |
q228548 | import_from_sqlite | train | def import_from_sqlite(
filename_or_connection,
table_name="table1",
query=None,
query_args=None,
*args,
**kwargs
):
"""Return a rows.Table with data from SQLite database."""
source = get_source(filename_or_connection)
connection = source.fobj
cursor = connection.cursor()
if... | python | {
"resource": ""
} |
q228549 | _cell_to_python | train | def _cell_to_python(cell):
"""Convert a PyOpenXL's `Cell` object to the corresponding Python object."""
data_type, value = cell.data_type, cell.value
if type(cell) is EmptyCell:
return None
elif data_type == "f" and value == "=TRUE()":
return True
elif data_type == "f" and value == ... | python | {
"resource": ""
} |
q228550 | import_from_xlsx | train | def import_from_xlsx(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
workbook_kwargs=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to op... | python | {
"resource": ""
} |
q228551 | export_to_xlsx | train | def export_to_xlsx(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLSX file and return the saved file."""
workbook = Workbook()
sheet = workbook.active
sheet.title = sheet_name
prepared_table = prepare_to_export(table, *args, **kwargs)
# Write ... | python | {
"resource": ""
} |
q228552 | download_organizations | train | def download_organizations():
"Download organizations JSON and extract its properties"
response = requests.get(URL)
data = response.json()
organizations = [organization["properties"] for organization in data["features"]]
return rows.import_from_dicts(organizations) | python | {
"resource": ""
} |
q228553 | import_from_html | train | def import_from_html(
filename_or_fobj,
encoding="utf-8",
index=0,
ignore_colspan=True,
preserve_html=False,
properties=False,
table_tag="table",
row_tag="tr",
column_tag="td|th",
*args,
**kwargs
):
"""Return rows.Table from HTML file."""
source = Source.from_file(
... | python | {
"resource": ""
} |
q228554 | export_to_html | train | def export_to_html(
table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
"""Export and return rows.Table data to HTML file."""
serialized_table = serialize(table, *args, **kwargs)
fields = next(serialized_table)
result = ["<table>\n\n"]
if caption and table.name:
... | python | {
"resource": ""
} |
q228555 | _extract_node_text | train | def _extract_node_text(node):
"""Extract text from a given lxml node."""
texts = map(
six.text_type.strip, map(six.text_type, map(unescape, node.xpath(".//text()")))
)
return " ".join(text for text in texts if text) | python | {
"resource": ""
} |
q228556 | count_tables | train | def count_tables(filename_or_fobj, encoding="utf-8", table_tag="table"):
"""Read a file passed by arg and return your table HTML tag count."""
source = Source.from_file(
filename_or_fobj, plugin_name="html", mode="rb", encoding=encoding
)
html = source.fobj.read().decode(source.encoding)
ht... | python | {
"resource": ""
} |
q228557 | tag_to_dict | train | def tag_to_dict(html):
"""Extract tag's attributes into a `dict`."""
element = document_fromstring(html).xpath("//html/body/child::*")[0]
attributes = dict(element.attrib)
attributes["text"] = element.text_content()
return attributes | python | {
"resource": ""
} |
q228558 | create_table | train | def create_table(
data,
meta=None,
fields=None,
skip_header=True,
import_fields=None,
samples=None,
force_types=None,
max_rows=None,
*args,
**kwargs
):
"""Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is se... | python | {
"resource": ""
} |
q228559 | export_data | train | def export_data(filename_or_fobj, data, mode="w"):
"""Return the object ready to be exported or only data if filename_or_fobj is not passed."""
if filename_or_fobj is None:
return data
_, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode)
source = Source.from_file(filename_or_fobj, mode... | python | {
"resource": ""
} |
q228560 | read_sample | train | def read_sample(fobj, sample):
"""Read `sample` bytes from `fobj` and return the cursor to where it was."""
cursor = fobj.tell()
data = fobj.read(sample)
fobj.seek(cursor)
return data | python | {
"resource": ""
} |
q228561 | export_to_csv | train | def export_to_csv(
table,
filename_or_fobj=None,
encoding="utf-8",
dialect=unicodecsv.excel,
batch_size=100,
callback=None,
*args,
**kwargs
):
"""Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='... | python | {
"resource": ""
} |
q228562 | join | train | def join(keys, tables):
"""Merge a list of `Table` objects using `keys` to group rows"""
# Make new (merged) Table fields
fields = OrderedDict()
for table in tables:
fields.update(table.fields)
# TODO: may raise an error if a same field is different in some tables
# Check if all keys a... | python | {
"resource": ""
} |
q228563 | transform | train | def transform(fields, function, *tables):
"Return a new table based on other tables and a transformation function"
new_table = Table(fields=fields)
for table in tables:
for row in filter(bool, map(lambda row: function(row, table), table)):
new_table.append(row)
return new_table | python | {
"resource": ""
} |
q228564 | make_pvc | train | def make_pvc(
name,
storage_class,
access_modes,
storage,
labels=None,
annotations=None,
):
"""
Make a k8s pvc specification for running a user notebook.
Parameters
----------
name:
Name of persistent volume claim. Must be unique within the namespace the object is
... | python | {
"resource": ""
} |
q228565 | make_ingress | train | def make_ingress(
name,
routespec,
target,
data
):
"""
Returns an ingress, service, endpoint object that'll work for this service
"""
# move beta imports here,
# which are more sensitive to kubernetes version
# and will change when they move out of beta
from ... | python | {
"resource": ""
} |
q228566 | shared_client | train | def shared_client(ClientType, *args, **kwargs):
"""Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
"""
kwarg_key = tuple(... | python | {
"resource": ""
} |
q228567 | generate_hashed_slug | train | def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility about what the o... | python | {
"resource": ""
} |
q228568 | get_k8s_model | train | def get_k8s_model(model_type, model_dict):
"""
Returns an instance of type specified model_type from an model instance or
represantative dictionary.
"""
model_dict = copy.deepcopy(model_dict)
if isinstance(model_dict, model_type):
return model_dict
elif isinstance(model_dict, dict):... | python | {
"resource": ""
} |
q228569 | _get_k8s_model_dict | train | def _get_k8s_model_dict(model_type, model):
"""
Returns a dictionary representation of a provided model type
"""
model = copy.deepcopy(model)
if isinstance(model, model_type):
return model.to_dict()
elif isinstance(model, dict):
return _map_dict_keys_to_model_attributes(model_ty... | python | {
"resource": ""
} |
q228570 | NamespacedResourceReflector._list_and_update | train | def _list_and_update(self):
"""
Update current list of resources by doing a full fetch.
Overwrites all current resource info.
"""
initial_resources = getattr(self.api, self.list_method_name)(
self.namespace,
label_selector=self.label_selector,
... | python | {
"resource": ""
} |
q228571 | NamespacedResourceReflector._watch_and_update | train | def _watch_and_update(self):
"""
Keeps the current list of resources up-to-date
This method is to be run not on the main thread!
We first fetch the list of current resources, and store that. Then we
register to be notified of changes to those resources, and keep our
loc... | python | {
"resource": ""
} |
q228572 | NamespacedResourceReflector.start | train | def start(self):
"""
Start the reflection process!
We'll do a blocking read of all resources first, so that we don't
race with any operations that are checking the state of the pod
store - such as polls. This should be called only once at the
start of program initializat... | python | {
"resource": ""
} |
q228573 | KubeSpawner.get_pod_manifest | train | def get_pod_manifest(self):
"""
Make a pod manifest that will spawn current user's notebook pod.
"""
if callable(self.uid):
uid = yield gen.maybe_future(self.uid(self))
else:
uid = self.uid
if callable(self.gid):
gid = yield gen.maybe_... | python | {
"resource": ""
} |
q228574 | KubeSpawner.get_pvc_manifest | train | def get_pvc_manifest(self):
"""
Make a pvc manifest that will spawn current user's pvc.
"""
labels = self._build_common_labels(self._expand_all(self.storage_extra_labels))
labels.update({
'component': 'singleuser-storage'
})
annotations = self._build_... | python | {
"resource": ""
} |
q228575 | KubeSpawner.is_pod_running | train | def is_pod_running(self, pod):
"""
Check if the given pod is running
pod must be a dictionary representing a Pod kubernetes API object.
"""
# FIXME: Validate if this is really the best way
is_running = (
pod is not None and
pod.status.phase == 'Ru... | python | {
"resource": ""
} |
q228576 | KubeSpawner.get_env | train | def get_env(self):
"""Return the environment dict to use for the Spawner.
See also: jupyterhub.Spawner.get_env
"""
env = super(KubeSpawner, self).get_env()
# deprecate image
env['JUPYTER_IMAGE_SPEC'] = self.image
env['JUPYTER_IMAGE'] = self.image
return... | python | {
"resource": ""
} |
q228577 | KubeSpawner.poll | train | def poll(self):
"""
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These ... | python | {
"resource": ""
} |
q228578 | KubeSpawner.events | train | def events(self):
"""Filter event-reflector to just our events
Returns list of all events that match our pod_name
since our ._last_event (if defined).
._last_event is set at the beginning of .start().
"""
if not self.event_reflector:
return []
events... | python | {
"resource": ""
} |
q228579 | KubeSpawner._start_reflector | train | def _start_reflector(self, key, ReflectorClass, replace=False, **kwargs):
"""Start a shared reflector on the KubeSpawner class
key: key for the reflector (e.g. 'pod' or 'events')
Reflector: Reflector class to be instantiated
kwargs: extra keyword-args to be relayed to ReflectorClass
... | python | {
"resource": ""
} |
q228580 | KubeSpawner._start_watching_events | train | def _start_watching_events(self, replace=False):
"""Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors).
... | python | {
"resource": ""
} |
q228581 | KubeSpawner._options_form_default | train | def _options_form_default(self):
'''
Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined.
'''
if not self.profile_list:
... | python | {
"resource": ""
} |
q228582 | KubeSpawner.options_from_form | train | def options_from_form(self, formdata):
"""get the option selected by the user on the form
This only constructs the user_options dict,
it should not actually load any options.
That is done later in `.load_user_options()`
Args:
formdata: user selection returned by the... | python | {
"resource": ""
} |
q228583 | KubeSpawner._load_profile | train | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | python | {
"resource": ""
} |
q228584 | KubeSpawner.load_user_options | train | def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None... | python | {
"resource": ""
} |
q228585 | list_motors | train | def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... | python | {
"resource": ""
} |
q228586 | SpeedRPS.to_native_units | train | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired rotations-per-second
"""
assert abs(self.rotations_per_second) <= motor.max_rps,\
"invalid rotations-per-second: {} max RPS is {}, {} was requested".format(
motor... | python | {
"resource": ""
} |
q228587 | SpeedRPM.to_native_units | train | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired rotations-per-minute
"""
assert abs(self.rotations_per_minute) <= motor.max_rpm,\
"invalid rotations-per-minute: {} max RPM is {}, {} was requested".format(
motor... | python | {
"resource": ""
} |
q228588 | SpeedDPS.to_native_units | train | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired degrees-per-second
"""
assert abs(self.degrees_per_second) <= motor.max_dps,\
"invalid degrees-per-second: {} max DPS is {}, {} was requested".format(
motor, moto... | python | {
"resource": ""
} |
q228589 | SpeedDPM.to_native_units | train | def to_native_units(self, motor):
"""
Return the native speed measurement required to achieve desired degrees-per-minute
"""
assert abs(self.degrees_per_minute) <= motor.max_dpm,\
"invalid degrees-per-minute: {} max DPM is {}, {} was requested".format(
motor, moto... | python | {
"resource": ""
} |
q228590 | Motor.address | train | def address(self):
"""
Returns the name of the port that this motor is connected to.
"""
self._address, value = self.get_attr_string(self._address, 'address')
return value | python | {
"resource": ""
} |
q228591 | Motor.commands | train | def commands(self):
"""
Returns a list of commands that are supported by the motor
controller. Possible values are `run-forever`, `run-to-abs-pos`, `run-to-rel-pos`,
`run-timed`, `run-direct`, `stop` and `reset`. Not all commands may be supported.
- `run-forever` will cause the ... | python | {
"resource": ""
} |
q228592 | Motor.driver_name | train | def driver_name(self):
"""
Returns the name of the driver that provides this tacho motor device.
"""
(self._driver_name, value) = self.get_cached_attr_string(self._driver_name, 'driver_name')
return value | python | {
"resource": ""
} |
q228593 | Motor.duty_cycle | train | def duty_cycle(self):
"""
Returns the current duty cycle of the motor. Units are percent. Values
are -100 to 100.
"""
self._duty_cycle, value = self.get_attr_int(self._duty_cycle, 'duty_cycle')
return value | python | {
"resource": ""
} |
q228594 | Motor.duty_cycle_sp | train | def duty_cycle_sp(self):
"""
Writing sets the duty cycle setpoint. Reading returns the current value.
Units are in percent. Valid values are -100 to 100. A negative value causes
the motor to rotate in reverse.
"""
self._duty_cycle_sp, value = self.get_attr_int(self._duty_... | python | {
"resource": ""
} |
q228595 | Motor.polarity | train | def polarity(self):
"""
Sets the polarity of the motor. With `normal` polarity, a positive duty
cycle will cause the motor to rotate clockwise. With `inversed` polarity,
a positive duty cycle will cause the motor to rotate counter-clockwise.
Valid values are `normal` and `inverse... | python | {
"resource": ""
} |
q228596 | Motor.position | train | def position(self):
"""
Returns the current position of the motor in pulses of the rotary
encoder. When the motor rotates clockwise, the position will increase.
Likewise, rotating counter-clockwise causes the position to decrease.
Writing will set the position to that value.
... | python | {
"resource": ""
} |
q228597 | Motor.position_p | train | def position_p(self):
"""
The proportional constant for the position PID.
"""
self._position_p, value = self.get_attr_int(self._position_p, 'hold_pid/Kp')
return value | python | {
"resource": ""
} |
q228598 | Motor.position_i | train | def position_i(self):
"""
The integral constant for the position PID.
"""
self._position_i, value = self.get_attr_int(self._position_i, 'hold_pid/Ki')
return value | python | {
"resource": ""
} |
q228599 | Motor.position_d | train | def position_d(self):
"""
The derivative constant for the position PID.
"""
self._position_d, value = self.get_attr_int(self._position_d, 'hold_pid/Kd')
return value | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.