_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q255400 | BluezProvider.disconnect_devices | validation | def disconnect_devices(self, service_uuids=[]):
"""Disconnect any connected devices that have the specified list of
service UUIDs. The default is an empty list which means all devices
are disconnected.
"""
service_uuids = set(service_uuids)
for device in self.list_device... | python | {
"resource": ""
} |
q255401 | BluezProvider._get_objects | validation | def _get_objects(self, interface, parent_path='/org/bluez'):
"""Return a list of all bluez DBus objects that implement the requested
interface name and are under the specified path. The default is to
search devices under the root of all bluez objects.
"""
# Iterate through all t... | python | {
"resource": ""
} |
q255402 | BluezProvider._get_objects_by_path | validation | def _get_objects_by_path(self, paths):
"""Return a list of all bluez DBus objects from the provided list of paths.
"""
return map(lambda x: self._bus.get_object('org.bluez', x), paths) | python | {
"resource": ""
} |
q255403 | BluezProvider._print_tree | validation | def _print_tree(self):
"""Print tree of all bluez objects, useful for debugging."""
# This is based on the bluez sample code get-managed-objects.py.
objects = self._bluez.GetManagedObjects()
for path in objects.keys():
print("[ %s ]" % (path))
interfaces = objects... | python | {
"resource": ""
} |
q255404 | Provider.find_device | validation | def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):
"""Return the first device that advertises the specified service UUIDs or
has the specified name. Will wait up to timeout_sec seconds for the device
to be found, and if the timeout is zero then it will not wait at all a... | python | {
"resource": ""
} |
q255405 | CoreBluetoothMetadata.get_all | validation | def get_all(self, cbobjects):
"""Retrieve a list of metadata objects associated with the specified
list of CoreBluetooth objects. If an object cannot be found then an
exception is thrown.
"""
try:
with self._lock:
return [self._metadata[x] for x in cb... | python | {
"resource": ""
} |
q255406 | CoreBluetoothMetadata.add | validation | def add(self, cbobject, metadata):
"""Add the specified CoreBluetooth item with the associated metadata if
it doesn't already exist. Returns the newly created or preexisting
metadata item.
"""
with self._lock:
if cbobject not in self._metadata:
self._... | python | {
"resource": ""
} |
q255407 | CoreBluetoothMetadata.remove | validation | def remove(self, cbobject):
"""Remove any metadata associated with the provided CoreBluetooth object.
"""
with self._lock:
if cbobject in self._metadata:
del self._metadata[cbobject] | python | {
"resource": ""
} |
q255408 | cbuuid_to_uuid | validation | def cbuuid_to_uuid(cbuuid):
"""Convert Objective-C CBUUID type to native Python UUID type."""
data = cbuuid.data().bytes()
template = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(data) <= 4 else '{:0>32}'
value = template.format(hexlify(data.tobytes()[:16]).decode('ascii'))
return uuid.UUID(hex=valu... | python | {
"resource": ""
} |
q255409 | Colorific.set_color | validation | def set_color(self, r, g, b):
"""Set the red, green, blue color of the bulb."""
# See more details on the bulb's protocol from this guide:
# https://learn.adafruit.com/reverse-engineering-a-bluetooth-low-energy-light-bulb/overview
command = '\x58\x01\x03\x01\xFF\x00{0}{1}{2}'.format(ch... | python | {
"resource": ""
} |
q255410 | get_provider | validation | def get_provider():
"""Return an instance of the BLE provider for the current platform."""
global _provider
# Set the provider based on the current platform.
if _provider is None:
if sys.platform.startswith('linux'):
# Linux platform
from .bluez_dbus.provider import Bluez... | python | {
"resource": ""
} |
q255411 | toBigInt | validation | def toBigInt(byteArray):
"""Convert the byte array to a BigInteger"""
array = byteArray[::-1] # reverse array
out = 0
for key, value in enumerate(array):
decoded = struct.unpack("B", bytes([value]))[0]
out = out | decoded << key * 8
return out | python | {
"resource": ""
} |
q255412 | GooglePlayAPI.encryptPassword | validation | def encryptPassword(self, login, passwd):
"""Encrypt credentials using the google publickey, with the
RSA algorithm"""
# structure of the binary key:
#
# *-------------------------------------------------------*
# | modulus_length | modulus | exponent_length | exponent |... | python | {
"resource": ""
} |
q255413 | GooglePlayAPI.getHeaders | validation | def getHeaders(self, upload_fields=False):
"""Return the default set of request headers, which
can later be expanded, based on the request type"""
if upload_fields:
headers = self.deviceBuilder.getDeviceUploadHeaders()
else:
headers = self.deviceBuilder.getBaseHe... | python | {
"resource": ""
} |
q255414 | GooglePlayAPI.search | validation | def search(self, query):
""" Search the play store for an app.
nb_result (int): is the maximum number of result to be returned
offset (int): is used to take result starting from an index.
"""
if self.authSubToken is None:
raise LoginError("You need to login before e... | python | {
"resource": ""
} |
q255415 | GooglePlayAPI.details | validation | def details(self, packageName):
"""Get app details from a package name.
packageName is the app unique ID (usually starting with 'com.')."""
path = DETAILS_URL + "?doc={}".format(requests.utils.quote(packageName))
data = self.executeRequestApi2(path)
return utils.parseProtobufObj... | python | {
"resource": ""
} |
q255416 | GooglePlayAPI.bulkDetails | validation | def bulkDetails(self, packageNames):
"""Get several apps details from a list of package names.
This is much more efficient than calling N times details() since it
requires only one request. If an item is not found it returns an empty object
instead of throwing a RequestError('Item not f... | python | {
"resource": ""
} |
q255417 | GooglePlayAPI.list | validation | def list(self, cat, ctr=None, nb_results=None, offset=None):
"""List all possible subcategories for a specific category. If
also a subcategory is provided, list apps from this category.
Args:
cat (str): category id
ctr (str): subcategory id
nb_results (int): ... | python | {
"resource": ""
} |
q255418 | GooglePlayAPI.reviews | validation | def reviews(self, packageName, filterByDevice=False, sort=2,
nb_results=None, offset=None):
"""Browse reviews for an application
Args:
packageName (str): app unique ID.
filterByDevice (bool): filter results for current device
sort (int): sorting crite... | python | {
"resource": ""
} |
q255419 | GooglePlayAPI.delivery | validation | def delivery(self, packageName, versionCode=None, offerType=1,
downloadToken=None, expansion_files=False):
"""Download an already purchased app.
Args:
packageName (str): app unique ID (usually starting with 'com.')
versionCode (int): version to download
... | python | {
"resource": ""
} |
q255420 | http_connection | validation | def http_connection(timeout):
"""
Decorator function that injects a requests.Session instance into
the decorated function's actual parameters if not given.
"""
def wrapper(f):
def wrapped(*args, **kwargs):
if not ('connection' in kwargs) or not kwargs['connection']:
... | python | {
"resource": ""
} |
q255421 | FirebaseTokenGenerator.create_token | validation | def create_token(self, data, options=None):
"""
Generates a secure authentication token.
Our token format follows the JSON Web Token (JWT) standard:
header.claims.signature
Where:
1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm ... | python | {
"resource": ""
} |
q255422 | FirebaseAuthentication.get_user | validation | def get_user(self):
"""
Method that gets the authenticated user. The returning user has
the token, email and the provider data.
"""
token = self.authenticator.create_token(self.extra)
user_id = self.extra.get('id')
return FirebaseUser(self.email, token, self.provi... | python | {
"resource": ""
} |
q255423 | FirebaseApplication._build_endpoint_url | validation | def _build_endpoint_url(self, url, name=None):
"""
Method that constructs a full url with the given url and the
snapshot name.
Example:
full_url = _build_endpoint_url('/users', '1')
full_url => 'http://firebase.localhost/users/1.json'
"""
if not url.endsw... | python | {
"resource": ""
} |
q255424 | FirebaseApplication._authenticate | validation | def _authenticate(self, params, headers):
"""
Method that simply adjusts authentication credentials for the
request.
`params` is the querystring of the request.
`headers` is the header of the request.
If auth instance is not provided to this class, this method simply
... | python | {
"resource": ""
} |
q255425 | FirebaseApplication.get | validation | def get(self, url, name, params=None, headers=None, connection=None):
"""
Synchronous GET request.
"""
if name is None: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
self._authenticate(params, header... | python | {
"resource": ""
} |
q255426 | FirebaseApplication.get_async | validation | def get_async(self, url, name, callback=None, params=None, headers=None):
"""
Asynchronous GET request with the process pool.
"""
if name is None: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
self._... | python | {
"resource": ""
} |
q255427 | FirebaseApplication.put | validation | def put(self, url, name, data, params=None, headers=None, connection=None):
"""
Synchronous PUT request. There will be no returning output from
the server, because the request will be made with ``silent``
parameter. ``data`` must be a JSONable value.
"""
assert name, 'Sna... | python | {
"resource": ""
} |
q255428 | FirebaseApplication.put_async | validation | def put_async(self, url, name, data, callback=None, params=None, headers=None):
"""
Asynchronous PUT request with the process pool.
"""
if name is None: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
... | python | {
"resource": ""
} |
q255429 | FirebaseApplication.post_async | validation | def post_async(self, url, data, callback=None, params=None, headers=None):
"""
Asynchronous POST request with the process pool.
"""
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, None)
self._authenticate(params, headers)
... | python | {
"resource": ""
} |
q255430 | FirebaseApplication.delete | validation | def delete(self, url, name, params=None, headers=None, connection=None):
"""
Synchronous DELETE request. ``data`` must be a JSONable value.
"""
if not name: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
... | python | {
"resource": ""
} |
q255431 | FirebaseApplication.delete_async | validation | def delete_async(self, url, name, callback=None, params=None, headers=None):
"""
Asynchronous DELETE request with the process pool.
"""
if not name: name = ''
params = params or {}
headers = headers or {}
endpoint = self._build_endpoint_url(url, name)
self... | python | {
"resource": ""
} |
q255432 | do_filter | validation | def do_filter(qs, keywords, exclude=False):
"""
Filter queryset based on keywords.
Support for multiple-selected parent values.
"""
and_q = Q()
for keyword, value in iteritems(keywords):
try:
values = value.split(",")
if len(values) > 0:
or_q = Q()... | python | {
"resource": ""
} |
q255433 | filterchain_all | validation | def filterchain_all(request, app, model, field, foreign_key_app_name,
foreign_key_model_name, foreign_key_field_name, value):
"""Returns filtered results followed by excluded results below."""
model_class = get_model(app, model)
keywords = get_keywords(field, value)
# SECURITY: Make... | python | {
"resource": ""
} |
q255434 | ChainedSelect._get_available_choices | validation | def _get_available_choices(self, queryset, value):
"""
get possible choices for selection
"""
item = queryset.filter(pk=value).first()
if item:
try:
pk = getattr(item, self.chained_model_field + "_id")
filter = {self.chained_model_field... | python | {
"resource": ""
} |
q255435 | AlgoliaIndex.get_raw_record | validation | def get_raw_record(self, instance, update_fields=None):
"""
Gets the raw record.
If `update_fields` is set, the raw record will be build with only
the objectID and the given fields. Also, `_geoloc` and `_tags` will
not be included.
"""
tmp = {'objectID': self.obj... | python | {
"resource": ""
} |
q255436 | AlgoliaIndex._should_really_index | validation | def _should_really_index(self, instance):
"""Return True if according to should_index the object should be indexed."""
if self._should_index_is_method:
is_method = inspect.ismethod(self.should_index)
try:
count_args = len(inspect.signature(self.should_index).param... | python | {
"resource": ""
} |
q255437 | AlgoliaIndex.get_settings | validation | def get_settings(self):
"""Returns the settings of the index."""
try:
logger.info('GET SETTINGS ON %s', self.index_name)
return self.__index.get_settings()
except AlgoliaException as e:
if DEBUG:
raise e
else:
logger... | python | {
"resource": ""
} |
q255438 | AlgoliaIndex.set_settings | validation | def set_settings(self):
"""Applies the settings to the index."""
if not self.settings:
return
try:
self.__index.set_settings(self.settings)
logger.info('APPLY SETTINGS ON %s', self.index_name)
except AlgoliaException as e:
if DEBUG:
... | python | {
"resource": ""
} |
q255439 | AlgoliaEngine.register | validation | def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None):
"""
Registers the given model with Algolia engine.
If the given model is already registered with Algolia engine, a
RegistrationError will be raised.
"""
# Check for existing registration.
if s... | python | {
"resource": ""
} |
q255440 | AlgoliaEngine.unregister | validation | def unregister(self, model):
"""
Unregisters the given model with Algolia engine.
If the given model is not registered with Algolia engine, a
RegistrationError will be raised.
"""
if not self.is_registered(model):
raise RegistrationError(
'{} ... | python | {
"resource": ""
} |
q255441 | AlgoliaEngine.get_adapter | validation | def get_adapter(self, model):
"""Returns the adapter associated with the given model."""
if not self.is_registered(model):
raise RegistrationError(
'{} is not registered with Algolia engine'.format(model))
return self.__registered_models[model] | python | {
"resource": ""
} |
q255442 | AlgoliaEngine.__post_save_receiver | validation | def __post_save_receiver(self, instance, **kwargs):
"""Signal handler for when a registered model has been saved."""
logger.debug('RECEIVE post_save FOR %s', instance.__class__)
self.save_record(instance, **kwargs) | python | {
"resource": ""
} |
q255443 | AlgoliaEngine.__pre_delete_receiver | validation | def __pre_delete_receiver(self, instance, **kwargs):
"""Signal handler for when a registered model has been deleted."""
logger.debug('RECEIVE pre_delete FOR %s', instance.__class__)
self.delete_record(instance) | python | {
"resource": ""
} |
q255444 | decode | validation | def decode(geohash):
"""
Decode geohash, returning two strings with latitude and longitude
containing only relevant digits and with trailing zeroes removed.
"""
lat, lon, lat_err, lon_err = decode_exactly(geohash)
# Format to the number of decimals that are known
lats = "%.*f" % (max(1, int(... | python | {
"resource": ""
} |
q255445 | encode | validation | def encode(latitude, longitude, precision=12):
"""
Encode a position given in float arguments latitude, longitude to
a geohash which will have the character count precision.
"""
lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0)
geohash = []
bits = [ 16, 8, 4, 2, 1 ]
bit = 0
... | python | {
"resource": ""
} |
q255446 | pad_to | validation | def pad_to(unpadded, target_len):
"""
Pad a string to the target length in characters, or return the original
string if it's longer than the target length.
"""
under = target_len - len(unpadded)
if under <= 0:
return unpadded
return unpadded + (' ' * under) | python | {
"resource": ""
} |
q255447 | normalize_cols | validation | def normalize_cols(table):
"""
Pad short rows to the length of the longest row to help render "jagged"
CSV files
"""
longest_row_len = max([len(row) for row in table])
for row in table:
while len(row) < longest_row_len:
row.append('')
return table | python | {
"resource": ""
} |
q255448 | pad_cells | validation | def pad_cells(table):
"""Pad each cell to the size of the largest cell in its column."""
col_sizes = [max(map(len, col)) for col in zip(*table)]
for row in table:
for cell_num, cell in enumerate(row):
row[cell_num] = pad_to(cell, col_sizes[cell_num])
return table | python | {
"resource": ""
} |
q255449 | horiz_div | validation | def horiz_div(col_widths, horiz, vert, padding):
"""
Create the column dividers for a table with given column widths.
col_widths: list of column widths
horiz: the character to use for a horizontal divider
vert: the character to use for a vertical divider
padding: amount of padding to add to eac... | python | {
"resource": ""
} |
q255450 | add_dividers | validation | def add_dividers(row, divider, padding):
"""Add dividers and padding to a row of cells and return a string."""
div = ''.join([padding * ' ', divider, padding * ' '])
return div.join(row) | python | {
"resource": ""
} |
q255451 | md_table | validation | def md_table(table, *, padding=DEFAULT_PADDING, divider='|', header_div='-'):
"""
Convert a 2D array of items into a Markdown table.
padding: the number of padding spaces on either side of each divider
divider: the vertical divider to place between columns
header_div: the horizontal divider to plac... | python | {
"resource": ""
} |
q255452 | baseId | validation | def baseId(resource_id, return_version=False):
"""Calculate base id and version from a resource id.
:params resource_id: Resource id.
:params return_version: (optional) True if You need version, returns (resource_id, version).
"""
version = 0
resource_id = resource_id + 0xC4000000 # 3288334336... | python | {
"resource": ""
} |
q255453 | Core.cardInfo | validation | def cardInfo(self, resource_id):
"""Return card info.
:params resource_id: Resource id.
"""
# TODO: add referer to headers (futweb)
base_id = baseId(resource_id)
if base_id in self.players:
return self.players[base_id]
else: # not a player?
... | python | {
"resource": ""
} |
q255454 | Core.search | validation | def search(self, ctype, level=None, category=None, assetId=None, defId=None,
min_price=None, max_price=None, min_buy=None, max_buy=None,
league=None, club=None, position=None, zone=None, nationality=None,
rare=False, playStyle=None, start=0, page_size=itemsPerPage['transferM... | python | {
"resource": ""
} |
q255455 | Core.bid | validation | def bid(self, trade_id, bid, fast=False):
"""Make a bid.
:params trade_id: Trade id.
:params bid: Amount of credits You want to spend.
:params fast: True for fastest bidding (skips trade status & credits check).
"""
method = 'PUT'
url = 'trade/%s/bid' % trade_id
... | python | {
"resource": ""
} |
q255456 | Core.club | validation | def club(self, sort='desc', ctype='player', defId='', start=0, count=None, page_size=itemsPerPage['club'],
level=None, category=None, assetId=None, league=None, club=None,
position=None, zone=None, nationality=None, rare=False, playStyle=None):
"""Return items in your club, excluding c... | python | {
"resource": ""
} |
q255457 | Core.clubStaff | validation | def clubStaff(self):
"""Return staff in your club."""
method = 'GET'
url = 'club/stats/staff'
rc = self.__request__(method, url)
return rc | python | {
"resource": ""
} |
q255458 | Core.clubConsumables | validation | def clubConsumables(self, fast=False):
"""Return all consumables from club."""
method = 'GET'
url = 'club/consumables/development'
rc = self.__request__(method, url)
events = [self.pin.event('page_view', 'Hub - Club')]
self.pin.send(events, fast=fast)
events = [... | python | {
"resource": ""
} |
q255459 | Core.squad | validation | def squad(self, squad_id=0, persona_id=None):
"""Return a squad.
:params squad_id: Squad id.
"""
method = 'GET'
url = 'squad/%s/user/%s' % (squad_id, persona_id or self.persona_id)
# pinEvents
events = [self.pin.event('page_view', 'Hub - Squads')]
self.p... | python | {
"resource": ""
} |
q255460 | Core.tradeStatus | validation | def tradeStatus(self, trade_id):
"""Return trade status.
:params trade_id: Trade id.
"""
method = 'GET'
url = 'trade/status'
if not isinstance(trade_id, (list, tuple)):
trade_id = (trade_id,)
trade_id = (str(i) for i in trade_id)
params = {'t... | python | {
"resource": ""
} |
q255461 | Core.tradepile | validation | def tradepile(self):
"""Return items in tradepile."""
method = 'GET'
url = 'tradepile'
rc = self.__request__(method, url)
# pinEvents
events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer List - List View')]
if rc.get('a... | python | {
"resource": ""
} |
q255462 | Core.sell | validation | def sell(self, item_id, bid, buy_now, duration=3600, fast=False):
"""Start auction. Returns trade_id.
:params item_id: Item id.
:params bid: Stard bid.
:params buy_now: Buy now price.
:params duration: Auction duration in seconds (Default: 3600).
"""
method = 'PO... | python | {
"resource": ""
} |
q255463 | Core.quickSell | validation | def quickSell(self, item_id):
"""Quick sell.
:params item_id: Item id.
"""
method = 'DELETE'
url = 'item'
if not isinstance(item_id, (list, tuple)):
item_id = (item_id,)
item_id = (str(i) for i in item_id)
params = {'itemIds': ','.join(item_i... | python | {
"resource": ""
} |
q255464 | Core.watchlistDelete | validation | def watchlistDelete(self, trade_id):
"""Remove cards from watchlist.
:params trade_id: Trade id.
"""
method = 'DELETE'
url = 'watchlist'
if not isinstance(trade_id, (list, tuple)):
trade_id = (trade_id,)
trade_id = (str(i) for i in trade_id)
... | python | {
"resource": ""
} |
q255465 | Core.tradepileDelete | validation | def tradepileDelete(self, trade_id): # item_id instead of trade_id?
"""Remove card from tradepile.
:params trade_id: Trade id.
"""
method = 'DELETE'
url = 'trade/%s' % trade_id
self.__request__(method, url) # returns nothing
# TODO: validate status code
... | python | {
"resource": ""
} |
q255466 | Core.sendToWatchlist | validation | def sendToWatchlist(self, trade_id):
"""Send to watchlist.
:params trade_id: Trade id.
"""
method = 'PUT'
url = 'watchlist'
data = {'auctionInfo': [{'id': trade_id}]}
return self.__request__(method, url, data=json.dumps(data)) | python | {
"resource": ""
} |
q255467 | Core.sendToSbs | validation | def sendToSbs(self, challenge_id, item_id):
"""Send card FROM CLUB to first free slot in sbs squad."""
# TODO?: multiple item_ids
method = 'PUT'
url = 'sbs/challenge/%s/squad' % challenge_id
squad = self.sbsSquad(challenge_id)
players = []
moved = False
n... | python | {
"resource": ""
} |
q255468 | Core.applyConsumable | validation | def applyConsumable(self, item_id, resource_id):
"""Apply consumable on player.
:params item_id: Item id of player.
:params resource_id: Resource id of consumable.
"""
# TODO: catch exception when consumable is not found etc.
# TODO: multiple players like in quickSell
... | python | {
"resource": ""
} |
q255469 | Core.messages | validation | def messages(self):
"""Return active messages."""
method = 'GET'
url = 'activeMessage'
rc = self.__request__(method, url)
# try:
# return rc['activeMessage']
# except:
# raise UnknownError('Invalid activeMessage response') # is it even possible?
... | python | {
"resource": ""
} |
q255470 | EAHashingAlgorithm.num2hex | validation | def num2hex(self, num):
'''
Convert a decimal number to hexadecimal
'''
temp = ''
for i in range(0, 4):
x = self.hexChars[ ( num >> (i * 8 + 4) ) & 0x0F ]
y = self.hexChars[ ( num >> (i * 8) ) & 0x0F ]
temp += (x + y)
return temp | python | {
"resource": ""
} |
q255471 | logger | validation | def logger(name=None, save=False):
"""Init and configure logger."""
logger = logging.getLogger(name)
if save:
logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)'
log_file_path = 'fut.log' # TODO: define logpath
open(log_file_path, 'w').w... | python | {
"resource": ""
} |
q255472 | _ThreadImpl.run | validation | def run(self):
"""
Runs its worker method.
This method will be terminated once its parent's is_running
property turns False.
"""
while self._base.is_running:
if self._worker:
self._worker()
time.sleep(self._sleep_duration) | python | {
"resource": ""
} |
q255473 | Component2DImage.represent_pixel_location | validation | def represent_pixel_location(self):
"""
Returns a NumPy array that represents the 2D pixel location,
which is defined by PFNC, of the original image data.
You may use the returned NumPy array for a calculation to map the
original image to another format.
:return: A NumP... | python | {
"resource": ""
} |
q255474 | ImageAcquirer.start_image_acquisition | validation | def start_image_acquisition(self):
"""
Starts image acquisition.
:return: None.
"""
if not self._create_ds_at_connection:
self._setup_data_streams()
#
num_required_buffers = self._num_buffers
for data_stream in self._data_streams:
... | python | {
"resource": ""
} |
q255475 | ImageAcquirer.stop_image_acquisition | validation | def stop_image_acquisition(self):
"""
Stops image acquisition.
:return: None.
"""
if self.is_acquiring_images:
#
self._is_acquiring_images = False
#
if self.thread_image_acquisition.is_running: # TODO
self.thread_... | python | {
"resource": ""
} |
q255476 | Harvester.add_cti_file | validation | def add_cti_file(self, file_path: str):
"""
Adds a CTI file to work with to the CTI file list.
:param file_path: Set a file path to the target CTI file.
:return: None.
"""
if not os.path.exists(file_path):
self._logger.warning(
'Attempted to ... | python | {
"resource": ""
} |
q255477 | Harvester.remove_cti_file | validation | def remove_cti_file(self, file_path: str):
"""
Removes the specified CTI file from the CTI file list.
:param file_path: Set a file path to the target CTI file.
:return: None.
"""
if file_path in self._cti_files:
self._cti_files.remove(file_path)
... | python | {
"resource": ""
} |
q255478 | Harvester._destroy_image_acquirer | validation | def _destroy_image_acquirer(self, ia):
"""
Releases all external resources including the controlling device.
"""
id_ = None
if ia.device:
#
ia.stop_image_acquisition()
#
ia._release_data_streams()
#
id_ = ... | python | {
"resource": ""
} |
q255479 | Zabransky_spline.add_coeffs | validation | def add_coeffs(self, Tmin, Tmax, coeffs):
'''Called internally during the parsing of the Zabransky database, to
add coefficients as they are read one per line'''
self.n += 1
if not self.Ts:
self.Ts = [Tmin, Tmax]
self.coeff_sets = [coeffs]
else:
... | python | {
"resource": ""
} |
q255480 | Zabransky_spline._coeff_ind_from_T | validation | def _coeff_ind_from_T(self, T):
'''Determines the index at which the coefficients for the current
temperature are stored in `coeff_sets`.
'''
# DO NOT CHANGE
if self.n == 1:
return 0
for i in range(self.n):
if T <= self.Ts[i+1]:
ret... | python | {
"resource": ""
} |
q255481 | HeatCapacityLiquid.calculate | validation | def calculate(self, T, method):
r'''Method to calculate heat capacity of a liquid at temperature `T`
with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature at which... | python | {
"resource": ""
} |
q255482 | HeatCapacityLiquid.calculate_integral | validation | def calculate_integral(self, T1, T2, method):
r'''Method to calculate the integral of a property with respect to
temperature, using a specified method. Implements the
analytical integrals of all available methods except for tabular data,
the case of multiple coefficient sets needed to ... | python | {
"resource": ""
} |
q255483 | HeatCapacityLiquid.calculate_integral_over_T | validation | def calculate_integral_over_T(self, T1, T2, method):
r'''Method to calculate the integral of a property over temperature
with respect to temperature, using a specified method. Implements the
analytical integrals of all available methods except for tabular data,
the case of multiple co... | python | {
"resource": ""
} |
q255484 | HeatCapacitySolid.calculate | validation | def calculate(self, T, method):
r'''Method to calculate heat capacity of a solid at temperature `T`
with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature at which ... | python | {
"resource": ""
} |
q255485 | HeatCapacityLiquidMixture.calculate | validation | def calculate(self, T, P, zs, ws, method):
r'''Method to calculate heat capacity of a liquid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
... | python | {
"resource": ""
} |
q255486 | HeatCapacitySolidMixture.calculate | validation | def calculate(self, T, P, zs, ws, method):
r'''Method to calculate heat capacity of a solid mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
... | python | {
"resource": ""
} |
q255487 | HeatCapacityGasMixture.calculate | validation | def calculate(self, T, P, zs, ws, method):
r'''Method to calculate heat capacity of a gas mixture at
temperature `T`, pressure `P`, mole fractions `zs` and weight fractions
`ws` with a given method.
This method has no exception handling; see `mixture_property`
for that.
... | python | {
"resource": ""
} |
q255488 | K_value | validation | def K_value(P=None, Psat=None, phi_l=None, phi_g=None, gamma=None, Poynting=1):
r'''Calculates the equilibrium K-value assuming Raoult's law,
or an equation of state model, or an activity coefficient model,
or a combined equation of state-activity model.
The calculation procedure will use the most adva... | python | {
"resource": ""
} |
q255489 | Rachford_Rice_flash_error | validation | def Rachford_Rice_flash_error(V_over_F, zs, Ks):
r'''Calculates the objective function of the Rachford-Rice flash equation.
This function should be called by a solver seeking a solution to a flash
calculation. The unknown variable is `V_over_F`, for which a solution
must be between 0 and 1.
.. math... | python | {
"resource": ""
} |
q255490 | Wilson | validation | def Wilson(xs, params):
r'''Calculates the activity coefficients of each species in a mixture
using the Wilson method, given their mole fractions, and
dimensionless interaction parameters. Those are normally correlated with
temperature, and need to be calculated separately.
.. math::
\ln \g... | python | {
"resource": ""
} |
q255491 | identify_phase | validation | def identify_phase(T, P, Tm=None, Tb=None, Tc=None, Psat=None):
r'''Determines the phase of a one-species chemical system according to
basic rules, using whatever information is available. Considers only the
phases liquid, solid, and gas; does not consider two-phase
scenarios, as should occurs between p... | python | {
"resource": ""
} |
q255492 | bubble_at_P | validation | def bubble_at_P(P, zs, vapor_pressure_eqns, fugacities=None, gammas=None):
'''Calculates bubble point for a given pressure
Parameters
----------
P : float
Pressure, [Pa]
zs : list[float]
Overall mole fractions of all species, [-]
vapor_pressure_eqns : list[functions]
Tem... | python | {
"resource": ""
} |
q255493 | Chemical.draw_2d | validation | def draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover
r'''Interface for drawing a 2D image of the molecule.
Requires an HTML5 browser, and the libraries RDKit and
IPython. An exception is raised if either of these libraries is
absent.
Parameters
--------... | python | {
"resource": ""
} |
q255494 | Chemical.draw_3d | validation | def draw_3d(self, width=300, height=500, style='stick', Hs=True): # pragma: no cover
r'''Interface for drawing an interactive 3D view of the molecule.
Requires an HTML5 browser, and the libraries RDKit, pymol3D, and
IPython. An exception is raised if all three of these libraries are
not ... | python | {
"resource": ""
} |
q255495 | Chemical.charge | validation | def charge(self):
r'''Charge of a chemical, computed with RDKit from a chemical's SMILES.
If RDKit is not available, holds None.
Examples
--------
>>> Chemical('sodium ion').charge
1
'''
try:
if not self.rdkitmol:
return charge... | python | {
"resource": ""
} |
q255496 | Chemical.rdkitmol | validation | def rdkitmol(self):
r'''RDKit object of the chemical, without hydrogen. If RDKit is not
available, holds None.
For examples of what can be done with RDKit, see
`their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.
'''
if self.__rdkitmol:
r... | python | {
"resource": ""
} |
q255497 | Chemical.rdkitmol_Hs | validation | def rdkitmol_Hs(self):
r'''RDKit object of the chemical, with hydrogen. If RDKit is not
available, holds None.
For examples of what can be done with RDKit, see
`their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_.
'''
if self.__rdkitmol_Hs:
... | python | {
"resource": ""
} |
q255498 | Chemical.legal_status | validation | def legal_status(self):
r'''Dictionary of legal status indicators for the chemical.
Examples
--------
>>> pprint(Chemical('benzene').legal_status)
{'DSL': 'LISTED',
'EINECS': 'LISTED',
'NLP': 'UNLISTED',
'SPIN': 'LISTED',
'TSCA': 'LISTED'}
... | python | {
"resource": ""
} |
q255499 | Chemical.economic_status | validation | def economic_status(self):
r'''Dictionary of economic status indicators for the chemical.
Examples
--------
>>> pprint(Chemical('benzene').economic_status)
["US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}",
u'1,000,000 - 10,000,00... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.