INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Uses ip to return a dictionary of interfaces with various information about
each (up/down state, ip address, netmask, and hwaddr) | def _interfaces_ip(out):
"""
Uses ip to return a dictionary of interfaces with various information about
each (up/down state, ip address, netmask, and hwaddr)
"""
ret = dict()
def parse_network(value, cols):
"""
Return a tuple of ip, netmask, broadcast
based on the curre... |
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr) | def _interfaces_ifconfig(out):
"""
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
"""
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]... |
From a Shaman URL, get the chacra url for a repository, read the
contents that point to the repo and return it as a string. | def get_chacra_repo(shaman_url):
"""
From a Shaman URL, get the chacra url for a repository, read the
contents that point to the repo and return it as a string.
"""
shaman_response = get_request(shaman_url)
chacra_url = shaman_response.geturl()
chacra_response = get_request(chacra_url)
... |
Returns a list of packages to install based on component names
This is done by checking if a component is in notsplit_packages,
if it is, we know we need to install 'ceph' instead of the
raw component name. Essentially, this component hasn't been
'split' from the master 'ceph' package yet. | def map_components(notsplit_packages, components):
"""
Returns a list of packages to install based on component names
This is done by checking if a component is in notsplit_packages,
if it is, we know we need to install 'ceph' instead of the
raw component name. Essentially, this component hasn't b... |
start mon service depending on distro init | def start_mon_service(distro, cluster, hostname):
"""
start mon service depending on distro init
"""
if distro.init == 'sysvinit':
service = distro.conn.remote_module.which_service()
remoto.process.run(
distro.conn,
[
service,
'ceph... |
Reconstruct infinite voronoi regions in a 2D diagram to finite
regions.
Parameters
----------
vor : Voronoi
Input diagram
radius : float, optional
Distance to 'points at infinity'.
Returns
-------
regions : list of tuples
... | def __voronoi_finite_polygons_2d(vor, radius=None):
"""
Reconstruct infinite voronoi regions in a 2D diagram to finite
regions.
Parameters
----------
vor : Voronoi
Input diagram
radius : float, optional
Distance to 'points at infinity'.
... |
display the map inline in ipython
:param width: image width for the browser | def inline(width=900):
"""display the map inline in ipython
:param width: image width for the browser
"""
from IPython.display import Image, HTML, display, clear_output
import random
import string
import urllib
import os
while True:
fname = ''.join(random.choice(string.asci... |
Create a dot density map
:param data: data access object
:param color: color
:param point_size: point size
:param f_tooltip: function to return a tooltip string for a point | def dot(data, color=None, point_size=2, f_tooltip=None):
"""Create a dot density map
:param data: data access object
:param color: color
:param point_size: point size
:param f_tooltip: function to return a tooltip string for a point
"""
from geoplotlib.layers import DotDensityLayer
_glo... |
Deprecated: use dot | def scatter(data, color=None, point_size=2, f_tooltip=None):
"""Deprecated: use dot
"""
import warnings
warnings.warn("deprecated, use geoplotlib.dot", DeprecationWarning)
dot(data, color, point_size, f_tooltip) |
Create a 2D histogram
:param data: data access object
:param cmap: colormap name
:param alpha: color alpha
:param colorscale: scaling [lin, log, sqrt]
:param binsize: size of the hist bins
:param show_tooltip: if True, will show the value of bins on mouseover
:param scalemin: min value for ... | def hist(data, cmap='hot', alpha=220, colorscale='sqrt', binsize=16, show_tooltip=False,
scalemin=0, scalemax=None, f_group=None, show_colorbar=True):
"""Create a 2D histogram
:param data: data access object
:param cmap: colormap name
:param alpha: color alpha
:param colorscale: scaling [l... |
Create a graph drawing a line between each pair of (src_lat, src_lon) and (dest_lat, dest_lon)
:param data: data access object
:param src_lat: field name of source latitude
:param src_lon: field name of source longitude
:param dest_lat: field name of destination latitude
:param dest_lon: field name... | def graph(data, src_lat, src_lon, dest_lat, dest_lon, linewidth=1, alpha=220, color='hot'):
"""Create a graph drawing a line between each pair of (src_lat, src_lon) and (dest_lat, dest_lon)
:param data: data access object
:param src_lat: field name of source latitude
:param src_lon: field name of sourc... |
Load and draws shapefiles
:param fname: full path to the shapefile
:param f_tooltip: function to generate a tooltip on mouseover
:param color: color
:param linewidth: line width
:param shape_type: either full or bbox | def shapefiles(fname, f_tooltip=None, color=None, linewidth=3, shape_type='full'):
"""
Load and draws shapefiles
:param fname: full path to the shapefile
:param f_tooltip: function to generate a tooltip on mouseover
:param color: color
:param linewidth: line width
:param shape_type: either ... |
Draw the voronoi tesselation of the points
:param data: data access object
:param line_color: line color
:param line_width: line width
:param f_tooltip: function to generate a tooltip on mouseover
:param cmap: color map
:param max_area: scaling constant to determine the color of the voronoi are... | def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220):
"""
Draw the voronoi tesselation of the points
:param data: data access object
:param line_color: line color
:param line_width: line width
:param f_tooltip: function to generate a tooltip on mo... |
Draw a delaunay triangulation of the points
:param data: data access object
:param line_color: line color
:param line_width: line width
:param cmap: color map
:param max_lenght: scaling constant for coloring the edges | def delaunay(data, line_color=None, line_width=2, cmap=None, max_lenght=100):
"""
Draw a delaunay triangulation of the points
:param data: data access object
:param line_color: line color
:param line_width: line width
:param cmap: color map
:param max_lenght: scaling constant for coloring t... |
Convex hull for a set of points
:param data: points
:param col: color
:param fill: whether to fill the convexhull polygon or not
:param point_size: size of the points on the convexhull. Points are not rendered if None | def convexhull(data, col, fill=True, point_size=4):
"""
Convex hull for a set of points
:param data: points
:param col: color
:param fill: whether to fill the convexhull polygon or not
:param point_size: size of the points on the convexhull. Points are not rendered if None
"""
from geop... |
Kernel density estimation visualization
:param data: data access object
:param bw: kernel bandwidth (in screen coordinates)
:param cmap: colormap
:param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation.
If hist, estimates density appl... | def kde(data, bw, cmap='hot', method='hist', scaling='sqrt', alpha=220,
cut_below=None, clip_above=None, binsize=1, cmap_levels=10, show_colorbar=False):
"""
Kernel density estimation visualization
:param data: data access object
:param bw: kernel bandwidth (in screen coordinates)
... |
Draw markers
:param data: data access object
:param marker: full filename of the marker image
:param f_tooltip: function to generate a tooltip on mouseover
:param marker_preferred_size: size in pixel for the marker images | def markers(data, marker, f_tooltip=None, marker_preferred_size=32):
"""
Draw markers
:param data: data access object
:param marker: full filename of the marker image
:param f_tooltip: function to generate a tooltip on mouseover
:param marker_preferred_size: size in pixel for the marker images
... |
Draw features described in geojson format (http://geojson.org/)
:param filename: filename of the geojson file
:param color: color for the shapes. If callable, it will be invoked for each feature, passing the properties element
:param linewidth: line width
:param fill: if fill=True the feature polygon i... | def geojson(filename, color='b', linewidth=1, fill=False, f_tooltip=None):
"""
Draw features described in geojson format (http://geojson.org/)
:param filename: filename of the geojson file
:param color: color for the shapes. If callable, it will be invoked for each feature, passing the properties eleme... |
Draw a text label for each sample
:param data: data access object
:param label_column: column in the data access object where the labels text is stored
:param color: color
:param font_name: font name
:param font_size: font size
:param anchor_x: anchor x
:param anchor_y: anchor y | def labels(data, label_column, color=None, font_name=FONT_NAME,
font_size=14, anchor_x='left', anchor_y='top'):
"""
Draw a text label for each sample
:param data: data access object
:param label_column: column in the data access object where the labels text is stored
:param color: color... |
Values on a uniform grid
:param lon_edges: longitude edges
:param lat_edges: latitude edges
:param values: matrix representing values on the grid
:param cmap: colormap name
:param alpha: color alpha
:param vmin: minimum value for the colormap
:param vmax... | def grid(lon_edges, lat_edges, values, cmap, alpha=255, vmin=None, vmax=None, levels=10, colormap_scale='lin', show_colorbar=True):
"""
Values on a uniform grid
:param lon_edges: longitude edges
:param lat_edges: latitude edges
:param values: matrix representing values on th... |
Alpha color of the map tiles
:param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness | def set_map_alpha(alpha):
"""
Alpha color of the map tiles
:param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness
"""
if alpha < 0 or alpha > 255:
raise Exception('invalid alpha ' + str(alpha))
_global_config.map_alpha = alpha |
Distance between geodesic coordinates http://www.movable-type.co.uk/scripts/latlong.html
:param lon1: point 1 latitude
:param lat1: point 1 longitude
:param lon2: point 1 latitude
:param lat2: point 2 longitude
:return: distance in meters between points 1 and 2 | def haversine(lon1, lat1, lon2, lat2):
"""
Distance between geodesic coordinates http://www.movable-type.co.uk/scripts/latlong.html
:param lon1: point 1 latitude
:param lat1: point 1 longitude
:param lon2: point 1 latitude
:param lat2: point 2 longitude
:return: distance in meters between p... |
Read a csv file into a DataAccessObject
:param fname: filename | def read_csv(fname):
"""
Read a csv file into a DataAccessObject
:param fname: filename
"""
values = defaultdict(list)
with open(fname) as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
values[k].append(v)
npvalues = {k... |
Rename fields
:param mapping: a dict in the format {'oldkey1': 'newkey1', ...} | def rename(self, mapping):
"""
Rename fields
:param mapping: a dict in the format {'oldkey1': 'newkey1', ...}
"""
for old_key, new_key in mapping:
self.dict[new_key] = self.dict[old_key]
del self.dict[old_key] |
:param mask: boolean mask
:return: a DataAccessObject with a subset of rows matching mask | def where(self, mask):
"""
:param mask: boolean mask
:return: a DataAccessObject with a subset of rows matching mask
"""
assert len(mask) == len(self)
return DataAccessObject({k: self.dict[k][mask] for k in self.dict}) |
Return a DataAccessObject containing the first n rows
:param n: number of rows
:return: DataAccessObject | def head(self, n):
"""
Return a DataAccessObject containing the first n rows
:param n: number of rows
:return: DataAccessObject
"""
return DataAccessObject({k: self.dict[k][:n] for k in self.dict}) |
Compute the BoundingBox from a set of latitudes and longitudes
:param lons: longitudes
:param lats: latitudes
:return: BoundingBox | def from_points(lons, lats):
"""
Compute the BoundingBox from a set of latitudes and longitudes
:param lons: longitudes
:param lats: latitudes
:return: BoundingBox
"""
north, west = max(lats), min(lons)
south, east = min(lats), max(lons)
return Bo... |
Compute a BoundingBox enclosing all specified bboxes
:param bboxes: a list of BoundingBoxes
:return: BoundingBox | def from_bboxes(bboxes):
"""
Compute a BoundingBox enclosing all specified bboxes
:param bboxes: a list of BoundingBoxes
:return: BoundingBox
"""
north = max([b.north for b in bboxes])
south = min([b.south for b in bboxes])
west = min([b.west for b in bbo... |
return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values | def create_set_cmap(values, cmap_name, alpha=255):
"""
return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values
"""
unique_values... |
Return a dict of colors for the unique values.
Colors are adapted from Harrower, Mark, and Cynthia A. Brewer.
"ColorBrewer. org: an online tool for selecting colour schemes for maps."
The Cartographic Journal 40.1 (2003): 27-37.
:param values: values
:param alpha: color alphs
:return: dict of c... | def colorbrewer(values, alpha=255):
"""
Return a dict of colors for the unique values.
Colors are adapted from Harrower, Mark, and Cynthia A. Brewer.
"ColorBrewer. org: an online tool for selecting colour schemes for maps."
The Cartographic Journal 40.1 (2003): 27-37.
:param values: values
... |
convert continuous values into colors using matplotlib colorscales
:param value: value to be converted
:param maxvalue: max value in the colorscale
:param scale: lin, log, sqrt
:param minvalue: minimum of the input values in linear scale (default is 0)
:return: the color correspo... | def to_color(self, value, maxvalue, scale, minvalue=0.0):
"""
convert continuous values into colors using matplotlib colorscales
:param value: value to be converted
:param maxvalue: max value in the colorscale
:param scale: lin, log, sqrt
:param minvalue: minimum of the i... |
catmullrom spline
http://www.mvps.org/directx/articles/catmull/ | def __generate_spline(self, x, y, closed=False, steps=20):
"""
catmullrom spline
http://www.mvps.org/directx/articles/catmull/
"""
if closed:
x = x.tolist()
x.insert(0, x[-1])
x.append(x[1])
x.append(x[2])
y = y.tolist... |
Fits the projector to a BoundingBox
:param bbox: BoundingBox
:param max_zoom: max zoom allowed
:param force_zoom: force this specific zoom value even if the whole bbox does not completely fit | def fit(self, bbox, max_zoom=MAX_ZOOM, force_zoom=None):
"""
Fits the projector to a BoundingBox
:param bbox: BoundingBox
:param max_zoom: max zoom allowed
:param force_zoom: force this specific zoom value even if the whole bbox does not completely fit
"""
BUFFER... |
Projects geodesic coordinates to screen
:param lon: longitude
:param lat: latitude
:return: x,y screen coordinates | def lonlat_to_screen(self, lon, lat):
"""
Projects geodesic coordinates to screen
:param lon: longitude
:param lat: latitude
:return: x,y screen coordinates
"""
if type(lon) == list:
lon = np.array(lon)
if type(lat) == list:
lat = n... |
Return the latitude and longitude corresponding to a screen point
:param x: screen x
:param y: screen y
:return: latitude and longitude at x,y | def screen_to_latlon(self, x, y):
"""
Return the latitude and longitude corresponding to a screen point
:param x: screen x
:param y: screen y
:return: latitude and longitude at x,y
"""
xtile = 1. * x / TILE_SIZE + self.xtile
ytile = 1. * y / TILE_SIZE + se... |
Get possible completions for modulename for pydoc.
Returns a list of possible values to be passed to pydoc. | def get_pydoc_completions(modulename):
"""Get possible completions for modulename for pydoc.
Returns a list of possible values to be passed to pydoc.
"""
modulename = compat.ensure_not_unicode(modulename)
modulename = modulename.rstrip(".")
if modulename == "":
return sorted(get_module... |
Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages. | def get_modules(modulename=None):
"""Return a list of modules and packages under modulename.
If modulename is not given, return a list of all top level modules
and packages.
"""
modulename = compat.ensure_not_unicode(modulename)
if not modulename:
try:
return ([modname for ... |
Read a single line and decode it as JSON.
Can raise an EOFError() when the input source was closed. | def read_json(self):
"""Read a single line and decode it as JSON.
Can raise an EOFError() when the input source was closed.
"""
line = self.stdin.readline()
if line == '':
raise EOFError()
return json.loads(line) |
Write an JSON object on a single line.
The keyword arguments are interpreted as a single JSON object.
It's not possible with this method to write non-objects. | def write_json(self, **kwargs):
"""Write an JSON object on a single line.
The keyword arguments are interpreted as a single JSON object.
It's not possible with this method to write non-objects.
"""
self.stdout.write(json.dumps(kwargs) + "\n")
self.stdout.flush() |
Handle a single JSON-RPC request.
Read a request, call the appropriate handler method, and
return the encoded result. Errors in the handler method are
caught and encoded as error objects. Errors in the decoding
phase are not caught, as we can not respond with an error
response t... | def handle_request(self):
"""Handle a single JSON-RPC request.
Read a request, call the appropriate handler method, and
return the encoded result. Errors in the handler method are
caught and encoded as error objects. Errors in the decoding
phase are not caught, as we can not res... |
Formats Python code to conform to the PEP 8 style guide. | def fix_code(code, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
if not autopep8:
raise Fault('autopep8 not installed, cannot fix code.',
code=400)
old_dir = os.getcwd()
try:
os.chdir(directory)
return autopep8.fix_code(code,... |
Translate fileobj into file contents.
fileobj is either a string or a dict. If it's a string, that's the
file contents. If it's a string, then the filename key contains
the name of the file whose contents we are to use.
If the dict contains a true value for the key delete_after_use,
the file shoul... | def get_source(fileobj):
"""Translate fileobj into file contents.
fileobj is either a string or a dict. If it's a string, that's the
file contents. If it's a string, then the filename key contains
the name of the file whose contents we are to use.
If the dict contains a true value for the key dele... |
Call the backend method with args.
If there is currently no backend, return default. | def _call_backend(self, method, default, *args, **kwargs):
"""Call the backend method with args.
If there is currently no backend, return default."""
meth = getattr(self.backend, method, None)
if meth is None:
return default
else:
return meth(*args, **kwa... |
Get the calltip for the function at the offset. | def rpc_get_calltip(self, filename, source, offset):
"""Get the calltip for the function at the offset.
"""
return self._call_backend("rpc_get_calltip", None, filename,
get_source(source), offset) |
Get a oneline docstring for the symbol at the offset. | def rpc_get_oneline_docstring(self, filename, source, offset):
"""Get a oneline docstring for the symbol at the offset.
"""
return self._call_backend("rpc_get_oneline_docstring", None, filename,
get_source(source), offset) |
Get a list of completion candidates for the symbol at offset. | def rpc_get_completions(self, filename, source, offset):
"""Get a list of completion candidates for the symbol at offset.
"""
results = self._call_backend("rpc_get_completions", [], filename,
get_source(source), offset)
# Uniquify by name
res... |
Get the location of the definition for the symbol at the offset. | def rpc_get_definition(self, filename, source, offset):
"""Get the location of the definition for the symbol at the offset.
"""
return self._call_backend("rpc_get_definition", None, filename,
get_source(source), offset) |
Get the location of the assignment for the symbol at the offset. | def rpc_get_assignment(self, filename, source, offset):
"""Get the location of the assignment for the symbol at the offset.
"""
return self._call_backend("rpc_get_assignment", None, filename,
get_source(source), offset) |
Get the docstring for the symbol at the offset. | def rpc_get_docstring(self, filename, source, offset):
"""Get the docstring for the symbol at the offset.
"""
return self._call_backend("rpc_get_docstring", None, filename,
get_source(source), offset) |
Get the Pydoc documentation for the given symbol.
Uses pydoc and can return a string with backspace characters
for bold highlighting. | def rpc_get_pydoc_documentation(self, symbol):
"""Get the Pydoc documentation for the given symbol.
Uses pydoc and can return a string with backspace characters
for bold highlighting.
"""
try:
docstring = pydoc.render_doc(str(symbol),
... |
Return a list of possible refactoring options.
This list will be filtered depending on whether it's
applicable at the point START and possibly the region between
START and END. | def rpc_get_refactor_options(self, filename, start, end=None):
"""Return a list of possible refactoring options.
This list will be filtered depending on whether it's
applicable at the point START and possibly the region between
START and END.
"""
try:
from e... |
Return a list of changes from the refactoring action.
A change is a dictionary describing the change. See
elpy.refactor.translate_changes for a description. | def rpc_refactor(self, filename, method, args):
"""Return a list of changes from the refactoring action.
A change is a dictionary describing the change. See
elpy.refactor.translate_changes for a description.
"""
try:
from elpy import refactor
except:
... |
Get all possible names | def rpc_get_names(self, filename, source, offset):
"""Get all possible names
"""
source = get_source(source)
if hasattr(self.backend, "rpc_get_names"):
return self.backend.rpc_get_names(filename, source, offset)
else:
raise Fault("get_names not implemente... |
Formats Python code to conform to the PEP 8 style guide. | def rpc_fix_code(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code(source, directory) |
Formats Python code to conform to the PEP 8 style guide. | def rpc_fix_code_with_yapf(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code_with_yapf(source, directory) |
Formats Python code to conform to the PEP 8 style guide. | def rpc_fix_code_with_black(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code_with_black(source, directory) |
Return a tuple of line and column for offset pos in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why. | def pos_to_linecol(text, pos):
"""Return a tuple of line and column for offset pos in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why.
"""
line_start = text.rfind("\n", 0, pos) + 1
line = text.count("\n", 0, line_start) + 1
col = pos - line_start... |
Return the offset of this line and column in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why. | def linecol_to_pos(text, line, col):
"""Return the offset of this line and column in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why.
"""
nth_newline_offset = 0
for i in range(line - 1):
new_offset = text.find("\n", nth_newline_offset)
... |
Return a oneline docstring for the symbol at offset | def rpc_get_oneline_docstring(self, filename, source, offset):
"""Return a oneline docstring for the symbol at offset"""
line, column = pos_to_linecol(source, offset)
definitions = run_with_debug(jedi, 'goto_definitions',
source=source, line=line, column=colu... |
Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset. | def rpc_get_usages(self, filename, source, offset):
"""Return the uses of the symbol at offset.
Returns a list of occurrences of the symbol, as dicts with the
fields name, filename, and offset.
"""
line, column = pos_to_linecol(source, offset)
uses = run_with_debug(jedi... |
Return the list of possible names | def rpc_get_names(self, filename, source, offset):
"""Return the list of possible names"""
names = jedi.api.names(source=source,
path=filename, encoding='utf-8',
all_scopes=True,
definitions=True,
... |
Formats Python code to conform to the PEP 8 style guide. | def fix_code(code, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
if not black:
raise Fault("black not installed", code=400)
try:
if parse_version(black.__version__) < parse_version("19.0"):
reformatted_source = black.format_file_contents(
... |
Decorator to set some options on a method. | def options(description, **kwargs):
"""Decorator to set some options on a method."""
def set_notes(function):
function.refactor_notes = {'name': function.__name__,
'category': "Miscellaneous",
'description': description,
... |
Translate rope.base.change.Change instances to dictionaries.
See Refactor.get_changes for an explanation of the resulting
dictionary. | def translate_changes(initial_change):
"""Translate rope.base.change.Change instances to dictionaries.
See Refactor.get_changes for an explanation of the resulting
dictionary.
"""
agenda = [initial_change]
result = []
while agenda:
change = agenda.pop(0)
if isinstance(chang... |
Return a list of options for refactoring at the given position.
If `end` is also given, refactoring on a region is assumed.
Each option is a dictionary of key/value pairs. The value of
the key 'name' is the one to be used for get_changes.
The key 'args' contains a list of additional a... | def get_refactor_options(self, start, end=None):
"""Return a list of options for refactoring at the given position.
If `end` is also given, refactoring on a region is assumed.
Each option is a dictionary of key/value pairs. The value of
the key 'name' is the one to be used for get_chan... |
Does this offset point to an import statement? | def _is_on_import_statement(self, offset):
"Does this offset point to an import statement?"
data = self.resource.read()
bol = data.rfind("\n", 0, offset) + 1
eol = data.find("\n", 0, bol)
if eol == -1:
eol = len(data)
line = data[bol:eol]
line = line.s... |
Is this offset on a symbol? | def _is_on_symbol(self, offset):
"Is this offset on a symbol?"
if not ROPE_AVAILABLE:
return False
data = self.resource.read()
if offset >= len(data):
return False
if data[offset] != '_' and not data[offset].isalnum():
return False
word... |
Return a list of changes for the named refactoring action.
Changes are dictionaries describing a single action to be
taken for the refactoring to be successful.
A change has an action and possibly a type. In the description
below, the action is before the slash and the type after it.
... | def get_changes(self, name, *args):
"""Return a list of changes for the named refactoring action.
Changes are dictionaries describing a single action to be
taken for the refactoring to be successful.
A change has an action and possibly a type. In the description
below, the acti... |
Converting imports of the form "from ..." to "import ...". | def refactor_froms_to_imports(self, offset):
"""Converting imports of the form "from ..." to "import ..."."""
refactor = ImportOrganizer(self.project)
changes = refactor.froms_to_imports(self.resource, offset)
return translate_changes(changes) |
Clean up and organize imports. | def refactor_organize_imports(self):
"""Clean up and organize imports."""
refactor = ImportOrganizer(self.project)
changes = refactor.organize_imports(self.resource)
return translate_changes(changes) |
Convert the current module into a package. | def refactor_module_to_package(self):
"""Convert the current module into a package."""
refactor = ModuleToPackage(self.project, self.resource)
return self._get_changes(refactor) |
Rename the symbol at point. | def refactor_rename_at_point(self, offset, new_name, in_hierarchy, docs):
"""Rename the symbol at point."""
try:
refactor = Rename(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(str(e), code=400)
return self._get_changes(refactor, n... |
Rename the current module. | def refactor_rename_current_module(self, new_name):
"""Rename the current module."""
refactor = Rename(self.project, self.resource, None)
return self._get_changes(refactor, new_name) |
Move the current module. | def refactor_move_module(self, new_name):
"""Move the current module."""
refactor = create_move(self.project, self.resource)
resource = path_to_resource(self.project, new_name)
return self._get_changes(refactor, resource) |
Inline the function call at point. | def refactor_create_inline(self, offset, only_this):
"""Inline the function call at point."""
refactor = create_inline(self.project, self.resource, offset)
if only_this:
return self._get_changes(refactor, remove=False, only_current=True)
else:
return self._get_cha... |
Extract region as a method. | def refactor_extract_method(self, start, end, name,
make_global):
"""Extract region as a method."""
refactor = ExtractMethod(self.project, self.resource, start, end)
return self._get_changes(
refactor, name, similar=True, global_=make_global
) |
Use the function at point wherever possible. | def refactor_use_function(self, offset):
"""Use the function at point wherever possible."""
try:
refactor = UseFunction(self.project, self.resource, offset)
except RefactoringError as e:
raise Fault(
'Refactoring error: {}'.format(e),
code=... |
Formats Python code to conform to the PEP 8 style guide. | def fix_code(code, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
if not yapf_api:
raise Fault('yapf not installed', code=400)
style_config = file_resources.GetDefaultStyleForDir(directory or os.getcwd())
try:
reformatted_source, _ = yapf_api.FormatCode(... |
Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send. | def _send_receive(self, payload):
"""
Send single buffer `payload` and receive a single buffer.
Args:
payload(bytes): Data to send.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
... |
Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to be send.
This is what will be passed via the 'dps' entry | def generate_payload(self, command, data=None):
"""
Generate the payload to send.
Args:
command(str): The type of command.
This is one of the entries from payload_dict
data(dict, optional): The data to be send.
This is what will be passed ... |
Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set | def set_status(self, on, switch=1):
"""
Set status of the device to 'on' or 'off'.
Args:
on(bool): True for 'on', False for 'off'.
switch(int): The switch to set
"""
# open device, send request, then close connection
if isinstance(switch,... |
Set a timer.
Args:
num_secs(int): Number of seconds | def set_timer(self, num_secs):
"""
Set a timer.
Args:
num_secs(int): Number of seconds
"""
# FIXME / TODO support schemas? Accept timer id number as parameter?
# Dumb heuristic; Query status, pick last device id as that is probably the timer
... |
Convert an RGB value to the hex representation expected by tuya.
Index '5' (DPS_INDEX_COLOUR) is assumed to be in the format:
rrggbb0hhhssvv
While r, g and b are just hexadecimal values of the corresponding
Red, Green and Blue values, the h, s and v values (which are va... | def _rgb_to_hexvalue(r, g, b):
"""
Convert an RGB value to the hex representation expected by tuya.
Index '5' (DPS_INDEX_COLOUR) is assumed to be in the format:
rrggbb0hhhssvv
While r, g and b are just hexadecimal values of the corresponding
Red, Green a... |
Converts the hexvalue used by tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue() | def _hexvalue_to_rgb(hexvalue):
"""
Converts the hexvalue used by tuya for colour representation into
an RGB value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
r = int(hexvalue[0:2], 16)
g = in... |
Converts the hexvalue used by tuya for colour representation into
an HSV value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue() | def _hexvalue_to_hsv(hexvalue):
"""
Converts the hexvalue used by tuya for colour representation into
an HSV value.
Args:
hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue()
"""
h = int(hexvalue[7:10], 16) / 360
... |
Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255. | def set_colour(self, r, g, b):
"""
Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255.
"""
if not 0 <= ... |
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
colourtemp(int): Value for the colour temperature (0-255). | def set_white(self, brightness, colourtemp):
"""
Set white coloured theme of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
colourtemp(int): Value for the colour temperature (0-255).
"""
if not 25 <= brightness <= 255:
... |
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255). | def set_brightness(self, brightness):
"""
Set the brightness value of an rgb bulb.
Args:
brightness(int): Value for the brightness (25-255).
"""
if not 25 <= brightness <= 255:
raise ValueError("The brightness needs to be between 25 and 255.")
pa... |
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255). | def set_colourtemp(self, colourtemp):
"""
Set the colour temperature of an rgb bulb.
Args:
colourtemp(int): Value for the colour temperature (0-255).
"""
if not 0 <= colourtemp <= 255:
raise ValueError("The colour temperature needs to be between 0 and 255... |
Return colour as RGB value | def colour_rgb(self):
"""Return colour as RGB value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_rgb(hexvalue) |
Return colour as HSV value | def colour_hsv(self):
"""Return colour as HSV value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_hsv(hexvalue) |
Set the group mask that the Crazyflie belongs to
:param group_mask: mask for which groups this CF belongs to | def set_group_mask(self, group_mask=ALL_GROUPS):
"""
Set the group mask that the Crazyflie belongs to
:param group_mask: mask for which groups this CF belongs to
"""
self._send_packet(struct.pack('<BB',
self.COMMAND_SET_GROUP_MASK,
... |
vertical takeoff from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param group_mask: mask for which CFs this should apply to | def takeoff(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS):
"""
vertical takeoff from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:par... |
vertical land from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param group_mask: mask for which CFs this should apply to | def land(self, absolute_height_m, duration_s, group_mask=ALL_GROUPS):
"""
vertical land from current x-y position to given height
:param absolute_height_m: absolut (m)
:param duration_s: time it should take until target height is
reached (s)
:param gro... |
stops the current trajectory (turns off the motors)
:param group_mask: mask for which CFs this should apply to
:return: | def stop(self, group_mask=ALL_GROUPS):
"""
stops the current trajectory (turns off the motors)
:param group_mask: mask for which CFs this should apply to
:return:
"""
self._send_packet(struct.pack('<BB',
self.COMMAND_STOP,
... |
Go to an absolute or relative position
:param x: x (m)
:param y: y (m)
:param z: z (m)
:param yaw: yaw (radians)
:param duration_s: time it should take to reach the position (s)
:param relative: True if x, y, z is relative to the current position
:param group_mas... | def go_to(self, x, y, z, yaw, duration_s, relative=False,
group_mask=ALL_GROUPS):
"""
Go to an absolute or relative position
:param x: x (m)
:param y: y (m)
:param z: z (m)
:param yaw: yaw (radians)
:param duration_s: time it should take to reach th... |
starts executing a specified trajectory
:param trajectory_id: id of the trajectory (previously defined by
define_trajectory)
:param time_scale: time factor; 1.0 = original speed;
>1.0: slower;
<1.0: faster
... | def start_trajectory(self, trajectory_id, time_scale=1.0, relative=False,
reversed=False, group_mask=ALL_GROUPS):
"""
starts executing a specified trajectory
:param trajectory_id: id of the trajectory (previously defined by
define_trajectory)
:par... |
Define a trajectory that has previously been uploaded to memory.
:param trajectory_id: The id of the trajectory
:param offset: offset in uploaded memory
:param n_pieces: Nr of pieces in the trajectory
:return: | def define_trajectory(self, trajectory_id, offset, n_pieces):
"""
Define a trajectory that has previously been uploaded to memory.
:param trajectory_id: The id of the trajectory
:param offset: offset in uploaded memory
:param n_pieces: Nr of pieces in the trajectory
:ret... |
Interactively choose one of the items. | def choose(items, title_text, question_text):
"""
Interactively choose one of the items.
"""
print(title_text)
for i, item in enumerate(items, start=1):
print('%d) %s' % (i, item))
print('%d) Abort' % (i + 1))
selected = input(question_text)
try:
index = int(selected)
... |
Scan for Crazyflie and return its URI. | def scan():
"""
Scan for Crazyflie and return its URI.
"""
# Initiate the low level drivers
cflib.crtp.init_drivers(enable_debug_driver=False)
# Scan for Crazyflies
print('Scanning interfaces for Crazyflies...')
available = cflib.crtp.scan_interfaces()
interfaces = [uri for uri, _ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.