docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Add or invite a user to your Team
Args:
account_id (str): The id of the account of the user to invite to your team.
email_address (str): The email address of the account to invite to your team. The account id prevails if both account_id and email_address are provided.
... | def add_team_member(self, account_id=None, email_address=None):
return self._add_remove_team_member(self.TEAM_ADD_MEMBER_URL, email_address, account_id) | 518,269 |
Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.
... | def remove_team_member(self, account_id=None, email_address=None):
return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id) | 518,270 |
Retrieves a embedded signing object
Retrieves an embedded object containing a signature url that can be opened in an iFrame.
Args:
signature_id (str): The id of the signature to get a signature url for
Returns:
An Embedded object | def get_embedded_object(self, signature_id):
request = self._get_request()
return request.get(self.EMBEDDED_OBJECT_GET_URL + signature_id) | 518,271 |
Retrieves a embedded template for editing
Retrieves an embedded object containing a template url that can be opened in an iFrame.
Args:
template_id (str): The id of the template to get a signature url for
Returns:
An Embedded object | def get_template_edit_url(self, template_id):
request = self._get_request()
return request.get(self.EMBEDDED_TEMPLATE_EDIT_URL + template_id) | 518,272 |
Get Oauth data from HelloSign
Args:
code (str): Code returned by HelloSign for our callback url
client_id (str): Client id of the associated app
client_secret (str): Secret token of the associated app
Returns:
A HSAccessTokenAuth... | def get_oauth_data(self, code, client_id, client_secret, state):
request = self._get_request()
response = request.post(self.OAUTH_TOKEN_URL, {
"state": state,
"code": code,
"grant_type": "authorization_code",
"client_id": client_id,
"c... | 518,276 |
Refreshes the current access token.
Gets a new access token, updates client auth and returns it.
Args:
refresh_token (str): Refresh token to use
Returns:
The new access token | def refresh_access_token(self, refresh_token):
request = self._get_request()
response = request.post(self.OAUTH_TOKEN_URL, {
"grant_type": "refresh_token",
"refresh_token": refresh_token
})
self.auth = HSAccessTokenAuth.from_response(response)
ret... | 518,277 |
Add or Remove a team member
We use this function for two different tasks because they have the same
API call
Args:
email_address (str): Email address of the Account to add/remove
account_id (str): ID of the Account to add/remove
Returns:
... | def _add_remove_team_member(self, url, email_address=None, account_id=None):
if not email_address and not account_id:
raise HSException("No email address or account_id specified")
data = {}
if account_id is not None:
data = {
"account_id": accou... | 518,285 |
Initialization of the object
Args:
jsonstr (str): a raw JSON string that is returned by a request.
We store all the data in `self.json_data` and use `__getattr__`
and `__setattr__` to make the data accessible like attributes
of the object
... | def __init__(self, jsonstr=None, key=None, warnings=None):
super(Resource, self).__init__()
self.warnings = warnings
if jsonstr is not None:
data = json.loads(json.dumps(jsonstr))
if key is not None:
object.__setattr__(self, 'json_data', data[key]... | 518,290 |
Send a GET request with custome headers and parameters
Args:
url (str): URL to send the request to
headers (str, optional): custom headers
parameters (str, optional): optional parameters
Returns:
A JSON object of the returned response if `get_json` is Tr... | def get(self, url, headers=None, parameters=None, get_json=True):
if self.debug:
print("GET: %s, headers=%s" % (url, headers))
self.headers = self._get_default_headers()
get_parameters = self.parameters
if get_parameters is None:
# In case self.paramete... | 518,295 |
Make POST request to a url
Args:
url (str): URL to send the request to
data (dict, optional): Data to send
files (dict, optional): Files to send with the request
headers (str, optional): custom headers
Returns:
A JSON object of the returned r... | def post(self, url, data=None, files=None, headers=None, get_json=True):
if self.debug:
print("POST: %s, headers=%s" % (url, headers))
self.headers = self._get_default_headers()
if headers is not None:
self.headers.update(headers)
response = requests.p... | 518,296 |
Check for HTTP error code from the response, raise exception if there's any
Args:
response (object): Object returned by requests' `get` and `post`
methods
json_response (dict): JSON response, if applicable
Raises:
HTTPError: If the status code of re... | def _check_error(self, response, json_response=None):
# If status code is 4xx or 5xx, that should be an error
if response.status_code >= 400:
json_response = json_response or self._get_json_response(response)
err_cls = self._check_http_error_code(response.status_code)
... | 518,299 |
Extract warnings from the response to make them accessible
Args:
json_response (dict): JSON response | def _check_warnings(self, json_response):
self.warnings = None
if json_response:
self.warnings = json_response.get('warnings')
if self.debug and self.warnings:
for w in self.warnings:
print("WARNING: %s - %s" % (w['warning_name'], w['warning_msg... | 518,300 |
Initialziation of the object
Args:
access_token (str): Access token
access_token_type (str): Access token type
refresh_token (str):
expires_in (int): Seconds after which the token will expire
state (str): | def __init__(self, access_token, access_token_type, refresh_token=None, expires_in=None, state=None):
self.access_token = access_token
self.access_token_type = access_token_type
self.refresh_token = refresh_token
self.expires_in = expires_in
self.state = state | 518,302 |
Builds a new HSAccessTokenAuth straight from response data
Args:
response_data (dict): Response data to use
Returns:
A HSAccessTokenAuth objet | def from_response(self, response_data):
return HSAccessTokenAuth(
response_data['access_token'],
response_data['token_type'],
response_data['refresh_token'],
response_data['expires_in'],
response_data.get('state') # Not always here
) | 518,304 |
Find one or many repsonse components.
Args:
api_id (str): Api id associated with the component(s) to be retrieved.
signature_id (str): Signature id associated with the component(s) to be retrieved.
Returns:
A list of dictionaries ... | def find_response_component(self, api_id=None, signature_id=None):
if not api_id and not signature_id:
raise ValueError('At least one of api_id and signature_id is required')
components = list()
if self.response_data:
for component in self.response_data... | 518,307 |
Return a signature for the given parameters
Args:
signature_id (str): Id of the signature to retrieve.
signer_email_address (str): Email address of the associated signer for the signature to retrieve.
Returns:
A Signature object ... | def find_signature(self, signature_id=None, signer_email_address=None):
if self.signatures:
for signature in self.signatures:
if signature.signature_id == signature_id or signature.signer_email_address == signer_email_address:
return signature | 518,308 |
Utility method for formatting lists of parameters for api consumption
Useful for email address lists, etc
Args:
listed_params (list of values) - the list to format
output_name (str) - the parameter name to prepend to each key | def format_param_list(listed_params, output_name):
output_payload = {}
if listed_params:
for index, item in enumerate(listed_params):
output_payload[str(output_name) + "[" + str(index) + "]" ] = item
return output_payload | 518,316 |
Generate the md5 checksum for a string
Args:
string (Str): The string to be checksummed.
Returns:
(Str): The hex checksum. | def md5sum( string ):
h = hashlib.new( 'md5' )
h.update( string.encode( 'utf-8' ) )
return h.hexdigest() | 518,545 |
Generate the md5 checksum for a file
Args:
filename (Str): The file to be checksummed.
Returns:
(Str): The hex checksum
Notes:
If the file is gzipped, the md5 checksum returned is
for the uncompressed ASCII file. | def file_md5( filename ):
with zopen( filename, 'r' ) as f:
file_string = f.read()
try: # attempt to decode byte object
file_string = file_string.decode()
except AttributeError:
pass
return( md5sum( file_string ) ) | 518,546 |
Checks whether a file exists, either as named, or as a a gzippped file (filename.gz)
Args:
(Str): The root filename.
Returns:
(Str|None): if the file exists (either as the root filename, or gzipped), the return
value will be the actual filename. If no matching filename is found the... | def match_filename( filename ):
f = next( ( '{}{}'.format( filename, extension ) for extension in [ '', '.gz' ]
if Path( '{}{}'.format( filename, extension ) ).is_file() ), None )
return f | 518,547 |
Compares the md5 checksum of a file with an expected value.
If the calculated and expected checksum values are not equal,
ValueError is raised.
If the filename `foo` is not found, will try to read a gzipped file named
`foo.gz`. In this case, the checksum is calculated for the unzipped file.
Args:
... | def validate_checksum( filename, md5sum ):
filename = match_filename( filename )
md5_hash = file_md5( filename=filename )
if md5_hash != md5sum:
raise ValueError('md5 checksums are inconsistent: {}'.format( filename )) | 518,548 |
Convert a list of matrix components to a symmetric 3x3 matrix.
Inputs should be in the order xx, yy, zz, xy, yz, xz.
Args:
xx (float): xx component of the matrix.
yy (float): yy component of the matrix.
zz (float): zz component of the matrix.
xy (float): xy component of the matr... | def to_matrix( xx, yy, zz, xy, yz, xz ):
matrix = np.array( [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]] )
return matrix | 518,549 |
Initialise a Rdf object for manipulating radial distribution functions.
Args:
max_r (Float): the maximum r value stored for g(r).
number_of_bins (Int): number of bins for storing data about g(r).
Returns:
None | def __init__( self, max_r, number_of_bins ):
self.max_r = max_r
self.number_of_bins = number_of_bins
self.data = np.zeros( number_of_bins )
self.dr = max_r / number_of_bins | 518,581 |
Add an observed interatomic distance to the g(r) data at dr.
Args:
dr (Float): the interatomic distance, dr.
Returns:
None | def add_dr( self, dr ):
this_bin = int( dr / self.dr )
if this_bin > self.number_of_bins:
raise IndexError( 'dr is larger than rdf max_r' )
self.data[ this_bin ] += 1 | 518,582 |
Calculate the distance between two atoms.
Args:
atom1 (vasppy.Atom): Atom 1.
atom2 (vasppy.Atom): Atom 2.
Returns:
(float): The distance between Atom 1 and Atom 2. | def dr( self, atom1, atom2 ):
return self.cell.dr( atom1.r, atom2.r ) | 518,586 |
Returns the area of a triangle defined by three points in Cartesian space.
Args:
a (np.array): Cartesian coordinates of point A.
b (np.array): Cartesian coordinates of point B.
c (np.array): Cartesian coordinates of point C.
Returns:
(float): the area of the triangle. | def area_of_a_triangle_in_cartesian_space( a, b, c ):
return 0.5 * np.linalg.norm( np.cross( b-a, c-a ) ) | 518,597 |
Calculate the effective mass given eigenvalues at two k-points.
Reimplemented from Aron Walsh's original effective mass Fortran code.
Args:
cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) Cartesian coordinates.
eigenvalues (np.array): numpy array con... | def two_point_effective_mass( cartesian_k_points, eigenvalues ):
assert( cartesian_k_points.shape[0] == 2 )
assert( eigenvalues.size == 2 )
dk = cartesian_k_points[ 1 ] - cartesian_k_points[ 0 ]
mod_dk = np.sqrt( np.dot( dk, dk ) )
delta_e = ( eigenvalues[ 1 ] - eigenvalues[ 0 ] ) * ev_to_hartr... | 518,599 |
Calculate the effective mass using a least squares quadratic fit.
Args:
cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points
eigenvalues (np.array): Energy eigenvalues at each k-point to be used in the fit.
Returns:
(float): The fitted effective mass
... | def least_squares_effective_mass( cartesian_k_points, eigenvalues ):
if not points_are_in_a_straight_line( cartesian_k_points ):
raise ValueError( 'k-points are not collinear' )
dk = cartesian_k_points - cartesian_k_points[0]
mod_dk = np.linalg.norm( dk, axis = 1 )
delta_e = eigenvalues - e... | 518,600 |
Stoichiometry for this POSCAR, as a Counter.
e.g. AB_2O_4 -> Counter( { 'A': 1, 'B': 2, O: 4 } )
Args:
None
Returns:
None | def stoichiometry( self ):
return Counter( { label: number for label, number in zip( self.atoms, self.atom_numbers ) } ) | 518,640 |
Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.
Args:
filename (Str): The name of the POTCAR file to process.
Returns:
(Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.
{ 'Fe_pv': 'PBE_54', 'O', 'PBE_54' } | def potcar_spec( filename ):
p_spec = {}
with open( filename, 'r' ) as f:
potcars = re.split('(End of Dataset\n)', f.read() )
potcar_md5sums = [ md5sum( ''.join( pair ) ) for pair in zip( potcars[::2], potcars[1:-1:2] ) ]
for this_md5sum in potcar_md5sums:
for ps in potcar_sets:
... | 518,642 |
Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories. | def find_vasp_calculations():
dir_list = [ './' + re.sub( r'vasprun\.xml', '', path ) for path in glob.iglob( '**/vasprun.xml', recursive=True ) ]
gz_dir_list = [ './' + re.sub( r'vasprun\.xml\.gz', '', path ) for path in glob.iglob( '**/vasprun.xml.gz', recursive=True ) ]
return dir_list + gz_dir_list | 518,643 |
Read in `vasprun.xml` as a pymatgen Vasprun object.
Args:
None
Returns:
None
None:
If the vasprun.xml is not well formed this method will catch the ParseError
and set self.vasprun = None. | def parse_vasprun( self ):
self.vasprun_filename = match_filename( 'vasprun.xml' )
if not self.vasprun_filename:
raise FileNotFoundError( 'Could not find vasprun.xml or vasprun.xml.gz file' )
try:
self.vasprun = Vasprun( self.vasprun_filename, parse_p... | 518,645 |
Calculate the change in energy for reactants --> products.
Args:
reactants (list(vasppy.Calculation): A list of vasppy.Calculation objects. The initial state.
products (list(vasppy.Calculation): A list of vasppy.Calculation objects. The final state.
check_balance (bool:optional): Check... | def delta_E( reactants, products, check_balance=True ):
if check_balance:
if delta_stoichiometry( reactants, products ) != {}:
raise ValueError( "reaction is not balanced: {}".format( delta_stoichiometry( reactants, products) ) )
return sum( [ r.energy for r in products ] ) - sum( [ r.e... | 518,682 |
Calculate the change in stoichiometry for reactants --> products.
Args:
reactants (list(vasppy.Calculation): A list of vasppy.Calculation objects. The initial state.
products (list(vasppy.Calculation): A list of vasppy.Calculation objects. The final state.
Returns:
(Counter): The chan... | def delta_stoichiometry( reactants, products ):
totals = Counter()
for r in reactants:
totals.update( ( r * -1.0 ).stoichiometry )
for p in products:
totals.update( p.stoichiometry )
to_return = {}
for c in totals:
if totals[c] != 0:
to_return[c] = totals[c]... | 518,683 |
Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.
Args:
string (str): The string to convert.
Return
(float) | def energy_string_to_float( string ):
energy_re = re.compile( "(-?\d+\.\d+)" )
return float( energy_re.match( string ).group(0) ) | 518,684 |
Initialise a Calculation object
Args:
title (Str): The title string for this calculation.
energy (Float): Final energy in eV.
stoichiometry (Dict{Str:Int}): A dict desribing the calculation stoichiometry,
e.g. { 'Ti': 1, 'O': 2 }
Returns:
... | def __init__( self, title, energy, stoichiometry ):
self.title = title
self.energy = energy
self.stoichiometry = Counter( stoichiometry ) | 518,686 |
"Multiply" this Calculation by a scaling factor.
Returns a new Calculation with the same title, but scaled energy and stoichiometry.
Args:
scaling (float): The scaling factor.
Returns:
(vasppy.Calculation): The scaled Calculation. | def __mul__( self, scaling ):
new_calculation = Calculation( title=self.title, energy=self.energy*scaling, stoichiometry=self.scale_stoichiometry( scaling ) )
return new_calculation | 518,687 |
Scale the Calculation stoichiometry
Returns the stoichiometry, scaled by the argument scaling.
Args:
scaling (float): The scaling factor.
Returns:
(Counter(Str:Int)): The scaled stoichiometry as a Counter of label: stoichiometry pairs | def scale_stoichiometry( self, scaling ):
return { k:v*scaling for k,v in self.stoichiometry.items() } | 518,688 |
Initialise an Atom instance
Args:
label (Str): a label for this atom
r (numpy.array): the atom coordinates
Returns:
None | def __init__( self, label, r ): # currently assume fractional coordinates
self.label = label
self.r = r | 518,689 |
Calculate the angle between two vectors, in degrees.
Args:
x (np.array): one vector.
y (np.array): the other vector.
Returns:
(float): the angle between x and y in degrees. | def angle( x, y ):
dot = np.dot( x, y )
x_mod = np.linalg.norm( x )
y_mod = np.linalg.norm( y )
cos_angle = dot / ( x_mod * y_mod )
return np.degrees( np.arccos( cos_angle ) ) | 518,692 |
Initialise a Cell object.
Args:
matrix (np.array): 3x3 numpy array containing the cell matrix.
Returns:
None | def __init__( self, matrix ):
assert type( matrix ) is np.ndarray
assert matrix.shape == ( 3, 3 )
self.matrix = matrix # 3 x 3 numpy Array
self.inv_matrix = np.linalg.inv( matrix ) | 518,693 |
Calculate the distance between two fractional coordinates in the cell.
Args:
r1 (np.array): fractional coordinates for position 1.
r2 (np.array): fractional coordinates for position 2.
cutoff (optional:Bool): If set, returns None for distances greater than the cutoff... | def dr( self, r1, r2, cutoff=None ):
delta_r_cartesian = ( r1 - r2 ).dot( self.matrix )
delta_r_squared = sum( delta_r_cartesian**2 )
if cutoff != None:
cutoff_squared = cutoff ** 2
if delta_r_squared > cutoff_squared:
return None
return( ... | 518,694 |
Find the minimum image vector from point r1 to point r2.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of point r2.
Returns:
(np.array): the fractional coordinate vector from r1 to the nearest image of r2. | def minimum_image( self, r1, r2 ):
delta_r = r2 - r1
delta_r = np.array( [ x - math.copysign( 1.0, x ) if abs(x) > 0.5 else x for x in delta_r ] )
return( delta_r ) | 518,695 |
Calculate the shortest distance between two points in the cell,
accounting for periodic boundary conditions.
Args:
r1 (np.array): fractional coordinates of point r1.
r2 (np.array): fractional coordinates of point r2.
cutoff (:obj: `float`, optional): if set, return ... | def minimum_image_dr( self, r1, r2, cutoff=None ):
delta_r_vector = self.minimum_image( r1, r2 )
return( self.dr( np.zeros( 3 ), delta_r_vector, cutoff ) ) | 518,696 |
The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths. | def lengths( self ):
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) | 518,697 |
The cell angles (in degrees).
Args:
None
Returns:
(list(alpha,beta,gamma)): The cell angles. | def angles( self ):
( a, b, c ) = [ row for row in self.matrix ]
return [ angle( b, c ), angle( a, c ), angle( a, b ) ] | 518,698 |
Given a fractional-coordinate, if this lies outside the cell return the equivalent point inside the cell.
Args:
r (np.array): Fractional coordinates of a point (this may be outside the cell boundaries).
Returns:
(np.array): Fractional coordinates of an equivalent point, inside ... | def inside_cell( self, r ):
centre = np.array( [ 0.5, 0.5, 0.5 ] )
new_r = self.nearest_image( centre, r )
return new_r | 518,699 |
The cell volume.
Args:
None
Returns:
(float): The cell volume. | def volume( self ):
return np.dot( self.matrix[0], np.cross( self.matrix[1], self.matrix[2] ) ) | 518,700 |
Create a VASPMeta object by reading a `vaspmeta.yaml` file
Args:
filename (Str): filename to read in.
Returns:
(vasppy.VASPMeta): the VASPMeta object | def from_file( cls, filename ):
with open( filename, 'r' ) as stream:
data = yaml.load( stream, Loader=yaml.SafeLoader )
notes = data.get( 'notes' )
v_type = data.get( 'type' )
track = data.get( 'track' )
xargs = {}
if track:
... | 518,704 |
Finds and returns the reciprocal lattice vectors, if more than
one set present, it just returns the last one.
Args:
filename (Str): The name of the outcar file to be read
Returns:
List(Float): The reciprocal lattice vectors. | def reciprocal_lattice_from_outcar( filename ): # from https://github.com/MaterialsDiscovery/PyChemia
outcar = open(filename, "r").read()
# just keeping the last component
recLat = re.findall(r"reciprocal\s*lattice\s*vectors\s*([-.\s\d]*)",
outcar)[-1]
recLat = recLat.split(... | 518,706 |
Finds and returns the energy from a VASP OUTCAR file, by searching for the last `energy(sigma->0)` entry.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(Float): The last energy read from the OUTCAR file. | def final_energy_from_outcar( filename='OUTCAR' ):
with open( filename ) as f:
outcar = f.read()
energy_re = re.compile( "energy\(sigma->0\) =\s+([-\d\.]+)" )
energy = float( energy_re.findall( outcar )[-1] )
return energy | 518,707 |
Returns the first line from a VASP OUTCAR file, to get the VASP source version string.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(Str): The first line read from the OUTCAR file. | def vasp_version_from_outcar( filename='OUTCAR' ):
with open( filename ) as f:
line = f.readline().strip()
return line | 518,708 |
Returns a list of EATOM values for the pseudopotentials used.
Args:
filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.
Returns:
(List(Float)): A list of EATOM values, in the order they appear in the OUTCAR. | def potcar_eatom_list_from_outcar( filename='OUTCAR' ):
with open( filename ) as f:
outcar = f.read()
eatom_re = re.compile( "energy of atom\s+\d+\s+EATOM=\s*([-\d\.]+)" )
eatom = [ float( e ) for e in eatom_re.findall( outcar ) ]
return eatom | 518,709 |
Finds and returns the fermi energy.
Args:
-filename: the name of the outcar file to be read
Returns:
(Float): The fermi energy as found in the OUTCAR | def fermi_energy_from_outcar( filename='OUTCAR' ):
outcar = open(filename, "r").read()
# returns a match object
fermi_energy = re.search(r"E-fermi\s*:\s*([-.\d]*)", outcar)
# take the first group - group(0) contains entire match
fermi_energy = float(fermi_energy.group(1))
return fermi_energ... | 518,710 |
Sets the sleep timer.
Args:
sleep_time_seconds (int or NoneType): How long to wait before
turning off speaker in seconds, None to cancel a sleep timer.
Maximum value of 86399
Raises:
SoCoException: Upon errors interacting with Sonos controller
... | def set_sleep_timer(self, sleep_time_seconds):
# Note: A value of None for sleep_time_seconds is valid, and needs to
# be preserved distinctly separate from 0. 0 means go to sleep now,
# which will immediately start the sound tappering, and could be a
# useful feature, while Non... | 519,018 |
Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
fade (bool): Whether volume should be fade... | def restore(self, fade=False):
try:
if self.is_coordinator:
self._restore_coordinator()
finally:
self._restore_volume(fade)
# Now everything is set, see if we need to be playing, stopped
# or paused ( only for coordinators)
if se... | 519,019 |
Reinstate volume.
Args:
fade (bool): Whether volume should be faded up on restore. | def _restore_volume(self, fade):
self.device.mute = self.mute
# Can only change volume on device with fixed volume set to False
# otherwise get uPnP error, so check first. Before issuing a network
# command to check, fixed volume always has volume set to 100.
# So only ... | 519,021 |
Return a device by name.
Args:
name (str): The name of the device to return.
Returns:
:class:`~.SoCo`: The first device encountered among all zone with the
given player name. If none are found `None` is returned. | def by_name(name):
devices = discover(all_households=True)
for device in (devices or []):
if device.player_name == name:
return device
return None | 519,025 |
Return a dictionary containing Steps read from file.
Args:
steps_dir (str, optional): path to directory containing CWL files.
step_file (str, optional): path or http(s) url to a single CWL file.
step_list (list, optional): a list of directories, urls or local file
paths to CWL f... | def load_steps(working_dir=None, steps_dir=None, step_file=None,
step_list=None):
if steps_dir is not None:
step_files = glob.glob(os.path.join(steps_dir, '*.cwl'))
elif step_file is not None:
step_files = [step_file]
elif step_list is not None:
step_files = []
... | 519,042 |
Set a Step's input variable to a certain value.
The value comes either from a workflow input or output of a previous
step.
Args:
name (str): the name of the Step input
value (str): the name of the output variable that provides the
value for this inpu... | def set_input(self, p_name, value):
name = self.python_names.get(p_name)
if p_name is None or name not in self.get_input_names():
raise ValueError('Invalid input "{}"'.format(p_name))
self.step_inputs[name] = value | 519,051 |
Return a reference to the given output for use in an input
of a next Step.
For a Step named `echo` that has an output called `echoed`, the
reference `echo/echoed` is returned.
Args:
name (str): the name of the Step output
Raises:
ValueError: The name... | def output_reference(self, name):
if name not in self.output_names:
raise ValueError('Invalid output "{}"'.format(name))
return Reference(step_name=self.name_in_workflow, output_name=name) | 519,052 |
Returns True if a step input parameter is optional.
Args:
inp (dict): a dictionary representation of an input.
Raises:
ValueError: The inp provided is not valid. | def _input_optional(inp):
if 'default' in inp.keys():
return True
typ = inp.get('type')
if isinstance(typ, six.string_types):
return typ.endswith('?')
elif isinstance(typ, dict):
# TODO: handle case where iput type is dict
return ... | 519,053 |
Load CWL steps into the WorkflowGenerator's steps library.
Adds steps (command line tools and workflows) to the
``WorkflowGenerator``'s steps library. These steps can be used to
create workflows.
Args:
steps_dir (str): path to directory containing CWL files. All CWL in
... | def load(self, steps_dir=None, step_file=None, step_list=None):
self._closed()
self.steps_library.load(steps_dir=steps_dir, step_file=step_file,
step_list=step_list) | 519,061 |
List input names and types of a step in the steps library.
Args:
name (str): name of a step in the steps library. | def inputs(self, name):
self._closed()
step = self._get_step(name, make_copy=False)
return step.list_inputs() | 519,063 |
Add a step to the workflow.
Args:
step (Step): a step from the steps library. | def _add_step(self, step):
self._closed()
self.has_workflow_step = self.has_workflow_step or step.is_workflow
self.wf_steps[step.name_in_workflow] = step | 519,064 |
Add workflow outputs.
The output type is added automatically, based on the steps in the steps
library.
Args:
kwargs (dict): A dict containing ``name=source name`` pairs.
``name`` is the name of the workflow output (e.g.,
``txt_files``) and source nam... | def add_outputs(self, **kwargs):
self._closed()
for name, source_name in kwargs.items():
obj = {}
obj['outputSource'] = source_name
obj['type'] = self.step_output_types[source_name]
self.wf_outputs[name] = obj | 519,066 |
Generated and print the scriptcwl script for the currunt workflow.
Args:
wf_name (str): string used for the WorkflowGenerator object in the
generated script (default: ``wf``). | def to_script(self, wf_name='wf'):
self._closed()
script = []
# Workflow documentation
# if self.documentation:
# if is_multiline(self.documentation):
# print('doc = ')
# print('{}.set_documentation(doc)'.format(wf_name))
# e... | 519,070 |
Save the workflow to file.
Save the workflow to a CWL file that can be run with a CWL runner.
Args:
fname (str): file to save the workflow to.
mode (str): one of (rel, abs, wd, inline, pack)
encoding (str): file encoding to use (default: ``utf-8``). | def save(self, fname, mode=None, validate=True, encoding='utf-8',
wd=False, inline=False, relative=False, pack=False):
self._closed()
if mode is None:
mode = 'abs'
if pack:
mode = 'pack'
elif wd:
mode = 'wd'
... | 519,079 |
Parse a line in a TileBus file
Args:
line_no (int): The line number for printing useful error messages
line (string): The line that we are trying to parse | def _parse_line(self, line_no, line):
try:
matched = statement.parseString(line)
except ParseException as exc:
raise DataError("Error parsing line in TileBus file", line_number=line_no, column=exc.col, contents=line)
if 'symbol' in matched:
self._pa... | 519,252 |
Process an input through this sensor graph.
The tick information in value should be correct and is transfered
to all results produced by nodes acting on this tick. This coroutine
is an asyncio compatible version of SensorGraph.process_input()
Args:
stream (DataStream): The stream the input is... | async def process_graph_input(graph, stream, value, rpc_executor):
graph.sensor_log.push(stream, value)
# FIXME: This should be specified in our device model
if stream.important:
associated_output = stream.associated_stream()
graph.sensor_log.push(associated_output, value)
to_che... | 519,281 |
Add a node to the sensor_graph using a binary node descriptor.
Args:
binary_descriptor (bytes): An encoded binary node descriptor.
Returns:
int: A packed error code. | def add_node(self, binary_descriptor):
try:
node_string = parse_binary_descriptor(binary_descriptor)
except:
self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor)
return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM) # F... | 519,296 |
Add a streamer to the sensor_graph using a binary streamer descriptor.
Args:
binary_descriptor (bytes): An encoded binary streamer descriptor.
Returns:
int: A packed error code | def add_streamer(self, binary_descriptor):
streamer = streamer_descriptor.parse_binary_descriptor(binary_descriptor)
try:
self.graph.add_streamer(streamer)
self.streamer_status[len(self.graph.streamers) - 1] = StreamerStatus()
return Error.NO_ERROR
... | 519,297 |
Create a new stimulus from a description string.
The string must have the format:
[time: ][system ]input X = Y
where X and Y are integers. The time, if given must
be a time_interval, which is an integer followed by a
time unit such as second(s), minute(s), etc.
Args:
... | def FromString(cls, desc):
if language.stream is None:
language.get_language()
parse_exp = Optional(time_interval('time') - Literal(':').suppress()) - language.stream('stream') - Literal('=').suppress() - number('value')
try:
data = parse_exp.parseString(desc)
... | 519,321 |
Constructor.
Args:
adapter_id (int): Since the ConnectionManager responds to callbacks on behalf
of a DeviceAdapter, it needs to know what adapter_id to send with the
callbacks. | def __init__(self, adapter_id):
super(ConnectionManager, self).__init__()
self.id = adapter_id
self._stop_event = threading.Event()
self._actions = queue.Queue()
self._connections = {}
self._int_connections = {}
self._data_lock = threading.Lock()
... | 519,323 |
Get the connection id.
Args:
conn_or_int_id (int, string): The external integer connection id or
and internal string connection id
Returns:
dict: The context data associated with that connection or None if it cannot
be found.
Raises:
... | def get_connection_id(self, conn_or_int_id):
key = conn_or_int_id
if isinstance(key, str):
table = self._int_connections
elif isinstance(key, int):
table = self._connections
else:
raise ArgumentError("You must supply either an int connection ... | 519,326 |
Get the data for a connection by either conn_id or internal_id
Args:
conn_or_int_id (int, string): The external integer connection id or
and internal string connection id
Returns:
dict: The context data associated with that connection or None if it cannot
... | def _get_connection(self, conn_or_int_id):
key = conn_or_int_id
if isinstance(key, str):
table = self._int_connections
elif isinstance(key, int):
table = self._connections
else:
return None
try:
data = table[key]
... | 519,327 |
Get a connection's state by either conn_id or internal_id
This routine must only be called from the internal worker thread.
Args:
conn_or_int_id (int, string): The external integer connection id or
and internal string connection id | def _get_connection_state(self, conn_or_int_id):
key = conn_or_int_id
if isinstance(key, str):
table = self._int_connections
elif isinstance(key, int):
table = self._connections
else:
raise ArgumentError("You must supply either an int connect... | 519,328 |
Begin a connection attempt
Args:
action (ConnectionAction): the action object describing what we are
connecting to | def _begin_connection_action(self, action):
conn_id = action.data['connection_id']
int_id = action.data['internal_id']
callback = action.data['callback']
# Make sure we are not reusing an id that is currently connected to something
if self._get_connection_state(conn_id... | 519,330 |
Finish a connection attempt
Args:
action (ConnectionAction): the action object describing what we are
connecting to and what the result of the operation was | def _finish_connection_action(self, action):
success = action.data['success']
conn_key = action.data['id']
if self._get_connection_state(conn_key) != self.Connecting:
print("Invalid finish_connection action on a connection whose state is not Connecting, conn_key=%s" % str(... | 519,331 |
Notify that there was an unexpected disconnection of the device.
Any in progress operations are canceled cleanly and the device is transitioned
to a disconnected state.
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id | def unexpected_disconnect(self, conn_or_internal_id):
data = {
'id': conn_or_internal_id
}
action = ConnectionAction('force_disconnect', data, sync=False)
self._actions.put(action) | 519,332 |
Begin a disconnection attempt
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
callback (callable): Callback to call when this disconnection attempt either
succeeds or fails
timeout (float): How ... | def begin_disconnection(self, conn_or_internal_id, callback, timeout):
data = {
'id': conn_or_internal_id,
'callback': callback
}
action = ConnectionAction('begin_disconnection', data, timeout=timeout, sync=False)
self._actions.put(action) | 519,333 |
Forcibly disconnect a device.
Args:
action (ConnectionAction): the action object describing what we are
forcibly disconnecting | def _force_disconnect_action(self, action):
conn_key = action.data['id']
if self._get_connection_state(conn_key) == self.Disconnected:
return
data = self._get_connection(conn_key)
# If there are any operations in progress, cancel them cleanly
if data['stat... | 519,334 |
Begin a disconnection attempt
Args:
action (ConnectionAction): the action object describing what we are
connecting to and what the result of the operation was | def _begin_disconnection_action(self, action):
conn_key = action.data['id']
callback = action.data['callback']
if self._get_connection_state(conn_key) != self.Idle:
callback(conn_key, self.id, False, 'Cannot start disconnection, connection is not idle')
return
... | 519,335 |
Finish a disconnection attempt
There are two possible outcomes:
- if we were successful at disconnecting, we transition to disconnected
- if we failed at disconnecting, we transition back to idle
Args:
action (ConnectionAction): the action object describing what we are
... | def _finish_disconnection_action(self, action):
success = action.data['success']
conn_key = action.data['id']
if self._get_connection_state(conn_key) != self.Disconnecting:
self._logger.error("Invalid finish_disconnection action on a connection whose state is not Disconnec... | 519,336 |
Finish an operation on a connection.
Args:
conn_or_internal_id (string, int): Either an integer connection id or a string
internal_id
success (bool): Whether the operation was successful
failure_reason (string): Optional reason why the operation failed
... | def finish_operation(self, conn_or_internal_id, success, *args):
data = {
'id': conn_or_internal_id,
'success': success,
'callback_args': args
}
action = ConnectionAction('finish_operation', data, sync=False)
self._actions.put(action) | 519,337 |
Finish an attempted operation.
Args:
action (ConnectionAction): the action object describing the result
of the operation that we are finishing | def _finish_operation_action(self, action):
success = action.data['success']
conn_key = action.data['id']
if self._get_connection_state(conn_key) != self.InProgress:
self._logger.error("Invalid finish_operation action on a connection whose state is not InProgress, conn_key... | 519,338 |
Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reason key set indicating
... | def verify(self, obj):
if isinstance(obj, str):
raise ValidationError("Object was not a list", reason="a string was passed instead of a list", object=obj)
out_obj = []
if self._min_length is not None and len(obj) < self._min_length:
raise ValidationError("List ... | 519,358 |
Asynchronously disconnect from a device that has previously been connected
Args:
conn_id (int): a unique identifier for this connection on the DeviceManager
that owns this adapter.
callback (callable): A function called as callback(conn_id, adapter_id, success, failure_r... | def disconnect_async(self, conn_id, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
self.conns.begin_disconnection(conn_id, callback, s... | 519,431 |
Open an interface on this device
Args:
conn_id (int): the unique identifier for the connection
iface (string): the interface name to open
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reas... | def _open_interface(self, conn_id, iface, callback):
try:
context = self.conns.get_context(conn_id)
except ArgumentError:
callback(conn_id, self.id, False, "Could not find connection information")
return
self.conns.begin_operation(conn_id, 'open_int... | 519,434 |
Probe for visible devices connected to this DeviceAdapter.
Args:
callback (callable): A callback for when the probe operation has completed.
callback should have signature callback(adapter_id, success, failure_reason) where:
success: bool
fail... | def probe_async(self, callback):
topics = MQTTTopicValidator(self.prefix)
self.client.publish(topics.probe, {'type': 'command', 'operation': 'probe', 'client': self.name})
callback(self.id, True, None) | 519,436 |
Subscribe to all the topics we need to communication with this device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we are connecting to. | def _bind_topics(self, topics):
# FIXME: Allow for these subscriptions to fail and clean up the previous ones
# so that this function is atomic
self.client.subscribe(topics.status, self._on_status_message)
self.client.subscribe(topics.tracing, self._on_trace)
self.clie... | 519,438 |
Unsubscribe to all of the topics we needed for communication with device
Args:
topics (MQTTTopicValidator): The topic validator for this device that
we have connected to. | def _unbind_topics(self, topics):
self.client.unsubscribe(topics.status)
self.client.unsubscribe(topics.tracing)
self.client.unsubscribe(topics.streaming)
self.client.unsubscribe(topics.response) | 519,439 |
Attempt to find a connection id corresponding with a topic
The device is found by assuming the topic ends in <slug>/[control|data]/channel
Args:
topic (string): The topic we received a message on
Returns:
int: The internal connect id (device slug) associated with this ... | def _find_connection(self, topic):
parts = topic.split('/')
if len(parts) < 3:
return None
slug = parts[-3]
return slug | 519,440 |
Process a report received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself | def _on_report(self, sequence, topic, message):
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping report message that does not correspond with a known connection, t... | 519,442 |
Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself | def _on_trace(self, sequence, topic, message):
try:
conn_key = self._find_connection(topic)
conn_id = self.conns.get_connection_id(conn_key)
except ArgumentError:
self._logger.warn("Dropping trace message that does not correspond with a known connection, top... | 519,443 |
Process a status message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself | def _on_status_message(self, sequence, topic, message):
self._logger.debug("Received message on (topic=%s): %s" % (topic, message))
try:
conn_key = self._find_connection(topic)
except ArgumentError:
self._logger.warn("Dropping message that does not correspond w... | 519,444 |
Process a response message received
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself | def _on_response_message(self, sequence, topic, message):
try:
conn_key = self._find_connection(topic)
context = self.conns.get_context(conn_key)
except ArgumentError:
self._logger.warn("Dropping message that does not correspond with a known connection, mess... | 519,445 |
Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reason key set indicating
... | def verify(self, obj):
if len(self._options) == 0:
raise ValidationError("No options", reason='no options given in options verifier, matching not possible',
object=obj)
exceptions = {}
for i, option in enumerate(self._options):
... | 519,452 |
Add all recipes inside a folder to this RecipeManager with an optional whitelist.
Args:
recipe_folder (str): The path to the folder of recipes to add.
whitelist (list): Only include files whose os.basename() matches something
on the whitelist | def add_recipe_folder(self, recipe_folder, whitelist=None):
if whitelist is not None:
whitelist = set(whitelist)
if recipe_folder == '':
recipe_folder = '.'
for yaml_file in [x for x in os.listdir(recipe_folder) if x.endswith('.yaml')]:
if whitelis... | 519,455 |
Add additional valid recipe actions to RecipeManager
args:
recipe_actions (list): List of tuples. First value of tuple is the classname,
second value of tuple is RecipeAction Object | def add_recipe_actions(self, recipe_actions):
for action_name, action in recipe_actions:
self._recipe_actions[action_name] = action | 519,456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.