INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Calculate the material physical property at the specified temperature in the units specified by the object s property_units property. | def calculate(self, **state):
"""
Calculate the material physical property at the specified temperature
in the units specified by the object's 'property_units' property.
:param T: [K] temperature
:returns: physical property value
"""
super().calculate(**state)
... |
Prepare the activity for execution. | def prepare_to_run(self, clock, period_count):
"""
Prepare the activity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be... |
Create a sub component in the business component. | def create_component(self, name, description=None):
"""
Create a sub component in the business component.
:param name: The new component's name.
:param description: The new component's description.
:returns: The created component.
"""
new_comp = Component(name,... |
Remove a sub component from the component. | def remove_component(self, name):
"""
Remove a sub component from the component.
:param name: The name of the component to remove.
"""
component_to_remove = None
for c in self.components:
if c.name == name:
component_to_remove = c
if ... |
Retrieve a child component given its name. | def get_component(self, name):
"""
Retrieve a child component given its name.
:param name: The name of the component.
:returns: The component.
"""
return [c for c in self.components if c.name == name][0] |
Add an activity to the component. | def add_activity(self, activity):
"""
Add an activity to the component.
:param activity: The activity.
"""
self.gl.structure.validate_account_names(
activity.get_referenced_accounts())
self.activities.append(activity)
activity.set_parent_path(self.pa... |
Retrieve an activity given its name. | def get_activity(self, name):
"""
Retrieve an activity given its name.
:param name: The name of the activity.
:returns: The activity.
"""
return [a for a in self.activities if a.name == name][0] |
Prepare the component for execution. | def prepare_to_run(self, clock, period_count):
"""
Prepare the component for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to b... |
Execute the component at the current clock cycle. | def run(self, clock, generalLedger):
"""
Execute the component at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
""... |
Prepare the entity for execution. | def prepare_to_run(self, clock, period_count):
"""
Prepare the entity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be r... |
Execute the entity at the current clock cycle. | def run(self, clock):
"""
Execute the entity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
"""
if clock.timestep_ix >= self.period_count:
return
for c in self.components:
... |
Update group counts with multiplier | def count_with_multiplier(groups, multiplier):
""" Update group counts with multiplier
This is for handling atom counts on groups like (OH)2
:param groups: iterable of Group/Element
:param multiplier: the number to multiply by
"""
counts = collections.defaultdict(float)
for group in group... |
Calculate the amounts from the specified compound masses. | def amounts(masses):
"""
Calculate the amounts from the specified compound masses.
:param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [kmol] dictionary
"""
return {compound: amount(compound, masses[compound])
for compound in masses.keys()} |
Calculate the mole fractions from the specified compound masses. | def amount_fractions(masses):
"""
Calculate the mole fractions from the specified compound masses.
:param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [mole fractions] dictionary
"""
n = amounts(masses)
n_total = sum(n.values())
return {compound: n[compound]/n_tot... |
Calculate the masses from the specified compound amounts. | def masses(amounts):
"""
Calculate the masses from the specified compound amounts.
:param masses: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [kg] dictionary
"""
return {compound: mass(compound, amounts[compound])
for compound in amounts.keys()} |
Calculate the mole fractions from the specified compound amounts. | def mass_fractions(amounts):
"""
Calculate the mole fractions from the specified compound amounts.
:param amounts: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5}
:returns: [mass fractions] dictionary
"""
m = masses(amounts)
m_total = sum(m.values())
return {compound: m[compound]/m_... |
Convert the specified mass of the source compound to the target using element as basis. | def convert_compound(mass, source, target, element):
"""
Convert the specified mass of the source compound to the target using
element as basis.
:param mass: Mass of from_compound. [kg]
:param source: Formula and phase of the original compound, e.g.
'Fe2O3[S1]'.
:param target: Formula and... |
Determine the mass fraction of an element in a chemical compound. | def element_mass_fraction(compound, element):
"""
Determine the mass fraction of an element in a chemical compound.
:param compound: Formula of the chemical compound, 'FeCr2O4'.
:param element: Element, e.g. 'Cr'.
:returns: Element mass fraction.
"""
coeff = stoichiometry_coefficient(comp... |
Determine the set of elements present in a list of chemical compounds. | def elements(compounds):
"""
Determine the set of elements present in a list of chemical compounds.
The list of elements is sorted alphabetically.
:param compounds: List of compound formulas and phases, e.g.
['Fe2O3[S1]', 'Al2O3[S1]'].
:returns: List of elements.
"""
elementlist = ... |
Determine the molar mass of a chemical compound. | def molar_mass(compound=''):
"""Determine the molar mass of a chemical compound.
The molar mass is usually the mass of one mole of the substance, but here
it is the mass of 1000 moles, since the mass unit used in auxi is kg.
:param compound: Formula of a chemical compound, e.g. 'Fe2O3'.
:returns:... |
Determine the stoichiometry coefficient of an element in a chemical compound. | def stoichiometry_coefficient(compound, element):
"""
Determine the stoichiometry coefficient of an element in a chemical
compound.
:param compound: Formula of a chemical compound, e.g. 'SiO2'.
:param element: Element, e.g. 'Si'.
:returns: Stoichiometry coefficient.
"""
stoichiometry... |
Determine the stoichiometry coefficients of the specified elements in the specified chemical compound. | def stoichiometry_coefficients(compound, elements):
"""
Determine the stoichiometry coefficients of the specified elements in
the specified chemical compound.
:param compound: Formula of a chemical compound, e.g. 'SiO2'.
:param elements: List of elements, e.g. ['Si', 'O', 'C'].
:returns: List ... |
Add an assay to the material. | def add_assay(self, name, assay):
"""
Add an assay to the material.
:param name: The name of the new assay.
:param assay: A numpy array containing the size class mass fractions
for the assay. The sequence of the assay's elements must correspond
to the sequence of the... |
Create a MaterialPackage based on the specified parameters. | def create_package(self, assay=None, mass=0.0, normalise=True):
"""
Create a MaterialPackage based on the specified parameters.
:param assay: The name of the assay based on which the package must be
created.
:param mass: [kg] The mass of the package.
:param normalise: ... |
Extract other from self modifying self and returning the extracted material as a new package. | def extract(self, other):
"""
Extract 'other' from self, modifying self and returning the extracted
material as a new package.
:param other: Can be one of the following:
* float: A mass equal to other is extracted from self. Self is
reduced by other and the extrac... |
Add another psd material package to this material package. | def add_to(self, other):
"""
Add another psd material package to this material package.
:param other: The other material package.
"""
# Add another package.
if type(other) is MaterialPackage:
# Packages of the same material.
if self.material == o... |
Execute the activity at the current clock cycle. | def run(self, clock, generalLedger):
"""
Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
"""... |
Prepare the activity for execution. | def prepare_to_run(self, clock, period_count):
"""
Prepare the activity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be... |
Execute the activity at the current clock cycle. | def run(self, clock, generalLedger):
"""
Execute the activity at the current clock cycle.
:param clock: The clock containing the current execution time and
period information.
:param generalLedger: The general ledger into which to create the
transactions.
"""... |
Get the datetime at a given period. | def get_datetime_at_period_ix(self, ix):
"""
Get the datetime at a given period.
:param period: The index of the period.
:returns: The datetime.
"""
if self.timestep_period_duration == TimePeriod.millisecond:
return self.start_datetime + timedelta(milliseco... |
Calculate the default path in which thermochemical data is stored. | def _get_default_data_path_():
"""
Calculate the default path in which thermochemical data is stored.
:returns: Default path.
"""
module_path = os.path.dirname(sys.modules[__name__].__file__)
data_path = os.path.join(module_path, r'data/rao')
data_path = os.path.abspath(data_path)
retu... |
Build a dictionary containing the factsage thermochemical data of a compound by reading the data from a file. | def _read_compound_from_factsage_file_(file_name):
"""
Build a dictionary containing the factsage thermochemical data of a
compound by reading the data from a file.
:param file_name: Name of file to read the data from.
:returns: Dictionary containing compound data.
"""
with open(file_name... |
Split a compound s combined formula and phase into separate strings for the formula and phase. | def _split_compound_string_(compound_string):
"""
Split a compound's combined formula and phase into separate strings for
the formula and phase.
:param compound_string: Formula and phase of a chemical compound, e.g.
'SiO2[S1]'.
:returns: Formula of chemical compound.
:returns: Phase of c... |
Convert the value to its final form by unit conversions and multiplying by mass. | def _finalise_result_(compound, value, mass):
"""
Convert the value to its final form by unit conversions and multiplying
by mass.
:param compound: Compound object.
:param value: [J/mol] Value to be finalised.
:param mass: [kg] Mass of compound.
:returns: [kWh] Finalised value.
"""
... |
Writes a compound to an auxi file at the specified directory. | def write_compound_to_auxi_file(directory, compound):
"""
Writes a compound to an auxi file at the specified directory.
:param dir: The directory.
:param compound: The compound.
"""
file_name = "Compound_" + compound.formula + ".json"
with open(os.path.join(directory, file_name), 'w') as f... |
Load all the thermochemical data factsage files located at a path. | def load_data_factsage(path=''):
"""
Load all the thermochemical data factsage files located at a path.
:param path: Path at which the data files are located.
"""
compounds.clear()
if path == '':
path = default_data_path
if not os.path.exists(path):
warnings.warn('The spec... |
Load all the thermochemical data auxi files located at a path. | def load_data_auxi(path=''):
"""
Load all the thermochemical data auxi files located at a path.
:param path: Path at which the data files are located.
"""
compounds.clear()
if path == '':
path = default_data_path
if not os.path.exists(path):
warnings.warn('The specified da... |
List all compounds that are currently loaded in the thermo module and their phases. | def list_compounds():
"""
List all compounds that are currently loaded in the thermo module, and
their phases.
"""
print('Compounds currently loaded:')
for compound in sorted(compounds.keys()):
phases = compounds[compound].get_phase_list()
print('%s: %s' % (compound, ', '.join(p... |
Calculate the heat capacity of the compound for the specified temperature and mass. | def Cp(compound_string, T, mass=1.0):
"""
Calculate the heat capacity of the compound for the specified temperature
and mass.
:param compound_string: Formula and phase of chemical compound, e.g.
'Fe2O3[S1]'.
:param T: [°C] temperature
:param mass: [kg]
:returns: [kWh/K] Heat capacity... |
Calculate the heat capacity of the compound phase. | def Cp(self, T):
"""
Calculate the heat capacity of the compound phase.
:param T: [K] temperature
:returns: [J/mol/K] Heat capacity.
"""
result = 0.0
for c, e in zip(self._coefficients, self._exponents):
result += c*T**e
return result |
Calculate the portion of enthalpy of the compound phase covered by this Cp record. | def H(self, T):
"""
Calculate the portion of enthalpy of the compound phase covered by this
Cp record.
:param T: [K] temperature
:returns: [J/mol] Enthalpy.
"""
result = 0.0
if T < self.Tmax:
lT = T
else:
lT = self.Tmax
... |
Calculate the portion of entropy of the compound phase covered by this Cp record. | def S(self, T):
"""
Calculate the portion of entropy of the compound phase covered by this
Cp record.
:param T: [K] temperature
:returns: Entropy. [J/mol/K]
"""
result = 0.0
if T < self.Tmax:
lT = T
else:
lT = self.Tmax
... |
Calculate the heat capacity of the compound phase at the specified temperature. | def Cp(self, T):
"""
Calculate the heat capacity of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol/K] The heat capacity of the compound phase.
"""
# TODO: Fix str/float conversion
for Tmax in sorted([float(TT... |
Calculate the phase s magnetic contribution to heat capacity at the specified temperature. | def Cp_mag(self, T):
"""
Calculate the phase's magnetic contribution to heat capacity at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic heat capacity of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calp... |
Calculate the enthalpy of the compound phase at the specified temperature. | def H(self, T):
"""
Calculate the enthalpy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The enthalpy of the compound phase.
"""
result = self.DHref
for Tmax in sorted([float(TT) for TT in self._Cp_reco... |
Calculate the phase s magnetic contribution to enthalpy at the specified temperature. | def H_mag(self, T):
"""
Calculate the phase's magnetic contribution to enthalpy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic enthalpy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
... |
Calculate the entropy of the compound phase at the specified temperature. | def S(self, T):
"""
Calculate the entropy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol/K] The entropy of the compound phase.
"""
result = self.Sref
for Tmax in sorted([float(TT) for TT in self._Cp_recor... |
Calculate the phase s magnetic contribution to entropy at the specified temperature. | def S_mag(self, T):
"""
Calculate the phase's magnetic contribution to entropy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic entropy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
... |
Calculate the heat capacity of the compound phase at the specified temperature. | def G(self, T):
"""Calculate the heat capacity of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The Gibbs free energy of the compound phase.
"""
h = self.DHref
s = self.Sref
for Tmax in sorted([float(TT) f... |
Calculate the phase s magnetic contribution to Gibbs energy at the specified temperature. | def G_mag(self, T):
"""
Calculate the phase's magnetic contribution to Gibbs energy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic Gibbs energy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, ... |
Calculate the heat capacity of a phase of the compound at a specified temperature. | def Cp(self, phase, T):
"""
Calculate the heat capacity of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol/K] Heat capacity.
"""
if phase not in se... |
Calculate the enthalpy of a phase of the compound at a specified temperature. | def H(self, phase, T):
"""
Calculate the enthalpy of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol] Enthalpy.
"""
try:
return self._p... |
Create a polynomial model to describe the specified property based on the specified data set and save it to a. json file. | def _create_polynomial_model(
name: str,
symbol: str,
degree: int,
ds: DataSet,
dss: dict):
"""
Create a polynomial model to describe the specified property based on the
specified data set, and save it to a .json file.
:param name: material name.
:param symbol: property symbol.
... |
Create a dictionary of datasets and a material object for air. | def _create_air():
"""
Create a dictionary of datasets and a material object for air.
:return: (Material, {str, DataSet})
"""
name = "Air"
namel = name.lower()
mm = 28.9645 # g/mol
ds_dict = _create_ds_dict([
"dataset-air-lienhard2015",
"dataset-air-lienhard2018"])
... |
Calculate dynamic viscosity at the specified temperature and composition: | def calculate(self, **state):
"""
Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g.
{'CO': 0.25, 'CO2': 0.25, 'N2': 0.25, 'O2': 0.25}
:returns: [Pa.s] dyn... |
Calculate dynamic viscosity at the specified temperature and composition: | def calculate(self, **state):
"""
Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param x: [mole fraction] composition dictionary , e.g.
{'CO': 0.25, 'CO2': 0.25, 'N2': 0.25, 'O2': 0.25}
:returns: [Pa.s] dyn... |
Render the report in the specified format | def render(self, format=ReportFormat.printout):
"""
Render the report in the specified format
:param format: The format. The default format is to print
the report to the console.
:returns: If the format was set to 'string' then a string
representation of the report ... |
Convert an RGB color representation to a HEX color representation. | def rgb_to_hex(rgb):
"""
Convert an RGB color representation to a HEX color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HEX representat... |
Convert an RGB color representation to a YIQ color representation. | def rgb_to_yiq(rgb):
"""
Convert an RGB color representation to a YIQ color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: YIQ representat... |
Convert an RGB color representation to an HSV color representation. | def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HSV representa... |
Convert a HEX color representation to an RGB color representation. | def hex_to_rgb(_hex):
"""
Convert a HEX color representation to an RGB color representation.
hex :: hex -> [000000, FFFFFF]
:param _hex: The 3- or 6-char hexadecimal string representing the color value.
:return: RGB representation of the input HEX value.
:rtype: tuple
"""
_hex = _hex.s... |
Convert a YIQ color representation to an RGB color representation. | def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and chrominance.
:return: RGB r... |
Convert an HSV color representation to an RGB color representation. | def hsv_to_rgb(hsv):
"""
Convert an HSV color representation to an RGB color representation.
(h, s, v) :: h -> [0, 360)
s -> [0, 1]
v -> [0, 1]
:param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.
:return: RGB representation... |
Given a seed color generate a specified number of random colors ( 1 color by default ) determined by a randomized offset from the seed. | def offset_random_rgb(seed, amount=1):
"""
Given a seed color, generate a specified number of random colors (1 color by default) determined by a randomized
offset from the seed.
:param seed:
:param amount:
:return:
"""
r, g, b = seed
results = []
for _ in range(amount):
... |
Given a start color end color and a number of steps returns a list of colors which represent a scale between the start and end color. | def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):
"""
Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between
the start and end color.
:param start_color: The color starting the run
:param end_color: The color... |
Given a background color in the form of an RGB 3 - tuple returns the color the text should be ( defaulting to white and black ) for best readability. The light ( white ) and dark ( black ) defaults can be overridden to return preferred values. | def text_color(background, dark_color=rgb_min, light_color=rgb_max):
"""
Given a background color in the form of an RGB 3-tuple, returns the color the text should be (defaulting to white
and black) for best readability. The light (white) and dark (black) defaults can be overridden to return preferred
va... |
Given a HEX value tries to reduce it from a 6 character hex ( e. g. #ffffff ) to a 3 character hex ( e. g. #fff ). If the HEX value is unable to be minified returns the 6 character HEX representation. | def minify_hex(_hex):
"""
Given a HEX value, tries to reduce it from a 6 character hex (e.g. #ffffff) to a 3 character hex (e.g. #fff).
If the HEX value is unable to be minified, returns the 6 character HEX representation.
:param _hex:
:return:
"""
size = len(_hex.strip('#'))
if size ==... |
Get key value return default if key doesn t exist | def get(self, key, default=None):
""" Get key value, return default if key doesn't exist """
if self.in_memory:
return self._memory_db.get(key, default)
else:
db = self._read_file()
return db.get(key, default) |
Set key value | def set(self, key, value):
""" Set key value """
if self.in_memory:
self._memory_db[key] = value
else:
db = self._read_file()
db[key] = value
with open(self.db_path, 'w') as f:
f.write(json.dumps(db, ensure_ascii=False, indent=2)) |
read the db file content: rtype: dict | def _read_file(self):
"""
read the db file content
:rtype: dict
"""
if not os.path.exists(self.db_path):
return {}
with open(self.db_path, 'r') as f:
content = f.read()
return json.loads(content) |
A class decorator that adds __repr__ __eq__ __cmp__ and __hash__ methods according to the fields defined on the SQLAlchemy model class. | def attrs_sqlalchemy(maybe_cls=None):
"""
A class decorator that adds ``__repr__``, ``__eq__``, ``__cmp__``, and
``__hash__`` methods according to the fields defined on the SQLAlchemy
model class.
"""
def wrap(cls):
warnings.warn(UserWarning('attrs_sqlalchemy is deprecated'))
th... |
Create an A - HREF tag that points to another page usable in paginate. | def paginate_link_tag(item):
"""
Create an A-HREF tag that points to another page usable in paginate.
"""
a_tag = Page.default_link_tag(item)
if item['type'] == 'current_page':
return make_html_tag('li', a_tag, **{'class': 'blue white-text'})
return make_html_tag('li', a_tag) |
Set a devices state. | def set_state(_id, body):
"""
Set a devices state.
"""
url = DEVICE_URL % _id
if "mode" in body:
url = MODES_URL % _id
arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code !... |
Pull a water heater s modes from the API. | def get_modes(_id):
"""
Pull a water heater's modes from the API.
"""
url = MODES_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
retur... |
Pull a water heater s usage report from the API. | def get_usage(_id):
"""
Pull a water heater's usage report from the API.
"""
url = USAGE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
... |
Pull a device from the API. | def get_device(_id):
"""
Pull a device from the API.
"""
url = DEVICE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
... |
Pull the accounts locations. | def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.... |
Pull the accounts vacations. | def get_vacations():
"""
Pull the accounts vacations.
"""
arequest = requests.get(VACATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.... |
Create a vacation. | def create_vacation(body):
"""
Create a vacation.
"""
arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '200':
_LOGGER.error("Failed to create vacation. " + status_code)
... |
Delete a vacation by ID. | def delete_vacation(_id):
"""
Delete a vacation by ID.
"""
arequest = requests.delete(VACATIONS_URL + "/" + _id, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code != '202':
_LOGGER.error("Failed to delete vacation. " + status_code)
... |
Authenticate with the API and return an authentication token. | def _authenticate(self):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/auth/token"
payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}
arequest = requests.post(auth_url, data=payload, head... |
Return a list of water heater devices. | def get_water_heaters(self):
"""
Return a list of water heater devices.
Parses the response from the locations endpoint in to a pyeconet.WaterHeater.
"""
water_heaters = []
for location in self.locations:
_location_id = location.get("id")
for devi... |
Get a list of all Uber products based on latitude and longitude coordinates.: param latitude: Latitude for which product list is required.: param longitude: Longitude for which product list is required.: return: JSON | def get_products(self, latitude, longitude):
"""
Get a list of all Uber products based on latitude and longitude coordinates.
:param latitude: Latitude for which product list is required.
:param longitude: Longitude for which product list is required.
:return: JSON
"""
... |
Returns the fare estimate based on two sets of coordinates.: param start_latitude: Starting latitude or latitude of pickup address.: param start_longitude: Starting longitude or longitude of pickup address.: param end_latitude: Ending latitude or latitude of destination address.: param end_longitude: Ending longitude o... | def get_price_estimate(self, start_latitude, start_longitude, end_latitude, end_longitude):
"""
Returns the fare estimate based on two sets of coordinates.
:param start_latitude: Starting latitude or latitude of pickup address.
:param start_longitude: Starting longitude or longitude of p... |
Get the ETA for Uber products.: param start_latitude: Starting latitude.: param start_longitude: Starting longitude.: param customer_uuid: ( Optional ) Customer unique ID.: param product_id: ( Optional ) If ETA is needed only for a specific product type.: return: JSON | def get_time_estimate(self, start_latitude, start_longitude, customer_uuid=None, product_id=None):
"""
Get the ETA for Uber products.
:param start_latitude: Starting latitude.
:param start_longitude: Starting longitude.
:param customer_uuid: (Optional) Customer unique ID.
... |
Wrap all sqlalchemy model in settings. | def models_preparing(app):
""" Wrap all sqlalchemy model in settings.
"""
def wrapper(resource, parent):
if isinstance(resource, DeclarativeMeta):
resource = ListResource(resource)
if not getattr(resource, '__parent__', None):
resource.__parent__ = parent
ret... |
Check the response that is returned for known exceptions and errors.: param response: Response that is returned from the call.: raise: MalformedRequestException if response. status is 400 UnauthorisedException if response. status is 401 NotFoundException if response. status is 404 UnacceptableContentException if respon... | def check_status(content, response):
"""
Check the response that is returned for known exceptions and errors.
:param response: Response that is returned from the call.
:raise:
MalformedRequestException if `response.status` is 400
UnauthorisedException if `response.statu... |
Build the HTTP request by adding query parameters to the path.: param path: API endpoint/ path to be used.: param query_parameters: Query parameters to be added to the request.: return: string | def build_request(self, path, query_parameters):
"""
Build the HTTP request by adding query parameters to the path.
:param path: API endpoint/path to be used.
:param query_parameters: Query parameters to be added to the request.
:return: string
"""
url = 'https://... |
Fetches the JSON returned after making the call and checking for errors.: param uri_path: Endpoint to be used to make a request.: param http_method: HTTP method to be used.: param query_parameters: Parameters to be added to the request.: param body: Optional body if required.: param headers: Optional headers if require... | def get_json(self, uri_path, http_method='GET', query_parameters=None, body=None, headers=None):
"""
Fetches the JSON returned, after making the call and checking for errors.
:param uri_path: Endpoint to be used to make a request.
:param http_method: HTTP method to be used.
:para... |
Generate the binary strings for a comma seperated list of commands. | def _translateCommands(commands):
"""Generate the binary strings for a comma seperated list of commands."""
for command in commands.split(','):
# each command results in 2 bytes of binary data
result = [0, 0]
device, command = command.strip().upper().split(None, 1)
# translate t... |
Conert an integer to binary ( i. e. a string of 1s and 0s ). | def _strBinary(n):
"""Conert an integer to binary (i.e., a string of 1s and 0s)."""
results = []
for i in range(8):
n, r = divmod(n, 2)
results.append('01'[r])
results.reverse()
return ''.join(results) |
Send a string of binary data to the FireCracker with proper timing. | def _sendBinaryData(port, data):
"""Send a string of binary data to the FireCracker with proper timing.
See the diagram in the spec referenced above for timing information.
The module level variables leadInOutDelay and bitDelay represent how
long each type of delay should be in seconds. They may requir... |
Send an individual bit to the FireCracker module usr RTS/ DTR. | def _sendBit(port, bit):
"""Send an individual bit to the FireCracker module usr RTS/DTR."""
if bit == '0':
_setRTSDTR(port, 0, 1)
elif bit == '1':
_setRTSDTR(port, 1, 0)
else:
return
time.sleep(bitDelay)
_setRTSDTR(port, 1, 1)
time.sleep(bitDelay) |
Set RTS and DTR to the requested state. | def _setRTSDTR(port, RTS, DTR):
"""Set RTS and DTR to the requested state."""
port.setRTS(RTS)
port.setDTR(DTR) |
Send X10 commands using the FireCracker on comPort | def sendCommands(comPort, commands):
"""Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Di... |
Send X10 commands when module is used from the command line. | def main(argv=None):
"""Send X10 commands when module is used from the command line.
This uses syntax similar to sendCommands, for example:
x10.py com2 A1 On, A2 Off, B All Off
"""
if len(argv):
# join all the arguments together by spaces so that quotes
# aren't required on the com... |
Returns a normalized house code i. e. upper case. Raises exception X10InvalidHouseCode if house code appears to be invalid | def normalize_housecode(house_code):
"""Returns a normalized house code, i.e. upper case.
Raises exception X10InvalidHouseCode if house code appears to be invalid
"""
if house_code is None:
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if not isinstance(house_code, b... |
Returns a normalized unit number i. e. integers Raises exception X10InvalidUnitNumber if unit number appears to be invalid | def normalize_unitnumber(unit_number):
"""Returns a normalized unit number, i.e. integers
Raises exception X10InvalidUnitNumber if unit number appears to be invalid
"""
try:
try:
unit_number = int(unit_number)
except ValueError:
raise X10InvalidUnitNumber('%r not ... |
Send X10 command to ??? unit. | def x10_command(self, house_code, unit_number, state):
"""Send X10 command to ??? unit.
@param house_code (A-P) - example='A'
@param unit_number (1-16)- example=1 (or None to impact entire house code)
@param state - Mochad command/state, See
https://sourceforge.net/p/moc... |
Real implementation | def _x10_command(self, house_code, unit_number, state):
"""Real implementation"""
print('x10_command%r' % ((house_code, unit_number, state), ))
raise NotImplementedError() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.