repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
ceph/ceph-deploy
ceph_deploy/install.py
make_purge
def make_purge(parser): """ Remove Ceph packages from remote hosts and purge all data. """ parser.add_argument( 'host', metavar='HOST', nargs='+', help='hosts to purge Ceph from', ) parser.set_defaults( func=purge, )
python
def make_purge(parser): """ Remove Ceph packages from remote hosts and purge all data. """ parser.add_argument( 'host', metavar='HOST', nargs='+', help='hosts to purge Ceph from', ) parser.set_defaults( func=purge, )
[ "def", "make_purge", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'host'", ",", "metavar", "=", "'HOST'", ",", "nargs", "=", "'+'", ",", "help", "=", "'hosts to purge Ceph from'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", ...
Remove Ceph packages from remote hosts and purge all data.
[ "Remove", "Ceph", "packages", "from", "remote", "hosts", "and", "purge", "all", "data", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/install.py#L642-L654
train
228,300
ceph/ceph-deploy
ceph_deploy/rgw.py
make
def make(parser): """ Ceph RGW daemon management """ rgw_parser = parser.add_subparsers(dest='subcommand') rgw_parser.required = True rgw_create = rgw_parser.add_parser( 'create', help='Create an RGW instance' ) rgw_create.add_argument( 'rgw', metavar='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on. \ NAME is automatically prefixed with \'rgw.\'', ) parser.set_defaults( func=rgw, )
python
def make(parser): """ Ceph RGW daemon management """ rgw_parser = parser.add_subparsers(dest='subcommand') rgw_parser.required = True rgw_create = rgw_parser.add_parser( 'create', help='Create an RGW instance' ) rgw_create.add_argument( 'rgw', metavar='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on. \ NAME is automatically prefixed with \'rgw.\'', ) parser.set_defaults( func=rgw, )
[ "def", "make", "(", "parser", ")", ":", "rgw_parser", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'subcommand'", ")", "rgw_parser", ".", "required", "=", "True", "rgw_create", "=", "rgw_parser", ".", "add_parser", "(", "'create'", ",", "help", ...
Ceph RGW daemon management
[ "Ceph", "RGW", "daemon", "management" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/rgw.py#L213-L233
train
228,301
ceph/ceph-deploy
ceph_deploy/util/ssh.py
can_connect_passwordless
def can_connect_passwordless(hostname): """ Ensure that current host can SSH remotely to the remote host using the ``BatchMode`` option to prevent a password prompt. That attempt will error with an exit status of 255 and a ``Permission denied`` message or a``Host key verification failed`` message. """ # Ensure we are not doing this for local hosts if not remoto.backends.needs_ssh(hostname): return True logger = logging.getLogger(hostname) with get_local_connection(logger) as conn: # Check to see if we can login, disabling password prompts command = ['ssh', '-CT', '-o', 'BatchMode=yes', hostname, 'true'] out, err, retval = remoto.process.check(conn, command, stop_on_error=False) permission_denied_error = 'Permission denied ' host_key_verify_error = 'Host key verification failed.' has_key_error = False for line in err: if permission_denied_error in line or host_key_verify_error in line: has_key_error = True if retval == 255 and has_key_error: return False return True
python
def can_connect_passwordless(hostname): """ Ensure that current host can SSH remotely to the remote host using the ``BatchMode`` option to prevent a password prompt. That attempt will error with an exit status of 255 and a ``Permission denied`` message or a``Host key verification failed`` message. """ # Ensure we are not doing this for local hosts if not remoto.backends.needs_ssh(hostname): return True logger = logging.getLogger(hostname) with get_local_connection(logger) as conn: # Check to see if we can login, disabling password prompts command = ['ssh', '-CT', '-o', 'BatchMode=yes', hostname, 'true'] out, err, retval = remoto.process.check(conn, command, stop_on_error=False) permission_denied_error = 'Permission denied ' host_key_verify_error = 'Host key verification failed.' has_key_error = False for line in err: if permission_denied_error in line or host_key_verify_error in line: has_key_error = True if retval == 255 and has_key_error: return False return True
[ "def", "can_connect_passwordless", "(", "hostname", ")", ":", "# Ensure we are not doing this for local hosts", "if", "not", "remoto", ".", "backends", ".", "needs_ssh", "(", "hostname", ")", ":", "return", "True", "logger", "=", "logging", ".", "getLogger", "(", ...
Ensure that current host can SSH remotely to the remote host using the ``BatchMode`` option to prevent a password prompt. That attempt will error with an exit status of 255 and a ``Permission denied`` message or a``Host key verification failed`` message.
[ "Ensure", "that", "current", "host", "can", "SSH", "remotely", "to", "the", "remote", "host", "using", "the", "BatchMode", "option", "to", "prevent", "a", "password", "prompt", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/ssh.py#L6-L32
train
228,302
ceph/ceph-deploy
ceph_deploy/util/net.py
ip_in_subnet
def ip_in_subnet(ip, subnet): """Does IP exists in a given subnet utility. Returns a boolean""" ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16) netstr, bits = subnet.split('/') netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16) mask = (0xffffffff << (32 - int(bits))) & 0xffffffff return (ipaddr & mask) == (netaddr & mask)
python
def ip_in_subnet(ip, subnet): """Does IP exists in a given subnet utility. Returns a boolean""" ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16) netstr, bits = subnet.split('/') netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16) mask = (0xffffffff << (32 - int(bits))) & 0xffffffff return (ipaddr & mask) == (netaddr & mask)
[ "def", "ip_in_subnet", "(", "ip", ",", "subnet", ")", ":", "ipaddr", "=", "int", "(", "''", ".", "join", "(", "[", "'%02x'", "%", "int", "(", "x", ")", "for", "x", "in", "ip", ".", "split", "(", "'.'", ")", "]", ")", ",", "16", ")", "netstr",...
Does IP exists in a given subnet utility. Returns a boolean
[ "Does", "IP", "exists", "in", "a", "given", "subnet", "utility", ".", "Returns", "a", "boolean" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L52-L58
train
228,303
ceph/ceph-deploy
ceph_deploy/util/net.py
in_subnet
def in_subnet(cidr, addrs=None): """ Returns True if host is within specified subnet, otherwise False """ for address in addrs: if ip_in_subnet(address, cidr): return True return False
python
def in_subnet(cidr, addrs=None): """ Returns True if host is within specified subnet, otherwise False """ for address in addrs: if ip_in_subnet(address, cidr): return True return False
[ "def", "in_subnet", "(", "cidr", ",", "addrs", "=", "None", ")", ":", "for", "address", "in", "addrs", ":", "if", "ip_in_subnet", "(", "address", ",", "cidr", ")", ":", "return", "True", "return", "False" ]
Returns True if host is within specified subnet, otherwise False
[ "Returns", "True", "if", "host", "is", "within", "specified", "subnet", "otherwise", "False" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L61-L68
train
228,304
ceph/ceph-deploy
ceph_deploy/util/net.py
get_chacra_repo
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) return chacra_response.read()
python
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) return chacra_response.read()
[ "def", "get_chacra_repo", "(", "shaman_url", ")", ":", "shaman_response", "=", "get_request", "(", "shaman_url", ")", "chacra_url", "=", "shaman_response", ".", "geturl", "(", ")", "chacra_response", "=", "get_request", "(", "chacra_url", ")", "return", "chacra_re...
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.
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L390-L399
train
228,305
ceph/ceph-deploy
ceph_deploy/hosts/common.py
map_components
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 been 'split' from the master 'ceph' package yet. """ packages = set() for c in components: if c in notsplit_packages: packages.add('ceph') else: packages.add(c) return list(packages)
python
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 been 'split' from the master 'ceph' package yet. """ packages = set() for c in components: if c in notsplit_packages: packages.add('ceph') else: packages.add(c) return list(packages)
[ "def", "map_components", "(", "notsplit_packages", ",", "components", ")", ":", "packages", "=", "set", "(", ")", "for", "c", "in", "components", ":", "if", "c", "in", "notsplit_packages", ":", "packages", ".", "add", "(", "'ceph'", ")", "else", ":", "pa...
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.
[ "Returns", "a", "list", "of", "packages", "to", "install", "based", "on", "component", "names" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/common.py#L165-L182
train
228,306
ceph/ceph-deploy
ceph_deploy/hosts/common.py
start_mon_service
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', '-c', '/etc/ceph/{cluster}.conf'.format(cluster=cluster), 'start', 'mon.{hostname}'.format(hostname=hostname) ], timeout=7, ) system.enable_service(distro.conn) elif distro.init == 'upstart': remoto.process.run( distro.conn, [ 'initctl', 'emit', 'ceph-mon', 'cluster={cluster}'.format(cluster=cluster), 'id={hostname}'.format(hostname=hostname), ], timeout=7, ) elif distro.init == 'systemd': # enable ceph target for this host (in case it isn't already enabled) remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph.target' ], timeout=7, ) # enable and start this mon instance remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, ) remoto.process.run( distro.conn, [ 'systemctl', 'start', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, )
python
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', '-c', '/etc/ceph/{cluster}.conf'.format(cluster=cluster), 'start', 'mon.{hostname}'.format(hostname=hostname) ], timeout=7, ) system.enable_service(distro.conn) elif distro.init == 'upstart': remoto.process.run( distro.conn, [ 'initctl', 'emit', 'ceph-mon', 'cluster={cluster}'.format(cluster=cluster), 'id={hostname}'.format(hostname=hostname), ], timeout=7, ) elif distro.init == 'systemd': # enable ceph target for this host (in case it isn't already enabled) remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph.target' ], timeout=7, ) # enable and start this mon instance remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, ) remoto.process.run( distro.conn, [ 'systemctl', 'start', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, )
[ "def", "start_mon_service", "(", "distro", ",", "cluster", ",", "hostname", ")", ":", "if", "distro", ".", "init", "==", "'sysvinit'", ":", "service", "=", "distro", ".", "conn", ".", "remote_module", ".", "which_service", "(", ")", "remoto", ".", "process...
start mon service depending on distro init
[ "start", "mon", "service", "depending", "on", "distro", "init" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/common.py#L185-L248
train
228,307
andrea-cuttone/geoplotlib
geoplotlib/layers.py
VoronoiLayer.__voronoi_finite_polygons_2d
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'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max() # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all(v >= 0 for v in vertices): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region if p1 not in all_ridges: continue ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
python
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'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max() # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all(v >= 0 for v in vertices): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region if p1 not in all_ridges: continue ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
[ "def", "__voronoi_finite_polygons_2d", "(", "vor", ",", "radius", "=", "None", ")", ":", "if", "vor", ".", "points", ".", "shape", "[", "1", "]", "!=", "2", ":", "raise", "ValueError", "(", "\"Requires 2D input\"", ")", "new_regions", "=", "[", "]", "new...
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 Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end.
[ "Reconstruct", "infinite", "voronoi", "regions", "in", "a", "2D", "diagram", "to", "finite", "regions", "." ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/layers.py#L505-L589
train
228,308
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
inline
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.ascii_uppercase + string.digits) for _ in range(32)) if not os.path.isfile(fname + '.png'): break savefig(fname) if os.path.isfile(fname + '.png'): with open(fname + '.png', 'rb') as fin: encoded = base64.b64encode(fin.read()) b64 = urllib.parse.quote(encoded) image_html = "<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />" % (width, b64) display(HTML(image_html)) os.remove(fname + '.png')
python
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.ascii_uppercase + string.digits) for _ in range(32)) if not os.path.isfile(fname + '.png'): break savefig(fname) if os.path.isfile(fname + '.png'): with open(fname + '.png', 'rb') as fin: encoded = base64.b64encode(fin.read()) b64 = urllib.parse.quote(encoded) image_html = "<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />" % (width, b64) display(HTML(image_html)) os.remove(fname + '.png')
[ "def", "inline", "(", "width", "=", "900", ")", ":", "from", "IPython", ".", "display", "import", "Image", ",", "HTML", ",", "display", ",", "clear_output", "import", "random", "import", "string", "import", "urllib", "import", "os", "while", "True", ":", ...
display the map inline in ipython :param width: image width for the browser
[ "display", "the", "map", "inline", "in", "ipython" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L52-L78
train
228,309
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
dot
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 _global_config.layers.append(DotDensityLayer(data, color=color, point_size=point_size, f_tooltip=f_tooltip))
python
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 _global_config.layers.append(DotDensityLayer(data, color=color, point_size=point_size, f_tooltip=f_tooltip))
[ "def", "dot", "(", "data", ",", "color", "=", "None", ",", "point_size", "=", "2", ",", "f_tooltip", "=", "None", ")", ":", "from", "geoplotlib", ".", "layers", "import", "DotDensityLayer", "_global_config", ".", "layers", ".", "append", "(", "DotDensityLa...
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
[ "Create", "a", "dot", "density", "map" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L81-L90
train
228,310
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
hist
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 [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 displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar """ from geoplotlib.layers import HistogramLayer _global_config.layers.append(HistogramLayer(data, cmap=cmap, alpha=alpha, colorscale=colorscale, binsize=binsize, show_tooltip=show_tooltip, scalemin=scalemin, scalemax=scalemax, f_group=f_group, show_colorbar=show_colorbar))
python
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 [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 displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar """ from geoplotlib.layers import HistogramLayer _global_config.layers.append(HistogramLayer(data, cmap=cmap, alpha=alpha, colorscale=colorscale, binsize=binsize, show_tooltip=show_tooltip, scalemin=scalemin, scalemax=scalemax, f_group=f_group, show_colorbar=show_colorbar))
[ "def", "hist", "(", "data", ",", "cmap", "=", "'hot'", ",", "alpha", "=", "220", ",", "colorscale", "=", "'sqrt'", ",", "binsize", "=", "16", ",", "show_tooltip", "=", "False", ",", "scalemin", "=", "0", ",", "scalemax", "=", "None", ",", "f_group", ...
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 displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar
[ "Create", "a", "2D", "histogram" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L101-L119
train
228,311
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
shapefiles
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 full or bbox """ from geoplotlib.layers import ShapefileLayer _global_config.layers.append(ShapefileLayer(fname, f_tooltip, color, linewidth, shape_type))
python
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 full or bbox """ from geoplotlib.layers import ShapefileLayer _global_config.layers.append(ShapefileLayer(fname, f_tooltip, color, linewidth, shape_type))
[ "def", "shapefiles", "(", "fname", ",", "f_tooltip", "=", "None", ",", "color", "=", "None", ",", "linewidth", "=", "3", ",", "shape_type", "=", "'full'", ")", ":", "from", "geoplotlib", ".", "layers", "import", "ShapefileLayer", "_global_config", ".", "la...
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
[ "Load", "and", "draws", "shapefiles" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L138-L149
train
228,312
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
voronoi
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 mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha """ from geoplotlib.layers import VoronoiLayer _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))
python
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 mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha """ from geoplotlib.layers import VoronoiLayer _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))
[ "def", "voronoi", "(", "data", ",", "line_color", "=", "None", ",", "line_width", "=", "2", ",", "f_tooltip", "=", "None", ",", "cmap", "=", "None", ",", "max_area", "=", "1e4", ",", "alpha", "=", "220", ")", ":", "from", "geoplotlib", ".", "layers",...
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 areas :param alpha: color alpha
[ "Draw", "the", "voronoi", "tesselation", "of", "the", "points" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L152-L165
train
228,313
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
delaunay
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 the edges """ from geoplotlib.layers import DelaunayLayer _global_config.layers.append(DelaunayLayer(data, line_color, line_width, cmap, max_lenght))
python
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 the edges """ from geoplotlib.layers import DelaunayLayer _global_config.layers.append(DelaunayLayer(data, line_color, line_width, cmap, max_lenght))
[ "def", "delaunay", "(", "data", ",", "line_color", "=", "None", ",", "line_width", "=", "2", ",", "cmap", "=", "None", ",", "max_lenght", "=", "100", ")", ":", "from", "geoplotlib", ".", "layers", "import", "DelaunayLayer", "_global_config", ".", "layers",...
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
[ "Draw", "a", "delaunay", "triangulation", "of", "the", "points" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L168-L179
train
228,314
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
convexhull
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 geoplotlib.layers import ConvexHullLayer _global_config.layers.append(ConvexHullLayer(data, col, fill, point_size))
python
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 geoplotlib.layers import ConvexHullLayer _global_config.layers.append(ConvexHullLayer(data, col, fill, point_size))
[ "def", "convexhull", "(", "data", ",", "col", ",", "fill", "=", "True", ",", "point_size", "=", "4", ")", ":", "from", "geoplotlib", ".", "layers", "import", "ConvexHullLayer", "_global_config", ".", "layers", ".", "append", "(", "ConvexHullLayer", "(", "d...
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
[ "Convex", "hull", "for", "a", "set", "of", "points" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L182-L192
train
228,315
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
kde
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) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar """ from geoplotlib.layers import KDELayer _global_config.layers.append(KDELayer(data, bw, cmap, method, scaling, alpha, cut_below, clip_above, binsize, cmap_levels, show_colorbar))
python
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) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar """ from geoplotlib.layers import KDELayer _global_config.layers.append(KDELayer(data, bw, cmap, method, scaling, alpha, cut_below, clip_above, binsize, cmap_levels, show_colorbar))
[ "def", "kde", "(", "data", ",", "bw", ",", "cmap", "=", "'hot'", ",", "method", "=", "'hist'", ",", "scaling", "=", "'sqrt'", ",", "alpha", "=", "220", ",", "cut_below", "=", "None", ",", "clip_above", "=", "None", ",", "binsize", "=", "1", ",", ...
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 applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar
[ "Kernel", "density", "estimation", "visualization" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L195-L215
train
228,316
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
labels
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 :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y """ from geoplotlib.layers import LabelsLayer _global_config.layers.append(LabelsLayer(data, label_column, color, font_name, font_size, anchor_x, anchor_y))
python
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 :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y """ from geoplotlib.layers import LabelsLayer _global_config.layers.append(LabelsLayer(data, label_column, color, font_name, font_size, anchor_x, anchor_y))
[ "def", "labels", "(", "data", ",", "label_column", ",", "color", "=", "None", ",", "font_name", "=", "FONT_NAME", ",", "font_size", "=", "14", ",", "anchor_x", "=", "'left'", ",", "anchor_y", "=", "'top'", ")", ":", "from", "geoplotlib", ".", "layers", ...
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
[ "Draw", "a", "text", "label", "for", "each", "sample" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L245-L260
train
228,317
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
set_map_alpha
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
python
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
[ "def", "set_map_alpha", "(", "alpha", ")", ":", "if", "alpha", "<", "0", "or", "alpha", ">", "255", ":", "raise", "Exception", "(", "'invalid alpha '", "+", "str", "(", "alpha", ")", ")", "_global_config", ".", "map_alpha", "=", "alpha" ]
Alpha color of the map tiles :param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness
[ "Alpha", "color", "of", "the", "map", "tiles" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L332-L340
train
228,318
andrea-cuttone/geoplotlib
geoplotlib/utils.py
read_csv
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: np.array(values[k]) for k in values.keys()} for k in npvalues.keys(): for datatype in [np.int, np.float]: try: npvalues[k][:1].astype(datatype) npvalues[k] = npvalues[k].astype(datatype) break except: pass dao = DataAccessObject(npvalues) return dao
python
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: np.array(values[k]) for k in values.keys()} for k in npvalues.keys(): for datatype in [np.int, np.float]: try: npvalues[k][:1].astype(datatype) npvalues[k] = npvalues[k].astype(datatype) break except: pass dao = DataAccessObject(npvalues) return dao
[ "def", "read_csv", "(", "fname", ")", ":", "values", "=", "defaultdict", "(", "list", ")", "with", "open", "(", "fname", ")", "as", "f", ":", "reader", "=", "csv", ".", "DictReader", "(", "f", ")", "for", "row", "in", "reader", ":", "for", "(", "...
Read a csv file into a DataAccessObject :param fname: filename
[ "Read", "a", "csv", "file", "into", "a", "DataAccessObject" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L141-L163
train
228,319
andrea-cuttone/geoplotlib
geoplotlib/utils.py
DataAccessObject.head
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})
python
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})
[ "def", "head", "(", "self", ",", "n", ")", ":", "return", "DataAccessObject", "(", "{", "k", ":", "self", ".", "dict", "[", "k", "]", "[", ":", "n", "]", "for", "k", "in", "self", ".", "dict", "}", ")" ]
Return a DataAccessObject containing the first n rows :param n: number of rows :return: DataAccessObject
[ "Return", "a", "DataAccessObject", "containing", "the", "first", "n", "rows" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L104-L111
train
228,320
andrea-cuttone/geoplotlib
geoplotlib/utils.py
BoundingBox.from_points
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 BoundingBox(north=north, west=west, south=south, east=east)
python
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 BoundingBox(north=north, west=west, south=south, east=east)
[ "def", "from_points", "(", "lons", ",", "lats", ")", ":", "north", ",", "west", "=", "max", "(", "lats", ")", ",", "min", "(", "lons", ")", "south", ",", "east", "=", "min", "(", "lats", ")", ",", "max", "(", "lons", ")", "return", "BoundingBox",...
Compute the BoundingBox from a set of latitudes and longitudes :param lons: longitudes :param lats: latitudes :return: BoundingBox
[ "Compute", "the", "BoundingBox", "from", "a", "set", "of", "latitudes", "and", "longitudes" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L207-L217
train
228,321
andrea-cuttone/geoplotlib
geoplotlib/utils.py
BoundingBox.from_bboxes
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 bboxes]) east = max([b.east for b in bboxes]) return BoundingBox(north=north, west=west, south=south, east=east)
python
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 bboxes]) east = max([b.east for b in bboxes]) return BoundingBox(north=north, west=west, south=south, east=east)
[ "def", "from_bboxes", "(", "bboxes", ")", ":", "north", "=", "max", "(", "[", "b", ".", "north", "for", "b", "in", "bboxes", "]", ")", "south", "=", "min", "(", "[", "b", ".", "south", "for", "b", "in", "bboxes", "]", ")", "west", "=", "min", ...
Compute a BoundingBox enclosing all specified bboxes :param bboxes: a list of BoundingBoxes :return: BoundingBox
[ "Compute", "a", "BoundingBox", "enclosing", "all", "specified", "bboxes" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L221-L232
train
228,322
jorgenschaefer/elpy
elpy/pydocutils.py
get_pydoc_completions
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_modules()) candidates = get_completions(modulename) if candidates: return sorted(candidates) needle = modulename if "." in needle: modulename, part = needle.rsplit(".", 1) candidates = get_completions(modulename) else: candidates = get_modules() return sorted(candidate for candidate in candidates if candidate.startswith(needle))
python
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_modules()) candidates = get_completions(modulename) if candidates: return sorted(candidates) needle = modulename if "." in needle: modulename, part = needle.rsplit(".", 1) candidates = get_completions(modulename) else: candidates = get_modules() return sorted(candidate for candidate in candidates if candidate.startswith(needle))
[ "def", "get_pydoc_completions", "(", "modulename", ")", ":", "modulename", "=", "compat", ".", "ensure_not_unicode", "(", "modulename", ")", "modulename", "=", "modulename", ".", "rstrip", "(", "\".\"", ")", "if", "modulename", "==", "\"\"", ":", "return", "so...
Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc.
[ "Get", "possible", "completions", "for", "modulename", "for", "pydoc", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/pydocutils.py#L24-L44
train
228,323
jorgenschaefer/elpy
elpy/pydocutils.py
get_modules
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 (importer, modname, ispkg) in iter_modules() if not modname.startswith("_")] + list(sys.builtin_module_names)) except OSError: # Bug in Python 2.6, see #275 return list(sys.builtin_module_names) try: module = safeimport(modulename) except ErrorDuringImport: return [] if module is None: return [] if hasattr(module, "__path__"): return [modname for (importer, modname, ispkg) in iter_modules(module.__path__) if not modname.startswith("_")] return []
python
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 (importer, modname, ispkg) in iter_modules() if not modname.startswith("_")] + list(sys.builtin_module_names)) except OSError: # Bug in Python 2.6, see #275 return list(sys.builtin_module_names) try: module = safeimport(modulename) except ErrorDuringImport: return [] if module is None: return [] if hasattr(module, "__path__"): return [modname for (importer, modname, ispkg) in iter_modules(module.__path__) if not modname.startswith("_")] return []
[ "def", "get_modules", "(", "modulename", "=", "None", ")", ":", "modulename", "=", "compat", ".", "ensure_not_unicode", "(", "modulename", ")", "if", "not", "modulename", ":", "try", ":", "return", "(", "[", "modname", "for", "(", "importer", ",", "modname...
Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages.
[ "Return", "a", "list", "of", "modules", "and", "packages", "under", "modulename", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/pydocutils.py#L64-L91
train
228,324
jorgenschaefer/elpy
elpy/rpc.py
JSONRPCServer.read_json
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)
python
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)
[ "def", "read_json", "(", "self", ")", ":", "line", "=", "self", ".", "stdin", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "raise", "EOFError", "(", ")", "return", "json", ".", "loads", "(", "line", ")" ]
Read a single line and decode it as JSON. Can raise an EOFError() when the input source was closed.
[ "Read", "a", "single", "line", "and", "decode", "it", "as", "JSON", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/rpc.py#L59-L68
train
228,325
jorgenschaefer/elpy
elpy/rpc.py
JSONRPCServer.write_json
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()
python
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()
[ "def", "write_json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "stdout", ".", "write", "(", "json", ".", "dumps", "(", "kwargs", ")", "+", "\"\\n\"", ")", "self", ".", "stdout", ".", "flush", "(", ")" ]
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.
[ "Write", "an", "JSON", "object", "on", "a", "single", "line", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/rpc.py#L70-L78
train
228,326
jorgenschaefer/elpy
elpy/rpc.py
JSONRPCServer.handle_request
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 respond with an error response to them. """ request = self.read_json() if 'method' not in request: raise ValueError("Received a bad request: {0}" .format(request)) method_name = request['method'] request_id = request.get('id', None) params = request.get('params') or [] try: method = getattr(self, "rpc_" + method_name, None) if method is not None: result = method(*params) else: result = self.handle(method_name, params) if request_id is not None: self.write_json(result=result, id=request_id) except Fault as fault: error = {"message": fault.message, "code": fault.code} if fault.data is not None: error["data"] = fault.data self.write_json(error=error, id=request_id) except Exception as e: error = {"message": str(e), "code": 500, "data": {"traceback": traceback.format_exc()}} self.write_json(error=error, id=request_id)
python
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 respond with an error response to them. """ request = self.read_json() if 'method' not in request: raise ValueError("Received a bad request: {0}" .format(request)) method_name = request['method'] request_id = request.get('id', None) params = request.get('params') or [] try: method = getattr(self, "rpc_" + method_name, None) if method is not None: result = method(*params) else: result = self.handle(method_name, params) if request_id is not None: self.write_json(result=result, id=request_id) except Fault as fault: error = {"message": fault.message, "code": fault.code} if fault.data is not None: error["data"] = fault.data self.write_json(error=error, id=request_id) except Exception as e: error = {"message": str(e), "code": 500, "data": {"traceback": traceback.format_exc()}} self.write_json(error=error, id=request_id)
[ "def", "handle_request", "(", "self", ")", ":", "request", "=", "self", ".", "read_json", "(", ")", "if", "'method'", "not", "in", "request", ":", "raise", "ValueError", "(", "\"Received a bad request: {0}\"", ".", "format", "(", "request", ")", ")", "method...
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 to them.
[ "Handle", "a", "single", "JSON", "-", "RPC", "request", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/rpc.py#L80-L116
train
228,327
jorgenschaefer/elpy
elpy/server.py
get_source
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 delete_after_use, the file should be deleted once read. """ if not isinstance(fileobj, dict): return fileobj else: try: with io.open(fileobj["filename"], encoding="utf-8", errors="ignore") as f: return f.read() finally: if fileobj.get('delete_after_use'): try: os.remove(fileobj["filename"]) except: # pragma: no cover pass
python
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 delete_after_use, the file should be deleted once read. """ if not isinstance(fileobj, dict): return fileobj else: try: with io.open(fileobj["filename"], encoding="utf-8", errors="ignore") as f: return f.read() finally: if fileobj.get('delete_after_use'): try: os.remove(fileobj["filename"]) except: # pragma: no cover pass
[ "def", "get_source", "(", "fileobj", ")", ":", "if", "not", "isinstance", "(", "fileobj", ",", "dict", ")", ":", "return", "fileobj", "else", ":", "try", ":", "with", "io", ".", "open", "(", "fileobj", "[", "\"filename\"", "]", ",", "encoding", "=", ...
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 should be deleted once read.
[ "Translate", "fileobj", "into", "file", "contents", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L232-L255
train
228,328
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer._call_backend
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, **kwargs)
python
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, **kwargs)
[ "def", "_call_backend", "(", "self", ",", "method", ",", "default", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "meth", "=", "getattr", "(", "self", ".", "backend", ",", "method", ",", "None", ")", "if", "meth", "is", "None", ":", "return"...
Call the backend method with args. If there is currently no backend, return default.
[ "Call", "the", "backend", "method", "with", "args", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L36-L44
train
228,329
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_calltip
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)
python
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)
[ "def", "rpc_get_calltip", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_calltip\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get the calltip for the function at the offset.
[ "Get", "the", "calltip", "for", "the", "function", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L67-L72
train
228,330
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_oneline_docstring
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)
python
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)
[ "def", "rpc_get_oneline_docstring", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_oneline_docstring\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "o...
Get a oneline docstring for the symbol at the offset.
[ "Get", "a", "oneline", "docstring", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L74-L79
train
228,331
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_completions
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 results = list(dict((res['name'], res) for res in results) .values()) results.sort(key=lambda cand: _pysymbol_key(cand["name"])) return results
python
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 results = list(dict((res['name'], res) for res in results) .values()) results.sort(key=lambda cand: _pysymbol_key(cand["name"])) return results
[ "def", "rpc_get_completions", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "results", "=", "self", ".", "_call_backend", "(", "\"rpc_get_completions\"", ",", "[", "]", ",", "filename", ",", "get_source", "(", "source", ")", ",", "o...
Get a list of completion candidates for the symbol at offset.
[ "Get", "a", "list", "of", "completion", "candidates", "for", "the", "symbol", "at", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L81-L91
train
228,332
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_definition
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)
python
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)
[ "def", "rpc_get_definition", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_definition\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ...
Get the location of the definition for the symbol at the offset.
[ "Get", "the", "location", "of", "the", "definition", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L109-L114
train
228,333
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_assignment
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)
python
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)
[ "def", "rpc_get_assignment", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_assignment\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ...
Get the location of the assignment for the symbol at the offset.
[ "Get", "the", "location", "of", "the", "assignment", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L116-L121
train
228,334
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_docstring
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)
python
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)
[ "def", "rpc_get_docstring", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_docstring\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get the docstring for the symbol at the offset.
[ "Get", "the", "docstring", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L123-L128
train
228,335
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_pydoc_documentation
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), "Elpy Pydoc Documentation for %s", False) except (ImportError, pydoc.ErrorDuringImport): return None else: if isinstance(docstring, bytes): docstring = docstring.decode("utf-8", "replace") return docstring
python
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), "Elpy Pydoc Documentation for %s", False) except (ImportError, pydoc.ErrorDuringImport): return None else: if isinstance(docstring, bytes): docstring = docstring.decode("utf-8", "replace") return docstring
[ "def", "rpc_get_pydoc_documentation", "(", "self", ",", "symbol", ")", ":", "try", ":", "docstring", "=", "pydoc", ".", "render_doc", "(", "str", "(", "symbol", ")", ",", "\"Elpy Pydoc Documentation for %s\"", ",", "False", ")", "except", "(", "ImportError", "...
Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting.
[ "Get", "the", "Pydoc", "documentation", "for", "the", "given", "symbol", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L139-L155
train
228,336
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_refactor_options
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 elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") ref = refactor.Refactor(self.project_root, filename) return ref.get_refactor_options(start, end)
python
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 elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") ref = refactor.Refactor(self.project_root, filename) return ref.get_refactor_options(start, end)
[ "def", "rpc_get_refactor_options", "(", "self", ",", "filename", ",", "start", ",", "end", "=", "None", ")", ":", "try", ":", "from", "elpy", "import", "refactor", "except", ":", "raise", "ImportError", "(", "\"Rope not installed, refactorings unavailable\"", ")",...
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.
[ "Return", "a", "list", "of", "possible", "refactoring", "options", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L157-L170
train
228,337
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_refactor
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: raise ImportError("Rope not installed, refactorings unavailable") if args is None: args = () ref = refactor.Refactor(self.project_root, filename) return ref.get_changes(method, *args)
python
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: raise ImportError("Rope not installed, refactorings unavailable") if args is None: args = () ref = refactor.Refactor(self.project_root, filename) return ref.get_changes(method, *args)
[ "def", "rpc_refactor", "(", "self", ",", "filename", ",", "method", ",", "args", ")", ":", "try", ":", "from", "elpy", "import", "refactor", "except", ":", "raise", "ImportError", "(", "\"Rope not installed, refactorings unavailable\"", ")", "if", "args", "is", ...
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.
[ "Return", "a", "list", "of", "changes", "from", "the", "refactoring", "action", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L172-L186
train
228,338
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_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 implemented by current backend", code=400)
python
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 implemented by current backend", code=400)
[ "def", "rpc_get_names", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "source", "=", "get_source", "(", "source", ")", "if", "hasattr", "(", "self", ".", "backend", ",", "\"rpc_get_names\"", ")", ":", "return", "self", ".", "backe...
Get all possible names
[ "Get", "all", "possible", "names" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L199-L208
train
228,339
jorgenschaefer/elpy
elpy/jedibackend.py
pos_to_linecol
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 line, col
python
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 line, col
[ "def", "pos_to_linecol", "(", "text", ",", "pos", ")", ":", "line_start", "=", "text", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "pos", ")", "+", "1", "line", "=", "text", ".", "count", "(", "\"\\n\"", ",", "0", ",", "line_start", ")", "+", "1...
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.
[ "Return", "a", "tuple", "of", "line", "and", "column", "for", "offset", "pos", "in", "text", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L272-L283
train
228,340
jorgenschaefer/elpy
elpy/jedibackend.py
linecol_to_pos
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) if new_offset < 0: raise ValueError("Text does not have {0} lines." .format(line)) nth_newline_offset = new_offset + 1 offset = nth_newline_offset + col if offset > len(text): raise ValueError("Line {0} column {1} is not within the text" .format(line, col)) return offset
python
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) if new_offset < 0: raise ValueError("Text does not have {0} lines." .format(line)) nth_newline_offset = new_offset + 1 offset = nth_newline_offset + col if offset > len(text): raise ValueError("Line {0} column {1} is not within the text" .format(line, col)) return offset
[ "def", "linecol_to_pos", "(", "text", ",", "line", ",", "col", ")", ":", "nth_newline_offset", "=", "0", "for", "i", "in", "range", "(", "line", "-", "1", ")", ":", "new_offset", "=", "text", ".", "find", "(", "\"\\n\"", ",", "nth_newline_offset", ")",...
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.
[ "Return", "the", "offset", "of", "this", "line", "and", "column", "in", "text", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L286-L305
train
228,341
jorgenschaefer/elpy
elpy/jedibackend.py
JediBackend.rpc_get_oneline_docstring
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=column, path=filename, encoding='utf-8') assignments = run_with_debug(jedi, 'goto_assignments', source=source, line=line, column=column, path=filename, encoding='utf-8') if definitions: definition = definitions[0] else: definition = None if assignments: assignment = assignments[0] else: assignment = None if definition: # Get name if definition.type in ['function', 'class']: raw_name = definition.name name = '{}()'.format(raw_name) doc = definition.docstring().split('\n') elif definition.type in ['module']: raw_name = definition.name name = '{} {}'.format(raw_name, definition.type) doc = definition.docstring().split('\n') elif (definition.type in ['instance'] and hasattr(assignment, "name")): raw_name = assignment.name name = raw_name doc = assignment.docstring().split('\n') else: return None # Keep only the first paragraph that is not a function declaration lines = [] call = "{}(".format(raw_name) # last line doc.append('') for i in range(len(doc)): if doc[i] == '' and len(lines) != 0: paragraph = " ".join(lines) lines = [] if call != paragraph[0:len(call)]: break paragraph = "" continue lines.append(doc[i]) # Keep only the first sentence onelinedoc = paragraph.split('. ', 1) if len(onelinedoc) == 2: onelinedoc = onelinedoc[0] + '.' else: onelinedoc = onelinedoc[0] if onelinedoc == '': onelinedoc = "No documentation" return {"name": name, "doc": onelinedoc} return None
python
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=column, path=filename, encoding='utf-8') assignments = run_with_debug(jedi, 'goto_assignments', source=source, line=line, column=column, path=filename, encoding='utf-8') if definitions: definition = definitions[0] else: definition = None if assignments: assignment = assignments[0] else: assignment = None if definition: # Get name if definition.type in ['function', 'class']: raw_name = definition.name name = '{}()'.format(raw_name) doc = definition.docstring().split('\n') elif definition.type in ['module']: raw_name = definition.name name = '{} {}'.format(raw_name, definition.type) doc = definition.docstring().split('\n') elif (definition.type in ['instance'] and hasattr(assignment, "name")): raw_name = assignment.name name = raw_name doc = assignment.docstring().split('\n') else: return None # Keep only the first paragraph that is not a function declaration lines = [] call = "{}(".format(raw_name) # last line doc.append('') for i in range(len(doc)): if doc[i] == '' and len(lines) != 0: paragraph = " ".join(lines) lines = [] if call != paragraph[0:len(call)]: break paragraph = "" continue lines.append(doc[i]) # Keep only the first sentence onelinedoc = paragraph.split('. ', 1) if len(onelinedoc) == 2: onelinedoc = onelinedoc[0] + '.' else: onelinedoc = onelinedoc[0] if onelinedoc == '': onelinedoc = "No documentation" return {"name": name, "doc": onelinedoc} return None
[ "def", "rpc_get_oneline_docstring", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "line", ",", "column", "=", "pos_to_linecol", "(", "source", ",", "offset", ")", "definitions", "=", "run_with_debug", "(", "jedi", ",", "'goto_definition...
Return a oneline docstring for the symbol at offset
[ "Return", "a", "oneline", "docstring", "for", "the", "symbol", "at", "offset" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L155-L213
train
228,342
jorgenschaefer/elpy
elpy/jedibackend.py
JediBackend.rpc_get_usages
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, 'usages', source=source, line=line, column=column, path=filename, encoding='utf-8') if uses is None: return None result = [] for use in uses: if use.module_path == filename: offset = linecol_to_pos(source, use.line, use.column) elif use.module_path is not None: with open(use.module_path) as f: text = f.read() offset = linecol_to_pos(text, use.line, use.column) result.append({"name": use.name, "filename": use.module_path, "offset": offset}) return result
python
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, 'usages', source=source, line=line, column=column, path=filename, encoding='utf-8') if uses is None: return None result = [] for use in uses: if use.module_path == filename: offset = linecol_to_pos(source, use.line, use.column) elif use.module_path is not None: with open(use.module_path) as f: text = f.read() offset = linecol_to_pos(text, use.line, use.column) result.append({"name": use.name, "filename": use.module_path, "offset": offset}) return result
[ "def", "rpc_get_usages", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "line", ",", "column", "=", "pos_to_linecol", "(", "source", ",", "offset", ")", "uses", "=", "run_with_debug", "(", "jedi", ",", "'usages'", ",", "source", "=...
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.
[ "Return", "the", "uses", "of", "the", "symbol", "at", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L215-L241
train
228,343
jorgenschaefer/elpy
elpy/jedibackend.py
JediBackend.rpc_get_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, references=True) result = [] for name in names: if name.module_path == filename: offset = linecol_to_pos(source, name.line, name.column) elif name.module_path is not None: with open(name.module_path) as f: text = f.read() offset = linecol_to_pos(text, name.line, name.column) result.append({"name": name.name, "filename": name.module_path, "offset": offset}) return result
python
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, references=True) result = [] for name in names: if name.module_path == filename: offset = linecol_to_pos(source, name.line, name.column) elif name.module_path is not None: with open(name.module_path) as f: text = f.read() offset = linecol_to_pos(text, name.line, name.column) result.append({"name": name.name, "filename": name.module_path, "offset": offset}) return result
[ "def", "rpc_get_names", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "names", "=", "jedi", ".", "api", ".", "names", "(", "source", "=", "source", ",", "path", "=", "filename", ",", "encoding", "=", "'utf-8'", ",", "all_scopes"...
Return the list of possible names
[ "Return", "the", "list", "of", "possible", "names" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L243-L262
train
228,344
jorgenschaefer/elpy
elpy/refactor.py
options
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, 'doc': getattr(function, '__doc__', ''), 'args': []} function.refactor_notes.update(kwargs) return function return set_notes
python
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, 'doc': getattr(function, '__doc__', ''), 'args': []} function.refactor_notes.update(kwargs) return function return set_notes
[ "def", "options", "(", "description", ",", "*", "*", "kwargs", ")", ":", "def", "set_notes", "(", "function", ")", ":", "function", ".", "refactor_notes", "=", "{", "'name'", ":", "function", ".", "__name__", ",", "'category'", ":", "\"Miscellaneous\"", ",...
Decorator to set some options on a method.
[ "Decorator", "to", "set", "some", "options", "on", "a", "method", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L75-L86
train
228,345
jorgenschaefer/elpy
elpy/refactor.py
translate_changes
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(change, rope_change.ChangeSet): agenda.extend(change.changes) elif isinstance(change, rope_change.ChangeContents): result.append({'action': 'change', 'file': change.resource.real_path, 'contents': change.new_contents, 'diff': change.get_description()}) elif isinstance(change, rope_change.CreateFile): result.append({'action': 'create', 'type': 'file', 'file': change.resource.real_path}) elif isinstance(change, rope_change.CreateFolder): result.append({'action': 'create', 'type': 'directory', 'path': change.resource.real_path}) elif isinstance(change, rope_change.MoveResource): result.append({'action': 'move', 'type': ('directory' if change.new_resource.is_folder() else 'file'), 'source': change.resource.real_path, 'destination': change.new_resource.real_path}) elif isinstance(change, rope_change.RemoveResource): if change.resource.is_folder(): result.append({'action': 'delete', 'type': 'directory', 'path': change.resource.real_path}) else: result.append({'action': 'delete', 'type': 'file', 'file': change.resource.real_path}) return result
python
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(change, rope_change.ChangeSet): agenda.extend(change.changes) elif isinstance(change, rope_change.ChangeContents): result.append({'action': 'change', 'file': change.resource.real_path, 'contents': change.new_contents, 'diff': change.get_description()}) elif isinstance(change, rope_change.CreateFile): result.append({'action': 'create', 'type': 'file', 'file': change.resource.real_path}) elif isinstance(change, rope_change.CreateFolder): result.append({'action': 'create', 'type': 'directory', 'path': change.resource.real_path}) elif isinstance(change, rope_change.MoveResource): result.append({'action': 'move', 'type': ('directory' if change.new_resource.is_folder() else 'file'), 'source': change.resource.real_path, 'destination': change.new_resource.real_path}) elif isinstance(change, rope_change.RemoveResource): if change.resource.is_folder(): result.append({'action': 'delete', 'type': 'directory', 'path': change.resource.real_path}) else: result.append({'action': 'delete', 'type': 'file', 'file': change.resource.real_path}) return result
[ "def", "translate_changes", "(", "initial_change", ")", ":", "agenda", "=", "[", "initial_change", "]", "result", "=", "[", "]", "while", "agenda", ":", "change", "=", "agenda", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "change", ",", "rope_cha...
Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary.
[ "Translate", "rope", ".", "base", ".", "change", ".", "Change", "instances", "to", "dictionaries", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L328-L370
train
228,346
jorgenschaefer/elpy
elpy/refactor.py
Refactor.get_refactor_options
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_changes. The key 'args' contains a list of additional arguments required for get_changes. """ result = [] for symbol in dir(self): if not symbol.startswith("refactor_"): continue method = getattr(self, symbol) if not method.refactor_notes.get('available', True): continue category = method.refactor_notes['category'] if end is not None and category != 'Region': continue if end is None and category == 'Region': continue is_on_symbol = self._is_on_symbol(start) if not is_on_symbol and category in ('Symbol', 'Method'): continue requires_import = method.refactor_notes.get('only_on_imports', False) if requires_import and not self._is_on_import_statement(start): continue result.append(method.refactor_notes) return result
python
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_changes. The key 'args' contains a list of additional arguments required for get_changes. """ result = [] for symbol in dir(self): if not symbol.startswith("refactor_"): continue method = getattr(self, symbol) if not method.refactor_notes.get('available', True): continue category = method.refactor_notes['category'] if end is not None and category != 'Region': continue if end is None and category == 'Region': continue is_on_symbol = self._is_on_symbol(start) if not is_on_symbol and category in ('Symbol', 'Method'): continue requires_import = method.refactor_notes.get('only_on_imports', False) if requires_import and not self._is_on_import_statement(start): continue result.append(method.refactor_notes) return result
[ "def", "get_refactor_options", "(", "self", ",", "start", ",", "end", "=", "None", ")", ":", "result", "=", "[", "]", "for", "symbol", "in", "dir", "(", "self", ")", ":", "if", "not", "symbol", ".", "startswith", "(", "\"refactor_\"", ")", ":", "cont...
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 arguments required for get_changes.
[ "Return", "a", "list", "of", "options", "for", "refactoring", "at", "the", "given", "position", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L113-L145
train
228,347
jorgenschaefer/elpy
elpy/refactor.py
Refactor._is_on_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.strip() if line.startswith("import ") or line.startswith("from "): return True else: return False
python
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.strip() if line.startswith("import ") or line.startswith("from "): return True else: return False
[ "def", "_is_on_import_statement", "(", "self", ",", "offset", ")", ":", "data", "=", "self", ".", "resource", ".", "read", "(", ")", "bol", "=", "data", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "offset", ")", "+", "1", "eol", "=", "data", ".", ...
Does this offset point to an import statement?
[ "Does", "this", "offset", "point", "to", "an", "import", "statement?" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L147-L159
train
228,348
jorgenschaefer/elpy
elpy/refactor.py
Refactor._is_on_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 = worder.get_name_at(self.resource, offset) if word: return True else: return False
python
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 = worder.get_name_at(self.resource, offset) if word: return True else: return False
[ "def", "_is_on_symbol", "(", "self", ",", "offset", ")", ":", "if", "not", "ROPE_AVAILABLE", ":", "return", "False", "data", "=", "self", ".", "resource", ".", "read", "(", ")", "if", "offset", ">=", "len", "(", "data", ")", ":", "return", "False", "...
Is this offset on a symbol?
[ "Is", "this", "offset", "on", "a", "symbol?" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L161-L174
train
228,349
jorgenschaefer/elpy
elpy/refactor.py
Refactor.get_changes
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 action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete """ if not name.startswith("refactor_"): raise ValueError("Bad refactoring name {0}".format(name)) method = getattr(self, name) if not method.refactor_notes.get('available', True): raise RuntimeError("Method not available") return method(*args)
python
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 action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete """ if not name.startswith("refactor_"): raise ValueError("Bad refactoring name {0}".format(name)) method = getattr(self, name) if not method.refactor_notes.get('available', True): raise RuntimeError("Method not available") return method(*args)
[ "def", "get_changes", "(", "self", ",", "name", ",", "*", "args", ")", ":", "if", "not", "name", ".", "startswith", "(", "\"refactor_\"", ")", ":", "raise", "ValueError", "(", "\"Bad refactoring name {0}\"", ".", "format", "(", "name", ")", ")", "method", ...
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. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete
[ "Return", "a", "list", "of", "changes", "for", "the", "named", "refactoring", "action", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L176-L216
train
228,350
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_froms_to_imports
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)
python
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)
[ "def", "refactor_froms_to_imports", "(", "self", ",", "offset", ")", ":", "refactor", "=", "ImportOrganizer", "(", "self", ".", "project", ")", "changes", "=", "refactor", ".", "froms_to_imports", "(", "self", ".", "resource", ",", "offset", ")", "return", "...
Converting imports of the form "from ..." to "import ...".
[ "Converting", "imports", "of", "the", "form", "from", "...", "to", "import", "...", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L222-L226
train
228,351
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_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)
python
def refactor_organize_imports(self): """Clean up and organize imports.""" refactor = ImportOrganizer(self.project) changes = refactor.organize_imports(self.resource) return translate_changes(changes)
[ "def", "refactor_organize_imports", "(", "self", ")", ":", "refactor", "=", "ImportOrganizer", "(", "self", ".", "project", ")", "changes", "=", "refactor", ".", "organize_imports", "(", "self", ".", "resource", ")", "return", "translate_changes", "(", "changes"...
Clean up and organize imports.
[ "Clean", "up", "and", "organize", "imports", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L230-L234
train
228,352
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_module_to_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)
python
def refactor_module_to_package(self): """Convert the current module into a package.""" refactor = ModuleToPackage(self.project, self.resource) return self._get_changes(refactor)
[ "def", "refactor_module_to_package", "(", "self", ")", ":", "refactor", "=", "ModuleToPackage", "(", "self", ".", "project", ",", "self", ".", "resource", ")", "return", "self", ".", "_get_changes", "(", "refactor", ")" ]
Convert the current module into a package.
[ "Convert", "the", "current", "module", "into", "a", "package", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L238-L241
train
228,353
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_rename_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, new_name, in_hierarchy=in_hierarchy, docs=docs)
python
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, new_name, in_hierarchy=in_hierarchy, docs=docs)
[ "def", "refactor_rename_at_point", "(", "self", ",", "offset", ",", "new_name", ",", "in_hierarchy", ",", "docs", ")", ":", "try", ":", "refactor", "=", "Rename", "(", "self", ".", "project", ",", "self", ".", "resource", ",", "offset", ")", "except", "R...
Rename the symbol at point.
[ "Rename", "the", "symbol", "at", "point", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L252-L259
train
228,354
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_rename_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)
python
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)
[ "def", "refactor_rename_current_module", "(", "self", ",", "new_name", ")", ":", "refactor", "=", "Rename", "(", "self", ".", "project", ",", "self", ".", "resource", ",", "None", ")", "return", "self", ".", "_get_changes", "(", "refactor", ",", "new_name", ...
Rename the current module.
[ "Rename", "the", "current", "module", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L264-L267
train
228,355
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_move_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)
python
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)
[ "def", "refactor_move_module", "(", "self", ",", "new_name", ")", ":", "refactor", "=", "create_move", "(", "self", ".", "project", ",", "self", ".", "resource", ")", "resource", "=", "path_to_resource", "(", "self", ".", "project", ",", "new_name", ")", "...
Move the current module.
[ "Move", "the", "current", "module", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L273-L277
train
228,356
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_create_inline
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_changes(refactor, remove=True, only_current=False)
python
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_changes(refactor, remove=True, only_current=False)
[ "def", "refactor_create_inline", "(", "self", ",", "offset", ",", "only_this", ")", ":", "refactor", "=", "create_inline", "(", "self", ".", "project", ",", "self", ".", "resource", ",", "offset", ")", "if", "only_this", ":", "return", "self", ".", "_get_c...
Inline the function call at point.
[ "Inline", "the", "function", "call", "at", "point", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L283-L289
train
228,357
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_extract_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 )
python
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 )
[ "def", "refactor_extract_method", "(", "self", ",", "start", ",", "end", ",", "name", ",", "make_global", ")", ":", "refactor", "=", "ExtractMethod", "(", "self", ".", "project", ",", "self", ".", "resource", ",", "start", ",", "end", ")", "return", "sel...
Extract region as a method.
[ "Extract", "region", "as", "a", "method", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L297-L303
train
228,358
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_use_function
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=400 ) return self._get_changes(refactor)
python
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=400 ) return self._get_changes(refactor)
[ "def", "refactor_use_function", "(", "self", ",", "offset", ")", ":", "try", ":", "refactor", "=", "UseFunction", "(", "self", ".", "project", ",", "self", ".", "resource", ",", "offset", ")", "except", "RefactoringError", "as", "e", ":", "raise", "Fault",...
Use the function at point wherever possible.
[ "Use", "the", "function", "at", "point", "wherever", "possible", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L308-L317
train
228,359
clach04/python-tuya
pytuya/__init__.py
XenonDevice.generate_payload
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 via the 'dps' entry """ json_data = payload_dict[self.dev_type][command]['command'] if 'gwId' in json_data: json_data['gwId'] = self.id if 'devId' in json_data: json_data['devId'] = self.id if 'uid' in json_data: json_data['uid'] = self.id # still use id, no seperate uid if 't' in json_data: json_data['t'] = str(int(time.time())) if data is not None: json_data['dps'] = data # Create byte buffer from hex data json_payload = json.dumps(json_data) #print(json_payload) json_payload = json_payload.replace(' ', '') # if spaces are not removed device does not respond! json_payload = json_payload.encode('utf-8') log.debug('json_payload=%r', json_payload) if command == SET: # need to encrypt #print('json_payload %r' % json_payload) self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new json_payload = self.cipher.encrypt(json_payload) #print('crypted json_payload %r' % json_payload) preMd5String = b'data=' + json_payload + b'||lpv=' + PROTOCOL_VERSION_BYTES + b'||' + self.local_key #print('preMd5String %r' % preMd5String) m = md5() m.update(preMd5String) #print(repr(m.digest())) hexdigest = m.hexdigest() #print(hexdigest) #print(hexdigest[8:][:16]) json_payload = PROTOCOL_VERSION_BYTES + hexdigest[8:][:16].encode('latin1') + json_payload #print('data_to_send') #print(json_payload) #print('crypted json_payload (%d) %r' % (len(json_payload), json_payload)) #print('json_payload %r' % repr(json_payload)) #print('json_payload len %r' % len(json_payload)) #print(bin2hex(json_payload)) self.cipher = None # expect to connect and then disconnect to set new postfix_payload = hex2bin(bin2hex(json_payload) + payload_dict[self.dev_type]['suffix']) #print('postfix_payload %r' % postfix_payload) #print('postfix_payload %r' % len(postfix_payload)) #print('postfix_payload %x' % len(postfix_payload)) #print('postfix_payload %r' % hex(len(postfix_payload))) assert len(postfix_payload) <= 0xff postfix_payload_hex_len = '%x' % len(postfix_payload) # TODO this assumes a single byte 0-255 (0x00-0xff) buffer = hex2bin( payload_dict[self.dev_type]['prefix'] + payload_dict[self.dev_type][command]['hexByte'] + '000000' + postfix_payload_hex_len ) + postfix_payload #print('command', command) #print('prefix') #print(payload_dict[self.dev_type][command]['prefix']) #print(repr(buffer)) #print(bin2hex(buffer, pretty=True)) #print(bin2hex(buffer, pretty=False)) #print('full buffer(%d) %r' % (len(buffer), buffer)) return buffer
python
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 via the 'dps' entry """ json_data = payload_dict[self.dev_type][command]['command'] if 'gwId' in json_data: json_data['gwId'] = self.id if 'devId' in json_data: json_data['devId'] = self.id if 'uid' in json_data: json_data['uid'] = self.id # still use id, no seperate uid if 't' in json_data: json_data['t'] = str(int(time.time())) if data is not None: json_data['dps'] = data # Create byte buffer from hex data json_payload = json.dumps(json_data) #print(json_payload) json_payload = json_payload.replace(' ', '') # if spaces are not removed device does not respond! json_payload = json_payload.encode('utf-8') log.debug('json_payload=%r', json_payload) if command == SET: # need to encrypt #print('json_payload %r' % json_payload) self.cipher = AESCipher(self.local_key) # expect to connect and then disconnect to set new json_payload = self.cipher.encrypt(json_payload) #print('crypted json_payload %r' % json_payload) preMd5String = b'data=' + json_payload + b'||lpv=' + PROTOCOL_VERSION_BYTES + b'||' + self.local_key #print('preMd5String %r' % preMd5String) m = md5() m.update(preMd5String) #print(repr(m.digest())) hexdigest = m.hexdigest() #print(hexdigest) #print(hexdigest[8:][:16]) json_payload = PROTOCOL_VERSION_BYTES + hexdigest[8:][:16].encode('latin1') + json_payload #print('data_to_send') #print(json_payload) #print('crypted json_payload (%d) %r' % (len(json_payload), json_payload)) #print('json_payload %r' % repr(json_payload)) #print('json_payload len %r' % len(json_payload)) #print(bin2hex(json_payload)) self.cipher = None # expect to connect and then disconnect to set new postfix_payload = hex2bin(bin2hex(json_payload) + payload_dict[self.dev_type]['suffix']) #print('postfix_payload %r' % postfix_payload) #print('postfix_payload %r' % len(postfix_payload)) #print('postfix_payload %x' % len(postfix_payload)) #print('postfix_payload %r' % hex(len(postfix_payload))) assert len(postfix_payload) <= 0xff postfix_payload_hex_len = '%x' % len(postfix_payload) # TODO this assumes a single byte 0-255 (0x00-0xff) buffer = hex2bin( payload_dict[self.dev_type]['prefix'] + payload_dict[self.dev_type][command]['hexByte'] + '000000' + postfix_payload_hex_len ) + postfix_payload #print('command', command) #print('prefix') #print(payload_dict[self.dev_type][command]['prefix']) #print(repr(buffer)) #print(bin2hex(buffer, pretty=True)) #print(bin2hex(buffer, pretty=False)) #print('full buffer(%d) %r' % (len(buffer), buffer)) return buffer
[ "def", "generate_payload", "(", "self", ",", "command", ",", "data", "=", "None", ")", ":", "json_data", "=", "payload_dict", "[", "self", ".", "dev_type", "]", "[", "command", "]", "[", "'command'", "]", "if", "'gwId'", "in", "json_data", ":", "json_dat...
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
[ "Generate", "the", "payload", "to", "send", "." ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L176-L249
train
228,360
clach04/python-tuya
pytuya/__init__.py
BulbDevice.set_colour
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 <= r <= 255: raise ValueError("The value for red needs to be between 0 and 255.") if not 0 <= g <= 255: raise ValueError("The value for green needs to be between 0 and 255.") if not 0 <= b <= 255: raise ValueError("The value for blue needs to be between 0 and 255.") #print(BulbDevice) hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b) payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR, self.DPS_INDEX_COLOUR: hexvalue}) data = self._send_receive(payload) return data
python
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 <= r <= 255: raise ValueError("The value for red needs to be between 0 and 255.") if not 0 <= g <= 255: raise ValueError("The value for green needs to be between 0 and 255.") if not 0 <= b <= 255: raise ValueError("The value for blue needs to be between 0 and 255.") #print(BulbDevice) hexvalue = BulbDevice._rgb_to_hexvalue(r, g, b) payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_COLOUR, self.DPS_INDEX_COLOUR: hexvalue}) data = self._send_receive(payload) return data
[ "def", "set_colour", "(", "self", ",", "r", ",", "g", ",", "b", ")", ":", "if", "not", "0", "<=", "r", "<=", "255", ":", "raise", "ValueError", "(", "\"The value for red needs to be between 0 and 255.\"", ")", "if", "not", "0", "<=", "g", "<=", "255", ...
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.
[ "Set", "colour", "of", "an", "rgb", "bulb", "." ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L437-L460
train
228,361
clach04/python-tuya
pytuya/__init__.py
BulbDevice.set_white
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: raise ValueError("The brightness needs to be between 25 and 255.") if not 0 <= colourtemp <= 255: raise ValueError("The colour temperature needs to be between 0 and 255.") payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_WHITE, self.DPS_INDEX_BRIGHTNESS: brightness, self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return data
python
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: raise ValueError("The brightness needs to be between 25 and 255.") if not 0 <= colourtemp <= 255: raise ValueError("The colour temperature needs to be between 0 and 255.") payload = self.generate_payload(SET, { self.DPS_INDEX_MODE: self.DPS_MODE_WHITE, self.DPS_INDEX_BRIGHTNESS: brightness, self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return data
[ "def", "set_white", "(", "self", ",", "brightness", ",", "colourtemp", ")", ":", "if", "not", "25", "<=", "brightness", "<=", "255", ":", "raise", "ValueError", "(", "\"The brightness needs to be between 25 and 255.\"", ")", "if", "not", "0", "<=", "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).
[ "Set", "white", "coloured", "theme", "of", "an", "rgb", "bulb", "." ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L462-L481
train
228,362
clach04/python-tuya
pytuya/__init__.py
BulbDevice.set_brightness
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.") payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness}) data = self._send_receive(payload) return data
python
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.") payload = self.generate_payload(SET, {self.DPS_INDEX_BRIGHTNESS: brightness}) data = self._send_receive(payload) return data
[ "def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "if", "not", "25", "<=", "brightness", "<=", "255", ":", "raise", "ValueError", "(", "\"The brightness needs to be between 25 and 255.\"", ")", "payload", "=", "self", ".", "generate_payload", "(",...
Set the brightness value of an rgb bulb. Args: brightness(int): Value for the brightness (25-255).
[ "Set", "the", "brightness", "value", "of", "an", "rgb", "bulb", "." ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L483-L495
train
228,363
clach04/python-tuya
pytuya/__init__.py
BulbDevice.set_colourtemp
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.") payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return data
python
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.") payload = self.generate_payload(SET, {self.DPS_INDEX_COLOURTEMP: colourtemp}) data = self._send_receive(payload) return data
[ "def", "set_colourtemp", "(", "self", ",", "colourtemp", ")", ":", "if", "not", "0", "<=", "colourtemp", "<=", "255", ":", "raise", "ValueError", "(", "\"The colour temperature needs to be between 0 and 255.\"", ")", "payload", "=", "self", ".", "generate_payload", ...
Set the colour temperature of an rgb bulb. Args: colourtemp(int): Value for the colour temperature (0-255).
[ "Set", "the", "colour", "temperature", "of", "an", "rgb", "bulb", "." ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L497-L509
train
228,364
clach04/python-tuya
pytuya/__init__.py
BulbDevice.colour_rgb
def colour_rgb(self): """Return colour as RGB value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_rgb(hexvalue)
python
def colour_rgb(self): """Return colour as RGB value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_rgb(hexvalue)
[ "def", "colour_rgb", "(", "self", ")", ":", "hexvalue", "=", "self", ".", "status", "(", ")", "[", "self", ".", "DPS", "]", "[", "self", ".", "DPS_INDEX_COLOUR", "]", "return", "BulbDevice", ".", "_hexvalue_to_rgb", "(", "hexvalue", ")" ]
Return colour as RGB value
[ "Return", "colour", "as", "RGB", "value" ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L519-L522
train
228,365
clach04/python-tuya
pytuya/__init__.py
BulbDevice.colour_hsv
def colour_hsv(self): """Return colour as HSV value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_hsv(hexvalue)
python
def colour_hsv(self): """Return colour as HSV value""" hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR] return BulbDevice._hexvalue_to_hsv(hexvalue)
[ "def", "colour_hsv", "(", "self", ")", ":", "hexvalue", "=", "self", ".", "status", "(", ")", "[", "self", ".", "DPS", "]", "[", "self", ".", "DPS_INDEX_COLOUR", "]", "return", "BulbDevice", ".", "_hexvalue_to_hsv", "(", "hexvalue", ")" ]
Return colour as HSV value
[ "Return", "colour", "as", "HSV", "value" ]
7b89d38c56f6e25700e2a333000d25bc8d923622
https://github.com/clach04/python-tuya/blob/7b89d38c56f6e25700e2a333000d25bc8d923622/pytuya/__init__.py#L524-L527
train
228,366
bitcraze/crazyflie-lib-python
cflib/crazyflie/high_level_commander.py
HighLevelCommander.set_group_mask
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, group_mask))
python
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, group_mask))
[ "def", "set_group_mask", "(", "self", ",", "group_mask", "=", "ALL_GROUPS", ")", ":", "self", ".", "_send_packet", "(", "struct", ".", "pack", "(", "'<BB'", ",", "self", ".", "COMMAND_SET_GROUP_MASK", ",", "group_mask", ")", ")" ]
Set the group mask that the Crazyflie belongs to :param group_mask: mask for which groups this CF belongs to
[ "Set", "the", "group", "mask", "that", "the", "Crazyflie", "belongs", "to" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L63-L71
train
228,367
bitcraze/crazyflie-lib-python
cflib/crazyflie/high_level_commander.py
HighLevelCommander.takeoff
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) :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBff', self.COMMAND_TAKEOFF, group_mask, absolute_height_m, duration_s))
python
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) :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBff', self.COMMAND_TAKEOFF, group_mask, absolute_height_m, duration_s))
[ "def", "takeoff", "(", "self", ",", "absolute_height_m", ",", "duration_s", ",", "group_mask", "=", "ALL_GROUPS", ")", ":", "self", ".", "_send_packet", "(", "struct", ".", "pack", "(", "'<BBff'", ",", "self", ".", "COMMAND_TAKEOFF", ",", "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
[ "vertical", "takeoff", "from", "current", "x", "-", "y", "position", "to", "given", "height" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L73-L86
train
228,368
bitcraze/crazyflie-lib-python
cflib/crazyflie/high_level_commander.py
HighLevelCommander.land
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 group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBff', self.COMMAND_LAND, group_mask, absolute_height_m, duration_s))
python
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 group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBff', self.COMMAND_LAND, group_mask, absolute_height_m, duration_s))
[ "def", "land", "(", "self", ",", "absolute_height_m", ",", "duration_s", ",", "group_mask", "=", "ALL_GROUPS", ")", ":", "self", ".", "_send_packet", "(", "struct", ".", "pack", "(", "'<BBff'", ",", "self", ".", "COMMAND_LAND", ",", "group_mask", ",", "abs...
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
[ "vertical", "land", "from", "current", "x", "-", "y", "position", "to", "given", "height" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L88-L101
train
228,369
bitcraze/crazyflie-lib-python
cflib/crazyflie/high_level_commander.py
HighLevelCommander.go_to
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 the position (s) :param relative: True if x, y, z is relative to the current position :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBBfffff', self.COMMAND_GO_TO, group_mask, relative, x, y, z, yaw, duration_s))
python
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 the position (s) :param relative: True if x, y, z is relative to the current position :param group_mask: mask for which CFs this should apply to """ self._send_packet(struct.pack('<BBBfffff', self.COMMAND_GO_TO, group_mask, relative, x, y, z, yaw, duration_s))
[ "def", "go_to", "(", "self", ",", "x", ",", "y", ",", "z", ",", "yaw", ",", "duration_s", ",", "relative", "=", "False", ",", "group_mask", "=", "ALL_GROUPS", ")", ":", "self", ".", "_send_packet", "(", "struct", ".", "pack", "(", "'<BBBfffff'", ",",...
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_mask: mask for which CFs this should apply to
[ "Go", "to", "an", "absolute", "or", "relative", "position" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L114-L133
train
228,370
bitcraze/crazyflie-lib-python
cflib/crazyflie/high_level_commander.py
HighLevelCommander.start_trajectory
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) :param time_scale: time factor; 1.0 = original speed; >1.0: slower; <1.0: faster :param relative: set to True, if trajectory should be shifted to current setpoint :param reversed: set to True, if trajectory should be executed in reverse :param group_mask: mask for which CFs this should apply to :return: """ self._send_packet(struct.pack('<BBBBBf', self.COMMAND_START_TRAJECTORY, group_mask, relative, reversed, trajectory_id, time_scale))
python
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) :param time_scale: time factor; 1.0 = original speed; >1.0: slower; <1.0: faster :param relative: set to True, if trajectory should be shifted to current setpoint :param reversed: set to True, if trajectory should be executed in reverse :param group_mask: mask for which CFs this should apply to :return: """ self._send_packet(struct.pack('<BBBBBf', self.COMMAND_START_TRAJECTORY, group_mask, relative, reversed, trajectory_id, time_scale))
[ "def", "start_trajectory", "(", "self", ",", "trajectory_id", ",", "time_scale", "=", "1.0", ",", "relative", "=", "False", ",", "reversed", "=", "False", ",", "group_mask", "=", "ALL_GROUPS", ")", ":", "self", ".", "_send_packet", "(", "struct", ".", "pac...
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 :param relative: set to True, if trajectory should be shifted to current setpoint :param reversed: set to True, if trajectory should be executed in reverse :param group_mask: mask for which CFs this should apply to :return:
[ "starts", "executing", "a", "specified", "trajectory" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L135-L158
train
228,371
bitcraze/crazyflie-lib-python
cflib/crazyflie/high_level_commander.py
HighLevelCommander.define_trajectory
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 :return: """ self._send_packet(struct.pack('<BBBBIB', self.COMMAND_DEFINE_TRAJECTORY, trajectory_id, self.TRAJECTORY_LOCATION_MEM, self.TRAJECTORY_TYPE_POLY4D, offset, n_pieces))
python
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 :return: """ self._send_packet(struct.pack('<BBBBIB', self.COMMAND_DEFINE_TRAJECTORY, trajectory_id, self.TRAJECTORY_LOCATION_MEM, self.TRAJECTORY_TYPE_POLY4D, offset, n_pieces))
[ "def", "define_trajectory", "(", "self", ",", "trajectory_id", ",", "offset", ",", "n_pieces", ")", ":", "self", ".", "_send_packet", "(", "struct", ".", "pack", "(", "'<BBBBIB'", ",", "self", ".", "COMMAND_DEFINE_TRAJECTORY", ",", "trajectory_id", ",", "self"...
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:
[ "Define", "a", "trajectory", "that", "has", "previously", "been", "uploaded", "to", "memory", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/high_level_commander.py#L160-L175
train
228,372
bitcraze/crazyflie-lib-python
examples/flash-memory.py
choose
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) except ValueError: index = -1 if not (index - 1) in range(len(items)): print('Aborting.') return None return items[index - 1]
python
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) except ValueError: index = -1 if not (index - 1) in range(len(items)): print('Aborting.') return None return items[index - 1]
[ "def", "choose", "(", "items", ",", "title_text", ",", "question_text", ")", ":", "print", "(", "title_text", ")", "for", "i", ",", "item", "in", "enumerate", "(", "items", ",", "start", "=", "1", ")", ":", "print", "(", "'%d) %s'", "%", "(", "i", ...
Interactively choose one of the items.
[ "Interactively", "choose", "one", "of", "the", "items", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L110-L129
train
228,373
bitcraze/crazyflie-lib-python
examples/flash-memory.py
scan
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, _ in available] if not interfaces: return None return choose(interfaces, 'Crazyflies found:', 'Select interface: ')
python
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, _ in available] if not interfaces: return None return choose(interfaces, 'Crazyflies found:', 'Select interface: ')
[ "def", "scan", "(", ")", ":", "# Initiate the low level drivers", "cflib", ".", "crtp", ".", "init_drivers", "(", "enable_debug_driver", "=", "False", ")", "# Scan for Crazyflies", "print", "(", "'Scanning interfaces for Crazyflies...'", ")", "available", "=", "cflib", ...
Scan for Crazyflie and return its URI.
[ "Scan", "for", "Crazyflie", "and", "return", "its", "URI", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L132-L147
train
228,374
bitcraze/crazyflie-lib-python
examples/flash-memory.py
Flasher.connect
def connect(self): """ Connect to the crazyflie. """ print('Connecting to %s' % self._link_uri) self._cf.open_link(self._link_uri)
python
def connect(self): """ Connect to the crazyflie. """ print('Connecting to %s' % self._link_uri) self._cf.open_link(self._link_uri)
[ "def", "connect", "(", "self", ")", ":", "print", "(", "'Connecting to %s'", "%", "self", ".", "_link_uri", ")", "self", ".", "_cf", ".", "open_link", "(", "self", ".", "_link_uri", ")" ]
Connect to the crazyflie.
[ "Connect", "to", "the", "crazyflie", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L55-L60
train
228,375
bitcraze/crazyflie-lib-python
examples/flash-memory.py
Flasher.wait_for_connection
def wait_for_connection(self, timeout=10): """ Busy loop until connection is established. Will abort after timeout (seconds). Return value is a boolean, whether connection could be established. """ start_time = datetime.datetime.now() while True: if self.connected: return True now = datetime.datetime.now() if (now - start_time).total_seconds() > timeout: return False time.sleep(0.5)
python
def wait_for_connection(self, timeout=10): """ Busy loop until connection is established. Will abort after timeout (seconds). Return value is a boolean, whether connection could be established. """ start_time = datetime.datetime.now() while True: if self.connected: return True now = datetime.datetime.now() if (now - start_time).total_seconds() > timeout: return False time.sleep(0.5)
[ "def", "wait_for_connection", "(", "self", ",", "timeout", "=", "10", ")", ":", "start_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "while", "True", ":", "if", "self", ".", "connected", ":", "return", "True", "now", "=", "datetime", "...
Busy loop until connection is established. Will abort after timeout (seconds). Return value is a boolean, whether connection could be established.
[ "Busy", "loop", "until", "connection", "is", "established", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L66-L81
train
228,376
bitcraze/crazyflie-lib-python
examples/flash-memory.py
Flasher.search_memories
def search_memories(self): """ Search and return list of 1-wire memories. """ if not self.connected: raise NotConnected() return self._cf.mem.get_mems(MemoryElement.TYPE_1W)
python
def search_memories(self): """ Search and return list of 1-wire memories. """ if not self.connected: raise NotConnected() return self._cf.mem.get_mems(MemoryElement.TYPE_1W)
[ "def", "search_memories", "(", "self", ")", ":", "if", "not", "self", ".", "connected", ":", "raise", "NotConnected", "(", ")", "return", "self", ".", "_cf", ".", "mem", ".", "get_mems", "(", "MemoryElement", ".", "TYPE_1W", ")" ]
Search and return list of 1-wire memories.
[ "Search", "and", "return", "list", "of", "1", "-", "wire", "memories", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/flash-memory.py#L83-L89
train
228,377
bitcraze/crazyflie-lib-python
examples/cfbridge.py
RadioBridge._stab_log_data
def _stab_log_data(self, timestamp, data, logconf): """Callback froma the log API when data arrives""" print('[%d][%s]: %s' % (timestamp, logconf.name, data))
python
def _stab_log_data(self, timestamp, data, logconf): """Callback froma the log API when data arrives""" print('[%d][%s]: %s' % (timestamp, logconf.name, data))
[ "def", "_stab_log_data", "(", "self", ",", "timestamp", ",", "data", ",", "logconf", ")", ":", "print", "(", "'[%d][%s]: %s'", "%", "(", "timestamp", ",", "logconf", ".", "name", ",", "data", ")", ")" ]
Callback froma the log API when data arrives
[ "Callback", "froma", "the", "log", "API", "when", "data", "arrives" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/cfbridge.py#L93-L95
train
228,378
bitcraze/crazyflie-lib-python
cflib/crazyflie/platformservice.py
PlatformService.fetch_platform_informations
def fetch_platform_informations(self, callback): """ Fetch platform info from the firmware Should be called at the earliest in the connection sequence """ self._protocolVersion = -1 self._callback = callback self._request_protocol_version()
python
def fetch_platform_informations(self, callback): """ Fetch platform info from the firmware Should be called at the earliest in the connection sequence """ self._protocolVersion = -1 self._callback = callback self._request_protocol_version()
[ "def", "fetch_platform_informations", "(", "self", ",", "callback", ")", ":", "self", ".", "_protocolVersion", "=", "-", "1", "self", ".", "_callback", "=", "callback", "self", ".", "_request_protocol_version", "(", ")" ]
Fetch platform info from the firmware Should be called at the earliest in the connection sequence
[ "Fetch", "platform", "info", "from", "the", "firmware", "Should", "be", "called", "at", "the", "earliest", "in", "the", "connection", "sequence" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/platformservice.py#L74-L83
train
228,379
bitcraze/crazyflie-lib-python
cflib/crtp/usbdriver.py
UsbDriver.receive_packet
def receive_packet(self, time=0): """ Receive a packet though the link. This call is blocking but will timeout and return None if a timeout is supplied. """ if time == 0: try: return self.in_queue.get(False) except queue.Empty: return None elif time < 0: try: return self.in_queue.get(True) except queue.Empty: return None else: try: return self.in_queue.get(True, time) except queue.Empty: return None
python
def receive_packet(self, time=0): """ Receive a packet though the link. This call is blocking but will timeout and return None if a timeout is supplied. """ if time == 0: try: return self.in_queue.get(False) except queue.Empty: return None elif time < 0: try: return self.in_queue.get(True) except queue.Empty: return None else: try: return self.in_queue.get(True, time) except queue.Empty: return None
[ "def", "receive_packet", "(", "self", ",", "time", "=", "0", ")", ":", "if", "time", "==", "0", ":", "try", ":", "return", "self", ".", "in_queue", ".", "get", "(", "False", ")", "except", "queue", ".", "Empty", ":", "return", "None", "elif", "time...
Receive a packet though the link. This call is blocking but will timeout and return None if a timeout is supplied.
[ "Receive", "a", "packet", "though", "the", "link", ".", "This", "call", "is", "blocking", "but", "will", "timeout", "and", "return", "None", "if", "a", "timeout", "is", "supplied", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/usbdriver.py#L116-L135
train
228,380
bitcraze/crazyflie-lib-python
cflib/utils/callbacks.py
Caller.add_callback
def add_callback(self, cb): """ Register cb as a new callback. Will not register duplicates. """ if ((cb in self.callbacks) is False): self.callbacks.append(cb)
python
def add_callback(self, cb): """ Register cb as a new callback. Will not register duplicates. """ if ((cb in self.callbacks) is False): self.callbacks.append(cb)
[ "def", "add_callback", "(", "self", ",", "cb", ")", ":", "if", "(", "(", "cb", "in", "self", ".", "callbacks", ")", "is", "False", ")", ":", "self", ".", "callbacks", ".", "append", "(", "cb", ")" ]
Register cb as a new callback. Will not register duplicates.
[ "Register", "cb", "as", "a", "new", "callback", ".", "Will", "not", "register", "duplicates", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/utils/callbacks.py#L42-L45
train
228,381
bitcraze/crazyflie-lib-python
cflib/bootloader/__init__.py
Bootloader.read_cf1_config
def read_cf1_config(self): """Read a flash page from the specified target""" target = self._cload.targets[0xFF] config_page = target.flash_pages - 1 return self._cload.read_flash(addr=0xFF, page=config_page)
python
def read_cf1_config(self): """Read a flash page from the specified target""" target = self._cload.targets[0xFF] config_page = target.flash_pages - 1 return self._cload.read_flash(addr=0xFF, page=config_page)
[ "def", "read_cf1_config", "(", "self", ")", ":", "target", "=", "self", ".", "_cload", ".", "targets", "[", "0xFF", "]", "config_page", "=", "target", ".", "flash_pages", "-", "1", "return", "self", ".", "_cload", ".", "read_flash", "(", "addr", "=", "...
Read a flash page from the specified target
[ "Read", "a", "flash", "page", "from", "the", "specified", "target" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/__init__.py#L122-L127
train
228,382
bitcraze/crazyflie-lib-python
cflib/drivers/crazyradio.py
Crazyradio.set_channel
def set_channel(self, channel): """ Set the radio channel to be used """ if channel != self.current_channel: _send_vendor_setup(self.handle, SET_RADIO_CHANNEL, channel, 0, ()) self.current_channel = channel
python
def set_channel(self, channel): """ Set the radio channel to be used """ if channel != self.current_channel: _send_vendor_setup(self.handle, SET_RADIO_CHANNEL, channel, 0, ()) self.current_channel = channel
[ "def", "set_channel", "(", "self", ",", "channel", ")", ":", "if", "channel", "!=", "self", ".", "current_channel", ":", "_send_vendor_setup", "(", "self", ".", "handle", ",", "SET_RADIO_CHANNEL", ",", "channel", ",", "0", ",", "(", ")", ")", "self", "."...
Set the radio channel to be used
[ "Set", "the", "radio", "channel", "to", "be", "used" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L185-L189
train
228,383
bitcraze/crazyflie-lib-python
cflib/drivers/crazyradio.py
Crazyradio.set_address
def set_address(self, address): """ Set the radio address to be used""" if len(address) != 5: raise Exception('Crazyradio: the radio address shall be 5' ' bytes long') if address != self.current_address: _send_vendor_setup(self.handle, SET_RADIO_ADDRESS, 0, 0, address) self.current_address = address
python
def set_address(self, address): """ Set the radio address to be used""" if len(address) != 5: raise Exception('Crazyradio: the radio address shall be 5' ' bytes long') if address != self.current_address: _send_vendor_setup(self.handle, SET_RADIO_ADDRESS, 0, 0, address) self.current_address = address
[ "def", "set_address", "(", "self", ",", "address", ")", ":", "if", "len", "(", "address", ")", "!=", "5", ":", "raise", "Exception", "(", "'Crazyradio: the radio address shall be 5'", "' bytes long'", ")", "if", "address", "!=", "self", ".", "current_address", ...
Set the radio address to be used
[ "Set", "the", "radio", "address", "to", "be", "used" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L191-L198
train
228,384
bitcraze/crazyflie-lib-python
cflib/drivers/crazyradio.py
Crazyradio.set_data_rate
def set_data_rate(self, datarate): """ Set the radio datarate to be used """ if datarate != self.current_datarate: _send_vendor_setup(self.handle, SET_DATA_RATE, datarate, 0, ()) self.current_datarate = datarate
python
def set_data_rate(self, datarate): """ Set the radio datarate to be used """ if datarate != self.current_datarate: _send_vendor_setup(self.handle, SET_DATA_RATE, datarate, 0, ()) self.current_datarate = datarate
[ "def", "set_data_rate", "(", "self", ",", "datarate", ")", ":", "if", "datarate", "!=", "self", ".", "current_datarate", ":", "_send_vendor_setup", "(", "self", ".", "handle", ",", "SET_DATA_RATE", ",", "datarate", ",", "0", ",", "(", ")", ")", "self", "...
Set the radio datarate to be used
[ "Set", "the", "radio", "datarate", "to", "be", "used" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L200-L204
train
228,385
bitcraze/crazyflie-lib-python
cflib/drivers/crazyradio.py
Crazyradio.set_arc
def set_arc(self, arc): """ Set the ACK retry count for radio communication """ _send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ()) self.arc = arc
python
def set_arc(self, arc): """ Set the ACK retry count for radio communication """ _send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ()) self.arc = arc
[ "def", "set_arc", "(", "self", ",", "arc", ")", ":", "_send_vendor_setup", "(", "self", ".", "handle", ",", "SET_RADIO_ARC", ",", "arc", ",", "0", ",", "(", ")", ")", "self", ".", "arc", "=", "arc" ]
Set the ACK retry count for radio communication
[ "Set", "the", "ACK", "retry", "count", "for", "radio", "communication" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L210-L213
train
228,386
bitcraze/crazyflie-lib-python
cflib/drivers/crazyradio.py
Crazyradio.set_ard_time
def set_ard_time(self, us): """ Set the ACK retry delay for radio communication """ # Auto Retransmit Delay: # 0000 - Wait 250uS # 0001 - Wait 500uS # 0010 - Wait 750uS # ........ # 1111 - Wait 4000uS # Round down, to value representing a multiple of 250uS t = int((us / 250) - 1) if (t < 0): t = 0 if (t > 0xF): t = 0xF _send_vendor_setup(self.handle, SET_RADIO_ARD, t, 0, ())
python
def set_ard_time(self, us): """ Set the ACK retry delay for radio communication """ # Auto Retransmit Delay: # 0000 - Wait 250uS # 0001 - Wait 500uS # 0010 - Wait 750uS # ........ # 1111 - Wait 4000uS # Round down, to value representing a multiple of 250uS t = int((us / 250) - 1) if (t < 0): t = 0 if (t > 0xF): t = 0xF _send_vendor_setup(self.handle, SET_RADIO_ARD, t, 0, ())
[ "def", "set_ard_time", "(", "self", ",", "us", ")", ":", "# Auto Retransmit Delay:", "# 0000 - Wait 250uS", "# 0001 - Wait 500uS", "# 0010 - Wait 750uS", "# ........", "# 1111 - Wait 4000uS", "# Round down, to value representing a multiple of 250uS", "t", "=", "int", "(", "(", ...
Set the ACK retry delay for radio communication
[ "Set", "the", "ACK", "retry", "delay", "for", "radio", "communication" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/drivers/crazyradio.py#L215-L230
train
228,387
bitcraze/crazyflie-lib-python
cflib/crazyflie/toccache.py
TocCache.fetch
def fetch(self, crc): """ Try to get a hit in the cache, return None otherwise """ cache_data = None pattern = '%08X.json' % crc hit = None for name in self._cache_files: if (name.endswith(pattern)): hit = name if (hit): try: cache = open(hit) cache_data = json.load(cache, object_hook=self._decoder) cache.close() except Exception as exp: logger.warning('Error while parsing cache file [%s]:%s', hit, str(exp)) return cache_data
python
def fetch(self, crc): """ Try to get a hit in the cache, return None otherwise """ cache_data = None pattern = '%08X.json' % crc hit = None for name in self._cache_files: if (name.endswith(pattern)): hit = name if (hit): try: cache = open(hit) cache_data = json.load(cache, object_hook=self._decoder) cache.close() except Exception as exp: logger.warning('Error while parsing cache file [%s]:%s', hit, str(exp)) return cache_data
[ "def", "fetch", "(", "self", ",", "crc", ")", ":", "cache_data", "=", "None", "pattern", "=", "'%08X.json'", "%", "crc", "hit", "=", "None", "for", "name", "in", "self", ".", "_cache_files", ":", "if", "(", "name", ".", "endswith", "(", "pattern", ")...
Try to get a hit in the cache, return None otherwise
[ "Try", "to", "get", "a", "hit", "in", "the", "cache", "return", "None", "otherwise" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L62-L82
train
228,388
bitcraze/crazyflie-lib-python
cflib/crazyflie/toccache.py
TocCache.insert
def insert(self, crc, toc): """ Save a new cache to file """ if self._rw_cache: try: filename = '%s/%08X.json' % (self._rw_cache, crc) cache = open(filename, 'w') cache.write(json.dumps(toc, indent=2, default=self._encoder)) cache.close() logger.info('Saved cache to [%s]', filename) self._cache_files += [filename] except Exception as exp: logger.warning('Could not save cache to file [%s]: %s', filename, str(exp)) else: logger.warning('Could not save cache, no writable directory')
python
def insert(self, crc, toc): """ Save a new cache to file """ if self._rw_cache: try: filename = '%s/%08X.json' % (self._rw_cache, crc) cache = open(filename, 'w') cache.write(json.dumps(toc, indent=2, default=self._encoder)) cache.close() logger.info('Saved cache to [%s]', filename) self._cache_files += [filename] except Exception as exp: logger.warning('Could not save cache to file [%s]: %s', filename, str(exp)) else: logger.warning('Could not save cache, no writable directory')
[ "def", "insert", "(", "self", ",", "crc", ",", "toc", ")", ":", "if", "self", ".", "_rw_cache", ":", "try", ":", "filename", "=", "'%s/%08X.json'", "%", "(", "self", ".", "_rw_cache", ",", "crc", ")", "cache", "=", "open", "(", "filename", ",", "'w...
Save a new cache to file
[ "Save", "a", "new", "cache", "to", "file" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L84-L99
train
228,389
bitcraze/crazyflie-lib-python
cflib/crazyflie/toccache.py
TocCache._encoder
def _encoder(self, obj): """ Encode a toc element leaf-node """ return {'__class__': obj.__class__.__name__, 'ident': obj.ident, 'group': obj.group, 'name': obj.name, 'ctype': obj.ctype, 'pytype': obj.pytype, 'access': obj.access} raise TypeError(repr(obj) + ' is not JSON serializable')
python
def _encoder(self, obj): """ Encode a toc element leaf-node """ return {'__class__': obj.__class__.__name__, 'ident': obj.ident, 'group': obj.group, 'name': obj.name, 'ctype': obj.ctype, 'pytype': obj.pytype, 'access': obj.access} raise TypeError(repr(obj) + ' is not JSON serializable')
[ "def", "_encoder", "(", "self", ",", "obj", ")", ":", "return", "{", "'__class__'", ":", "obj", ".", "__class__", ".", "__name__", ",", "'ident'", ":", "obj", ".", "ident", ",", "'group'", ":", "obj", ".", "group", ",", "'name'", ":", "obj", ".", "...
Encode a toc element leaf-node
[ "Encode", "a", "toc", "element", "leaf", "-", "node" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L101-L110
train
228,390
bitcraze/crazyflie-lib-python
cflib/crazyflie/toccache.py
TocCache._decoder
def _decoder(self, obj): """ Decode a toc element leaf-node """ if '__class__' in obj: elem = eval(obj['__class__'])() elem.ident = obj['ident'] elem.group = str(obj['group']) elem.name = str(obj['name']) elem.ctype = str(obj['ctype']) elem.pytype = str(obj['pytype']) elem.access = obj['access'] return elem return obj
python
def _decoder(self, obj): """ Decode a toc element leaf-node """ if '__class__' in obj: elem = eval(obj['__class__'])() elem.ident = obj['ident'] elem.group = str(obj['group']) elem.name = str(obj['name']) elem.ctype = str(obj['ctype']) elem.pytype = str(obj['pytype']) elem.access = obj['access'] return elem return obj
[ "def", "_decoder", "(", "self", ",", "obj", ")", ":", "if", "'__class__'", "in", "obj", ":", "elem", "=", "eval", "(", "obj", "[", "'__class__'", "]", ")", "(", ")", "elem", ".", "ident", "=", "obj", "[", "'ident'", "]", "elem", ".", "group", "="...
Decode a toc element leaf-node
[ "Decode", "a", "toc", "element", "leaf", "-", "node" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toccache.py#L112-L123
train
228,391
bitcraze/crazyflie-lib-python
lpslib/lopoanchor.py
LoPoAnchor.set_mode
def set_mode(self, anchor_id, mode): """ Send a packet to set the anchor mode. If the anchor receive the packet, it will change mode and resets. """ data = struct.pack('<BB', LoPoAnchor.LPP_TYPE_MODE, mode) self.crazyflie.loc.send_short_lpp_packet(anchor_id, data)
python
def set_mode(self, anchor_id, mode): """ Send a packet to set the anchor mode. If the anchor receive the packet, it will change mode and resets. """ data = struct.pack('<BB', LoPoAnchor.LPP_TYPE_MODE, mode) self.crazyflie.loc.send_short_lpp_packet(anchor_id, data)
[ "def", "set_mode", "(", "self", ",", "anchor_id", ",", "mode", ")", ":", "data", "=", "struct", ".", "pack", "(", "'<BB'", ",", "LoPoAnchor", ".", "LPP_TYPE_MODE", ",", "mode", ")", "self", ".", "crazyflie", ".", "loc", ".", "send_short_lpp_packet", "(",...
Send a packet to set the anchor mode. If the anchor receive the packet, it will change mode and resets.
[ "Send", "a", "packet", "to", "set", "the", "anchor", "mode", ".", "If", "the", "anchor", "receive", "the", "packet", "it", "will", "change", "mode", "and", "resets", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/lpslib/lopoanchor.py#L66-L72
train
228,392
bitcraze/crazyflie-lib-python
cflib/crazyflie/swarm.py
Swarm.open_links
def open_links(self): """ Open links to all individuals in the swarm """ if self._is_open: raise Exception('Already opened') try: self.parallel_safe(lambda scf: scf.open_link()) self._is_open = True except Exception as e: self.close_links() raise e
python
def open_links(self): """ Open links to all individuals in the swarm """ if self._is_open: raise Exception('Already opened') try: self.parallel_safe(lambda scf: scf.open_link()) self._is_open = True except Exception as e: self.close_links() raise e
[ "def", "open_links", "(", "self", ")", ":", "if", "self", ".", "_is_open", ":", "raise", "Exception", "(", "'Already opened'", ")", "try", ":", "self", ".", "parallel_safe", "(", "lambda", "scf", ":", "scf", ".", "open_link", "(", ")", ")", "self", "."...
Open links to all individuals in the swarm
[ "Open", "links", "to", "all", "individuals", "in", "the", "swarm" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L80-L92
train
228,393
bitcraze/crazyflie-lib-python
cflib/crazyflie/swarm.py
Swarm.close_links
def close_links(self): """ Close all open links """ for uri, cf in self._cfs.items(): cf.close_link() self._is_open = False
python
def close_links(self): """ Close all open links """ for uri, cf in self._cfs.items(): cf.close_link() self._is_open = False
[ "def", "close_links", "(", "self", ")", ":", "for", "uri", ",", "cf", "in", "self", ".", "_cfs", ".", "items", "(", ")", ":", "cf", ".", "close_link", "(", ")", "self", ".", "_is_open", "=", "False" ]
Close all open links
[ "Close", "all", "open", "links" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L94-L101
train
228,394
bitcraze/crazyflie-lib-python
cflib/crazyflie/swarm.py
Swarm.sequential
def sequential(self, func, args_dict=None): """ Execute a function for all Crazyflies in the swarm, in sequence. The first argument of the function that is passed in will be a SyncCrazyflie instance connected to the Crazyflie to operate on. A list of optional parameters (per Crazyflie) may follow defined by the args_dict. The dictionary is keyed on URI. Example: def my_function(scf, optional_param0, optional_param1) ... args_dict = { URI0: [optional_param0_cf0, optional_param1_cf0], URI1: [optional_param0_cf1, optional_param1_cf1], ... } self.sequential(my_function, args_dict) :param func: the function to execute :param args_dict: parameters to pass to the function """ for uri, cf in self._cfs.items(): args = self._process_args_dict(cf, uri, args_dict) func(*args)
python
def sequential(self, func, args_dict=None): """ Execute a function for all Crazyflies in the swarm, in sequence. The first argument of the function that is passed in will be a SyncCrazyflie instance connected to the Crazyflie to operate on. A list of optional parameters (per Crazyflie) may follow defined by the args_dict. The dictionary is keyed on URI. Example: def my_function(scf, optional_param0, optional_param1) ... args_dict = { URI0: [optional_param0_cf0, optional_param1_cf0], URI1: [optional_param0_cf1, optional_param1_cf1], ... } self.sequential(my_function, args_dict) :param func: the function to execute :param args_dict: parameters to pass to the function """ for uri, cf in self._cfs.items(): args = self._process_args_dict(cf, uri, args_dict) func(*args)
[ "def", "sequential", "(", "self", ",", "func", ",", "args_dict", "=", "None", ")", ":", "for", "uri", ",", "cf", "in", "self", ".", "_cfs", ".", "items", "(", ")", ":", "args", "=", "self", ".", "_process_args_dict", "(", "cf", ",", "uri", ",", "...
Execute a function for all Crazyflies in the swarm, in sequence. The first argument of the function that is passed in will be a SyncCrazyflie instance connected to the Crazyflie to operate on. A list of optional parameters (per Crazyflie) may follow defined by the args_dict. The dictionary is keyed on URI. Example: def my_function(scf, optional_param0, optional_param1) ... args_dict = { URI0: [optional_param0_cf0, optional_param1_cf0], URI1: [optional_param0_cf1, optional_param1_cf1], ... } self.sequential(my_function, args_dict) :param func: the function to execute :param args_dict: parameters to pass to the function
[ "Execute", "a", "function", "for", "all", "Crazyflies", "in", "the", "swarm", "in", "sequence", "." ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L110-L137
train
228,395
bitcraze/crazyflie-lib-python
cflib/crazyflie/swarm.py
Swarm.parallel_safe
def parallel_safe(self, func, args_dict=None): """ Execute a function for all Crazyflies in the swarm, in parallel. One thread per Crazyflie is started to execute the function. The threads are joined at the end and if one or more of the threads raised an exception this function will also raise an exception. For a description of the arguments, see sequential() :param func: :param args_dict: """ threads = [] reporter = self.Reporter() for uri, scf in self._cfs.items(): args = [func, reporter] + \ self._process_args_dict(scf, uri, args_dict) thread = Thread(target=self._thread_function_wrapper, args=args) threads.append(thread) thread.start() for thread in threads: thread.join() if reporter.is_error_reported(): raise Exception('One or more threads raised an exception when ' 'executing parallel task')
python
def parallel_safe(self, func, args_dict=None): """ Execute a function for all Crazyflies in the swarm, in parallel. One thread per Crazyflie is started to execute the function. The threads are joined at the end and if one or more of the threads raised an exception this function will also raise an exception. For a description of the arguments, see sequential() :param func: :param args_dict: """ threads = [] reporter = self.Reporter() for uri, scf in self._cfs.items(): args = [func, reporter] + \ self._process_args_dict(scf, uri, args_dict) thread = Thread(target=self._thread_function_wrapper, args=args) threads.append(thread) thread.start() for thread in threads: thread.join() if reporter.is_error_reported(): raise Exception('One or more threads raised an exception when ' 'executing parallel task')
[ "def", "parallel_safe", "(", "self", ",", "func", ",", "args_dict", "=", "None", ")", ":", "threads", "=", "[", "]", "reporter", "=", "self", ".", "Reporter", "(", ")", "for", "uri", ",", "scf", "in", "self", ".", "_cfs", ".", "items", "(", ")", ...
Execute a function for all Crazyflies in the swarm, in parallel. One thread per Crazyflie is started to execute the function. The threads are joined at the end and if one or more of the threads raised an exception this function will also raise an exception. For a description of the arguments, see sequential() :param func: :param args_dict:
[ "Execute", "a", "function", "for", "all", "Crazyflies", "in", "the", "swarm", "in", "parallel", ".", "One", "thread", "per", "Crazyflie", "is", "started", "to", "execute", "the", "function", ".", "The", "threads", "are", "joined", "at", "the", "end", "and"...
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/swarm.py#L156-L184
train
228,396
bitcraze/crazyflie-lib-python
cflib/positioning/position_hl_commander.py
PositionHlCommander.take_off
def take_off(self, height=DEFAULT, velocity=DEFAULT): """ Takes off, that is starts the motors, goes straight up and hovers. Do not call this function if you use the with keyword. Take off is done automatically when the context is created. :param height: the height (meters) to hover at. None uses the default height set when constructed. :param velocity: the velocity (meters/second) when taking off :return: """ if self._is_flying: raise Exception('Already flying') if not self._cf.is_connected(): raise Exception('Crazyflie is not connected') self._is_flying = True self._reset_position_estimator() self._activate_controller() self._activate_high_level_commander() self._hl_commander = self._cf.high_level_commander height = self._height(height) duration_s = height / self._velocity(velocity) self._hl_commander.takeoff(height, duration_s) time.sleep(duration_s) self._z = height
python
def take_off(self, height=DEFAULT, velocity=DEFAULT): """ Takes off, that is starts the motors, goes straight up and hovers. Do not call this function if you use the with keyword. Take off is done automatically when the context is created. :param height: the height (meters) to hover at. None uses the default height set when constructed. :param velocity: the velocity (meters/second) when taking off :return: """ if self._is_flying: raise Exception('Already flying') if not self._cf.is_connected(): raise Exception('Crazyflie is not connected') self._is_flying = True self._reset_position_estimator() self._activate_controller() self._activate_high_level_commander() self._hl_commander = self._cf.high_level_commander height = self._height(height) duration_s = height / self._velocity(velocity) self._hl_commander.takeoff(height, duration_s) time.sleep(duration_s) self._z = height
[ "def", "take_off", "(", "self", ",", "height", "=", "DEFAULT", ",", "velocity", "=", "DEFAULT", ")", ":", "if", "self", ".", "_is_flying", ":", "raise", "Exception", "(", "'Already flying'", ")", "if", "not", "self", ".", "_cf", ".", "is_connected", "(",...
Takes off, that is starts the motors, goes straight up and hovers. Do not call this function if you use the with keyword. Take off is done automatically when the context is created. :param height: the height (meters) to hover at. None uses the default height set when constructed. :param velocity: the velocity (meters/second) when taking off :return:
[ "Takes", "off", "that", "is", "starts", "the", "motors", "goes", "straight", "up", "and", "hovers", ".", "Do", "not", "call", "this", "function", "if", "you", "use", "the", "with", "keyword", ".", "Take", "off", "is", "done", "automatically", "when", "th...
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/position_hl_commander.py#L82-L110
train
228,397
bitcraze/crazyflie-lib-python
cflib/positioning/position_hl_commander.py
PositionHlCommander.go_to
def go_to(self, x, y, z=DEFAULT, velocity=DEFAULT): """ Go to a position :param x: X coordinate :param y: Y coordinate :param z: Z coordinate :param velocity: the velocity (meters/second) :return: """ z = self._height(z) dx = x - self._x dy = y - self._y dz = z - self._z distance = math.sqrt(dx * dx + dy * dy + dz * dz) duration_s = distance / self._velocity(velocity) self._hl_commander.go_to(x, y, z, 0, duration_s) time.sleep(duration_s) self._x = x self._y = y self._z = z
python
def go_to(self, x, y, z=DEFAULT, velocity=DEFAULT): """ Go to a position :param x: X coordinate :param y: Y coordinate :param z: Z coordinate :param velocity: the velocity (meters/second) :return: """ z = self._height(z) dx = x - self._x dy = y - self._y dz = z - self._z distance = math.sqrt(dx * dx + dy * dy + dz * dz) duration_s = distance / self._velocity(velocity) self._hl_commander.go_to(x, y, z, 0, duration_s) time.sleep(duration_s) self._x = x self._y = y self._z = z
[ "def", "go_to", "(", "self", ",", "x", ",", "y", ",", "z", "=", "DEFAULT", ",", "velocity", "=", "DEFAULT", ")", ":", "z", "=", "self", ".", "_height", "(", "z", ")", "dx", "=", "x", "-", "self", ".", "_x", "dy", "=", "y", "-", "self", ".",...
Go to a position :param x: X coordinate :param y: Y coordinate :param z: Z coordinate :param velocity: the velocity (meters/second) :return:
[ "Go", "to", "a", "position" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/position_hl_commander.py#L219-L243
train
228,398
bitcraze/crazyflie-lib-python
cflib/crazyflie/param.py
Param.request_update_of_all_params
def request_update_of_all_params(self): """Request an update of all the parameters in the TOC""" for group in self.toc.toc: for name in self.toc.toc[group]: complete_name = '%s.%s' % (group, name) self.request_param_update(complete_name)
python
def request_update_of_all_params(self): """Request an update of all the parameters in the TOC""" for group in self.toc.toc: for name in self.toc.toc[group]: complete_name = '%s.%s' % (group, name) self.request_param_update(complete_name)
[ "def", "request_update_of_all_params", "(", "self", ")", ":", "for", "group", "in", "self", ".", "toc", ".", "toc", ":", "for", "name", "in", "self", ".", "toc", ".", "toc", "[", "group", "]", ":", "complete_name", "=", "'%s.%s'", "%", "(", "group", ...
Request an update of all the parameters in the TOC
[ "Request", "an", "update", "of", "all", "the", "parameters", "in", "the", "TOC" ]
f6ebb4eb315bbe6e02db518936ac17fb615b2af8
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L145-L150
train
228,399