_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q271400 | RestSession.request | test | 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 Teams rate-limiting
* Inspects response codes and raises exceptions as appropriate
Args:
method(basestring): The request-method type ('GET', 'POST', etc.).
url(basestring): The URL of the API endpoint to be called.
erc(int): The expected response code that should be returned by the
Webex Teams API endpoint to indicate success.
**kwargs: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
"""
# Ensure the url is an absolute URL
abs_url = self.abs_url(url)
# Update request kwargs with session defaults
kwargs.setdefault('timeout', self.single_request_timeout)
while True:
# Make the HTTP | python | {
"resource": ""
} |
q271401 | RestSession.get | test | 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.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
"""
| python | {
"resource": ""
} |
q271402 | RestSession.get_pages | test | 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.
**kwargs:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
| python | {
"resource": ""
} |
q271403 | RestSession.get_items | test | 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 additional pages as needed until all items have
been returned.
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.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
MalformedResponse: If the returned response does not contain a
top-level dictionary with an 'items' key.
"""
# Get generator for | python | {
"resource": ""
} |
q271404 | RestSession.put | test | 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:
erc(int): The expected (success) response code for the request.
others: Passed on to the requests package.
Raises:
ApiError: If anything other than the expected response code is
| python | {
"resource": ""
} |
q271405 | RestSession.delete | test | 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:
ApiError: If anything other than the expected response code is
returned by the Webex Teams API endpoint.
"""
| python | {
"resource": ""
} |
q271406 | GuestIssuerAPI.create | test | 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(basestring): Display Name of the guest user
issuerToken(basestring): Issuer token from developer hub
expiration(basestring): Expiration time as a unix timestamp
secret(basestring): The secret used to sign your guest issuers
Returns:
GuestIssuerToken: A Guest Issuer with a valid access token.
Raises:
TypeError: If the parameter types are incorrect
ApiError: If the webex teams cloud returns an error.
"""
check_type(subject, basestring)
check_type(displayName, basestring)
check_type(issuerToken, basestring)
check_type(expiration, basestring)
check_type(secret, basestring)
payload = {
"sub": subject,
| python | {
"resource": ""
} |
q271407 | MessagesAPI.list | test | 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 method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all messages returned by the
query. The generator will automatically request additional 'pages' of
responses from Webex as needed until all responses have been returned.
The container makes the generator safe for reuse. A new API call will
be made, using the same parameters that were specified when the
generator was created, every time a new iterator is requested from the
container.
Args:
roomId(basestring): List messages for a room, by ID.
mentionedPeople(basestring): List messages where the caller is
| python | {
"resource": ""
} |
q271408 | MessagesAPI.create | test | 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, but currently only one file may be included with
the message.
Args:
roomId(basestring): The room ID.
toPersonId(basestring): The ID of the recipient when sending a
private 1:1 message.
toPersonEmail(basestring): The email address of the recipient when
sending a private 1:1 message.
text(basestring): The message, in plain text. If `markdown` is
specified this parameter may be optionally used to provide
alternate text for UI clients that do not support rich text.
markdown(basestring): The message, in markdown format.
files(`list`): A list of public URL(s) or local path(s) to files to
be posted into the room. Only one file is allowed per message.
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
Message: A Message object with the details of the created message.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
ValueError: If the files parameter is a list of length > 1, or if
the string in the list (the only element in the list) does not
contain a valid URL or path to a local file.
"""
check_type(roomId, basestring)
check_type(toPersonId, basestring)
check_type(toPersonEmail, basestring)
check_type(text, basestring)
check_type(markdown, basestring)
check_type(files, list)
if files:
if len(files) != 1:
raise ValueError("The length of the `files` list is greater "
"than one (1). The files parameter is a "
"list, which accepts multiple values to "
| python | {
"resource": ""
} |
q271409 | MessagesAPI.delete | test | 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.
| python | {
"resource": ""
} |
q271410 | PeopleAPI.create | test | 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:
emails(`list`): Email address(es) of the person (list of strings).
displayName(basestring): Full name of the person.
firstName(basestring): First name of the person.
lastName(basestring): Last name of the person.
avatar(basestring): URL to the person's avatar in PNG format.
orgId(basestring): ID of the organization to which this
person belongs.
roles(`list`): Roles of the person (list of strings containing
the role IDs to be assigned to the person).
licenses(`list`): Licenses allocated to the person (list of
strings - containing the license IDs to be allocated to the
person).
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
Person: A Person object with the details of the created person.
Raises:
| python | {
"resource": ""
} |
q271411 | PeopleAPI.get | test | 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:
| python | {
"resource": ""
} |
q271412 | PeopleAPI.update | test | 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 for a person cannot be changed via the Webex Teams API.
Include all details for the person. This action expects all user
details to be present in the request. A common approach is to first GET
the person's details, make changes, then PUT both the changed and
unchanged values.
Args:
personId(basestring): The person ID.
emails(`list`): Email address(es) of the person (list of strings).
displayName(basestring): Full name of the person.
firstName(basestring): First name of the person.
lastName(basestring): Last name of the person.
avatar(basestring): URL to the person's avatar in PNG format.
orgId(basestring): ID of the organization to which this
| python | {
"resource": ""
} |
q271413 | PeopleAPI.delete | test | 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.
| python | {
"resource": ""
} |
q271414 | PeopleAPI.me | test | 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')
| python | {
"resource": ""
} |
q271415 | RolesAPI.list | test | 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,
yields the roles returned by the Webex Teams query.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
| python | {
"resource": ""
} |
q271416 | TeamsAPI.list | test | 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 by the
query. The generator will automatically request additional 'pages' of
responses from Webex as needed until all responses have been returned.
The container makes the generator safe for reuse. A new API call will
be made, using the same parameters that were specified when the
generator was created, every time a new iterator is requested from the
container.
Args:
max(int): Limit the maximum number of items returned from the Webex
Teams service per request.
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
| python | {
"resource": ""
} |
q271417 | TeamsAPI.create | test | 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
support for parameters that may be added in the future).
Returns:
Team: A Team object with the details of the created team.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
| python | {
"resource": ""
} |
q271418 | TeamsAPI.update | test | 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
support for parameters that may be added in the future).
Returns:
Team: A Team object with the updated Webex Teams team details.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(teamId, | python | {
"resource": ""
} |
q271419 | TeamsAPI.delete | test | 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.
| python | {
"resource": ""
} |
q271420 | EventsAPI.list | test | 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 used as a variable
name, so we had to use `_from` instead.
This method supports Webex Teams's implementation of RFC5988 Web
Linking to provide pagination support. It returns a generator
container that incrementally yields all events returned by the
query. The generator will automatically request additional 'pages' of
responses from Wevex as needed until all responses have been returned.
The container makes the generator safe for reuse. A new API call will
be made, using the same parameters that were specified when the
generator was created, every time a new iterator is requested from the
container.
Args:
resource(basestring): Limit results to a specific resource type.
Possible values: "messages", "memberships".
type(basestring): Limit results to a specific event type. Possible
values: "created", "updated", "deleted".
actorId(basestring): Limit results to events performed by this
person, by ID.
_from(basestring): Limit results to events which occurred after a
date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
to(basestring): Limit results to events which occurred before a
date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
max(int): Limit the maximum number of items returned from the Webex
Teams service per request.
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
yields the events returned by the Webex Teams query.
Raises: | python | {
"resource": ""
} |
q271421 | ImmutableData._serialize | test | 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 the list and return as a tuple
return tuple((cls._serialize(item) for item in data))
elif isinstance(data, dict):
# Freeze the elements of the dictionary, sort them, and return
# them as a list of tuples
key_value_tuples = [ | python | {
"resource": ""
} |
q271422 | AccessTokensAPI.get | test | 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 integration.
client_secret(basestring): Provided when you created your
integration.
code(basestring): The Authorization Code provided by the user
OAuth process.
redirect_uri(basestring): The redirect URI used in the user OAuth
process.
Returns:
AccessToken: An AccessToken object with the access token provided
by the Webex Teams cloud.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(client_id, basestring, may_be_none=False)
check_type(client_secret, basestring, may_be_none=False)
check_type(code, basestring, may_be_none=False)
check_type(redirect_uri, basestring, may_be_none=False)
post_data = dict_from_items_with_values(
grant_type="authorization_code", | python | {
"resource": ""
} |
q271423 | PersonBasicPropertiesMixin.lastActivity | test | def lastActivity(self):
"""The date and time of the person's last activity."""
last_activity = self._json_data.get('lastActivity')
if last_activity:
| python | {
"resource": ""
} |
q271424 | post_events_service | test | 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 JSON data
webhook_obj = Webhook(json_data)
# Get the room details
room = api.rooms.get(webhook_obj.data.roomId)
# Get the message details
message = api.messages.get(webhook_obj.data.id)
# Get the sender's details
person = api.people.get(message.personId)
log.info("NEW MESSAGE IN ROOM '{}'".format(room.title))
log.info("FROM '{}'".format(person.displayName))
log.info("MESSAGE '{}'\n".format(message.text))
# This is a VERY IMPORTANT loop prevention control step.
# If you respond to all messages... You will respond to the messages
# that the bot posts and thereby create a loop condition.
me = api.people.me()
| python | {
"resource": ""
} |
q271425 | get_ngrok_public_url | test | 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()
| python | {
"resource": ""
} |
q271426 | delete_webhooks_with_name | test | def delete_webhooks_with_name(api, name):
"""Find a webhook by name."""
for webhook in api.webhooks.list():
if webhook.name == name:
| python | {
"resource": ""
} |
q271427 | create_ngrok_webhook | test | 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, | python | {
"resource": ""
} |
q271428 | main | test | def main():
"""Delete previous webhooks. If local ngrok tunnel, create a webhook."""
api = WebexTeamsAPI()
delete_webhooks_with_name(api, name=WEBHOOK_NAME)
| python | {
"resource": ""
} |
q271429 | console | test | 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='alternatively connect using TCP host.')
parser.add_argument('--port', default=None,
help='TCP port to use for connection')
parser.add_argument('--version', default='2.2', choices=['2.2', '4'],
help='DSMR version (2.2, 4)')
parser.add_argument('--verbose', '-v', action='count')
args = parser.parse_args()
if args.verbose:
level = logging.DEBUG
else:
level = logging.ERROR
logging.basicConfig(level=level)
loop = asyncio.get_event_loop()
def print_callback(telegram):
"""Callback that prints telegram values."""
| python | {
"resource": ""
} |
q271430 | SerialReader.read | test | 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.readline()
self.telegram_buffer.append(data.decode('ascii'))
for telegram in self.telegram_buffer.get_all():
try:
| python | {
"resource": ""
} |
q271431 | AsyncSerialReader.read | test | 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 Serial StreamReader
conn = serial_asyncio.open_serial_connection(**self.serial_settings)
reader, _ = yield from conn
while True:
# Read line if available or give control back to loop until new
# data has arrived.
data = yield from | python | {
"resource": ""
} |
q271432 | create_dsmr_protocol | test | 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_specifications.V4
serial_settings = SERIAL_SETTINGS_V4
elif dsmr_version == '5':
specification = telegram_specifications.V5
| python | {
"resource": ""
} |
q271433 | create_dsmr_reader | test | 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)
| python | {
"resource": ""
} |
q271434 | create_tcp_dsmr_reader | test | 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(
| python | {
"resource": ""
} |
q271435 | DSMRProtocol.data_received | test | 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)
| python | {
"resource": ""
} |
q271436 | DSMRProtocol.connection_lost | test | def connection_lost(self, exc):
"""Stop when connection is lost."""
if exc:
self.log.exception('disconnected due to exception')
else:
| python | {
"resource": ""
} |
q271437 | DSMRProtocol.handle_telegram | test | 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) | python | {
"resource": ""
} |
q271438 | TelegramParser.parse | test | 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
:rtype: dict
:returns: Shortened example:
{
..
r'\d-\d:96\.1\.1.+?\r\n': <CosemObject>, # EQUIPMENT_IDENTIFIER
r'\d-\d:1\.8\.1.+?\r\n': <CosemObject>, # ELECTRICITY_USED_TARIFF_1
| python | {
"resource": ""
} |
q271439 | get_version | test | 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)
| python | {
"resource": ""
} |
q271440 | ensure_python | test | 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
| python | {
"resource": ""
} |
q271441 | find_packages | test | 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, '.'))
| python | {
"resource": ""
} |
q271442 | create_cmdclass | test | 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: dict, optional
A dictionary whose keys are the dotted package names and
whose values are a list of glob patterns.
data_files_spec: list, optional
A list of (path, dname, pattern) tuples where the path is the
`data_files` install path, dname is the source directory, and the
pattern is a glob pattern.
Notes
-----
We use specs so that we can find the files *after* the build
command has run.
The package data glob patterns should be relative paths from the package
folder | python | {
"resource": ""
} |
q271443 | command_for_func | test | def command_for_func(func):
"""Create a command that calls the given function."""
class FuncCommand(BaseCommand):
def run(self):
| python | {
"resource": ""
} |
q271444 | run | test | 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)) | python | {
"resource": ""
} |
q271445 | ensure_targets | test | 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:
log.info('Skipping target checks')
return
| python | {
"resource": ""
} |
q271446 | _wrap_command | test | 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 run(self):
if not getattr(self, 'uninstall', None):
try:
[self.run_command(cmd) for cmd in cmds]
| python | {
"resource": ""
} |
q271447 | _get_file_handler | test | 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, patterns) in package_spec.items():
| python | {
"resource": ""
} |
q271448 | _get_data_files | test | 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
-------
A valid list of data_files items.
"""
# Extract the existing data files into a staging object.
file_data = defaultdict(list)
for (path, files) in existing or []:
| python | {
"resource": ""
} |
q271449 | _get_package_data | test | 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.
The globs can be recursive if they include a `**`.
They should | python | {
"resource": ""
} |
q271450 | _compile_pattern | test | 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') | python | {
"resource": ""
} |
q271451 | _iexplode_path | test | 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:
| python | {
"resource": ""
} |
q271452 | _translate_glob | test | def _translate_glob(pat):
"""Translate a glob PATTERN to a regular expression."""
translated_parts = []
for part in _iexplode_path(pat):
| python | {
"resource": ""
} |
q271453 | _join_translated | test | 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 separator, since it is optional
# (** matches ZERO or more dirs)
res += part
else:
res += part + os_sep_class
| python | {
"resource": ""
} |
q271454 | _translate_glob_part | test | 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 == '*':
# Match anything but path separators:
res.append('[^%s]*' % SEPARATORS)
elif c == '?':
res.append('[^%s]?' % SEPARATORS)
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j + 1
if j < n and pat[j] == ']':
j = j + 1
while j < n and pat[j] != ']':
j | python | {
"resource": ""
} |
q271455 | PostgresDbWriter.truncate | test | def truncate(self, table):
"""Send DDL to truncate the specified `table`
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
Returns None
"""
truncate_sql, | python | {
"resource": ""
} |
q271456 | PostgresDbWriter.write_table | test | def write_table(self, table):
"""Send DDL to create the specified `table`
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
Returns None
"""
table_sql, | python | {
"resource": ""
} |
q271457 | PostgresDbWriter.write_indexes | test | def write_indexes(self, table):
"""Send DDL to create the specified `table` indexes
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that | python | {
"resource": ""
} |
q271458 | PostgresDbWriter.write_triggers | test | def write_triggers(self, table):
"""Send DDL to create the specified `table` triggers
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that | python | {
"resource": ""
} |
q271459 | PostgresDbWriter.write_constraints | test | def write_constraints(self, table):
"""Send DDL to create the specified `table` constraints
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that | python | {
"resource": ""
} |
q271460 | PostgresDbWriter.write_contents | test | def write_contents(self, table, reader):
"""Write the contents of `table`
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
- `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader` object that allows reading from the data source.
Returns None | python | {
"resource": ""
} |
q271461 | PostgresWriter.process_row | test | def process_row(self, table, row):
"""Examines row data from MySQL and alters
the values when necessary to be compatible with
sending to PostgreSQL via the copy command
"""
for index, column in enumerate(table.columns):
hash_key = hash(frozenset(column.items()))
column_type = self.column_types[hash_key] if hash_key in self.column_types else self.column_type(column)
if row[index] == None and ('timestamp' not in column_type or not column['default']):
row[index] = '\N'
elif row[index] == None and column['default']:
if self.tz:
row[index] = '1970-01-01T00:00:00.000000' + self.tz_offset
else:
row[index] = '1970-01-01 00:00:00'
elif 'bit' in column_type:
row[index] = bin(ord(row[index]))[2:]
elif isinstance(row[index], (str, unicode, basestring)):
if column_type == 'bytea':
row[index] = Binary(row[index]).getquoted()[1:-8] if row[index] else row[index]
elif 'text[' in column_type:
row[index] = '{%s}' % ','.join('"%s"' % v.replace('"', r'\"') for v in row[index].split(','))
else:
row[index] = row[index].replace('\\', r'\\').replace('\n', r'\n').replace(
'\t', r'\t').replace('\r', r'\r').replace('\0', | python | {
"resource": ""
} |
q271462 | PostgresFileWriter.write_indexes | test | def write_indexes(self, table):
"""Write DDL of `table` indexes to the output file
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
| python | {
"resource": ""
} |
q271463 | PostgresFileWriter.write_constraints | test | def write_constraints(self, table):
"""Write DDL of `table` constraints to the output file
:Parameters:
- `table`: an instance of a | python | {
"resource": ""
} |
q271464 | PostgresFileWriter.write_triggers | test | def write_triggers(self, table):
"""Write TRIGGERs existing on `table` to the output file
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. | python | {
"resource": ""
} |
q271465 | SQLStepQueue.qsize | test | def qsize(self, extra_predicate=None):
""" Return an approximate number of queued tasks in | python | {
"resource": ""
} |
q271466 | SQLStepQueue.enqueue | test | def enqueue(self, data):
""" Enqueue task with specified data. """
jsonified_data = json.dumps(data)
with self._db_conn() as conn:
return conn.execute(
'INSERT INTO %s (created, data) VALUES | python | {
"resource": ""
} |
q271467 | SQLStepQueue.start | test | def start(self, block=False, timeout=None, retry_interval=0.5, extra_predicate=None):
"""
Retrieve a task handler from the queue.
If block is True, this function will block until it is able to retrieve a task.
If block is True and timeout is a number it will block for at most <timeout> seconds.
retry_interval is the maximum time in seconds between successive retries.
extra_predicate
If extra_predicate is defined, it should be a tuple of (raw_predicate, predicate_args)
raw_predicate will be prefixed by AND, and inserted into the WHERE condition in the queries.
predicate_args will be sql escaped and formatted into raw_predicate.
"""
start = time.time()
| python | {
"resource": ""
} |
q271468 | SQLStepQueue._build_extra_predicate | test | def _build_extra_predicate(self, extra_predicate):
""" This method is a good one to extend if you want to create a queue which always applies an extra predicate. """
if extra_predicate is None:
return ''
# if they don't have a supported format seq, wrap it for them
if not isinstance(extra_predicate[1], (list, dict, | python | {
"resource": ""
} |
q271469 | simplejson_datetime_serializer | test | def simplejson_datetime_serializer(obj):
"""
Designed to be passed as the default kwarg in simplejson.dumps. Serializes dates and datetimes to ISO | python | {
"resource": ""
} |
q271470 | Connection.reconnect | test | def reconnect(self):
"""Closes the existing database connection and re-opens it."""
conn = _mysql.connect(**self._db_args)
| python | {
"resource": ""
} |
q271471 | Connection.get | test | def get(self, query, *parameters, **kwparameters):
"""Returns the first row returned for the given query."""
rows = self._query(query, parameters, kwparameters)
if not rows:
return None
elif not isinstance(rows, list):
| python | {
"resource": ""
} |
q271472 | get_connection | test | def get_connection(db=DATABASE):
""" Returns a new connection to the | python | {
"resource": ""
} |
q271473 | run_benchmark | test | def run_benchmark():
""" Run a set of InsertWorkers and record their performance. """
stopping = threading.Event()
workers = [ InsertWorker(stopping) for _ in range(NUM_WORKERS) ]
print('Launching %d workers' % NUM_WORKERS)
[ worker.start() for worker in workers ]
time.sleep(WORKLOAD_TIME)
print('Stopping workload')
stopping.set()
[ worker.join() for worker in workers ]
| python | {
"resource": ""
} |
q271474 | RandomAggregatorPool._connect | test | def _connect(self):
""" Returns an aggregator connection. """
with self._lock:
if self._aggregator:
try:
return self._pool_connect(self._aggregator)
except PoolConnectionException:
self._aggregator = None
if not len(self._aggregators):
with self._pool_connect(self._primary_aggregator) as conn:
self._update_aggregator_list(conn)
conn.expire()
random.shuffle(self._aggregators)
last_exception = None
for aggregator in self._aggregators:
self.logger.debug('Attempting connection with %s:%s' % (aggregator[0], aggregator[1]))
try:
conn = self._pool_connect(aggregator)
# connection successful!
| python | {
"resource": ""
} |
q271475 | lookup_by_number | test | def lookup_by_number(errno):
""" Used for development only """
for key, val in | python | {
"resource": ""
} |
q271476 | ConnectionPool.size | test | def size(self):
""" Returns the number of connections cached by | python | {
"resource": ""
} |
q271477 | _PoolConnectionFairy.__potential_connection_failure | test | def __potential_connection_failure(self, e):
""" OperationalError's are emitted by the _mysql library for
almost every error code emitted by MySQL. Because of this we
verify that the error is actually a connection error before
terminating the connection and firing off a PoolConnectionException
"""
try:
| python | {
"resource": ""
} |
q271478 | simple_expression | test | def simple_expression(joiner=', ', **fields):
""" Build a simple expression ready to be added onto another query.
>>> simple_expression(joiner=' AND ', name='bob', role='admin')
"`name`=%(_QB_name)s AND `name`=%(_QB_role)s", { '_QB_name': | python | {
"resource": ""
} |
q271479 | update | test | def update(table_name, **fields):
""" Build a update query.
>>> update('foo_table', a=5, b=2)
"UPDATE `foo_table` SET `a`=%(_QB_a)s, `b`=%(_QB_b)s", { '_QB_a': 5, '_QB_b': 2 }
"""
prefix | python | {
"resource": ""
} |
q271480 | SQLUtility.connect | test | def connect(self, host='127.0.0.1', port=3306, user='root', password='', database=None):
""" Connect to the database specified """
if database is None:
| python | {
"resource": ""
} |
q271481 | SQLUtility.setup | test | def setup(self):
""" Initialize the required tables in the database """
with self._db_conn() as conn:
for table_defn in | python | {
"resource": ""
} |
q271482 | SQLUtility.destroy | test | def destroy(self):
""" Destroy the SQLStepQueue tables in the database """
with self._db_conn() as conn: | python | {
"resource": ""
} |
q271483 | TaskHandler.start_step | test | def start_step(self, step_name):
""" Start a step. """
if self.finished is not None:
raise AlreadyFinished()
step_data = self._get_step(step_name)
if step_data is not None:
if 'stop' in step_data:
raise StepAlreadyFinished()
else:
raise StepAlreadyStarted()
| python | {
"resource": ""
} |
q271484 | TaskHandler.stop_step | test | def stop_step(self, step_name):
""" Stop a step. """
if self.finished is not None:
raise AlreadyFinished()
steps = copy.deepcopy(self.steps)
step_data = self._get_step(step_name, steps=steps)
if step_data is None:
raise StepNotStarted()
elif | python | {
"resource": ""
} |
q271485 | TaskHandler._load_steps | test | def _load_steps(self, raw_steps):
""" load steps -> basically load all the datetime isoformats into datetimes """
for step in raw_steps:
if 'start' in step:
step['start'] = parser.parse(step['start'])
| python | {
"resource": ""
} |
q271486 | WebSocketConnection.disconnect | test | def disconnect(self):
"""Disconnects from the websocket connection and joins the Thread.
:return:
"""
self.log.debug("disconnect(): Disconnecting from API..")
self.reconnect_required.clear()
| python | {
"resource": ""
} |
q271487 | WebSocketConnection.reconnect | test | def reconnect(self):
"""Issues a reconnection by setting the reconnect_required event.
:return:
"""
# Reconnect attempt at self.reconnect_interval
self.log.debug("reconnect(): Initialzion reconnect sequence..")
| python | {
"resource": ""
} |
q271488 | WebSocketConnection._connect | test | def _connect(self):
"""Creates a websocket connection.
:return:
"""
self.log.debug("_connect(): Initializing Connection..")
self.socket = websocket.WebSocketApp(
self.url,
on_open=self._on_open,
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close
)
if 'ca_certs' not in self.sslopt.keys():
ssl_defaults = ssl.get_default_verify_paths()
self.sslopt['ca_certs'] = ssl_defaults.cafile
self.log.debug("_connect(): Starting Connection..")
self.socket.run_forever(sslopt=self.sslopt,
http_proxy_host=self.http_proxy_host,
http_proxy_port=self.http_proxy_port,
http_proxy_auth=self.http_proxy_auth,
http_no_proxy=self.http_no_proxy)
# stop outstanding ping/pong timers
self._stop_timers()
while self.reconnect_required.is_set():
if not self.disconnect_called.is_set():
self.log.info("Attempting to connect again in %s seconds."
| python | {
"resource": ""
} |
q271489 | WebSocketConnection._on_message | test | def _on_message(self, ws, message):
"""Handles and passes received data to the appropriate handlers.
:return:
"""
self._stop_timers()
raw, received_at = message, time.time()
self.log.debug("_on_message(): Received new message %s at %s",
raw, received_at)
try:
data = json.loads(raw)
except json.JSONDecodeError:
# Something wrong with this data, log and discard
return
# Handle data
if isinstance(data, dict):
| python | {
"resource": ""
} |
q271490 | WebSocketConnection._stop_timers | test | def _stop_timers(self):
"""Stops ping, pong and connection timers.
:return:
"""
if self.ping_timer:
self.ping_timer.cancel()
| python | {
"resource": ""
} |
q271491 | WebSocketConnection.send_ping | test | def send_ping(self):
"""Sends a ping message to the API and starts pong timers.
:return:
"""
self.log.debug("send_ping(): Sending ping to API..")
| python | {
"resource": ""
} |
q271492 | WebSocketConnection._check_pong | test | def _check_pong(self):
"""Checks if a Pong message was received.
:return:
"""
self.pong_timer.cancel()
if self.pong_received:
self.log.debug("_check_pong(): Pong received in time.")
self.pong_received = False
else:
| python | {
"resource": ""
} |
q271493 | WebSocketConnection.send | test | def send(self, api_key=None, secret=None, list_data=None, auth=False, **kwargs):
"""Sends the given Payload to the API via the websocket connection.
:param kwargs: payload paarameters as key=value pairs
:return:
"""
if auth:
nonce = str(int(time.time() * 10000000))
auth_string = 'AUTH' + nonce
auth_sig = hmac.new(secret.encode(), auth_string.encode(),
hashlib.sha384).hexdigest()
payload = {'event': 'auth', 'apiKey': api_key, 'authSig': auth_sig,
'authPayload': | python | {
"resource": ""
} |
q271494 | WebSocketConnection._unpause | test | def _unpause(self):
"""Unpauses the connection.
Send a message up to client that he should re-subscribe to all
channels.
:return:
"""
self.log.debug("_unpause(): Clearing paused() Flag!")
| python | {
"resource": ""
} |
q271495 | WebSocketConnection._system_handler | test | def _system_handler(self, data, ts):
"""Distributes system messages to the appropriate handler.
System messages include everything that arrives as a dict,
or a list containing a heartbeat.
:param data:
:param ts:
:return:
"""
self.log.debug("_system_handler(): Received a system message: %s", data)
# Unpack the data
event = data.pop('event')
if event == 'pong':
self.log.debug("_system_handler(): Distributing %s to _pong_handler..",
data)
self._pong_handler()
elif event == 'info':
self.log.debug("_system_handler(): Distributing %s to _info_handler..",
data)
self._info_handler(data)
elif event == 'error':
self.log.debug("_system_handler(): Distributing %s to _error_handler..",
| python | {
"resource": ""
} |
q271496 | WebSocketConnection._info_handler | test | def _info_handler(self, data):
"""
Handle INFO messages from the API and issues relevant actions.
:param data:
:param ts:
"""
def raise_exception():
"""Log info code as error and raise a ValueError."""
self.log.error("%s: %s", data['code'], info_message[data['code']])
raise ValueError("%s: %s" % (data['code'], info_message[data['code']]))
if 'code' not in data and 'version' in data:
self.log.info('Initialized Client on API Version %s', data['version'])
return
info_message = {20000: 'Invalid User given! Please make sure the given ID is correct!',
20051: 'Stop/Restart websocket server '
'(please try to reconnect)',
20060: 'Refreshing data from the trading engine; '
'please pause any acivity.',
| python | {
"resource": ""
} |
q271497 | WebSocketConnection._error_handler | test | def _error_handler(self, data):
"""
Handle Error messages and log them accordingly.
:param data:
:param ts:
"""
errors = {10000: 'Unknown event',
10001: 'Generic error',
10008: 'Concurrency error',
10020: 'Request parameters error',
10050: 'Configuration setup failed',
10100: 'Failed authentication',
10111: 'Error in authentication request payload',
10112: 'Error in authentication request signature',
10113: 'Error in authentication request encryption',
10114: 'Error in authentication request nonce',
10200: 'Error in un-authentication request',
10300: 'Subscription Failed (generic)',
10301: 'Already Subscribed',
10302: 'Unknown channel',
10400: 'Subscription Failed (generic)',
| python | {
"resource": ""
} |
q271498 | WebSocketConnection._data_handler | test | def _data_handler(self, data, ts):
"""Handles data messages by passing them up to the client.
:param data:
:param ts:
:return:
"""
# Pass the data up to the Client
| python | {
"resource": ""
} |
q271499 | WebSocketConnection._resubscribe | test | def _resubscribe(self, soft=False):
"""Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None
"""
# Restore non-default Bitfinex websocket configuration
if self.bitfinex_config:
self.send(**self.bitfinex_config)
q_list = []
while True:
try:
identifier, q = self.channel_configs.popitem(last=True if soft else False)
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.