Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _step_decorator_args(self, decorator):
"""
Get arguments passed to step decorators converted to python objects.
"""
args = decorator.call.value
step = None
if len(args) == 1:
try:
step = args[0].value.to_python()
except (ValueEr... |
def iter_steps(self):
"""Iterate over steps in the parsed file."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
if step:
yield step, func.name, self._span_for_node(func, True) |
def _find_step_node(self, step_text):
"""Find the ast node which contains the text."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
arg_node = decorator.call.value[0].value
if step == step_text:
... |
def refactor_step(self, old_text, new_text, move_param_from_idx):
"""
Find the step with old_text and change it to new_text.
The step function parameters are also changed according
to move_param_from_idx. Each entry in this list should
specify parameter position from old
... |
def select_python_parser(parser=None):
"""
Select default parser for loading and refactoring steps. Passing `redbaron` as argument
will select the old paring engine from v0.3.3
Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our
best to make... |
def list(self, teamId, max=None, **request_parameters):
"""List team memberships for a team, by ID.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all team memberships re... |
def create(self, teamId, personId=None, personEmail=None,
isModerator=False, **request_parameters):
"""Add someone to a team by Person ID or email address.
Add someone to a team by Person ID or email address; optionally making
them a moderator.
Args:
teamId(b... |
def update(self, membershipId, isModerator=None, **request_parameters):
"""Update a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
isModerator(bool): Set to True to make the person a team moderator.
**request_parameters: Additional re... |
def delete(self, membershipId):
"""Delete a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
che... |
def get_catfact():
"""Get a cat fact from catfact.ninja and return it as a string.
Functions for Soundhound, Google, IBM Watson, or other APIs can be added
to create the desired functionality into this bot.
"""
response = requests.get(CAT_FACTS_URL, verify=False)
response.raise_for_status()
... |
def POST(self):
"""Respond to inbound webhook JSON HTTP POSTs from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = web.data()
print("\nWEBHOOK POST RECEIVED:")
print(json_data, "\n")
# Create a Webhook object from the JSON data
webhook_obj =... |
def list(self, roomId=None, personId=None, personEmail=None, max=None,
**request_parameters):
"""List room memberships.
By default, lists memberships for rooms to which the authenticated user
belongs.
Use query parameters to filter the response.
Use `roomId` to li... |
def delete(self, membershipId):
"""Delete a membership, by ID.
Args:
membershipId(basestring): The membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(me... |
def to_unicode(string):
"""Convert a string (bytes, str or unicode) to unicode."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, bytes):
return string.decode('utf-8')
else:
return string
else:
if isinstance(string... |
def to_bytes(string):
"""Convert a string (bytes, str or unicode) to bytes."""
assert isinstance(string, basestring)
if sys.version_info[0] >= 3:
if isinstance(string, str):
return string.encode('utf-8')
else:
return string
else:
if isinstance(string, unic... |
def validate_base_url(base_url):
"""Verify that base_url specifies a protocol and network location."""
parsed_url = urllib.parse.urlparse(base_url)
if parsed_url.scheme and parsed_url.netloc:
return parsed_url.geturl()
else:
error_message = "base_url must contain a valid scheme (protocol... |
def is_web_url(string):
"""Check to see if string is an validly-formatted web url."""
assert isinstance(string, basestring)
parsed_url = urllib.parse.urlparse(string)
return (
(
parsed_url.scheme.lower() == 'http'
or parsed_url.scheme.lower() == 'https'
)
... |
def open_local_file(file_path):
"""Open the file and return an EncodableFile tuple."""
assert isinstance(file_path, basestring)
assert is_local_file(file_path)
file_name = os.path.basename(file_path)
file_object = open(file_path, 'rb')
content_type = mimetypes.guess_type(file_name)[0] or 'text/p... |
def check_type(o, acceptable_types, may_be_none=True):
"""Object is an instance of one of the acceptable types or None.
Args:
o: The object to be inspected.
acceptable_types: A type or tuple of acceptable types.
may_be_none(bool): Whether or not the object may be None.
Raises:
... |
def dict_from_items_with_values(*dictionaries, **items):
"""Creates a dict with the inputted items; pruning any that are `None`.
Args:
*dictionaries(dict): Dictionaries of items to be pruned and included.
**items: Items to be pruned and included.
Returns:
dict: A dictionary contain... |
def check_response_code(response, expected_response_code):
"""Check response code against the expected code; raise ApiError.
Checks the requests.response.status_code against the provided expected
response code (erc), and raises a ApiError if they do not match.
Args:
response(requests.response)... |
def json_dict(json_data):
"""Given a dictionary or JSON string; return a dictionary.
Args:
json_data(dict, str): Input JSON object.
Returns:
A Python dictionary with the contents of the JSON object.
Raises:
TypeError: If the input object is not a dictionary or string.
"""... |
def strptime(cls, date_string, format=WEBEX_TEAMS_DATETIME_FORMAT):
"""strptime with the Webex Teams DateTime format as the default."""
return super(WebexTeamsDateTime, cls).strptime(
date_string, format
).replace(tzinfo=ZuluTimeZone()) |
def list(self, teamId=None, type=None, sortBy=None, max=None,
**request_parameters):
"""List rooms.
By default, lists rooms to which the authenticated user belongs.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It ... |
def create(self, title, teamId=None, **request_parameters):
"""Create a room.
The authenticated user is automatically added as a member of the room.
Args:
title(basestring): A user-friendly name for the room.
teamId(basestring): The team ID with which this room is
... |
def update(self, roomId, title=None, **request_parameters):
"""Update details for a room, by ID.
Args:
roomId(basestring): The room ID.
title(basestring): A user-friendly name for the room.
**request_parameters: Additional request parameters (provides
... |
def delete(self, roomId):
"""Delete a room.
Args:
roomId(basestring): The ID of the room to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(roomId, base... |
def list(self, orgId=None, **request_parameters):
"""List all licenses for a given organization.
If no orgId is specified, the default is the organization of the
authenticated user.
Args:
orgId(basestring): Specify the organization, by ID.
**request_parameters: ... |
def created(self):
"""Creation date and time in ISO8601 format."""
created = self._json_data.get('created')
if created:
return WebexTeamsDateTime.strptime(created)
else:
return None |
def generator_container(generator_function):
"""Function Decorator: Containerize calls to a generator function.
Args:
generator_function(func): The generator function being containerized.
Returns:
func: A wrapper function that containerizes the calls to the generator
function.
... |
def webex_teams_webhook_events():
"""Processes incoming requests to the '/events' URI."""
if request.method == 'GET':
return ("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webex Tea... |
def _get_access_token():
"""Attempt to get the access token from the environment.
Try using the current and legacy environment variables. If the access token
is found in a legacy environment variable, raise a deprecation warning.
Returns:
The access token found in the environment (str), or Non... |
def create(self, name, targetUrl, resource, event,
filter=None, secret=None, **request_parameters):
"""Create a webhook.
Args:
name(basestring): A user-friendly name for this webhook.
targetUrl(basestring): The URL that receives POST requests for
e... |
def update(self, webhookId, name=None, targetUrl=None,
**request_parameters):
"""Update a webhook, by ID.
Args:
webhookId(basestring): The webhook ID.
name(basestring): A user-friendly name for this webhook.
targetUrl(basestring): The URL that receives... |
def delete(self, webhookId):
"""Delete a webhook, by ID.
Args:
webhookId(basestring): The ID of the webhook to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
chec... |
def _fix_next_url(next_url):
"""Remove max=null parameter from URL.
Patch for Webex Teams Defect: 'next' URL returned in the Link headers of
the responses contain an errant 'max=null' parameter, which causes the
next request (to this URL) to fail if the URL is requested as-is.
This patch parses t... |
def single_request_timeout(self, value):
"""The timeout (seconds) for a single HTTP REST API request."""
check_type(value, int)
assert value is None or value > 0
self._single_request_timeout = value |
def wait_on_rate_limit(self, value):
"""Enable or disable automatic rate-limit handling."""
check_type(value, bool, may_be_none=False)
self._wait_on_rate_limit = value |
def update_headers(self, headers):
"""Update the HTTP headers used for requests in this session.
Note: Updates provided by the dictionary passed as the `headers`
parameter to this method are merged into the session headers by adding
new key-value pairs and/or updating the values of exis... |
def abs_url(self, url):
"""Given a relative or absolute URL; return an absolute URL.
Args:
url(basestring): A relative or absolute URL.
Returns:
str: An absolute URL.
"""
parsed_url = urllib.parse.urlparse(url)
if not parsed_url.scheme and not p... |
def request(self, method, url, erc, **kwargs):
"""Abstract base method for making requests to the Webex Teams APIs.
This base method:
* Expands the API endpoint URL to an absolute URL
* Makes the actual HTTP request to the API endpoint
* Provides support for Webex Te... |
def get(self, url, params=None, **kwargs):
"""Sends a GET request.
Args:
url(basestring): The URL of the API endpoint.
params(dict): The parameters for the HTTP GET request.
**kwargs:
erc(int): The expected (success) response code for the request.
... |
def get_pages(self, url, params=None, **kwargs):
"""Return a generator that GETs and yields pages of data.
Provides native support for RFC5988 Web Linking.
Args:
url(basestring): The URL of the API endpoint.
params(dict): The parameters for the HTTP GET request.
... |
def get_items(self, url, params=None, **kwargs):
"""Return a generator that GETs and yields individual JSON `items`.
Yields individual `items` from Webex Teams's top-level {'items': [...]}
JSON objects. Provides native support for RFC5988 Web Linking. The
generator will request additio... |
def put(self, url, json=None, data=None, **kwargs):
"""Sends a PUT request.
Args:
url(basestring): The URL of the API endpoint.
json: Data to be sent in JSON format in tbe body of the request.
data: Data to be sent in the body of the request.
**kwargs:
... |
def delete(self, url, **kwargs):
"""Sends a DELETE request.
Args:
url(basestring): The URL of the API endpoint.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
... |
def create(self, subject, displayName, issuerToken, expiration, secret):
"""Create a new guest issuer using the provided issuer token.
This function returns a guest issuer with an api access token.
Args:
subject(basestring): Unique and public identifier
displayName(base... |
def list(self, roomId, mentionedPeople=None, before=None,
beforeMessage=None, max=None, **request_parameters):
"""Lists messages in a room.
Each message will include content attachments if present.
The list API sorts the messages in descending order by creation date.
This... |
def create(self, roomId=None, toPersonId=None, toPersonEmail=None,
text=None, markdown=None, files=None, **request_parameters):
"""Post a message, and optionally a attachment, to a room.
The files parameter is a list, which accepts multiple values to allow
for future expansion, b... |
def delete(self, messageId):
"""Delete a message.
Args:
messageId(basestring): The ID of the message to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(... |
def list(self, email=None, displayName=None, id=None, orgId=None, max=None,
**request_parameters):
"""List people
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yie... |
def create(self, emails, displayName=None, firstName=None, lastName=None,
avatar=None, orgId=None, roles=None, licenses=None,
**request_parameters):
"""Create a new user account for a given organization
Only an admin can create a new user account.
Args:
... |
def get(self, personId):
"""Get a person's details, by ID.
Args:
personId(basestring): The ID of the person to be retrieved.
Returns:
Person: A Person object with the details of the requested person.
Raises:
TypeError: If the parameter types are inc... |
def update(self, personId, emails=None, displayName=None, firstName=None,
lastName=None, avatar=None, orgId=None, roles=None,
licenses=None, **request_parameters):
"""Update details for a person, by ID.
Only an admin can update a person's details.
Email addresses ... |
def delete(self, personId):
"""Remove a person from the system.
Only an admin can remove a person.
Args:
personId(basestring): The ID of the person to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams ... |
def me(self):
"""Get the details of the person accessing the API.
Raises:
ApiError: If the Webex Teams cloud returns an error.
"""
# API request
json_data = self._session.get(API_ENDPOINT + '/me')
# Return a person object created from the response JSON data... |
def list(self, **request_parameters):
"""List all roles.
Args:
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
... |
def list(self, max=None, **request_parameters):
"""List teams to which the authenticated user belongs.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all teams returned b... |
def create(self, name, **request_parameters):
"""Create a team.
The authenticated user is automatically added as a member of the team.
Args:
name(basestring): A user-friendly name for the team.
**request_parameters: Additional request parameters (provides
... |
def update(self, teamId, name=None, **request_parameters):
"""Update details for a team, by ID.
Args:
teamId(basestring): The team ID.
name(basestring): A user-friendly name for the team.
**request_parameters: Additional request parameters (provides
s... |
def delete(self, teamId):
"""Delete a team.
Args:
teamId(basestring): The ID of the team to be deleted.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(teamId, base... |
def list(self, resource=None, type=None, actorId=None, _from=None, to=None,
max=None, **request_parameters):
"""List events.
List events in your organization. Several query parameters are
available to filter the response.
Note: `from` is a keyword in Python and may not be ... |
def _serialize(cls, data):
"""Serialize data to an frozen tuple."""
if hasattr(data, "__hash__") and callable(data.__hash__):
# If the data is already hashable (should be immutable) return it
return data
elif isinstance(data, list):
# Freeze the elements of th... |
def get(self, client_id, client_secret, code, redirect_uri):
"""Exchange an Authorization Code for an Access Token.
Exchange an Authorization Code for an Access Token that can be used to
invoke the APIs.
Args:
client_id(basestring): Provided when you created your integratio... |
def lastActivity(self):
"""The date and time of the person's last activity."""
last_activity = self._json_data.get('lastActivity')
if last_activity:
return WebexTeamsDateTime.strptime(last_activity)
else:
return None |
def post_events_service(request):
"""Respond to inbound webhook JSON HTTP POST from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = request.json
log.info("\n")
log.info("WEBHOOK POST RECEIVED:")
log.info(json_data)
log.info("\n")
# Create a Webhook object from the... |
def get_ngrok_public_url():
"""Get the ngrok public HTTP URL from the local client API."""
try:
response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels",
headers={'content-type': 'application/json'})
response.raise_for_status()
except request... |
def delete_webhooks_with_name(api, name):
"""Find a webhook by name."""
for webhook in api.webhooks.list():
if webhook.name == name:
print("Deleting Webhook:", webhook.name, webhook.targetUrl)
api.webhooks.delete(webhook.id) |
def create_ngrok_webhook(api, ngrok_public_url):
"""Create a Webex Teams webhook pointing to the public ngrok URL."""
print("Creating Webhook...")
webhook = api.webhooks.create(
name=WEBHOOK_NAME,
targetUrl=urljoin(ngrok_public_url, WEBHOOK_URL_SUFFIX),
resource=WEBHOOK_RESOURC... |
def main():
"""Delete previous webhooks. If local ngrok tunnel, create a webhook."""
api = WebexTeamsAPI()
delete_webhooks_with_name(api, name=WEBHOOK_NAME)
public_url = get_ngrok_public_url()
if public_url is not None:
create_ngrok_webhook(api, public_url) |
def read(self):
"""
Since there isn't a real sensor connected, read() creates random
data.
"""
data = [0]*6
for i in range(6):
data[i] = random.uniform(-2048, 2048)
accel = data[:3]
mag = data[3:]
return (accel, mag) |
def console():
"""Output DSMR data to console."""
parser = argparse.ArgumentParser(description=console.__doc__)
parser.add_argument('--device', default='/dev/ttyUSB0',
help='port to read DSMR data from')
parser.add_argument('--host', default=None,
help='a... |
def read(self):
"""
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's
:rtype: generator
"""
with serial.Serial(**self.serial_settings) as serial_handle:
while True:
data = serial_handle.re... |
def read(self, queue):
"""
Read complete DSMR telegram's from the serial interface and parse it
into CosemObject's and MbusObject's.
Instead of being a generator, values are pushed to provided queue for
asynchronous processing.
:rtype: None
"""
# create ... |
def create_dsmr_protocol(dsmr_version, telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol."""
if dsmr_version == '2.2':
specification = telegram_specifications.V2_2
serial_settings = SERIAL_SETTINGS_V2_2
elif dsmr_version == '4':
specification = telegram_specification... |
def create_dsmr_reader(port, dsmr_version, telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol coroutine using serial port."""
protocol, serial_settings = create_dsmr_protocol(
dsmr_version, telegram_callback, loop=None)
serial_settings['url'] = port
conn = create_serial_connectio... |
def create_tcp_dsmr_reader(host, port, dsmr_version,
telegram_callback, loop=None):
"""Creates a DSMR asyncio protocol coroutine using TCP connection."""
protocol, _ = create_dsmr_protocol(
dsmr_version, telegram_callback, loop=None)
conn = loop.create_connection(protocol,... |
def data_received(self, data):
"""Add incoming data to buffer."""
data = data.decode('ascii')
self.log.debug('received data: %s', data)
self.telegram_buffer.append(data)
for telegram in self.telegram_buffer.get_all():
self.handle_telegram(telegram) |
def connection_lost(self, exc):
"""Stop when connection is lost."""
if exc:
self.log.exception('disconnected due to exception')
else:
self.log.info('disconnected because of close/abort.')
self._closed.set() |
def handle_telegram(self, telegram):
"""Send off parsed telegram to handling callback."""
self.log.debug('got telegram: %s', telegram)
try:
parsed_telegram = self.telegram_parser.parse(telegram)
except InvalidChecksumError as e:
self.log.warning(str(e))
e... |
def parse(self, telegram_data):
"""
Parse telegram from string to dict.
The telegram str type makes python 2.x integration easier.
:param str telegram_data: full telegram from start ('/') to checksum
('!ABCD') including line endings in between the telegram's lines
:... |
def validate_checksum(telegram):
"""
:param str telegram:
:raises ParseError:
:raises InvalidChecksumError:
"""
# Extract the part for which the checksum applies.
checksum_contents = re.search(r'\/.+\!', telegram, re.DOTALL)
# Extract the hexadecimal che... |
def _remove(self, telegram):
"""
Remove telegram from buffer and incomplete data preceding it. This
is easier than validating the data before adding it to the buffer.
:param str telegram:
:return:
"""
# Remove data leading up to the telegram and the telegram itsel... |
def get_version(file, name='__version__'):
"""Get the version of the package from the given file by
executing it and extracting the given `name`.
"""
path = os.path.realpath(file)
version_ns = {}
with io.open(path, encoding="utf8") as f:
exec(f.read(), {}, version_ns)
return version_... |
def ensure_python(specs):
"""Given a list of range specifiers for python, ensure compatibility.
"""
if not isinstance(specs, (list, tuple)):
specs = [specs]
v = sys.version_info
part = '%s.%s' % (v.major, v.minor)
for spec in specs:
if part == spec:
return
try... |
def find_packages(top=HERE):
"""
Find all of the packages.
"""
packages = []
for d, dirs, _ in os.walk(top, followlinks=True):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(os.path.relpath(d, top).replace(os.path.sep, '.'))
elif d != top:
# Do no... |
def create_cmdclass(prerelease_cmd=None, package_data_spec=None,
data_files_spec=None):
"""Create a command class with the given optional prerelease class.
Parameters
----------
prerelease_cmd: (name, Command) tuple, optional
The command to run before releasing.
package_data_spec: d... |
def command_for_func(func):
"""Create a command that calls the given function."""
class FuncCommand(BaseCommand):
def run(self):
func()
update_package_data(self.distribution)
return FuncCommand |
def run(cmd, **kwargs):
"""Echo a command before running it. Defaults to repo as cwd"""
log.info('> ' + list2cmdline(cmd))
kwargs.setdefault('cwd', HERE)
kwargs.setdefault('shell', os.name == 'nt')
if not isinstance(cmd, (list, tuple)) and os.name != 'nt':
cmd = shlex.split(cmd)
cmd[0] ... |
def recursive_mtime(path, newest=True):
"""Gets the newest/oldest mtime for all files in a directory."""
if os.path.isfile(path):
return mtime(path)
current_extreme = None
for dirname, dirnames, filenames in os.walk(path, topdown=False):
for filename in filenames:
mt = mtime(... |
def ensure_targets(targets):
"""Return a Command that checks that certain files exist.
Raises a ValueError if any of the files are missing.
Note: The check is skipped if the `--skip-npm` flag is used.
"""
class TargetsCheck(BaseCommand):
def run(self):
if skip_npm:
... |
def _wrap_command(cmds, cls, strict=True):
"""Wrap a setup command
Parameters
----------
cmds: list(str)
The names of the other commands to run prior to the command.
strict: boolean, optional
Whether to raise errors when a pre-command fails.
"""
class WrappedCommand(cls):
... |
def _get_file_handler(package_data_spec, data_files_spec):
"""Get a package_data and data_files handler command.
"""
class FileHandler(BaseCommand):
def run(self):
package_data = self.distribution.package_data
package_spec = package_data_spec or dict()
for (key,... |
def _get_data_files(data_specs, existing):
"""Expand data file specs into valid data files metadata.
Parameters
----------
data_specs: list of tuples
See [createcmdclass] for description.
existing: list of tuples
The existing distribution data_files metadata.
Returns
------... |
def _get_package_data(root, file_patterns=None):
"""Expand file patterns to a list of `package_data` paths.
Parameters
-----------
root: str
The relative path to the package root from `HERE`.
file_patterns: list or str, optional
A list of glob patterns for the data file locations.
... |
def _compile_pattern(pat, ignore_case=True):
"""Translate and compile a glob pattern to a regular expression matcher."""
if isinstance(pat, bytes):
pat_str = pat.decode('ISO-8859-1')
res_str = _translate_glob(pat_str)
res = res_str.encode('ISO-8859-1')
else:
res = _translate_... |
def _iexplode_path(path):
"""Iterate over all the parts of a path.
Splits path recursively with os.path.split().
"""
(head, tail) = os.path.split(path)
if not head or (not tail and head == path):
if head:
yield head
if tail or not head:
yield tail
ret... |
def _translate_glob(pat):
"""Translate a glob PATTERN to a regular expression."""
translated_parts = []
for part in _iexplode_path(pat):
translated_parts.append(_translate_glob_part(part))
os_sep_class = '[%s]' % re.escape(SEPARATORS)
res = _join_translated(translated_parts, os_sep_class)
... |
def _join_translated(translated_parts, os_sep_class):
"""Join translated glob pattern parts.
This is different from a simple join, as care need to be taken
to allow ** to match ZERO or more directories.
"""
res = ''
for part in translated_parts[:-1]:
if part == '.*':
# drop ... |
def _translate_glob_part(pat):
"""Translate a glob PATTERN PART to a regular expression."""
# Code modified from Python 3 standard lib fnmatch:
if pat == '**':
return '.*'
i, n = 0, len(pat)
res = []
while i < n:
c = pat[i]
i = i + 1
if c == '*':
# Mat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.