INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Set the R/G/B and optionally intensity in one call | def set(self, r, g, b, intensity=None):
"""Set the R/G/B and optionally intensity in one call"""
self.r = r
self.g = g
self.b = b
if intensity:
self.intensity = intensity |
Callback for when new memory data has been fetched | def new_data(self, mem, addr, data):
"""Callback for when new memory data has been fetched"""
if mem.id == self.id:
logger.debug(
"Got new data from the LED driver, but we don't care.") |
Write the saved LED-ring data to the Crazyflie | def write_data(self, write_finished_cb):
"""Write the saved LED-ring data to the Crazyflie"""
self._write_finished_cb = write_finished_cb
data = bytearray()
for led in self.leds:
# In order to fit all the LEDs in one radio packet RGB565 is used
# to compress the c... |
Callback for when new memory data has been fetched | def new_data(self, mem, addr, data):
"""Callback for when new memory data has been fetched"""
if mem.id == self.id:
if addr == 0:
done = False
# Check for header
if data[0:4] == EEPROM_TOKEN:
logger.debug('Got new data: {}'.... |
Callback for when new memory data has been fetched | def new_data(self, mem, addr, data):
"""Callback for when new memory data has been fetched"""
if mem.id == self.id:
if addr == 0:
if self._parse_and_check_header(data[0:8]):
if self._parse_and_check_elements(data[9:11]):
self.valid ... |
Parse and check the CRC and length of the elements part of the memory | def _parse_and_check_elements(self, data):
"""
Parse and check the CRC and length of the elements part of the memory
"""
crc = data[-1]
test_crc = crc32(data[:-1]) & 0x0ff
elem_data = data[2:-1]
if test_crc == crc:
while len(elem_data) > 0:
... |
Request an update of the memory content | def update(self, update_finished_cb):
"""Request an update of the memory content"""
if not self._update_finished_cb:
self._update_finished_cb = update_finished_cb
self.valid = False
logger.debug('Updating content of memory {}'.format(self.id))
# Start read... |
Parse and check the CRC of the header part of the memory | def _parse_and_check_header(self, data):
"""Parse and check the CRC of the header part of the memory"""
(start, self.pins, self.vid, self.pid, crc) = struct.unpack('<BIBBB',
data)
test_crc = crc32(data[:-1]) & 0x0ff
if s... |
Callback for when new memory data has been fetched | def new_data(self, mem, addr, data):
"""Callback for when new memory data has been fetched"""
done = False
if mem.id == self.id:
if addr == LocoMemory.MEM_LOCO_INFO:
self.nr_of_anchors = data[0]
if self.nr_of_anchors == 0:
done = Tr... |
Request an update of the memory content | def update(self, update_finished_cb):
"""Request an update of the memory content"""
if not self._update_finished_cb:
self._update_finished_cb = update_finished_cb
self.anchor_data = []
self.nr_of_anchors = 0
self.valid = False
logger.debug('Upd... |
Callback for when new memory data has been fetched | def new_data(self, mem, addr, data):
"""Callback for when new memory data has been fetched"""
if mem.id == self.id:
if addr == LocoMemory2.ADR_ID_LIST:
self._handle_id_list_data(data)
elif addr == LocoMemory2.ADR_ACTIVE_ID_LIST:
self._handle_active... |
Request an update of the id list | def update_id_list(self, update_ids_finished_cb):
"""Request an update of the id list"""
if not self._update_ids_finished_cb:
self._update_ids_finished_cb = update_ids_finished_cb
self.anchor_ids = []
self.active_anchor_ids = []
self.anchor_data = {}
... |
Request an update of the active id list | def update_active_id_list(self, update_active_ids_finished_cb):
"""Request an update of the active id list"""
if not self._update_active_ids_finished_cb:
self._update_active_ids_finished_cb = update_active_ids_finished_cb
self.active_anchor_ids = []
self.active_ids_v... |
Request an update of the anchor data | def update_data(self, update_data_finished_cb):
"""Request an update of the anchor data"""
if not self._update_data_finished_cb and self.nr_of_anchors > 0:
self._update_data_finished_cb = update_data_finished_cb
self.anchor_data = {}
self.data_valid = False
... |
Write trajectory data to the Crazyflie | def write_data(self, write_finished_cb):
"""Write trajectory data to the Crazyflie"""
self._write_finished_cb = write_finished_cb
data = bytearray()
for poly4D in self.poly4Ds:
data += struct.pack('<ffffffff', *poly4D.x.values)
data += struct.pack('<ffffffff', *p... |
Called to request a new chunk of data to be read from the Crazyflie | def _request_new_chunk(self):
"""
Called to request a new chunk of data to be read from the Crazyflie
"""
# Figure out the length of the next request
new_len = self._bytes_left
if new_len > _ReadRequest.MAX_DATA_LENGTH:
new_len = _ReadRequest.MAX_DATA_LENGTH
... |
Callback when data is received from the Crazyflie | def add_data(self, addr, data):
"""Callback when data is received from the Crazyflie"""
data_len = len(data)
if not addr == self._current_addr:
logger.warning(
'Address did not match when adding data to read request!')
return
# Add the data and ca... |
Called to request a new chunk of data to be read from the Crazyflie | def _write_new_chunk(self):
"""
Called to request a new chunk of data to be read from the Crazyflie
"""
# Figure out the length of the next request
new_len = len(self._data)
if new_len > _WriteRequest.MAX_DATA_LENGTH:
new_len = _WriteRequest.MAX_DATA_LENGTH
... |
Callback when data is received from the Crazyflie | def write_done(self, addr):
"""Callback when data is received from the Crazyflie"""
if not addr == self._current_addr:
logger.warning(
'Address did not match when adding data to read request!')
return
if len(self._data) > 0:
self._current_addr... |
Callback from each individual memory (only 1-wire) when reading of
header/elements are done | def _mem_update_done(self, mem):
"""
Callback from each individual memory (only 1-wire) when reading of
header/elements are done
"""
if mem.id in self._ow_mems_left_to_update:
self._ow_mems_left_to_update.remove(mem.id)
logger.debug(mem)
if len(self.... |
Fetch the memory with the supplied id | def get_mem(self, id):
"""Fetch the memory with the supplied id"""
for m in self.mems:
if m.id == id:
return m
return None |
Fetch all the memories of the supplied type | def get_mems(self, type):
"""Fetch all the memories of the supplied type"""
ret = ()
for m in self.mems:
if m.type == type:
ret += (m,)
return ret |
Search for specific memory id/name and return it | def ow_search(self, vid=0xBC, pid=None, name=None):
"""Search for specific memory id/name and return it"""
for m in self.get_mems(MemoryElement.TYPE_1W):
if pid and m.pid == pid or name and m.name == name:
return m
return None |
Write the specified data to the given memory at the given address | def write(self, memory, addr, data, flush_queue=False):
"""Write the specified data to the given memory at the given address"""
wreq = _WriteRequest(memory, addr, data, self.cf)
if memory.id not in self._write_requests:
self._write_requests[memory.id] = []
# Workaround until... |
Read the specified amount of bytes from the given memory at the given
address | def read(self, memory, addr, length):
"""
Read the specified amount of bytes from the given memory at the given
address
"""
if memory.id in self._read_requests:
logger.warning('There is already a read operation ongoing for '
'memory id {}'.f... |
Start fetching all the detected memories | def refresh(self, refresh_done_callback):
"""Start fetching all the detected memories"""
self._refresh_callback = refresh_done_callback
self._fetch_id = 0
for m in self.mems:
try:
self.mem_read_cb.remove_callback(m.new_data)
m.disconnect()
... |
Callback for newly arrived packets for the memory port | def _new_packet_cb(self, packet):
"""Callback for newly arrived packets for the memory port"""
chan = packet.channel
cmd = packet.data[0]
payload = packet.data[1:]
if chan == CHAN_INFO:
if cmd == CMD_INFO_NBR:
self.nbr_of_mems = payload[0]
... |
Reset to the bootloader
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done and the contact with the
bootloader is established. | def reset_to_bootloader1(self, cpu_id):
""" Reset to the bootloader
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done and the contact with the
bootloader is established.
"""
# Send an echo request and wait for the answer
... |
Reset to firmware
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done | def reset_to_firmware(self, target_id):
""" Reset to firmware
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done
"""
# The fake CPU ID is legacy from the Crazyflie 1.0
# In order to reset the CPU id had to be sent, but thi... |
Try to get a connection with the bootloader by requesting info
5 times. This let roughly 10 seconds to boot the copter ... | def check_link_and_get_info(self, target_id=0xFF):
"""Try to get a connection with the bootloader by requesting info
5 times. This let roughly 10 seconds to boot the copter ..."""
for _ in range(0, 5):
if self._update_info(target_id):
if self._in_boot_cb:
... |
Call the command getInfo and fill up the information received in
the fields of the object | def _update_info(self, target_id):
""" Call the command getInfo and fill up the information received in
the fields of the object
"""
# Call getInfo ...
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (target_id, 0x10)
self.link.send_packet(pk)
... |
Upload data into a buffer on the Crazyflie | def upload_buffer(self, target_id, page, address, buff):
"""Upload data into a buffer on the Crazyflie"""
# print len(buff)
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page, address)
for i in range(0, len(... |
Read back a flash page from the Crazyflie and return it | def read_flash(self, addr=0xFF, page=0x00):
"""Read back a flash page from the Crazyflie and return it"""
buff = bytearray()
page_size = self.targets[addr].page_size
for i in range(0, int(math.ceil(page_size / 25.0))):
pk = None
retry_counter = 5
whi... |
Initiate flashing of data in the buffer to flash. | def write_flash(self, addr, page_buffer, target_page, page_count):
"""Initiate flashing of data in the buffer to flash."""
# print "Write page", flashPage
# print "Writing page [%d] and [%d] forward" % (flashPage, nPage)
pk = None
# Flushing downlink ...
pk = self.link.r... |
Decode the CPU id into a string | def decode_cpu_id(self, cpuid):
"""Decode the CPU id into a string"""
ret = ()
for i in cpuid.split(':'):
ret += (eval('0x' + i),)
return ret |
Set the port and channel for this packet. | def set_header(self, port, channel):
"""
Set the port and channel for this packet.
"""
self._port = port
self.channel = channel
self._update_header() |
Set the packet data | def _set_data(self, data):
"""Set the packet data"""
if type(data) == bytearray:
self._data = data
elif type(data) == str:
if sys.version_info < (3,):
self._data = bytearray(data)
else:
self._data = bytearray(data.encode('ISO-88... |
Takes off, that is starts the motors, goes straigt 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 const... | def take_off(self, height=None, velocity=VELOCITY):
"""
Takes off, that is starts the motors, goes straigt 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 hove... |
Go straight down and turn off the motors.
Do not call this function if you use the with keyword. Landing is
done automatically when the context goes out of scope.
:param velocity: The velocity (meters/second) when going down
:return: | def land(self, velocity=VELOCITY):
"""
Go straight down and turn off the motors.
Do not call this function if you use the with keyword. Landing is
done automatically when the context goes out of scope.
:param velocity: The velocity (meters/second) when going down
:retur... |
Turn to the left, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return: | def turn_left(self, angle_degrees, rate=RATE):
"""
Turn to the left, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_left... |
Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return: | def turn_right(self, angle_degrees, rate=RATE):
"""
Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_ri... |
Go in circle, counter clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return: | def circle_left(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):
"""
Go in circle, counter clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degr... |
Go in circle, clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return: | def circle_right(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):
"""
Go in circle, clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
... |
Move in a straight line.
positive X is forward
positive Y is left
positive Z is up
:param distance_x_m: The distance to travel along the X-axis (meters)
:param distance_y_m: The distance to travel along the Y-axis (meters)
:param distance_z_m: The distance to travel alon... | def move_distance(self, distance_x_m, distance_y_m, distance_z_m,
velocity=VELOCITY):
"""
Move in a straight line.
positive X is forward
positive Y is left
positive Z is up
:param distance_x_m: The distance to travel along the X-axis (meters)
... |
Start a circular motion to the left. This function returns immediately.
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity of the motion (meters/second)
:return: | def start_circle_left(self, radius_m, velocity=VELOCITY):
"""
Start a circular motion to the left. This function returns immediately.
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity of the motion (meters/second)
:return:
"""
circu... |
Start a linear motion. This function returns immediately.
positive X is forward
positive Y is left
positive Z is up
:param velocity_x_m: The velocity along the X-axis (meters/second)
:param velocity_y_m: The velocity along the Y-axis (meters/second)
:param velocity_z_m:... | def start_linear_motion(self, velocity_x_m, velocity_y_m, velocity_z_m):
"""
Start a linear motion. This function returns immediately.
positive X is forward
positive Y is left
positive Z is up
:param velocity_x_m: The velocity along the X-axis (meters/second)
:p... |
Set the velocity setpoint to use for the future motion | def set_vel_setpoint(self, velocity_x, velocity_y, velocity_z, rate_yaw):
"""Set the velocity setpoint to use for the future motion"""
self._queue.put((velocity_x, velocity_y, velocity_z, rate_yaw)) |
This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded. | def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""
print('Connected to %s' % link_uri)
mems = self._cf.mem.get_mems(MemoryElement.TYPE_1W)
print('Found {} 1-wire memories'.f... |
Returns a list of CrazyRadio devices currently connected to the computer | def _find_devices():
"""
Returns a list of CrazyRadio devices currently connected to the computer
"""
ret = []
logger.info('Looking for devices....')
if pyusb1:
for d in usb.core.find(idVendor=USB_VID, idProduct=USB_PID, find_all=1,
backend=pyusb_backend)... |
Send a packet and receive the ack from the radio dongle
The ack contains information about the packet transmition
and a data payload if the ack packet contained any | def send_packet(self, dataOut):
""" Send a packet and receive the ack from the radio dongle
The ack contains information about the packet transmition
and a data payload if the ack packet contained any """
try:
if (pyusb1 is False):
self.handle.bulkWrit... |
This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded. | def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""
print('Connected to %s' % link_uri)
# Print the param TOC
p_toc = self._cf.param.toc.toc
for group in sorted(p_toc... |
Generic callback registered for all the groups | def _param_callback(self, name, value):
"""Generic callback registered for all the groups"""
print('{0}: {1}'.format(name, value))
# Remove each parameter from the list and close the link when
# all are fetched
self._param_check_list.remove(name)
if len(self._param_check... |
Callback for pid_attitude.pitch_kd | def _a_pitch_kd_callback(self, name, value):
"""Callback for pid_attitude.pitch_kd"""
print('Readback: {0}={1}'.format(name, value))
# End the example by closing the link (will cause the app to quit)
self._cf.close_link() |
Connect the link driver to a specified URI of the format:
radio://<dongle nbr>/<radio channel>/[250K,1M,2M]
The callback for linkQuality can be called at any moment from the
driver to report back the link quality in percentage. The
callback from linkError will be called when a error occ... | def connect(self, uri, link_quality_callback, link_error_callback):
"""
Connect the link driver to a specified URI of the format:
radio://<dongle nbr>/<radio channel>/[250K,1M,2M]
The callback for linkQuality can be called at any moment from the
driver to report back the link qu... |
Send the packet pk though the link | def send_packet(self, pk):
""" Send the packet pk though the link """
try:
self.out_queue.put(pk, True, 2)
except queue.Full:
if self.link_error_callback:
self.link_error_callback('RadioDriver: Could not send packet'
... |
Close the link. | def close(self):
""" Close the link. """
# Stop the comm thread
self._thread.stop()
# Close the USB dongle
if self._radio_manager:
self._radio_manager.close()
self._radio_manager = None
while not self.out_queue.empty():
self.out_queue.get... |
Scan for Crazyflies between the supplied channels. | def _scan_radio_channels(self, cradio, start=0, stop=125):
""" Scan for Crazyflies between the supplied channels. """
return list(cradio.scan_channels(start, stop, (0xff,))) |
Scan interface for Crazyflies | def scan_interface(self, address):
""" Scan interface for Crazyflies """
if self._radio_manager is None:
try:
self._radio_manager = _RadioManager(0)
except Exception:
return []
with self._radio_manager as cradio:
# FIXME: impl... |
Adds 1bit counter to CRTP header to guarantee that no ack (downlink)
payload are lost and no uplink packet are duplicated.
The caller should resend packet if not acked (ie. same as with a
direct call to crazyradio.send_packet) | def _send_packet_safe(self, cr, packet):
"""
Adds 1bit counter to CRTP header to guarantee that no ack (downlink)
payload are lost and no uplink packet are duplicated.
The caller should resend packet if not acked (ie. same as with a
direct call to crazyradio.send_packet)
... |
Run the receiver thread | def run(self):
""" Run the receiver thread """
dataOut = array.array('B', [0xFF])
waitTime = 0
emptyCtr = 0
# Try up to 10 times to enable the safelink mode
with self._radio_manager as cradio:
for _ in range(10):
resp = cradio.send_packet((0xf... |
This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded. | def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""
print('Connected to %s' % link_uri)
mems = self._cf.mem.get_mems(MemoryElement.TYPE_1W)
print('Found {} 1-wire memories'.f... |
Command-line tool for obtaining authorization and credentials from a user.
This tool uses the OAuth 2.0 Authorization Code grant as described
in section 1.3.1 of RFC6749:
https://tools.ietf.org/html/rfc6749#section-1.3.1
This tool is intended for assist developers in obtaining credentials
for test... | def main(client_secrets, scope, save, credentials, headless):
"""Command-line tool for obtaining authorization and credentials from a user.
This tool uses the OAuth 2.0 Authorization Code grant as described
in section 1.3.1 of RFC6749:
https://tools.ietf.org/html/rfc6749#section-1.3.1
This tool is... |
Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Google `client secrets`_ format.
scopes (Sequence[str]): The list of scopes to reque... | def session_from_client_config(client_config, scopes, **kwargs):
"""Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Google `client secre... |
Creates a :class:`requests_oauthlib.OAuth2Session` instance from a
Google-format client secrets file.
Args:
client_secrets_file (str): The path to the `client secrets`_ .json
file.
scopes (Sequence[str]): The list of scopes to request during the
flow.
kwargs: Any... | def session_from_client_secrets_file(client_secrets_file, scopes, **kwargs):
"""Creates a :class:`requests_oauthlib.OAuth2Session` instance from a
Google-format client secrets file.
Args:
client_secrets_file (str): The path to the `client secrets`_ .json
file.
scopes (Sequence[s... |
Creates :class:`google.oauth2.credentials.Credentials` from a
:class:`requests_oauthlib.OAuth2Session`.
:meth:`fetch_token` must be called on the session before before calling
this. This uses the session's auth token and the provided client
configuration to create :class:`google.oauth2.credentials.Cred... | def credentials_from_session(session, client_config=None):
"""Creates :class:`google.oauth2.credentials.Credentials` from a
:class:`requests_oauthlib.OAuth2Session`.
:meth:`fetch_token` must be called on the session before before calling
this. This uses the session's auth token and the provided client
... |
Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Google `client secrets`_ format.
scopes (Sequence[str]): The lis... | def from_client_config(cls, client_config, scopes, **kwargs):
"""Creates a :class:`requests_oauthlib.OAuth2Session` from client
configuration loaded from a Google-format client secrets file.
Args:
client_config (Mapping[str, Any]): The client
configuration in the Goo... |
Creates a :class:`Flow` instance from a Google client secrets file.
Args:
client_secrets_file (str): The path to the client secrets .json
file.
scopes (Sequence[str]): The list of scopes to request during the
flow.
kwargs: Any additional param... | def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs):
"""Creates a :class:`Flow` instance from a Google client secrets file.
Args:
client_secrets_file (str): The path to the client secrets .json
file.
scopes (Sequence[str]): The list of scopes... |
Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
and specifies the client configuration's authoriz... | def authorization_url(self, **kwargs):
"""Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
... |
Completes the Authorization Flow and obtains an access token.
This is the final step in the OAuth 2.0 Authorization Flow. This is
called after the user consents.
This method calls
:meth:`requests_oauthlib.OAuth2Session.fetch_token`
and specifies the client configuration's token... | def fetch_token(self, **kwargs):
"""Completes the Authorization Flow and obtains an access token.
This is the final step in the OAuth 2.0 Authorization Flow. This is
called after the user consents.
This method calls
:meth:`requests_oauthlib.OAuth2Session.fetch_token`
an... |
Run the flow using the console strategy.
The console strategy instructs the user to open the authorization URL
in their browser. Once the authorization is complete the authorization
server will give the user a code. The user then must copy & paste this
code into the application. The cod... | def run_console(
self,
authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE,
authorization_code_message=_DEFAULT_AUTH_CODE_MESSAGE,
**kwargs):
"""Run the flow using the console strategy.
The console strategy instructs the user to open the authorizati... |
Run the flow using the server strategy.
The server strategy instructs the user to open the authorization URL in
their browser and will attempt to automatically open the URL for them.
It will start a local web server to listen for the authorization
response. Once authorization is complet... | def run_local_server(
self, host='localhost', port=8080,
authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE,
success_message=_DEFAULT_WEB_SUCCESS_MESSAGE,
open_browser=True,
**kwargs):
"""Run the flow using the server strategy.
The serv... |
Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class decorator. For example::
registry = Registry()
@registry.install
cl... | def install(self, opener):
# type: (Union[Type[Opener], Opener, Callable[[], Opener]]) -> None
"""Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class d... |
`list`: the list of supported protocols. | def protocols(self):
# type: () -> List[Text]
"""`list`: the list of supported protocols.
"""
_protocols = list(self._protocols)
if self.load_extern:
_protocols.extend(
entry_point.name
for entry_point in pkg_resources.iter_entry_point... |
Get the opener class associated to a given protocol.
Arguments:
protocol (str): A filesystem protocol.
Returns:
Opener: an opener instance.
Raises:
~fs.opener.errors.UnsupportedProtocol: If no opener
could be found for the given protocol.
... | def get_opener(self, protocol):
# type: (Text) -> Opener
"""Get the opener class associated to a given protocol.
Arguments:
protocol (str): A filesystem protocol.
Returns:
Opener: an opener instance.
Raises:
~fs.opener.errors.UnsupportedProt... |
Open a filesystem from a FS URL.
Returns a tuple of a filesystem object and a path. If there is
no path in the FS URL, the path value will be `None`.
Arguments:
fs_url (str): A filesystem URL.
writeable (bool, optional): `True` if the filesystem must be
... | def open(
self,
fs_url, # type: Text
writeable=True, # type: bool
create=False, # type: bool
cwd=".", # type: Text
default_protocol="osfs", # type: Text
):
# type: (...) -> Tuple[FS, Text]
"""Open a filesystem from a FS URL.
Returns a tup... |
Open a filesystem from a FS URL (ignoring the path component).
Arguments:
fs_url (str): A filesystem URL.
writeable (bool, optional): `True` if the filesystem must
be writeable.
create (bool, optional): `True` if the filesystem should be
creat... | def open_fs(
self,
fs_url, # type: Union[FS, Text]
writeable=False, # type: bool
create=False, # type: bool
cwd=".", # type: Text
default_protocol="osfs", # type: Text
):
# type: (...) -> FS
"""Open a filesystem from a FS URL (ignoring the path co... |
Get a context manager to open and close a filesystem.
Arguments:
fs_url (FS or str): A filesystem instance or a FS URL.
create (bool, optional): If `True`, then create the filesystem if
it doesn't already exist.
writeable (bool, optional): If `True`, then the... | def manage_fs(
self,
fs_url, # type: Union[FS, Text]
create=False, # type: bool
writeable=False, # type: bool
cwd=".", # type: Text
):
# type: (...) -> Iterator[FS]
"""Get a context manager to open and close a filesystem.
Arguments:
fs... |
Copy the contents of one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``... | def copy_fs(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another.
Arguments:
src_fs (F... |
Copy the contents of one filesystem to another, checking times.
If both source and destination files exist, the copy is executed
only if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy file is always executed.
Ar... | def copy_fs_if_newer(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another, checking times.
If ... |
Determine if source file is newer than destination file.
Arguments:
src_fs (FS): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination fil... | def _source_is_newer(src_fs, src_path, dst_fs, dst_path):
# type: (FS, Text, FS, Text) -> bool
"""Determine if source file is newer than destination file.
Arguments:
src_fs (FS): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS... |
Copy a file from one filesystem to another.
If the destination exists, and is a file, it will be first truncated.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (ins... | def copy_file(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
):
# type: (...) -> None
"""Copy a file from one filesystem to another.
If the destination exists, and is a file, it will be first truncated.
Arguments:
... |
Low level copy, that doesn't call manage_fs or lock.
If the destination exists, and is a file, it will be first truncated.
This method exists to optimize copying in loops. In general you
should prefer `copy_file`.
Arguments:
src_fs (FS): Source filesystem.
src_path (str): Path to a fi... | def copy_file_internal(
src_fs, # type: FS
src_path, # type: Text
dst_fs, # type: FS
dst_path, # type: Text
):
# type: (...) -> None
"""Low level copy, that doesn't call manage_fs or lock.
If the destination exists, and is a file, it will be first truncated.
This method exists to o... |
Copy a file from one filesystem to another, checking times.
If the destination exists, and is a file, it will be first truncated.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destinat... | def copy_file_if_newer(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
):
# type: (...) -> bool
"""Copy a file from one filesystem to another, checking times.
If the destination exists, and is a file, it will be first trunca... |
Copy directories (but not files) from ``src_fs`` to ``dst_fs``.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
dst_fs (FS or str): Destination filesystem (instance or URL).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for fil... | def copy_structure(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Copy directories (but not files) from ``src_fs`` to ``dst_fs``.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
... |
Copy a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the... | def copy_dir(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy a directory from on... |
Copy a directory from one filesystem to another, checking times.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Argume... | def copy_dir_if_newer(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy a director... |
Extract code and message from ftp error. | def _parse_ftp_error(error):
# type: (ftplib.Error) -> Tuple[Text, Text]
"""Extract code and message from ftp error."""
code, _, message = text_type(error).partition(" ")
return code, message |
Open an ftp object for the file. | def _open_ftp(self):
# type: () -> FTP
"""Open an ftp object for the file."""
ftp = self.fs._open_ftp()
ftp.voidcmd(str("TYPE I"))
return ftp |
Parse a dict of features from FTP feat response. | def _parse_features(cls, feat_response):
# type: (Text) -> Dict[Text, Text]
"""Parse a dict of features from FTP feat response.
"""
features = {}
if feat_response.split("-")[0] == "211":
for line in feat_response.splitlines():
if line.startswith(" "):
... |
Open a new ftp object. | def _open_ftp(self):
# type: () -> FTP
"""Open a new ftp object.
"""
_ftp = FTP()
_ftp.set_debuglevel(0)
with ftp_errors(self):
_ftp.connect(self.host, self.port, self.timeout)
_ftp.login(self.user, self.passwd, self.acct)
self._feature... |
Get the FTP url this filesystem will open. | def ftp_url(self):
# type: () -> Text
"""Get the FTP url this filesystem will open."""
url = (
"ftp://{}".format(self.host)
if self.port == 21
else "ftp://{}:{}".format(self.host, self.port)
)
return url |
Parse a time from an ftp directory listing. | def _parse_ftp_time(cls, time_text):
# type: (Text) -> Optional[int]
"""Parse a time from an ftp directory listing.
"""
try:
tm_year = int(time_text[0:4])
tm_month = int(time_text[4:6])
tm_day = int(time_text[6:8])
tm_hour = int(time_text[8... |
Write the contents of a filesystem to a zip file.
Arguments:
src_fs (~fs.base.FS): The source filesystem to compress.
file (str or io.IOBase): Destination file, may be a file name
or an open file object.
compression (int): Compression to use (one of the constants
def... | def write_zip(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=zipfile.ZIP_DEFLATED, # type: int
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a zip file.
Arguments:
... |
Write the contents of a filesystem to a tar file.
Arguments:
file (str or io.IOBase): Destination file, may be a file
name or an open file object.
compression (str, optional): Compression to use, or `None`
for a plain Tar archive without compression.
encoding(str): T... | def write_tar(
src_fs, # type: FS
file, # type: Union[Text, BinaryIO]
compression=None, # type: Optional[Text]
encoding="utf-8", # type: Text
walker=None, # type: Optional[Walker]
):
# type: (...) -> None
"""Write the contents of a filesystem to a tar file.
Arguments:
file ... |
Compare a glob pattern with a path (case sensitive).
Arguments:
pattern (str): A glob pattern.
path (str): A path.
Returns:
bool: ``True`` if the path matches the pattern.
Example:
>>> from fs.glob import match
>>> match("**/*.py", "/fs/glob.py")
True | def match(pattern, path):
# type: (str, str) -> bool
"""Compare a glob pattern with a path (case sensitive).
Arguments:
pattern (str): A glob pattern.
path (str): A path.
Returns:
bool: ``True`` if the path matches the pattern.
Example:
>>> from fs.glob import mat... |
Count files / directories / data in matched paths.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count()
Counts(files=18519, directories=0, data=206690458)
Returns:
`~Counts`: A named tuple containing results. | def count(self):
# type: () -> Counts
"""Count files / directories / data in matched paths.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count()
Counts(files=18519, directories=0, data=206690458)
Returns:
`~Counts`:... |
Count the lines in the matched files.
Returns:
`~LineCounts`: A named tuple containing line counts.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count_lines()
LineCounts(lines=5767102, non_blank=4915110) | def count_lines(self):
# type: () -> LineCounts
"""Count the lines in the matched files.
Returns:
`~LineCounts`: A named tuple containing line counts.
Example:
>>> import fs
>>> fs.open_fs('~/projects').glob('**/*.py').count_lines()
LineC... |
Removed all matched paths.
Returns:
int: Number of file and directories removed.
Example:
>>> import fs
>>> fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove()
29 | def remove(self):
# type: () -> int
"""Removed all matched paths.
Returns:
int: Number of file and directories removed.
Example:
>>> import fs
>>> fs.open_fs('~/projects/my_project').glob('**/*.pyc').remove()
29
"""
remov... |
Move a file from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on ``src_fs``.
dst_fs (FS or str); Destination filesystem (instance or URL).
dst_path (str): Path to a file on ``dst_fs``. | def move_file(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
):
# type: (...) -> None
"""Move a file from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_pa... |
Move a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on ``src_fs``
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on ``dst_fs``.
... | def move_dir(
src_fs, # type: Union[Text, FS]
src_path, # type: Text
dst_fs, # type: Union[Text, FS]
dst_path, # type: Text
workers=0, # type: int
):
# type: (...) -> None
"""Move a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.