partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
PolynomialModelT.calculate
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
auxi/tools/materialphysicalproperties/polynomial.py
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) return np.polyval(self._coeffs, state['T'])
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) return np.polyval(self._coeffs, state['T'])
[ "Calculate", "the", "material", "physical", "property", "at", "the", "specified", "temperature", "in", "the", "units", "specified", "by", "the", "object", "s", "property_units", "property", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/polynomial.py#L79-L89
[ "def", "calculate", "(", "self", ",", "*", "*", "state", ")", ":", "super", "(", ")", ".", "calculate", "(", "*", "*", "state", ")", "return", "np", ".", "polyval", "(", "self", ".", "_coeffs", ",", "state", "[", "'T'", "]", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Activity.prepare_to_run
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 run for.
auxi/modelling/business/structure.py
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 run for. """ if self.start_period_ix == -1 and self.start_datetime != datetime.min: # Set the Start period index for i in range(0, period_count): if clock.get_datetime_at_period_ix(i) > self.start_datetime: self.start_period_ix = i break if self.start_period_ix == -1: self.start_period_ix = 0 if self.period_count == -1 and self.end_datetime != datetime.max: # Set the Start date for i in range(0, period_count): if clock.get_datetime_at_period_ix(i) > self.end_datetime: self.period_count = i - self.start_period_ix break if self.period_count != -1: self.end_period_ix = self.start_period_ix + self.period_count else: self.end_period_ix = self.start_period_ix + period_count
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 run for. """ if self.start_period_ix == -1 and self.start_datetime != datetime.min: # Set the Start period index for i in range(0, period_count): if clock.get_datetime_at_period_ix(i) > self.start_datetime: self.start_period_ix = i break if self.start_period_ix == -1: self.start_period_ix = 0 if self.period_count == -1 and self.end_datetime != datetime.max: # Set the Start date for i in range(0, period_count): if clock.get_datetime_at_period_ix(i) > self.end_datetime: self.period_count = i - self.start_period_ix break if self.period_count != -1: self.end_period_ix = self.start_period_ix + self.period_count else: self.end_period_ix = self.start_period_ix + period_count
[ "Prepare", "the", "activity", "for", "execution", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L81-L108
[ "def", "prepare_to_run", "(", "self", ",", "clock", ",", "period_count", ")", ":", "if", "self", ".", "start_period_ix", "==", "-", "1", "and", "self", ".", "start_datetime", "!=", "datetime", ".", "min", ":", "# Set the Start period index", "for", "i", "in", "range", "(", "0", ",", "period_count", ")", ":", "if", "clock", ".", "get_datetime_at_period_ix", "(", "i", ")", ">", "self", ".", "start_datetime", ":", "self", ".", "start_period_ix", "=", "i", "break", "if", "self", ".", "start_period_ix", "==", "-", "1", ":", "self", ".", "start_period_ix", "=", "0", "if", "self", ".", "period_count", "==", "-", "1", "and", "self", ".", "end_datetime", "!=", "datetime", ".", "max", ":", "# Set the Start date", "for", "i", "in", "range", "(", "0", ",", "period_count", ")", ":", "if", "clock", ".", "get_datetime_at_period_ix", "(", "i", ")", ">", "self", ".", "end_datetime", ":", "self", ".", "period_count", "=", "i", "-", "self", ".", "start_period_ix", "break", "if", "self", ".", "period_count", "!=", "-", "1", ":", "self", ".", "end_period_ix", "=", "self", ".", "start_period_ix", "+", "self", ".", "period_count", "else", ":", "self", ".", "end_period_ix", "=", "self", ".", "start_period_ix", "+", "period_count" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.create_component
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.
auxi/modelling/business/structure.py
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, self.gl, description=description) new_comp.set_parent_path(self.path) self.components.append(new_comp) return new_comp
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, self.gl, description=description) new_comp.set_parent_path(self.path) self.components.append(new_comp) return new_comp
[ "Create", "a", "sub", "component", "in", "the", "business", "component", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L170-L183
[ "def", "create_component", "(", "self", ",", "name", ",", "description", "=", "None", ")", ":", "new_comp", "=", "Component", "(", "name", ",", "self", ".", "gl", ",", "description", "=", "description", ")", "new_comp", ".", "set_parent_path", "(", "self", ".", "path", ")", "self", ".", "components", ".", "append", "(", "new_comp", ")", "return", "new_comp" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.remove_component
Remove a sub component from the component. :param name: The name of the component to remove.
auxi/modelling/business/structure.py
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 component_to_remove is not None: self.components.remove(component_to_remove)
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 component_to_remove is not None: self.components.remove(component_to_remove)
[ "Remove", "a", "sub", "component", "from", "the", "component", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L185-L197
[ "def", "remove_component", "(", "self", ",", "name", ")", ":", "component_to_remove", "=", "None", "for", "c", "in", "self", ".", "components", ":", "if", "c", ".", "name", "==", "name", ":", "component_to_remove", "=", "c", "if", "component_to_remove", "is", "not", "None", ":", "self", ".", "components", ".", "remove", "(", "component_to_remove", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.get_component
Retrieve a child component given its name. :param name: The name of the component. :returns: The component.
auxi/modelling/business/structure.py
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]
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]
[ "Retrieve", "a", "child", "component", "given", "its", "name", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L199-L208
[ "def", "get_component", "(", "self", ",", "name", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "components", "if", "c", ".", "name", "==", "name", "]", "[", "0", "]" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.add_activity
Add an activity to the component. :param activity: The activity.
auxi/modelling/business/structure.py
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.path)
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.path)
[ "Add", "an", "activity", "to", "the", "component", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L210-L220
[ "def", "add_activity", "(", "self", ",", "activity", ")", ":", "self", ".", "gl", ".", "structure", ".", "validate_account_names", "(", "activity", ".", "get_referenced_accounts", "(", ")", ")", "self", ".", "activities", ".", "append", "(", "activity", ")", "activity", ".", "set_parent_path", "(", "self", ".", "path", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.get_activity
Retrieve an activity given its name. :param name: The name of the activity. :returns: The activity.
auxi/modelling/business/structure.py
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]
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]
[ "Retrieve", "an", "activity", "given", "its", "name", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L222-L231
[ "def", "get_activity", "(", "self", ",", "name", ")", ":", "return", "[", "a", "for", "a", "in", "self", ".", "activities", "if", "a", ".", "name", "==", "name", "]", "[", "0", "]" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.prepare_to_run
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 be run for.
auxi/modelling/business/structure.py
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 be run for. """ for c in self.components: c.prepare_to_run(clock, period_count) for a in self.activities: a.prepare_to_run(clock, period_count)
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 be run for. """ for c in self.components: c.prepare_to_run(clock, period_count) for a in self.activities: a.prepare_to_run(clock, period_count)
[ "Prepare", "the", "component", "for", "execution", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L233-L246
[ "def", "prepare_to_run", "(", "self", ",", "clock", ",", "period_count", ")", ":", "for", "c", "in", "self", ".", "components", ":", "c", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")", "for", "a", "in", "self", ".", "activities", ":", "a", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Component.run
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.
auxi/modelling/business/structure.py
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. """ for c in self.components: c.run(clock, generalLedger) for a in self.activities: a.run(clock, generalLedger)
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. """ for c in self.components: c.run(clock, generalLedger) for a in self.activities: a.run(clock, generalLedger)
[ "Execute", "the", "component", "at", "the", "current", "clock", "cycle", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L248-L261
[ "def", "run", "(", "self", ",", "clock", ",", "generalLedger", ")", ":", "for", "c", "in", "self", ".", "components", ":", "c", ".", "run", "(", "clock", ",", "generalLedger", ")", "for", "a", "in", "self", ".", "activities", ":", "a", ".", "run", "(", "clock", ",", "generalLedger", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Entity.prepare_to_run
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 run for.
auxi/modelling/business/structure.py
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 run for. """ self.period_count = period_count self._exec_year_end_datetime = clock.get_datetime_at_period_ix( period_count) self._prev_year_end_datetime = clock.start_datetime self._curr_year_end_datetime = clock.start_datetime + relativedelta( years=1) # Remove all the transactions del self.gl.transactions[:] for c in self.components: c.prepare_to_run(clock, period_count) self.negative_income_tax_total = 0
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 run for. """ self.period_count = period_count self._exec_year_end_datetime = clock.get_datetime_at_period_ix( period_count) self._prev_year_end_datetime = clock.start_datetime self._curr_year_end_datetime = clock.start_datetime + relativedelta( years=1) # Remove all the transactions del self.gl.transactions[:] for c in self.components: c.prepare_to_run(clock, period_count) self.negative_income_tax_total = 0
[ "Prepare", "the", "entity", "for", "execution", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L349-L373
[ "def", "prepare_to_run", "(", "self", ",", "clock", ",", "period_count", ")", ":", "self", ".", "period_count", "=", "period_count", "self", ".", "_exec_year_end_datetime", "=", "clock", ".", "get_datetime_at_period_ix", "(", "period_count", ")", "self", ".", "_prev_year_end_datetime", "=", "clock", ".", "start_datetime", "self", ".", "_curr_year_end_datetime", "=", "clock", ".", "start_datetime", "+", "relativedelta", "(", "years", "=", "1", ")", "# Remove all the transactions", "del", "self", ".", "gl", ".", "transactions", "[", ":", "]", "for", "c", "in", "self", ".", "components", ":", "c", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")", "self", ".", "negative_income_tax_total", "=", "0" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Entity.run
Execute the entity at the current clock cycle. :param clock: The clock containing the current execution time and period information.
auxi/modelling/business/structure.py
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: c.run(clock, self.gl) self._perform_year_end_procedure(clock)
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: c.run(clock, self.gl) self._perform_year_end_procedure(clock)
[ "Execute", "the", "entity", "at", "the", "current", "clock", "cycle", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L375-L389
[ "def", "run", "(", "self", ",", "clock", ")", ":", "if", "clock", ".", "timestep_ix", ">=", "self", ".", "period_count", ":", "return", "for", "c", "in", "self", ".", "components", ":", "c", ".", "run", "(", "clock", ",", "self", ".", "gl", ")", "self", ".", "_perform_year_end_procedure", "(", "clock", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
count_with_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
auxi/tools/chemistry/stoichiometry.py
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 groups: for element, count in group.count().items(): counts[element] += count*multiplier return counts
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 groups: for element, count in group.count().items(): counts[element] += count*multiplier return counts
[ "Update", "group", "counts", "with", "multiplier" ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L57-L70
[ "def", "count_with_multiplier", "(", "groups", ",", "multiplier", ")", ":", "counts", "=", "collections", ".", "defaultdict", "(", "float", ")", "for", "group", "in", "groups", ":", "for", "element", ",", "count", "in", "group", ".", "count", "(", ")", ".", "items", "(", ")", ":", "counts", "[", "element", "]", "+=", "count", "*", "multiplier", "return", "counts" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
amounts
Calculate the amounts from the specified compound masses. :param masses: [kg] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5} :returns: [kmol] dictionary
auxi/tools/chemistry/stoichiometry.py
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()}
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", "amounts", "from", "the", "specified", "compound", "masses", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L202-L212
[ "def", "amounts", "(", "masses", ")", ":", "return", "{", "compound", ":", "amount", "(", "compound", ",", "masses", "[", "compound", "]", ")", "for", "compound", "in", "masses", ".", "keys", "(", ")", "}" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
amount_fractions
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
auxi/tools/chemistry/stoichiometry.py
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_total for compound in n.keys()}
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_total for compound in n.keys()}
[ "Calculate", "the", "mole", "fractions", "from", "the", "specified", "compound", "masses", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L215-L226
[ "def", "amount_fractions", "(", "masses", ")", ":", "n", "=", "amounts", "(", "masses", ")", "n_total", "=", "sum", "(", "n", ".", "values", "(", ")", ")", "return", "{", "compound", ":", "n", "[", "compound", "]", "/", "n_total", "for", "compound", "in", "n", ".", "keys", "(", ")", "}" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
masses
Calculate the masses from the specified compound amounts. :param masses: [kmol] dictionary, e.g. {'SiO2': 3.0, 'FeO': 1.5} :returns: [kg] dictionary
auxi/tools/chemistry/stoichiometry.py
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()}
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", "masses", "from", "the", "specified", "compound", "amounts", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L243-L253
[ "def", "masses", "(", "amounts", ")", ":", "return", "{", "compound", ":", "mass", "(", "compound", ",", "amounts", "[", "compound", "]", ")", "for", "compound", "in", "amounts", ".", "keys", "(", ")", "}" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
mass_fractions
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
auxi/tools/chemistry/stoichiometry.py
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_total for compound in m.keys()}
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_total for compound in m.keys()}
[ "Calculate", "the", "mole", "fractions", "from", "the", "specified", "compound", "amounts", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L256-L267
[ "def", "mass_fractions", "(", "amounts", ")", ":", "m", "=", "masses", "(", "amounts", ")", "m_total", "=", "sum", "(", "m", ".", "values", "(", ")", ")", "return", "{", "compound", ":", "m", "[", "compound", "]", "/", "m_total", "for", "compound", "in", "m", ".", "keys", "(", ")", "}" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
convert_compound
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 phase of the target compound, e.g. 'Fe[S1]'. :param element: Element to use as basis for the conversion, e.g. 'Fe' or 'O'. :returns: Mass of target. [kg]
auxi/tools/chemistry/stoichiometry.py
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 phase of the target compound, e.g. 'Fe[S1]'. :param element: Element to use as basis for the conversion, e.g. 'Fe' or 'O'. :returns: Mass of target. [kg] """ # Perform the conversion. target_mass_fraction = element_mass_fraction(target, element) if target_mass_fraction == 0.0: # If target_formula does not contain element, just return 0.0. return 0.0 else: source_mass_fraction = element_mass_fraction(source, element) return mass * source_mass_fraction / target_mass_fraction
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 phase of the target compound, e.g. 'Fe[S1]'. :param element: Element to use as basis for the conversion, e.g. 'Fe' or 'O'. :returns: Mass of target. [kg] """ # Perform the conversion. target_mass_fraction = element_mass_fraction(target, element) if target_mass_fraction == 0.0: # If target_formula does not contain element, just return 0.0. return 0.0 else: source_mass_fraction = element_mass_fraction(source, element) return mass * source_mass_fraction / target_mass_fraction
[ "Convert", "the", "specified", "mass", "of", "the", "source", "compound", "to", "the", "target", "using", "element", "as", "basis", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L270-L292
[ "def", "convert_compound", "(", "mass", ",", "source", ",", "target", ",", "element", ")", ":", "# Perform the conversion.", "target_mass_fraction", "=", "element_mass_fraction", "(", "target", ",", "element", ")", "if", "target_mass_fraction", "==", "0.0", ":", "# If target_formula does not contain element, just return 0.0.", "return", "0.0", "else", ":", "source_mass_fraction", "=", "element_mass_fraction", "(", "source", ",", "element", ")", "return", "mass", "*", "source_mass_fraction", "/", "target_mass_fraction" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
element_mass_fraction
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.
auxi/tools/chemistry/stoichiometry.py
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(compound, element) if coeff == 0.0: return 0.0 formula_mass = molar_mass(compound) element_mass = molar_mass(element) return coeff * element_mass / formula_mass
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(compound, element) if coeff == 0.0: return 0.0 formula_mass = molar_mass(compound) element_mass = molar_mass(element) return coeff * element_mass / formula_mass
[ "Determine", "the", "mass", "fraction", "of", "an", "element", "in", "a", "chemical", "compound", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L295-L312
[ "def", "element_mass_fraction", "(", "compound", ",", "element", ")", ":", "coeff", "=", "stoichiometry_coefficient", "(", "compound", ",", "element", ")", "if", "coeff", "==", "0.0", ":", "return", "0.0", "formula_mass", "=", "molar_mass", "(", "compound", ")", "element_mass", "=", "molar_mass", "(", "element", ")", "return", "coeff", "*", "element_mass", "/", "formula_mass" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
elements
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.
auxi/tools/chemistry/stoichiometry.py
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 = [parse_compound(compound).count().keys() for compound in compounds] return set().union(*elementlist)
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 = [parse_compound(compound).count().keys() for compound in compounds] return set().union(*elementlist)
[ "Determine", "the", "set", "of", "elements", "present", "in", "a", "list", "of", "chemical", "compounds", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L330-L344
[ "def", "elements", "(", "compounds", ")", ":", "elementlist", "=", "[", "parse_compound", "(", "compound", ")", ".", "count", "(", ")", ".", "keys", "(", ")", "for", "compound", "in", "compounds", "]", "return", "set", "(", ")", ".", "union", "(", "*", "elementlist", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
molar_mass
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: Molar mass. [kg/kmol]
auxi/tools/chemistry/stoichiometry.py
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: Molar mass. [kg/kmol] """ result = 0.0 if compound is None or len(compound) == 0: return result compound = compound.strip() parsed = parse_compound(compound) return parsed.molar_mass()
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: Molar mass. [kg/kmol] """ result = 0.0 if compound is None or len(compound) == 0: return result compound = compound.strip() parsed = parse_compound(compound) return parsed.molar_mass()
[ "Determine", "the", "molar", "mass", "of", "a", "chemical", "compound", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L347-L366
[ "def", "molar_mass", "(", "compound", "=", "''", ")", ":", "result", "=", "0.0", "if", "compound", "is", "None", "or", "len", "(", "compound", ")", "==", "0", ":", "return", "result", "compound", "=", "compound", ".", "strip", "(", ")", "parsed", "=", "parse_compound", "(", "compound", ")", "return", "parsed", ".", "molar_mass", "(", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
stoichiometry_coefficient
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.
auxi/tools/chemistry/stoichiometry.py
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 = parse_compound(compound.strip()).count() return stoichiometry[element]
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 = parse_compound(compound.strip()).count() return stoichiometry[element]
[ "Determine", "the", "stoichiometry", "coefficient", "of", "an", "element", "in", "a", "chemical", "compound", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L369-L382
[ "def", "stoichiometry_coefficient", "(", "compound", ",", "element", ")", ":", "stoichiometry", "=", "parse_compound", "(", "compound", ".", "strip", "(", ")", ")", ".", "count", "(", ")", "return", "stoichiometry", "[", "element", "]" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
stoichiometry_coefficients
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 of stoichiometry coefficients.
auxi/tools/chemistry/stoichiometry.py
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 of stoichiometry coefficients. """ stoichiometry = parse_compound(compound.strip()).count() return [stoichiometry[element] for element in elements]
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 of stoichiometry coefficients. """ stoichiometry = parse_compound(compound.strip()).count() return [stoichiometry[element] for element in elements]
[ "Determine", "the", "stoichiometry", "coefficients", "of", "the", "specified", "elements", "in", "the", "specified", "chemical", "compound", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/stoichiometry.py#L385-L398
[ "def", "stoichiometry_coefficients", "(", "compound", ",", "elements", ")", ":", "stoichiometry", "=", "parse_compound", "(", "compound", ".", "strip", "(", ")", ")", ".", "count", "(", ")", "return", "[", "stoichiometry", "[", "element", "]", "for", "element", "in", "elements", "]" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Material.add_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 material's size classes.
auxi/modelling/process/materials/psd.py
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 material's size classes. """ if not type(assay) is numpy.ndarray: raise Exception("Invalid assay. It must be a numpy array.") elif not assay.shape == (self.size_class_count,): raise Exception( "Invalid assay: It must have the same number of elements " "as the material has size classes.") elif name in self.assays.keys(): raise Exception( "Invalid assay: An assay with that name already exists.") self.assays[name] = assay
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 material's size classes. """ if not type(assay) is numpy.ndarray: raise Exception("Invalid assay. It must be a numpy array.") elif not assay.shape == (self.size_class_count,): raise Exception( "Invalid assay: It must have the same number of elements " "as the material has size classes.") elif name in self.assays.keys(): raise Exception( "Invalid assay: An assay with that name already exists.") self.assays[name] = assay
[ "Add", "an", "assay", "to", "the", "material", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/psd.py#L166-L185
[ "def", "add_assay", "(", "self", ",", "name", ",", "assay", ")", ":", "if", "not", "type", "(", "assay", ")", "is", "numpy", ".", "ndarray", ":", "raise", "Exception", "(", "\"Invalid assay. It must be a numpy array.\"", ")", "elif", "not", "assay", ".", "shape", "==", "(", "self", ".", "size_class_count", ",", ")", ":", "raise", "Exception", "(", "\"Invalid assay: It must have the same number of elements \"", "\"as the material has size classes.\"", ")", "elif", "name", "in", "self", ".", "assays", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"Invalid assay: An assay with that name already exists.\"", ")", "self", ".", "assays", "[", "name", "]", "=", "assay" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Material.create_package
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: Indicates whether the assay must be normalised before creating the package. :returns: The created MaterialPackage.
auxi/modelling/process/materials/psd.py
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: Indicates whether the assay must be normalised before creating the package. :returns: The created MaterialPackage. """ if assay is None: return MaterialPackage(self, self.create_empty_assay()) if normalise: assay_total = self.get_assay_total(assay) else: assay_total = 1.0 return MaterialPackage(self, mass * self.assays[assay] / assay_total)
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: Indicates whether the assay must be normalised before creating the package. :returns: The created MaterialPackage. """ if assay is None: return MaterialPackage(self, self.create_empty_assay()) if normalise: assay_total = self.get_assay_total(assay) else: assay_total = 1.0 return MaterialPackage(self, mass * self.assays[assay] / assay_total)
[ "Create", "a", "MaterialPackage", "based", "on", "the", "specified", "parameters", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/psd.py#L198-L218
[ "def", "create_package", "(", "self", ",", "assay", "=", "None", ",", "mass", "=", "0.0", ",", "normalise", "=", "True", ")", ":", "if", "assay", "is", "None", ":", "return", "MaterialPackage", "(", "self", ",", "self", ".", "create_empty_assay", "(", ")", ")", "if", "normalise", ":", "assay_total", "=", "self", ".", "get_assay_total", "(", "assay", ")", "else", ":", "assay_total", "=", "1.0", "return", "MaterialPackage", "(", "self", ",", "mass", "*", "self", ".", "assays", "[", "assay", "]", "/", "assay_total", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
MaterialPackage.extract
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 extracted package is returned as a new package. * tuple (size class, mass): The other tuple specifies the mass of a size class to be extracted. It is extracted from self and the extracted mass is returned as a new package. * string: The 'other' string specifies the size class to be extracted. All of the mass of that size class will be removed from self and a new package created with it. :returns: A new material package containing the material that was extracted from self.
auxi/modelling/process/materials/psd.py
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 extracted package is returned as a new package. * tuple (size class, mass): The other tuple specifies the mass of a size class to be extracted. It is extracted from self and the extracted mass is returned as a new package. * string: The 'other' string specifies the size class to be extracted. All of the mass of that size class will be removed from self and a new package created with it. :returns: A new material package containing the material that was extracted from self. """ # Extract the specified mass. if type(other) is float or \ type(other) is numpy.float64 or \ type(other) is numpy.float32: if other > self.get_mass(): raise Exception( "Invalid extraction operation. " "Cannot extract a mass larger than the package's mass.") fraction_to_subtract = other / self.get_mass() result = MaterialPackage( self.material, self.size_class_masses * fraction_to_subtract) self.size_class_masses = self.size_class_masses * ( 1.0 - fraction_to_subtract) return result # Extract the specified mass of the specified size class. elif self._is_size_class_mass_tuple(other): index = self.material.get_size_class_index(other[0]) if other[1] > self.size_class_masses[index]: raise Exception( "Invalid extraction operation. " "Cannot extract a size class mass larger than what the " "package contains.") self.size_class_masses[index] = \ self.size_class_masses[index] - other[1] resultarray = self.size_class_masses*0.0 resultarray[index] = other[1] result = MaterialPackage(self.material, resultarray) return result # Extract all of the specified size class. elif type(other) is str: index = self.material.get_size_class_index(float(other)) result = self * 0.0 result.size_class_masses[index] = self.size_class_masses[index] self.size_class_masses[index] = 0.0 return result # If not one of the above, it must be an invalid argument. else: raise TypeError("Invalid extraction argument.")
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 extracted package is returned as a new package. * tuple (size class, mass): The other tuple specifies the mass of a size class to be extracted. It is extracted from self and the extracted mass is returned as a new package. * string: The 'other' string specifies the size class to be extracted. All of the mass of that size class will be removed from self and a new package created with it. :returns: A new material package containing the material that was extracted from self. """ # Extract the specified mass. if type(other) is float or \ type(other) is numpy.float64 or \ type(other) is numpy.float32: if other > self.get_mass(): raise Exception( "Invalid extraction operation. " "Cannot extract a mass larger than the package's mass.") fraction_to_subtract = other / self.get_mass() result = MaterialPackage( self.material, self.size_class_masses * fraction_to_subtract) self.size_class_masses = self.size_class_masses * ( 1.0 - fraction_to_subtract) return result # Extract the specified mass of the specified size class. elif self._is_size_class_mass_tuple(other): index = self.material.get_size_class_index(other[0]) if other[1] > self.size_class_masses[index]: raise Exception( "Invalid extraction operation. " "Cannot extract a size class mass larger than what the " "package contains.") self.size_class_masses[index] = \ self.size_class_masses[index] - other[1] resultarray = self.size_class_masses*0.0 resultarray[index] = other[1] result = MaterialPackage(self.material, resultarray) return result # Extract all of the specified size class. elif type(other) is str: index = self.material.get_size_class_index(float(other)) result = self * 0.0 result.size_class_masses[index] = self.size_class_masses[index] self.size_class_masses[index] = 0.0 return result # If not one of the above, it must be an invalid argument. else: raise TypeError("Invalid extraction argument.")
[ "Extract", "other", "from", "self", "modifying", "self", "and", "returning", "the", "extracted", "material", "as", "a", "new", "package", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/psd.py#L431-L493
[ "def", "extract", "(", "self", ",", "other", ")", ":", "# Extract the specified mass.", "if", "type", "(", "other", ")", "is", "float", "or", "type", "(", "other", ")", "is", "numpy", ".", "float64", "or", "type", "(", "other", ")", "is", "numpy", ".", "float32", ":", "if", "other", ">", "self", ".", "get_mass", "(", ")", ":", "raise", "Exception", "(", "\"Invalid extraction operation. \"", "\"Cannot extract a mass larger than the package's mass.\"", ")", "fraction_to_subtract", "=", "other", "/", "self", ".", "get_mass", "(", ")", "result", "=", "MaterialPackage", "(", "self", ".", "material", ",", "self", ".", "size_class_masses", "*", "fraction_to_subtract", ")", "self", ".", "size_class_masses", "=", "self", ".", "size_class_masses", "*", "(", "1.0", "-", "fraction_to_subtract", ")", "return", "result", "# Extract the specified mass of the specified size class.", "elif", "self", ".", "_is_size_class_mass_tuple", "(", "other", ")", ":", "index", "=", "self", ".", "material", ".", "get_size_class_index", "(", "other", "[", "0", "]", ")", "if", "other", "[", "1", "]", ">", "self", ".", "size_class_masses", "[", "index", "]", ":", "raise", "Exception", "(", "\"Invalid extraction operation. \"", "\"Cannot extract a size class mass larger than what the \"", "\"package contains.\"", ")", "self", ".", "size_class_masses", "[", "index", "]", "=", "self", ".", "size_class_masses", "[", "index", "]", "-", "other", "[", "1", "]", "resultarray", "=", "self", ".", "size_class_masses", "*", "0.0", "resultarray", "[", "index", "]", "=", "other", "[", "1", "]", "result", "=", "MaterialPackage", "(", "self", ".", "material", ",", "resultarray", ")", "return", "result", "# Extract all of the specified size class.", "elif", "type", "(", "other", ")", "is", "str", ":", "index", "=", "self", ".", "material", ".", "get_size_class_index", "(", "float", "(", "other", ")", ")", "result", "=", "self", "*", "0.0", "result", ".", "size_class_masses", "[", "index", "]", "=", "self", ".", "size_class_masses", "[", "index", "]", "self", ".", "size_class_masses", "[", "index", "]", "=", "0.0", "return", "result", "# If not one of the above, it must be an invalid argument.", "else", ":", "raise", "TypeError", "(", "\"Invalid extraction argument.\"", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
MaterialPackage.add_to
Add another psd material package to this material package. :param other: The other material package.
auxi/modelling/process/materials/psd.py
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 == other.material: self.size_class_masses = \ self.size_class_masses + other.size_class_masses else: # Packages of different materials. for size_class in other.material.size_classes: if size_class not in self.material.size_classes: raise Exception( "Packages of '" + other.material.name + "' cannot be added to packages of '" + self.material.name + "'. The size class '" + size_class + "' was not found in '" + self.material.name + "'.") self.add_to( (size_class, other.get_size_class_mass(size_class))) # Add the specified mass of the specified size class. elif self._is_size_class_mass_tuple(other): # Added material variables. size_class = other[0] compound_index = self.material.get_size_class_index(size_class) mass = other[1] # Create the result package. self.size_class_masses[compound_index] = \ self.size_class_masses[compound_index] + mass # If not one of the above, it must be an invalid argument. else: raise TypeError("Invalid addition argument.")
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 == other.material: self.size_class_masses = \ self.size_class_masses + other.size_class_masses else: # Packages of different materials. for size_class in other.material.size_classes: if size_class not in self.material.size_classes: raise Exception( "Packages of '" + other.material.name + "' cannot be added to packages of '" + self.material.name + "'. The size class '" + size_class + "' was not found in '" + self.material.name + "'.") self.add_to( (size_class, other.get_size_class_mass(size_class))) # Add the specified mass of the specified size class. elif self._is_size_class_mass_tuple(other): # Added material variables. size_class = other[0] compound_index = self.material.get_size_class_index(size_class) mass = other[1] # Create the result package. self.size_class_masses[compound_index] = \ self.size_class_masses[compound_index] + mass # If not one of the above, it must be an invalid argument. else: raise TypeError("Invalid addition argument.")
[ "Add", "another", "psd", "material", "package", "to", "this", "material", "package", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/psd.py#L496-L534
[ "def", "add_to", "(", "self", ",", "other", ")", ":", "# Add another package.", "if", "type", "(", "other", ")", "is", "MaterialPackage", ":", "# Packages of the same material.", "if", "self", ".", "material", "==", "other", ".", "material", ":", "self", ".", "size_class_masses", "=", "self", ".", "size_class_masses", "+", "other", ".", "size_class_masses", "else", ":", "# Packages of different materials.", "for", "size_class", "in", "other", ".", "material", ".", "size_classes", ":", "if", "size_class", "not", "in", "self", ".", "material", ".", "size_classes", ":", "raise", "Exception", "(", "\"Packages of '\"", "+", "other", ".", "material", ".", "name", "+", "\"' cannot be added to packages of '\"", "+", "self", ".", "material", ".", "name", "+", "\"'. The size class '\"", "+", "size_class", "+", "\"' was not found in '\"", "+", "self", ".", "material", ".", "name", "+", "\"'.\"", ")", "self", ".", "add_to", "(", "(", "size_class", ",", "other", ".", "get_size_class_mass", "(", "size_class", ")", ")", ")", "# Add the specified mass of the specified size class.", "elif", "self", ".", "_is_size_class_mass_tuple", "(", "other", ")", ":", "# Added material variables.", "size_class", "=", "other", "[", "0", "]", "compound_index", "=", "self", ".", "material", ".", "get_size_class_index", "(", "size_class", ")", "mass", "=", "other", "[", "1", "]", "# Create the result package.", "self", ".", "size_class_masses", "[", "compound_index", "]", "=", "self", ".", "size_class_masses", "[", "compound_index", "]", "+", "mass", "# If not one of the above, it must be an invalid argument.", "else", ":", "raise", "TypeError", "(", "\"Invalid addition argument.\"", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
BasicActivity.run
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.
auxi/modelling/business/basic.py
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. """ if not self._meet_execution_criteria(clock.timestep_ix): return generalLedger.create_transaction( self.description if self.description is not None else self.name, description='', tx_date=clock.get_datetime(), dt_account=self.dt_account, cr_account=self.cr_account, source=self.path, amount=self.amount)
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. """ if not self._meet_execution_criteria(clock.timestep_ix): return generalLedger.create_transaction( self.description if self.description is not None else self.name, description='', tx_date=clock.get_datetime(), dt_account=self.dt_account, cr_account=self.cr_account, source=self.path, amount=self.amount)
[ "Execute", "the", "activity", "at", "the", "current", "clock", "cycle", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/basic.py#L61-L81
[ "def", "run", "(", "self", ",", "clock", ",", "generalLedger", ")", ":", "if", "not", "self", ".", "_meet_execution_criteria", "(", "clock", ".", "timestep_ix", ")", ":", "return", "generalLedger", ".", "create_transaction", "(", "self", ".", "description", "if", "self", ".", "description", "is", "not", "None", "else", "self", ".", "name", ",", "description", "=", "''", ",", "tx_date", "=", "clock", ".", "get_datetime", "(", ")", ",", "dt_account", "=", "self", ".", "dt_account", ",", "cr_account", "=", "self", ".", "cr_account", ",", "source", "=", "self", ".", "path", ",", "amount", "=", "self", ".", "amount", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
BasicLoanActivity.prepare_to_run
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 run for.
auxi/modelling/business/basic.py
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 run for. """ super(BasicLoanActivity, self).prepare_to_run(clock, period_count) self._months_executed = 0 self._amount_left = self.amount
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 run for. """ super(BasicLoanActivity, self).prepare_to_run(clock, period_count) self._months_executed = 0 self._amount_left = self.amount
[ "Prepare", "the", "activity", "for", "execution", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/basic.py#L223-L236
[ "def", "prepare_to_run", "(", "self", ",", "clock", ",", "period_count", ")", ":", "super", "(", "BasicLoanActivity", ",", "self", ")", ".", "prepare_to_run", "(", "clock", ",", "period_count", ")", "self", ".", "_months_executed", "=", "0", "self", ".", "_amount_left", "=", "self", ".", "amount" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
BasicLoanActivity.run
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.
auxi/modelling/business/basic.py
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. """ if not self._meet_execution_criteria(clock.timestep_ix): return if self.description is None: tx_name = self.name else: tx_name = self.description if self._months_executed == 0: generalLedger.create_transaction( tx_name, description='Make a loan', tx_date=clock.get_datetime(), dt_account=self.bank_account, cr_account=self.loan_account, source=self.path, amount=self.amount) else: curr_interest_amount = (self._amount_left * self.interest_rate) / 12.0 generalLedger.create_transaction( tx_name, description='Consider interest', tx_date=clock.get_datetime(), dt_account=self.interest_account, cr_account=self.loan_account, source=self.path, amount=curr_interest_amount) generalLedger.create_transaction( tx_name, description='Pay principle', tx_date=clock.get_datetime(), dt_account=self.loan_account, cr_account=self.bank_account, source=self.path, amount=self._monthly_payment) self._amount_left += curr_interest_amount - self._monthly_payment self._months_executed += self.interval
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. """ if not self._meet_execution_criteria(clock.timestep_ix): return if self.description is None: tx_name = self.name else: tx_name = self.description if self._months_executed == 0: generalLedger.create_transaction( tx_name, description='Make a loan', tx_date=clock.get_datetime(), dt_account=self.bank_account, cr_account=self.loan_account, source=self.path, amount=self.amount) else: curr_interest_amount = (self._amount_left * self.interest_rate) / 12.0 generalLedger.create_transaction( tx_name, description='Consider interest', tx_date=clock.get_datetime(), dt_account=self.interest_account, cr_account=self.loan_account, source=self.path, amount=curr_interest_amount) generalLedger.create_transaction( tx_name, description='Pay principle', tx_date=clock.get_datetime(), dt_account=self.loan_account, cr_account=self.bank_account, source=self.path, amount=self._monthly_payment) self._amount_left += curr_interest_amount - self._monthly_payment self._months_executed += self.interval
[ "Execute", "the", "activity", "at", "the", "current", "clock", "cycle", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/basic.py#L238-L289
[ "def", "run", "(", "self", ",", "clock", ",", "generalLedger", ")", ":", "if", "not", "self", ".", "_meet_execution_criteria", "(", "clock", ".", "timestep_ix", ")", ":", "return", "if", "self", ".", "description", "is", "None", ":", "tx_name", "=", "self", ".", "name", "else", ":", "tx_name", "=", "self", ".", "description", "if", "self", ".", "_months_executed", "==", "0", ":", "generalLedger", ".", "create_transaction", "(", "tx_name", ",", "description", "=", "'Make a loan'", ",", "tx_date", "=", "clock", ".", "get_datetime", "(", ")", ",", "dt_account", "=", "self", ".", "bank_account", ",", "cr_account", "=", "self", ".", "loan_account", ",", "source", "=", "self", ".", "path", ",", "amount", "=", "self", ".", "amount", ")", "else", ":", "curr_interest_amount", "=", "(", "self", ".", "_amount_left", "*", "self", ".", "interest_rate", ")", "/", "12.0", "generalLedger", ".", "create_transaction", "(", "tx_name", ",", "description", "=", "'Consider interest'", ",", "tx_date", "=", "clock", ".", "get_datetime", "(", ")", ",", "dt_account", "=", "self", ".", "interest_account", ",", "cr_account", "=", "self", ".", "loan_account", ",", "source", "=", "self", ".", "path", ",", "amount", "=", "curr_interest_amount", ")", "generalLedger", ".", "create_transaction", "(", "tx_name", ",", "description", "=", "'Pay principle'", ",", "tx_date", "=", "clock", ".", "get_datetime", "(", ")", ",", "dt_account", "=", "self", ".", "loan_account", ",", "cr_account", "=", "self", ".", "bank_account", ",", "source", "=", "self", ".", "path", ",", "amount", "=", "self", ".", "_monthly_payment", ")", "self", ".", "_amount_left", "+=", "curr_interest_amount", "-", "self", ".", "_monthly_payment", "self", ".", "_months_executed", "+=", "self", ".", "interval" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Clock.get_datetime_at_period_ix
Get the datetime at a given period. :param period: The index of the period. :returns: The datetime.
auxi/core/time.py
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(milliseconds=ix) elif self.timestep_period_duration == TimePeriod.second: return self.start_datetime + timedelta(seconds=ix) elif self.timestep_period_duration == TimePeriod.minute: return self.start_datetime + timedelta(minutes=ix) elif self.timestep_period_duration == TimePeriod.hour: return self.start_datetime + timedelta(hours=ix) elif self.timestep_period_duration == TimePeriod.day: return self.start_datetime + relativedelta(days=ix) elif self.timestep_period_duration == TimePeriod.week: return self.start_datetime + relativedelta(days=ix*7) elif self.timestep_period_duration == TimePeriod.month: return self.start_datetime + relativedelta(months=ix) elif self.timestep_period_duration == TimePeriod.year: return self.start_datetime + relativedelta(years=ix)
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(milliseconds=ix) elif self.timestep_period_duration == TimePeriod.second: return self.start_datetime + timedelta(seconds=ix) elif self.timestep_period_duration == TimePeriod.minute: return self.start_datetime + timedelta(minutes=ix) elif self.timestep_period_duration == TimePeriod.hour: return self.start_datetime + timedelta(hours=ix) elif self.timestep_period_duration == TimePeriod.day: return self.start_datetime + relativedelta(days=ix) elif self.timestep_period_duration == TimePeriod.week: return self.start_datetime + relativedelta(days=ix*7) elif self.timestep_period_duration == TimePeriod.month: return self.start_datetime + relativedelta(months=ix) elif self.timestep_period_duration == TimePeriod.year: return self.start_datetime + relativedelta(years=ix)
[ "Get", "the", "datetime", "at", "a", "given", "period", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/time.py#L79-L103
[ "def", "get_datetime_at_period_ix", "(", "self", ",", "ix", ")", ":", "if", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "millisecond", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "milliseconds", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "second", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "seconds", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "minute", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "minutes", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "hour", ":", "return", "self", ".", "start_datetime", "+", "timedelta", "(", "hours", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "day", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "days", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "week", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "days", "=", "ix", "*", "7", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "month", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "months", "=", "ix", ")", "elif", "self", ".", "timestep_period_duration", "==", "TimePeriod", ".", "year", ":", "return", "self", ".", "start_datetime", "+", "relativedelta", "(", "years", "=", "ix", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
_get_default_data_path_
Calculate the default path in which thermochemical data is stored. :returns: Default path.
auxi/tools/chemistry/thermochemistry.py
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) return data_path
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) return data_path
[ "Calculate", "the", "default", "path", "in", "which", "thermochemical", "data", "is", "stored", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L540-L550
[ "def", "_get_default_data_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", ")", "return", "data_path" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
_read_compound_from_factsage_file_
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.
auxi/tools/chemistry/thermochemistry.py
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) as f: lines = f.readlines() compound = {'Formula': lines[0].split(' ')[1]} # FIXME: replace with logging print(compound['Formula']) compound['Phases'] = phs = {} started = False phaseold = 'zz' recordold = '0' for line in lines: if started: if line.startswith('_'): # line indicating end of data break line = line.replace(' 298 ', ' 298.15 ') line = line.replace(' - ', ' ') while ' ' in line: line = line.replace(' ', ' ') line = line.replace(' \n', '') line = line.replace('\n', '') strings = line.split(' ') if len(strings) < 2: # empty line continue phase = strings[0] if phase != phaseold: # new phase detected phaseold = phase ph = phs[phase] = {} ph['Symbol'] = phase ph['DHref'] = float(strings[2]) ph['Sref'] = float(strings[3]) cprecs = ph['Cp_records'] = {} record = strings[1] if record != recordold: # new record detected recordold = record Tmax = float(strings[len(strings) - 1]) cprecs[Tmax] = {} cprecs[Tmax]['Tmin'] = float(strings[len(strings) - 2]) cprecs[Tmax]['Tmax'] = float(strings[len(strings) - 1]) cprecs[Tmax]['Terms'] = [] t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 10: t = {'Coefficient': float(strings[6]), 'Exponent': float(strings[7])} cprecs[Tmax]['Terms'].append(t) else: # old record detected t = {'Coefficient': float(strings[2]), 'Exponent': float(strings[3])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 8: t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) else: # old phase detected ph = phs[phase] record = strings[1] if record != recordold: # new record detected recordold = record Tmax = float(strings[len(strings) - 1]) cprecs = ph['Cp_records'] cprecs[Tmax] = {} cprecs[Tmax]['Tmin'] = float(strings[len(strings) - 2]) cprecs[Tmax]['Tmax'] = float(strings[len(strings) - 1]) cprecs[Tmax]['Terms'] = [] t = {'Coefficient': float(strings[2]), 'Exponent': float(strings[3])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 8: t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) else: # old record detected t = {'Coefficient': float(strings[2]), 'Exponent': float(strings[3])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 8: t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) if line.startswith('_'): # line indicating the start of the data started = True for name, ph in phs.items(): cprecs = ph['Cp_records'] first = cprecs[min(cprecs.keys())] first['Tmin'] = 298.15 return compound
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) as f: lines = f.readlines() compound = {'Formula': lines[0].split(' ')[1]} # FIXME: replace with logging print(compound['Formula']) compound['Phases'] = phs = {} started = False phaseold = 'zz' recordold = '0' for line in lines: if started: if line.startswith('_'): # line indicating end of data break line = line.replace(' 298 ', ' 298.15 ') line = line.replace(' - ', ' ') while ' ' in line: line = line.replace(' ', ' ') line = line.replace(' \n', '') line = line.replace('\n', '') strings = line.split(' ') if len(strings) < 2: # empty line continue phase = strings[0] if phase != phaseold: # new phase detected phaseold = phase ph = phs[phase] = {} ph['Symbol'] = phase ph['DHref'] = float(strings[2]) ph['Sref'] = float(strings[3]) cprecs = ph['Cp_records'] = {} record = strings[1] if record != recordold: # new record detected recordold = record Tmax = float(strings[len(strings) - 1]) cprecs[Tmax] = {} cprecs[Tmax]['Tmin'] = float(strings[len(strings) - 2]) cprecs[Tmax]['Tmax'] = float(strings[len(strings) - 1]) cprecs[Tmax]['Terms'] = [] t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 10: t = {'Coefficient': float(strings[6]), 'Exponent': float(strings[7])} cprecs[Tmax]['Terms'].append(t) else: # old record detected t = {'Coefficient': float(strings[2]), 'Exponent': float(strings[3])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 8: t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) else: # old phase detected ph = phs[phase] record = strings[1] if record != recordold: # new record detected recordold = record Tmax = float(strings[len(strings) - 1]) cprecs = ph['Cp_records'] cprecs[Tmax] = {} cprecs[Tmax]['Tmin'] = float(strings[len(strings) - 2]) cprecs[Tmax]['Tmax'] = float(strings[len(strings) - 1]) cprecs[Tmax]['Terms'] = [] t = {'Coefficient': float(strings[2]), 'Exponent': float(strings[3])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 8: t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) else: # old record detected t = {'Coefficient': float(strings[2]), 'Exponent': float(strings[3])} cprecs[Tmax]['Terms'].append(t) if len(strings) == 8: t = {'Coefficient': float(strings[4]), 'Exponent': float(strings[5])} cprecs[Tmax]['Terms'].append(t) if line.startswith('_'): # line indicating the start of the data started = True for name, ph in phs.items(): cprecs = ph['Cp_records'] first = cprecs[min(cprecs.keys())] first['Tmin'] = 298.15 return compound
[ "Build", "a", "dictionary", "containing", "the", "factsage", "thermochemical", "data", "of", "a", "compound", "by", "reading", "the", "data", "from", "a", "file", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L553-L653
[ "def", "_read_compound_from_factsage_file_", "(", "file_name", ")", ":", "with", "open", "(", "file_name", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "compound", "=", "{", "'Formula'", ":", "lines", "[", "0", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "}", "# FIXME: replace with logging", "print", "(", "compound", "[", "'Formula'", "]", ")", "compound", "[", "'Phases'", "]", "=", "phs", "=", "{", "}", "started", "=", "False", "phaseold", "=", "'zz'", "recordold", "=", "'0'", "for", "line", "in", "lines", ":", "if", "started", ":", "if", "line", ".", "startswith", "(", "'_'", ")", ":", "# line indicating end of data", "break", "line", "=", "line", ".", "replace", "(", "' 298 '", ",", "' 298.15 '", ")", "line", "=", "line", ".", "replace", "(", "' - '", ",", "' '", ")", "while", "' '", "in", "line", ":", "line", "=", "line", ".", "replace", "(", "' '", ",", "' '", ")", "line", "=", "line", ".", "replace", "(", "' \\n'", ",", "''", ")", "line", "=", "line", ".", "replace", "(", "'\\n'", ",", "''", ")", "strings", "=", "line", ".", "split", "(", "' '", ")", "if", "len", "(", "strings", ")", "<", "2", ":", "# empty line", "continue", "phase", "=", "strings", "[", "0", "]", "if", "phase", "!=", "phaseold", ":", "# new phase detected", "phaseold", "=", "phase", "ph", "=", "phs", "[", "phase", "]", "=", "{", "}", "ph", "[", "'Symbol'", "]", "=", "phase", "ph", "[", "'DHref'", "]", "=", "float", "(", "strings", "[", "2", "]", ")", "ph", "[", "'Sref'", "]", "=", "float", "(", "strings", "[", "3", "]", ")", "cprecs", "=", "ph", "[", "'Cp_records'", "]", "=", "{", "}", "record", "=", "strings", "[", "1", "]", "if", "record", "!=", "recordold", ":", "# new record detected", "recordold", "=", "record", "Tmax", "=", "float", "(", "strings", "[", "len", "(", "strings", ")", "-", "1", "]", ")", "cprecs", "[", "Tmax", "]", "=", "{", "}", "cprecs", "[", "Tmax", "]", "[", "'Tmin'", "]", "=", "float", "(", "strings", "[", "len", "(", "strings", ")", "-", "2", "]", ")", "cprecs", "[", "Tmax", "]", "[", "'Tmax'", "]", "=", "float", "(", "strings", "[", "len", "(", "strings", ")", "-", "1", "]", ")", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", "=", "[", "]", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "4", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "5", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "if", "len", "(", "strings", ")", "==", "10", ":", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "6", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "7", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "else", ":", "# old record detected", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "2", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "3", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "if", "len", "(", "strings", ")", "==", "8", ":", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "4", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "5", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "else", ":", "# old phase detected", "ph", "=", "phs", "[", "phase", "]", "record", "=", "strings", "[", "1", "]", "if", "record", "!=", "recordold", ":", "# new record detected", "recordold", "=", "record", "Tmax", "=", "float", "(", "strings", "[", "len", "(", "strings", ")", "-", "1", "]", ")", "cprecs", "=", "ph", "[", "'Cp_records'", "]", "cprecs", "[", "Tmax", "]", "=", "{", "}", "cprecs", "[", "Tmax", "]", "[", "'Tmin'", "]", "=", "float", "(", "strings", "[", "len", "(", "strings", ")", "-", "2", "]", ")", "cprecs", "[", "Tmax", "]", "[", "'Tmax'", "]", "=", "float", "(", "strings", "[", "len", "(", "strings", ")", "-", "1", "]", ")", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", "=", "[", "]", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "2", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "3", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "if", "len", "(", "strings", ")", "==", "8", ":", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "4", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "5", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "else", ":", "# old record detected", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "2", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "3", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "if", "len", "(", "strings", ")", "==", "8", ":", "t", "=", "{", "'Coefficient'", ":", "float", "(", "strings", "[", "4", "]", ")", ",", "'Exponent'", ":", "float", "(", "strings", "[", "5", "]", ")", "}", "cprecs", "[", "Tmax", "]", "[", "'Terms'", "]", ".", "append", "(", "t", ")", "if", "line", ".", "startswith", "(", "'_'", ")", ":", "# line indicating the start of the data", "started", "=", "True", "for", "name", ",", "ph", "in", "phs", ".", "items", "(", ")", ":", "cprecs", "=", "ph", "[", "'Cp_records'", "]", "first", "=", "cprecs", "[", "min", "(", "cprecs", ".", "keys", "(", ")", ")", "]", "first", "[", "'Tmin'", "]", "=", "298.15", "return", "compound" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
_split_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 chemical compound.
auxi/tools/chemistry/thermochemistry.py
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 chemical compound. """ formula = compound_string.replace(']', '').split('[')[0] phase = compound_string.replace(']', '').split('[')[1] return formula, 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 chemical compound. """ formula = compound_string.replace(']', '').split('[')[0] phase = compound_string.replace(']', '').split('[')[1] return formula, phase
[ "Split", "a", "compound", "s", "combined", "formula", "and", "phase", "into", "separate", "strings", "for", "the", "formula", "and", "phase", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L656-L671
[ "def", "_split_compound_string_", "(", "compound_string", ")", ":", "formula", "=", "compound_string", ".", "replace", "(", "']'", ",", "''", ")", ".", "split", "(", "'['", ")", "[", "0", "]", "phase", "=", "compound_string", ".", "replace", "(", "']'", ",", "''", ")", ".", "split", "(", "'['", ")", "[", "1", "]", "return", "formula", ",", "phase" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
_finalise_result_
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.
auxi/tools/chemistry/thermochemistry.py
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. """ result = value / 3.6E6 # J/x -> kWh/x result = result / compound.molar_mass # x/mol -> x/kg result = result * mass # x/kg -> x return result
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. """ result = value / 3.6E6 # J/x -> kWh/x result = result / compound.molar_mass # x/mol -> x/kg result = result * mass # x/kg -> x return result
[ "Convert", "the", "value", "to", "its", "final", "form", "by", "unit", "conversions", "and", "multiplying", "by", "mass", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L674-L690
[ "def", "_finalise_result_", "(", "compound", ",", "value", ",", "mass", ")", ":", "result", "=", "value", "/", "3.6E6", "# J/x -> kWh/x", "result", "=", "result", "/", "compound", ".", "molar_mass", "# x/mol -> x/kg", "result", "=", "result", "*", "mass", "# x/kg -> x", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
write_compound_to_auxi_file
Writes a compound to an auxi file at the specified directory. :param dir: The directory. :param compound: The compound.
auxi/tools/chemistry/thermochemistry.py
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: f.write(str(compound))
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: f.write(str(compound))
[ "Writes", "a", "compound", "to", "an", "auxi", "file", "at", "the", "specified", "directory", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L707-L717
[ "def", "write_compound_to_auxi_file", "(", "directory", ",", "compound", ")", ":", "file_name", "=", "\"Compound_\"", "+", "compound", ".", "formula", "+", "\".json\"", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "file_name", ")", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "str", "(", "compound", ")", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
load_data_factsage
Load all the thermochemical data factsage files located at a path. :param path: Path at which the data files are located.
auxi/tools/chemistry/thermochemistry.py
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 specified data file path does not exist. (%s)' % path) return files = glob.glob(os.path.join(path, 'Compound_*.txt')) for file in files: compound = Compound(_read_compound_from_factsage_file_(file)) compounds[compound.formula] = compound
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 specified data file path does not exist. (%s)' % path) return files = glob.glob(os.path.join(path, 'Compound_*.txt')) for file in files: compound = Compound(_read_compound_from_factsage_file_(file)) compounds[compound.formula] = compound
[ "Load", "all", "the", "thermochemical", "data", "factsage", "files", "located", "at", "a", "path", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L720-L739
[ "def", "load_data_factsage", "(", "path", "=", "''", ")", ":", "compounds", ".", "clear", "(", ")", "if", "path", "==", "''", ":", "path", "=", "default_data_path", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "warnings", ".", "warn", "(", "'The specified data file path does not exist. (%s)'", "%", "path", ")", "return", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'Compound_*.txt'", ")", ")", "for", "file", "in", "files", ":", "compound", "=", "Compound", "(", "_read_compound_from_factsage_file_", "(", "file", ")", ")", "compounds", "[", "compound", ".", "formula", "]", "=", "compound" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
load_data_auxi
Load all the thermochemical data auxi files located at a path. :param path: Path at which the data files are located.
auxi/tools/chemistry/thermochemistry.py
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 data file path does not exist. (%s)' % path) return files = glob.glob(os.path.join(path, 'Compound_*.json')) for file in files: compound = Compound.read(file) compounds[compound.formula] = compound
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 data file path does not exist. (%s)' % path) return files = glob.glob(os.path.join(path, 'Compound_*.json')) for file in files: compound = Compound.read(file) compounds[compound.formula] = compound
[ "Load", "all", "the", "thermochemical", "data", "auxi", "files", "located", "at", "a", "path", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L742-L761
[ "def", "load_data_auxi", "(", "path", "=", "''", ")", ":", "compounds", ".", "clear", "(", ")", "if", "path", "==", "''", ":", "path", "=", "default_data_path", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "warnings", ".", "warn", "(", "'The specified data file path does not exist. (%s)'", "%", "path", ")", "return", "files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'Compound_*.json'", ")", ")", "for", "file", "in", "files", ":", "compound", "=", "Compound", ".", "read", "(", "file", ")", "compounds", "[", "compound", ".", "formula", "]", "=", "compound" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
list_compounds
List all compounds that are currently loaded in the thermo module, and their phases.
auxi/tools/chemistry/thermochemistry.py
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(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(phases)))
[ "List", "all", "compounds", "that", "are", "currently", "loaded", "in", "the", "thermo", "module", "and", "their", "phases", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L764-L773
[ "def", "list_compounds", "(", ")", ":", "print", "(", "'Compounds currently loaded:'", ")", "for", "compound", "in", "sorted", "(", "compounds", ".", "keys", "(", ")", ")", ":", "phases", "=", "compounds", "[", "compound", "]", ".", "get_phase_list", "(", ")", "print", "(", "'%s: %s'", "%", "(", "compound", ",", "', '", ".", "join", "(", "phases", ")", ")", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Cp
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.
auxi/tools/chemistry/thermochemistry.py
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. """ formula, phase = _split_compound_string_(compound_string) TK = T + 273.15 compound = compounds[formula] result = compound.Cp(phase, TK) return _finalise_result_(compound, result, 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. """ formula, phase = _split_compound_string_(compound_string) TK = T + 273.15 compound = compounds[formula] result = compound.Cp(phase, TK) return _finalise_result_(compound, result, mass)
[ "Calculate", "the", "heat", "capacity", "of", "the", "compound", "for", "the", "specified", "temperature", "and", "mass", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L798-L816
[ "def", "Cp", "(", "compound_string", ",", "T", ",", "mass", "=", "1.0", ")", ":", "formula", ",", "phase", "=", "_split_compound_string_", "(", "compound_string", ")", "TK", "=", "T", "+", "273.15", "compound", "=", "compounds", "[", "formula", "]", "result", "=", "compound", ".", "Cp", "(", "phase", ",", "TK", ")", "return", "_finalise_result_", "(", "compound", ",", "result", ",", "mass", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
CpRecord.Cp
Calculate the heat capacity of the compound phase. :param T: [K] temperature :returns: [J/mol/K] Heat capacity.
auxi/tools/chemistry/thermochemistry.py
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
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", "heat", "capacity", "of", "the", "compound", "phase", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L77-L89
[ "def", "Cp", "(", "self", ",", "T", ")", ":", "result", "=", "0.0", "for", "c", ",", "e", "in", "zip", "(", "self", ".", "_coefficients", ",", "self", ".", "_exponents", ")", ":", "result", "+=", "c", "*", "T", "**", "e", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
CpRecord.H
Calculate the portion of enthalpy of the compound phase covered by this Cp record. :param T: [K] temperature :returns: [J/mol] Enthalpy.
auxi/tools/chemistry/thermochemistry.py
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 Tref = self.Tmin for c, e in zip(self._coefficients, self._exponents): # Analytically integrate Cp(T). if e == -1.0: result += c * math.log(lT/Tref) else: result += c * (lT**(e+1.0) - Tref**(e+1.0)) / (e+1.0) return result
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 Tref = self.Tmin for c, e in zip(self._coefficients, self._exponents): # Analytically integrate Cp(T). if e == -1.0: result += c * math.log(lT/Tref) else: result += c * (lT**(e+1.0) - Tref**(e+1.0)) / (e+1.0) return result
[ "Calculate", "the", "portion", "of", "enthalpy", "of", "the", "compound", "phase", "covered", "by", "this", "Cp", "record", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L91-L114
[ "def", "H", "(", "self", ",", "T", ")", ":", "result", "=", "0.0", "if", "T", "<", "self", ".", "Tmax", ":", "lT", "=", "T", "else", ":", "lT", "=", "self", ".", "Tmax", "Tref", "=", "self", ".", "Tmin", "for", "c", ",", "e", "in", "zip", "(", "self", ".", "_coefficients", ",", "self", ".", "_exponents", ")", ":", "# Analytically integrate Cp(T).", "if", "e", "==", "-", "1.0", ":", "result", "+=", "c", "*", "math", ".", "log", "(", "lT", "/", "Tref", ")", "else", ":", "result", "+=", "c", "*", "(", "lT", "**", "(", "e", "+", "1.0", ")", "-", "Tref", "**", "(", "e", "+", "1.0", ")", ")", "/", "(", "e", "+", "1.0", ")", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
CpRecord.S
Calculate the portion of entropy of the compound phase covered by this Cp record. :param T: [K] temperature :returns: Entropy. [J/mol/K]
auxi/tools/chemistry/thermochemistry.py
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 Tref = self.Tmin for c, e in zip(self._coefficients, self._exponents): # Create a modified exponent to analytically integrate Cp(T)/T # instead of Cp(T). e_modified = e - 1.0 if e_modified == -1.0: result += c * math.log(lT/Tref) else: e_mod = e_modified + 1.0 result += c * (lT**e_mod - Tref**e_mod) / e_mod return result
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 Tref = self.Tmin for c, e in zip(self._coefficients, self._exponents): # Create a modified exponent to analytically integrate Cp(T)/T # instead of Cp(T). e_modified = e - 1.0 if e_modified == -1.0: result += c * math.log(lT/Tref) else: e_mod = e_modified + 1.0 result += c * (lT**e_mod - Tref**e_mod) / e_mod return result
[ "Calculate", "the", "portion", "of", "entropy", "of", "the", "compound", "phase", "covered", "by", "this", "Cp", "record", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L116-L141
[ "def", "S", "(", "self", ",", "T", ")", ":", "result", "=", "0.0", "if", "T", "<", "self", ".", "Tmax", ":", "lT", "=", "T", "else", ":", "lT", "=", "self", ".", "Tmax", "Tref", "=", "self", ".", "Tmin", "for", "c", ",", "e", "in", "zip", "(", "self", ".", "_coefficients", ",", "self", ".", "_exponents", ")", ":", "# Create a modified exponent to analytically integrate Cp(T)/T", "# instead of Cp(T).", "e_modified", "=", "e", "-", "1.0", "if", "e_modified", "==", "-", "1.0", ":", "result", "+=", "c", "*", "math", ".", "log", "(", "lT", "/", "Tref", ")", "else", ":", "e_mod", "=", "e_modified", "+", "1.0", "result", "+=", "c", "*", "(", "lT", "**", "e_mod", "-", "Tref", "**", "e_mod", ")", "/", "e_mod", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.Cp
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.
auxi/tools/chemistry/thermochemistry.py
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) for TT in self._Cp_records.keys()]): if T < Tmax: return self._Cp_records[str(Tmax)].Cp(T) + self.Cp_mag(T) Tmax = max([float(TT) for TT in self._Cp_records.keys()]) return self._Cp_records[str(Tmax)].Cp(Tmax) + self.Cp_mag(T)
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) for TT in self._Cp_records.keys()]): if T < Tmax: return self._Cp_records[str(Tmax)].Cp(T) + self.Cp_mag(T) Tmax = max([float(TT) for TT in self._Cp_records.keys()]) return self._Cp_records[str(Tmax)].Cp(Tmax) + self.Cp_mag(T)
[ "Calculate", "the", "heat", "capacity", "of", "the", "compound", "phase", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L229-L246
[ "def", "Cp", "(", "self", ",", "T", ")", ":", "# TODO: Fix str/float conversion", "for", "Tmax", "in", "sorted", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", ":", "if", "T", "<", "Tmax", ":", "return", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "Cp", "(", "T", ")", "+", "self", ".", "Cp_mag", "(", "T", ")", "Tmax", "=", "max", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", "return", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "Cp", "(", "Tmax", ")", "+", "self", ".", "Cp_mag", "(", "T", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.Cp_mag
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. Calphad, 15(4), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N
auxi/tools/chemistry/thermochemistry.py
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. Calphad, 15(4), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: c = (self._B_mag*(2*tau**3 + 2*tau**9/3 + 2*tau**15/5))/self._D_mag else: c = (2*tau**-5 + 2*tau**-15/3 + 2*tau**-25/5)/self._D_mag result = R*math.log(self.beta0_mag + 1)*c return result
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. Calphad, 15(4), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: c = (self._B_mag*(2*tau**3 + 2*tau**9/3 + 2*tau**15/5))/self._D_mag else: c = (2*tau**-5 + 2*tau**-15/3 + 2*tau**-25/5)/self._D_mag result = R*math.log(self.beta0_mag + 1)*c return result
[ "Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "heat", "capacity", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L248-L270
[ "def", "Cp_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "c", "=", "(", "self", ".", "_B_mag", "*", "(", "2", "*", "tau", "**", "3", "+", "2", "*", "tau", "**", "9", "/", "3", "+", "2", "*", "tau", "**", "15", "/", "5", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "c", "=", "(", "2", "*", "tau", "**", "-", "5", "+", "2", "*", "tau", "**", "-", "15", "/", "3", "+", "2", "*", "tau", "**", "-", "25", "/", "5", ")", "/", "self", ".", "_D_mag", "result", "=", "R", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "c", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.H
Calculate the enthalpy of the compound phase at the specified temperature. :param T: [K] temperature :returns: [J/mol] The enthalpy of the compound phase.
auxi/tools/chemistry/thermochemistry.py
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_records.keys()]): result += self._Cp_records[str(Tmax)].H(T) if T <= Tmax: return result + self.H_mag(T) # Extrapolate beyond the upper limit by using a constant heat capacity. Tmax = max([float(TT) for TT in self._Cp_records.keys()]) result += self.Cp(Tmax)*(T - Tmax) return result + self.H_mag(T)
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_records.keys()]): result += self._Cp_records[str(Tmax)].H(T) if T <= Tmax: return result + self.H_mag(T) # Extrapolate beyond the upper limit by using a constant heat capacity. Tmax = max([float(TT) for TT in self._Cp_records.keys()]) result += self.Cp(Tmax)*(T - Tmax) return result + self.H_mag(T)
[ "Calculate", "the", "enthalpy", "of", "the", "compound", "phase", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L272-L293
[ "def", "H", "(", "self", ",", "T", ")", ":", "result", "=", "self", ".", "DHref", "for", "Tmax", "in", "sorted", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", ":", "result", "+=", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "H", "(", "T", ")", "if", "T", "<=", "Tmax", ":", "return", "result", "+", "self", ".", "H_mag", "(", "T", ")", "# Extrapolate beyond the upper limit by using a constant heat capacity.", "Tmax", "=", "max", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", "result", "+=", "self", ".", "Cp", "(", "Tmax", ")", "*", "(", "T", "-", "Tmax", ")", "return", "result", "+", "self", ".", "H_mag", "(", "T", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.H_mag
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), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N
auxi/tools/chemistry/thermochemistry.py
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), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: h = (-self._A_mag/tau + self._B_mag*(tau**3/2 + tau**9/15 + tau**15/40))/self._D_mag else: h = -(tau**-5/2 + tau**-15/21 + tau**-25/60)/self._D_mag return R*T*math.log(self.beta0_mag + 1)*h
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), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: h = (-self._A_mag/tau + self._B_mag*(tau**3/2 + tau**9/15 + tau**15/40))/self._D_mag else: h = -(tau**-5/2 + tau**-15/21 + tau**-25/60)/self._D_mag return R*T*math.log(self.beta0_mag + 1)*h
[ "Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "enthalpy", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L295-L316
[ "def", "H_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "h", "=", "(", "-", "self", ".", "_A_mag", "/", "tau", "+", "self", ".", "_B_mag", "*", "(", "tau", "**", "3", "/", "2", "+", "tau", "**", "9", "/", "15", "+", "tau", "**", "15", "/", "40", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "h", "=", "-", "(", "tau", "**", "-", "5", "/", "2", "+", "tau", "**", "-", "15", "/", "21", "+", "tau", "**", "-", "25", "/", "60", ")", "/", "self", ".", "_D_mag", "return", "R", "*", "T", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "h" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.S
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.
auxi/tools/chemistry/thermochemistry.py
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_records.keys()]): result += self._Cp_records[str(Tmax)].S(T) if T <= Tmax: return result + self.S_mag(T) # Extrapolate beyond the upper limit by using a constant heat capacity. Tmax = max([float(TT) for TT in self._Cp_records.keys()]) result += self.Cp(Tmax)*math.log(T / Tmax) return result + self.S_mag(T)
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_records.keys()]): result += self._Cp_records[str(Tmax)].S(T) if T <= Tmax: return result + self.S_mag(T) # Extrapolate beyond the upper limit by using a constant heat capacity. Tmax = max([float(TT) for TT in self._Cp_records.keys()]) result += self.Cp(Tmax)*math.log(T / Tmax) return result + self.S_mag(T)
[ "Calculate", "the", "entropy", "of", "the", "compound", "phase", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L318-L339
[ "def", "S", "(", "self", ",", "T", ")", ":", "result", "=", "self", ".", "Sref", "for", "Tmax", "in", "sorted", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", ":", "result", "+=", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "S", "(", "T", ")", "if", "T", "<=", "Tmax", ":", "return", "result", "+", "self", ".", "S_mag", "(", "T", ")", "# Extrapolate beyond the upper limit by using a constant heat capacity.", "Tmax", "=", "max", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", "result", "+=", "self", ".", "Cp", "(", "Tmax", ")", "*", "math", ".", "log", "(", "T", "/", "Tmax", ")", "return", "result", "+", "self", ".", "S_mag", "(", "T", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.S_mag
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), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N
auxi/tools/chemistry/thermochemistry.py
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), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: s = 1 - (self._B_mag*(2*tau**3/3 + 2*tau**9/27 + 2*tau**15/75)) / \ self._D_mag else: s = (2*tau**-5/5 + 2*tau**-15/45 + 2*tau**-25/125)/self._D_mag return -R*math.log(self.beta0_mag + 1)*s
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), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: s = 1 - (self._B_mag*(2*tau**3/3 + 2*tau**9/27 + 2*tau**15/75)) / \ self._D_mag else: s = (2*tau**-5/5 + 2*tau**-15/45 + 2*tau**-25/125)/self._D_mag return -R*math.log(self.beta0_mag + 1)*s
[ "Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "entropy", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L341-L362
[ "def", "S_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "s", "=", "1", "-", "(", "self", ".", "_B_mag", "*", "(", "2", "*", "tau", "**", "3", "/", "3", "+", "2", "*", "tau", "**", "9", "/", "27", "+", "2", "*", "tau", "**", "15", "/", "75", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "s", "=", "(", "2", "*", "tau", "**", "-", "5", "/", "5", "+", "2", "*", "tau", "**", "-", "15", "/", "45", "+", "2", "*", "tau", "**", "-", "25", "/", "125", ")", "/", "self", ".", "_D_mag", "return", "-", "R", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "s" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.G
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.
auxi/tools/chemistry/thermochemistry.py
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) for TT in self._Cp_records.keys()]): h = h + self._Cp_records[str(Tmax)].H(T) s = s + self._Cp_records[str(Tmax)].S(T) if T <= Tmax: return h - T * s + self.G_mag(T) # Extrapolate beyond the upper limit by using a constant heat capacity. Tmax = max([float(TT) for TT in self._Cp_records.keys()]) h = h + self.Cp(Tmax)*(T - Tmax) s = s + self.Cp(Tmax)*math.log(T / Tmax) return h - T * s + self.G_mag(T)
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) for TT in self._Cp_records.keys()]): h = h + self._Cp_records[str(Tmax)].H(T) s = s + self._Cp_records[str(Tmax)].S(T) if T <= Tmax: return h - T * s + self.G_mag(T) # Extrapolate beyond the upper limit by using a constant heat capacity. Tmax = max([float(TT) for TT in self._Cp_records.keys()]) h = h + self.Cp(Tmax)*(T - Tmax) s = s + self.Cp(Tmax)*math.log(T / Tmax) return h - T * s + self.G_mag(T)
[ "Calculate", "the", "heat", "capacity", "of", "the", "compound", "phase", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L364-L387
[ "def", "G", "(", "self", ",", "T", ")", ":", "h", "=", "self", ".", "DHref", "s", "=", "self", ".", "Sref", "for", "Tmax", "in", "sorted", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", ":", "h", "=", "h", "+", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "H", "(", "T", ")", "s", "=", "s", "+", "self", ".", "_Cp_records", "[", "str", "(", "Tmax", ")", "]", ".", "S", "(", "T", ")", "if", "T", "<=", "Tmax", ":", "return", "h", "-", "T", "*", "s", "+", "self", ".", "G_mag", "(", "T", ")", "# Extrapolate beyond the upper limit by using a constant heat capacity.", "Tmax", "=", "max", "(", "[", "float", "(", "TT", ")", "for", "TT", "in", "self", ".", "_Cp_records", ".", "keys", "(", ")", "]", ")", "h", "=", "h", "+", "self", ".", "Cp", "(", "Tmax", ")", "*", "(", "T", "-", "Tmax", ")", "s", "=", "s", "+", "self", ".", "Cp", "(", "Tmax", ")", "*", "math", ".", "log", "(", "T", "/", "Tmax", ")", "return", "h", "-", "T", "*", "s", "+", "self", ".", "G_mag", "(", "T", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Phase.G_mag
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, 15(4), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N
auxi/tools/chemistry/thermochemistry.py
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, 15(4), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: g = 1 - (self._A_mag/tau + self._B_mag*(tau**3/6 + tau**9/135 + tau**15/600)) /\ self._D_mag else: g = -(tau**-5/10 + tau**-15/315 + tau**-25/1500)/self._D_mag return R*T*math.log(self.beta0_mag + 1)*g
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, 15(4), 317–425. http://doi.org/10.1016/0364-5916(91)90030-N """ tau = T / self.Tc_mag if tau <= 1.0: g = 1 - (self._A_mag/tau + self._B_mag*(tau**3/6 + tau**9/135 + tau**15/600)) /\ self._D_mag else: g = -(tau**-5/10 + tau**-15/315 + tau**-25/1500)/self._D_mag return R*T*math.log(self.beta0_mag + 1)*g
[ "Calculate", "the", "phase", "s", "magnetic", "contribution", "to", "Gibbs", "energy", "at", "the", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L389-L411
[ "def", "G_mag", "(", "self", ",", "T", ")", ":", "tau", "=", "T", "/", "self", ".", "Tc_mag", "if", "tau", "<=", "1.0", ":", "g", "=", "1", "-", "(", "self", ".", "_A_mag", "/", "tau", "+", "self", ".", "_B_mag", "*", "(", "tau", "**", "3", "/", "6", "+", "tau", "**", "9", "/", "135", "+", "tau", "**", "15", "/", "600", ")", ")", "/", "self", ".", "_D_mag", "else", ":", "g", "=", "-", "(", "tau", "**", "-", "5", "/", "10", "+", "tau", "**", "-", "15", "/", "315", "+", "tau", "**", "-", "25", "/", "1500", ")", "/", "self", ".", "_D_mag", "return", "R", "*", "T", "*", "math", ".", "log", "(", "self", ".", "beta0_mag", "+", "1", ")", "*", "g" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Compound.Cp
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.
auxi/tools/chemistry/thermochemistry.py
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 self._phases: raise Exception("The phase '%s' was not found in compound '%s'." % (phase, self.formula)) return self._phases[phase].Cp(T)
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 self._phases: raise Exception("The phase '%s' was not found in compound '%s'." % (phase, self.formula)) return self._phases[phase].Cp(T)
[ "Calculate", "the", "heat", "capacity", "of", "a", "phase", "of", "the", "compound", "at", "a", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L471-L486
[ "def", "Cp", "(", "self", ",", "phase", ",", "T", ")", ":", "if", "phase", "not", "in", "self", ".", "_phases", ":", "raise", "Exception", "(", "\"The phase '%s' was not found in compound '%s'.\"", "%", "(", "phase", ",", "self", ".", "formula", ")", ")", "return", "self", ".", "_phases", "[", "phase", "]", ".", "Cp", "(", "T", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Compound.H
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.
auxi/tools/chemistry/thermochemistry.py
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._phases[phase].H(T) except KeyError: raise Exception("The phase '{}' was not found in compound '{}'." .format(phase, self.formula))
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._phases[phase].H(T) except KeyError: raise Exception("The phase '{}' was not found in compound '{}'." .format(phase, self.formula))
[ "Calculate", "the", "enthalpy", "of", "a", "phase", "of", "the", "compound", "at", "a", "specified", "temperature", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/chemistry/thermochemistry.py#L488-L503
[ "def", "H", "(", "self", ",", "phase", ",", "T", ")", ":", "try", ":", "return", "self", ".", "_phases", "[", "phase", "]", ".", "H", "(", "T", ")", "except", "KeyError", ":", "raise", "Exception", "(", "\"The phase '{}' was not found in compound '{}'.\"", ".", "format", "(", "phase", ",", "self", ".", "formula", ")", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
_create_polynomial_model
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. :param degree: polynomial degree. :param ds: the source data set. :param dss: dictionary of all datasets.
auxi/tools/materialphysicalproperties/gases.py
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. :param degree: polynomial degree. :param ds: the source data set. :param dss: dictionary of all datasets. """ ds_name = ds.name.split(".")[0].lower() file_name = f"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}" newmod = PolynomialModelT.create(ds, symbol, degree) newmod.plot(dss, _path(f"data/{file_name}.pdf"), False) newmod.write(_path(f"data/{file_name}.json"))
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. :param degree: polynomial degree. :param ds: the source data set. :param dss: dictionary of all datasets. """ ds_name = ds.name.split(".")[0].lower() file_name = f"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}" newmod = PolynomialModelT.create(ds, symbol, degree) newmod.plot(dss, _path(f"data/{file_name}.pdf"), False) newmod.write(_path(f"data/{file_name}.json"))
[ "Create", "a", "polynomial", "model", "to", "describe", "the", "specified", "property", "based", "on", "the", "specified", "data", "set", "and", "save", "it", "to", "a", ".", "json", "file", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/gases.py#L61-L81
[ "def", "_create_polynomial_model", "(", "name", ":", "str", ",", "symbol", ":", "str", ",", "degree", ":", "int", ",", "ds", ":", "DataSet", ",", "dss", ":", "dict", ")", ":", "ds_name", "=", "ds", ".", "name", ".", "split", "(", "\".\"", ")", "[", "0", "]", ".", "lower", "(", ")", "file_name", "=", "f\"{name.lower()}-{symbol.lower()}-polynomialmodelt-{ds_name}\"", "newmod", "=", "PolynomialModelT", ".", "create", "(", "ds", ",", "symbol", ",", "degree", ")", "newmod", ".", "plot", "(", "dss", ",", "_path", "(", "f\"data/{file_name}.pdf\"", ")", ",", "False", ")", "newmod", ".", "write", "(", "_path", "(", "f\"data/{file_name}.json\"", ")", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
_create_air
Create a dictionary of datasets and a material object for air. :return: (Material, {str, DataSet})
auxi/tools/materialphysicalproperties/gases.py
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"]) active_ds = "dataset-air-lienhard2018" # create polynomial models to describe material properties # comment it out after model creation is complete, so that it does not # run every time during use. # _create_polynomial_model(name, "Cp", 13, ds_dict[active_ds], ds_dict) # _create_polynomial_model(name, "k", 8, ds_dict[active_ds], ds_dict) # _create_polynomial_model(name, "mu", 8, ds_dict[active_ds], ds_dict) # _create_polynomial_model(name, "rho", 14, ds_dict[active_ds], ds_dict) # IgRhoT(mm, 101325.0).plot(ds_dict, _path(f"data/{namel}-rho-igrhot.pdf")) model_dict = { "rho": IgRhoT(mm, 101325.0), "beta": IgBetaT()} model_type = "polynomialmodelt" for property in ["Cp", "mu", "k"]: name = f"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json" model_dict[property] = PolynomialModelT.read(_path(name)) material = Material(name, StateOfMatter.gas, model_dict) return material, ds_dict
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"]) active_ds = "dataset-air-lienhard2018" # create polynomial models to describe material properties # comment it out after model creation is complete, so that it does not # run every time during use. # _create_polynomial_model(name, "Cp", 13, ds_dict[active_ds], ds_dict) # _create_polynomial_model(name, "k", 8, ds_dict[active_ds], ds_dict) # _create_polynomial_model(name, "mu", 8, ds_dict[active_ds], ds_dict) # _create_polynomial_model(name, "rho", 14, ds_dict[active_ds], ds_dict) # IgRhoT(mm, 101325.0).plot(ds_dict, _path(f"data/{namel}-rho-igrhot.pdf")) model_dict = { "rho": IgRhoT(mm, 101325.0), "beta": IgBetaT()} model_type = "polynomialmodelt" for property in ["Cp", "mu", "k"]: name = f"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json" model_dict[property] = PolynomialModelT.read(_path(name)) material = Material(name, StateOfMatter.gas, model_dict) return material, ds_dict
[ "Create", "a", "dictionary", "of", "datasets", "and", "a", "material", "object", "for", "air", "." ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/gases.py#L84-L120
[ "def", "_create_air", "(", ")", ":", "name", "=", "\"Air\"", "namel", "=", "name", ".", "lower", "(", ")", "mm", "=", "28.9645", "# g/mol", "ds_dict", "=", "_create_ds_dict", "(", "[", "\"dataset-air-lienhard2015\"", ",", "\"dataset-air-lienhard2018\"", "]", ")", "active_ds", "=", "\"dataset-air-lienhard2018\"", "# create polynomial models to describe material properties", "# comment it out after model creation is complete, so that it does not", "# run every time during use.", "# _create_polynomial_model(name, \"Cp\", 13, ds_dict[active_ds], ds_dict)", "# _create_polynomial_model(name, \"k\", 8, ds_dict[active_ds], ds_dict)", "# _create_polynomial_model(name, \"mu\", 8, ds_dict[active_ds], ds_dict)", "# _create_polynomial_model(name, \"rho\", 14, ds_dict[active_ds], ds_dict)", "# IgRhoT(mm, 101325.0).plot(ds_dict, _path(f\"data/{namel}-rho-igrhot.pdf\"))", "model_dict", "=", "{", "\"rho\"", ":", "IgRhoT", "(", "mm", ",", "101325.0", ")", ",", "\"beta\"", ":", "IgBetaT", "(", ")", "}", "model_type", "=", "\"polynomialmodelt\"", "for", "property", "in", "[", "\"Cp\"", ",", "\"mu\"", ",", "\"k\"", "]", ":", "name", "=", "f\"data/{namel}-{property.lower()}-{model_type}-{active_ds}.json\"", "model_dict", "[", "property", "]", "=", "PolynomialModelT", ".", "read", "(", "_path", "(", "name", ")", ")", "material", "=", "Material", "(", "name", ",", "StateOfMatter", ".", "gas", ",", "model_dict", ")", "return", "material", ",", "ds_dict" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
WilkeMuTx.calculate
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] dynamic viscosity The **state parameter contains the keyword argument(s) specified above that are used to describe the state of the material.
auxi/tools/materialphysicalproperties/gases.py
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] dynamic viscosity The **state parameter contains the keyword argument(s) specified above that are used to describe the state of the material. """ def phi(i, j, mu_i, mu_j): M_i = M(i) M_j = M(j) result = (1.0 + (mu_i / mu_j)**0.5 * (M_j / M_i)**0.25)**2.0 result /= (4.0 / sqrt(2.0)) result /= (1.0 + M_i / M_j)**0.5 return result T = state['T'] x = state['x'] # normalise mole fractions x_total = sum([ x for compound, x in x.items() if compound in materials]) x = { compound: x[compound]/x_total for compound in x.keys() if compound in materials} result = 0.0 # Pa.s mu = {i: materials[i].mu(T=T) for i in x.keys()} for i in x.keys(): sum_i = 0.0 for j in x.keys(): if j == i: continue sum_i += x[j] * phi(i, j, mu[i], mu[j]) result += x[i] * mu[i] / (x[i] + sum_i) return result
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] dynamic viscosity The **state parameter contains the keyword argument(s) specified above that are used to describe the state of the material. """ def phi(i, j, mu_i, mu_j): M_i = M(i) M_j = M(j) result = (1.0 + (mu_i / mu_j)**0.5 * (M_j / M_i)**0.25)**2.0 result /= (4.0 / sqrt(2.0)) result /= (1.0 + M_i / M_j)**0.5 return result T = state['T'] x = state['x'] # normalise mole fractions x_total = sum([ x for compound, x in x.items() if compound in materials]) x = { compound: x[compound]/x_total for compound in x.keys() if compound in materials} result = 0.0 # Pa.s mu = {i: materials[i].mu(T=T) for i in x.keys()} for i in x.keys(): sum_i = 0.0 for j in x.keys(): if j == i: continue sum_i += x[j] * phi(i, j, mu[i], mu[j]) result += x[i] * mu[i] / (x[i] + sum_i) return result
[ "Calculate", "dynamic", "viscosity", "at", "the", "specified", "temperature", "and", "composition", ":" ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/gases.py#L422-L469
[ "def", "calculate", "(", "self", ",", "*", "*", "state", ")", ":", "def", "phi", "(", "i", ",", "j", ",", "mu_i", ",", "mu_j", ")", ":", "M_i", "=", "M", "(", "i", ")", "M_j", "=", "M", "(", "j", ")", "result", "=", "(", "1.0", "+", "(", "mu_i", "/", "mu_j", ")", "**", "0.5", "*", "(", "M_j", "/", "M_i", ")", "**", "0.25", ")", "**", "2.0", "result", "/=", "(", "4.0", "/", "sqrt", "(", "2.0", ")", ")", "result", "/=", "(", "1.0", "+", "M_i", "/", "M_j", ")", "**", "0.5", "return", "result", "T", "=", "state", "[", "'T'", "]", "x", "=", "state", "[", "'x'", "]", "# normalise mole fractions", "x_total", "=", "sum", "(", "[", "x", "for", "compound", ",", "x", "in", "x", ".", "items", "(", ")", "if", "compound", "in", "materials", "]", ")", "x", "=", "{", "compound", ":", "x", "[", "compound", "]", "/", "x_total", "for", "compound", "in", "x", ".", "keys", "(", ")", "if", "compound", "in", "materials", "}", "result", "=", "0.0", "# Pa.s", "mu", "=", "{", "i", ":", "materials", "[", "i", "]", ".", "mu", "(", "T", "=", "T", ")", "for", "i", "in", "x", ".", "keys", "(", ")", "}", "for", "i", "in", "x", ".", "keys", "(", ")", ":", "sum_i", "=", "0.0", "for", "j", "in", "x", ".", "keys", "(", ")", ":", "if", "j", "==", "i", ":", "continue", "sum_i", "+=", "x", "[", "j", "]", "*", "phi", "(", "i", ",", "j", ",", "mu", "[", "i", "]", ",", "mu", "[", "j", "]", ")", "result", "+=", "x", "[", "i", "]", "*", "mu", "[", "i", "]", "/", "(", "x", "[", "i", "]", "+", "sum_i", ")", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
HerningZippererMuTx.calculate
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] dynamic viscosity The **state parameter contains the keyword argument(s) specified above that are used to describe the state of the material.
auxi/tools/materialphysicalproperties/gases.py
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] dynamic viscosity The **state parameter contains the keyword argument(s) specified above that are used to describe the state of the material. """ T = state['T'] x = state['x'] # normalise mole fractions x_total = sum([ x for compound, x in x.items() if compound in materials]) x = { compound: x[compound]/x_total for compound in x.keys() if compound in materials} mu = {i: materials[i].mu(T=T) for i in x.keys()} result = sum([mu[i] * x[i] * sqrt(M(i)) for i in x.keys()]) result /= sum([x[i] * sqrt(M(i)) for i in x.keys()]) return result
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] dynamic viscosity The **state parameter contains the keyword argument(s) specified above that are used to describe the state of the material. """ T = state['T'] x = state['x'] # normalise mole fractions x_total = sum([ x for compound, x in x.items() if compound in materials]) x = { compound: x[compound]/x_total for compound in x.keys() if compound in materials} mu = {i: materials[i].mu(T=T) for i in x.keys()} result = sum([mu[i] * x[i] * sqrt(M(i)) for i in x.keys()]) result /= sum([x[i] * sqrt(M(i)) for i in x.keys()]) return result
[ "Calculate", "dynamic", "viscosity", "at", "the", "specified", "temperature", "and", "composition", ":" ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/gases.py#L520-L552
[ "def", "calculate", "(", "self", ",", "*", "*", "state", ")", ":", "T", "=", "state", "[", "'T'", "]", "x", "=", "state", "[", "'x'", "]", "# normalise mole fractions", "x_total", "=", "sum", "(", "[", "x", "for", "compound", ",", "x", "in", "x", ".", "items", "(", ")", "if", "compound", "in", "materials", "]", ")", "x", "=", "{", "compound", ":", "x", "[", "compound", "]", "/", "x_total", "for", "compound", "in", "x", ".", "keys", "(", ")", "if", "compound", "in", "materials", "}", "mu", "=", "{", "i", ":", "materials", "[", "i", "]", ".", "mu", "(", "T", "=", "T", ")", "for", "i", "in", "x", ".", "keys", "(", ")", "}", "result", "=", "sum", "(", "[", "mu", "[", "i", "]", "*", "x", "[", "i", "]", "*", "sqrt", "(", "M", "(", "i", ")", ")", "for", "i", "in", "x", ".", "keys", "(", ")", "]", ")", "result", "/=", "sum", "(", "[", "x", "[", "i", "]", "*", "sqrt", "(", "M", "(", "i", ")", ")", "for", "i", "in", "x", ".", "keys", "(", ")", "]", ")", "return", "result" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
Report.render
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 is returned.
auxi/core/reporting.py
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 is returned. """ table = self._generate_table_() if format == ReportFormat.printout: print(tabulate(table, headers="firstrow", tablefmt="simple")) elif format == ReportFormat.latex: self._render_latex_(table) elif format == ReportFormat.txt: self._render_txt_(table) elif format == ReportFormat.csv: self._render_csv_(table) elif format == ReportFormat.string: return str(tabulate(table, headers="firstrow", tablefmt="simple")) elif format == ReportFormat.matplotlib: self._render_matplotlib_() elif format == ReportFormat.png: if self.output_path is None: self._render_matplotlib_() else: self._render_matplotlib_(True)
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 is returned. """ table = self._generate_table_() if format == ReportFormat.printout: print(tabulate(table, headers="firstrow", tablefmt="simple")) elif format == ReportFormat.latex: self._render_latex_(table) elif format == ReportFormat.txt: self._render_txt_(table) elif format == ReportFormat.csv: self._render_csv_(table) elif format == ReportFormat.string: return str(tabulate(table, headers="firstrow", tablefmt="simple")) elif format == ReportFormat.matplotlib: self._render_matplotlib_() elif format == ReportFormat.png: if self.output_path is None: self._render_matplotlib_() else: self._render_matplotlib_(True)
[ "Render", "the", "report", "in", "the", "specified", "format" ]
Ex-Mente/auxi.0
python
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/reporting.py#L53-L81
[ "def", "render", "(", "self", ",", "format", "=", "ReportFormat", ".", "printout", ")", ":", "table", "=", "self", ".", "_generate_table_", "(", ")", "if", "format", "==", "ReportFormat", ".", "printout", ":", "print", "(", "tabulate", "(", "table", ",", "headers", "=", "\"firstrow\"", ",", "tablefmt", "=", "\"simple\"", ")", ")", "elif", "format", "==", "ReportFormat", ".", "latex", ":", "self", ".", "_render_latex_", "(", "table", ")", "elif", "format", "==", "ReportFormat", ".", "txt", ":", "self", ".", "_render_txt_", "(", "table", ")", "elif", "format", "==", "ReportFormat", ".", "csv", ":", "self", ".", "_render_csv_", "(", "table", ")", "elif", "format", "==", "ReportFormat", ".", "string", ":", "return", "str", "(", "tabulate", "(", "table", ",", "headers", "=", "\"firstrow\"", ",", "tablefmt", "=", "\"simple\"", ")", ")", "elif", "format", "==", "ReportFormat", ".", "matplotlib", ":", "self", ".", "_render_matplotlib_", "(", ")", "elif", "format", "==", "ReportFormat", ".", "png", ":", "if", "self", ".", "output_path", "is", "None", ":", "self", ".", "_render_matplotlib_", "(", ")", "else", ":", "self", ".", "_render_matplotlib_", "(", "True", ")" ]
2dcdae74154f136f8ca58289fe5b20772f215046
valid
rgb_to_hex
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 representation of the input RGB value. :rtype: str
colorutils/convert.py
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 representation of the input RGB value. :rtype: str """ r, g, b = rgb return "#{0}{1}{2}".format(hex(int(r))[2:].zfill(2), hex(int(g))[2:].zfill(2), hex(int(b))[2:].zfill(2))
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 representation of the input RGB value. :rtype: str """ r, g, b = rgb return "#{0}{1}{2}".format(hex(int(r))[2:].zfill(2), hex(int(g))[2:].zfill(2), hex(int(b))[2:].zfill(2))
[ "Convert", "an", "RGB", "color", "representation", "to", "a", "HEX", "color", "representation", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L16-L29
[ "def", "rgb_to_hex", "(", "rgb", ")", ":", "r", ",", "g", ",", "b", "=", "rgb", "return", "\"#{0}{1}{2}\"", ".", "format", "(", "hex", "(", "int", "(", "r", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "2", ")", ",", "hex", "(", "int", "(", "g", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "2", ")", ",", "hex", "(", "int", "(", "b", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "2", ")", ")" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
rgb_to_yiq
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 representation of the input RGB value. :rtype: tuple
colorutils/convert.py
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 representation of the input RGB value. :rtype: tuple """ r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255 y = (0.299 * r) + (0.587 * g) + (0.114 * b) i = (0.596 * r) - (0.275 * g) - (0.321 * b) q = (0.212 * r) - (0.528 * g) + (0.311 * b) return round(y, 3), round(i, 3), round(q, 3)
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 representation of the input RGB value. :rtype: tuple """ r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255 y = (0.299 * r) + (0.587 * g) + (0.114 * b) i = (0.596 * r) - (0.275 * g) - (0.321 * b) q = (0.212 * r) - (0.528 * g) + (0.311 * b) return round(y, 3), round(i, 3), round(q, 3)
[ "Convert", "an", "RGB", "color", "representation", "to", "a", "YIQ", "color", "representation", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L50-L66
[ "def", "rgb_to_yiq", "(", "rgb", ")", ":", "r", ",", "g", ",", "b", "=", "rgb", "[", "0", "]", "/", "255", ",", "rgb", "[", "1", "]", "/", "255", ",", "rgb", "[", "2", "]", "/", "255", "y", "=", "(", "0.299", "*", "r", ")", "+", "(", "0.587", "*", "g", ")", "+", "(", "0.114", "*", "b", ")", "i", "=", "(", "0.596", "*", "r", ")", "-", "(", "0.275", "*", "g", ")", "-", "(", "0.321", "*", "b", ")", "q", "=", "(", "0.212", "*", "r", ")", "-", "(", "0.528", "*", "g", ")", "+", "(", "0.311", "*", "b", ")", "return", "round", "(", "y", ",", "3", ")", ",", "round", "(", "i", ",", "3", ")", ",", "round", "(", "q", ",", "3", ")" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
rgb_to_hsv
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 representation of the input RGB value. :rtype: tuple
colorutils/convert.py
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 representation of the input RGB value. :rtype: tuple """ r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255 _min = min(r, g, b) _max = max(r, g, b) v = _max delta = _max - _min if _max == 0: return 0, 0, v s = delta / _max if delta == 0: delta = 1 if r == _max: h = 60 * (((g - b) / delta) % 6) elif g == _max: h = 60 * (((b - r) / delta) + 2) else: h = 60 * (((r - g) / delta) + 4) return round(h, 3), round(s, 3), round(v, 3)
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 representation of the input RGB value. :rtype: tuple """ r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255 _min = min(r, g, b) _max = max(r, g, b) v = _max delta = _max - _min if _max == 0: return 0, 0, v s = delta / _max if delta == 0: delta = 1 if r == _max: h = 60 * (((g - b) / delta) % 6) elif g == _max: h = 60 * (((b - r) / delta) + 2) else: h = 60 * (((r - g) / delta) + 4) return round(h, 3), round(s, 3), round(v, 3)
[ "Convert", "an", "RGB", "color", "representation", "to", "an", "HSV", "color", "representation", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L69-L104
[ "def", "rgb_to_hsv", "(", "rgb", ")", ":", "r", ",", "g", ",", "b", "=", "rgb", "[", "0", "]", "/", "255", ",", "rgb", "[", "1", "]", "/", "255", ",", "rgb", "[", "2", "]", "/", "255", "_min", "=", "min", "(", "r", ",", "g", ",", "b", ")", "_max", "=", "max", "(", "r", ",", "g", ",", "b", ")", "v", "=", "_max", "delta", "=", "_max", "-", "_min", "if", "_max", "==", "0", ":", "return", "0", ",", "0", ",", "v", "s", "=", "delta", "/", "_max", "if", "delta", "==", "0", ":", "delta", "=", "1", "if", "r", "==", "_max", ":", "h", "=", "60", "*", "(", "(", "(", "g", "-", "b", ")", "/", "delta", ")", "%", "6", ")", "elif", "g", "==", "_max", ":", "h", "=", "60", "*", "(", "(", "(", "b", "-", "r", ")", "/", "delta", ")", "+", "2", ")", "else", ":", "h", "=", "60", "*", "(", "(", "(", "r", "-", "g", ")", "/", "delta", ")", "+", "4", ")", "return", "round", "(", "h", ",", "3", ")", ",", "round", "(", "s", ",", "3", ")", ",", "round", "(", "v", ",", "3", ")" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
hex_to_rgb
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
colorutils/convert.py
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.strip('#') n = len(_hex) // 3 if len(_hex) == 3: r = int(_hex[:n] * 2, 16) g = int(_hex[n:2 * n] * 2, 16) b = int(_hex[2 * n:3 * n] * 2, 16) else: r = int(_hex[:n], 16) g = int(_hex[n:2 * n], 16) b = int(_hex[2 * n:3 * n], 16) return r, g, b
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.strip('#') n = len(_hex) // 3 if len(_hex) == 3: r = int(_hex[:n] * 2, 16) g = int(_hex[n:2 * n] * 2, 16) b = int(_hex[2 * n:3 * n] * 2, 16) else: r = int(_hex[:n], 16) g = int(_hex[n:2 * n], 16) b = int(_hex[2 * n:3 * n], 16) return r, g, b
[ "Convert", "a", "HEX", "color", "representation", "to", "an", "RGB", "color", "representation", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L112-L132
[ "def", "hex_to_rgb", "(", "_hex", ")", ":", "_hex", "=", "_hex", ".", "strip", "(", "'#'", ")", "n", "=", "len", "(", "_hex", ")", "//", "3", "if", "len", "(", "_hex", ")", "==", "3", ":", "r", "=", "int", "(", "_hex", "[", ":", "n", "]", "*", "2", ",", "16", ")", "g", "=", "int", "(", "_hex", "[", "n", ":", "2", "*", "n", "]", "*", "2", ",", "16", ")", "b", "=", "int", "(", "_hex", "[", "2", "*", "n", ":", "3", "*", "n", "]", "*", "2", ",", "16", ")", "else", ":", "r", "=", "int", "(", "_hex", "[", ":", "n", "]", ",", "16", ")", "g", "=", "int", "(", "_hex", "[", "n", ":", "2", "*", "n", "]", ",", "16", ")", "b", "=", "int", "(", "_hex", "[", "2", "*", "n", ":", "3", "*", "n", "]", ",", "16", ")", "return", "r", ",", "g", ",", "b" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
yiq_to_rgb
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 representation of the input YIQ value. :rtype: tuple
colorutils/convert.py
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 representation of the input YIQ value. :rtype: tuple """ y, i, q = yiq r = y + (0.956 * i) + (0.621 * q) g = y - (0.272 * i) - (0.647 * q) b = y - (1.108 * i) + (1.705 * q) r = 1 if r > 1 else max(0, r) g = 1 if g > 1 else max(0, g) b = 1 if b > 1 else max(0, b) return round(r * 255, 3), round(g * 255, 3), round(b * 255, 3)
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 representation of the input YIQ value. :rtype: tuple """ y, i, q = yiq r = y + (0.956 * i) + (0.621 * q) g = y - (0.272 * i) - (0.647 * q) b = y - (1.108 * i) + (1.705 * q) r = 1 if r > 1 else max(0, r) g = 1 if g > 1 else max(0, g) b = 1 if b > 1 else max(0, b) return round(r * 255, 3), round(g * 255, 3), round(b * 255, 3)
[ "Convert", "a", "YIQ", "color", "representation", "to", "an", "RGB", "color", "representation", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L249-L270
[ "def", "yiq_to_rgb", "(", "yiq", ")", ":", "y", ",", "i", ",", "q", "=", "yiq", "r", "=", "y", "+", "(", "0.956", "*", "i", ")", "+", "(", "0.621", "*", "q", ")", "g", "=", "y", "-", "(", "0.272", "*", "i", ")", "-", "(", "0.647", "*", "q", ")", "b", "=", "y", "-", "(", "1.108", "*", "i", ")", "+", "(", "1.705", "*", "q", ")", "r", "=", "1", "if", "r", ">", "1", "else", "max", "(", "0", ",", "r", ")", "g", "=", "1", "if", "g", ">", "1", "else", "max", "(", "0", ",", "g", ")", "b", "=", "1", "if", "b", ">", "1", "else", "max", "(", "0", ",", "b", ")", "return", "round", "(", "r", "*", "255", ",", "3", ")", ",", "round", "(", "g", "*", "255", ",", "3", ")", ",", "round", "(", "b", "*", "255", ",", "3", ")" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
hsv_to_rgb
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 of the input HSV value. :rtype: tuple
colorutils/convert.py
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 of the input HSV value. :rtype: tuple """ h, s, v = hsv c = v * s h /= 60 x = c * (1 - abs((h % 2) - 1)) m = v - c if h < 1: res = (c, x, 0) elif h < 2: res = (x, c, 0) elif h < 3: res = (0, c, x) elif h < 4: res = (0, x, c) elif h < 5: res = (x, 0, c) elif h < 6: res = (c, 0, x) else: raise ColorException("Unable to convert from HSV to RGB") r, g, b = res return round((r + m)*255, 3), round((g + m)*255, 3), round((b + m)*255, 3)
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 of the input HSV value. :rtype: tuple """ h, s, v = hsv c = v * s h /= 60 x = c * (1 - abs((h % 2) - 1)) m = v - c if h < 1: res = (c, x, 0) elif h < 2: res = (x, c, 0) elif h < 3: res = (0, c, x) elif h < 4: res = (0, x, c) elif h < 5: res = (x, 0, c) elif h < 6: res = (c, 0, x) else: raise ColorException("Unable to convert from HSV to RGB") r, g, b = res return round((r + m)*255, 3), round((g + m)*255, 3), round((b + m)*255, 3)
[ "Convert", "an", "HSV", "color", "representation", "to", "an", "RGB", "color", "representation", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/convert.py#L323-L357
[ "def", "hsv_to_rgb", "(", "hsv", ")", ":", "h", ",", "s", ",", "v", "=", "hsv", "c", "=", "v", "*", "s", "h", "/=", "60", "x", "=", "c", "*", "(", "1", "-", "abs", "(", "(", "h", "%", "2", ")", "-", "1", ")", ")", "m", "=", "v", "-", "c", "if", "h", "<", "1", ":", "res", "=", "(", "c", ",", "x", ",", "0", ")", "elif", "h", "<", "2", ":", "res", "=", "(", "x", ",", "c", ",", "0", ")", "elif", "h", "<", "3", ":", "res", "=", "(", "0", ",", "c", ",", "x", ")", "elif", "h", "<", "4", ":", "res", "=", "(", "0", ",", "x", ",", "c", ")", "elif", "h", "<", "5", ":", "res", "=", "(", "x", ",", "0", ",", "c", ")", "elif", "h", "<", "6", ":", "res", "=", "(", "c", ",", "0", ",", "x", ")", "else", ":", "raise", "ColorException", "(", "\"Unable to convert from HSV to RGB\"", ")", "r", ",", "g", ",", "b", "=", "res", "return", "round", "(", "(", "r", "+", "m", ")", "*", "255", ",", "3", ")", ",", "round", "(", "(", "g", "+", "m", ")", "*", "255", ",", "3", ")", ",", "round", "(", "(", "b", "+", "m", ")", "*", "255", ",", "3", ")" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
offset_random_rgb
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:
colorutils/colorutils.py
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): base_val = ((r + g + b) / 3) + 1 # Add one to eliminate case where the base value would otherwise be 0 new_val = base_val + (random.random() * rgb_max_val / 5) # Randomly offset with an arbitrary multiplier ratio = new_val / base_val results.append((min(int(r*ratio), rgb_max_val), min(int(g*ratio), rgb_max_val), min(int(b*ratio), rgb_max_val))) return results[0] if len(results) > 1 else results
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): base_val = ((r + g + b) / 3) + 1 # Add one to eliminate case where the base value would otherwise be 0 new_val = base_val + (random.random() * rgb_max_val / 5) # Randomly offset with an arbitrary multiplier ratio = new_val / base_val results.append((min(int(r*ratio), rgb_max_val), min(int(g*ratio), rgb_max_val), min(int(b*ratio), rgb_max_val))) return results[0] if len(results) > 1 else results
[ "Given", "a", "seed", "color", "generate", "a", "specified", "number", "of", "random", "colors", "(", "1", "color", "by", "default", ")", "determined", "by", "a", "randomized", "offset", "from", "the", "seed", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/colorutils.py#L230-L248
[ "def", "offset_random_rgb", "(", "seed", ",", "amount", "=", "1", ")", ":", "r", ",", "g", ",", "b", "=", "seed", "results", "=", "[", "]", "for", "_", "in", "range", "(", "amount", ")", ":", "base_val", "=", "(", "(", "r", "+", "g", "+", "b", ")", "/", "3", ")", "+", "1", "# Add one to eliminate case where the base value would otherwise be 0", "new_val", "=", "base_val", "+", "(", "random", ".", "random", "(", ")", "*", "rgb_max_val", "/", "5", ")", "# Randomly offset with an arbitrary multiplier", "ratio", "=", "new_val", "/", "base_val", "results", ".", "append", "(", "(", "min", "(", "int", "(", "r", "*", "ratio", ")", ",", "rgb_max_val", ")", ",", "min", "(", "int", "(", "g", "*", "ratio", ")", ",", "rgb_max_val", ")", ",", "min", "(", "int", "(", "b", "*", "ratio", ")", ",", "rgb_max_val", ")", ")", ")", "return", "results", "[", "0", "]", "if", "len", "(", "results", ")", ">", "1", "else", "results" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
color_run
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 ending the run :param step_count: The number of colors to have between the start and end color :param inclusive: Flag determining whether to include start and end values in run (default True) :param to_color: Flag indicating return values should be Color objects (default True) :return: List of colors between the start and end color :rtype: list
colorutils/colorutils.py
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 ending the run :param step_count: The number of colors to have between the start and end color :param inclusive: Flag determining whether to include start and end values in run (default True) :param to_color: Flag indicating return values should be Color objects (default True) :return: List of colors between the start and end color :rtype: list """ if isinstance(start_color, Color): start_color = start_color.rgb if isinstance(end_color, Color): end_color = end_color.rgb step = tuple((end_color[i] - start_color[i])/step_count for i in range(3)) add = lambda x, y: tuple(sum(z) for z in zip(x, y)) mult = lambda x, y: tuple(y * z for z in x) run = [add(start_color, mult(step, i)) for i in range(1, step_count)] if inclusive: run = [start_color] + run + [end_color] return run if not to_color else [Color(c) for c in run]
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 ending the run :param step_count: The number of colors to have between the start and end color :param inclusive: Flag determining whether to include start and end values in run (default True) :param to_color: Flag indicating return values should be Color objects (default True) :return: List of colors between the start and end color :rtype: list """ if isinstance(start_color, Color): start_color = start_color.rgb if isinstance(end_color, Color): end_color = end_color.rgb step = tuple((end_color[i] - start_color[i])/step_count for i in range(3)) add = lambda x, y: tuple(sum(z) for z in zip(x, y)) mult = lambda x, y: tuple(y * z for z in x) run = [add(start_color, mult(step, i)) for i in range(1, step_count)] if inclusive: run = [start_color] + run + [end_color] return run if not to_color else [Color(c) for c in run]
[ "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", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/colorutils.py#L280-L309
[ "def", "color_run", "(", "start_color", ",", "end_color", ",", "step_count", ",", "inclusive", "=", "True", ",", "to_color", "=", "True", ")", ":", "if", "isinstance", "(", "start_color", ",", "Color", ")", ":", "start_color", "=", "start_color", ".", "rgb", "if", "isinstance", "(", "end_color", ",", "Color", ")", ":", "end_color", "=", "end_color", ".", "rgb", "step", "=", "tuple", "(", "(", "end_color", "[", "i", "]", "-", "start_color", "[", "i", "]", ")", "/", "step_count", "for", "i", "in", "range", "(", "3", ")", ")", "add", "=", "lambda", "x", ",", "y", ":", "tuple", "(", "sum", "(", "z", ")", "for", "z", "in", "zip", "(", "x", ",", "y", ")", ")", "mult", "=", "lambda", "x", ",", "y", ":", "tuple", "(", "y", "*", "z", "for", "z", "in", "x", ")", "run", "=", "[", "add", "(", "start_color", ",", "mult", "(", "step", ",", "i", ")", ")", "for", "i", "in", "range", "(", "1", ",", "step_count", ")", "]", "if", "inclusive", ":", "run", "=", "[", "start_color", "]", "+", "run", "+", "[", "end_color", "]", "return", "run", "if", "not", "to_color", "else", "[", "Color", "(", "c", ")", "for", "c", "in", "run", "]" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
text_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. :param background: :param dark_color: :param light_color: :return:
colorutils/colorutils.py
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 values. :param background: :param dark_color: :param light_color: :return: """ max_y = rgb_to_yiq(rgb_max)[0] return light_color if rgb_to_yiq(background)[0] <= max_y / 2 else dark_color
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 values. :param background: :param dark_color: :param light_color: :return: """ max_y = rgb_to_yiq(rgb_max)[0] return light_color if rgb_to_yiq(background)[0] <= max_y / 2 else dark_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", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/colorutils.py#L312-L324
[ "def", "text_color", "(", "background", ",", "dark_color", "=", "rgb_min", ",", "light_color", "=", "rgb_max", ")", ":", "max_y", "=", "rgb_to_yiq", "(", "rgb_max", ")", "[", "0", "]", "return", "light_color", "if", "rgb_to_yiq", "(", "background", ")", "[", "0", "]", "<=", "max_y", "/", "2", "else", "dark_color" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
minify_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:
colorutils/colorutils.py
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 == 3: return _hex elif size == 6: if _hex[1] == _hex[2] and _hex[3] == _hex[4] and _hex[5] == _hex[6]: return _hex[0::2] else: return _hex else: raise ColorException('Unexpected HEX size when minifying: {}'.format(size))
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 == 3: return _hex elif size == 6: if _hex[1] == _hex[2] and _hex[3] == _hex[4] and _hex[5] == _hex[6]: return _hex[0::2] else: return _hex else: raise ColorException('Unexpected HEX size when minifying: {}'.format(size))
[ "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", "." ]
edaniszewski/colorutils
python
https://github.com/edaniszewski/colorutils/blob/bdff54091cb5d62aa8628ce39bc09abd40fb8dd0/colorutils/colorutils.py#L327-L344
[ "def", "minify_hex", "(", "_hex", ")", ":", "size", "=", "len", "(", "_hex", ".", "strip", "(", "'#'", ")", ")", "if", "size", "==", "3", ":", "return", "_hex", "elif", "size", "==", "6", ":", "if", "_hex", "[", "1", "]", "==", "_hex", "[", "2", "]", "and", "_hex", "[", "3", "]", "==", "_hex", "[", "4", "]", "and", "_hex", "[", "5", "]", "==", "_hex", "[", "6", "]", ":", "return", "_hex", "[", "0", ":", ":", "2", "]", "else", ":", "return", "_hex", "else", ":", "raise", "ColorException", "(", "'Unexpected HEX size when minifying: {}'", ".", "format", "(", "size", ")", ")" ]
bdff54091cb5d62aa8628ce39bc09abd40fb8dd0
valid
ForgiveDB.get
Get key value, return default if key doesn't exist
forgive/db.py
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)
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)
[ "Get", "key", "value", "return", "default", "if", "key", "doesn", "t", "exist" ]
hui-z/ForgiveDB
python
https://github.com/hui-z/ForgiveDB/blob/cc94e87377a230e23a8e55dffe07047c34c33d6e/forgive/db.py#L29-L35
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "self", ".", "in_memory", ":", "return", "self", ".", "_memory_db", ".", "get", "(", "key", ",", "default", ")", "else", ":", "db", "=", "self", ".", "_read_file", "(", ")", "return", "db", ".", "get", "(", "key", ",", "default", ")" ]
cc94e87377a230e23a8e55dffe07047c34c33d6e
valid
ForgiveDB.set
Set key value
forgive/db.py
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))
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))
[ "Set", "key", "value" ]
hui-z/ForgiveDB
python
https://github.com/hui-z/ForgiveDB/blob/cc94e87377a230e23a8e55dffe07047c34c33d6e/forgive/db.py#L37-L45
[ "def", "set", "(", "self", ",", "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", ")", ")" ]
cc94e87377a230e23a8e55dffe07047c34c33d6e
valid
ForgiveDB._read_file
read the db file content :rtype: dict
forgive/db.py
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)
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)
[ "read", "the", "db", "file", "content", ":", "rtype", ":", "dict" ]
hui-z/ForgiveDB
python
https://github.com/hui-z/ForgiveDB/blob/cc94e87377a230e23a8e55dffe07047c34c33d6e/forgive/db.py#L47-L56
[ "def", "_read_file", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "db_path", ")", ":", "return", "{", "}", "with", "open", "(", "self", ".", "db_path", ",", "'r'", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "return", "json", ".", "loads", "(", "content", ")" ]
cc94e87377a230e23a8e55dffe07047c34c33d6e
valid
attrs_sqlalchemy
A class decorator that adds ``__repr__``, ``__eq__``, ``__cmp__``, and ``__hash__`` methods according to the fields defined on the SQLAlchemy model class.
attrs_sqlalchemy.py
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')) these = { name: attr.ib() # `__mapper__.columns` is a dictionary mapping field names on the # model class to table columns. SQLAlchemy provides many ways to # access the fields/columns, but this works at the time the class # decorator is called: # # - We can't use `cls.__table__.columns` because that directly maps # the column names rather than the field names on the model. For # example, given `_my_field = Column('field', ...)`, # `__table__.columns` will contain 'field' rather than '_my_field'. # # - We can't use `cls.__dict__`, where values are # `InstrumentedAttribute`s, because that includes relationships, # synonyms, and other features. # # - We can't use `cls.__mapper__.column_attrs` # (or `sqlalchemy.inspect`) because they will attempt to # initialize mappers for all of the classes in the registry, # which won't be ready yet. for name in inspect(cls).columns.keys() } return attr.s(cls, these=these, init=False) # `maybe_cls` depends on the usage of the decorator. It's a class if it's # used as `@attrs_sqlalchemy` but `None` if it's used as # `@attrs_sqlalchemy()` # ref: https://github.com/hynek/attrs/blob/15.2.0/src/attr/_make.py#L195 if maybe_cls is None: return wrap else: return wrap(maybe_cls)
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')) these = { name: attr.ib() # `__mapper__.columns` is a dictionary mapping field names on the # model class to table columns. SQLAlchemy provides many ways to # access the fields/columns, but this works at the time the class # decorator is called: # # - We can't use `cls.__table__.columns` because that directly maps # the column names rather than the field names on the model. For # example, given `_my_field = Column('field', ...)`, # `__table__.columns` will contain 'field' rather than '_my_field'. # # - We can't use `cls.__dict__`, where values are # `InstrumentedAttribute`s, because that includes relationships, # synonyms, and other features. # # - We can't use `cls.__mapper__.column_attrs` # (or `sqlalchemy.inspect`) because they will attempt to # initialize mappers for all of the classes in the registry, # which won't be ready yet. for name in inspect(cls).columns.keys() } return attr.s(cls, these=these, init=False) # `maybe_cls` depends on the usage of the decorator. It's a class if it's # used as `@attrs_sqlalchemy` but `None` if it's used as # `@attrs_sqlalchemy()` # ref: https://github.com/hynek/attrs/blob/15.2.0/src/attr/_make.py#L195 if maybe_cls is None: return wrap else: return wrap(maybe_cls)
[ "A", "class", "decorator", "that", "adds", "__repr__", "__eq__", "__cmp__", "and", "__hash__", "methods", "according", "to", "the", "fields", "defined", "on", "the", "SQLAlchemy", "model", "class", "." ]
GoodRx/attrs_sqlalchemy
python
https://github.com/GoodRx/attrs_sqlalchemy/blob/907eb269f1a0a1e4647ede5b44eb7a9210d954ae/attrs_sqlalchemy.py#L29-L69
[ "def", "attrs_sqlalchemy", "(", "maybe_cls", "=", "None", ")", ":", "def", "wrap", "(", "cls", ")", ":", "warnings", ".", "warn", "(", "UserWarning", "(", "'attrs_sqlalchemy is deprecated'", ")", ")", "these", "=", "{", "name", ":", "attr", ".", "ib", "(", ")", "# `__mapper__.columns` is a dictionary mapping field names on the", "# model class to table columns. SQLAlchemy provides many ways to", "# access the fields/columns, but this works at the time the class", "# decorator is called:", "#", "# - We can't use `cls.__table__.columns` because that directly maps", "# the column names rather than the field names on the model. For", "# example, given `_my_field = Column('field', ...)`,", "# `__table__.columns` will contain 'field' rather than '_my_field'.", "#", "# - We can't use `cls.__dict__`, where values are", "# `InstrumentedAttribute`s, because that includes relationships,", "# synonyms, and other features.", "#", "# - We can't use `cls.__mapper__.column_attrs`", "# (or `sqlalchemy.inspect`) because they will attempt to", "# initialize mappers for all of the classes in the registry,", "# which won't be ready yet.", "for", "name", "in", "inspect", "(", "cls", ")", ".", "columns", ".", "keys", "(", ")", "}", "return", "attr", ".", "s", "(", "cls", ",", "these", "=", "these", ",", "init", "=", "False", ")", "# `maybe_cls` depends on the usage of the decorator. It's a class if it's", "# used as `@attrs_sqlalchemy` but `None` if it's used as", "# `@attrs_sqlalchemy()`", "# ref: https://github.com/hynek/attrs/blob/15.2.0/src/attr/_make.py#L195", "if", "maybe_cls", "is", "None", ":", "return", "wrap", "else", ":", "return", "wrap", "(", "maybe_cls", ")" ]
907eb269f1a0a1e4647ede5b44eb7a9210d954ae
valid
paginate_link_tag
Create an A-HREF tag that points to another page usable in paginate.
ps_alchemy/paginator.py
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)
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)
[ "Create", "an", "A", "-", "HREF", "tag", "that", "points", "to", "another", "page", "usable", "in", "paginate", "." ]
sacrud/ps_alchemy
python
https://github.com/sacrud/ps_alchemy/blob/4f042329eb4643bf26fa2540df277fa94c5265ec/ps_alchemy/paginator.py#L15-L22
[ "def", "paginate_link_tag", "(", "item", ")", ":", "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", ")" ]
4f042329eb4643bf26fa2540df277fa94c5265ec
valid
EcoNetApiInterface.set_state
Set a devices state.
src/pyeconet/api.py
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 != '202': _LOGGER.error("State not accepted. " + status_code) return False
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 != '202': _LOGGER.error("State not accepted. " + status_code) return False
[ "Set", "a", "devices", "state", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L45-L56
[ "def", "set_state", "(", "_id", ",", "body", ")", ":", "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", "!=", "'202'", ":", "_LOGGER", ".", "error", "(", "\"State not accepted. \"", "+", "status_code", ")", "return", "False" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.get_modes
Pull a water heater's modes from the API.
src/pyeconet/api.py
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.") return False return arequest.json()
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.") return False return arequest.json()
[ "Pull", "a", "water", "heater", "s", "modes", "from", "the", "API", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L59-L69
[ "def", "get_modes", "(", "_id", ")", ":", "url", "=", "MODES_URL", "%", "_id", "arequest", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "return", "arequest", ".", "json", "(", ")" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.get_usage
Pull a water heater's usage report from the API.
src/pyeconet/api.py
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.") return False try: return arequest.json() except ValueError: _LOGGER.info("Failed to get usage. Not supported by unit?") return None
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.") return False try: return arequest.json() except ValueError: _LOGGER.info("Failed to get usage. Not supported by unit?") return None
[ "Pull", "a", "water", "heater", "s", "usage", "report", "from", "the", "API", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L72-L86
[ "def", "get_usage", "(", "_id", ")", ":", "url", "=", "USAGE_URL", "%", "_id", "arequest", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGER", ".", "error", "(", "\"Token expired.\"", ")", "return", "False", "try", ":", "return", "arequest", ".", "json", "(", ")", "except", "ValueError", ":", "_LOGGER", ".", "info", "(", "\"Failed to get usage. Not supported by unit?\"", ")", "return", "None" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.get_device
Pull a device from the API.
src/pyeconet/api.py
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 return arequest.json()
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 return arequest.json()
[ "Pull", "a", "device", "from", "the", "API", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L89-L99
[ "def", "get_device", "(", "_id", ")", ":", "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", "return", "arequest", ".", "json", "(", ")" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.get_locations
Pull the accounts locations.
src/pyeconet/api.py
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.json()
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.json()
[ "Pull", "the", "accounts", "locations", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L102-L111
[ "def", "get_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", ".", "json", "(", ")" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.get_vacations
Pull the accounts vacations.
src/pyeconet/api.py
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.json()
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.json()
[ "Pull", "the", "accounts", "vacations", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L114-L123
[ "def", "get_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", ".", "json", "(", ")" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.create_vacation
Create a vacation.
src/pyeconet/api.py
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) _LOGGER.error(arequest.json()) return False return arequest.json()
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) _LOGGER.error(arequest.json()) return False return arequest.json()
[ "Create", "a", "vacation", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L126-L136
[ "def", "create_vacation", "(", "body", ")", ":", "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", ")", "_LOGGER", ".", "error", "(", "arequest", ".", "json", "(", ")", ")", "return", "False", "return", "arequest", ".", "json", "(", ")" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface.delete_vacation
Delete a vacation by ID.
src/pyeconet/api.py
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) return False return True
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) return False return True
[ "Delete", "a", "vacation", "by", "ID", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L139-L148
[ "def", "delete_vacation", "(", "_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", ")", "return", "False", "return", "True" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
EcoNetApiInterface._authenticate
Authenticate with the API and return an authentication token.
src/pyeconet/api.py
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, headers=BASIC_HEADERS) status = arequest.status_code if status != 200: _LOGGER.error("Authentication request failed, please check credintials. " + str(status)) return False response = arequest.json() _LOGGER.debug(str(response)) self.token = response.get("access_token") self.refresh_token = response.get("refresh_token") _auth = HEADERS.get("Authorization") _auth = _auth % self.token HEADERS["Authorization"] = _auth _LOGGER.info("Authentication was successful, token set.") return True
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, headers=BASIC_HEADERS) status = arequest.status_code if status != 200: _LOGGER.error("Authentication request failed, please check credintials. " + str(status)) return False response = arequest.json() _LOGGER.debug(str(response)) self.token = response.get("access_token") self.refresh_token = response.get("refresh_token") _auth = HEADERS.get("Authorization") _auth = _auth % self.token HEADERS["Authorization"] = _auth _LOGGER.info("Authentication was successful, token set.") return True
[ "Authenticate", "with", "the", "API", "and", "return", "an", "authentication", "token", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L150-L169
[ "def", "_authenticate", "(", "self", ")", ":", "auth_url", "=", "BASE_URL", "+", "\"/auth/token\"", "payload", "=", "{", "'username'", ":", "self", ".", "email", ",", "'password'", ":", "self", ".", "password", ",", "'grant_type'", ":", "'password'", "}", "arequest", "=", "requests", ".", "post", "(", "auth_url", ",", "data", "=", "payload", ",", "headers", "=", "BASIC_HEADERS", ")", "status", "=", "arequest", ".", "status_code", "if", "status", "!=", "200", ":", "_LOGGER", ".", "error", "(", "\"Authentication request failed, please check credintials. \"", "+", "str", "(", "status", ")", ")", "return", "False", "response", "=", "arequest", ".", "json", "(", ")", "_LOGGER", ".", "debug", "(", "str", "(", "response", ")", ")", "self", ".", "token", "=", "response", ".", "get", "(", "\"access_token\"", ")", "self", ".", "refresh_token", "=", "response", ".", "get", "(", "\"refresh_token\"", ")", "_auth", "=", "HEADERS", ".", "get", "(", "\"Authorization\"", ")", "_auth", "=", "_auth", "%", "self", ".", "token", "HEADERS", "[", "\"Authorization\"", "]", "=", "_auth", "_LOGGER", ".", "info", "(", "\"Authentication was successful, token set.\"", ")", "return", "True" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
PyEcoNet.get_water_heaters
Return a list of water heater devices. Parses the response from the locations endpoint in to a pyeconet.WaterHeater.
src/pyeconet/api.py
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 device in location.get("equipment"): if device.get("type") == "Water Heater": water_heater_modes = self.api_interface.get_modes(device.get("id")) water_heater_usage = self.api_interface.get_usage(device.get("id")) water_heater = self.api_interface.get_device(device.get("id")) vacations = self.api_interface.get_vacations() device_vacations = [] for vacation in vacations: for equipment in vacation.get("participatingEquipment"): if equipment.get("id") == water_heater.get("id"): device_vacations.append(EcoNetVacation(vacation, self.api_interface)) water_heaters.append(EcoNetWaterHeater(water_heater, water_heater_modes, water_heater_usage, _location_id, device_vacations, self.api_interface)) return water_heaters
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 device in location.get("equipment"): if device.get("type") == "Water Heater": water_heater_modes = self.api_interface.get_modes(device.get("id")) water_heater_usage = self.api_interface.get_usage(device.get("id")) water_heater = self.api_interface.get_device(device.get("id")) vacations = self.api_interface.get_vacations() device_vacations = [] for vacation in vacations: for equipment in vacation.get("participatingEquipment"): if equipment.get("id") == water_heater.get("id"): device_vacations.append(EcoNetVacation(vacation, self.api_interface)) water_heaters.append(EcoNetWaterHeater(water_heater, water_heater_modes, water_heater_usage, _location_id, device_vacations, self.api_interface)) return water_heaters
[ "Return", "a", "list", "of", "water", "heater", "devices", "." ]
w1ll1am23/pyeconet
python
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L183-L207
[ "def", "get_water_heaters", "(", "self", ")", ":", "water_heaters", "=", "[", "]", "for", "location", "in", "self", ".", "locations", ":", "_location_id", "=", "location", ".", "get", "(", "\"id\"", ")", "for", "device", "in", "location", ".", "get", "(", "\"equipment\"", ")", ":", "if", "device", ".", "get", "(", "\"type\"", ")", "==", "\"Water Heater\"", ":", "water_heater_modes", "=", "self", ".", "api_interface", ".", "get_modes", "(", "device", ".", "get", "(", "\"id\"", ")", ")", "water_heater_usage", "=", "self", ".", "api_interface", ".", "get_usage", "(", "device", ".", "get", "(", "\"id\"", ")", ")", "water_heater", "=", "self", ".", "api_interface", ".", "get_device", "(", "device", ".", "get", "(", "\"id\"", ")", ")", "vacations", "=", "self", ".", "api_interface", ".", "get_vacations", "(", ")", "device_vacations", "=", "[", "]", "for", "vacation", "in", "vacations", ":", "for", "equipment", "in", "vacation", ".", "get", "(", "\"participatingEquipment\"", ")", ":", "if", "equipment", ".", "get", "(", "\"id\"", ")", "==", "water_heater", ".", "get", "(", "\"id\"", ")", ":", "device_vacations", ".", "append", "(", "EcoNetVacation", "(", "vacation", ",", "self", ".", "api_interface", ")", ")", "water_heaters", ".", "append", "(", "EcoNetWaterHeater", "(", "water_heater", ",", "water_heater_modes", ",", "water_heater_usage", ",", "_location_id", ",", "device_vacations", ",", "self", ".", "api_interface", ")", ")", "return", "water_heaters" ]
05abf965f67c7445355508a38f11992d13adac4f
valid
Uber.get_products
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
uberpy/uber.py
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 """ endpoint = 'products' query_parameters = { 'latitude': latitude, 'longitude': longitude } return self.get_json(endpoint, 'GET', query_parameters, None, None)
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 """ endpoint = 'products' query_parameters = { 'latitude': latitude, 'longitude': longitude } return self.get_json(endpoint, 'GET', query_parameters, None, None)
[ "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" ]
vivangkumar/uberpy
python
https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/uber.py#L24-L37
[ "def", "get_products", "(", "self", ",", "latitude", ",", "longitude", ")", ":", "endpoint", "=", "'products'", "query_parameters", "=", "{", "'latitude'", ":", "latitude", ",", "'longitude'", ":", "longitude", "}", "return", "self", ".", "get_json", "(", "endpoint", ",", "'GET'", ",", "query_parameters", ",", "None", ",", "None", ")" ]
abc62ccb5399424eb5690f12c392ab2dbd9d96e0
valid
Uber.get_price_estimate
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 or longitude of destination address. :return: JSON
uberpy/uber.py
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 pickup address. :param end_latitude: Ending latitude or latitude of destination address. :param end_longitude: Ending longitude or longitude of destination address. :return: JSON """ endpoint = 'estimates/price' query_parameters = { 'start_latitude': start_latitude, 'start_longitude': start_longitude, 'end_latitude': end_latitude, 'end_longitude': end_longitude } return self.get_json(endpoint, 'GET', query_parameters, None, None)
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 pickup address. :param end_latitude: Ending latitude or latitude of destination address. :param end_longitude: Ending longitude or longitude of destination address. :return: JSON """ endpoint = 'estimates/price' query_parameters = { 'start_latitude': start_latitude, 'start_longitude': start_longitude, 'end_latitude': end_latitude, 'end_longitude': end_longitude } return self.get_json(endpoint, 'GET', query_parameters, None, None)
[ "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", "or", "longitude", "of", "destination", "address", ".", ":", "return", ":", "JSON" ]
vivangkumar/uberpy
python
https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/uber.py#L39-L56
[ "def", "get_price_estimate", "(", "self", ",", "start_latitude", ",", "start_longitude", ",", "end_latitude", ",", "end_longitude", ")", ":", "endpoint", "=", "'estimates/price'", "query_parameters", "=", "{", "'start_latitude'", ":", "start_latitude", ",", "'start_longitude'", ":", "start_longitude", ",", "'end_latitude'", ":", "end_latitude", ",", "'end_longitude'", ":", "end_longitude", "}", "return", "self", ".", "get_json", "(", "endpoint", ",", "'GET'", ",", "query_parameters", ",", "None", ",", "None", ")" ]
abc62ccb5399424eb5690f12c392ab2dbd9d96e0
valid
Uber.get_time_estimate
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
uberpy/uber.py
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. :param product_id: (Optional) If ETA is needed only for a specific product type. :return: JSON """ endpoint = 'estimates/time' query_parameters = { 'start_latitude': start_latitude, 'start_longitude': start_longitude } if customer_uuid is not None: query_parameters['customer_uuid'] = customer_uuid elif product_id is not None: query_parameters['product_id'] = product_id elif customer_uuid is not None and product_id is not None: query_parameters['customer_uuid'] = customer_uuid query_parameters['product_id'] = product_id return self.get_json(endpoint, 'GET', query_parameters, None, None)
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. :param product_id: (Optional) If ETA is needed only for a specific product type. :return: JSON """ endpoint = 'estimates/time' query_parameters = { 'start_latitude': start_latitude, 'start_longitude': start_longitude } if customer_uuid is not None: query_parameters['customer_uuid'] = customer_uuid elif product_id is not None: query_parameters['product_id'] = product_id elif customer_uuid is not None and product_id is not None: query_parameters['customer_uuid'] = customer_uuid query_parameters['product_id'] = product_id return self.get_json(endpoint, 'GET', query_parameters, None, None)
[ "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" ]
vivangkumar/uberpy
python
https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/uber.py#L58-L82
[ "def", "get_time_estimate", "(", "self", ",", "start_latitude", ",", "start_longitude", ",", "customer_uuid", "=", "None", ",", "product_id", "=", "None", ")", ":", "endpoint", "=", "'estimates/time'", "query_parameters", "=", "{", "'start_latitude'", ":", "start_latitude", ",", "'start_longitude'", ":", "start_longitude", "}", "if", "customer_uuid", "is", "not", "None", ":", "query_parameters", "[", "'customer_uuid'", "]", "=", "customer_uuid", "elif", "product_id", "is", "not", "None", ":", "query_parameters", "[", "'product_id'", "]", "=", "product_id", "elif", "customer_uuid", "is", "not", "None", "and", "product_id", "is", "not", "None", ":", "query_parameters", "[", "'customer_uuid'", "]", "=", "customer_uuid", "query_parameters", "[", "'product_id'", "]", "=", "product_id", "return", "self", ".", "get_json", "(", "endpoint", ",", "'GET'", ",", "query_parameters", ",", "None", ",", "None", ")" ]
abc62ccb5399424eb5690f12c392ab2dbd9d96e0
valid
models_preparing
Wrap all sqlalchemy model in settings.
ps_alchemy/__init__.py
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 return resource resources_preparing_factory(app, wrapper)
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 return resource resources_preparing_factory(app, wrapper)
[ "Wrap", "all", "sqlalchemy", "model", "in", "settings", "." ]
sacrud/ps_alchemy
python
https://github.com/sacrud/ps_alchemy/blob/4f042329eb4643bf26fa2540df277fa94c5265ec/ps_alchemy/__init__.py#L15-L26
[ "def", "models_preparing", "(", "app", ")", ":", "def", "wrapper", "(", "resource", ",", "parent", ")", ":", "if", "isinstance", "(", "resource", ",", "DeclarativeMeta", ")", ":", "resource", "=", "ListResource", "(", "resource", ")", "if", "not", "getattr", "(", "resource", ",", "'__parent__'", ",", "None", ")", ":", "resource", ".", "__parent__", "=", "parent", "return", "resource", "resources_preparing_factory", "(", "app", ",", "wrapper", ")" ]
4f042329eb4643bf26fa2540df277fa94c5265ec
valid
Api.check_status
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 `response.status` is 406 InvalidRequestException if `response.status` is 422 RateLimitException if `response.status` is 429 ServerException if `response.status` > 500
uberpy/api.py
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.status` is 401 NotFoundException if `response.status` is 404 UnacceptableContentException if `response.status` is 406 InvalidRequestException if `response.status` is 422 RateLimitException if `response.status` is 429 ServerException if `response.status` > 500 """ if response.status == 400: raise MalformedRequestException(content, response) if response.status == 401: raise UnauthorisedException(content, response) if response.status == 404: raise NotFoundException(content, response) if response.status == 406: raise UnacceptableContentException(content, response) if response.status == 422: raise InvalidRequestException(content, response) if response.status == 429: raise RateLimitException(content, response) if response.status >= 500: raise ServerException(content, response)
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.status` is 401 NotFoundException if `response.status` is 404 UnacceptableContentException if `response.status` is 406 InvalidRequestException if `response.status` is 422 RateLimitException if `response.status` is 429 ServerException if `response.status` > 500 """ if response.status == 400: raise MalformedRequestException(content, response) if response.status == 401: raise UnauthorisedException(content, response) if response.status == 404: raise NotFoundException(content, response) if response.status == 406: raise UnacceptableContentException(content, response) if response.status == 422: raise InvalidRequestException(content, response) if response.status == 429: raise RateLimitException(content, response) if response.status >= 500: raise ServerException(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", ".", "status", "is", "401", "NotFoundException", "if", "response", ".", "status", "is", "404", "UnacceptableContentException", "if", "response", ".", "status", "is", "406", "InvalidRequestException", "if", "response", ".", "status", "is", "422", "RateLimitException", "if", "response", ".", "status", "is", "429", "ServerException", "if", "response", ".", "status", ">", "500" ]
vivangkumar/uberpy
python
https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/api.py#L58-L91
[ "def", "check_status", "(", "content", ",", "response", ")", ":", "if", "response", ".", "status", "==", "400", ":", "raise", "MalformedRequestException", "(", "content", ",", "response", ")", "if", "response", ".", "status", "==", "401", ":", "raise", "UnauthorisedException", "(", "content", ",", "response", ")", "if", "response", ".", "status", "==", "404", ":", "raise", "NotFoundException", "(", "content", ",", "response", ")", "if", "response", ".", "status", "==", "406", ":", "raise", "UnacceptableContentException", "(", "content", ",", "response", ")", "if", "response", ".", "status", "==", "422", ":", "raise", "InvalidRequestException", "(", "content", ",", "response", ")", "if", "response", ".", "status", "==", "429", ":", "raise", "RateLimitException", "(", "content", ",", "response", ")", "if", "response", ".", "status", ">=", "500", ":", "raise", "ServerException", "(", "content", ",", "response", ")" ]
abc62ccb5399424eb5690f12c392ab2dbd9d96e0
valid
Api.build_request
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
uberpy/api.py
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://api.uber.com/v1' + self.sanitise_path(path) url += '?' + urlencode(query_parameters) return url
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://api.uber.com/v1' + self.sanitise_path(path) url += '?' + urlencode(query_parameters) return url
[ "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" ]
vivangkumar/uberpy
python
https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/api.py#L93-L103
[ "def", "build_request", "(", "self", ",", "path", ",", "query_parameters", ")", ":", "url", "=", "'https://api.uber.com/v1'", "+", "self", ".", "sanitise_path", "(", "path", ")", "url", "+=", "'?'", "+", "urlencode", "(", "query_parameters", ")", "return", "url" ]
abc62ccb5399424eb5690f12c392ab2dbd9d96e0
valid
Api.get_json
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 required. :return: JSON
uberpy/api.py
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. :param query_parameters: Parameters to be added to the request. :param body: Optional body, if required. :param headers: Optional headers, if required. :return: JSON """ query_parameters = query_parameters or {} headers = headers or {} # Add credentials to the request query_parameters = self.add_credentials(query_parameters) # Build the request uri with parameters uri = self.build_request(uri_path, query_parameters) if http_method in ('POST', 'PUT', 'DELETE') and 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' headers['Accept'] = 'application/json' response, content = self.client.request( uri=uri, method=http_method, body=body, headers=headers ) # Check for known errors that could be returned self.check_status(content, response) return json.loads(content.decode('utf-8'))
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. :param query_parameters: Parameters to be added to the request. :param body: Optional body, if required. :param headers: Optional headers, if required. :return: JSON """ query_parameters = query_parameters or {} headers = headers or {} # Add credentials to the request query_parameters = self.add_credentials(query_parameters) # Build the request uri with parameters uri = self.build_request(uri_path, query_parameters) if http_method in ('POST', 'PUT', 'DELETE') and 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' headers['Accept'] = 'application/json' response, content = self.client.request( uri=uri, method=http_method, body=body, headers=headers ) # Check for known errors that could be returned self.check_status(content, response) return json.loads(content.decode('utf-8'))
[ "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", "required", ".", ":", "return", ":", "JSON" ]
vivangkumar/uberpy
python
https://github.com/vivangkumar/uberpy/blob/abc62ccb5399424eb5690f12c392ab2dbd9d96e0/uberpy/api.py#L105-L138
[ "def", "get_json", "(", "self", ",", "uri_path", ",", "http_method", "=", "'GET'", ",", "query_parameters", "=", "None", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "query_parameters", "=", "query_parameters", "or", "{", "}", "headers", "=", "headers", "or", "{", "}", "# Add credentials to the request", "query_parameters", "=", "self", ".", "add_credentials", "(", "query_parameters", ")", "# Build the request uri with parameters", "uri", "=", "self", ".", "build_request", "(", "uri_path", ",", "query_parameters", ")", "if", "http_method", "in", "(", "'POST'", ",", "'PUT'", ",", "'DELETE'", ")", "and", "'Content-Type'", "not", "in", "headers", ":", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", "headers", "[", "'Accept'", "]", "=", "'application/json'", "response", ",", "content", "=", "self", ".", "client", ".", "request", "(", "uri", "=", "uri", ",", "method", "=", "http_method", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "# Check for known errors that could be returned", "self", ".", "check_status", "(", "content", ",", "response", ")", "return", "json", ".", "loads", "(", "content", ".", "decode", "(", "'utf-8'", ")", ")" ]
abc62ccb5399424eb5690f12c392ab2dbd9d96e0
valid
_translateCommands
Generate the binary strings for a comma seperated list of commands.
x10_any/cm17a.py
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 the house code result[0] = houseCodes[device[0]] # translate the device number if there is one if len(device) > 1: deviceNumber = deviceNumbers[device[1:]] result[0] |= deviceNumber[0] result[1] = deviceNumber[1] # translate the command result[1] |= commandCodes[command] # convert 2 bytes to bit strings and yield them yield ' '.join(map(_strBinary, result))
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 the house code result[0] = houseCodes[device[0]] # translate the device number if there is one if len(device) > 1: deviceNumber = deviceNumbers[device[1:]] result[0] |= deviceNumber[0] result[1] = deviceNumber[1] # translate the command result[1] |= commandCodes[command] # convert 2 bytes to bit strings and yield them yield ' '.join(map(_strBinary, result))
[ "Generate", "the", "binary", "strings", "for", "a", "comma", "seperated", "list", "of", "commands", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L73-L93
[ "def", "_translateCommands", "(", "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 the house code", "result", "[", "0", "]", "=", "houseCodes", "[", "device", "[", "0", "]", "]", "# translate the device number if there is one", "if", "len", "(", "device", ")", ">", "1", ":", "deviceNumber", "=", "deviceNumbers", "[", "device", "[", "1", ":", "]", "]", "result", "[", "0", "]", "|=", "deviceNumber", "[", "0", "]", "result", "[", "1", "]", "=", "deviceNumber", "[", "1", "]", "# translate the command", "result", "[", "1", "]", "|=", "commandCodes", "[", "command", "]", "# convert 2 bytes to bit strings and yield them", "yield", "' '", ".", "join", "(", "map", "(", "_strBinary", ",", "result", ")", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
_strBinary
Conert an integer to binary (i.e., a string of 1s and 0s).
x10_any/cm17a.py
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)
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)
[ "Conert", "an", "integer", "to", "binary", "(", "i", ".", "e", ".", "a", "string", "of", "1s", "and", "0s", ")", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L96-L103
[ "def", "_strBinary", "(", "n", ")", ":", "results", "=", "[", "]", "for", "i", "in", "range", "(", "8", ")", ":", "n", ",", "r", "=", "divmod", "(", "n", ",", "2", ")", "results", ".", "append", "(", "'01'", "[", "r", "]", ")", "results", ".", "reverse", "(", ")", "return", "''", ".", "join", "(", "results", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
_sendBinaryData
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 require tweaking on some setups.
x10_any/cm17a.py
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 require tweaking on some setups. """ _reset(port) time.sleep(leadInOutDelay) for digit in data: _sendBit(port, digit) time.sleep(leadInOutDelay)
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 require tweaking on some setups. """ _reset(port) time.sleep(leadInOutDelay) for digit in data: _sendBit(port, digit) time.sleep(leadInOutDelay)
[ "Send", "a", "string", "of", "binary", "data", "to", "the", "FireCracker", "with", "proper", "timing", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L106-L118
[ "def", "_sendBinaryData", "(", "port", ",", "data", ")", ":", "_reset", "(", "port", ")", "time", ".", "sleep", "(", "leadInOutDelay", ")", "for", "digit", "in", "data", ":", "_sendBit", "(", "port", ",", "digit", ")", "time", ".", "sleep", "(", "leadInOutDelay", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
_sendBit
Send an individual bit to the FireCracker module usr RTS/DTR.
x10_any/cm17a.py
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)
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)
[ "Send", "an", "individual", "bit", "to", "the", "FireCracker", "module", "usr", "RTS", "/", "DTR", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L127-L137
[ "def", "_sendBit", "(", "port", ",", "bit", ")", ":", "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", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
_setRTSDTR
Set RTS and DTR to the requested state.
x10_any/cm17a.py
def _setRTSDTR(port, RTS, DTR): """Set RTS and DTR to the requested state.""" port.setRTS(RTS) port.setDTR(DTR)
def _setRTSDTR(port, RTS, DTR): """Set RTS and DTR to the requested state.""" port.setRTS(RTS) port.setDTR(DTR)
[ "Set", "RTS", "and", "DTR", "to", "the", "requested", "state", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L140-L143
[ "def", "_setRTSDTR", "(", "port", ",", "RTS", ",", "DTR", ")", ":", "port", ".", "setRTS", "(", "RTS", ")", "port", ".", "setDTR", "(", "DTR", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
sendCommands
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 Dim, A Dim, A Lamps Off'. The letter is a house code (A-P) and the number is the device number (1-16). Possible commands for a house code / device number combination are 'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a house code alone after sending an On command to a specific device. The 'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also be used with a house code alone. # Turn on module A1 >>> sendCommands('com1', 'A1 On') # Turn all modules with house code A off >>> sendCommands('com1', 'A All Off') # Turn all lamp modules with house code B on >>> sendCommands('com1', 'B Lamps On') # Turn on module A1 and dim it 3 steps, then brighten it 1 step >>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright')
x10_any/cm17a.py
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 Dim, A Dim, A Lamps Off'. The letter is a house code (A-P) and the number is the device number (1-16). Possible commands for a house code / device number combination are 'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a house code alone after sending an On command to a specific device. The 'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also be used with a house code alone. # Turn on module A1 >>> sendCommands('com1', 'A1 On') # Turn all modules with house code A off >>> sendCommands('com1', 'A All Off') # Turn all lamp modules with house code B on >>> sendCommands('com1', 'B Lamps On') # Turn on module A1 and dim it 3 steps, then brighten it 1 step >>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright') """ mutex.acquire() try: try: port = serial.Serial(port=comPort) header = '11010101 10101010' footer = '10101101' for command in _translateCommands(commands): _sendBinaryData(port, header + command + footer) except serial.SerialException: print('Unable to open serial port %s' % comPort) print('') raise finally: mutex.release()
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 Dim, A Dim, A Lamps Off'. The letter is a house code (A-P) and the number is the device number (1-16). Possible commands for a house code / device number combination are 'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a house code alone after sending an On command to a specific device. The 'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also be used with a house code alone. # Turn on module A1 >>> sendCommands('com1', 'A1 On') # Turn all modules with house code A off >>> sendCommands('com1', 'A All Off') # Turn all lamp modules with house code B on >>> sendCommands('com1', 'B Lamps On') # Turn on module A1 and dim it 3 steps, then brighten it 1 step >>> sendCommands('com1', 'A1 On, A Dim, A Dim, A Dim, A Bright') """ mutex.acquire() try: try: port = serial.Serial(port=comPort) header = '11010101 10101010' footer = '10101101' for command in _translateCommands(commands): _sendBinaryData(port, header + command + footer) except serial.SerialException: print('Unable to open serial port %s' % comPort) print('') raise finally: mutex.release()
[ "Send", "X10", "commands", "using", "the", "FireCracker", "on", "comPort" ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L150-L190
[ "def", "sendCommands", "(", "comPort", ",", "commands", ")", ":", "mutex", ".", "acquire", "(", ")", "try", ":", "try", ":", "port", "=", "serial", ".", "Serial", "(", "port", "=", "comPort", ")", "header", "=", "'11010101 10101010'", "footer", "=", "'10101101'", "for", "command", "in", "_translateCommands", "(", "commands", ")", ":", "_sendBinaryData", "(", "port", ",", "header", "+", "command", "+", "footer", ")", "except", "serial", ".", "SerialException", ":", "print", "(", "'Unable to open serial port %s'", "%", "comPort", ")", "print", "(", "''", ")", "raise", "finally", ":", "mutex", ".", "release", "(", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
main
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
x10_any/cm17a.py
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 command line. commands = ' '.join(argv) # the comPort is everything leading up to the first space comPort, commands = commands.split(None, 1) sendCommands(comPort, commands) return 0
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 command line. commands = ' '.join(argv) # the comPort is everything leading up to the first space comPort, commands = commands.split(None, 1) sendCommands(comPort, commands) return 0
[ "Send", "X10", "commands", "when", "module", "is", "used", "from", "the", "command", "line", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/cm17a.py#L193-L210
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "len", "(", "argv", ")", ":", "# join all the arguments together by spaces so that quotes", "# aren't required on the command line.", "commands", "=", "' '", ".", "join", "(", "argv", ")", "# the comPort is everything leading up to the first space", "comPort", ",", "commands", "=", "commands", ".", "split", "(", "None", ",", "1", ")", "sendCommands", "(", "comPort", ",", "commands", ")", "return", "0" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
normalize_housecode
Returns a normalized house code, i.e. upper case. Raises exception X10InvalidHouseCode if house code appears to be invalid
x10_any/__init__.py
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, basestring): raise X10InvalidHouseCode('%r is not a valid house code' % house_code) if len(house_code) != 1: raise X10InvalidHouseCode('%r is not a valid house code' % house_code) house_code = house_code.upper() if not ('A' <= house_code <= 'P'): raise X10InvalidHouseCode('%r is not a valid house code' % house_code) return house_code
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, basestring): raise X10InvalidHouseCode('%r is not a valid house code' % house_code) if len(house_code) != 1: raise X10InvalidHouseCode('%r is not a valid house code' % house_code) house_code = house_code.upper() if not ('A' <= house_code <= 'P'): raise X10InvalidHouseCode('%r is not a valid house code' % house_code) return house_code
[ "Returns", "a", "normalized", "house", "code", "i", ".", "e", ".", "upper", "case", ".", "Raises", "exception", "X10InvalidHouseCode", "if", "house", "code", "appears", "to", "be", "invalid" ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L67-L80
[ "def", "normalize_housecode", "(", "house_code", ")", ":", "if", "house_code", "is", "None", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "if", "not", "isinstance", "(", "house_code", ",", "basestring", ")", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "if", "len", "(", "house_code", ")", "!=", "1", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "house_code", "=", "house_code", ".", "upper", "(", ")", "if", "not", "(", "'A'", "<=", "house_code", "<=", "'P'", ")", ":", "raise", "X10InvalidHouseCode", "(", "'%r is not a valid house code'", "%", "house_code", ")", "return", "house_code" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
normalize_unitnumber
Returns a normalized unit number, i.e. integers Raises exception X10InvalidUnitNumber if unit number appears to be invalid
x10_any/__init__.py
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 a valid unit number' % unit_number) except TypeError: raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number) if not (1 <= unit_number <= 16): raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number) return unit_number
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 a valid unit number' % unit_number) except TypeError: raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number) if not (1 <= unit_number <= 16): raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number) return unit_number
[ "Returns", "a", "normalized", "unit", "number", "i", ".", "e", ".", "integers", "Raises", "exception", "X10InvalidUnitNumber", "if", "unit", "number", "appears", "to", "be", "invalid" ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L83-L96
[ "def", "normalize_unitnumber", "(", "unit_number", ")", ":", "try", ":", "try", ":", "unit_number", "=", "int", "(", "unit_number", ")", "except", "ValueError", ":", "raise", "X10InvalidUnitNumber", "(", "'%r not a valid unit number'", "%", "unit_number", ")", "except", "TypeError", ":", "raise", "X10InvalidUnitNumber", "(", "'%r not a valid unit number'", "%", "unit_number", ")", "if", "not", "(", "1", "<=", "unit_number", "<=", "16", ")", ":", "raise", "X10InvalidUnitNumber", "(", "'%r not a valid unit number'", "%", "unit_number", ")", "return", "unit_number" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
X10Driver.x10_command
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/mochad/code/ci/master/tree/README examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc. Examples: x10_command('A', '1', ON) x10_command('A', '1', OFF) x10_command('A', '1', 'ON') x10_command('A', '1', 'OFF') x10_command('A', None, ON) x10_command('A', None, OFF) x10_command('A', None, 'all_lights_off') x10_command('A', None, 'all_units_off') x10_command('A', None, ALL_OFF) x10_command('A', None, 'all_lights_on') x10_command('A', 1, 'xdim 128')
x10_any/__init__.py
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/mochad/code/ci/master/tree/README examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc. Examples: x10_command('A', '1', ON) x10_command('A', '1', OFF) x10_command('A', '1', 'ON') x10_command('A', '1', 'OFF') x10_command('A', None, ON) x10_command('A', None, OFF) x10_command('A', None, 'all_lights_off') x10_command('A', None, 'all_units_off') x10_command('A', None, ALL_OFF) x10_command('A', None, 'all_lights_on') x10_command('A', 1, 'xdim 128') """ house_code = normalize_housecode(house_code) if unit_number is not None: unit_number = normalize_unitnumber(unit_number) # else command is intended for the entire house code, not a single unit number # TODO normalize/validate state return self._x10_command(house_code, unit_number, state)
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/mochad/code/ci/master/tree/README examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc. Examples: x10_command('A', '1', ON) x10_command('A', '1', OFF) x10_command('A', '1', 'ON') x10_command('A', '1', 'OFF') x10_command('A', None, ON) x10_command('A', None, OFF) x10_command('A', None, 'all_lights_off') x10_command('A', None, 'all_units_off') x10_command('A', None, ALL_OFF) x10_command('A', None, 'all_lights_on') x10_command('A', 1, 'xdim 128') """ house_code = normalize_housecode(house_code) if unit_number is not None: unit_number = normalize_unitnumber(unit_number) # else command is intended for the entire house code, not a single unit number # TODO normalize/validate state return self._x10_command(house_code, unit_number, state)
[ "Send", "X10", "command", "to", "???", "unit", "." ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L130-L159
[ "def", "x10_command", "(", "self", ",", "house_code", ",", "unit_number", ",", "state", ")", ":", "house_code", "=", "normalize_housecode", "(", "house_code", ")", "if", "unit_number", "is", "not", "None", ":", "unit_number", "=", "normalize_unitnumber", "(", "unit_number", ")", "# else command is intended for the entire house code, not a single unit number", "# TODO normalize/validate state", "return", "self", ".", "_x10_command", "(", "house_code", ",", "unit_number", ",", "state", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc
valid
X10Driver._x10_command
Real implementation
x10_any/__init__.py
def _x10_command(self, house_code, unit_number, state): """Real implementation""" print('x10_command%r' % ((house_code, unit_number, state), )) raise NotImplementedError()
def _x10_command(self, house_code, unit_number, state): """Real implementation""" print('x10_command%r' % ((house_code, unit_number, state), )) raise NotImplementedError()
[ "Real", "implementation" ]
clach04/x10_any
python
https://github.com/clach04/x10_any/blob/5b90a543b127ab9e6112fd547929b5ef4b8f0cbc/x10_any/__init__.py#L161-L164
[ "def", "_x10_command", "(", "self", ",", "house_code", ",", "unit_number", ",", "state", ")", ":", "print", "(", "'x10_command%r'", "%", "(", "(", "house_code", ",", "unit_number", ",", "state", ")", ",", ")", ")", "raise", "NotImplementedError", "(", ")" ]
5b90a543b127ab9e6112fd547929b5ef4b8f0cbc