_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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 Te... | 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.
... | 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.
... | 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 additio... | 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:
... | 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:
... | 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(base... | 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... | 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, b... | 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.
"""
check_type(... | 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:
... | 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:
TypeError: If the parameter types are inc... | 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 ... | 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.
ApiError: If the Webex Teams ... | 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')
# Return a person object created from the response JSON data... | 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,
... | 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 b... | 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
... | 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
s... | 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.
"""
check_type(teamId, base... | 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 ... | 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 th... | 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 integratio... | 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:
return WebexTeamsDateTime.strptime(last_activity)
else:
return None | 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... | 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()
except request... | 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:
print("Deleting Webhook:", webhook.name, webhook.targetUrl)
api.webhooks.delete(webhook.id) | 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, WEBHOOK_URL_SUFFIX),
resource=WEBHOOK_RESOURC... | 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)
public_url = get_ngrok_public_url()
if public_url is not None:
create_ngrok_webhook(api, public_url) | 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='a... | 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.re... | 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 ... | 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_specification... | 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)
serial_settings['url'] = port
conn = create_serial_connectio... | 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(
dsmr_version, telegram_callback, loop=None)
conn = loop.create_connection(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)
for telegram in self.telegram_buffer.get_all():
self.handle_telegram(telegram) | 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:
self.log.info('disconnected because of close/abort.')
self._closed.set() | 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)
except InvalidChecksumError as e:
self.log.warning(str(e))
e... | 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
:... | 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)
version_ns = {}
with io.open(path, encoding="utf8") as f:
exec(f.read(), {}, version_ns)
return version_... | 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
part = '%s.%s' % (v.major, v.minor)
for spec in specs:
if part == spec:
return
try... | 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, '.'))
elif d != top:
# Do no... | 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: d... | 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):
func()
update_package_data(self.distribution)
return FuncCommand | 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)) and os.name != 'nt':
cmd = shlex.split(cmd)
cmd[0] ... | 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:
... | 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):
... | 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,... | 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
------... | 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.
... | 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')
res_str = _translate_glob(pat_str)
res = res_str.encode('ISO-8859-1')
else:
res = _translate_... | 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:
yield head
if tail or not head:
yield tail
ret... | 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):
translated_parts.append(_translate_glob_part(part))
os_sep_class = '[%s]' % re.escape(SEPARATORS)
res = _join_translated(translated_parts, os_sep_class)
... | 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 ... | 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 == '*':
# Mat... | 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, serial_key_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, serial_key_sql = s... | 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 represents the table to read/write.
Returns None
"""
index_sql = super(P... | 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 represents the table to read/write.
Returns None
"""
index_sql = super... | 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 represents the table to read/write.
Returns None
"""
constraint_... | 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... | 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()))
... | 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.
Returns None
"""
self.f.write('\n'.jo... | 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 :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
Returns None
"""
self.f.write... | 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.
Returns None
"""
self.f.write(... | python | {
"resource": ""
} |
q271465 | SQLStepQueue.qsize | test | def qsize(self, extra_predicate=None):
""" Return an approximate number of queued tasks in the queue. """
count = self._query_queued('COUNT(*) AS count', extra_predicate=extra_predicate)
return count[0].count | 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 (%%(created)s, %%(data)s)' % self.table_name,
created=datetim... | 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> ... | 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 is... | 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 strings.
"""
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
raise TypeError('Object of type %s with value of %s is not JSON ... | python | {
"resource": ""
} |
q271470 | Connection.reconnect | test | def reconnect(self):
"""Closes the existing database connection and re-opens it."""
conn = _mysql.connect(**self._db_args)
if conn is not None:
self.close()
self._db = conn | 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):
raise MySQLError("Query is not a select query... | python | {
"resource": ""
} |
q271472 | get_connection | test | def get_connection(db=DATABASE):
""" Returns a new connection to the database. """
return database.connect(host=HOST, port=PORT, user=USER, password=PASSWORD, database=db) | 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)
... | 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... | python | {
"resource": ""
} |
q271475 | lookup_by_number | test | def lookup_by_number(errno):
""" Used for development only """
for key, val in globals().items():
if errno == val:
print(key) | python | {
"resource": ""
} |
q271476 | ConnectionPool.size | test | def size(self):
""" Returns the number of connections cached by the pool. """
return sum(q.qsize() for q in self._connections.values()) + len(self._fairies) | 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 PoolConnectionEx... | 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': 'bob', '_QB_role': 'admin' }
"""
expression, params = [], {}... | 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 = "UPDATE `%s` SET " % table_name
sets, params = simple_expression(', ', **fields)
return prefix + sets,... | 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:
raise exceptions.RequiresDatabase()
self._db_args = { 'host': host, 'port': port, 'user': user, 'password': password, 'database': ... | 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 self._tables.values():
conn.execute(table_defn)
return self | python | {
"resource": ""
} |
q271482 | SQLUtility.destroy | test | def destroy(self):
""" Destroy the SQLStepQueue tables in the database """
with self._db_conn() as conn:
for table_name in self._tables:
conn.execute('DROP TABLE IF EXISTS %s' % table_name)
return self | 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:
... | 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 'sto... | 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'])
if 'stop' in step:
step['stop'] = parser.parse(... | 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()
self.disconnect_called.set()
if self.socket:
self.socket.clo... | 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..")
self.connected.clear()
self.reconnect_required.set()... | 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_erro... | 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, recei... | 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()
if self.connection_timer:
self.connection_timer.cancel()
if self.pong_timer:
self.pong_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..")
self.socket.send(json.dumps({'event': 'ping'}))
self.pong_timer = Timer(self.pong_timeout, self._check_pong)
self.pon... | 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:
# reconnect
... | 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))
... | 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!")
self.paused.clear()
self.log.debug("_unpause(): Re-subscribing sof... | 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_hand... | 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_... | 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 par... | 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
self.log.debug("_data_handler(): Passing %s to client..",
data)
self.pass... | 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.bit... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.