_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263300 | _upload_as_item | validation | def _upload_as_item(local_file, parent_folder_id, file_path,
reuse_existing=False):
"""
Function for doing an upload of a file as an item. This should be a
building block for user-level functions.
:param local_file: name of local file to upload
:type local_file: string
:param parent_folder_id: id of parent folder on the Midas Server instance,
where the item will be added
:type parent_folder_id: int | long
:param file_path: full path to the file
:type file_path: string
:param reuse_existing: (optional) whether to accept an existing item of the
same name in the same location, or create a new one instead
:type reuse_existing: bool
| python | {
"resource": ""
} |
q263301 | _create_folder | validation | def _create_folder(local_folder, parent_folder_id):
"""
Function for creating a remote folder and returning the id. This should be
a building block for user-level functions.
:param local_folder: full path to a local folder
:type local_folder: string
:param parent_folder_id: id of parent folder on the Midas Server instance,
where the new folder will be added
:type parent_folder_id: int | python | {
"resource": ""
} |
q263302 | _upload_folder_recursive | validation | def _upload_folder_recursive(local_folder,
parent_folder_id,
leaf_folders_as_items=False,
reuse_existing=False):
"""
Function to recursively upload a folder and all of its descendants.
:param local_folder: full path to local folder to be uploaded
:type local_folder: string
:param parent_folder_id: id of parent folder on the Midas Server instance,
where the new folder will be added
:type parent_folder_id: int | long
:param leaf_folders_as_items: (optional) whether leaf folders should have
all files uploaded as single items
:type leaf_folders_as_items: bool
:param reuse_existing: (optional) whether to accept an existing item of the
same name in the same location, or create a new one instead
:type reuse_existing: bool
"""
if leaf_folders_as_items and _has_only_files(local_folder):
print('Creating item from {0}'.format(local_folder))
_upload_folder_as_item(local_folder, parent_folder_id, reuse_existing)
return
else:
# do not need to check if folder exists, if it does, an attempt to
# create it will just return the existing id
print('Creating folder from {0}'.format(local_folder))
new_folder_id = _create_or_reuse_folder(local_folder, parent_folder_id,
| python | {
"resource": ""
} |
q263303 | _has_only_files | validation | def _has_only_files(local_folder):
"""
Return whether a folder contains only files. This will be False if the
folder contains any subdirectories.
:param local_folder: full path to the local folder
:type local_folder: string
:returns: | python | {
"resource": ""
} |
q263304 | _upload_folder_as_item | validation | def _upload_folder_as_item(local_folder, parent_folder_id,
reuse_existing=False):
"""
Upload a folder as a new item. Take a folder and use its base name as the
name of a new item. Then, upload its containing files into the new item as
bitstreams.
:param local_folder: The path to the folder to be uploaded
:type local_folder: string
:param parent_folder_id: The id of the destination folder for the new item.
:type parent_folder_id: int | long
:param reuse_existing: (optional) whether to accept an existing item of the
same name in the same location, or create a new one instead
:type reuse_existing: bool
"""
item_id = _create_or_reuse_item(local_folder, parent_folder_id,
| python | {
"resource": ""
} |
q263305 | upload | validation | def upload(file_pattern, destination='Private', leaf_folders_as_items=False,
reuse_existing=False):
"""
Upload a pattern of files. This will recursively walk down every tree in
the file pattern to create a hierarchy on the server. As of right now, this
places the file into the currently logged in user's home directory.
:param file_pattern: a glob type pattern for files
:type file_pattern: string
:param destination: (optional) name of the midas destination folder,
defaults to Private
:type destination: string
:param leaf_folders_as_items: (optional) whether leaf folders should have
all files uploaded as single items
:type leaf_folders_as_items: bool
:param reuse_existing: (optional) whether to accept an existing item of the
same name in the same location, or create a new one instead
:type reuse_existing: bool
"""
session.token = verify_credentials()
# Logic for finding the proper folder to place the files in.
parent_folder_id = None
user_folders = session.communicator.list_user_folders(session.token)
if destination.startswith('/'):
parent_folder_id = _find_resource_id_from_path(destination)
else:
for cur_folder in user_folders:
if cur_folder['name'] == destination:
parent_folder_id = cur_folder['folder_id']
if parent_folder_id is None:
print('Unable to locate specified destination. Defaulting to {0}.'
| python | {
"resource": ""
} |
q263306 | _descend_folder_for_id | validation | def _descend_folder_for_id(parsed_path, folder_id):
"""
Descend a path to return a folder id starting from the given folder id.
:param parsed_path: a list of folders from top to bottom of a hierarchy
:type parsed_path: list[string]
:param folder_id: The id of the folder from which to start the descent
:type folder_id: int | long
:returns: The id of the found folder or -1
:rtype: int | long
"""
if len(parsed_path) == 0:
return folder_id
session.token = verify_credentials()
base_folder = session.communicator.folder_get(session.token,
folder_id)
cur_folder_id = -1
| python | {
"resource": ""
} |
q263307 | _search_folder_for_item_or_folder | validation | def _search_folder_for_item_or_folder(name, folder_id):
"""
Find an item or folder matching the name. A folder will be found first if
both are present.
:param name: The name of the resource
:type name: string
:param folder_id: The folder to search within
:type folder_id: int | long
:returns: A tuple indicating whether the resource is an item an the id of
| python | {
"resource": ""
} |
q263308 | _find_resource_id_from_path | validation | def _find_resource_id_from_path(path):
"""
Get a folder id from a path on the server.
Warning: This is NOT efficient at all.
The schema for this path is:
path := "/users/<name>/" | "/communities/<name>" , {<subfolder>/}
name := <firstname> , "_" , <lastname>
:param path: The virtual path on the server.
:type path: string
:returns: a tuple indicating True or False about whether the resource is an
item and id of the resource i.e. (True, item_id) or (False, folder_id)
:rtype: (bool, int | long)
"""
session.token = verify_credentials()
parsed_path = path.split('/')
if parsed_path[-1] == '':
parsed_path.pop()
if path.startswith('/users/'):
parsed_path.pop(0) # remove '' before /
parsed_path.pop(0) # remove 'users'
name = parsed_path.pop(0) # remove '<firstname>_<lastname>'
firstname, lastname = name.split('_')
end = parsed_path.pop()
| python | {
"resource": ""
} |
q263309 | _download_folder_recursive | validation | def _download_folder_recursive(folder_id, path='.'):
"""
Download a folder to the specified path along with any children.
:param folder_id: The id of the target folder
:type folder_id: int | long
:param path: (optional) the location to download the folder
:type path: string
"""
session.token = verify_credentials()
cur_folder = session.communicator.folder_get(session.token, folder_id)
# Replace any '/' in the folder name.
folder_path = os.path.join(path, cur_folder['name'].replace('/', '_'))
print('Creating folder at {0}'.format(folder_path))
try:
os.mkdir(folder_path)
except OSError as e:
if e.errno == errno.EEXIST and session.allow_existing_download_paths:
pass
else:
| python | {
"resource": ""
} |
q263310 | _download_item | validation | def _download_item(item_id, path='.', item=None):
"""
Download the requested item to the specified path.
:param item_id: The id of the item to be downloaded
:type item_id: int | long
:param path: (optional) the location to download the item
:type path: string
:param item: The dict of item info
:type item: dict | None
"""
session.token = verify_credentials()
filename, content_iter = session.communicator.download_item(
item_id, session.token)
item_path = os.path.join(path, filename)
print('Creating file at | python | {
"resource": ""
} |
q263311 | download | validation | def download(server_path, local_path='.'):
"""
Recursively download a file or item from the Midas Server instance.
:param server_path: The location on the server to find the resource to
download
:type server_path: string
:param local_path: The location on the client to store the downloaded data
:type local_path: string
"""
session.token = verify_credentials()
is_item, resource_id = _find_resource_id_from_path(server_path)
| python | {
"resource": ""
} |
q263312 | BaseDriver.login_with_api_key | validation | def login_with_api_key(self, email, api_key, application='Default'):
"""
Login and get a token. If you do not specify a specific application,
'Default' will be used.
:param email: Email address of the user
:type email: string
:param api_key: API key assigned to the user
:type api_key: string
:param application: (optional) Application designated for this API key
:type application: string
:returns: Token to be used for interaction with the API until
expiration
:rtype: string
"""
parameters = dict() | python | {
"resource": ""
} |
q263313 | CoreDriver.list_user_folders | validation | def list_user_folders(self, token):
"""
List the folders in the users home area.
:param token: A valid token for the user in question.
:type token: string
:returns: List of dictionaries containing folder information.
:rtype: list[dict]
"""
| python | {
"resource": ""
} |
q263314 | CoreDriver.get_default_api_key | validation | def get_default_api_key(self, email, password):
"""
Get the default API key for a user.
:param email: The email of the user.
:type email: string
:param password: The user's password.
:type password: string
:returns: API key to confirm that it was fetched successfully.
:rtype: string
| python | {
"resource": ""
} |
q263315 | CoreDriver.list_users | validation | def list_users(self, limit=20):
"""
List the public users in the system.
:param limit: (optional) The number of users to fetch.
:type limit: int | long
:returns: The list of users.
:rtype: list[dict]
""" | python | {
"resource": ""
} |
q263316 | CoreDriver.get_user_by_email | validation | def get_user_by_email(self, email):
"""
Get a user by the email of that user.
:param email: The email of the desired user.
:type email: string
:returns: The user requested.
:rtype: dict
"""
| python | {
"resource": ""
} |
q263317 | CoreDriver.create_community | validation | def create_community(self, token, name, **kwargs):
"""
Create a new community or update an existing one using the uuid.
:param token: A valid token for the user in question.
:type token: string
:param name: The community name.
:type name: string
:param description: (optional) The community description.
:type description: string
:param uuid: (optional) uuid of the community. If none is passed, will
generate one.
:type uuid: string
:param privacy: (optional) Default 'Public', possible values
| python | {
"resource": ""
} |
q263318 | CoreDriver.get_community_by_name | validation | def get_community_by_name(self, name, token=None):
"""
Get a community based on its name.
:param name: The name of the target community.
:type name: string
:param token: (optional) A valid token for the user in | python | {
"resource": ""
} |
q263319 | CoreDriver.get_community_by_id | validation | def get_community_by_id(self, community_id, token=None):
"""
Get a community based on its id.
:param community_id: The id of the target community.
:type community_id: int | long
:param token: (optional) A valid token for the | python | {
"resource": ""
} |
q263320 | CoreDriver.get_community_children | validation | def get_community_children(self, community_id, token=None):
"""
Get the non-recursive children of the passed in community_id.
:param community_id: The id of the requested community.
:type community_id: int | long
:param token: (optional) A valid token for | python | {
"resource": ""
} |
q263321 | CoreDriver.list_communities | validation | def list_communities(self, token=None):
"""
List all communities visible to a user.
:param token: (optional) A valid token for the user in question.
:type token: None | string
:returns: The list of communities.
:rtype: list[dict]
""" | python | {
"resource": ""
} |
q263322 | CoreDriver.folder_get | validation | def folder_get(self, token, folder_id):
"""
Get the attributes of the specified folder.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the requested folder.
:type folder_id: int | long
:returns: Dictionary of the folder attributes.
| python | {
"resource": ""
} |
q263323 | CoreDriver.folder_children | validation | def folder_children(self, token, folder_id):
"""
Get the non-recursive children of the passed in folder_id.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the requested folder.
:type folder_id: int | long
:returns: Dictionary of two lists: 'folders' and 'items'.
| python | {
"resource": ""
} |
q263324 | CoreDriver.delete_folder | validation | def delete_folder(self, token, folder_id):
"""
Delete the folder with the passed in folder_id.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the folder to be deleted.
:type folder_id: int | long
:returns: None.
| python | {
"resource": ""
} |
q263325 | CoreDriver.move_folder | validation | def move_folder(self, token, folder_id, dest_folder_id):
"""
Move a folder to the destination folder.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the folder to be moved.
:type folder_id: int | long
| python | {
"resource": ""
} |
q263326 | CoreDriver.create_item | validation | def create_item(self, token, name, parent_id, **kwargs):
"""
Create an item to the server.
:param token: A valid token for the user in question.
:type token: string
:param name: The name of the item to be created.
:type name: string
:param parent_id: The id of the destination folder.
:type parent_id: int | long
:param description: (optional) The description text of the item.
:type description: string
:param uuid: (optional) The UUID for the item. It will be generated if
not given.
:type uuid: string
:param privacy: (optional) The privacy state of the item
('Public' or 'Private').
| python | {
"resource": ""
} |
q263327 | CoreDriver.item_get | validation | def item_get(self, token, item_id):
"""
Get the attributes of the specified item.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the requested item.
:type item_id: int | string
:returns: Dictionary of the item attributes.
| python | {
"resource": ""
} |
q263328 | CoreDriver.download_item | validation | def download_item(self, item_id, token=None, revision=None):
"""
Download an item to disk.
:param item_id: The id of the item to be downloaded.
:type item_id: int | long
:param token: (optional) The authentication token of the user
requesting the download.
:type token: None | string
:param revision: (optional) The revision of the item to download, this
defaults to HEAD.
:type revision: None | int | long
:returns: A tuple of the filename and the content iterator.
:rtype: (string, unknown)
"""
parameters = dict()
parameters['id'] = item_id
if | python | {
"resource": ""
} |
q263329 | CoreDriver.delete_item | validation | def delete_item(self, token, item_id):
"""
Delete the item with the passed in item_id.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item to be deleted.
:type item_id: int | long
:returns: None.
| python | {
"resource": ""
} |
q263330 | CoreDriver.get_item_metadata | validation | def get_item_metadata(self, item_id, token=None, revision=None):
"""
Get the metadata associated with an item.
:param item_id: The id of the item for which metadata will be returned
:type item_id: int | long
:param token: (optional) A valid token for the user in question.
:type token: None | string
:param revision: (optional) Revision of the item. Defaults to latest
revision.
:type revision: int | long
:returns: List of dictionaries containing item metadata.
:rtype: list[dict]
| python | {
"resource": ""
} |
q263331 | CoreDriver.set_item_metadata | validation | def set_item_metadata(self, token, item_id, element, value,
qualifier=None):
"""
Set the metadata associated with an item.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item for which metadata will be set.
:type item_id: int | long
:param element: The metadata element name.
:type element: string
:param value: The metadata value for the field.
:type value: string
:param qualifier: (optional) The metadata qualifier. Defaults to empty
string.
:type qualifier: None | string
| python | {
"resource": ""
} |
q263332 | CoreDriver.share_item | validation | def share_item(self, token, item_id, dest_folder_id):
"""
Share an item to the destination folder.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item to be shared.
:type item_id: int | long
:param dest_folder_id: The id of destination folder where the item is
shared to.
:type dest_folder_id: int | long
:returns: Dictionary containing the details of the shared item.
:rtype: dict
"""
| python | {
"resource": ""
} |
q263333 | CoreDriver.move_item | validation | def move_item(self, token, item_id, src_folder_id, dest_folder_id):
"""
Move an item from the source folder to the destination folder.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The id of the item to be moved
:type item_id: int | long
:param src_folder_id: The id of source folder where the item is located
:type src_folder_id: int | long
:param dest_folder_id: The id of destination folder where the item is
moved to
:type dest_folder_id: int | long
:returns: Dictionary containing | python | {
"resource": ""
} |
q263334 | CoreDriver.search_item_by_name | validation | def search_item_by_name(self, name, token=None):
"""
Return all items.
:param name: The name of the item to search by.
:type name: string
:param token: (optional) A valid token for the user in question.
| python | {
"resource": ""
} |
q263335 | CoreDriver.search_item_by_name_and_folder | validation | def search_item_by_name_and_folder(self, name, folder_id, token=None):
"""
Return all items with a given name and parent folder id.
:param name: The name of the item to search by.
:type name: string
:param folder_id: The id of the parent folder to search by.
:type folder_id: int | long
:param token: (optional) A valid token for the user in question.
:type token: None | string
:returns: A list of all items with the given name and parent folder id.
:rtype: list[dict]
""" | python | {
"resource": ""
} |
q263336 | CoreDriver.search_item_by_name_and_folder_name | validation | def search_item_by_name_and_folder_name(self, name, folder_name,
token=None):
"""
Return all items with a given name and parent folder name.
:param name: The name of the item to search by.
:type name: string
:param folder_name: The name of the parent folder to search by.
:type folder_name: string
:param token: (optional) A valid token for the user in question.
:type token: None | string
:returns: A list of all items with the given name and parent folder
name.
| python | {
"resource": ""
} |
q263337 | CoreDriver.create_link | validation | def create_link(self, token, folder_id, url, **kwargs):
"""
Create a link bitstream.
:param token: A valid token for the user in question.
:type token: string
:param folder_id: The id of the folder in which to create a new item
that will contain the link. The new item will have the same name as
the URL unless an item name is supplied.
:type folder_id: int | long
:param url: The URL of the link you will create, will be used as the
name of the bitstream and of the item unless an item name is
supplied.
:type url: string
:param item_name: (optional) The name of the newly created item, if
not supplied, the item will have the same name as the URL.
:type item_name: string
:param length: (optional) The length in bytes of the file to which the
link points.
:type length: int | long
:param checksum: (optional) The MD5 checksum of the file to which the
link points.
:type checksum: string
:returns: The item information | python | {
"resource": ""
} |
q263338 | CoreDriver.generate_upload_token | validation | def generate_upload_token(self, token, item_id, filename, checksum=None):
"""
Generate a token to use for upload.
Midas Server uses a individual token for each upload. The token
corresponds to the file specified and that file only. Passing the MD5
checksum allows the server to determine if the file is already in the
asset store.
If :param:`checksum` is passed and the token returned is blank, the
server already has this file and there is no need to follow this
call with a call to `perform_upload`, as the passed in file will have
been added as a bitstream to the item's latest revision, creating a
| python | {
"resource": ""
} |
q263339 | CoreDriver.perform_upload | validation | def perform_upload(self, upload_token, filename, **kwargs):
"""
Upload a file into a given item (or just to the public folder if the
item is not specified.
:param upload_token: The upload token (returned by
generate_upload_token)
:type upload_token: string
:param filename: The upload filename. Also used as the path to the
file, if 'filepath' is not set.
:type filename: string
:param mode: (optional) Stream or multipart. Default is stream.
:type mode: string
:param folder_id: (optional) The id of the folder to upload into.
:type folder_id: int | long
:param item_id: (optional) If set, will append item ``bitstreams`` to
the latest revision (or the one set using :param:`revision` ) of
the existing item.
:type item_id: int | long
:param revision: (optional) If set, will add a new file into an
existing revision. Set this to 'head' to add to the most recent
revision.
:type revision: string | int | long
:param filepath: (optional) The path to the file.
:type filepath: string
:param create_additional_revision: (optional) If set, will create a
new revision in the existing item.
:type create_additional_revision: bool
:returns: Dictionary containing the details of the item created or
changed.
:rtype: dict
"""
parameters = dict()
parameters['uploadtoken'] = upload_token
| python | {
"resource": ""
} |
q263340 | CoreDriver.search | validation | def search(self, search, token=None):
"""
Get the resources corresponding to a given query.
:param search: The search criterion.
:type search: string
:param token: (optional) The credentials to use when searching.
:type token: None | string
| python | {
"resource": ""
} |
q263341 | BatchmakeDriver.add_condor_dag | validation | def add_condor_dag(self, token, batchmaketaskid, dagfilename,
dagmanoutfilename):
"""
Add a Condor DAG to the given Batchmake task.
:param token: A valid token for the user in question.
:type token: string
:param batchmaketaskid: id of the Batchmake task for this DAG
:type batchmaketaskid: int | long
:param dagfilename: Filename of the DAG file
:type dagfilename: string
:param dagmanoutfilename: Filename of the DAG processing output
:type dagmanoutfilename: string
:returns: The created Condor DAG DAO
:rtype: dict
| python | {
"resource": ""
} |
q263342 | BatchmakeDriver.add_condor_job | validation | def add_condor_job(self, token, batchmaketaskid, jobdefinitionfilename,
outputfilename, errorfilename, logfilename,
postfilename):
"""
Add a Condor DAG job to the Condor DAG associated with this
Batchmake task
:param token: A valid token for the user in question.
:type token: string
:param batchmaketaskid: id of the Batchmake task for this DAG
:type batchmaketaskid: int | long
:param jobdefinitionfilename: Filename of the definition file for the
job
:type jobdefinitionfilename: string
:param outputfilename: Filename of the output file for the job
:type outputfilename: string
:param errorfilename: Filename of the error file for the job
:type errorfilename: string
:param logfilename: Filename of the log file for the job
:type logfilename: string
:param postfilename: Filename of the post script log file for the job
:type postfilename: string
:return: The created Condor job DAO.
:rtype: dict
"""
| python | {
"resource": ""
} |
q263343 | DicomextractorDriver.extract_dicommetadata | validation | def extract_dicommetadata(self, token, item_id):
"""
Extract DICOM metadata from the given item
:param token: A valid token for the user in question.
:type token: string
:param item_id: id of the item | python | {
"resource": ""
} |
q263344 | MultiFactorAuthenticationDriver.mfa_otp_login | validation | def mfa_otp_login(self, temp_token, one_time_pass):
"""
Log in to get the real token using the temporary token and otp.
:param temp_token: The temporary token or id returned from normal login
:type temp_token: string
:param one_time_pass: The one-time pass to be sent | python | {
"resource": ""
} |
q263345 | ThumbnailCreatorDriver.create_big_thumbnail | validation | def create_big_thumbnail(self, token, bitstream_id, item_id, width=575):
"""
Create a big thumbnail for the given bitstream with the given width.
It is used as the main image of the given item and shown in the item
view page.
:param token: A valid token for the user in question.
:type token: string
:param bitstream_id: The bitstream from which to create the thumbnail.
:type bitstream_id: int | long
:param item_id: The item on which to set the thumbnail.
:type item_id: int | long
:param width: (optional) The width in pixels to which to resize (aspect
ratio will be preserved). Defaults to 575.
| python | {
"resource": ""
} |
q263346 | ThumbnailCreatorDriver.create_small_thumbnail | validation | def create_small_thumbnail(self, token, item_id):
"""
Create a 100x100 small thumbnail for the given item. It is used for
preview purpose and displayed in the 'preview' and 'thumbnails'
sidebar sections.
:param token: A valid token for the user in question.
:type token: string
:param item_id: The item on which to set the thumbnail.
:type item_id: int | long
:returns: The item object (with the new thumbnail id) and the path
where the newly created thumbnail is stored.
| python | {
"resource": ""
} |
q263347 | SolrDriver.solr_advanced_search | validation | def solr_advanced_search(self, query, token=None, limit=20):
"""
Search item metadata using Apache Solr.
:param query: The Apache Lucene search query.
:type query: string
:param token: (optional) A valid token for the user in question.
:type token: None | string
:param limit: (optional) The limit of the search.
:type limit: int | long
:returns: The list of items that match the search query.
:rtype: list[dict]
"""
| python | {
"resource": ""
} |
q263348 | TrackerDriver.add_scalar_data | validation | def add_scalar_data(self, token, community_id, producer_display_name,
metric_name, producer_revision, submit_time, value,
**kwargs):
"""
Create a new scalar data point.
:param token: A valid token for the user in question.
:type token: string
:param community_id: The id of the community that owns the producer.
:type community_id: int | long
:param producer_display_name: The display name of the producer.
:type producer_display_name: string
:param metric_name: The metric name that identifies which trend this
point belongs to.
:type metric_name: string
:param producer_revision: The repository revision of the producer that
produced this value.
:type producer_revision: int | long | string
:param submit_time: The submit timestamp. Must be parsable with PHP
strtotime().
:type submit_time: string
:param value: The value of the scalar.
:type value: float
:param config_item_id: (optional) If this value pertains to a specific
configuration item, pass its id here.
:type config_item_id: int | long
:param test_dataset_id: (optional) If this value pertains to a
specific test dataset, pass its id here.
:type test_dataset_id: int | long
:param truth_dataset_id: (optional) If this value pertains to a
specific ground truth dataset, pass its id here.
:type truth_dataset_id: int | long
:param silent: (optional) If true, do not perform threshold-based email
notifications for this scalar.
:type silent: bool
:param unofficial: (optional) If true, creates an unofficial scalar
visible only to the user performing the submission.
:type unofficial: bool
:param build_results_url: (optional) A URL for linking to build results
for this submission.
:type build_results_url: string
:param branch: (optional) The branch name in the source repository for
this submission.
:type branch: string
:param submission_id: (optional) The id of the submission.
:type submission_id: int | long
:param submission_uuid: (optional) The uuid of the submission. If one
does not exist, it will be created.
:type submission_uuid: string
:type branch: string
:param params: (optional) Any key/value pairs that should be displayed
with this scalar result.
:type params: dict
:param extra_urls: (optional) Other URL's that should be displayed with
with this scalar result. Each element of the list should be a dict
with the following keys: label, text, href
:type extra_urls: list[dict]
:param unit: (optional) The unit of the scalar value.
:type unit: string
:param reproduction_command: (optional) The command to reproduce this
scalar.
:type reproduction_command: string
:returns: The scalar object that | python | {
"resource": ""
} |
q263349 | TrackerDriver.upload_json_results | validation | def upload_json_results(self, token, filepath, community_id,
producer_display_name, metric_name,
producer_revision, submit_time, **kwargs):
"""
Upload a JSON file containing numeric scoring results to be added as
scalars. File is parsed and then deleted from the server.
:param token: A valid token for the user in question.
:param filepath: The path to the JSON file.
:param community_id: The id of the community that owns the producer.
:param producer_display_name: The display name of the producer.
:param producer_revision: The repository revision of the producer
that produced this value.
:param submit_time: The submit timestamp. Must be parsable with PHP
strtotime().
:param config_item_id: (optional) If this value pertains to a specific
configuration item, pass its id here.
:param test_dataset_id: (optional) If this value pertains to a
specific test dataset, pass its id here.
:param truth_dataset_id: (optional) If this value pertains to a
specific ground truth dataset, pass its id here.
:param parent_keys: (optional) Semicolon-separated list of parent keys
to look for numeric results under. Use '.' to denote nesting, like
in normal javascript syntax.
:param silent: (optional) If true, do not perform threshold-based email
notifications for this scalar.
:param unofficial: (optional) If true, creates an unofficial scalar
visible only to the user performing the submission.
:param build_results_url: (optional) A URL for linking to build results
for this submission.
:param branch: (optional) The branch name in the source repository for
this submission.
:param params: (optional) Any key/value pairs that should be displayed
with this scalar result.
:type params: dict
:param extra_urls: (optional) Other URL's that should be displayed with
with this scalar result. Each element of the list should be a dict
with the following keys: label, text, href
:type extra_urls: list of dicts
:returns: The list of scalars that were created.
"""
parameters = dict()
parameters['token'] = token
parameters['communityId'] = community_id
parameters['producerDisplayName'] = producer_display_name
parameters['metricName'] = metric_name
parameters['producerRevision'] = producer_revision
parameters['submitTime'] = submit_time
optional_keys = [
| python | {
"resource": ""
} |
q263350 | RevisionCollection.__get_rev | validation | def __get_rev(self, key, version, **kwa):
'''Obtain particular version of the doc at key.'''
if '_doc' in kwa:
doc = kwa['_doc']
else:
if type(version) is int:
if version == 0:
order = pymongo.ASCENDING
elif version == -1:
order = pymongo.DESCENDING
doc = self._collection.find_one({'k': key}, sort=[['d', order]])
elif type(version) is datetime:
ver = | python | {
"resource": ""
} |
q263351 | RequestsMock._hashkey | validation | def _hashkey(self, method, url, **kwa):
'''Find a hash value for the linear combination of invocation methods.
'''
to_hash = ''.join([str(method), str(url),
str(kwa.get('data', | python | {
"resource": ""
} |
q263352 | Driver.setup | validation | def setup(self, address, rack=0, slot=1, port=102):
"""Connects to a Siemens S7 PLC.
Connects to a Siemens S7 using the Snap7 library.
See [the snap7 documentation](http://snap7.sourceforge.net/) for
supported models and more details.
It's not currently possible to query the device for available pins,
so `available_pins()` returns an empty list. Instead, you should use
`map_pin()` to map to a Merker, Input or Output in the PLC. The
internal id you should use is a string following this format:
'[DMQI][XBWD][0-9]+.?[0-9]*' where:
* [DMQI]: D for DB, M for Merker, Q for Output, I for Input
* [XBWD]: X for bit, B for byte, W for word, D for dword
* [0-9]+: Address of the resource
* [0-9]*: Bit of the address (type X only, ignored in others)
For example: 'IB100' will read a byte from an input at address 100 and
'MX50.2' will read/write bit 2 of the Merker at address 50. It's not
allowed to write to inputs (I), but you can read/write Outpus, DBs and
Merkers. If it's disallowed by the PLC, an exception will be thrown by
python-snap7 library.
For this library to work, it might be needed to change some settings
in the PLC itself. See
[the snap7 documentation](http://snap7.sourceforge.net/) for more
information. You also need to put the | python | {
"resource": ""
} |
q263353 | Driver.setup | validation | def setup(self, port):
"""Connects to an Arduino UNO on serial port `port`.
@throw RuntimeError can't connect to Arduino
"""
port = str(port)
# timeout is used by all I/O operations
self._serial = serial.Serial(port, 115200, timeout=2)
time.sleep(2) # time to | python | {
"resource": ""
} |
q263354 | Cluster.block_resource_fitnesses | validation | def block_resource_fitnesses(self, block: block.Block):
"""Returns a map of nodename to average fitness value for this block.
Assumes that required resources have been checked on all nodes."""
# Short-circuit! My algorithm is terrible, so it doesn't work well for the edge case where
# the block has no requirements
if not block.resources:
return {n: 1 for n in self.config.nodes.keys()}
node_fitnesses = {}
for resource in block.resources:
resource_fitnesses = self.resource_fitnesses(resource)
if not resource_fitnesses:
raise UnassignableBlock(block.name)
max_fit = max(resource_fitnesses.values())
min_fit = min(resource_fitnesses.values())
for node, fitness in resource_fitnesses.items():
| python | {
"resource": ""
} |
q263355 | available_drivers | validation | def available_drivers():
"""Returns a list of available drivers names.
"""
global __modules
global __available
if type(__modules) is not list:
| python | {
"resource": ""
} |
q263356 | AbstractDriver.map_pin | validation | def map_pin(self, abstract_pin_id, physical_pin_id):
"""Maps a pin number to a physical device pin.
To make it easy to change drivers without having to refactor a lot of
code, this library does not use the names set by the driver to identify
a pin. This function will map a number, that will be used by other
functions, to a physical pin represented by the drivers pin id. That
way, if you need to use another pin or change the underlying driver
completly, you only need to redo the mapping.
If you're developing a driver, keep in mind that your driver will not
know about this. The other functions will translate the mapped pin to
your id before calling your function.
| python | {
"resource": ""
} |
q263357 | AbstractDriver.set_pin_direction | validation | def set_pin_direction(self, pin, direction):
"""Sets pin `pin` to `direction`.
The pin should support the requested mode. Calling this function
on a unmapped pin does nothing. Calling it with a unsupported direction
throws RuntimeError.
If you're developing a driver, you should implement
_set_pin_direction(self, pin, direction) where `pin` will be one of
your internal IDs. If a pin is set to OUTPUT, put it on LOW state.
@arg pin pin id you've set using `AbstractDriver.map_pin`
@arg mode a value from `AbstractDriver.Direction`
@throw KeyError if pin isn't mapped.
@throw RuntimeError if direction is not supported by pin.
| python | {
"resource": ""
} |
q263358 | AbstractDriver.pin_direction | validation | def pin_direction(self, pin):
"""Gets the `ahio.Direction` this pin was set to.
If you're developing a driver, implement _pin_direction(self, pin)
@arg pin the pin you want to see the mode
@returns the `ahio.Direction` the pin is set | python | {
"resource": ""
} |
q263359 | AbstractDriver.set_pin_type | validation | def set_pin_type(self, pin, ptype):
"""Sets pin `pin` to `type`.
The pin should support the requested mode. Calling this function
on a unmapped pin does nothing. Calling it with a unsupported mode
throws RuntimeError.
If you're developing a driver, you should implement
_set_pin_type(self, pin, ptype) where `pin` will be one of your
internal IDs. If a pin is set to OUTPUT, put it on LOW state.
@arg pin pin id you've set using `AbstractDriver.map_pin`
@arg mode a value from `AbstractDriver.PortType`
@throw KeyError if pin isn't mapped.
@throw RuntimeError if type is not supported by pin.
"""
| python | {
"resource": ""
} |
q263360 | AbstractDriver.pin_type | validation | def pin_type(self, pin):
"""Gets the `ahio.PortType` this pin was set to.
If you're developing a driver, implement _pin_type(self, pin)
@arg pin the pin you want to see the mode
@returns the `ahio.PortType` the pin is set | python | {
"resource": ""
} |
q263361 | AbstractDriver.write | validation | def write(self, pin, value, pwm=False):
"""Sets the output to the given value.
Sets `pin` output to given value. If the pin is in INPUT mode, do
nothing. If it's an analog pin, value should be in write_range.
If it's not in the allowed range, it will be clamped. If pin is in
digital mode, value can be `ahio.LogicValue` if `pwm` = False, or a
number between 0 and 1 if `pwm` = True. If PWM is False, the pin will
be set to HIGH or LOW, if `pwm` is True, a PWM wave with the given
cycle will be created. If the pin does not support PWM and `pwm` is
True, raise RuntimeError. The `pwm` argument should be ignored in case
the pin is analog. If value is not valid for the given
pwm/analog|digital combination, raise TypeError.
If you're developing a driver, implement _write(self, pin, value, pwm)
@arg pin the pin to write to
@arg value the value to write on the pin
@arg pwm wether the output should be a pwm wave
@throw RuntimeError if the pin does not support PWM and `pwm` is True.
@throw TypeError if value is not valid for this pin's mode and pwm
value.
@throw KeyError if pin isn't mapped. | python | {
"resource": ""
} |
q263362 | AbstractDriver.read | validation | def read(self, pin):
"""Reads value from pin `pin`.
Returns the value read from pin `pin`. If it's an analog pin, returns
a number in analog.input_range. If it's digital, returns
`ahio.LogicValue`.
If you're developing a driver, implement _read(self, pin)
@arg pin the pin to read from
@returns the value read from the pin
@throw KeyError if pin isn't mapped.
"""
if type(pin) is list:
return [self.read(p) for p in pin]
pin_id = self._pin_mapping.get(pin, None)
| python | {
"resource": ""
} |
q263363 | AbstractDriver.set_analog_reference | validation | def set_analog_reference(self, reference, pin=None):
"""Sets the analog reference to `reference`
If the driver supports per pin reference setting, set pin to the
desired reference. If not, passing None means set to all, which is the
default in most hardware. If only per pin reference is supported and
pin is None, raise RuntimeError.
If you're developing a driver, implement
_set_analog_reference(self, reference, pin). Raise RuntimeError if pin
was set but is not supported by the platform.
@arg reference the value that describes the analog reference. See
`AbstractDriver.analog_references`
@arg pin if the the driver supports it, the pin that will use
`reference` as reference. None for | python | {
"resource": ""
} |
q263364 | AbstractDriver.analog_reference | validation | def analog_reference(self, pin=None):
"""Returns the analog reference.
If the driver supports per pin analog reference setting, returns the
reference for pin `pin`. If pin is None, returns the global analog
reference. If only per pin reference is supported and pin is None,
raise RuntimeError.
If you're developing a driver, implement _analog_reference(self, pin)
@arg pin if the the driver supports it, the pin that will use
`reference` as reference. None for all.
@returns the reference used for pin
@throw RuntimeError if pin is None on a per pin only hardware, or if
| python | {
"resource": ""
} |
q263365 | AbstractDriver.set_pwm_frequency | validation | def set_pwm_frequency(self, frequency, pin=None):
"""Sets PWM frequency, if supported by hardware
If the driver supports per pin frequency setting, set pin to the
desired frequency. If not, passing None means set to all. If only per
pin frequency is supported and pin is None, raise RuntimeError.
If you're developing a driver, implement
_set_pwm_frequency(self, frequency, pin). Raise RuntimeError if pin
was set but is not supported by the platform.
@arg frequency pwm frequency to be set, in Hz
@arg pin if the the driver supports it, the pin that will use
`frequency` as pwm frequency. None for all/global.
@throw RuntimeError | python | {
"resource": ""
} |
q263366 | SIRode | validation | def SIRode(y0, time, beta, gamma):
"""Integrate SIR epidemic model
Simulate a very basic deterministic SIR system.
:param 2x1 numpy array y0: initial conditions
:param Ntimestep length numpy array time: Vector of time points that \
solution is returned at
:param float beta: transmission rate
:param float gamma: recovery rate
| python | {
"resource": ""
} |
q263367 | Communicator.url | validation | def url(self):
"""
Return the URL of the server.
:returns: URL of the server
:rtype: string
"""
if len(self.drivers) > 0:
| python | {
"resource": ""
} |
q263368 | guess_array_memory_usage | validation | def guess_array_memory_usage( bam_readers, dtype, use_strand=False ):
"""Returns an estimate for the maximum amount of memory to be consumed by numpy arrays."""
ARRAY_COUNT = 5
if not isinstance( bam_readers, list ):
bam_readers = [ bam_readers ]
if isinstance( dtype, basestring ):
dtype = NUMPY_DTYPES.get( dtype, None )
use_strand = use_strand + 1 #if false, factor of 1, if true, factor of 2
dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=None, force_dtype=False )
if not [ dt for dt in dtypes if dt is not None ]:
#found no info from idx
dtypes = guess_numpy_dtypes_from_idxstats( bam_readers, default=dtype or numpy.uint64, force_dtype=True )
elif dtype:
dtypes = [ dtype if dt else None for dt in dtypes ]
read_groups = []
no_read_group = False
for bam in bam_readers:
rgs = bam.get_read_groups()
if rgs:
for rg in rgs:
if rg not in read_groups:
read_groups.append( rg )
else:
| python | {
"resource": ""
} |
q263369 | main | validation | def main():
"""Create coverage reports and open them in the browser."""
usage = "Usage: %prog PATH_TO_PACKAGE"
parser = optparse.OptionParser(usage=usage)
parser.add_option(
"-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="Show debug output")
parser.add_option(
"-d", "--output-dir",
action="store", type="string", dest="output_dir",
default='',
help="")
parser.add_option(
"-t", "--test-args",
action="store", type="string", dest="test_args",
default='',
help=("Pass argument on to bin/test. Quote the argument, " +
"for instance \"-t '-m somemodule'\"."))
(options, args) = parser.parse_args()
if options.verbose:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logging.basicConfig(level=log_level,
format="%(levelname)s: %(message)s")
curdir = os.getcwd()
testbinary = os.path.join(curdir, 'bin', 'test')
if not os.path.exists(testbinary):
raise RuntimeError("Test command doesn't exist: %s" % testbinary)
coveragebinary = os.path.join(curdir, 'bin', 'coverage')
if not os.path.exists(coveragebinary):
logger.debug("Trying globally installed coverage command.")
coveragebinary = 'coverage'
logger.info("Running tests in coverage mode (can take a long time)")
parts = [coveragebinary, 'run', testbinary]
if options.test_args:
parts.append(options.test_args) | python | {
"resource": ""
} |
q263370 | Driver.setup | validation | def setup(
self,
configuration="ModbusSerialClient(method='rtu',port='/dev/cu.usbmodem14101',baudrate=9600)"
):
"""Start a Modbus server.
The following classes are available with their respective named
parameters:
ModbusTcpClient
host: The host to connect to (default 127.0.0.1)
port: The modbus port to connect to (default 502)
source_address: The source address tuple to bind to (default ('', 0))
timeout: The timeout to use for this socket (default Defaults.Timeout)
ModbusUdpClient
host: The host to connect to (default 127.0.0.1)
port: The modbus port to connect to (default 502)
timeout: The timeout to use for this socket (default None)
ModbusSerialClient
method: The method to use for connection (asii, rtu, binary)
port: The serial port to attach to
stopbits: The number of stop bits to use (default 1)
bytesize: The bytesize of the serial messages (default 8 bits)
parity: Which kind of parity to use (default None)
baudrate: The baud rate to use for | python | {
"resource": ""
} |
q263371 | get_exception_from_status_and_error_codes | validation | def get_exception_from_status_and_error_codes(status_code, error_code, value):
"""
Return an exception given status and error codes.
:param status_code: HTTP status code.
:type status_code: None | int
:param error_code: Midas Server error code.
:type error_code: None | int
:param value: Message to display.
:type value: string
:returns: Exception.
:rtype : pydas.exceptions.ResponseError
"""
if status_code == requests.codes.bad_request:
exception = BadRequest(value)
elif status_code == requests.codes.unauthorized:
exception = Unauthorized(value)
elif status_code == requests.codes.forbidden:
exception = Unauthorized(value)
elif status_code in [requests.codes.not_found, requests.codes.gone]:
exception = NotFound(value)
elif status_code == requests.codes.method_not_allowed:
exception = MethodNotAllowed(value)
elif status_code >= requests.codes.bad_request:
exception = HTTPError(value)
else:
exception = ResponseError(value)
| python | {
"resource": ""
} |
q263372 | PyMata.analog_read | validation | def analog_read(self, pin):
"""
Retrieve the last analog data value received for the specified pin.
:param pin: Selected pin
:return: The last value entered into the analog response table.
"""
with self.data_lock:
| python | {
"resource": ""
} |
q263373 | PyMata.disable_analog_reporting | validation | def disable_analog_reporting(self, pin):
"""
Disables analog reporting for a single analog pin.
:param pin: Analog pin number. For example for A0, the number is 0.
:return: No return value
"""
| python | {
"resource": ""
} |
q263374 | PyMata.disable_digital_reporting | validation | def disable_digital_reporting(self, pin):
"""
Disables digital reporting. By turning reporting off for this pin, reporting
is disabled for all 8 bits in the "port" -
:param pin: Pin and all pins for this port
:return: No return value
| python | {
"resource": ""
} |
q263375 | PyMata.enable_analog_reporting | validation | def enable_analog_reporting(self, pin):
"""
Enables analog reporting. By turning reporting on for a single pin.
:param pin: Analog pin number. For example for A0, the number is 0.
:return: No return value
"""
| python | {
"resource": ""
} |
q263376 | PyMata.enable_digital_reporting | validation | def enable_digital_reporting(self, pin):
"""
Enables digital reporting. By turning reporting on for all 8 bits in the "port" -
this is part of Firmata's protocol specification.
:param pin: Pin and all pins for this port
:return: No return value
| python | {
"resource": ""
} |
q263377 | PyMata.extended_analog | validation | def extended_analog(self, pin, data):
"""
This method will send an extended data analog output command to the selected pin
:param pin: 0 - 127
:param data: 0 - 0xfffff
"""
analog_data = | python | {
"resource": ""
} |
q263378 | PyMata.get_stepper_version | validation | def get_stepper_version(self, timeout=20):
"""
Get the stepper library version number.
:param timeout: specify a time to allow arduino to process and return a version
:return: the stepper version number if it was set.
"""
# get current time
start_time = time.time()
# wait for up to 20 seconds for a successful capability query to occur
while self._command_handler.stepper_library_version <= 0:
if time.time() - start_time > timeout:
if self.verbose is True:
| python | {
"resource": ""
} |
q263379 | PyMata.i2c_write | validation | def i2c_write(self, address, *args):
"""
Write data to an i2c device.
:param address: i2c device address
:param args: A variable number of bytes to be sent to the device
"""
data = [address, self.I2C_WRITE]
for | python | {
"resource": ""
} |
q263380 | PyMata.i2c_stop_reading | validation | def i2c_stop_reading(self, address):
"""
This method stops an I2C_READ_CONTINUOUSLY operation for the i2c device address specified.
:param address: address of i2c device
"""
data = [address, | python | {
"resource": ""
} |
q263381 | PyMata.play_tone | validation | def play_tone(self, pin, tone_command, frequency, duration):
"""
This method will call the Tone library for the selected pin.
If the tone command is set to TONE_TONE, then the specified tone will be played.
Else, if the tone command is TONE_NO_TONE, then any currently playing tone will be disabled.
It is intended for a future release of Arduino Firmata
:param pin: Pin number
:param tone_command: Either TONE_TONE, or TONE_NO_TONE
:param frequency: Frequency of tone in hz
| python | {
"resource": ""
} |
q263382 | PyMata.set_analog_latch | validation | def set_analog_latch(self, pin, threshold_type, threshold_value, cb=None):
"""
This method "arms" an analog pin for its data to be latched and saved in the latching table
If a callback method is provided, when latching criteria is achieved, the callback function is called
with latching data notification. In that case, the latching table is not updated.
:param pin: Analog pin number (value following an 'A' designator, i.e. A5 = 5
:param threshold_type: ANALOG_LATCH_GT | ANALOG_LATCH_LT | ANALOG_LATCH_GTE | ANALOG_LATCH_LTE
:param threshold_value: numerical value - between 0 and 1023
:param cb: callback method
:return: True if successful, False | python | {
"resource": ""
} |
q263383 | PyMata.set_digital_latch | validation | def set_digital_latch(self, pin, threshold_type, cb=None):
"""
This method "arms" a digital pin for its data to be latched and saved in the latching table
If a callback method is provided, when latching criteria is achieved, the callback function is called
with latching data notification. In that case, the latching table is not updated.
:param pin: Digital pin number
:param threshold_type: DIGITAL_LATCH_HIGH | | python | {
"resource": ""
} |
q263384 | PyMata.servo_config | validation | def servo_config(self, pin, min_pulse=544, max_pulse=2400):
"""
Configure a pin as a servo pin. Set pulse min, max in ms.
:param pin: Servo Pin.
:param min_pulse: Min pulse width in ms.
:param max_pulse: Max pulse width in ms.
:return: No return value
"""
| python | {
"resource": ""
} |
q263385 | PyMata.stepper_config | validation | def stepper_config(self, steps_per_revolution, stepper_pins):
"""
Configure stepper motor prior to operation.
:param steps_per_revolution: number of steps per motor revolution
:param stepper_pins: a list of control pin numbers - either 4 or 2
"""
data = [self.STEPPER_CONFIGURE, steps_per_revolution & 0x7f, (steps_per_revolution >> | python | {
"resource": ""
} |
q263386 | PyMata.stepper_step | validation | def stepper_step(self, motor_speed, number_of_steps):
"""
Move a stepper motor for the number of steps at the specified speed
:param motor_speed: 21 bits of data to set motor speed
:param number_of_steps: 14 bits for number of steps & direction
positive is forward, negative is reverse
"""
if number_of_steps > 0:
direction = 1
else:
direction = 0
| python | {
"resource": ""
} |
q263387 | PyMata.stepper_request_library_version | validation | def stepper_request_library_version(self):
"""
Request the stepper library version from the Arduino.
To retrieve the version after | python | {
"resource": ""
} |
q263388 | PyMataSerial.open | validation | def open(self, verbose):
"""
open the serial port using the configuration data
returns a reference to this instance
"""
# open a serial port
if verbose:
print('\nOpening Arduino Serial port %s ' % self.port_id)
try:
# in case the port is already open, let's close it and then
# reopen it
self.arduino.close()
| python | {
"resource": ""
} |
q263389 | PyMataSerial.run | validation | def run(self):
"""
This method continually runs. If an incoming character is available on the serial port
it is read and placed on the _command_deque
@return: Never Returns
"""
while not self.is_stopped():
# we can get an OSError: [Errno9] Bad file descriptor when shutting down
# just ignore it
try:
if self.arduino.inWaiting():
| python | {
"resource": ""
} |
q263390 | BiColorDisplayController.set_brightness | validation | def set_brightness(self, brightness):
"""
Set the brightness level for the entire display
@param brightness: brightness level (0 -15)
"""
if brightness > 15:
| python | {
"resource": ""
} |
q263391 | BiColorDisplayController.set_bit_map | validation | def set_bit_map(self, shape, color):
"""
Populate the bit map with the supplied "shape" and color
and then write the entire bitmap to the display
@param shape: pattern to display
@param color: color for the pattern
"""
for row in range(0, 8):
data = shape[row]
# shift data into buffer
bit_mask = 0x80
| python | {
"resource": ""
} |
q263392 | BiColorDisplayController.output_entire_buffer | validation | def output_entire_buffer(self):
"""
Write the entire buffer to the display
"""
green = 0
red = 0
for row in range(0, 8):
for col in range(0, 8):
if self.display_buffer[row][col] == self.LED_GREEN:
green |= 1 << col
elif self.display_buffer[row][col] == self.LED_RED:
red |= 1 << col
elif self.display_buffer[row][col] == self.LED_YELLOW:
green |= 1 << col | python | {
"resource": ""
} |
q263393 | BiColorDisplayController.clear_display_buffer | validation | def clear_display_buffer(self):
"""
Set all led's to off.
"""
for row in range(0, 8):
self.firmata.i2c_write(0x70, row * 2, 0, 0)
self.firmata.i2c_write(0x70, | python | {
"resource": ""
} |
q263394 | PyMataCommandHandler.digital_message | validation | def digital_message(self, data):
"""
This method handles the incoming digital message.
It stores the data values in the digital response table.
Data is stored for all 8 bits of a digital port
:param data: Message data from Firmata
:return: No return value.
"""
port = data[0]
port_data = (data[self.MSB] << 7) + data[self.LSB]
# set all the pins for this reporting port
# get the first pin number for this report
pin = port * 8
for pin in range(pin, min(pin + 8, self.total_pins_discovered)):
# shift through all the bit positions and set the digital response table
with self.pymata.data_lock:
# look at the previously stored value for this pin
prev_data = self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]
# get the current value
self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE] = port_data & 0x01
# if the values differ and callback is enabled for the pin, then send out the callback
if prev_data != port_data & 0x01:
callback = self.digital_response_table[pin][self.RESPONSE_TABLE_CALLBACK]
if callback:
callback([self.pymata.DIGITAL, pin,
self.digital_response_table[pin][self.RESPONSE_TABLE_PIN_DATA_VALUE]])
# determine if the latch data table needs to be updated for each pin
latching_entry = self.digital_latch_table[pin]
| python | {
"resource": ""
} |
q263395 | PyMataCommandHandler.encoder_data | validation | def encoder_data(self, data):
"""
This method handles the incoming encoder data message and stores
the data in the digital response table.
:param data: Message data from Firmata
:return: No return value.
"""
prev_val = self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE]
val = int((data[self.MSB] << 7) + data[self.LSB])
# set value so that it shows positive and negative values
if val > 8192:
val -= 16384
pin = data[0]
with self.pymata.data_lock:
| python | {
"resource": ""
} |
q263396 | PyMataCommandHandler.sonar_data | validation | def sonar_data(self, data):
"""
This method handles the incoming sonar data message and stores
the data in the response table.
:param data: Message data from Firmata
:return: No return value.
"""
val = int((data[self.MSB] << 7) + data[self.LSB])
pin_number = data[0]
with self.pymata.data_lock:
sonar_pin_entry = self.active_sonar_map[pin_number]
# also write it into the digital response table
self.digital_response_table[data[self.RESPONSE_TABLE_MODE]][self.RESPONSE_TABLE_PIN_DATA_VALUE] = val
# send data through callback if there is a callback function for the pin
if sonar_pin_entry[0] is not None:
| python | {
"resource": ""
} |
q263397 | PyMataCommandHandler.send_sysex | validation | def send_sysex(self, sysex_command, sysex_data=None):
"""
This method will send a Sysex command to Firmata with any accompanying data
:param sysex_command: sysex command
:param sysex_data: data for command
:return : No return value.
"""
if not sysex_data:
sysex_data = []
# convert the message command and data to characters
sysex_message = chr(self.START_SYSEX)
sysex_message += chr(sysex_command)
| python | {
"resource": ""
} |
q263398 | PyMataCommandHandler.send_command | validation | def send_command(self, command):
"""
This method is used to transmit a non-sysex command.
:param command: Command to send to firmata includes command + data formatted by caller
:return : No return value.
"""
| python | {
"resource": ""
} |
q263399 | PyMataCommandHandler.system_reset | validation | def system_reset(self):
"""
Send the reset command to the Arduino.
It resets the response tables to their initial values
:return: No return value
"""
data = chr(self.SYSTEM_RESET)
self.pymata.transport.write(data)
# response table re-initialization
# for each pin set the mode to input and the last read data value to zero
with self.pymata.data_lock:
# remove all old entries from existing tables
for _ in range(len(self.digital_response_table)):
self.digital_response_table.pop()
for _ in range(len(self.analog_response_table)):
self.analog_response_table.pop()
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.