repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation.set_input | def set_input(self, variable_name, period, value):
"""
Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
>>> from openfisca_country_template import CountryTaxBenefitSystem
>>> simulation = Simulation(CountryTaxBenefitSystem())
>>> simulation.set_input('age', '2018-04', [12, 14])
>>> simulation.get_array('age', '2018-04')
array([12, 14], dtype=int32)
If a ``set_input`` property has been set for the variable, this method may accept inputs for periods not matching the ``definition_period`` of the variable. To read more about this, check the `documentation <https://openfisca.org/doc/coding-the-legislation/35_periods.html#automatically-process-variable-inputs-defined-for-periods-not-matching-the-definitionperiod>`_.
"""
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
period = periods.period(period)
if ((variable.end is not None) and (period.start.date > variable.end)):
return
self.get_holder(variable_name).set_input(period, value) | python | def set_input(self, variable_name, period, value):
"""
Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
>>> from openfisca_country_template import CountryTaxBenefitSystem
>>> simulation = Simulation(CountryTaxBenefitSystem())
>>> simulation.set_input('age', '2018-04', [12, 14])
>>> simulation.get_array('age', '2018-04')
array([12, 14], dtype=int32)
If a ``set_input`` property has been set for the variable, this method may accept inputs for periods not matching the ``definition_period`` of the variable. To read more about this, check the `documentation <https://openfisca.org/doc/coding-the-legislation/35_periods.html#automatically-process-variable-inputs-defined-for-periods-not-matching-the-definitionperiod>`_.
"""
variable = self.tax_benefit_system.get_variable(variable_name, check_existence = True)
period = periods.period(period)
if ((variable.end is not None) and (period.start.date > variable.end)):
return
self.get_holder(variable_name).set_input(period, value) | [
"def",
"set_input",
"(",
"self",
",",
"variable_name",
",",
"period",
",",
"value",
")",
":",
"variable",
"=",
"self",
".",
"tax_benefit_system",
".",
"get_variable",
"(",
"variable_name",
",",
"check_existence",
"=",
"True",
")",
"period",
"=",
"periods",
"... | Set a variable's value for a given period
:param variable: the variable to be set
:param value: the input value for the variable
:param period: the period for which the value is setted
Example:
>>> from openfisca_country_template import CountryTaxBenefitSystem
>>> simulation = Simulation(CountryTaxBenefitSystem())
>>> simulation.set_input('age', '2018-04', [12, 14])
>>> simulation.get_array('age', '2018-04')
array([12, 14], dtype=int32)
If a ``set_input`` property has been set for the variable, this method may accept inputs for periods not matching the ``definition_period`` of the variable. To read more about this, check the `documentation <https://openfisca.org/doc/coding-the-legislation/35_periods.html#automatically-process-variable-inputs-defined-for-periods-not-matching-the-definitionperiod>`_. | [
"Set",
"a",
"variable",
"s",
"value",
"for",
"a",
"given",
"period"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L436-L457 | train | 206,300 |
openfisca/openfisca-core | openfisca_core/simulations.py | Simulation.clone | def clone(self, debug = False, trace = False):
"""
Copy the simulation just enough to be able to run the copy without modifying the original simulation
"""
new = empty_clone(self)
new_dict = new.__dict__
for key, value in self.__dict__.items():
if key not in ('debug', 'trace', 'tracer'):
new_dict[key] = value
new.persons = self.persons.clone(new)
setattr(new, new.persons.entity.key, new.persons)
new.populations = {new.persons.entity.key: new.persons}
for entity in self.tax_benefit_system.group_entities:
population = self.populations[entity.key].clone(new)
new.populations[entity.key] = population
setattr(new, entity.key, population) # create shortcut simulation.household (for instance)
new.debug = debug
new.trace = trace
return new | python | def clone(self, debug = False, trace = False):
"""
Copy the simulation just enough to be able to run the copy without modifying the original simulation
"""
new = empty_clone(self)
new_dict = new.__dict__
for key, value in self.__dict__.items():
if key not in ('debug', 'trace', 'tracer'):
new_dict[key] = value
new.persons = self.persons.clone(new)
setattr(new, new.persons.entity.key, new.persons)
new.populations = {new.persons.entity.key: new.persons}
for entity in self.tax_benefit_system.group_entities:
population = self.populations[entity.key].clone(new)
new.populations[entity.key] = population
setattr(new, entity.key, population) # create shortcut simulation.household (for instance)
new.debug = debug
new.trace = trace
return new | [
"def",
"clone",
"(",
"self",
",",
"debug",
"=",
"False",
",",
"trace",
"=",
"False",
")",
":",
"new",
"=",
"empty_clone",
"(",
"self",
")",
"new_dict",
"=",
"new",
".",
"__dict__",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"it... | Copy the simulation just enough to be able to run the copy without modifying the original simulation | [
"Copy",
"the",
"simulation",
"just",
"enough",
"to",
"be",
"able",
"to",
"run",
"the",
"copy",
"without",
"modifying",
"the",
"original",
"simulation"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L473-L496 | train | 206,301 |
openfisca/openfisca-core | openfisca_core/holders.py | Holder.clone | def clone(self, population):
"""
Copy the holder just enough to be able to run a new simulation without modifying the original simulation.
"""
new = empty_clone(self)
new_dict = new.__dict__
for key, value in self.__dict__.items():
if key not in ('population', 'formula', 'simulation'):
new_dict[key] = value
new_dict['population'] = population
new_dict['simulation'] = population.simulation
return new | python | def clone(self, population):
"""
Copy the holder just enough to be able to run a new simulation without modifying the original simulation.
"""
new = empty_clone(self)
new_dict = new.__dict__
for key, value in self.__dict__.items():
if key not in ('population', 'formula', 'simulation'):
new_dict[key] = value
new_dict['population'] = population
new_dict['simulation'] = population.simulation
return new | [
"def",
"clone",
"(",
"self",
",",
"population",
")",
":",
"new",
"=",
"empty_clone",
"(",
"self",
")",
"new_dict",
"=",
"new",
".",
"__dict__",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"key",
"no... | Copy the holder just enough to be able to run a new simulation without modifying the original simulation. | [
"Copy",
"the",
"holder",
"just",
"enough",
"to",
"be",
"able",
"to",
"run",
"a",
"new",
"simulation",
"without",
"modifying",
"the",
"original",
"simulation",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/holders.py#L43-L57 | train | 206,302 |
openfisca/openfisca-core | openfisca_core/holders.py | Holder.delete_arrays | def delete_arrays(self, period = None):
"""
If ``period`` is ``None``, remove all known values of the variable.
If ``period`` is not ``None``, only remove all values for any period included in period (e.g. if period is "2017", values for "2017-01", "2017-07", etc. would be removed)
"""
self._memory_storage.delete(period)
if self._disk_storage:
self._disk_storage.delete(period) | python | def delete_arrays(self, period = None):
"""
If ``period`` is ``None``, remove all known values of the variable.
If ``period`` is not ``None``, only remove all values for any period included in period (e.g. if period is "2017", values for "2017-01", "2017-07", etc. would be removed)
"""
self._memory_storage.delete(period)
if self._disk_storage:
self._disk_storage.delete(period) | [
"def",
"delete_arrays",
"(",
"self",
",",
"period",
"=",
"None",
")",
":",
"self",
".",
"_memory_storage",
".",
"delete",
"(",
"period",
")",
"if",
"self",
".",
"_disk_storage",
":",
"self",
".",
"_disk_storage",
".",
"delete",
"(",
"period",
")"
] | If ``period`` is ``None``, remove all known values of the variable.
If ``period`` is not ``None``, only remove all values for any period included in period (e.g. if period is "2017", values for "2017-01", "2017-07", etc. would be removed) | [
"If",
"period",
"is",
"None",
"remove",
"all",
"known",
"values",
"of",
"the",
"variable",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/holders.py#L71-L81 | train | 206,303 |
openfisca/openfisca-core | openfisca_core/holders.py | Holder.get_array | def get_array(self, period):
"""
Get the value of the variable for the given period.
If the value is not known, return ``None``.
"""
if self.variable.is_neutralized:
return self.default_array()
value = self._memory_storage.get(period)
if value is not None:
return value
if self._disk_storage:
return self._disk_storage.get(period) | python | def get_array(self, period):
"""
Get the value of the variable for the given period.
If the value is not known, return ``None``.
"""
if self.variable.is_neutralized:
return self.default_array()
value = self._memory_storage.get(period)
if value is not None:
return value
if self._disk_storage:
return self._disk_storage.get(period) | [
"def",
"get_array",
"(",
"self",
",",
"period",
")",
":",
"if",
"self",
".",
"variable",
".",
"is_neutralized",
":",
"return",
"self",
".",
"default_array",
"(",
")",
"value",
"=",
"self",
".",
"_memory_storage",
".",
"get",
"(",
"period",
")",
"if",
"... | Get the value of the variable for the given period.
If the value is not known, return ``None``. | [
"Get",
"the",
"value",
"of",
"the",
"variable",
"for",
"the",
"given",
"period",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/holders.py#L83-L95 | train | 206,304 |
openfisca/openfisca-core | openfisca_core/holders.py | Holder.get_memory_usage | def get_memory_usage(self):
"""
Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the variable values for 12 different periods
>>> 'nb_cells_by_array': 100, # There are 100 entities (e.g. persons) in our simulation
>>> 'cell_size': 8, # Each value takes 8B of memory
>>> 'dtype': dtype('float64') # Each value is a float 64
>>> 'total_nb_bytes': 10400 # The holder uses 10.4kB of virtual memory
>>> 'nb_requests': 24 # The variable has been computed 24 times
>>> 'nb_requests_by_array': 2 # Each array stored has been on average requested twice
>>> }
"""
usage = dict(
nb_cells_by_array = self.population.count,
dtype = self.variable.dtype,
)
usage.update(self._memory_storage.get_memory_usage())
if self.simulation.trace:
usage_stats = self.simulation.tracer.usage_stats[self.variable.name]
usage.update(dict(
nb_requests = usage_stats['nb_requests'],
nb_requests_by_array = usage_stats['nb_requests'] / float(usage['nb_arrays']) if usage['nb_arrays'] > 0 else np.nan
))
return usage | python | def get_memory_usage(self):
"""
Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the variable values for 12 different periods
>>> 'nb_cells_by_array': 100, # There are 100 entities (e.g. persons) in our simulation
>>> 'cell_size': 8, # Each value takes 8B of memory
>>> 'dtype': dtype('float64') # Each value is a float 64
>>> 'total_nb_bytes': 10400 # The holder uses 10.4kB of virtual memory
>>> 'nb_requests': 24 # The variable has been computed 24 times
>>> 'nb_requests_by_array': 2 # Each array stored has been on average requested twice
>>> }
"""
usage = dict(
nb_cells_by_array = self.population.count,
dtype = self.variable.dtype,
)
usage.update(self._memory_storage.get_memory_usage())
if self.simulation.trace:
usage_stats = self.simulation.tracer.usage_stats[self.variable.name]
usage.update(dict(
nb_requests = usage_stats['nb_requests'],
nb_requests_by_array = usage_stats['nb_requests'] / float(usage['nb_arrays']) if usage['nb_arrays'] > 0 else np.nan
))
return usage | [
"def",
"get_memory_usage",
"(",
"self",
")",
":",
"usage",
"=",
"dict",
"(",
"nb_cells_by_array",
"=",
"self",
".",
"population",
".",
"count",
",",
"dtype",
"=",
"self",
".",
"variable",
".",
"dtype",
",",
")",
"usage",
".",
"update",
"(",
"self",
"."... | Get data about the virtual memory usage of the holder.
:returns: Memory usage data
:rtype: dict
Example:
>>> holder.get_memory_usage()
>>> {
>>> 'nb_arrays': 12, # The holder contains the variable values for 12 different periods
>>> 'nb_cells_by_array': 100, # There are 100 entities (e.g. persons) in our simulation
>>> 'cell_size': 8, # Each value takes 8B of memory
>>> 'dtype': dtype('float64') # Each value is a float 64
>>> 'total_nb_bytes': 10400 # The holder uses 10.4kB of virtual memory
>>> 'nb_requests': 24 # The variable has been computed 24 times
>>> 'nb_requests_by_array': 2 # Each array stored has been on average requested twice
>>> } | [
"Get",
"data",
"about",
"the",
"virtual",
"memory",
"usage",
"of",
"the",
"holder",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/holders.py#L97-L132 | train | 206,305 |
openfisca/openfisca-core | openfisca_core/holders.py | Holder.get_known_periods | def get_known_periods(self):
"""
Get the list of periods the variable value is known for.
"""
return list(self._memory_storage.get_known_periods()) + list((
self._disk_storage.get_known_periods() if self._disk_storage else [])) | python | def get_known_periods(self):
"""
Get the list of periods the variable value is known for.
"""
return list(self._memory_storage.get_known_periods()) + list((
self._disk_storage.get_known_periods() if self._disk_storage else [])) | [
"def",
"get_known_periods",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_memory_storage",
".",
"get_known_periods",
"(",
")",
")",
"+",
"list",
"(",
"(",
"self",
".",
"_disk_storage",
".",
"get_known_periods",
"(",
")",
"if",
"self",
".",
... | Get the list of periods the variable value is known for. | [
"Get",
"the",
"list",
"of",
"periods",
"the",
"variable",
"value",
"is",
"known",
"for",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/holders.py#L134-L140 | train | 206,306 |
openfisca/openfisca-core | openfisca_core/tools/simulation_dumper.py | dump_simulation | def dump_simulation(simulation, directory):
"""
Write simulation data to directory, so that it can be restored later.
"""
parent_directory = os.path.abspath(os.path.join(directory, os.pardir))
if not os.path.isdir(parent_directory): # To deal with reforms
os.mkdir(parent_directory)
if not os.path.isdir(directory):
os.mkdir(directory)
if os.listdir(directory):
raise ValueError("Directory '{}' is not empty".format(directory))
entities_dump_dir = os.path.join(directory, "__entities__")
os.mkdir(entities_dump_dir)
for entity in simulation.populations.values():
# Dump entity structure
_dump_entity(entity, entities_dump_dir)
# Dump variable values
for holder in entity._holders.values():
_dump_holder(holder, directory) | python | def dump_simulation(simulation, directory):
"""
Write simulation data to directory, so that it can be restored later.
"""
parent_directory = os.path.abspath(os.path.join(directory, os.pardir))
if not os.path.isdir(parent_directory): # To deal with reforms
os.mkdir(parent_directory)
if not os.path.isdir(directory):
os.mkdir(directory)
if os.listdir(directory):
raise ValueError("Directory '{}' is not empty".format(directory))
entities_dump_dir = os.path.join(directory, "__entities__")
os.mkdir(entities_dump_dir)
for entity in simulation.populations.values():
# Dump entity structure
_dump_entity(entity, entities_dump_dir)
# Dump variable values
for holder in entity._holders.values():
_dump_holder(holder, directory) | [
"def",
"dump_simulation",
"(",
"simulation",
",",
"directory",
")",
":",
"parent_directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"os",
".",
"pardir",
")",
")",
"if",
"not",
"os",
".",
"p... | Write simulation data to directory, so that it can be restored later. | [
"Write",
"simulation",
"data",
"to",
"directory",
"so",
"that",
"it",
"can",
"be",
"restored",
"later",
"."
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/tools/simulation_dumper.py#L13-L35 | train | 206,307 |
openfisca/openfisca-core | openfisca_core/tools/simulation_dumper.py | restore_simulation | def restore_simulation(directory, tax_benefit_system, **kwargs):
"""
Restore simulation from directory
"""
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities())
entities_dump_dir = os.path.join(directory, "__entities__")
for population in simulation.populations.values():
if population.entity.is_person:
continue
person_count = _restore_entity(population, entities_dump_dir)
for population in simulation.populations.values():
if not population.entity.is_person:
continue
_restore_entity(population, entities_dump_dir)
population.count = person_count
variables_to_restore = (variable for variable in os.listdir(directory) if variable != "__entities__")
for variable in variables_to_restore:
_restore_holder(simulation, variable, directory)
return simulation | python | def restore_simulation(directory, tax_benefit_system, **kwargs):
"""
Restore simulation from directory
"""
simulation = Simulation(tax_benefit_system, tax_benefit_system.instantiate_entities())
entities_dump_dir = os.path.join(directory, "__entities__")
for population in simulation.populations.values():
if population.entity.is_person:
continue
person_count = _restore_entity(population, entities_dump_dir)
for population in simulation.populations.values():
if not population.entity.is_person:
continue
_restore_entity(population, entities_dump_dir)
population.count = person_count
variables_to_restore = (variable for variable in os.listdir(directory) if variable != "__entities__")
for variable in variables_to_restore:
_restore_holder(simulation, variable, directory)
return simulation | [
"def",
"restore_simulation",
"(",
"directory",
",",
"tax_benefit_system",
",",
"*",
"*",
"kwargs",
")",
":",
"simulation",
"=",
"Simulation",
"(",
"tax_benefit_system",
",",
"tax_benefit_system",
".",
"instantiate_entities",
"(",
")",
")",
"entities_dump_dir",
"=",
... | Restore simulation from directory | [
"Restore",
"simulation",
"from",
"directory"
] | 92ce9396e29ae5d9bac5ea604cfce88517c6b35c | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/tools/simulation_dumper.py#L38-L60 | train | 206,308 |
TimBest/django-multi-form-view | multi_form_view/base.py | MultiFormView.are_forms_valid | def are_forms_valid(self, forms):
"""
Check if all forms defined in `form_classes` are valid.
"""
for form in six.itervalues(forms):
if not form.is_valid():
return False
return True | python | def are_forms_valid(self, forms):
"""
Check if all forms defined in `form_classes` are valid.
"""
for form in six.itervalues(forms):
if not form.is_valid():
return False
return True | [
"def",
"are_forms_valid",
"(",
"self",
",",
"forms",
")",
":",
"for",
"form",
"in",
"six",
".",
"itervalues",
"(",
"forms",
")",
":",
"if",
"not",
"form",
".",
"is_valid",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Check if all forms defined in `form_classes` are valid. | [
"Check",
"if",
"all",
"forms",
"defined",
"in",
"form_classes",
"are",
"valid",
"."
] | d7f0a341881a5a36e4d567ca9bc29d233de01720 | https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L15-L22 | train | 206,309 |
TimBest/django-multi-form-view | multi_form_view/base.py | MultiFormView.get_context_data | def get_context_data(self, **kwargs):
"""
Add forms into the context dictionary.
"""
context = {}
if 'forms' not in kwargs:
context['forms'] = self.get_forms()
else:
context['forms'] = kwargs['forms']
return context | python | def get_context_data(self, **kwargs):
"""
Add forms into the context dictionary.
"""
context = {}
if 'forms' not in kwargs:
context['forms'] = self.get_forms()
else:
context['forms'] = kwargs['forms']
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"{",
"}",
"if",
"'forms'",
"not",
"in",
"kwargs",
":",
"context",
"[",
"'forms'",
"]",
"=",
"self",
".",
"get_forms",
"(",
")",
"else",
":",
"context",
"[",
... | Add forms into the context dictionary. | [
"Add",
"forms",
"into",
"the",
"context",
"dictionary",
"."
] | d7f0a341881a5a36e4d567ca9bc29d233de01720 | https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L42-L51 | train | 206,310 |
TimBest/django-multi-form-view | multi_form_view/base.py | MultiFormView.get_form_kwargs | def get_form_kwargs(self):
"""
Build the keyword arguments required to instantiate the form.
"""
kwargs = {}
for key in six.iterkeys(self.form_classes):
if self.request.method in ('POST', 'PUT'):
kwargs[key] = {
'data': self.request.POST,
'files': self.request.FILES,
}
else:
kwargs[key] = {}
return kwargs | python | def get_form_kwargs(self):
"""
Build the keyword arguments required to instantiate the form.
"""
kwargs = {}
for key in six.iterkeys(self.form_classes):
if self.request.method in ('POST', 'PUT'):
kwargs[key] = {
'data': self.request.POST,
'files': self.request.FILES,
}
else:
kwargs[key] = {}
return kwargs | [
"def",
"get_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"form_classes",
")",
":",
"if",
"self",
".",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PUT'",
")",
"... | Build the keyword arguments required to instantiate the form. | [
"Build",
"the",
"keyword",
"arguments",
"required",
"to",
"instantiate",
"the",
"form",
"."
] | d7f0a341881a5a36e4d567ca9bc29d233de01720 | https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L65-L79 | train | 206,311 |
TimBest/django-multi-form-view | multi_form_view/base.py | MultiFormView.get_initial | def get_initial(self):
"""
Returns a copy of `initial` with empty initial data dictionaries for each form.
"""
initial = super(MultiFormView, self).get_initial()
for key in six.iterkeys(self.form_classes):
initial[key] = {}
return initial | python | def get_initial(self):
"""
Returns a copy of `initial` with empty initial data dictionaries for each form.
"""
initial = super(MultiFormView, self).get_initial()
for key in six.iterkeys(self.form_classes):
initial[key] = {}
return initial | [
"def",
"get_initial",
"(",
"self",
")",
":",
"initial",
"=",
"super",
"(",
"MultiFormView",
",",
"self",
")",
".",
"get_initial",
"(",
")",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"form_classes",
")",
":",
"initial",
"[",
"key",
... | Returns a copy of `initial` with empty initial data dictionaries for each form. | [
"Returns",
"a",
"copy",
"of",
"initial",
"with",
"empty",
"initial",
"data",
"dictionaries",
"for",
"each",
"form",
"."
] | d7f0a341881a5a36e4d567ca9bc29d233de01720 | https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L81-L88 | train | 206,312 |
TimBest/django-multi-form-view | multi_form_view/base.py | MultiModelFormView.get_objects | def get_objects(self):
"""
Returns dictionary with the instance objects for each form. Keys should match the
corresponding form.
"""
objects = {}
for key in six.iterkeys(self.form_classes):
objects[key] = None
return objects | python | def get_objects(self):
"""
Returns dictionary with the instance objects for each form. Keys should match the
corresponding form.
"""
objects = {}
for key in six.iterkeys(self.form_classes):
objects[key] = None
return objects | [
"def",
"get_objects",
"(",
"self",
")",
":",
"objects",
"=",
"{",
"}",
"for",
"key",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"form_classes",
")",
":",
"objects",
"[",
"key",
"]",
"=",
"None",
"return",
"objects"
] | Returns dictionary with the instance objects for each form. Keys should match the
corresponding form. | [
"Returns",
"dictionary",
"with",
"the",
"instance",
"objects",
"for",
"each",
"form",
".",
"Keys",
"should",
"match",
"the",
"corresponding",
"form",
"."
] | d7f0a341881a5a36e4d567ca9bc29d233de01720 | https://github.com/TimBest/django-multi-form-view/blob/d7f0a341881a5a36e4d567ca9bc29d233de01720/multi_form_view/base.py#L127-L135 | train | 206,313 |
adamcharnock/django-hordak | hordak/utilities/money.py | ratio_split | def ratio_split(amount, ratios):
""" Split in_value according to the ratios specified in `ratios`
This is special in that it ensures the returned values always sum to
in_value (i.e. we avoid losses or gains due to rounding errors). As a
result, this method returns a list of `Decimal` values with length equal
to that of `ratios`.
Examples:
.. code-block:: python
>>> from hordak.utilities.money import ratio_split
>>> from decimal import Decimal
>>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')])
[Decimal('3.33'), Decimal('6.67')]
Note the returned values sum to the original input of ``10``. If we were to
do this calculation in a naive fashion then the returned values would likely
be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing
``0.01``.
Args:
amount (Decimal): The amount to be split
ratios (list[Decimal]): The ratios that will determine the split
Returns: list(Decimal)
"""
ratio_total = sum(ratios)
divided_value = amount / ratio_total
values = []
for ratio in ratios:
value = divided_value * ratio
values.append(value)
# Now round the values, keeping track of the bits we cut off
rounded = [v.quantize(Decimal("0.01")) for v in values]
remainders = [v - rounded[i] for i, v in enumerate(values)]
remainder = sum(remainders)
# Give the last person the (positive or negative) remainder
rounded[-1] = (rounded[-1] + remainder).quantize(Decimal("0.01"))
assert sum(rounded) == amount
return rounded | python | def ratio_split(amount, ratios):
""" Split in_value according to the ratios specified in `ratios`
This is special in that it ensures the returned values always sum to
in_value (i.e. we avoid losses or gains due to rounding errors). As a
result, this method returns a list of `Decimal` values with length equal
to that of `ratios`.
Examples:
.. code-block:: python
>>> from hordak.utilities.money import ratio_split
>>> from decimal import Decimal
>>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')])
[Decimal('3.33'), Decimal('6.67')]
Note the returned values sum to the original input of ``10``. If we were to
do this calculation in a naive fashion then the returned values would likely
be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing
``0.01``.
Args:
amount (Decimal): The amount to be split
ratios (list[Decimal]): The ratios that will determine the split
Returns: list(Decimal)
"""
ratio_total = sum(ratios)
divided_value = amount / ratio_total
values = []
for ratio in ratios:
value = divided_value * ratio
values.append(value)
# Now round the values, keeping track of the bits we cut off
rounded = [v.quantize(Decimal("0.01")) for v in values]
remainders = [v - rounded[i] for i, v in enumerate(values)]
remainder = sum(remainders)
# Give the last person the (positive or negative) remainder
rounded[-1] = (rounded[-1] + remainder).quantize(Decimal("0.01"))
assert sum(rounded) == amount
return rounded | [
"def",
"ratio_split",
"(",
"amount",
",",
"ratios",
")",
":",
"ratio_total",
"=",
"sum",
"(",
"ratios",
")",
"divided_value",
"=",
"amount",
"/",
"ratio_total",
"values",
"=",
"[",
"]",
"for",
"ratio",
"in",
"ratios",
":",
"value",
"=",
"divided_value",
... | Split in_value according to the ratios specified in `ratios`
This is special in that it ensures the returned values always sum to
in_value (i.e. we avoid losses or gains due to rounding errors). As a
result, this method returns a list of `Decimal` values with length equal
to that of `ratios`.
Examples:
.. code-block:: python
>>> from hordak.utilities.money import ratio_split
>>> from decimal import Decimal
>>> ratio_split(Decimal('10'), [Decimal('1'), Decimal('2')])
[Decimal('3.33'), Decimal('6.67')]
Note the returned values sum to the original input of ``10``. If we were to
do this calculation in a naive fashion then the returned values would likely
be ``3.33`` and ``6.66``, which would sum to ``9.99``, thereby loosing
``0.01``.
Args:
amount (Decimal): The amount to be split
ratios (list[Decimal]): The ratios that will determine the split
Returns: list(Decimal) | [
"Split",
"in_value",
"according",
"to",
"the",
"ratios",
"specified",
"in",
"ratios"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/money.py#L4-L49 | train | 206,314 |
adamcharnock/django-hordak | hordak/models/statement_csv_import.py | TransactionCsvImport.create_columns | def create_columns(self):
"""For each column in file create a TransactionCsvImportColumn"""
reader = self._get_csv_reader()
headings = six.next(reader)
try:
examples = six.next(reader)
except StopIteration:
examples = []
found_fields = set()
for i, value in enumerate(headings):
if i >= 20:
break
infer_field = self.has_headings and value not in found_fields
to_field = (
{
"date": "date",
"amount": "amount",
"description": "description",
"memo": "description",
"notes": "description",
}.get(value.lower(), "")
if infer_field
else ""
)
if to_field:
found_fields.add(to_field)
TransactionCsvImportColumn.objects.update_or_create(
transaction_import=self,
column_number=i + 1,
column_heading=value if self.has_headings else "",
to_field=to_field,
example=examples[i].strip() if examples else "",
) | python | def create_columns(self):
"""For each column in file create a TransactionCsvImportColumn"""
reader = self._get_csv_reader()
headings = six.next(reader)
try:
examples = six.next(reader)
except StopIteration:
examples = []
found_fields = set()
for i, value in enumerate(headings):
if i >= 20:
break
infer_field = self.has_headings and value not in found_fields
to_field = (
{
"date": "date",
"amount": "amount",
"description": "description",
"memo": "description",
"notes": "description",
}.get(value.lower(), "")
if infer_field
else ""
)
if to_field:
found_fields.add(to_field)
TransactionCsvImportColumn.objects.update_or_create(
transaction_import=self,
column_number=i + 1,
column_heading=value if self.has_headings else "",
to_field=to_field,
example=examples[i].strip() if examples else "",
) | [
"def",
"create_columns",
"(",
"self",
")",
":",
"reader",
"=",
"self",
".",
"_get_csv_reader",
"(",
")",
"headings",
"=",
"six",
".",
"next",
"(",
"reader",
")",
"try",
":",
"examples",
"=",
"six",
".",
"next",
"(",
"reader",
")",
"except",
"StopIterat... | For each column in file create a TransactionCsvImportColumn | [
"For",
"each",
"column",
"in",
"file",
"create",
"a",
"TransactionCsvImportColumn"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/statement_csv_import.py#L38-L75 | train | 206,315 |
adamcharnock/django-hordak | hordak/resources.py | StatementLineResource._get_num_similar_objects | def _get_num_similar_objects(self, obj):
"""Get any statement lines which would be considered a duplicate of obj"""
return StatementLine.objects.filter(
date=obj.date, amount=obj.amount, description=obj.description
).count() | python | def _get_num_similar_objects(self, obj):
"""Get any statement lines which would be considered a duplicate of obj"""
return StatementLine.objects.filter(
date=obj.date, amount=obj.amount, description=obj.description
).count() | [
"def",
"_get_num_similar_objects",
"(",
"self",
",",
"obj",
")",
":",
"return",
"StatementLine",
".",
"objects",
".",
"filter",
"(",
"date",
"=",
"obj",
".",
"date",
",",
"amount",
"=",
"obj",
".",
"amount",
",",
"description",
"=",
"obj",
".",
"descript... | Get any statement lines which would be considered a duplicate of obj | [
"Get",
"any",
"statement",
"lines",
"which",
"would",
"be",
"considered",
"a",
"duplicate",
"of",
"obj"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/resources.py#L74-L78 | train | 206,316 |
adamcharnock/django-hordak | hordak/resources.py | StatementLineResource._get_num_similar_rows | def _get_num_similar_rows(self, row, until=None):
"""Get the number of rows similar to row which precede the index `until`"""
return len(list(filter(lambda r: row == r, self.dataset[:until]))) | python | def _get_num_similar_rows(self, row, until=None):
"""Get the number of rows similar to row which precede the index `until`"""
return len(list(filter(lambda r: row == r, self.dataset[:until]))) | [
"def",
"_get_num_similar_rows",
"(",
"self",
",",
"row",
",",
"until",
"=",
"None",
")",
":",
"return",
"len",
"(",
"list",
"(",
"filter",
"(",
"lambda",
"r",
":",
"row",
"==",
"r",
",",
"self",
".",
"dataset",
"[",
":",
"until",
"]",
")",
")",
"... | Get the number of rows similar to row which precede the index `until` | [
"Get",
"the",
"number",
"of",
"rows",
"similar",
"to",
"row",
"which",
"precede",
"the",
"index",
"until"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/resources.py#L80-L82 | train | 206,317 |
adamcharnock/django-hordak | hordak/data_sources/tellerio.py | do_import | def do_import(token, account_uuid, bank_account, since=None):
"""Import data from teller.io
Returns the created StatementImport
"""
response = requests.get(
url="https://api.teller.io/accounts/{}/transactions".format(account_uuid),
headers={"Authorization": "Bearer {}".format(token)},
)
response.raise_for_status()
data = response.json()
statement_import = StatementImport.objects.create(
source="teller.io", extra={"account_uuid": account_uuid}, bank_account=bank_account
)
for line_data in data:
uuid = UUID(hex=line_data["id"])
if StatementLine.objects.filter(uuid=uuid):
continue
description = ", ".join(filter(bool, [line_data["counterparty"], line_data["description"]]))
date = datetime.date(*map(int, line_data["date"].split("-")))
if not since or date >= since:
StatementLine.objects.create(
uuid=uuid,
date=line_data["date"],
statement_import=statement_import,
amount=line_data["amount"],
type=line_data["type"],
description=description,
source_data=line_data,
) | python | def do_import(token, account_uuid, bank_account, since=None):
"""Import data from teller.io
Returns the created StatementImport
"""
response = requests.get(
url="https://api.teller.io/accounts/{}/transactions".format(account_uuid),
headers={"Authorization": "Bearer {}".format(token)},
)
response.raise_for_status()
data = response.json()
statement_import = StatementImport.objects.create(
source="teller.io", extra={"account_uuid": account_uuid}, bank_account=bank_account
)
for line_data in data:
uuid = UUID(hex=line_data["id"])
if StatementLine.objects.filter(uuid=uuid):
continue
description = ", ".join(filter(bool, [line_data["counterparty"], line_data["description"]]))
date = datetime.date(*map(int, line_data["date"].split("-")))
if not since or date >= since:
StatementLine.objects.create(
uuid=uuid,
date=line_data["date"],
statement_import=statement_import,
amount=line_data["amount"],
type=line_data["type"],
description=description,
source_data=line_data,
) | [
"def",
"do_import",
"(",
"token",
",",
"account_uuid",
",",
"bank_account",
",",
"since",
"=",
"None",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"\"https://api.teller.io/accounts/{}/transactions\"",
".",
"format",
"(",
"account_uuid",
"... | Import data from teller.io
Returns the created StatementImport | [
"Import",
"data",
"from",
"teller",
".",
"io"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/data_sources/tellerio.py#L11-L44 | train | 206,318 |
adamcharnock/django-hordak | hordak/models/core.py | Account.validate_accounting_equation | def validate_accounting_equation(cls):
"""Check that all accounts sum to 0"""
balances = [account.balance(raw=True) for account in Account.objects.root_nodes()]
if sum(balances, Balance()) != 0:
raise exceptions.AccountingEquationViolationError(
"Account balances do not sum to zero. They sum to {}".format(sum(balances))
) | python | def validate_accounting_equation(cls):
"""Check that all accounts sum to 0"""
balances = [account.balance(raw=True) for account in Account.objects.root_nodes()]
if sum(balances, Balance()) != 0:
raise exceptions.AccountingEquationViolationError(
"Account balances do not sum to zero. They sum to {}".format(sum(balances))
) | [
"def",
"validate_accounting_equation",
"(",
"cls",
")",
":",
"balances",
"=",
"[",
"account",
".",
"balance",
"(",
"raw",
"=",
"True",
")",
"for",
"account",
"in",
"Account",
".",
"objects",
".",
"root_nodes",
"(",
")",
"]",
"if",
"sum",
"(",
"balances",... | Check that all accounts sum to 0 | [
"Check",
"that",
"all",
"accounts",
"sum",
"to",
"0"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L149-L155 | train | 206,319 |
adamcharnock/django-hordak | hordak/models/core.py | Account.sign | def sign(self):
"""
Returns 1 if a credit should increase the value of the
account, or -1 if a credit should decrease the value of the
account.
This is based on the account type as is standard accounting practice.
The signs can be derrived from the following expanded form of the
accounting equation:
Assets = Liabilities + Equity + (Income - Expenses)
Which can be rearranged as:
0 = Liabilities + Equity + Income - Expenses - Assets
Further details here: https://en.wikipedia.org/wiki/Debits_and_credits
"""
return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 | python | def sign(self):
"""
Returns 1 if a credit should increase the value of the
account, or -1 if a credit should decrease the value of the
account.
This is based on the account type as is standard accounting practice.
The signs can be derrived from the following expanded form of the
accounting equation:
Assets = Liabilities + Equity + (Income - Expenses)
Which can be rearranged as:
0 = Liabilities + Equity + Income - Expenses - Assets
Further details here: https://en.wikipedia.org/wiki/Debits_and_credits
"""
return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1 | [
"def",
"sign",
"(",
"self",
")",
":",
"return",
"-",
"1",
"if",
"self",
".",
"type",
"in",
"(",
"Account",
".",
"TYPES",
".",
"asset",
",",
"Account",
".",
"TYPES",
".",
"expense",
")",
"else",
"1"
] | Returns 1 if a credit should increase the value of the
account, or -1 if a credit should decrease the value of the
account.
This is based on the account type as is standard accounting practice.
The signs can be derrived from the following expanded form of the
accounting equation:
Assets = Liabilities + Equity + (Income - Expenses)
Which can be rearranged as:
0 = Liabilities + Equity + Income - Expenses - Assets
Further details here: https://en.wikipedia.org/wiki/Debits_and_credits | [
"Returns",
"1",
"if",
"a",
"credit",
"should",
"increase",
"the",
"value",
"of",
"the",
"account",
"or",
"-",
"1",
"if",
"a",
"credit",
"should",
"decrease",
"the",
"value",
"of",
"the",
"account",
"."
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L180-L199 | train | 206,320 |
adamcharnock/django-hordak | hordak/models/core.py | Account.balance | def balance(self, as_of=None, raw=False, leg_query=None, **kwargs):
"""Get the balance for this account, including child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
kwargs (dict): Will be used to filter the transaction legs
Returns:
Balance
See Also:
:meth:`simple_balance()`
"""
balances = [
account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs)
for account in self.get_descendants(include_self=True)
]
return sum(balances, Balance()) | python | def balance(self, as_of=None, raw=False, leg_query=None, **kwargs):
"""Get the balance for this account, including child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
kwargs (dict): Will be used to filter the transaction legs
Returns:
Balance
See Also:
:meth:`simple_balance()`
"""
balances = [
account.simple_balance(as_of=as_of, raw=raw, leg_query=leg_query, **kwargs)
for account in self.get_descendants(include_self=True)
]
return sum(balances, Balance()) | [
"def",
"balance",
"(",
"self",
",",
"as_of",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"leg_query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"balances",
"=",
"[",
"account",
".",
"simple_balance",
"(",
"as_of",
"=",
"as_of",
",",
"raw",
"=... | Get the balance for this account, including child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
kwargs (dict): Will be used to filter the transaction legs
Returns:
Balance
See Also:
:meth:`simple_balance()` | [
"Get",
"the",
"balance",
"for",
"this",
"account",
"including",
"child",
"accounts"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L201-L220 | train | 206,321 |
adamcharnock/django-hordak | hordak/models/core.py | Account.simple_balance | def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs):
"""Get the balance for this account, ignoring all child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs.
allows for more complex filtering than that provided by **kwargs.
kwargs (dict): Will be used to filter the transaction legs
Returns:
Balance
"""
legs = self.legs
if as_of:
legs = legs.filter(transaction__date__lte=as_of)
if leg_query or kwargs:
leg_query = leg_query or models.Q()
legs = legs.filter(leg_query, **kwargs)
return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance() | python | def simple_balance(self, as_of=None, raw=False, leg_query=None, **kwargs):
"""Get the balance for this account, ignoring all child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs.
allows for more complex filtering than that provided by **kwargs.
kwargs (dict): Will be used to filter the transaction legs
Returns:
Balance
"""
legs = self.legs
if as_of:
legs = legs.filter(transaction__date__lte=as_of)
if leg_query or kwargs:
leg_query = leg_query or models.Q()
legs = legs.filter(leg_query, **kwargs)
return legs.sum_to_balance() * (1 if raw else self.sign) + self._zero_balance() | [
"def",
"simple_balance",
"(",
"self",
",",
"as_of",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"leg_query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"legs",
"=",
"self",
".",
"legs",
"if",
"as_of",
":",
"legs",
"=",
"legs",
".",
"filter",
... | Get the balance for this account, ignoring all child accounts
Args:
as_of (Date): Only include transactions on or before this date
raw (bool): If true the returned balance should not have its sign
adjusted for display purposes.
leg_query (models.Q): Django Q-expression, will be used to filter the transaction legs.
allows for more complex filtering than that provided by **kwargs.
kwargs (dict): Will be used to filter the transaction legs
Returns:
Balance | [
"Get",
"the",
"balance",
"for",
"this",
"account",
"ignoring",
"all",
"child",
"accounts"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L222-L244 | train | 206,322 |
adamcharnock/django-hordak | hordak/models/core.py | Account.transfer_to | def transfer_to(self, to_account, amount, **transaction_kwargs):
"""Create a transaction which transfers amount to to_account
This is a shortcut utility method which simplifies the process of
transferring between accounts.
This method attempts to perform the transaction in an intuitive manner.
For example:
* Transferring income -> income will result in the former decreasing and the latter increasing
* Transferring asset (i.e. bank) -> income will result in the balance of both increasing
* Transferring asset -> asset will result in the former decreasing and the latter increasing
.. note::
Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}``
will always result in both balances increasing. This may change in future if it is
found to be unhelpful.
Transfers to trading accounts will always behave as normal.
Args:
to_account (Account): The destination account.
amount (Money): The amount to be transferred.
transaction_kwargs: Passed through to transaction creation. Useful for setting the
transaction `description` field.
"""
if not isinstance(amount, Money):
raise TypeError("amount must be of type Money")
if to_account.sign == 1 and to_account.type != self.TYPES.trading:
# Transferring from two positive-signed accounts implies that
# the caller wants to reduce the first account and increase the second
# (which is opposite to the implicit behaviour)
direction = -1
elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense:
# Transfers from liability -> asset accounts should reduce both.
# For example, moving money from Rent Payable (liability) to your Rent (expense) account
# should use the funds you've built up in the liability account to pay off the expense account.
direction = -1
else:
direction = 1
transaction = Transaction.objects.create(**transaction_kwargs)
Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction)
Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction)
return transaction | python | def transfer_to(self, to_account, amount, **transaction_kwargs):
"""Create a transaction which transfers amount to to_account
This is a shortcut utility method which simplifies the process of
transferring between accounts.
This method attempts to perform the transaction in an intuitive manner.
For example:
* Transferring income -> income will result in the former decreasing and the latter increasing
* Transferring asset (i.e. bank) -> income will result in the balance of both increasing
* Transferring asset -> asset will result in the former decreasing and the latter increasing
.. note::
Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}``
will always result in both balances increasing. This may change in future if it is
found to be unhelpful.
Transfers to trading accounts will always behave as normal.
Args:
to_account (Account): The destination account.
amount (Money): The amount to be transferred.
transaction_kwargs: Passed through to transaction creation. Useful for setting the
transaction `description` field.
"""
if not isinstance(amount, Money):
raise TypeError("amount must be of type Money")
if to_account.sign == 1 and to_account.type != self.TYPES.trading:
# Transferring from two positive-signed accounts implies that
# the caller wants to reduce the first account and increase the second
# (which is opposite to the implicit behaviour)
direction = -1
elif self.type == self.TYPES.liability and to_account.type == self.TYPES.expense:
# Transfers from liability -> asset accounts should reduce both.
# For example, moving money from Rent Payable (liability) to your Rent (expense) account
# should use the funds you've built up in the liability account to pay off the expense account.
direction = -1
else:
direction = 1
transaction = Transaction.objects.create(**transaction_kwargs)
Leg.objects.create(transaction=transaction, account=self, amount=+amount * direction)
Leg.objects.create(transaction=transaction, account=to_account, amount=-amount * direction)
return transaction | [
"def",
"transfer_to",
"(",
"self",
",",
"to_account",
",",
"amount",
",",
"*",
"*",
"transaction_kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"amount",
",",
"Money",
")",
":",
"raise",
"TypeError",
"(",
"\"amount must be of type Money\"",
")",
"if",
"t... | Create a transaction which transfers amount to to_account
This is a shortcut utility method which simplifies the process of
transferring between accounts.
This method attempts to perform the transaction in an intuitive manner.
For example:
* Transferring income -> income will result in the former decreasing and the latter increasing
* Transferring asset (i.e. bank) -> income will result in the balance of both increasing
* Transferring asset -> asset will result in the former decreasing and the latter increasing
.. note::
Transfers in any direction between ``{asset | expense} <-> {income | liability | equity}``
will always result in both balances increasing. This may change in future if it is
found to be unhelpful.
Transfers to trading accounts will always behave as normal.
Args:
to_account (Account): The destination account.
amount (Money): The amount to be transferred.
transaction_kwargs: Passed through to transaction creation. Useful for setting the
transaction `description` field. | [
"Create",
"a",
"transaction",
"which",
"transfers",
"amount",
"to",
"to_account"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L251-L298 | train | 206,323 |
adamcharnock/django-hordak | hordak/models/core.py | LegQuerySet.sum_to_balance | def sum_to_balance(self):
"""Sum the Legs of the QuerySet to get a `Balance`_ object
"""
result = self.values("amount_currency").annotate(total=models.Sum("amount"))
return Balance([Money(r["total"], r["amount_currency"]) for r in result]) | python | def sum_to_balance(self):
"""Sum the Legs of the QuerySet to get a `Balance`_ object
"""
result = self.values("amount_currency").annotate(total=models.Sum("amount"))
return Balance([Money(r["total"], r["amount_currency"]) for r in result]) | [
"def",
"sum_to_balance",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"values",
"(",
"\"amount_currency\"",
")",
".",
"annotate",
"(",
"total",
"=",
"models",
".",
"Sum",
"(",
"\"amount\"",
")",
")",
"return",
"Balance",
"(",
"[",
"Money",
"(",
"... | Sum the Legs of the QuerySet to get a `Balance`_ object | [
"Sum",
"the",
"Legs",
"of",
"the",
"QuerySet",
"to",
"get",
"a",
"Balance",
"_",
"object"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L366-L370 | train | 206,324 |
adamcharnock/django-hordak | hordak/models/core.py | Leg.account_balance_after | def account_balance_after(self):
"""Get the balance of the account associated with this leg following the transaction"""
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support
transaction_date = self.transaction.date
return self.account.balance(
leg_query=(
models.Q(transaction__date__lt=transaction_date)
| (
models.Q(transaction__date=transaction_date)
& models.Q(transaction_id__lte=self.transaction_id)
)
)
) | python | def account_balance_after(self):
"""Get the balance of the account associated with this leg following the transaction"""
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support
transaction_date = self.transaction.date
return self.account.balance(
leg_query=(
models.Q(transaction__date__lt=transaction_date)
| (
models.Q(transaction__date=transaction_date)
& models.Q(transaction_id__lte=self.transaction_id)
)
)
) | [
"def",
"account_balance_after",
"(",
"self",
")",
":",
"# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support",
"transaction_date",
"=",
"self",
".",
"transaction",
".",
"date",
"return",
"self",
".",
"account",
".",
"balance",
... | Get the balance of the account associated with this leg following the transaction | [
"Get",
"the",
"balance",
"of",
"the",
"account",
"associated",
"with",
"this",
"leg",
"following",
"the",
"transaction"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L441-L453 | train | 206,325 |
adamcharnock/django-hordak | hordak/models/core.py | Leg.account_balance_before | def account_balance_before(self):
"""Get the balance of the account associated with this leg before the transaction"""
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support
transaction_date = self.transaction.date
return self.account.balance(
leg_query=(
models.Q(transaction__date__lt=transaction_date)
| (
models.Q(transaction__date=transaction_date)
& models.Q(transaction_id__lt=self.transaction_id)
)
)
) | python | def account_balance_before(self):
"""Get the balance of the account associated with this leg before the transaction"""
# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support
transaction_date = self.transaction.date
return self.account.balance(
leg_query=(
models.Q(transaction__date__lt=transaction_date)
| (
models.Q(transaction__date=transaction_date)
& models.Q(transaction_id__lt=self.transaction_id)
)
)
) | [
"def",
"account_balance_before",
"(",
"self",
")",
":",
"# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support",
"transaction_date",
"=",
"self",
".",
"transaction",
".",
"date",
"return",
"self",
".",
"account",
".",
"balance",... | Get the balance of the account associated with this leg before the transaction | [
"Get",
"the",
"balance",
"of",
"the",
"account",
"associated",
"with",
"this",
"leg",
"before",
"the",
"transaction"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L455-L467 | train | 206,326 |
adamcharnock/django-hordak | hordak/models/core.py | StatementLine.create_transaction | def create_transaction(self, to_account):
"""Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transaction is into / out of.
Returns:
Transaction: The newly created (and committed) transaction.
"""
from_account = self.statement_import.bank_account
transaction = Transaction.objects.create()
Leg.objects.create(
transaction=transaction, account=from_account, amount=+(self.amount * -1)
)
Leg.objects.create(transaction=transaction, account=to_account, amount=-(self.amount * -1))
transaction.date = self.date
transaction.save()
self.transaction = transaction
self.save()
return transaction | python | def create_transaction(self, to_account):
"""Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transaction is into / out of.
Returns:
Transaction: The newly created (and committed) transaction.
"""
from_account = self.statement_import.bank_account
transaction = Transaction.objects.create()
Leg.objects.create(
transaction=transaction, account=from_account, amount=+(self.amount * -1)
)
Leg.objects.create(transaction=transaction, account=to_account, amount=-(self.amount * -1))
transaction.date = self.date
transaction.save()
self.transaction = transaction
self.save()
return transaction | [
"def",
"create_transaction",
"(",
"self",
",",
"to_account",
")",
":",
"from_account",
"=",
"self",
".",
"statement_import",
".",
"bank_account",
"transaction",
"=",
"Transaction",
".",
"objects",
".",
"create",
"(",
")",
"Leg",
".",
"objects",
".",
"create",
... | Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transaction is into / out of.
Returns:
Transaction: The newly created (and committed) transaction. | [
"Create",
"a",
"transaction",
"for",
"this",
"statement",
"amount",
"and",
"account",
"into",
"to_account"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L574-L600 | train | 206,327 |
adamcharnock/django-hordak | hordak/utilities/currency.py | currency_exchange | def currency_exchange(
source,
source_amount,
destination,
destination_amount,
trading_account,
fee_destination=None,
fee_amount=None,
date=None,
description=None,
):
""" Exchange funds from one currency to another
Use this method to represent a real world currency transfer. Note this
process doesn't care about exchange rates, only about the value
of currency going in and out of the transaction.
You can also record any exchange fees by syphoning off funds to ``fee_account`` of amount ``fee_amount``. Note
that the free currency must be the same as the source currency.
Examples:
For example, imagine our Canadian bank has obligingly transferred 120 CAD into our US bank account.
We sent CAD 120, and received USD 100. We were also changed 1.50 CAD in fees.
We can represent this exchange in Hordak as follows::
from hordak.utilities.currency import currency_exchange
currency_exchange(
# Source account and amount
source=cad_cash,
source_amount=Money(120, 'CAD'),
# Destination account and amount
destination=usd_cash,
destination_amount=Money(100, 'USD'),
# Trading account the exchange will be done through
trading_account=trading,
# We also incur some fees
fee_destination=banking_fees,
fee_amount=Money(1.50, 'CAD')
)
We should now find that:
1. ``cad_cash.balance()`` has decreased by ``CAD 120``
2. ``usd_cash.balance()`` has increased by ``USD 100``
3. ``banking_fees.balance()`` is ``CAD 1.50``
4. ``trading_account.balance()`` is ``USD 100, CAD -120``
You can perform ``trading_account.normalise()`` to discover your unrealised gains/losses
on currency traded through that account.
Args:
source (Account): The account the funds will be taken from
source_amount (Money): A ``Money`` instance containing the inbound amount and currency.
destination (Account): The account the funds will be placed into
destination_amount (Money): A ``Money`` instance containing the outbound amount and currency
trading_account (Account): The trading account to be used. The normalised balance of this account will indicate
gains/losses you have made as part of your activity via this account. Note that the normalised balance
fluctuates with the current exchange rate.
fee_destination (Account): Your exchange may incur fees. Specifying this will move incurred fees
into this account (optional).
fee_amount (Money): The amount and currency of any incurred fees (optional).
description (str): Description for the transaction. Will default to describing funds in/out & fees (optional).
date (datetime.date): The date on which the transaction took place. Defaults to today (optional).
Returns:
(Transaction): The transaction created
See Also:
You can see the above example in practice in ``CurrencyExchangeTestCase.test_fees`` in `test_currency.py`_.
.. _test_currency.py: https://github.com/adamcharnock/django-hordak/blob/master/hordak/tests/utilities/test_currency.py
"""
from hordak.models import Account, Transaction, Leg
if trading_account.type != Account.TYPES.trading:
raise TradingAccountRequiredError(
"Account {} must be a trading account".format(trading_account)
)
if (fee_destination or fee_amount) and not (fee_destination and fee_amount):
raise RuntimeError(
"You must specify either neither or both fee_destination and fee_amount."
)
if fee_amount is None:
# If fees are not specified then set fee_amount to be zero
fee_amount = Money(0, source_amount.currency)
else:
# If we do have fees then make sure the fee currency matches the source currency
if fee_amount.currency != source_amount.currency:
raise InvalidFeeCurrency(
"Fee amount currency ({}) must match source amount currency ({})".format(
fee_amount.currency, source_amount.currency
)
)
# Checks over and done now. Let's create the transaction
with db_transaction.atomic():
transaction = Transaction.objects.create(
date=date or datetime.date.today(),
description=description
or "Exchange of {} to {}, incurring {} fees".format(
source_amount, destination_amount, "no" if fee_amount is None else fee_amount
),
)
# Source currency into trading account
Leg.objects.create(transaction=transaction, account=source, amount=source_amount)
Leg.objects.create(
transaction=transaction, account=trading_account, amount=-(source_amount - fee_amount)
)
# Any fees
if fee_amount and fee_destination:
Leg.objects.create(
transaction=transaction,
account=fee_destination,
amount=-fee_amount,
description="Fees",
)
# Destination currency out of trading account
Leg.objects.create(
transaction=transaction, account=trading_account, amount=destination_amount
)
Leg.objects.create(transaction=transaction, account=destination, amount=-destination_amount)
return transaction | python | def currency_exchange(
source,
source_amount,
destination,
destination_amount,
trading_account,
fee_destination=None,
fee_amount=None,
date=None,
description=None,
):
""" Exchange funds from one currency to another
Use this method to represent a real world currency transfer. Note this
process doesn't care about exchange rates, only about the value
of currency going in and out of the transaction.
You can also record any exchange fees by syphoning off funds to ``fee_account`` of amount ``fee_amount``. Note
that the free currency must be the same as the source currency.
Examples:
For example, imagine our Canadian bank has obligingly transferred 120 CAD into our US bank account.
We sent CAD 120, and received USD 100. We were also changed 1.50 CAD in fees.
We can represent this exchange in Hordak as follows::
from hordak.utilities.currency import currency_exchange
currency_exchange(
# Source account and amount
source=cad_cash,
source_amount=Money(120, 'CAD'),
# Destination account and amount
destination=usd_cash,
destination_amount=Money(100, 'USD'),
# Trading account the exchange will be done through
trading_account=trading,
# We also incur some fees
fee_destination=banking_fees,
fee_amount=Money(1.50, 'CAD')
)
We should now find that:
1. ``cad_cash.balance()`` has decreased by ``CAD 120``
2. ``usd_cash.balance()`` has increased by ``USD 100``
3. ``banking_fees.balance()`` is ``CAD 1.50``
4. ``trading_account.balance()`` is ``USD 100, CAD -120``
You can perform ``trading_account.normalise()`` to discover your unrealised gains/losses
on currency traded through that account.
Args:
source (Account): The account the funds will be taken from
source_amount (Money): A ``Money`` instance containing the inbound amount and currency.
destination (Account): The account the funds will be placed into
destination_amount (Money): A ``Money`` instance containing the outbound amount and currency
trading_account (Account): The trading account to be used. The normalised balance of this account will indicate
gains/losses you have made as part of your activity via this account. Note that the normalised balance
fluctuates with the current exchange rate.
fee_destination (Account): Your exchange may incur fees. Specifying this will move incurred fees
into this account (optional).
fee_amount (Money): The amount and currency of any incurred fees (optional).
description (str): Description for the transaction. Will default to describing funds in/out & fees (optional).
date (datetime.date): The date on which the transaction took place. Defaults to today (optional).
Returns:
(Transaction): The transaction created
See Also:
You can see the above example in practice in ``CurrencyExchangeTestCase.test_fees`` in `test_currency.py`_.
.. _test_currency.py: https://github.com/adamcharnock/django-hordak/blob/master/hordak/tests/utilities/test_currency.py
"""
from hordak.models import Account, Transaction, Leg
if trading_account.type != Account.TYPES.trading:
raise TradingAccountRequiredError(
"Account {} must be a trading account".format(trading_account)
)
if (fee_destination or fee_amount) and not (fee_destination and fee_amount):
raise RuntimeError(
"You must specify either neither or both fee_destination and fee_amount."
)
if fee_amount is None:
# If fees are not specified then set fee_amount to be zero
fee_amount = Money(0, source_amount.currency)
else:
# If we do have fees then make sure the fee currency matches the source currency
if fee_amount.currency != source_amount.currency:
raise InvalidFeeCurrency(
"Fee amount currency ({}) must match source amount currency ({})".format(
fee_amount.currency, source_amount.currency
)
)
# Checks over and done now. Let's create the transaction
with db_transaction.atomic():
transaction = Transaction.objects.create(
date=date or datetime.date.today(),
description=description
or "Exchange of {} to {}, incurring {} fees".format(
source_amount, destination_amount, "no" if fee_amount is None else fee_amount
),
)
# Source currency into trading account
Leg.objects.create(transaction=transaction, account=source, amount=source_amount)
Leg.objects.create(
transaction=transaction, account=trading_account, amount=-(source_amount - fee_amount)
)
# Any fees
if fee_amount and fee_destination:
Leg.objects.create(
transaction=transaction,
account=fee_destination,
amount=-fee_amount,
description="Fees",
)
# Destination currency out of trading account
Leg.objects.create(
transaction=transaction, account=trading_account, amount=destination_amount
)
Leg.objects.create(transaction=transaction, account=destination, amount=-destination_amount)
return transaction | [
"def",
"currency_exchange",
"(",
"source",
",",
"source_amount",
",",
"destination",
",",
"destination_amount",
",",
"trading_account",
",",
"fee_destination",
"=",
"None",
",",
"fee_amount",
"=",
"None",
",",
"date",
"=",
"None",
",",
"description",
"=",
"None"... | Exchange funds from one currency to another
Use this method to represent a real world currency transfer. Note this
process doesn't care about exchange rates, only about the value
of currency going in and out of the transaction.
You can also record any exchange fees by syphoning off funds to ``fee_account`` of amount ``fee_amount``. Note
that the free currency must be the same as the source currency.
Examples:
For example, imagine our Canadian bank has obligingly transferred 120 CAD into our US bank account.
We sent CAD 120, and received USD 100. We were also changed 1.50 CAD in fees.
We can represent this exchange in Hordak as follows::
from hordak.utilities.currency import currency_exchange
currency_exchange(
# Source account and amount
source=cad_cash,
source_amount=Money(120, 'CAD'),
# Destination account and amount
destination=usd_cash,
destination_amount=Money(100, 'USD'),
# Trading account the exchange will be done through
trading_account=trading,
# We also incur some fees
fee_destination=banking_fees,
fee_amount=Money(1.50, 'CAD')
)
We should now find that:
1. ``cad_cash.balance()`` has decreased by ``CAD 120``
2. ``usd_cash.balance()`` has increased by ``USD 100``
3. ``banking_fees.balance()`` is ``CAD 1.50``
4. ``trading_account.balance()`` is ``USD 100, CAD -120``
You can perform ``trading_account.normalise()`` to discover your unrealised gains/losses
on currency traded through that account.
Args:
source (Account): The account the funds will be taken from
source_amount (Money): A ``Money`` instance containing the inbound amount and currency.
destination (Account): The account the funds will be placed into
destination_amount (Money): A ``Money`` instance containing the outbound amount and currency
trading_account (Account): The trading account to be used. The normalised balance of this account will indicate
gains/losses you have made as part of your activity via this account. Note that the normalised balance
fluctuates with the current exchange rate.
fee_destination (Account): Your exchange may incur fees. Specifying this will move incurred fees
into this account (optional).
fee_amount (Money): The amount and currency of any incurred fees (optional).
description (str): Description for the transaction. Will default to describing funds in/out & fees (optional).
date (datetime.date): The date on which the transaction took place. Defaults to today (optional).
Returns:
(Transaction): The transaction created
See Also:
You can see the above example in practice in ``CurrencyExchangeTestCase.test_fees`` in `test_currency.py`_.
.. _test_currency.py: https://github.com/adamcharnock/django-hordak/blob/master/hordak/tests/utilities/test_currency.py | [
"Exchange",
"funds",
"from",
"one",
"currency",
"to",
"another"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L88-L218 | train | 206,328 |
adamcharnock/django-hordak | hordak/utilities/currency.py | BaseBackend.cache_rate | def cache_rate(self, currency, date, rate):
"""
Cache a rate for future use
"""
if not self.is_supported(defaults.INTERNAL_CURRENCY):
logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency))
else:
cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date)) | python | def cache_rate(self, currency, date, rate):
"""
Cache a rate for future use
"""
if not self.is_supported(defaults.INTERNAL_CURRENCY):
logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency))
else:
cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date)) | [
"def",
"cache_rate",
"(",
"self",
",",
"currency",
",",
"date",
",",
"rate",
")",
":",
"if",
"not",
"self",
".",
"is_supported",
"(",
"defaults",
".",
"INTERNAL_CURRENCY",
")",
":",
"logger",
".",
"info",
"(",
"'Tried to cache unsupported currency \"{}\". Ignori... | Cache a rate for future use | [
"Cache",
"a",
"rate",
"for",
"future",
"use"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L237-L244 | train | 206,329 |
adamcharnock/django-hordak | hordak/utilities/currency.py | BaseBackend.get_rate | def get_rate(self, currency, date):
"""Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY``
If implementing your own backend, you should probably override :meth:`_get_rate()`
rather than this.
"""
if str(currency) == defaults.INTERNAL_CURRENCY:
return Decimal(1)
cached = cache.get(_cache_key(currency, date))
if cached:
return Decimal(cached)
else:
# Expect self._get_rate() to implement caching
return Decimal(self._get_rate(currency, date)) | python | def get_rate(self, currency, date):
"""Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY``
If implementing your own backend, you should probably override :meth:`_get_rate()`
rather than this.
"""
if str(currency) == defaults.INTERNAL_CURRENCY:
return Decimal(1)
cached = cache.get(_cache_key(currency, date))
if cached:
return Decimal(cached)
else:
# Expect self._get_rate() to implement caching
return Decimal(self._get_rate(currency, date)) | [
"def",
"get_rate",
"(",
"self",
",",
"currency",
",",
"date",
")",
":",
"if",
"str",
"(",
"currency",
")",
"==",
"defaults",
".",
"INTERNAL_CURRENCY",
":",
"return",
"Decimal",
"(",
"1",
")",
"cached",
"=",
"cache",
".",
"get",
"(",
"_cache_key",
"(",
... | Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY``
If implementing your own backend, you should probably override :meth:`_get_rate()`
rather than this. | [
"Get",
"the",
"exchange",
"rate",
"for",
"currency",
"against",
"_INTERNAL_CURRENCY"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L246-L260 | train | 206,330 |
adamcharnock/django-hordak | hordak/utilities/currency.py | Converter.convert | def convert(self, money, to_currency, date=None):
"""Convert the given ``money`` to ``to_currency`` using exchange rate on ``date``
If ``date`` is omitted then the date given by ``money.date`` will be used.
"""
if str(money.currency) == str(to_currency):
return copy.copy(money)
return Money(
amount=money.amount
* self.rate(money.currency, to_currency, date or datetime.date.today()),
currency=to_currency,
) | python | def convert(self, money, to_currency, date=None):
"""Convert the given ``money`` to ``to_currency`` using exchange rate on ``date``
If ``date`` is omitted then the date given by ``money.date`` will be used.
"""
if str(money.currency) == str(to_currency):
return copy.copy(money)
return Money(
amount=money.amount
* self.rate(money.currency, to_currency, date or datetime.date.today()),
currency=to_currency,
) | [
"def",
"convert",
"(",
"self",
",",
"money",
",",
"to_currency",
",",
"date",
"=",
"None",
")",
":",
"if",
"str",
"(",
"money",
".",
"currency",
")",
"==",
"str",
"(",
"to_currency",
")",
":",
"return",
"copy",
".",
"copy",
"(",
"money",
")",
"retu... | Convert the given ``money`` to ``to_currency`` using exchange rate on ``date``
If ``date`` is omitted then the date given by ``money.date`` will be used. | [
"Convert",
"the",
"given",
"money",
"to",
"to_currency",
"using",
"exchange",
"rate",
"on",
"date"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L354-L365 | train | 206,331 |
adamcharnock/django-hordak | hordak/utilities/currency.py | Converter.rate | def rate(self, from_currency, to_currency, date):
"""Get the exchange rate between the specified currencies"""
return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(
to_currency, date
) | python | def rate(self, from_currency, to_currency, date):
"""Get the exchange rate between the specified currencies"""
return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(
to_currency, date
) | [
"def",
"rate",
"(",
"self",
",",
"from_currency",
",",
"to_currency",
",",
"date",
")",
":",
"return",
"(",
"1",
"/",
"self",
".",
"backend",
".",
"get_rate",
"(",
"from_currency",
",",
"date",
")",
")",
"*",
"self",
".",
"backend",
".",
"get_rate",
... | Get the exchange rate between the specified currencies | [
"Get",
"the",
"exchange",
"rate",
"between",
"the",
"specified",
"currencies"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L367-L371 | train | 206,332 |
adamcharnock/django-hordak | hordak/utilities/currency.py | Balance.currencies | def currencies(self):
"""Get all currencies with non-zero values"""
return [m.currency.code for m in self.monies() if m.amount] | python | def currencies(self):
"""Get all currencies with non-zero values"""
return [m.currency.code for m in self.monies() if m.amount] | [
"def",
"currencies",
"(",
"self",
")",
":",
"return",
"[",
"m",
".",
"currency",
".",
"code",
"for",
"m",
"in",
"self",
".",
"monies",
"(",
")",
"if",
"m",
".",
"amount",
"]"
] | Get all currencies with non-zero values | [
"Get",
"all",
"currencies",
"with",
"non",
"-",
"zero",
"values"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L542-L544 | train | 206,333 |
adamcharnock/django-hordak | hordak/utilities/currency.py | Balance.normalise | def normalise(self, to_currency):
"""Normalise this balance into a single currency
Args:
to_currency (str): Destination currency
Returns:
(Balance): A new balance object containing a single Money value in the specified currency
"""
out = Money(currency=to_currency)
for money in self._money_obs:
out += converter.convert(money, to_currency)
return Balance([out]) | python | def normalise(self, to_currency):
"""Normalise this balance into a single currency
Args:
to_currency (str): Destination currency
Returns:
(Balance): A new balance object containing a single Money value in the specified currency
"""
out = Money(currency=to_currency)
for money in self._money_obs:
out += converter.convert(money, to_currency)
return Balance([out]) | [
"def",
"normalise",
"(",
"self",
",",
"to_currency",
")",
":",
"out",
"=",
"Money",
"(",
"currency",
"=",
"to_currency",
")",
"for",
"money",
"in",
"self",
".",
"_money_obs",
":",
"out",
"+=",
"converter",
".",
"convert",
"(",
"money",
",",
"to_currency"... | Normalise this balance into a single currency
Args:
to_currency (str): Destination currency
Returns:
(Balance): A new balance object containing a single Money value in the specified currency | [
"Normalise",
"this",
"balance",
"into",
"a",
"single",
"currency"
] | 0ffcad1d3b388b860c8c47fde12aa40df213066f | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/utilities/currency.py#L546-L558 | train | 206,334 |
thornomad/django-hitcount | hitcount/managers.py | HitManager.filter_active | def filter_active(self, *args, **kwargs):
"""
Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defaulf is to consider a visitor's hit still 'active' if they
return within a the last seven days.. After that the hit
will be counted again. So if one person visits once a week for a year,
they will add 52 hits to a given object.
Change how long the expiration is by adding to settings.py:
HITCOUNT_KEEP_HIT_ACTIVE = {'days' : 30, 'minutes' : 30}
Accepts days, seconds, microseconds, milliseconds, minutes,
hours, and weeks. It's creating a datetime.timedelta object.
"""
grace = getattr(settings, 'HITCOUNT_KEEP_HIT_ACTIVE', {'days': 7})
period = timezone.now() - timedelta(**grace)
return self.filter(created__gte=period).filter(*args, **kwargs) | python | def filter_active(self, *args, **kwargs):
"""
Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defaulf is to consider a visitor's hit still 'active' if they
return within a the last seven days.. After that the hit
will be counted again. So if one person visits once a week for a year,
they will add 52 hits to a given object.
Change how long the expiration is by adding to settings.py:
HITCOUNT_KEEP_HIT_ACTIVE = {'days' : 30, 'minutes' : 30}
Accepts days, seconds, microseconds, milliseconds, minutes,
hours, and weeks. It's creating a datetime.timedelta object.
"""
grace = getattr(settings, 'HITCOUNT_KEEP_HIT_ACTIVE', {'days': 7})
period = timezone.now() - timedelta(**grace)
return self.filter(created__gte=period).filter(*args, **kwargs) | [
"def",
"filter_active",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"grace",
"=",
"getattr",
"(",
"settings",
",",
"'HITCOUNT_KEEP_HIT_ACTIVE'",
",",
"{",
"'days'",
":",
"7",
"}",
")",
"period",
"=",
"timezone",
".",
"now",
"(",
... | Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defaulf is to consider a visitor's hit still 'active' if they
return within a the last seven days.. After that the hit
will be counted again. So if one person visits once a week for a year,
they will add 52 hits to a given object.
Change how long the expiration is by adding to settings.py:
HITCOUNT_KEEP_HIT_ACTIVE = {'days' : 30, 'minutes' : 30}
Accepts days, seconds, microseconds, milliseconds, minutes,
hours, and weeks. It's creating a datetime.timedelta object. | [
"Return",
"only",
"the",
"active",
"hits",
"."
] | b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416 | https://github.com/thornomad/django-hitcount/blob/b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416/hitcount/managers.py#L22-L45 | train | 206,335 |
thornomad/django-hitcount | example_project/blog/migrations/0002_auto_20150512_1644.py | unload_fixture | def unload_fixture(apps, schema_editor):
"Brutally deleting all entries for this model..."
MyModel = apps.get_model("blog", "Post")
MyModel.objects.all().delete() | python | def unload_fixture(apps, schema_editor):
"Brutally deleting all entries for this model..."
MyModel = apps.get_model("blog", "Post")
MyModel.objects.all().delete() | [
"def",
"unload_fixture",
"(",
"apps",
",",
"schema_editor",
")",
":",
"MyModel",
"=",
"apps",
".",
"get_model",
"(",
"\"blog\"",
",",
"\"Post\"",
")",
"MyModel",
".",
"objects",
".",
"all",
"(",
")",
".",
"delete",
"(",
")"
] | Brutally deleting all entries for this model... | [
"Brutally",
"deleting",
"all",
"entries",
"for",
"this",
"model",
"..."
] | b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416 | https://github.com/thornomad/django-hitcount/blob/b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416/example_project/blog/migrations/0002_auto_20150512_1644.py#L29-L33 | train | 206,336 |
thornomad/django-hitcount | hitcount/utils.py | get_ip | def get_ip(request):
"""
Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy will put the
REMOTE_ADDR into HTTP_X_FORWARDED_FOR. This will handle pulling back the
IP from the proper place.
**NOTE** This function was taken from django-tracking (MIT LICENSE)
http://code.google.com/p/django-tracking/
"""
# if neither header contain a value, just use local loopback
ip_address = request.META.get('HTTP_X_FORWARDED_FOR',
request.META.get('REMOTE_ADDR', '127.0.0.1'))
if ip_address:
# make sure we have one and only one IP
try:
ip_address = IP_RE.match(ip_address)
if ip_address:
ip_address = ip_address.group(0)
else:
# no IP, probably from some dirty proxy or other device
# throw in some bogus IP
ip_address = '10.0.0.1'
except IndexError:
pass
return ip_address | python | def get_ip(request):
"""
Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy will put the
REMOTE_ADDR into HTTP_X_FORWARDED_FOR. This will handle pulling back the
IP from the proper place.
**NOTE** This function was taken from django-tracking (MIT LICENSE)
http://code.google.com/p/django-tracking/
"""
# if neither header contain a value, just use local loopback
ip_address = request.META.get('HTTP_X_FORWARDED_FOR',
request.META.get('REMOTE_ADDR', '127.0.0.1'))
if ip_address:
# make sure we have one and only one IP
try:
ip_address = IP_RE.match(ip_address)
if ip_address:
ip_address = ip_address.group(0)
else:
# no IP, probably from some dirty proxy or other device
# throw in some bogus IP
ip_address = '10.0.0.1'
except IndexError:
pass
return ip_address | [
"def",
"get_ip",
"(",
"request",
")",
":",
"# if neither header contain a value, just use local loopback",
"ip_address",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_FORWARDED_FOR'",
",",
"request",
".",
"META",
".",
"get",
"(",
"'REMOTE_ADDR'",
",",
"'127... | Retrieves the remote IP address from the request data. If the user is
behind a proxy, they may have a comma-separated list of IP addresses, so
we need to account for that. In such a case, only the first IP in the
list will be retrieved. Also, some hosts that use a proxy will put the
REMOTE_ADDR into HTTP_X_FORWARDED_FOR. This will handle pulling back the
IP from the proper place.
**NOTE** This function was taken from django-tracking (MIT LICENSE)
http://code.google.com/p/django-tracking/ | [
"Retrieves",
"the",
"remote",
"IP",
"address",
"from",
"the",
"request",
"data",
".",
"If",
"the",
"user",
"is",
"behind",
"a",
"proxy",
"they",
"may",
"have",
"a",
"comma",
"-",
"separated",
"list",
"of",
"IP",
"addresses",
"so",
"we",
"need",
"to",
"... | b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416 | https://github.com/thornomad/django-hitcount/blob/b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416/hitcount/utils.py#L11-L40 | train | 206,337 |
thornomad/django-hitcount | hitcount/views.py | update_hit_count_ajax | def update_hit_count_ajax(request, *args, **kwargs):
"""
Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead.
"""
warnings.warn(
"hitcount.views.update_hit_count_ajax is deprecated. "
"Use hitcount.views.HitCountJSONView instead.",
RemovedInHitCount13Warning
)
view = HitCountJSONView.as_view()
return view(request, *args, **kwargs) | python | def update_hit_count_ajax(request, *args, **kwargs):
"""
Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead.
"""
warnings.warn(
"hitcount.views.update_hit_count_ajax is deprecated. "
"Use hitcount.views.HitCountJSONView instead.",
RemovedInHitCount13Warning
)
view = HitCountJSONView.as_view()
return view(request, *args, **kwargs) | [
"def",
"update_hit_count_ajax",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"hitcount.views.update_hit_count_ajax is deprecated. \"",
"\"Use hitcount.views.HitCountJSONView instead.\"",
",",
"RemovedInHitCount13Warning"... | Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead. | [
"Deprecated",
"in",
"1",
".",
"2",
".",
"Use",
"hitcount",
".",
"views",
".",
"HitCountJSONView",
"instead",
"."
] | b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416 | https://github.com/thornomad/django-hitcount/blob/b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416/hitcount/views.py#L179-L189 | train | 206,338 |
thornomad/django-hitcount | hitcount/templatetags/hitcount_tags.py | get_hit_count_from_obj_variable | def get_hit_count_from_obj_variable(context, obj_variable, tag_name):
"""
Helper function to return a HitCount for a given template object variable.
Raises TemplateSyntaxError if the passed object variable cannot be parsed.
"""
error_to_raise = template.TemplateSyntaxError(
"'%(a)s' requires a valid individual model variable "
"in the form of '%(a)s for [model_obj]'.\n"
"Got: %(b)s" % {'a': tag_name, 'b': obj_variable}
)
try:
obj = obj_variable.resolve(context)
except template.VariableDoesNotExist:
raise error_to_raise
try:
ctype = ContentType.objects.get_for_model(obj)
except AttributeError:
raise error_to_raise
hit_count, created = HitCount.objects.get_or_create(
content_type=ctype, object_pk=obj.pk)
return hit_count | python | def get_hit_count_from_obj_variable(context, obj_variable, tag_name):
"""
Helper function to return a HitCount for a given template object variable.
Raises TemplateSyntaxError if the passed object variable cannot be parsed.
"""
error_to_raise = template.TemplateSyntaxError(
"'%(a)s' requires a valid individual model variable "
"in the form of '%(a)s for [model_obj]'.\n"
"Got: %(b)s" % {'a': tag_name, 'b': obj_variable}
)
try:
obj = obj_variable.resolve(context)
except template.VariableDoesNotExist:
raise error_to_raise
try:
ctype = ContentType.objects.get_for_model(obj)
except AttributeError:
raise error_to_raise
hit_count, created = HitCount.objects.get_or_create(
content_type=ctype, object_pk=obj.pk)
return hit_count | [
"def",
"get_hit_count_from_obj_variable",
"(",
"context",
",",
"obj_variable",
",",
"tag_name",
")",
":",
"error_to_raise",
"=",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'%(a)s' requires a valid individual model variable \"",
"\"in the form of '%(a)s for [model_obj]'.\\n\"",... | Helper function to return a HitCount for a given template object variable.
Raises TemplateSyntaxError if the passed object variable cannot be parsed. | [
"Helper",
"function",
"to",
"return",
"a",
"HitCount",
"for",
"a",
"given",
"template",
"object",
"variable",
"."
] | b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416 | https://github.com/thornomad/django-hitcount/blob/b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416/hitcount/templatetags/hitcount_tags.py#L17-L42 | train | 206,339 |
cloudant/python-cloudant | src/cloudant/feed.py | Feed._start | def _start(self):
"""
Starts streaming the feed using the provided session and feed options.
"""
params = self._translate(self._options)
self._resp = self._r_session.get(self._url, params=params, stream=True)
self._resp.raise_for_status()
self._lines = self._resp.iter_lines(self._chunk_size) | python | def _start(self):
"""
Starts streaming the feed using the provided session and feed options.
"""
params = self._translate(self._options)
self._resp = self._r_session.get(self._url, params=params, stream=True)
self._resp.raise_for_status()
self._lines = self._resp.iter_lines(self._chunk_size) | [
"def",
"_start",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"_translate",
"(",
"self",
".",
"_options",
")",
"self",
".",
"_resp",
"=",
"self",
".",
"_r_session",
".",
"get",
"(",
"self",
".",
"_url",
",",
"params",
"=",
"params",
",",
"str... | Starts streaming the feed using the provided session and feed options. | [
"Starts",
"streaming",
"the",
"feed",
"using",
"the",
"provided",
"session",
"and",
"feed",
"options",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/feed.py#L82-L89 | train | 206,340 |
cloudant/python-cloudant | src/cloudant/feed.py | Feed.next | def next(self):
"""
Handles the iteration by pulling the next line out of the stream,
attempting to convert the response to JSON if necessary.
:returns: Data representing what was seen in the feed
"""
while True:
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data | python | def next(self):
"""
Handles the iteration by pulling the next line out of the stream,
attempting to convert the response to JSON if necessary.
:returns: Data representing what was seen in the feed
"""
while True:
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data | [
"def",
"next",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"not",
"self",
".",
"_resp",
":",
"self",
".",
"_start",
"(",
")",
"if",
"self",
".",
"_stop",
":",
"raise",
"StopIteration",
"skip",
",",
"data",
"=",
"self",
".",
"_process_data",
... | Handles the iteration by pulling the next line out of the stream,
attempting to convert the response to JSON if necessary.
:returns: Data representing what was seen in the feed | [
"Handles",
"the",
"iteration",
"by",
"pulling",
"the",
"next",
"line",
"out",
"of",
"the",
"stream",
"attempting",
"to",
"convert",
"the",
"response",
"to",
"JSON",
"if",
"necessary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/feed.py#L149-L164 | train | 206,341 |
cloudant/python-cloudant | src/cloudant/feed.py | Feed._process_data | def _process_data(self, line):
"""
Validates and processes the line passed in and converts it to a
Python object if necessary.
"""
skip = False
if self._raw_data:
return skip, line
line = unicode_(line)
if not line:
if (self._options.get('heartbeat', False) and
self._options.get('feed') in ('continuous', 'longpoll') and
not self._last_seq):
line = None
else:
skip = True
elif line in ('{"results":[', '],'):
skip = True
elif line[-1] == ',':
line = line[:-1]
elif line[:10] == ('"last_seq"'):
line = '{' + line
try:
if line:
data = json.loads(line)
if data.get('last_seq'):
self._last_seq = data['last_seq']
skip = True
else:
data = None
except ValueError:
data = {"error": "Bad JSON line", "line": line}
return skip, data | python | def _process_data(self, line):
"""
Validates and processes the line passed in and converts it to a
Python object if necessary.
"""
skip = False
if self._raw_data:
return skip, line
line = unicode_(line)
if not line:
if (self._options.get('heartbeat', False) and
self._options.get('feed') in ('continuous', 'longpoll') and
not self._last_seq):
line = None
else:
skip = True
elif line in ('{"results":[', '],'):
skip = True
elif line[-1] == ',':
line = line[:-1]
elif line[:10] == ('"last_seq"'):
line = '{' + line
try:
if line:
data = json.loads(line)
if data.get('last_seq'):
self._last_seq = data['last_seq']
skip = True
else:
data = None
except ValueError:
data = {"error": "Bad JSON line", "line": line}
return skip, data | [
"def",
"_process_data",
"(",
"self",
",",
"line",
")",
":",
"skip",
"=",
"False",
"if",
"self",
".",
"_raw_data",
":",
"return",
"skip",
",",
"line",
"line",
"=",
"unicode_",
"(",
"line",
")",
"if",
"not",
"line",
":",
"if",
"(",
"self",
".",
"_opt... | Validates and processes the line passed in and converts it to a
Python object if necessary. | [
"Validates",
"and",
"processes",
"the",
"line",
"passed",
"in",
"and",
"converts",
"it",
"to",
"a",
"Python",
"object",
"if",
"necessary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/feed.py#L166-L198 | train | 206,342 |
cloudant/python-cloudant | src/cloudant/feed.py | InfiniteFeed.next | def next(self):
"""
Handles the iteration by pulling the next line out of the stream and
converting the response to JSON.
:returns: Data representing what was seen in the feed
"""
while True:
if self._source == 'CouchDB':
raise CloudantFeedException(101)
if self._last_seq:
self._options.update({'since': self._last_seq})
self._resp = None
self._last_seq = None
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data | python | def next(self):
"""
Handles the iteration by pulling the next line out of the stream and
converting the response to JSON.
:returns: Data representing what was seen in the feed
"""
while True:
if self._source == 'CouchDB':
raise CloudantFeedException(101)
if self._last_seq:
self._options.update({'since': self._last_seq})
self._resp = None
self._last_seq = None
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data | [
"def",
"next",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_source",
"==",
"'CouchDB'",
":",
"raise",
"CloudantFeedException",
"(",
"101",
")",
"if",
"self",
".",
"_last_seq",
":",
"self",
".",
"_options",
".",
"update",
"(",
"{",
... | Handles the iteration by pulling the next line out of the stream and
converting the response to JSON.
:returns: Data representing what was seen in the feed | [
"Handles",
"the",
"iteration",
"by",
"pulling",
"the",
"next",
"line",
"out",
"of",
"the",
"stream",
"and",
"converting",
"the",
"response",
"to",
"JSON",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/feed.py#L240-L261 | train | 206,343 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.features | def features(self):
"""
lazy fetch and cache features
"""
if self._features is None:
metadata = self.metadata()
if "features" in metadata:
self._features = metadata["features"]
else:
self._features = []
return self._features | python | def features(self):
"""
lazy fetch and cache features
"""
if self._features is None:
metadata = self.metadata()
if "features" in metadata:
self._features = metadata["features"]
else:
self._features = []
return self._features | [
"def",
"features",
"(",
"self",
")",
":",
"if",
"self",
".",
"_features",
"is",
"None",
":",
"metadata",
"=",
"self",
".",
"metadata",
"(",
")",
"if",
"\"features\"",
"in",
"metadata",
":",
"self",
".",
"_features",
"=",
"metadata",
"[",
"\"features\"",
... | lazy fetch and cache features | [
"lazy",
"fetch",
"and",
"cache",
"features"
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L133-L143 | train | 206,344 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.connect | def connect(self):
"""
Starts up an authentication session for the client using cookie
authentication if necessary.
"""
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(
timeout=self._timeout
)
elif self._use_basic_auth:
self._use_iam = False
self.r_session = BasicSession(
self._user,
self._auth_token,
self.server_url,
timeout=self._timeout
)
elif self._use_iam:
self.r_session = IAMSession(
self._auth_token,
self.server_url,
auto_renew=self._auto_renew,
client_id=self._iam_client_id,
client_secret=self._iam_client_secret,
timeout=self._timeout
)
else:
self.r_session = CookieSession(
self._user,
self._auth_token,
self.server_url,
auto_renew=self._auto_renew,
timeout=self._timeout
)
# If a Transport Adapter was supplied add it to the session
if self.adapter is not None:
self.r_session.mount(self.server_url, self.adapter)
if self._client_user_header is not None:
self.r_session.headers.update(self._client_user_header)
self.session_login()
# Utilize an event hook to append to the response message
# using :func:`~cloudant.common_util.append_response_error_content`
self.r_session.hooks['response'].append(append_response_error_content) | python | def connect(self):
"""
Starts up an authentication session for the client using cookie
authentication if necessary.
"""
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(
timeout=self._timeout
)
elif self._use_basic_auth:
self._use_iam = False
self.r_session = BasicSession(
self._user,
self._auth_token,
self.server_url,
timeout=self._timeout
)
elif self._use_iam:
self.r_session = IAMSession(
self._auth_token,
self.server_url,
auto_renew=self._auto_renew,
client_id=self._iam_client_id,
client_secret=self._iam_client_secret,
timeout=self._timeout
)
else:
self.r_session = CookieSession(
self._user,
self._auth_token,
self.server_url,
auto_renew=self._auto_renew,
timeout=self._timeout
)
# If a Transport Adapter was supplied add it to the session
if self.adapter is not None:
self.r_session.mount(self.server_url, self.adapter)
if self._client_user_header is not None:
self.r_session.headers.update(self._client_user_header)
self.session_login()
# Utilize an event hook to append to the response message
# using :func:`~cloudant.common_util.append_response_error_content`
self.r_session.hooks['response'].append(append_response_error_content) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"r_session",
":",
"self",
".",
"session_logout",
"(",
")",
"if",
"self",
".",
"admin_party",
":",
"self",
".",
"_use_iam",
"=",
"False",
"self",
".",
"r_session",
"=",
"ClientSession",
"(",
"t... | Starts up an authentication session for the client using cookie
authentication if necessary. | [
"Starts",
"up",
"an",
"authentication",
"session",
"for",
"the",
"client",
"using",
"cookie",
"authentication",
"if",
"necessary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L145-L194 | train | 206,345 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.disconnect | def disconnect(self):
"""
Ends a client authentication session, performs a logout and a clean up.
"""
if self.r_session:
self.session_logout()
self.r_session = None
self.clear() | python | def disconnect(self):
"""
Ends a client authentication session, performs a logout and a clean up.
"""
if self.r_session:
self.session_logout()
self.r_session = None
self.clear() | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"r_session",
":",
"self",
".",
"session_logout",
"(",
")",
"self",
".",
"r_session",
"=",
"None",
"self",
".",
"clear",
"(",
")"
] | Ends a client authentication session, performs a logout and a clean up. | [
"Ends",
"a",
"client",
"authentication",
"session",
"performs",
"a",
"logout",
"and",
"a",
"clean",
"up",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L196-L204 | train | 206,346 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.session_login | def session_login(self, user=None, passwd=None):
"""
Performs a session login by posting the auth information
to the _session endpoint.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server.
"""
self.change_credentials(user=user, auth_token=passwd) | python | def session_login(self, user=None, passwd=None):
"""
Performs a session login by posting the auth information
to the _session endpoint.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server.
"""
self.change_credentials(user=user, auth_token=passwd) | [
"def",
"session_login",
"(",
"self",
",",
"user",
"=",
"None",
",",
"passwd",
"=",
"None",
")",
":",
"self",
".",
"change_credentials",
"(",
"user",
"=",
"user",
",",
"auth_token",
"=",
"passwd",
")"
] | Performs a session login by posting the auth information
to the _session endpoint.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server. | [
"Performs",
"a",
"session",
"login",
"by",
"posting",
"the",
"auth",
"information",
"to",
"the",
"_session",
"endpoint",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L223-L231 | train | 206,347 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.change_credentials | def change_credentials(self, user=None, auth_token=None):
"""
Change login credentials.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server.
"""
self.r_session.set_credentials(user, auth_token)
self.r_session.login() | python | def change_credentials(self, user=None, auth_token=None):
"""
Change login credentials.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server.
"""
self.r_session.set_credentials(user, auth_token)
self.r_session.login() | [
"def",
"change_credentials",
"(",
"self",
",",
"user",
"=",
"None",
",",
"auth_token",
"=",
"None",
")",
":",
"self",
".",
"r_session",
".",
"set_credentials",
"(",
"user",
",",
"auth_token",
")",
"self",
".",
"r_session",
".",
"login",
"(",
")"
] | Change login credentials.
:param str user: Username used to connect to server.
:param str auth_token: Authentication token used to connect to server. | [
"Change",
"login",
"credentials",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L233-L241 | train | 206,348 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.all_dbs | def all_dbs(self):
"""
Retrieves a list of all database names for the current client.
:returns: List of database names for the client
"""
url = '/'.join((self.server_url, '_all_dbs'))
resp = self.r_session.get(url)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def all_dbs(self):
"""
Retrieves a list of all database names for the current client.
:returns: List of database names for the client
"""
url = '/'.join((self.server_url, '_all_dbs'))
resp = self.r_session.get(url)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"all_dbs",
"(",
"self",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_all_dbs'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"url",
")",
"resp",
".",
"raise_for_status",
"(",
")"... | Retrieves a list of all database names for the current client.
:returns: List of database names for the client | [
"Retrieves",
"a",
"list",
"of",
"all",
"database",
"names",
"for",
"the",
"current",
"client",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L259-L268 | train | 206,349 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.create_database | def create_database(self, dbname, partitioned=False, **kwargs):
"""
Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely.
:param str dbname: Name used to create the database.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantClientException when attempting to
create a database that already exists.
:param bool partitioned: Create as a partitioned database. Defaults to
``False``.
:returns: The newly created database object
"""
new_db = self._DATABASE_CLASS(self, dbname, partitioned=partitioned)
try:
new_db.create(kwargs.get('throw_on_exists', False))
except CloudantDatabaseException as ex:
if ex.status_code == 412:
raise CloudantClientException(412, dbname)
super(CouchDB, self).__setitem__(dbname, new_db)
return new_db | python | def create_database(self, dbname, partitioned=False, **kwargs):
"""
Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely.
:param str dbname: Name used to create the database.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantClientException when attempting to
create a database that already exists.
:param bool partitioned: Create as a partitioned database. Defaults to
``False``.
:returns: The newly created database object
"""
new_db = self._DATABASE_CLASS(self, dbname, partitioned=partitioned)
try:
new_db.create(kwargs.get('throw_on_exists', False))
except CloudantDatabaseException as ex:
if ex.status_code == 412:
raise CloudantClientException(412, dbname)
super(CouchDB, self).__setitem__(dbname, new_db)
return new_db | [
"def",
"create_database",
"(",
"self",
",",
"dbname",
",",
"partitioned",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"new_db",
"=",
"self",
".",
"_DATABASE_CLASS",
"(",
"self",
",",
"dbname",
",",
"partitioned",
"=",
"partitioned",
")",
"try",
":",... | Creates a new database on the remote server with the name provided
and adds the new database object to the client's locally cached
dictionary before returning it to the caller. The method will
optionally throw a CloudantClientException if the database
exists remotely.
:param str dbname: Name used to create the database.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantClientException when attempting to
create a database that already exists.
:param bool partitioned: Create as a partitioned database. Defaults to
``False``.
:returns: The newly created database object | [
"Creates",
"a",
"new",
"database",
"on",
"the",
"remote",
"server",
"with",
"the",
"name",
"provided",
"and",
"adds",
"the",
"new",
"database",
"object",
"to",
"the",
"client",
"s",
"locally",
"cached",
"dictionary",
"before",
"returning",
"it",
"to",
"the",... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L270-L294 | train | 206,350 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.delete_database | def delete_database(self, dbname):
"""
Removes the named database remotely and locally. The method will throw
a CloudantClientException if the database does not exist.
:param str dbname: Name of the database to delete.
"""
db = self._DATABASE_CLASS(self, dbname)
if not db.exists():
raise CloudantClientException(404, dbname)
db.delete()
if dbname in list(self.keys()):
super(CouchDB, self).__delitem__(dbname) | python | def delete_database(self, dbname):
"""
Removes the named database remotely and locally. The method will throw
a CloudantClientException if the database does not exist.
:param str dbname: Name of the database to delete.
"""
db = self._DATABASE_CLASS(self, dbname)
if not db.exists():
raise CloudantClientException(404, dbname)
db.delete()
if dbname in list(self.keys()):
super(CouchDB, self).__delitem__(dbname) | [
"def",
"delete_database",
"(",
"self",
",",
"dbname",
")",
":",
"db",
"=",
"self",
".",
"_DATABASE_CLASS",
"(",
"self",
",",
"dbname",
")",
"if",
"not",
"db",
".",
"exists",
"(",
")",
":",
"raise",
"CloudantClientException",
"(",
"404",
",",
"dbname",
... | Removes the named database remotely and locally. The method will throw
a CloudantClientException if the database does not exist.
:param str dbname: Name of the database to delete. | [
"Removes",
"the",
"named",
"database",
"remotely",
"and",
"locally",
".",
"The",
"method",
"will",
"throw",
"a",
"CloudantClientException",
"if",
"the",
"database",
"does",
"not",
"exist",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L296-L308 | train | 206,351 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.metadata | def metadata(self):
"""
Retrieves the remote server metadata dictionary.
:returns: Dictionary containing server metadata details
"""
resp = self.r_session.get(self.server_url)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def metadata(self):
"""
Retrieves the remote server metadata dictionary.
:returns: Dictionary containing server metadata details
"""
resp = self.r_session.get(self.server_url)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"metadata",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"self",
".",
"server_url",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"response_to_json_dict",
"(",
"resp",
")"
] | Retrieves the remote server metadata dictionary.
:returns: Dictionary containing server metadata details | [
"Retrieves",
"the",
"remote",
"server",
"metadata",
"dictionary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L351-L359 | train | 206,352 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.keys | def keys(self, remote=False):
"""
Returns the database names for this client. Default is
to return only the locally cached database names, specify
``remote=True`` to make a remote request to include all databases.
:param bool remote: Dictates whether the list of locally cached
database names are returned or a remote request is made to include
an up to date list of databases from the server. Defaults to False.
:returns: List of database names
"""
if not remote:
return list(super(CouchDB, self).keys())
return self.all_dbs() | python | def keys(self, remote=False):
"""
Returns the database names for this client. Default is
to return only the locally cached database names, specify
``remote=True`` to make a remote request to include all databases.
:param bool remote: Dictates whether the list of locally cached
database names are returned or a remote request is made to include
an up to date list of databases from the server. Defaults to False.
:returns: List of database names
"""
if not remote:
return list(super(CouchDB, self).keys())
return self.all_dbs() | [
"def",
"keys",
"(",
"self",
",",
"remote",
"=",
"False",
")",
":",
"if",
"not",
"remote",
":",
"return",
"list",
"(",
"super",
"(",
"CouchDB",
",",
"self",
")",
".",
"keys",
"(",
")",
")",
"return",
"self",
".",
"all_dbs",
"(",
")"
] | Returns the database names for this client. Default is
to return only the locally cached database names, specify
``remote=True`` to make a remote request to include all databases.
:param bool remote: Dictates whether the list of locally cached
database names are returned or a remote request is made to include
an up to date list of databases from the server. Defaults to False.
:returns: List of database names | [
"Returns",
"the",
"database",
"names",
"for",
"this",
"client",
".",
"Default",
"is",
"to",
"return",
"only",
"the",
"locally",
"cached",
"database",
"names",
"specify",
"remote",
"=",
"True",
"to",
"make",
"a",
"remote",
"request",
"to",
"include",
"all",
... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L361-L375 | train | 206,353 |
cloudant/python-cloudant | src/cloudant/client.py | CouchDB.get | def get(self, key, default=None, remote=False):
"""
Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database name used to retrieve the database object.
:param str default: Default database name. Defaults to None.
:param bool remote: Dictates whether the locally cached
database is returned or a remote request is made to retrieve
the database from the server. Defaults to False.
:returns: Database object
"""
if not remote:
return super(CouchDB, self).get(key, default)
db = self._DATABASE_CLASS(self, key)
if db.exists():
super(CouchDB, self).__setitem__(key, db)
return db
return default | python | def get(self, key, default=None, remote=False):
"""
Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database name used to retrieve the database object.
:param str default: Default database name. Defaults to None.
:param bool remote: Dictates whether the locally cached
database is returned or a remote request is made to retrieve
the database from the server. Defaults to False.
:returns: Database object
"""
if not remote:
return super(CouchDB, self).get(key, default)
db = self._DATABASE_CLASS(self, key)
if db.exists():
super(CouchDB, self).__setitem__(key, db)
return db
return default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"remote",
"=",
"False",
")",
":",
"if",
"not",
"remote",
":",
"return",
"super",
"(",
"CouchDB",
",",
"self",
")",
".",
"get",
"(",
"key",
",",
"default",
")",
"db",
"=",
... | Overrides dictionary get behavior to retrieve database objects with
support for returning a default. If remote=True then a remote
request is made to retrieve the database from the remote server,
otherwise the client's locally cached database object is returned.
:param str key: Database name used to retrieve the database object.
:param str default: Default database name. Defaults to None.
:param bool remote: Dictates whether the locally cached
database is returned or a remote request is made to retrieve
the database from the server. Defaults to False.
:returns: Database object | [
"Overrides",
"dictionary",
"get",
"behavior",
"to",
"retrieve",
"database",
"objects",
"with",
"support",
"for",
"returning",
"a",
"default",
".",
"If",
"remote",
"=",
"True",
"then",
"a",
"remote",
"request",
"is",
"made",
"to",
"retrieve",
"the",
"database",... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L421-L443 | train | 206,354 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant._usage_endpoint | def _usage_endpoint(self, endpoint, year=None, month=None):
"""
Common helper for getting usage and billing reports with
optional year and month URL elements.
:param str endpoint: Cloudant usage endpoint.
:param int year: Year to query against. Optional parameter.
Defaults to None. If used, it must be accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
"""
err = False
if year is None and month is None:
resp = self.r_session.get(endpoint)
else:
try:
if int(year) > 0 and int(month) in range(1, 13):
resp = self.r_session.get(
'/'.join((endpoint, str(int(year)), str(int(month)))))
else:
err = True
except (ValueError, TypeError):
err = True
if err:
raise CloudantArgumentError(101, year, month)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def _usage_endpoint(self, endpoint, year=None, month=None):
"""
Common helper for getting usage and billing reports with
optional year and month URL elements.
:param str endpoint: Cloudant usage endpoint.
:param int year: Year to query against. Optional parameter.
Defaults to None. If used, it must be accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
"""
err = False
if year is None and month is None:
resp = self.r_session.get(endpoint)
else:
try:
if int(year) > 0 and int(month) in range(1, 13):
resp = self.r_session.get(
'/'.join((endpoint, str(int(year)), str(int(month)))))
else:
err = True
except (ValueError, TypeError):
err = True
if err:
raise CloudantArgumentError(101, year, month)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"_usage_endpoint",
"(",
"self",
",",
"endpoint",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"err",
"=",
"False",
"if",
"year",
"is",
"None",
"and",
"month",
"is",
"None",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"... | Common helper for getting usage and billing reports with
optional year and month URL elements.
:param str endpoint: Cloudant usage endpoint.
:param int year: Year to query against. Optional parameter.
Defaults to None. If used, it must be accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``. | [
"Common",
"helper",
"for",
"getting",
"usage",
"and",
"billing",
"reports",
"with",
"optional",
"year",
"and",
"month",
"URL",
"elements",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L607-L636 | train | 206,355 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.bill | def bill(self, year=None, month=None):
"""
Retrieves Cloudant billing data, optionally for a given year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Billing data in JSON format
"""
endpoint = '/'.join((self.server_url, '_api', 'v2', 'bill'))
return self._usage_endpoint(endpoint, year, month) | python | def bill(self, year=None, month=None):
"""
Retrieves Cloudant billing data, optionally for a given year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Billing data in JSON format
"""
endpoint = '/'.join((self.server_url, '_api', 'v2', 'bill'))
return self._usage_endpoint(endpoint, year, month) | [
"def",
"bill",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'bill'",
")",
")",
"return",
"self",
".",
"_usa... | Retrieves Cloudant billing data, optionally for a given year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Billing data in JSON format | [
"Retrieves",
"Cloudant",
"billing",
"data",
"optionally",
"for",
"a",
"given",
"year",
"and",
"month",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L638-L652 | train | 206,356 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.volume_usage | def volume_usage(self, year=None, month=None):
"""
Retrieves Cloudant volume usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Volume usage data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'data_volume'))
return self._usage_endpoint(endpoint, year, month) | python | def volume_usage(self, year=None, month=None):
"""
Retrieves Cloudant volume usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Volume usage data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'data_volume'))
return self._usage_endpoint(endpoint, year, month) | [
"def",
"volume_usage",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'usage'",
",",
"'data_volume'",
")",
")",
... | Retrieves Cloudant volume usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Volume usage data in JSON format | [
"Retrieves",
"Cloudant",
"volume",
"usage",
"data",
"optionally",
"for",
"a",
"given",
"year",
"and",
"month",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L654-L670 | train | 206,357 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.requests_usage | def requests_usage(self, year=None, month=None):
"""
Retrieves Cloudant requests usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Requests usage data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'requests'))
return self._usage_endpoint(endpoint, year, month) | python | def requests_usage(self, year=None, month=None):
"""
Retrieves Cloudant requests usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Requests usage data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'requests'))
return self._usage_endpoint(endpoint, year, month) | [
"def",
"requests_usage",
"(",
"self",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'usage'",
",",
"'requests'",
")",
")",
... | Retrieves Cloudant requests usage data, optionally for a given
year and month.
:param int year: Year to query against, for example 2014.
Optional parameter. Defaults to None. If used, it must be
accompanied by ``month``.
:param int month: Month to query against that must be an integer
between 1 and 12. Optional parameter. Defaults to None.
If used, it must be accompanied by ``year``.
:returns: Requests usage data in JSON format | [
"Retrieves",
"Cloudant",
"requests",
"usage",
"data",
"optionally",
"for",
"a",
"given",
"year",
"and",
"month",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L672-L688 | train | 206,358 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.shared_databases | def shared_databases(self):
"""
Retrieves a list containing the names of databases shared
with this account.
:returns: List of database names
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'shared_databases'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data.get('shared_databases', []) | python | def shared_databases(self):
"""
Retrieves a list containing the names of databases shared
with this account.
:returns: List of database names
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'shared_databases'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data.get('shared_databases', []) | [
"def",
"shared_databases",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'user'",
",",
"'shared_databases'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get... | Retrieves a list containing the names of databases shared
with this account.
:returns: List of database names | [
"Retrieves",
"a",
"list",
"containing",
"the",
"names",
"of",
"databases",
"shared",
"with",
"this",
"account",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L690-L702 | train | 206,359 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.cors_configuration | def cors_configuration(self):
"""
Retrieves the current CORS configuration.
:returns: CORS data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def cors_configuration(self):
"""
Retrieves the current CORS configuration.
:returns: CORS data in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"cors_configuration",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'user'",
",",
"'config'",
",",
"'cors'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
... | Retrieves the current CORS configuration.
:returns: CORS data in JSON format | [
"Retrieves",
"the",
"current",
"CORS",
"configuration",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L715-L726 | train | 206,360 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.disable_cors | def disable_cors(self):
"""
Switches CORS off.
:returns: CORS status in JSON format
"""
return self.update_cors_configuration(
enable_cors=False,
allow_credentials=False,
origins=[],
overwrite_origins=True
) | python | def disable_cors(self):
"""
Switches CORS off.
:returns: CORS status in JSON format
"""
return self.update_cors_configuration(
enable_cors=False,
allow_credentials=False,
origins=[],
overwrite_origins=True
) | [
"def",
"disable_cors",
"(",
"self",
")",
":",
"return",
"self",
".",
"update_cors_configuration",
"(",
"enable_cors",
"=",
"False",
",",
"allow_credentials",
"=",
"False",
",",
"origins",
"=",
"[",
"]",
",",
"overwrite_origins",
"=",
"True",
")"
] | Switches CORS off.
:returns: CORS status in JSON format | [
"Switches",
"CORS",
"off",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L728-L739 | train | 206,361 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.update_cors_configuration | def update_cors_configuration(
self,
enable_cors=True,
allow_credentials=True,
origins=None,
overwrite_origins=False):
"""
Merges existing CORS configuration with updated values.
:param bool enable_cors: Enables/disables CORS. Defaults to True.
:param bool allow_credentials: Allows authentication credentials.
Defaults to True.
:param list origins: List of allowed CORS origin(s). Special cases are
a list containing a single "*" which will allow any origin and
an empty list which will not allow any origin. Defaults to None.
:param bool overwrite_origins: Dictates whether the origins list is
overwritten of appended to. Defaults to False.
:returns: CORS configuration update status in JSON format
"""
if origins is None:
origins = []
cors_config = {
'enable_cors': enable_cors,
'allow_credentials': allow_credentials,
'origins': origins
}
if overwrite_origins:
return self._write_cors_configuration(cors_config)
old_config = self.cors_configuration()
# update config values
updated_config = old_config.copy()
updated_config['enable_cors'] = cors_config.get('enable_cors')
updated_config['allow_credentials'] = cors_config.get('allow_credentials')
if cors_config.get('origins') == ["*"]:
updated_config['origins'] = ["*"]
elif old_config.get('origins') != cors_config.get('origins'):
new_origins = list(
set(old_config.get('origins')).union(
set(cors_config.get('origins')))
)
updated_config['origins'] = new_origins
return self._write_cors_configuration(updated_config) | python | def update_cors_configuration(
self,
enable_cors=True,
allow_credentials=True,
origins=None,
overwrite_origins=False):
"""
Merges existing CORS configuration with updated values.
:param bool enable_cors: Enables/disables CORS. Defaults to True.
:param bool allow_credentials: Allows authentication credentials.
Defaults to True.
:param list origins: List of allowed CORS origin(s). Special cases are
a list containing a single "*" which will allow any origin and
an empty list which will not allow any origin. Defaults to None.
:param bool overwrite_origins: Dictates whether the origins list is
overwritten of appended to. Defaults to False.
:returns: CORS configuration update status in JSON format
"""
if origins is None:
origins = []
cors_config = {
'enable_cors': enable_cors,
'allow_credentials': allow_credentials,
'origins': origins
}
if overwrite_origins:
return self._write_cors_configuration(cors_config)
old_config = self.cors_configuration()
# update config values
updated_config = old_config.copy()
updated_config['enable_cors'] = cors_config.get('enable_cors')
updated_config['allow_credentials'] = cors_config.get('allow_credentials')
if cors_config.get('origins') == ["*"]:
updated_config['origins'] = ["*"]
elif old_config.get('origins') != cors_config.get('origins'):
new_origins = list(
set(old_config.get('origins')).union(
set(cors_config.get('origins')))
)
updated_config['origins'] = new_origins
return self._write_cors_configuration(updated_config) | [
"def",
"update_cors_configuration",
"(",
"self",
",",
"enable_cors",
"=",
"True",
",",
"allow_credentials",
"=",
"True",
",",
"origins",
"=",
"None",
",",
"overwrite_origins",
"=",
"False",
")",
":",
"if",
"origins",
"is",
"None",
":",
"origins",
"=",
"[",
... | Merges existing CORS configuration with updated values.
:param bool enable_cors: Enables/disables CORS. Defaults to True.
:param bool allow_credentials: Allows authentication credentials.
Defaults to True.
:param list origins: List of allowed CORS origin(s). Special cases are
a list containing a single "*" which will allow any origin and
an empty list which will not allow any origin. Defaults to None.
:param bool overwrite_origins: Dictates whether the origins list is
overwritten of appended to. Defaults to False.
:returns: CORS configuration update status in JSON format | [
"Merges",
"existing",
"CORS",
"configuration",
"with",
"updated",
"values",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L751-L800 | train | 206,362 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant._write_cors_configuration | def _write_cors_configuration(self, config):
"""
Overwrites the entire CORS config with the values updated in
update_cors_configuration.
:param dict config: Dictionary containing the updated CORS
configuration.
:returns: CORS configuration update status in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.put(
endpoint,
data=json.dumps(config, cls=self.encoder),
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def _write_cors_configuration(self, config):
"""
Overwrites the entire CORS config with the values updated in
update_cors_configuration.
:param dict config: Dictionary containing the updated CORS
configuration.
:returns: CORS configuration update status in JSON format
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.put(
endpoint,
data=json.dumps(config, cls=self.encoder),
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"_write_cors_configuration",
"(",
"self",
",",
"config",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'user'",
",",
"'config'",
",",
"'cors'",
")",
")",
"resp",
"=",
"self"... | Overwrites the entire CORS config with the values updated in
update_cors_configuration.
:param dict config: Dictionary containing the updated CORS
configuration.
:returns: CORS configuration update status in JSON format | [
"Overwrites",
"the",
"entire",
"CORS",
"config",
"with",
"the",
"values",
"updated",
"in",
"update_cors_configuration",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L802-L821 | train | 206,363 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.bluemix | def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs):
"""
Create a Cloudant session using a VCAP_SERVICES environment variable.
:param vcap_services: VCAP_SERVICES environment variable
:type vcap_services: dict or str
:param str instance_name: Optional Bluemix instance name. Only required
if multiple Cloudant instances are available.
:param str service_name: Optional Bluemix service name.
Example usage:
.. code-block:: python
import os
from cloudant.client import Cloudant
client = Cloudant.bluemix(os.getenv('VCAP_SERVICES'),
'Cloudant NoSQL DB')
print client.all_dbs()
"""
service_name = service_name or 'cloudantNoSQLDB' # default service
try:
service = CloudFoundryService(vcap_services,
instance_name=instance_name,
service_name=service_name)
except CloudantException:
raise CloudantClientException(103)
if hasattr(service, 'iam_api_key'):
return Cloudant.iam(service.username,
service.iam_api_key,
url=service.url,
**kwargs)
return Cloudant(service.username,
service.password,
url=service.url,
**kwargs) | python | def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs):
"""
Create a Cloudant session using a VCAP_SERVICES environment variable.
:param vcap_services: VCAP_SERVICES environment variable
:type vcap_services: dict or str
:param str instance_name: Optional Bluemix instance name. Only required
if multiple Cloudant instances are available.
:param str service_name: Optional Bluemix service name.
Example usage:
.. code-block:: python
import os
from cloudant.client import Cloudant
client = Cloudant.bluemix(os.getenv('VCAP_SERVICES'),
'Cloudant NoSQL DB')
print client.all_dbs()
"""
service_name = service_name or 'cloudantNoSQLDB' # default service
try:
service = CloudFoundryService(vcap_services,
instance_name=instance_name,
service_name=service_name)
except CloudantException:
raise CloudantClientException(103)
if hasattr(service, 'iam_api_key'):
return Cloudant.iam(service.username,
service.iam_api_key,
url=service.url,
**kwargs)
return Cloudant(service.username,
service.password,
url=service.url,
**kwargs) | [
"def",
"bluemix",
"(",
"cls",
",",
"vcap_services",
",",
"instance_name",
"=",
"None",
",",
"service_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"service_name",
"=",
"service_name",
"or",
"'cloudantNoSQLDB'",
"# default service",
"try",
":",
"servic... | Create a Cloudant session using a VCAP_SERVICES environment variable.
:param vcap_services: VCAP_SERVICES environment variable
:type vcap_services: dict or str
:param str instance_name: Optional Bluemix instance name. Only required
if multiple Cloudant instances are available.
:param str service_name: Optional Bluemix service name.
Example usage:
.. code-block:: python
import os
from cloudant.client import Cloudant
client = Cloudant.bluemix(os.getenv('VCAP_SERVICES'),
'Cloudant NoSQL DB')
print client.all_dbs() | [
"Create",
"a",
"Cloudant",
"session",
"using",
"a",
"VCAP_SERVICES",
"environment",
"variable",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L824-L862 | train | 206,364 |
cloudant/python-cloudant | src/cloudant/client.py | Cloudant.iam | def iam(cls, account_name, api_key, **kwargs):
"""
Create a Cloudant client that uses IAM authentication.
:param account_name: Cloudant account name.
:param api_key: IAM authentication API key.
"""
return cls(None,
api_key,
account=account_name,
auto_renew=kwargs.get('auto_renew', True),
use_iam=True,
**kwargs) | python | def iam(cls, account_name, api_key, **kwargs):
"""
Create a Cloudant client that uses IAM authentication.
:param account_name: Cloudant account name.
:param api_key: IAM authentication API key.
"""
return cls(None,
api_key,
account=account_name,
auto_renew=kwargs.get('auto_renew', True),
use_iam=True,
**kwargs) | [
"def",
"iam",
"(",
"cls",
",",
"account_name",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"None",
",",
"api_key",
",",
"account",
"=",
"account_name",
",",
"auto_renew",
"=",
"kwargs",
".",
"get",
"(",
"'auto_renew'",
",",... | Create a Cloudant client that uses IAM authentication.
:param account_name: Cloudant account name.
:param api_key: IAM authentication API key. | [
"Create",
"a",
"Cloudant",
"client",
"that",
"uses",
"IAM",
"authentication",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L865-L877 | train | 206,365 |
cloudant/python-cloudant | src/cloudant/query.py | Query.url | def url(self):
"""
Constructs and returns the Query URL.
:returns: Query URL
"""
if self._partition_key:
base_url = self._database.database_partition_url(
self._partition_key)
else:
base_url = self._database.database_url
return base_url + '/_find' | python | def url(self):
"""
Constructs and returns the Query URL.
:returns: Query URL
"""
if self._partition_key:
base_url = self._database.database_partition_url(
self._partition_key)
else:
base_url = self._database.database_url
return base_url + '/_find' | [
"def",
"url",
"(",
"self",
")",
":",
"if",
"self",
".",
"_partition_key",
":",
"base_url",
"=",
"self",
".",
"_database",
".",
"database_partition_url",
"(",
"self",
".",
"_partition_key",
")",
"else",
":",
"base_url",
"=",
"self",
".",
"_database",
".",
... | Constructs and returns the Query URL.
:returns: Query URL | [
"Constructs",
"and",
"returns",
"the",
"Query",
"URL",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/query.py#L107-L119 | train | 206,366 |
cloudant/python-cloudant | src/cloudant/scheduler.py | Scheduler.get_doc | def get_doc(self, doc_id):
"""
Get replication document state for a given replication document ID.
"""
resp = self._r_session.get('/'.join([self._scheduler, 'docs', '_replicator', doc_id]))
resp.raise_for_status()
return response_to_json_dict(resp) | python | def get_doc(self, doc_id):
"""
Get replication document state for a given replication document ID.
"""
resp = self._r_session.get('/'.join([self._scheduler, 'docs', '_replicator', doc_id]))
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"get_doc",
"(",
"self",
",",
"doc_id",
")",
":",
"resp",
"=",
"self",
".",
"_r_session",
".",
"get",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"_scheduler",
",",
"'docs'",
",",
"'_replicator'",
",",
"doc_id",
"]",
")",
")",
"resp",
"."... | Get replication document state for a given replication document ID. | [
"Get",
"replication",
"document",
"state",
"for",
"a",
"given",
"replication",
"document",
"ID",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/scheduler.py#L54-L60 | train | 206,367 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.document_partition_url | def document_partition_url(self, partition_key):
"""
Retrieve the design document partition URL.
:param str partition_key: Partition key.
:return: Design document partition URL.
:rtype: str
"""
return '/'.join((
self._database.database_partition_url(partition_key),
'_design',
url_quote_plus(self['_id'][8:], safe='')
)) | python | def document_partition_url(self, partition_key):
"""
Retrieve the design document partition URL.
:param str partition_key: Partition key.
:return: Design document partition URL.
:rtype: str
"""
return '/'.join((
self._database.database_partition_url(partition_key),
'_design',
url_quote_plus(self['_id'][8:], safe='')
)) | [
"def",
"document_partition_url",
"(",
"self",
",",
"partition_key",
")",
":",
"return",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"_database",
".",
"database_partition_url",
"(",
"partition_key",
")",
",",
"'_design'",
",",
"url_quote_plus",
"(",
"self",
"[",... | Retrieve the design document partition URL.
:param str partition_key: Partition key.
:return: Design document partition URL.
:rtype: str | [
"Retrieve",
"the",
"design",
"document",
"partition",
"URL",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L279-L291 | train | 206,368 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.add_show_function | def add_show_function(self, show_name, show_func):
"""
Appends a show function to the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the show function.
:param show_func: Javascript show function.
"""
if self.get_show_function(show_name) is not None:
raise CloudantArgumentError(110, show_name)
self.shows.__setitem__(show_name, show_func) | python | def add_show_function(self, show_name, show_func):
"""
Appends a show function to the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the show function.
:param show_func: Javascript show function.
"""
if self.get_show_function(show_name) is not None:
raise CloudantArgumentError(110, show_name)
self.shows.__setitem__(show_name, show_func) | [
"def",
"add_show_function",
"(",
"self",
",",
"show_name",
",",
"show_func",
")",
":",
"if",
"self",
".",
"get_show_function",
"(",
"show_name",
")",
"is",
"not",
"None",
":",
"raise",
"CloudantArgumentError",
"(",
"110",
",",
"show_name",
")",
"self",
".",
... | Appends a show function to the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the show function.
:param show_func: Javascript show function. | [
"Appends",
"a",
"show",
"function",
"to",
"the",
"locally",
"cached",
"DesignDocument",
"shows",
"dictionary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L344-L355 | train | 206,369 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.delete_index | def delete_index(self, index_name):
"""
Removes an existing index in the locally cached DesignDocument
indexes dictionary.
:param str index_name: Name used to identify the index.
"""
index = self.get_index(index_name)
if index is None:
return
self.indexes.__delitem__(index_name) | python | def delete_index(self, index_name):
"""
Removes an existing index in the locally cached DesignDocument
indexes dictionary.
:param str index_name: Name used to identify the index.
"""
index = self.get_index(index_name)
if index is None:
return
self.indexes.__delitem__(index_name) | [
"def",
"delete_index",
"(",
"self",
",",
"index_name",
")",
":",
"index",
"=",
"self",
".",
"get_index",
"(",
"index_name",
")",
"if",
"index",
"is",
"None",
":",
"return",
"self",
".",
"indexes",
".",
"__delitem__",
"(",
"index_name",
")"
] | Removes an existing index in the locally cached DesignDocument
indexes dictionary.
:param str index_name: Name used to identify the index. | [
"Removes",
"an",
"existing",
"index",
"in",
"the",
"locally",
"cached",
"DesignDocument",
"indexes",
"dictionary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L443-L454 | train | 206,370 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.delete_show_function | def delete_show_function(self, show_name):
"""
Removes an existing show function in the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the list.
"""
if self.get_show_function(show_name) is None:
return
self.shows.__delitem__(show_name) | python | def delete_show_function(self, show_name):
"""
Removes an existing show function in the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the list.
"""
if self.get_show_function(show_name) is None:
return
self.shows.__delitem__(show_name) | [
"def",
"delete_show_function",
"(",
"self",
",",
"show_name",
")",
":",
"if",
"self",
".",
"get_show_function",
"(",
"show_name",
")",
"is",
"None",
":",
"return",
"self",
".",
"shows",
".",
"__delitem__",
"(",
"show_name",
")"
] | Removes an existing show function in the locally cached DesignDocument
shows dictionary.
:param show_name: Name used to identify the list. | [
"Removes",
"an",
"existing",
"show",
"function",
"in",
"the",
"locally",
"cached",
"DesignDocument",
"shows",
"dictionary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L465-L475 | train | 206,371 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.fetch | def fetch(self):
"""
Retrieves the remote design document content and populates the locally
cached DesignDocument dictionary. View content is stored either as
View or QueryIndexView objects which are extensions of the ``dict``
type. All other design document data are stored directly as
``dict`` types.
"""
super(DesignDocument, self).fetch()
if self.views:
for view_name, view_def in iteritems_(self.get('views', dict())):
if self.get('language', None) != QUERY_LANGUAGE:
self['views'][view_name] = View(
self,
view_name,
view_def.pop('map', None),
view_def.pop('reduce', None),
**view_def
)
else:
self['views'][view_name] = QueryIndexView(
self,
view_name,
view_def.pop('map', None),
view_def.pop('reduce', None),
**view_def
)
for prop in self._nested_object_names:
# Ensure dict for each sub-object exists in locally cached DesignDocument.
getattr(self, prop, self.setdefault(prop, dict())) | python | def fetch(self):
"""
Retrieves the remote design document content and populates the locally
cached DesignDocument dictionary. View content is stored either as
View or QueryIndexView objects which are extensions of the ``dict``
type. All other design document data are stored directly as
``dict`` types.
"""
super(DesignDocument, self).fetch()
if self.views:
for view_name, view_def in iteritems_(self.get('views', dict())):
if self.get('language', None) != QUERY_LANGUAGE:
self['views'][view_name] = View(
self,
view_name,
view_def.pop('map', None),
view_def.pop('reduce', None),
**view_def
)
else:
self['views'][view_name] = QueryIndexView(
self,
view_name,
view_def.pop('map', None),
view_def.pop('reduce', None),
**view_def
)
for prop in self._nested_object_names:
# Ensure dict for each sub-object exists in locally cached DesignDocument.
getattr(self, prop, self.setdefault(prop, dict())) | [
"def",
"fetch",
"(",
"self",
")",
":",
"super",
"(",
"DesignDocument",
",",
"self",
")",
".",
"fetch",
"(",
")",
"if",
"self",
".",
"views",
":",
"for",
"view_name",
",",
"view_def",
"in",
"iteritems_",
"(",
"self",
".",
"get",
"(",
"'views'",
",",
... | Retrieves the remote design document content and populates the locally
cached DesignDocument dictionary. View content is stored either as
View or QueryIndexView objects which are extensions of the ``dict``
type. All other design document data are stored directly as
``dict`` types. | [
"Retrieves",
"the",
"remote",
"design",
"document",
"content",
"and",
"populates",
"the",
"locally",
"cached",
"DesignDocument",
"dictionary",
".",
"View",
"content",
"is",
"stored",
"either",
"as",
"View",
"or",
"QueryIndexView",
"objects",
"which",
"are",
"exten... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L477-L507 | train | 206,372 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.save | def save(self):
"""
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updated remotely. In
either case the locally cached DesignDocument object is also updated
accordingly based on the successful response of the operation.
"""
if self.views:
if self.get('language', None) != QUERY_LANGUAGE:
for view_name, view in self.iterviews():
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(104, view_name)
else:
for view_name, view in self.iterviews():
if not isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(105, view_name)
if self.indexes:
if self.get('language', None) != QUERY_LANGUAGE:
for index_name, search in self.iterindexes():
# Check the instance of the javascript search function
if not isinstance(search['index'], STRTYPE):
raise CloudantDesignDocumentException(106, index_name)
else:
for index_name, index in self.iterindexes():
if not isinstance(index['index'], dict):
raise CloudantDesignDocumentException(107, index_name)
for prop in self._nested_object_names:
if not getattr(self, prop):
# Ensure empty dict for each sub-object is not saved remotely.
self.__delitem__(prop)
super(DesignDocument, self).save()
for prop in self._nested_object_names:
# Ensure views, indexes, and lists dict exist in locally cached DesignDocument.
getattr(self, prop, self.setdefault(prop, dict())) | python | def save(self):
"""
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updated remotely. In
either case the locally cached DesignDocument object is also updated
accordingly based on the successful response of the operation.
"""
if self.views:
if self.get('language', None) != QUERY_LANGUAGE:
for view_name, view in self.iterviews():
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(104, view_name)
else:
for view_name, view in self.iterviews():
if not isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(105, view_name)
if self.indexes:
if self.get('language', None) != QUERY_LANGUAGE:
for index_name, search in self.iterindexes():
# Check the instance of the javascript search function
if not isinstance(search['index'], STRTYPE):
raise CloudantDesignDocumentException(106, index_name)
else:
for index_name, index in self.iterindexes():
if not isinstance(index['index'], dict):
raise CloudantDesignDocumentException(107, index_name)
for prop in self._nested_object_names:
if not getattr(self, prop):
# Ensure empty dict for each sub-object is not saved remotely.
self.__delitem__(prop)
super(DesignDocument, self).save()
for prop in self._nested_object_names:
# Ensure views, indexes, and lists dict exist in locally cached DesignDocument.
getattr(self, prop, self.setdefault(prop, dict())) | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"views",
":",
"if",
"self",
".",
"get",
"(",
"'language'",
",",
"None",
")",
"!=",
"QUERY_LANGUAGE",
":",
"for",
"view_name",
",",
"view",
"in",
"self",
".",
"iterviews",
"(",
")",
":",
"if",... | Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is updated remotely. In
either case the locally cached DesignDocument object is also updated
accordingly based on the successful response of the operation. | [
"Saves",
"changes",
"made",
"to",
"the",
"locally",
"cached",
"DesignDocument",
"object",
"s",
"data",
"structures",
"to",
"the",
"remote",
"database",
".",
"If",
"the",
"design",
"document",
"does",
"not",
"exist",
"remotely",
"then",
"it",
"is",
"created",
... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L510-L549 | train | 206,373 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.info | def info(self):
"""
Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info
"""
ddoc_info = self.r_session.get(
'/'.join([self.document_url, '_info']))
ddoc_info.raise_for_status()
return response_to_json_dict(ddoc_info) | python | def info(self):
"""
Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info
"""
ddoc_info = self.r_session.get(
'/'.join([self.document_url, '_info']))
ddoc_info.raise_for_status()
return response_to_json_dict(ddoc_info) | [
"def",
"info",
"(",
"self",
")",
":",
"ddoc_info",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"document_url",
",",
"'_info'",
"]",
")",
")",
"ddoc_info",
".",
"raise_for_status",
"(",
")",
"return",
"re... | Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info | [
"Retrieves",
"the",
"design",
"document",
"view",
"information",
"data",
"returns",
"dictionary"
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L701-L710 | train | 206,374 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.search_info | def search_info(self, search_index):
"""
Retrieves information about a specified search index within the design
document, returns dictionary
GET databasename/_design/{ddoc}/_search_info/{search_index}
"""
ddoc_search_info = self.r_session.get(
'/'.join([self.document_url, '_search_info', search_index]))
ddoc_search_info.raise_for_status()
return response_to_json_dict(ddoc_search_info) | python | def search_info(self, search_index):
"""
Retrieves information about a specified search index within the design
document, returns dictionary
GET databasename/_design/{ddoc}/_search_info/{search_index}
"""
ddoc_search_info = self.r_session.get(
'/'.join([self.document_url, '_search_info', search_index]))
ddoc_search_info.raise_for_status()
return response_to_json_dict(ddoc_search_info) | [
"def",
"search_info",
"(",
"self",
",",
"search_index",
")",
":",
"ddoc_search_info",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"document_url",
",",
"'_search_info'",
",",
"search_index",
"]",
")",
")",
"d... | Retrieves information about a specified search index within the design
document, returns dictionary
GET databasename/_design/{ddoc}/_search_info/{search_index} | [
"Retrieves",
"information",
"about",
"a",
"specified",
"search",
"index",
"within",
"the",
"design",
"document",
"returns",
"dictionary"
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L712-L722 | train | 206,375 |
cloudant/python-cloudant | src/cloudant/design_document.py | DesignDocument.search_disk_size | def search_disk_size(self, search_index):
"""
Retrieves disk size information about a specified search index within
the design document, returns dictionary
GET databasename/_design/{ddoc}/_search_disk_size/{search_index}
"""
ddoc_search_disk_size = self.r_session.get(
'/'.join([self.document_url, '_search_disk_size', search_index]))
ddoc_search_disk_size.raise_for_status()
return response_to_json_dict(ddoc_search_disk_size) | python | def search_disk_size(self, search_index):
"""
Retrieves disk size information about a specified search index within
the design document, returns dictionary
GET databasename/_design/{ddoc}/_search_disk_size/{search_index}
"""
ddoc_search_disk_size = self.r_session.get(
'/'.join([self.document_url, '_search_disk_size', search_index]))
ddoc_search_disk_size.raise_for_status()
return response_to_json_dict(ddoc_search_disk_size) | [
"def",
"search_disk_size",
"(",
"self",
",",
"search_index",
")",
":",
"ddoc_search_disk_size",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"document_url",
",",
"'_search_disk_size'",
",",
"search_index",
"]",
"... | Retrieves disk size information about a specified search index within
the design document, returns dictionary
GET databasename/_design/{ddoc}/_search_disk_size/{search_index} | [
"Retrieves",
"disk",
"size",
"information",
"about",
"a",
"specified",
"search",
"index",
"within",
"the",
"design",
"document",
"returns",
"dictionary"
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/design_document.py#L724-L734 | train | 206,376 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.creds | def creds(self):
"""
Retrieves a dictionary of useful authentication information
that can be used to authenticate against this database.
:returns: Dictionary containing authentication information
"""
session = self.client.session()
if session is None:
return None
return {
"basic_auth": self.client.basic_auth_str(),
"user_ctx": session.get('userCtx')
} | python | def creds(self):
"""
Retrieves a dictionary of useful authentication information
that can be used to authenticate against this database.
:returns: Dictionary containing authentication information
"""
session = self.client.session()
if session is None:
return None
return {
"basic_auth": self.client.basic_auth_str(),
"user_ctx": session.get('userCtx')
} | [
"def",
"creds",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"client",
".",
"session",
"(",
")",
"if",
"session",
"is",
"None",
":",
"return",
"None",
"return",
"{",
"\"basic_auth\"",
":",
"self",
".",
"client",
".",
"basic_auth_str",
"(",
")",
... | Retrieves a dictionary of useful authentication information
that can be used to authenticate against this database.
:returns: Dictionary containing authentication information | [
"Retrieves",
"a",
"dictionary",
"of",
"useful",
"authentication",
"information",
"that",
"can",
"be",
"used",
"to",
"authenticate",
"against",
"this",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L96-L110 | train | 206,377 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.exists | def exists(self):
"""
Performs an existence check on the remote database.
:returns: Boolean True if the database exists, False otherwise
"""
resp = self.r_session.head(self.database_url)
if resp.status_code not in [200, 404]:
resp.raise_for_status()
return resp.status_code == 200 | python | def exists(self):
"""
Performs an existence check on the remote database.
:returns: Boolean True if the database exists, False otherwise
"""
resp = self.r_session.head(self.database_url)
if resp.status_code not in [200, 404]:
resp.raise_for_status()
return resp.status_code == 200 | [
"def",
"exists",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"head",
"(",
"self",
".",
"database_url",
")",
"if",
"resp",
".",
"status_code",
"not",
"in",
"[",
"200",
",",
"404",
"]",
":",
"resp",
".",
"raise_for_status",
"(",
... | Performs an existence check on the remote database.
:returns: Boolean True if the database exists, False otherwise | [
"Performs",
"an",
"existence",
"check",
"on",
"the",
"remote",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L124-L134 | train | 206,378 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.metadata | def metadata(self):
"""
Retrieves the remote database metadata dictionary.
:returns: Dictionary containing database metadata details
"""
resp = self.r_session.get(self.database_url)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def metadata(self):
"""
Retrieves the remote database metadata dictionary.
:returns: Dictionary containing database metadata details
"""
resp = self.r_session.get(self.database_url)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"metadata",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"self",
".",
"database_url",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"response_to_json_dict",
"(",
"resp",
")"
] | Retrieves the remote database metadata dictionary.
:returns: Dictionary containing database metadata details | [
"Retrieves",
"the",
"remote",
"database",
"metadata",
"dictionary",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L136-L144 | train | 206,379 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.partition_metadata | def partition_metadata(self, partition_key):
"""
Retrieves the metadata dictionary for the remote database partition.
:param str partition_key: Partition key.
:returns: Metadata dictionary for the database partition.
:rtype: dict
"""
resp = self.r_session.get(self.database_partition_url(partition_key))
resp.raise_for_status()
return response_to_json_dict(resp) | python | def partition_metadata(self, partition_key):
"""
Retrieves the metadata dictionary for the remote database partition.
:param str partition_key: Partition key.
:returns: Metadata dictionary for the database partition.
:rtype: dict
"""
resp = self.r_session.get(self.database_partition_url(partition_key))
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"partition_metadata",
"(",
"self",
",",
"partition_key",
")",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"self",
".",
"database_partition_url",
"(",
"partition_key",
")",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"res... | Retrieves the metadata dictionary for the remote database partition.
:param str partition_key: Partition key.
:returns: Metadata dictionary for the database partition.
:rtype: dict | [
"Retrieves",
"the",
"metadata",
"dictionary",
"for",
"the",
"remote",
"database",
"partition",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L146-L156 | train | 206,380 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.new_document | def new_document(self):
"""
Creates a new, empty document in the remote and locally cached database,
auto-generating the _id.
:returns: Document instance corresponding to the new document in the
database
"""
doc = Document(self, None)
doc.create()
super(CouchDatabase, self).__setitem__(doc['_id'], doc)
return doc | python | def new_document(self):
"""
Creates a new, empty document in the remote and locally cached database,
auto-generating the _id.
:returns: Document instance corresponding to the new document in the
database
"""
doc = Document(self, None)
doc.create()
super(CouchDatabase, self).__setitem__(doc['_id'], doc)
return doc | [
"def",
"new_document",
"(",
"self",
")",
":",
"doc",
"=",
"Document",
"(",
"self",
",",
"None",
")",
"doc",
".",
"create",
"(",
")",
"super",
"(",
"CouchDatabase",
",",
"self",
")",
".",
"__setitem__",
"(",
"doc",
"[",
"'_id'",
"]",
",",
"doc",
")"... | Creates a new, empty document in the remote and locally cached database,
auto-generating the _id.
:returns: Document instance corresponding to the new document in the
database | [
"Creates",
"a",
"new",
"empty",
"document",
"in",
"the",
"remote",
"and",
"locally",
"cached",
"database",
"auto",
"-",
"generating",
"the",
"_id",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L201-L212 | train | 206,381 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.design_documents | def design_documents(self):
"""
Retrieve the JSON content for all design documents in this database.
Performs a remote call to retrieve the content.
:returns: All design documents found in this database in JSON format
"""
url = '/'.join((self.database_url, '_all_docs'))
query = "startkey=\"_design\"&endkey=\"_design0\"&include_docs=true"
resp = self.r_session.get(url, params=query)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data['rows'] | python | def design_documents(self):
"""
Retrieve the JSON content for all design documents in this database.
Performs a remote call to retrieve the content.
:returns: All design documents found in this database in JSON format
"""
url = '/'.join((self.database_url, '_all_docs'))
query = "startkey=\"_design\"&endkey=\"_design0\"&include_docs=true"
resp = self.r_session.get(url, params=query)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data['rows'] | [
"def",
"design_documents",
"(",
"self",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_all_docs'",
")",
")",
"query",
"=",
"\"startkey=\\\"_design\\\"&endkey=\\\"_design0\\\"&include_docs=true\"",
"resp",
"=",
"self",
".",... | Retrieve the JSON content for all design documents in this database.
Performs a remote call to retrieve the content.
:returns: All design documents found in this database in JSON format | [
"Retrieve",
"the",
"JSON",
"content",
"for",
"all",
"design",
"documents",
"in",
"this",
"database",
".",
"Performs",
"a",
"remote",
"call",
"to",
"retrieve",
"the",
"content",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L214-L226 | train | 206,382 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.get_design_document | def get_design_document(self, ddoc_id):
"""
Retrieves a design document. If a design document exists remotely
then that content is wrapped in a DesignDocument object and returned
to the caller. Otherwise a "shell" DesignDocument object is returned.
:param str ddoc_id: Design document id
:returns: A DesignDocument instance, if exists remotely then it will
be populated accordingly
"""
ddoc = DesignDocument(self, ddoc_id)
try:
ddoc.fetch()
except HTTPError as error:
if error.response.status_code != 404:
raise
return ddoc | python | def get_design_document(self, ddoc_id):
"""
Retrieves a design document. If a design document exists remotely
then that content is wrapped in a DesignDocument object and returned
to the caller. Otherwise a "shell" DesignDocument object is returned.
:param str ddoc_id: Design document id
:returns: A DesignDocument instance, if exists remotely then it will
be populated accordingly
"""
ddoc = DesignDocument(self, ddoc_id)
try:
ddoc.fetch()
except HTTPError as error:
if error.response.status_code != 404:
raise
return ddoc | [
"def",
"get_design_document",
"(",
"self",
",",
"ddoc_id",
")",
":",
"ddoc",
"=",
"DesignDocument",
"(",
"self",
",",
"ddoc_id",
")",
"try",
":",
"ddoc",
".",
"fetch",
"(",
")",
"except",
"HTTPError",
"as",
"error",
":",
"if",
"error",
".",
"response",
... | Retrieves a design document. If a design document exists remotely
then that content is wrapped in a DesignDocument object and returned
to the caller. Otherwise a "shell" DesignDocument object is returned.
:param str ddoc_id: Design document id
:returns: A DesignDocument instance, if exists remotely then it will
be populated accordingly | [
"Retrieves",
"a",
"design",
"document",
".",
"If",
"a",
"design",
"document",
"exists",
"remotely",
"then",
"that",
"content",
"is",
"wrapped",
"in",
"a",
"DesignDocument",
"object",
"and",
"returned",
"to",
"the",
"caller",
".",
"Otherwise",
"a",
"shell",
"... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L242-L260 | train | 206,383 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.get_partitioned_view_result | def get_partitioned_view_result(self, partition_key, ddoc_id, view_name,
raw_result=False, **kwargs):
"""
Retrieves the partitioned view result based on the design document and
view name.
See :func:`~cloudant.database.CouchDatabase.get_view_result` method for
further details.
:param str partition_key: Partition key.
:param str ddoc_id: Design document id used to get result.
:param str view_name: Name of the view used to get result.
:param bool raw_result: Dictates whether the view result is returned
as a default Result object or a raw JSON response.
Defaults to False.
:param kwargs: See
:func:`~cloudant.database.CouchDatabase.get_view_result` method for
available keyword arguments.
:returns: The result content either wrapped in a QueryResult or
as the raw response JSON content.
:rtype: QueryResult, dict
"""
ddoc = DesignDocument(self, ddoc_id)
view = View(ddoc, view_name, partition_key=partition_key)
return self._get_view_result(view, raw_result, **kwargs) | python | def get_partitioned_view_result(self, partition_key, ddoc_id, view_name,
raw_result=False, **kwargs):
"""
Retrieves the partitioned view result based on the design document and
view name.
See :func:`~cloudant.database.CouchDatabase.get_view_result` method for
further details.
:param str partition_key: Partition key.
:param str ddoc_id: Design document id used to get result.
:param str view_name: Name of the view used to get result.
:param bool raw_result: Dictates whether the view result is returned
as a default Result object or a raw JSON response.
Defaults to False.
:param kwargs: See
:func:`~cloudant.database.CouchDatabase.get_view_result` method for
available keyword arguments.
:returns: The result content either wrapped in a QueryResult or
as the raw response JSON content.
:rtype: QueryResult, dict
"""
ddoc = DesignDocument(self, ddoc_id)
view = View(ddoc, view_name, partition_key=partition_key)
return self._get_view_result(view, raw_result, **kwargs) | [
"def",
"get_partitioned_view_result",
"(",
"self",
",",
"partition_key",
",",
"ddoc_id",
",",
"view_name",
",",
"raw_result",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ddoc",
"=",
"DesignDocument",
"(",
"self",
",",
"ddoc_id",
")",
"view",
"=",
"Vi... | Retrieves the partitioned view result based on the design document and
view name.
See :func:`~cloudant.database.CouchDatabase.get_view_result` method for
further details.
:param str partition_key: Partition key.
:param str ddoc_id: Design document id used to get result.
:param str view_name: Name of the view used to get result.
:param bool raw_result: Dictates whether the view result is returned
as a default Result object or a raw JSON response.
Defaults to False.
:param kwargs: See
:func:`~cloudant.database.CouchDatabase.get_view_result` method for
available keyword arguments.
:returns: The result content either wrapped in a QueryResult or
as the raw response JSON content.
:rtype: QueryResult, dict | [
"Retrieves",
"the",
"partitioned",
"view",
"result",
"based",
"on",
"the",
"design",
"document",
"and",
"view",
"name",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L275-L300 | train | 206,384 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase._get_view_result | def _get_view_result(view, raw_result, **kwargs):
""" Get view results helper. """
if raw_result:
return view(**kwargs)
if kwargs:
return Result(view, **kwargs)
return view.result | python | def _get_view_result(view, raw_result, **kwargs):
""" Get view results helper. """
if raw_result:
return view(**kwargs)
if kwargs:
return Result(view, **kwargs)
return view.result | [
"def",
"_get_view_result",
"(",
"view",
",",
"raw_result",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"raw_result",
":",
"return",
"view",
"(",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
":",
"return",
"Result",
"(",
"view",
",",
"*",
"*",
"kwargs",
")",... | Get view results helper. | [
"Get",
"view",
"results",
"helper",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L400-L407 | train | 206,385 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.create | def create(self, throw_on_exists=False):
"""
Creates a database defined by the current database object, if it
does not already exist and raises a CloudantException if the operation
fails. If the database already exists then this method call is a no-op.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantDatabaseException when attempting to
create a database that already exists.
:returns: The database object
"""
if not throw_on_exists and self.exists():
return self
resp = self.r_session.put(self.database_url, params={
'partitioned': TYPE_CONVERTERS.get(bool)(self._partitioned)
})
if resp.status_code == 201 or resp.status_code == 202:
return self
raise CloudantDatabaseException(
resp.status_code, self.database_url, resp.text
) | python | def create(self, throw_on_exists=False):
"""
Creates a database defined by the current database object, if it
does not already exist and raises a CloudantException if the operation
fails. If the database already exists then this method call is a no-op.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantDatabaseException when attempting to
create a database that already exists.
:returns: The database object
"""
if not throw_on_exists and self.exists():
return self
resp = self.r_session.put(self.database_url, params={
'partitioned': TYPE_CONVERTERS.get(bool)(self._partitioned)
})
if resp.status_code == 201 or resp.status_code == 202:
return self
raise CloudantDatabaseException(
resp.status_code, self.database_url, resp.text
) | [
"def",
"create",
"(",
"self",
",",
"throw_on_exists",
"=",
"False",
")",
":",
"if",
"not",
"throw_on_exists",
"and",
"self",
".",
"exists",
"(",
")",
":",
"return",
"self",
"resp",
"=",
"self",
".",
"r_session",
".",
"put",
"(",
"self",
".",
"database_... | Creates a database defined by the current database object, if it
does not already exist and raises a CloudantException if the operation
fails. If the database already exists then this method call is a no-op.
:param bool throw_on_exists: Boolean flag dictating whether or
not to throw a CloudantDatabaseException when attempting to
create a database that already exists.
:returns: The database object | [
"Creates",
"a",
"database",
"defined",
"by",
"the",
"current",
"database",
"object",
"if",
"it",
"does",
"not",
"already",
"exist",
"and",
"raises",
"a",
"CloudantException",
"if",
"the",
"operation",
"fails",
".",
"If",
"the",
"database",
"already",
"exists",... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L409-L432 | train | 206,386 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.delete | def delete(self):
"""
Deletes the current database from the remote instance.
"""
resp = self.r_session.delete(self.database_url)
resp.raise_for_status() | python | def delete(self):
"""
Deletes the current database from the remote instance.
"""
resp = self.r_session.delete(self.database_url)
resp.raise_for_status() | [
"def",
"delete",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"r_session",
".",
"delete",
"(",
"self",
".",
"database_url",
")",
"resp",
".",
"raise_for_status",
"(",
")"
] | Deletes the current database from the remote instance. | [
"Deletes",
"the",
"current",
"database",
"from",
"the",
"remote",
"instance",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L434-L439 | train | 206,387 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.partitioned_all_docs | def partitioned_all_docs(self, partition_key, **kwargs):
"""
Wraps the _all_docs primary index on the database partition, and returns
the results by value.
See :func:`~cloudant.database.CouchDatabase.all_docs` method for further
details.
:param str partition_key: Partition key.
:param kwargs: See :func:`~cloudant.database.CouchDatabase.all_docs`
method for available keyword arguments.
:returns: Raw JSON response content from ``_all_docs`` endpoint.
:rtype: dict
"""
resp = get_docs(self.r_session,
'/'.join([
self.database_partition_url(partition_key),
'_all_docs'
]),
self.client.encoder,
**kwargs)
return response_to_json_dict(resp) | python | def partitioned_all_docs(self, partition_key, **kwargs):
"""
Wraps the _all_docs primary index on the database partition, and returns
the results by value.
See :func:`~cloudant.database.CouchDatabase.all_docs` method for further
details.
:param str partition_key: Partition key.
:param kwargs: See :func:`~cloudant.database.CouchDatabase.all_docs`
method for available keyword arguments.
:returns: Raw JSON response content from ``_all_docs`` endpoint.
:rtype: dict
"""
resp = get_docs(self.r_session,
'/'.join([
self.database_partition_url(partition_key),
'_all_docs'
]),
self.client.encoder,
**kwargs)
return response_to_json_dict(resp) | [
"def",
"partitioned_all_docs",
"(",
"self",
",",
"partition_key",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"get_docs",
"(",
"self",
".",
"r_session",
",",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"database_partition_url",
"(",
"partition_key",
")"... | Wraps the _all_docs primary index on the database partition, and returns
the results by value.
See :func:`~cloudant.database.CouchDatabase.all_docs` method for further
details.
:param str partition_key: Partition key.
:param kwargs: See :func:`~cloudant.database.CouchDatabase.all_docs`
method for available keyword arguments.
:returns: Raw JSON response content from ``_all_docs`` endpoint.
:rtype: dict | [
"Wraps",
"the",
"_all_docs",
"primary",
"index",
"on",
"the",
"database",
"partition",
"and",
"returns",
"the",
"results",
"by",
"value",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L474-L495 | train | 206,388 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.keys | def keys(self, remote=False):
"""
Retrieves the list of document ids in the database. Default is
to return only the locally cached document ids, specify remote=True
to make a remote request to include all document ids from the remote
database instance.
:param bool remote: Dictates whether the list of locally cached
document ids are returned or a remote request is made to include
an up to date list of document ids from the server.
Defaults to False.
:returns: List of document ids
"""
if not remote:
return list(super(CouchDatabase, self).keys())
docs = self.all_docs()
return [row['id'] for row in docs.get('rows', [])] | python | def keys(self, remote=False):
"""
Retrieves the list of document ids in the database. Default is
to return only the locally cached document ids, specify remote=True
to make a remote request to include all document ids from the remote
database instance.
:param bool remote: Dictates whether the list of locally cached
document ids are returned or a remote request is made to include
an up to date list of document ids from the server.
Defaults to False.
:returns: List of document ids
"""
if not remote:
return list(super(CouchDatabase, self).keys())
docs = self.all_docs()
return [row['id'] for row in docs.get('rows', [])] | [
"def",
"keys",
"(",
"self",
",",
"remote",
"=",
"False",
")",
":",
"if",
"not",
"remote",
":",
"return",
"list",
"(",
"super",
"(",
"CouchDatabase",
",",
"self",
")",
".",
"keys",
"(",
")",
")",
"docs",
"=",
"self",
".",
"all_docs",
"(",
")",
"re... | Retrieves the list of document ids in the database. Default is
to return only the locally cached document ids, specify remote=True
to make a remote request to include all document ids from the remote
database instance.
:param bool remote: Dictates whether the list of locally cached
document ids are returned or a remote request is made to include
an up to date list of document ids from the server.
Defaults to False.
:returns: List of document ids | [
"Retrieves",
"the",
"list",
"of",
"document",
"ids",
"in",
"the",
"database",
".",
"Default",
"is",
"to",
"return",
"only",
"the",
"locally",
"cached",
"document",
"ids",
"specify",
"remote",
"=",
"True",
"to",
"make",
"a",
"remote",
"request",
"to",
"incl... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L536-L553 | train | 206,389 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.missing_revisions | def missing_revisions(self, doc_id, *revisions):
"""
Returns a list of document revision values that do not exist in the
current remote database for the specified document id and specified
list of revision values.
:param str doc_id: Document id to check for missing revisions against.
:param list revisions: List of document revisions values to check
against.
:returns: List of missing document revision values
"""
url = '/'.join((self.database_url, '_missing_revs'))
data = {doc_id: list(revisions)}
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data, cls=self.client.encoder)
)
resp.raise_for_status()
resp_json = response_to_json_dict(resp)
missing_revs = resp_json['missing_revs'].get(doc_id)
if missing_revs is None:
missing_revs = []
return missing_revs | python | def missing_revisions(self, doc_id, *revisions):
"""
Returns a list of document revision values that do not exist in the
current remote database for the specified document id and specified
list of revision values.
:param str doc_id: Document id to check for missing revisions against.
:param list revisions: List of document revisions values to check
against.
:returns: List of missing document revision values
"""
url = '/'.join((self.database_url, '_missing_revs'))
data = {doc_id: list(revisions)}
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data, cls=self.client.encoder)
)
resp.raise_for_status()
resp_json = response_to_json_dict(resp)
missing_revs = resp_json['missing_revs'].get(doc_id)
if missing_revs is None:
missing_revs = []
return missing_revs | [
"def",
"missing_revisions",
"(",
"self",
",",
"doc_id",
",",
"*",
"revisions",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_missing_revs'",
")",
")",
"data",
"=",
"{",
"doc_id",
":",
"list",
"(",
"revisions",... | Returns a list of document revision values that do not exist in the
current remote database for the specified document id and specified
list of revision values.
:param str doc_id: Document id to check for missing revisions against.
:param list revisions: List of document revisions values to check
against.
:returns: List of missing document revision values | [
"Returns",
"a",
"list",
"of",
"document",
"revision",
"values",
"that",
"do",
"not",
"exist",
"in",
"the",
"current",
"remote",
"database",
"for",
"the",
"specified",
"document",
"id",
"and",
"specified",
"list",
"of",
"revision",
"values",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L812-L839 | train | 206,390 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.revisions_diff | def revisions_diff(self, doc_id, *revisions):
"""
Returns the differences in the current remote database for the specified
document id and specified list of revision values.
:param str doc_id: Document id to check for revision differences
against.
:param list revisions: List of document revisions values to check
against.
:returns: The revision differences in JSON format
"""
url = '/'.join((self.database_url, '_revs_diff'))
data = {doc_id: list(revisions)}
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data, cls=self.client.encoder)
)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def revisions_diff(self, doc_id, *revisions):
"""
Returns the differences in the current remote database for the specified
document id and specified list of revision values.
:param str doc_id: Document id to check for revision differences
against.
:param list revisions: List of document revisions values to check
against.
:returns: The revision differences in JSON format
"""
url = '/'.join((self.database_url, '_revs_diff'))
data = {doc_id: list(revisions)}
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data, cls=self.client.encoder)
)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"revisions_diff",
"(",
"self",
",",
"doc_id",
",",
"*",
"revisions",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_revs_diff'",
")",
")",
"data",
"=",
"{",
"doc_id",
":",
"list",
"(",
"revisions",
")"... | Returns the differences in the current remote database for the specified
document id and specified list of revision values.
:param str doc_id: Document id to check for revision differences
against.
:param list revisions: List of document revisions values to check
against.
:returns: The revision differences in JSON format | [
"Returns",
"the",
"differences",
"in",
"the",
"current",
"remote",
"database",
"for",
"the",
"specified",
"document",
"id",
"and",
"specified",
"list",
"of",
"revision",
"values",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L841-L863 | train | 206,391 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.get_revision_limit | def get_revision_limit(self):
"""
Retrieves the limit of historical revisions to store for any single
document in the current remote database.
:returns: Revision limit value for the current remote database
"""
url = '/'.join((self.database_url, '_revs_limit'))
resp = self.r_session.get(url)
resp.raise_for_status()
try:
ret = int(resp.text)
except ValueError:
raise CloudantDatabaseException(400, response_to_json_dict(resp))
return ret | python | def get_revision_limit(self):
"""
Retrieves the limit of historical revisions to store for any single
document in the current remote database.
:returns: Revision limit value for the current remote database
"""
url = '/'.join((self.database_url, '_revs_limit'))
resp = self.r_session.get(url)
resp.raise_for_status()
try:
ret = int(resp.text)
except ValueError:
raise CloudantDatabaseException(400, response_to_json_dict(resp))
return ret | [
"def",
"get_revision_limit",
"(",
"self",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_revs_limit'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"url",
")",
"resp",
".",
"raise_for_statu... | Retrieves the limit of historical revisions to store for any single
document in the current remote database.
:returns: Revision limit value for the current remote database | [
"Retrieves",
"the",
"limit",
"of",
"historical",
"revisions",
"to",
"store",
"for",
"any",
"single",
"document",
"in",
"the",
"current",
"remote",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L865-L881 | train | 206,392 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.set_revision_limit | def set_revision_limit(self, limit):
"""
Sets the limit of historical revisions to store for any single document
in the current remote database.
:param int limit: Number of revisions to store for any single document
in the current remote database.
:returns: Revision limit set operation status in JSON format
"""
url = '/'.join((self.database_url, '_revs_limit'))
resp = self.r_session.put(url, data=json.dumps(limit, cls=self.client.encoder))
resp.raise_for_status()
return response_to_json_dict(resp) | python | def set_revision_limit(self, limit):
"""
Sets the limit of historical revisions to store for any single document
in the current remote database.
:param int limit: Number of revisions to store for any single document
in the current remote database.
:returns: Revision limit set operation status in JSON format
"""
url = '/'.join((self.database_url, '_revs_limit'))
resp = self.r_session.put(url, data=json.dumps(limit, cls=self.client.encoder))
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"set_revision_limit",
"(",
"self",
",",
"limit",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_revs_limit'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"put",
"(",
"url",
",",
"data",
"=",
... | Sets the limit of historical revisions to store for any single document
in the current remote database.
:param int limit: Number of revisions to store for any single document
in the current remote database.
:returns: Revision limit set operation status in JSON format | [
"Sets",
"the",
"limit",
"of",
"historical",
"revisions",
"to",
"store",
"for",
"any",
"single",
"document",
"in",
"the",
"current",
"remote",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L883-L898 | train | 206,393 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.view_cleanup | def view_cleanup(self):
"""
Removes view files that are not used by any design document in the
remote database.
:returns: View cleanup status in JSON format
"""
url = '/'.join((self.database_url, '_view_cleanup'))
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
return response_to_json_dict(resp) | python | def view_cleanup(self):
"""
Removes view files that are not used by any design document in the
remote database.
:returns: View cleanup status in JSON format
"""
url = '/'.join((self.database_url, '_view_cleanup'))
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
return response_to_json_dict(resp) | [
"def",
"view_cleanup",
"(",
"self",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_view_cleanup'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"{",
"'Content... | Removes view files that are not used by any design document in the
remote database.
:returns: View cleanup status in JSON format | [
"Removes",
"view",
"files",
"that",
"are",
"not",
"used",
"by",
"any",
"design",
"document",
"in",
"the",
"remote",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L900-L914 | train | 206,394 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.get_list_function_result | def get_list_function_result(self, ddoc_id, list_name, view_name, **kwargs):
"""
Retrieves a customized MapReduce view result from the specified
database based on the list function provided. List functions are
used, for example, when you want to access Cloudant directly
from a browser, and need data to be returned in a different
format, such as HTML.
Note: All query parameters for View requests are supported.
See :class:`~cloudant.database.get_view_result` for
all supported query parameters.
For example:
.. code-block:: python
# Assuming that 'view001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve documents where the list function is 'list1'
resp = db.get_list_function_result('ddoc001', 'list1', 'view001', limit=10)
for row in resp['rows']:
# Process data (in text format).
For more detail on list functions, refer to the
`Cloudant list documentation <https://console.bluemix.net/docs/services/Cloudant/api/
design_documents.html#list-functions>`_.
:param str ddoc_id: Design document id used to get result.
:param str list_name: Name used in part to identify the
list function.
:param str view_name: Name used in part to identify the view.
:return: Formatted view result data in text format
"""
ddoc = DesignDocument(self, ddoc_id)
headers = {'Content-Type': 'application/json'}
resp = get_docs(self.r_session,
'/'.join([ddoc.document_url, '_list', list_name, view_name]),
self.client.encoder,
headers,
**kwargs)
return resp.text | python | def get_list_function_result(self, ddoc_id, list_name, view_name, **kwargs):
"""
Retrieves a customized MapReduce view result from the specified
database based on the list function provided. List functions are
used, for example, when you want to access Cloudant directly
from a browser, and need data to be returned in a different
format, such as HTML.
Note: All query parameters for View requests are supported.
See :class:`~cloudant.database.get_view_result` for
all supported query parameters.
For example:
.. code-block:: python
# Assuming that 'view001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve documents where the list function is 'list1'
resp = db.get_list_function_result('ddoc001', 'list1', 'view001', limit=10)
for row in resp['rows']:
# Process data (in text format).
For more detail on list functions, refer to the
`Cloudant list documentation <https://console.bluemix.net/docs/services/Cloudant/api/
design_documents.html#list-functions>`_.
:param str ddoc_id: Design document id used to get result.
:param str list_name: Name used in part to identify the
list function.
:param str view_name: Name used in part to identify the view.
:return: Formatted view result data in text format
"""
ddoc = DesignDocument(self, ddoc_id)
headers = {'Content-Type': 'application/json'}
resp = get_docs(self.r_session,
'/'.join([ddoc.document_url, '_list', list_name, view_name]),
self.client.encoder,
headers,
**kwargs)
return resp.text | [
"def",
"get_list_function_result",
"(",
"self",
",",
"ddoc_id",
",",
"list_name",
",",
"view_name",
",",
"*",
"*",
"kwargs",
")",
":",
"ddoc",
"=",
"DesignDocument",
"(",
"self",
",",
"ddoc_id",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/... | Retrieves a customized MapReduce view result from the specified
database based on the list function provided. List functions are
used, for example, when you want to access Cloudant directly
from a browser, and need data to be returned in a different
format, such as HTML.
Note: All query parameters for View requests are supported.
See :class:`~cloudant.database.get_view_result` for
all supported query parameters.
For example:
.. code-block:: python
# Assuming that 'view001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve documents where the list function is 'list1'
resp = db.get_list_function_result('ddoc001', 'list1', 'view001', limit=10)
for row in resp['rows']:
# Process data (in text format).
For more detail on list functions, refer to the
`Cloudant list documentation <https://console.bluemix.net/docs/services/Cloudant/api/
design_documents.html#list-functions>`_.
:param str ddoc_id: Design document id used to get result.
:param str list_name: Name used in part to identify the
list function.
:param str view_name: Name used in part to identify the view.
:return: Formatted view result data in text format | [
"Retrieves",
"a",
"customized",
"MapReduce",
"view",
"result",
"from",
"the",
"specified",
"database",
"based",
"on",
"the",
"list",
"function",
"provided",
".",
"List",
"functions",
"are",
"used",
"for",
"example",
"when",
"you",
"want",
"to",
"access",
"Clou... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L916-L957 | train | 206,395 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.get_show_function_result | def get_show_function_result(self, ddoc_id, show_name, doc_id):
"""
Retrieves a formatted document from the specified database
based on the show function provided. Show functions, for example,
are used when you want to access Cloudant directly from a browser,
and need data to be returned in a different format, such as HTML.
For example:
.. code-block:: python
# Assuming that 'view001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve a formatted 'doc001' document where the show function is 'show001'
resp = db.get_show_function_result('ddoc001', 'show001', 'doc001')
for row in resp['rows']:
# Process data (in text format).
For more detail on show functions, refer to the
`Cloudant show documentation <https://console.bluemix.net/docs/services/Cloudant/api/
design_documents.html#show-functions>`_.
:param str ddoc_id: Design document id used to get the result.
:param str show_name: Name used in part to identify the
show function.
:param str doc_id: The ID of the document to show.
:return: Formatted document result data in text format
"""
ddoc = DesignDocument(self, ddoc_id)
headers = {'Content-Type': 'application/json'}
resp = get_docs(self.r_session,
'/'.join([ddoc.document_url, '_show', show_name, doc_id]),
self.client.encoder,
headers)
return resp.text | python | def get_show_function_result(self, ddoc_id, show_name, doc_id):
"""
Retrieves a formatted document from the specified database
based on the show function provided. Show functions, for example,
are used when you want to access Cloudant directly from a browser,
and need data to be returned in a different format, such as HTML.
For example:
.. code-block:: python
# Assuming that 'view001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve a formatted 'doc001' document where the show function is 'show001'
resp = db.get_show_function_result('ddoc001', 'show001', 'doc001')
for row in resp['rows']:
# Process data (in text format).
For more detail on show functions, refer to the
`Cloudant show documentation <https://console.bluemix.net/docs/services/Cloudant/api/
design_documents.html#show-functions>`_.
:param str ddoc_id: Design document id used to get the result.
:param str show_name: Name used in part to identify the
show function.
:param str doc_id: The ID of the document to show.
:return: Formatted document result data in text format
"""
ddoc = DesignDocument(self, ddoc_id)
headers = {'Content-Type': 'application/json'}
resp = get_docs(self.r_session,
'/'.join([ddoc.document_url, '_show', show_name, doc_id]),
self.client.encoder,
headers)
return resp.text | [
"def",
"get_show_function_result",
"(",
"self",
",",
"ddoc_id",
",",
"show_name",
",",
"doc_id",
")",
":",
"ddoc",
"=",
"DesignDocument",
"(",
"self",
",",
"ddoc_id",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"resp",
"=",
"g... | Retrieves a formatted document from the specified database
based on the show function provided. Show functions, for example,
are used when you want to access Cloudant directly from a browser,
and need data to be returned in a different format, such as HTML.
For example:
.. code-block:: python
# Assuming that 'view001' exists as part of the
# 'ddoc001' design document in the remote database...
# Retrieve a formatted 'doc001' document where the show function is 'show001'
resp = db.get_show_function_result('ddoc001', 'show001', 'doc001')
for row in resp['rows']:
# Process data (in text format).
For more detail on show functions, refer to the
`Cloudant show documentation <https://console.bluemix.net/docs/services/Cloudant/api/
design_documents.html#show-functions>`_.
:param str ddoc_id: Design document id used to get the result.
:param str show_name: Name used in part to identify the
show function.
:param str doc_id: The ID of the document to show.
:return: Formatted document result data in text format | [
"Retrieves",
"a",
"formatted",
"document",
"from",
"the",
"specified",
"database",
"based",
"on",
"the",
"show",
"function",
"provided",
".",
"Show",
"functions",
"for",
"example",
"are",
"used",
"when",
"you",
"want",
"to",
"access",
"Cloudant",
"directly",
"... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L959-L994 | train | 206,396 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.update_handler_result | def update_handler_result(self, ddoc_id, handler_name, doc_id=None, data=None, **params):
"""
Creates or updates a document from the specified database based on the
update handler function provided. Update handlers are used, for
example, to provide server-side modification timestamps, and document
updates to individual fields without the latest revision. You can
provide query parameters needed by the update handler function using
the ``params`` argument.
Create a document with a generated ID:
.. code-block:: python
# Assuming that 'update001' update handler exists as part of the
# 'ddoc001' design document in the remote database...
# Execute 'update001' to create a new document
resp = db.update_handler_result('ddoc001', 'update001', data={'name': 'John',
'message': 'hello'})
Create or update a document with the specified ID:
.. code-block:: python
# Assuming that 'update001' update handler exists as part of the
# 'ddoc001' design document in the remote database...
# Execute 'update001' to update document 'doc001' in the database
resp = db.update_handler_result('ddoc001', 'update001', 'doc001',
data={'month': 'July'})
For more details, see the `update handlers documentation
<https://console.bluemix.net/docs/services/Cloudant/api/design_documents.html#update-handlers>`_.
:param str ddoc_id: Design document id used to get result.
:param str handler_name: Name used in part to identify the
update handler function.
:param str doc_id: Optional document id used to specify the
document to be handled.
:returns: Result of update handler function in text format
"""
ddoc = DesignDocument(self, ddoc_id)
if doc_id:
resp = self.r_session.put(
'/'.join([ddoc.document_url, '_update', handler_name, doc_id]),
params=params, data=data)
else:
resp = self.r_session.post(
'/'.join([ddoc.document_url, '_update', handler_name]),
params=params, data=data)
resp.raise_for_status()
return resp.text | python | def update_handler_result(self, ddoc_id, handler_name, doc_id=None, data=None, **params):
"""
Creates or updates a document from the specified database based on the
update handler function provided. Update handlers are used, for
example, to provide server-side modification timestamps, and document
updates to individual fields without the latest revision. You can
provide query parameters needed by the update handler function using
the ``params`` argument.
Create a document with a generated ID:
.. code-block:: python
# Assuming that 'update001' update handler exists as part of the
# 'ddoc001' design document in the remote database...
# Execute 'update001' to create a new document
resp = db.update_handler_result('ddoc001', 'update001', data={'name': 'John',
'message': 'hello'})
Create or update a document with the specified ID:
.. code-block:: python
# Assuming that 'update001' update handler exists as part of the
# 'ddoc001' design document in the remote database...
# Execute 'update001' to update document 'doc001' in the database
resp = db.update_handler_result('ddoc001', 'update001', 'doc001',
data={'month': 'July'})
For more details, see the `update handlers documentation
<https://console.bluemix.net/docs/services/Cloudant/api/design_documents.html#update-handlers>`_.
:param str ddoc_id: Design document id used to get result.
:param str handler_name: Name used in part to identify the
update handler function.
:param str doc_id: Optional document id used to specify the
document to be handled.
:returns: Result of update handler function in text format
"""
ddoc = DesignDocument(self, ddoc_id)
if doc_id:
resp = self.r_session.put(
'/'.join([ddoc.document_url, '_update', handler_name, doc_id]),
params=params, data=data)
else:
resp = self.r_session.post(
'/'.join([ddoc.document_url, '_update', handler_name]),
params=params, data=data)
resp.raise_for_status()
return resp.text | [
"def",
"update_handler_result",
"(",
"self",
",",
"ddoc_id",
",",
"handler_name",
",",
"doc_id",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"ddoc",
"=",
"DesignDocument",
"(",
"self",
",",
"ddoc_id",
")",
"if",
"doc_id",
... | Creates or updates a document from the specified database based on the
update handler function provided. Update handlers are used, for
example, to provide server-side modification timestamps, and document
updates to individual fields without the latest revision. You can
provide query parameters needed by the update handler function using
the ``params`` argument.
Create a document with a generated ID:
.. code-block:: python
# Assuming that 'update001' update handler exists as part of the
# 'ddoc001' design document in the remote database...
# Execute 'update001' to create a new document
resp = db.update_handler_result('ddoc001', 'update001', data={'name': 'John',
'message': 'hello'})
Create or update a document with the specified ID:
.. code-block:: python
# Assuming that 'update001' update handler exists as part of the
# 'ddoc001' design document in the remote database...
# Execute 'update001' to update document 'doc001' in the database
resp = db.update_handler_result('ddoc001', 'update001', 'doc001',
data={'month': 'July'})
For more details, see the `update handlers documentation
<https://console.bluemix.net/docs/services/Cloudant/api/design_documents.html#update-handlers>`_.
:param str ddoc_id: Design document id used to get result.
:param str handler_name: Name used in part to identify the
update handler function.
:param str doc_id: Optional document id used to specify the
document to be handled.
:returns: Result of update handler function in text format | [
"Creates",
"or",
"updates",
"a",
"document",
"from",
"the",
"specified",
"database",
"based",
"on",
"the",
"update",
"handler",
"function",
"provided",
".",
"Update",
"handlers",
"are",
"used",
"for",
"example",
"to",
"provide",
"server",
"-",
"side",
"modific... | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L996-L1046 | train | 206,397 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.get_query_indexes | def get_query_indexes(self, raw_result=False):
"""
Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
:class:`~cloudant.index.TextIndex`, and
:class:`~cloudant.index.SpecialIndex` wrapped objects.
:returns: The query indexes in the database
"""
url = '/'.join((self.database_url, '_index'))
resp = self.r_session.get(url)
resp.raise_for_status()
if raw_result:
return response_to_json_dict(resp)
indexes = []
for data in response_to_json_dict(resp).get('indexes', []):
if data.get('type') == JSON_INDEX_TYPE:
indexes.append(Index(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
elif data.get('type') == TEXT_INDEX_TYPE:
indexes.append(TextIndex(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
elif data.get('type') == SPECIAL_INDEX_TYPE:
indexes.append(SpecialIndex(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
else:
raise CloudantDatabaseException(101, data.get('type'))
return indexes | python | def get_query_indexes(self, raw_result=False):
"""
Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
:class:`~cloudant.index.TextIndex`, and
:class:`~cloudant.index.SpecialIndex` wrapped objects.
:returns: The query indexes in the database
"""
url = '/'.join((self.database_url, '_index'))
resp = self.r_session.get(url)
resp.raise_for_status()
if raw_result:
return response_to_json_dict(resp)
indexes = []
for data in response_to_json_dict(resp).get('indexes', []):
if data.get('type') == JSON_INDEX_TYPE:
indexes.append(Index(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
elif data.get('type') == TEXT_INDEX_TYPE:
indexes.append(TextIndex(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
elif data.get('type') == SPECIAL_INDEX_TYPE:
indexes.append(SpecialIndex(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
else:
raise CloudantDatabaseException(101, data.get('type'))
return indexes | [
"def",
"get_query_indexes",
"(",
"self",
",",
"raw_result",
"=",
"False",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_index'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get",
"(",
"url",
")",
... | Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
:class:`~cloudant.index.TextIndex`, and
:class:`~cloudant.index.SpecialIndex` wrapped objects.
:returns: The query indexes in the database | [
"Retrieves",
"query",
"indexes",
"from",
"the",
"remote",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L1048-L1096 | train | 206,398 |
cloudant/python-cloudant | src/cloudant/database.py | CouchDatabase.create_query_index | def create_query_index(
self,
design_document_id=None,
index_name=None,
index_type='json',
partitioned=False,
**kwargs
):
"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: The type of the index to create. Can
be either 'text' or 'json'. Defaults to 'json'.
:param str design_document_id: Optional identifier of the design
document in which the index will be created. If omitted the default
is that each index will be created in its own design document.
Indexes can be grouped into design documents for efficiency.
However, a change to one index in a design document will invalidate
all other indexes in the same document.
:param str index_name: Optional name of the index. If omitted, a name
will be generated automatically.
:param list fields: A list of fields that should be indexed. For JSON
indexes, the fields parameter is mandatory and should follow the
'sort syntax'. For example ``fields=['name', {'age': 'desc'}]``
will create an index on the 'name' field in ascending order and the
'age' field in descending order. For text indexes, the fields
parameter is optional. If it is included then each field element
in the fields list must be a single element dictionary where the
key is the field name and the value is the field type. For example
``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field
types are ``'string'``, ``'number'``, and ``'boolean'``.
:param dict default_field: Optional parameter that specifies how the
``$text`` operator can be used with the index. Only valid when
creating a text index.
:param dict selector: Optional parameter that can be used to limit the
index to a specific set of documents that match a query. It uses
the same syntax used for selectors in queries. Only valid when
creating a text index.
:returns: An Index object representing the index created in the
remote database
"""
if index_type == JSON_INDEX_TYPE:
index = Index(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
elif index_type == TEXT_INDEX_TYPE:
index = TextIndex(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
else:
raise CloudantArgumentError(103, index_type)
index.create()
return index | python | def create_query_index(
self,
design_document_id=None,
index_name=None,
index_type='json',
partitioned=False,
**kwargs
):
"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: The type of the index to create. Can
be either 'text' or 'json'. Defaults to 'json'.
:param str design_document_id: Optional identifier of the design
document in which the index will be created. If omitted the default
is that each index will be created in its own design document.
Indexes can be grouped into design documents for efficiency.
However, a change to one index in a design document will invalidate
all other indexes in the same document.
:param str index_name: Optional name of the index. If omitted, a name
will be generated automatically.
:param list fields: A list of fields that should be indexed. For JSON
indexes, the fields parameter is mandatory and should follow the
'sort syntax'. For example ``fields=['name', {'age': 'desc'}]``
will create an index on the 'name' field in ascending order and the
'age' field in descending order. For text indexes, the fields
parameter is optional. If it is included then each field element
in the fields list must be a single element dictionary where the
key is the field name and the value is the field type. For example
``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field
types are ``'string'``, ``'number'``, and ``'boolean'``.
:param dict default_field: Optional parameter that specifies how the
``$text`` operator can be used with the index. Only valid when
creating a text index.
:param dict selector: Optional parameter that can be used to limit the
index to a specific set of documents that match a query. It uses
the same syntax used for selectors in queries. Only valid when
creating a text index.
:returns: An Index object representing the index created in the
remote database
"""
if index_type == JSON_INDEX_TYPE:
index = Index(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
elif index_type == TEXT_INDEX_TYPE:
index = TextIndex(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
else:
raise CloudantArgumentError(103, index_type)
index.create()
return index | [
"def",
"create_query_index",
"(",
"self",
",",
"design_document_id",
"=",
"None",
",",
"index_name",
"=",
"None",
",",
"index_type",
"=",
"'json'",
",",
"partitioned",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"index_type",
"==",
"JSON_INDEX_TYP... | Creates either a JSON or a text query index in the remote database.
:param str index_type: The type of the index to create. Can
be either 'text' or 'json'. Defaults to 'json'.
:param str design_document_id: Optional identifier of the design
document in which the index will be created. If omitted the default
is that each index will be created in its own design document.
Indexes can be grouped into design documents for efficiency.
However, a change to one index in a design document will invalidate
all other indexes in the same document.
:param str index_name: Optional name of the index. If omitted, a name
will be generated automatically.
:param list fields: A list of fields that should be indexed. For JSON
indexes, the fields parameter is mandatory and should follow the
'sort syntax'. For example ``fields=['name', {'age': 'desc'}]``
will create an index on the 'name' field in ascending order and the
'age' field in descending order. For text indexes, the fields
parameter is optional. If it is included then each field element
in the fields list must be a single element dictionary where the
key is the field name and the value is the field type. For example
``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field
types are ``'string'``, ``'number'``, and ``'boolean'``.
:param dict default_field: Optional parameter that specifies how the
``$text`` operator can be used with the index. Only valid when
creating a text index.
:param dict selector: Optional parameter that can be used to limit the
index to a specific set of documents that match a query. It uses
the same syntax used for selectors in queries. Only valid when
creating a text index.
:returns: An Index object representing the index created in the
remote database | [
"Creates",
"either",
"a",
"JSON",
"or",
"a",
"text",
"query",
"index",
"in",
"the",
"remote",
"database",
"."
] | e0ba190f6ba07fe3522a668747128214ad573c7e | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/database.py#L1098-L1149 | train | 206,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.