Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def and_raise_future(self, exception):
future = _get_future()
future.set_exception(exception)
return self.and_return(future) | [
"Similar to `and_raise` but the doubled method returns a future.\n\n :param Exception exception: The exception to raise.\n "
] |
Please provide a description of the function:def and_return_future(self, *return_values):
futures = []
for value in return_values:
future = _get_future()
future.set_result(value)
futures.append(future)
return self.and_return(*futures) | [
"Similar to `and_return` but the doubled method returns a future.\n\n :param object return_values: The values the double will return when called,\n "
] |
Please provide a description of the function:def and_return(self, *return_values):
if not return_values:
raise TypeError('and_return() expected at least 1 return value')
return_values = list(return_values)
final_value = return_values.pop()
self.and_return_result_o... | [
"Set a return value for an allowance\n\n Causes the double to return the provided values in order. If multiple\n values are provided, they are returned one at a time in sequence as the double is called.\n If the double is called more times than there are return values, it should continue to\n ... |
Please provide a description of the function:def and_return_result_of(self, return_value):
if not check_func_takes_args(return_value):
self._return_value = lambda *args, **kwargs: return_value()
else:
self._return_value = return_value
return self | [
" Causes the double to return the result of calling the provided value.\n\n :param return_value: A callable that will be invoked to determine the double's return value.\n :type return_value: any callable object\n "
] |
Please provide a description of the function:def with_args(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.verify_arguments()
return self | [
"Declares that the double can only be called with the provided arguments.\n\n :param args: Any positional arguments required for invocation.\n :param kwargs: Any keyword arguments required for invocation.\n "
] |
Please provide a description of the function:def with_args_validator(self, matching_function):
self.args = None
self.kwargs = None
self._custom_matcher = matching_function
return self | [
"Define a custom function for testing arguments\n\n :param func matching_function: The function used to test arguments passed to the stub.\n "
] |
Please provide a description of the function:def satisfy_exact_match(self, args, kwargs):
if self.args is None and self.kwargs is None:
return False
elif self.args is _any and self.kwargs is _any:
return True
elif args == self.args and kwargs == self.kwargs:
... | [
"Returns a boolean indicating whether or not the stub will accept the provided arguments.\n\n :return: Whether or not the stub accepts the provided arguments.\n :rtype: bool\n "
] |
Please provide a description of the function:def satisfy_custom_matcher(self, args, kwargs):
if not self._custom_matcher:
return False
try:
return self._custom_matcher(*args, **kwargs)
except Exception:
return False | [
"Return a boolean indicating if the args satisfy the stub\n\n :return: Whether or not the stub accepts the provided arguments.\n :rtype: bool\n "
] |
Please provide a description of the function:def return_value(self, *args, **kwargs):
self._called()
return self._return_value(*args, **kwargs) | [
"Extracts the real value to be returned from the wrapping callable.\n\n :return: The value the double should return when called.\n "
] |
Please provide a description of the function:def verify_arguments(self, args=None, kwargs=None):
args = self.args if args is None else args
kwargs = self.kwargs if kwargs is None else kwargs
try:
verify_arguments(self._target, self._method_name, args, kwargs)
excep... | [
"Ensures that the arguments specified match the signature of the real method.\n\n :raise: ``VerifyingDoubleError`` if the arguments do not match.\n "
] |
Please provide a description of the function:def raise_failure_exception(self, expect_or_allow='Allowed'):
raise MockExpectationError(
"{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format(
expect_or_allow,
self._method_name,
... | [
"Raises a ``MockExpectationError`` with a useful message.\n\n :raise: ``MockExpectationError``\n "
] |
Please provide a description of the function:def _expected_argument_string(self):
if self.args is _any and self.kwargs is _any:
return 'any args'
elif self._custom_matcher:
return "custom matcher: '{}'".format(self._custom_matcher.__name__)
else:
ret... | [
"Generates a string describing what arguments the double expected.\n\n :return: A string describing expected arguments.\n :rtype: str\n "
] |
Please provide a description of the function:def is_class_or_module(self):
if isinstance(self.obj, ObjectDouble):
return self.obj.is_class
return isclass(self.doubled_obj) or ismodule(self.doubled_obj) | [
"Determines if the object is a class or a module\n\n :return: True if the object is a class or a module, False otherwise.\n :rtype: bool\n "
] |
Please provide a description of the function:def _determine_doubled_obj(self):
if isinstance(self.obj, ObjectDouble):
return self.obj._doubles_target
else:
return self.obj | [
"Return the target object.\n\n Returns the object that should be treated as the target object. For partial doubles, this\n will be the same as ``self.obj``, but for pure doubles, it's pulled from the special\n ``_doubles_target`` attribute.\n\n :return: The object to be doubled.\n ... |
Please provide a description of the function:def _determine_doubled_obj_type(self):
if isclass(self.doubled_obj) or ismodule(self.doubled_obj):
return self.doubled_obj
return self.doubled_obj.__class__ | [
"Returns the type (class) of the target object.\n\n :return: The type (class) of the target.\n :rtype: type, classobj\n "
] |
Please provide a description of the function:def _generate_attrs(self):
attrs = {}
if ismodule(self.doubled_obj):
for name, func in getmembers(self.doubled_obj, is_callable):
attrs[name] = Attribute(func, 'toplevel', self.doubled_obj)
else:
for a... | [
"Get detailed info about target object.\n\n Uses ``inspect.classify_class_attrs`` to get several important details about each attribute\n on the target object.\n\n :return: The attribute details dict.\n :rtype: dict\n "
] |
Please provide a description of the function:def hijack_attr(self, attr_name):
if not self._original_attr(attr_name):
setattr(
self.obj.__class__,
attr_name,
_proxy_class_method_to_instance(
getattr(self.obj.__class__, attr... | [
"Hijack an attribute on the target object.\n\n Updates the underlying class and delegating the call to the instance.\n This allows specially-handled attributes like __call__, __enter__,\n and __exit__ to be mocked on a per-instance basis.\n\n :param str attr_name: the name of the attribu... |
Please provide a description of the function:def restore_attr(self, attr_name):
original_attr = self._original_attr(attr_name)
if self._original_attr(attr_name):
setattr(self.obj.__class__, attr_name, original_attr) | [
"Restore an attribute back onto the target object.\n\n :param str attr_name: the name of the attribute to restore\n "
] |
Please provide a description of the function:def _original_attr(self, attr_name):
try:
return getattr(
getattr(self.obj.__class__, attr_name), '_doubles_target_method', None
)
except AttributeError:
return None | [
"Return the original attribute off of the proxy on the target object.\n\n :param str attr_name: the name of the original attribute to return\n :return: Func or None.\n :rtype: func\n "
] |
Please provide a description of the function:def get_callable_attr(self, attr_name):
if not hasattr(self.doubled_obj, attr_name):
return None
func = getattr(self.doubled_obj, attr_name)
if not is_callable(func):
return None
attr = Attribute(
... | [
"Used to double methods added to an object after creation\n\n :param str attr_name: the name of the original attribute to return\n :return: Attribute or None.\n :rtype: func\n "
] |
Please provide a description of the function:def get_attr(self, method_name):
return self.attrs.get(method_name) or self.get_callable_attr(method_name) | [
"Get attribute from the target object"
] |
Please provide a description of the function:def add_allowance(self, caller):
allowance = Allowance(self._target, self._method_name, caller)
self._allowances.insert(0, allowance)
return allowance | [
"Adds a new allowance for the method.\n\n :param: tuple caller: A tuple indicating where the method was called\n :return: The new ``Allowance``.\n :rtype: Allowance\n "
] |
Please provide a description of the function:def add_expectation(self, caller):
expectation = Expectation(self._target, self._method_name, caller)
self._expectations.insert(0, expectation)
return expectation | [
"Adds a new expectation for the method.\n\n :return: The new ``Expectation``.\n :rtype: Expectation\n "
] |
Please provide a description of the function:def _find_matching_allowance(self, args, kwargs):
for allowance in self._allowances:
if allowance.satisfy_exact_match(args, kwargs):
return allowance
for allowance in self._allowances:
if allowance.satisfy_cu... | [
"Return a matching allowance.\n\n Returns the first allowance that matches the ones declared. Tries one with specific\n arguments first, then falls back to an allowance that allows arbitrary arguments.\n\n :return: The matching ``Allowance``, if one was found.\n :rtype: Allowance, None\n... |
Please provide a description of the function:def _find_matching_double(self, args, kwargs):
expectation = self._find_matching_expectation(args, kwargs)
if expectation:
return expectation
allowance = self._find_matching_allowance(args, kwargs)
if allowance:
... | [
"Returns the first matching expectation or allowance.\n\n Returns the first allowance or expectation that matches the ones declared. Tries one\n with specific arguments first, then falls back to an expectation that allows arbitrary\n arguments.\n\n :return: The matching ``Allowance`` or ... |
Please provide a description of the function:def _find_matching_expectation(self, args, kwargs):
for expectation in self._expectations:
if expectation.satisfy_exact_match(args, kwargs):
return expectation
for expectation in self._expectations:
if expect... | [
"Return a matching expectation.\n\n Returns the first expectation that matches the ones declared. Tries one with specific\n arguments first, then falls back to an expectation that allows arbitrary arguments.\n\n :return: The matching ``Expectation``, if one was found.\n :rtype: Expectati... |
Please provide a description of the function:def _verify_method(self):
class_level = self._target.is_class_or_module()
verify_method(self._target, self._method_name, class_level=class_level) | [
"Verify that a method may be doubled.\n\n Verifies that the target object has a method matching the name the user is attempting to\n double.\n\n :raise: ``VerifyingDoubleError`` if no matching method is found.\n "
] |
Please provide a description of the function:def verify_method(target, method_name, class_level=False):
attr = target.get_attr(method_name)
if not attr:
raise VerifyingDoubleError(method_name, target.doubled_obj).no_matching_method()
if attr.kind == 'data' and not isbuiltin(attr.object) and ... | [
"Verifies that the provided method exists on the target object.\n\n :param Target target: A ``Target`` object containing the object with the method to double.\n :param str method_name: The name of the method to double.\n :raise: ``VerifyingDoubleError`` if the attribute doesn't exist, if it's not a callabl... |
Please provide a description of the function:def verify_arguments(target, method_name, args, kwargs):
if method_name == '_doubles__new__':
return _verify_arguments_of_doubles__new__(target, args, kwargs)
attr = target.get_attr(method_name)
method = attr.object
if attr.kind in ('data', 'a... | [
"Verifies that the provided arguments match the signature of the provided method.\n\n :param Target target: A ``Target`` object containing the object with the method to double.\n :param str method_name: The name of the method to double.\n :param tuple args: The positional arguments the method should be cal... |
Please provide a description of the function:def allow_constructor(target):
if not isinstance(target, ClassDouble):
raise ConstructorDoubleError(
'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target),
)
return allow(target)._doubles__new__ | [
"\n Set an allowance on a ``ClassDouble`` constructor\n\n This allows the caller to control what a ClassDouble returns when a new instance is created.\n\n :param ClassDouble target: The ClassDouble to set the allowance on.\n :return: an ``Allowance`` for the __new__ method.\n :raise: ``ConstructorDo... |
Please provide a description of the function:def patch(target, value):
patch = current_space().patch_for(target)
patch.set_value(value)
return patch | [
"\n Replace the specified object\n\n :param str target: A string pointing to the target to patch.\n :param object value: The value to replace the target with.\n :return: A ``Patch`` object.\n "
] |
Please provide a description of the function:def get_path_components(path):
path_segments = path.split('.')
module_path = '.'.join(path_segments[:-1])
if module_path == '':
raise VerifyingDoubleImportError('Invalid import path: {}.'.format(path))
class_name = path_segments[-1]
retur... | [
"Extract the module name and class name out of the fully qualified path to the class.\n\n :param str path: The full path to the class.\n :return: The module path and the class name.\n :rtype: str, str\n :raise: ``VerifyingDoubleImportError`` if the path is to a top-level module.\n "
] |
Please provide a description of the function:def expect_constructor(target):
if not isinstance(target, ClassDouble):
raise ConstructorDoubleError(
'Cannot allow_constructor of {} since it is not a ClassDouble.'.format(target),
)
return expect(target)._doubles__new__ | [
"\n Set an expectation on a ``ClassDouble`` constructor\n\n :param ClassDouble target: The ClassDouble to set the expectation on.\n :return: an ``Expectation`` for the __new__ method.\n :raise: ``ConstructorDoubleError`` if target is not a ClassDouble.\n "
] |
Please provide a description of the function:def write_table(self):
with self._logger:
self._verify_property()
self._preprocess()
for values in self._table_value_matrix:
ltsv_item_list = [
"{:s}:{}".format(pathvalidate.sanitize_l... | [
"\n |write_table| with\n `Labeled Tab-separated Values (LTSV) <http://ltsv.org/>`__ format.\n Invalid characters in labels/data are removed.\n\n :raises pytablewriter.EmptyHeaderError: If the |headers| is empty.\n :Example:\n :ref:`example-ltsv-table-writer`\n "
... |
Please provide a description of the function:def write_table(self):
import toml
with self._logger:
self._verify_property()
self.stream.write(toml.dumps(self.tabledata.as_dict())) | [
"\n |write_table| with\n `TOML <https://github.com/toml-lang/toml>`__ format.\n\n :raises pytablewriter.EmptyTableNameError:\n If the |headers| is empty.\n :raises pytablewriter.EmptyHeaderError:\n If the |headers| is empty.\n :Example:\n :ref:`exa... |
Please provide a description of the function:def write_table(self):
with self._logger:
self._verify_property()
self.__write_chapter()
self._write_table()
if self.is_write_null_line_after_table:
self.write_null_line() | [
"\n |write_table| with Markdown table format.\n\n :raises pytablewriter.EmptyHeaderError: If the |headers| is empty.\n :Example:\n :ref:`example-markdown-table-writer`\n\n .. note::\n - |None| values are written as an empty string\n - Vertical bar charact... |
Please provide a description of the function:def validate_excel_sheet_name(sheet_name):
validate_null_string(sheet_name)
if len(sheet_name) > __MAX_SHEET_NAME_LEN:
raise InvalidLengthError(
"sheet name is too long: expected<={:d}, actual={:d}".format(
__MAX_SHEET_NAME_... | [
"\n :param str sheet_name: Excel sheet name to validate.\n :raises pathvalidate.NullNameError: If the ``sheet_name`` is empty.\n :raises pathvalidate.InvalidCharError:\n If the ``sheet_name`` includes invalid char(s):\n |invalid_excel_sheet_chars|.\n :raises pathvalidate.InvalidLengthError... |
Please provide a description of the function:def sanitize_excel_sheet_name(sheet_name, replacement_text=""):
try:
unicode_sheet_name = _preprocess(sheet_name)
except AttributeError as e:
raise ValueError(e)
modify_sheet_name = __RE_INVALID_EXCEL_SHEET_NAME.sub(replacement_text, unicod... | [
"\n Replace invalid characters for an Excel sheet name within\n the ``sheet_name`` with the ``replacement_text``.\n Invalid characters are as follows:\n |invalid_excel_sheet_chars|.\n The ``sheet_name`` truncate to 31 characters\n (max sheet name length of Excel) from the head, if the length\n ... |
Please provide a description of the function:def dumps_tabledata(value, format_name="rst_grid_table", **kwargs):
from ._factory import TableWriterFactory
if not value:
raise TypeError("value must be a tabledata.TableData instance")
writer = TableWriterFactory.create_from_format_name(format_n... | [
"\n :param tabledata.TableData value: Tabular data to dump.\n :param str format_name:\n Dumped format name of tabular data.\n Available formats are described in\n :py:meth:`~pytablewriter.TableWriterFactory.create_from_format_name`\n\n :Example:\n .. code:: python\n\n ... |
Please provide a description of the function:def write_table(self):
tags = _get_tags_module()
with self._logger:
self._verify_property()
self._preprocess()
if typepy.is_not_null_string(self.table_name):
self._table_tag = tags.table(id=sanit... | [
"\n |write_table| with HTML table format.\n\n :Example:\n :ref:`example-html-table-writer`\n\n .. note::\n - |None| is not written\n "
] |
Please provide a description of the function:def write_table(self):
super(TextTableWriter, self).write_table()
if self.is_write_null_line_after_table:
self.write_null_line() | [
"\n |write_table|.\n\n .. note::\n - |None| values are written as an empty string.\n "
] |
Please provide a description of the function:def dump(self, output, close_after_write=True):
try:
output.write
self.stream = output
except AttributeError:
self.stream = io.open(output, "w", encoding="utf-8")
try:
self.write_table()
... | [
"Write data to the output with tabular format.\n\n Args:\n output (file descriptor or str):\n file descriptor or path to the output file.\n close_after_write (bool, optional):\n Close the output after write.\n Defaults to |True|.\n "
] |
Please provide a description of the function:def dumps(self):
old_stream = self.stream
try:
self.stream = six.StringIO()
self.write_table()
tabular_text = self.stream.getvalue()
finally:
self.stream = old_stream
return tabular_t... | [
"Get rendered tabular text from the table data.\n\n Only available for text format table writers.\n\n Returns:\n str: Rendered tabular text.\n "
] |
Please provide a description of the function:def open(self, file_path):
if self.is_opened() and self.workbook.file_path == file_path:
self._logger.logger.debug("workbook already opened: {}".format(self.workbook.file_path))
return
self.close()
self._open(file_pa... | [
"\n Open an Excel workbook file.\n\n :param str file_path: Excel workbook file path to open.\n "
] |
Please provide a description of the function:def from_tabledata(self, value, is_overwrite_table_name=True):
super(ExcelTableWriter, self).from_tabledata(value)
if self.is_opened():
self.make_worksheet(self.table_name) | [
"\n Set following attributes from |TableData|\n\n - :py:attr:`~.table_name`.\n - :py:attr:`~.headers`.\n - :py:attr:`~.value_matrix`.\n\n And create worksheet named from :py:attr:`~.table_name` ABC\n if not existed yet.\n\n :param tabledata.TableData value: Input tab... |
Please provide a description of the function:def make_worksheet(self, sheet_name=None):
if sheet_name is None:
sheet_name = self.table_name
if not sheet_name:
sheet_name = ""
self._stream = self.workbook.add_worksheet(sheet_name)
self._current_data_row ... | [
"Make a worksheet to the current workbook.\n\n Args:\n sheet_name (str):\n Name of the worksheet to create. The name will be automatically generated\n (like ``\"Sheet1\"``) if the ``sheet_name`` is empty.\n "
] |
Please provide a description of the function:def dump(self, output, close_after_write=True):
self.open(output)
try:
self.make_worksheet(self.table_name)
self.write_table()
finally:
if close_after_write:
self.close() | [
"Write a worksheet to the current workbook.\n\n Args:\n output (str):\n Path to the workbook file to write.\n close_after_write (bool, optional):\n Close the workbook after write.\n Defaults to |True|.\n "
] |
Please provide a description of the function:def open(self, file_path):
from simplesqlite import SimpleSQLite
if self.is_opened():
if self.stream.database_path == abspath(file_path):
self._logger.logger.debug(
"database already opened: {}".forma... | [
"\n Open a SQLite database file.\n\n :param str file_path: SQLite database file path to open.\n "
] |
Please provide a description of the function:def create_from_file_extension(cls, file_extension):
ext = os.path.splitext(file_extension)[1]
if typepy.is_null_string(ext):
file_extension = file_extension
else:
file_extension = ext
file_extension = file_e... | [
"\n Create a table writer class instance from a file extension.\n Supported file extensions are as follows:\n\n ================== ===================================\n Extension Writer Class\n ================== ===================================\n ... |
Please provide a description of the function:def create_from_format_name(cls, format_name):
format_name = format_name.lower()
for table_format in TableFormat:
if format_name in table_format.names and not (
table_format.format_attribute & FormatAttr.SECONDARY_NAME
... | [
"\n Create a table writer class instance from a format name.\n Supported file format names are as follows:\n\n ============================================= ===================================\n Format name Writer Class\n ===========... |
Please provide a description of the function:def get_format_names(cls):
format_name_set = set()
for table_format in TableFormat:
for format_name in table_format.names:
format_name_set.add(format_name)
return sorted(list(format_name_set)) | [
"\n :return: Available format names.\n :rtype: list\n\n :Example:\n .. code:: python\n\n >>> import pytablewriter as ptw\n >>> for name in ptw.TableWriterFactory.get_format_names():\n ... print(name)\n ...\n ... |
Please provide a description of the function:def get_extensions(cls):
file_extension_set = set()
for table_format in TableFormat:
for file_extension in table_format.file_extensions:
file_extension_set.add(file_extension)
return sorted(list(file_extension_se... | [
"\n :return: Available file extensions.\n :rtype: list\n\n :Example:\n .. code:: python\n\n >>> import pytablewriter as ptw\n >>> for name in ptw.TableWriterFactory.get_extensions():\n ... print(name)\n ...\n ... |
Please provide a description of the function:def set_style(self, column, style):
column_idx = None
while len(self.headers) > len(self.__style_list):
self.__style_list.append(None)
if isinstance(column, six.integer_types):
column_idx = column
elif isins... | [
"Set |Style| for a specific column.\n\n Args:\n column (|int| or |str|):\n Column specifier. column index or header name correlated with the column.\n style (|Style|):\n Style value to be set to the column.\n\n Raises:\n ValueError: If the... |
Please provide a description of the function:def close(self):
if self.stream is None:
return
try:
self.stream.isatty()
if self.stream.name in ["<stdin>", "<stdout>", "<stderr>"]:
return
except AttributeError:
pass
... | [
"\n Close the current |stream|.\n "
] |
Please provide a description of the function:def from_tabledata(self, value, is_overwrite_table_name=True):
self.__clear_preprocess()
if is_overwrite_table_name:
self.table_name = value.table_name
self.headers = value.headers
self.value_matrix = value.rows
... | [
"\n Set tabular attributes to the writer from |TableData|.\n Following attributes are configured:\n\n - :py:attr:`~.table_name`.\n - :py:attr:`~.headers`.\n - :py:attr:`~.value_matrix`.\n\n |TableData| can be created from various data formats by\n ``pytablereader``. ... |
Please provide a description of the function:def from_csv(self, csv_source, delimiter=","):
import pytablereader as ptr
loader = ptr.CsvTableTextLoader(csv_source, quoting_flags=self._quoting_flags)
loader.delimiter = delimiter
try:
for table_data in loader.load():... | [
"\n Set tabular attributes to the writer from a character-separated values (CSV) data source.\n Following attributes are set to the writer by the method:\n\n - :py:attr:`~.headers`.\n - :py:attr:`~.value_matrix`.\n\n :py:attr:`~.table_name` also be set if the CSV data source is a ... |
Please provide a description of the function:def from_dataframe(self, dataframe, add_index_column=False):
if typepy.String(dataframe).is_type():
import pandas as pd
dataframe = pd.read_pickle(dataframe)
self.headers = list(dataframe.columns.values)
self.type_h... | [
"\n Set tabular attributes to the writer from :py:class:`pandas.DataFrame`.\n Following attributes are set by the method:\n\n - :py:attr:`~.headers`\n - :py:attr:`~.value_matrix`\n - :py:attr:`~.type_hints`\n\n Args:\n dataframe(pandas.DataFrame or |s... |
Please provide a description of the function:def from_series(self, series, add_index_column=True):
if series.name:
self.headers = [series.name]
else:
self.headers = ["value"]
self.type_hints = [self.__get_typehint_from_dtype(series.dtype)]
if add_index... | [
"\n Set tabular attributes to the writer from :py:class:`pandas.Series`.\n Following attributes are set by the method:\n\n - :py:attr:`~.headers`\n - :py:attr:`~.value_matrix`\n - :py:attr:`~.type_hints`\n\n Args:\n series(pandas.Series):\n ... |
Please provide a description of the function:def from_tablib(self, tablib_dataset):
self.headers = tablib_dataset.headers
self.value_matrix = [row for row in tablib_dataset] | [
"\n Set tabular attributes to the writer from :py:class:`tablib.Dataset`.\n "
] |
Please provide a description of the function:def write_table(self):
with self._logger:
self._verify_property()
self._preprocess()
for values in self._table_value_matrix:
self._write_line(json.dumps(values)) | [
"\n |write_table| with\n `Line-delimited JSON(LDJSON) <https://en.wikipedia.org/wiki/JSON_streaming#Line-delimited_JSON>`__\n /NDJSON/JSON Lines format.\n\n :raises pytablewriter.EmptyHeaderError: If the |headers| is empty.\n :Example:\n :ref:`example-jsonl-writer`\n ... |
Please provide a description of the function:def _ids(self):
for pk in self._pks:
yield getattr(self, pk)
for pk in self._pks:
try:
yield str(getattr(self, pk))
except ValueError:
pass | [
"The list of primary keys to validate against."
] |
Please provide a description of the function:def upgrade(self, name, params=None):
# Allow non-namespaced upgrades. (e.g. advanced vs logging:advanced)
if ':' not in name:
name = '{0}:{1}'.format(self.type, name)
r = self._h._http_resource(
method='PUT',
... | [
"Upgrades an addon to the given tier."
] |
Please provide a description of the function:def new(self, name=None, stack='cedar', region=None):
payload = {}
if name:
payload['app[name]'] = name
if stack:
payload['app[stack]'] = stack
if region:
payload['app[region]'] = region
... | [
"Creates a new app."
] |
Please provide a description of the function:def collaborators(self):
return self._h._get_resources(
resource=('apps', self.name, 'collaborators'),
obj=Collaborator, app=self
) | [
"The collaborators for this app."
] |
Please provide a description of the function:def domains(self):
return self._h._get_resources(
resource=('apps', self.name, 'domains'),
obj=Domain, app=self
) | [
"The domains for this app."
] |
Please provide a description of the function:def releases(self):
return self._h._get_resources(
resource=('apps', self.name, 'releases'),
obj=Release, app=self
) | [
"The releases for this app."
] |
Please provide a description of the function:def processes(self):
return self._h._get_resources(
resource=('apps', self.name, 'ps'),
obj=Process, app=self, map=ProcessListResource
) | [
"The proccesses for this app."
] |
Please provide a description of the function:def config(self):
return self._h._get_resource(
resource=('apps', self.name, 'config_vars'),
obj=ConfigVars, app=self
) | [
"The envs for this app."
] |
Please provide a description of the function:def info(self):
return self._h._get_resource(
resource=('apps', self.name),
obj=App,
) | [
"Returns current info for this app."
] |
Please provide a description of the function:def rollback(self, release):
r = self._h._http_resource(
method='POST',
resource=('apps', self.name, 'releases'),
data={'rollback': release}
)
return self.releases[-1] | [
"Rolls back the release to the given version."
] |
Please provide a description of the function:def rename(self, name):
r = self._h._http_resource(
method='PUT',
resource=('apps', self.name),
data={'app[name]': name}
)
return r.ok | [
"Renames app to given name."
] |
Please provide a description of the function:def transfer(self, user):
r = self._h._http_resource(
method='PUT',
resource=('apps', self.name),
data={'app[transfer_owner]': user}
)
return r.ok | [
"Transfers app to given username's account."
] |
Please provide a description of the function:def maintenance(self, on=True):
r = self._h._http_resource(
method='POST',
resource=('apps', self.name, 'server', 'maintenance'),
data={'maintenance_mode': int(on)}
)
return r.ok | [
"Toggles maintenance mode."
] |
Please provide a description of the function:def destroy(self):
r = self._h._http_resource(
method='DELETE',
resource=('apps', self.name)
)
return r.ok | [
"Destoys the app. Do be careful."
] |
Please provide a description of the function:def logs(self, num=None, source=None, ps=None, tail=False):
# Bootstrap payload package.
payload = {'logplex': 'true'}
if num:
payload['num'] = num
if source:
payload['source'] = source
if ps:
... | [
"Returns the requested log."
] |
Please provide a description of the function:def delete(self):
r = self._h._http_resource(
method='DELETE',
resource=('user', 'keys', self.id)
)
r.raise_for_status() | [
"Deletes the key."
] |
Please provide a description of the function:def new(self, command, attach=""):
r = self._h._http_resource(
method='POST',
resource=('apps', self.app.name, 'ps',),
data={'attach': attach, 'command': command}
)
r.raise_for_status()
return self... | [
"\n Creates a new Process\n Attach: If attach=True it will return a rendezvous connection point, for streaming stdout/stderr\n Command: The actual command it will run\n "
] |
Please provide a description of the function:def restart(self, all=False):
if all:
data = {'type': self.type}
else:
data = {'ps': self.process}
r = self._h._http_resource(
method='POST',
resource=('apps', self.app.name, 'ps', 'restart')... | [
"Restarts the given process."
] |
Please provide a description of the function:def scale(self, quantity):
r = self._h._http_resource(
method='POST',
resource=('apps', self.app.name, 'ps', 'scale'),
data={'type': self.type, 'qty': quantity}
)
r.raise_for_status()
try:
... | [
"Scales the given process to the given number of dynos."
] |
Please provide a description of the function:def is_collection(obj):
col = getattr(obj, '__getitem__', False)
val = False if (not col) else True
if isinstance(obj, basestring):
val = False
return val | [
"Tests if an object is a collection."
] |
Please provide a description of the function:def to_python(obj,
in_dict,
str_keys=None,
date_keys=None,
int_keys=None,
object_map=None,
bool_keys=None,
dict_keys=None,
**kwargs):
d = dict()
if str_keys:
for in_key in str_keys:
d[in_key] = in_dict.get(in... | [
"Extends a given object for API Consumption.\n\n :param obj: Object to extend.\n :param in_dict: Dict to extract data from.\n :param string_keys: List of in_dict keys that will be extracted as strings.\n :param date_keys: List of in_dict keys that will be extrad as datetimes.\n :param object_map: Dic... |
Please provide a description of the function:def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None):
# Cast all int_keys to int()
if int_keys:
for in_key in int_keys:
if (in_key in in_dict) and (in_dict.get(in_key, None) is not None):
in_dict[in_key] = int(i... | [
"Extends a given object for API Production."
] |
Please provide a description of the function:def clear(self):
r = self._h._http_resource(
method='DELETE',
resource=('user', 'keys'),
)
return r.ok | [
"Removes all SSH keys from a user's system."
] |
Please provide a description of the function:def authenticate(self, api_key):
self._api_key = api_key
# Attach auth to session.
self._session.auth = ('', self._api_key)
return self._verify_api_key() | [
"Logs user into Heroku with given api_key."
] |
Please provide a description of the function:def _http_resource(self, method, resource, params=None, data=None):
if not is_collection(resource):
resource = [resource]
url = self._url_for(*resource)
r = self._session.request(method, url, params=params, data=data)
i... | [
"Makes an HTTP request."
] |
Please provide a description of the function:def _get_resource(self, resource, obj, params=None, **kwargs):
r = self._http_resource('GET', resource, params=params)
item = self._resource_deserialize(r.content.decode("utf-8"))
return obj.new_from_dict(item, h=self, **kwargs) | [
"Returns a mapped object from an HTTP resource."
] |
Please provide a description of the function:def _get_resources(self, resource, obj, params=None, map=None, **kwargs):
r = self._http_resource('GET', resource, params=params)
d_items = self._resource_deserialize(r.content.decode("utf-8"))
items = [obj.new_from_dict(item, h=self, **kwa... | [
"Returns a list of mapped objects from an HTTP resource."
] |
Please provide a description of the function:def from_key(api_key, **kwargs):
h = Heroku(**kwargs)
# Login.
h.authenticate(api_key)
return h | [
"Returns an authenticated Heroku instance, via API Key."
] |
Please provide a description of the function:def get_setup_version(location, reponame, pkgname=None, archive_commit=None):
import warnings
pkgname = reponame if pkgname is None else pkgname
if archive_commit is None:
warnings.warn("No archive commit available; git archives will not contain vers... | [
"Helper for use in setup.py to get the current version from either\n git describe or the .version file (if available).\n\n Set pkgname to the package name if it is different from the\n repository name.\n\n To ensure git information is included in a git archive, add\n setup.py to .gitattributes (in ad... |
Please provide a description of the function:def get_setupcfg_version():
try:
import configparser
except ImportError:
import ConfigParser as configparser # python2 (also prevents dict-like access)
import re
cfg = "setup.cfg"
autover_section = 'tool:autover'
config = configpa... | [
"As get_setup_version(), but configure via setup.cfg.\n\n If your project uses setup.cfg to configure setuptools, and hence has\n at least a \"name\" key in the [metadata] section, you can\n set the version as follows:\n ```\n [metadata]\n name = mypackage\n version = attr: autover.version.get_... |
Please provide a description of the function:def fetch(self):
if self._release is not None:
return self
self._release = self.expected_release
if not self.fpath:
self._commit = self._expected_commit
return self
# Only git right now but easil... | [
"\n Returns a tuple of the major version together with the\n appropriate SHA and dirty bit (for development version only).\n "
] |
Please provide a description of the function:def _known_stale(self):
if self._output_from_file() is None:
commit = None
else:
commit = self.commit
known_stale = (self.archive_commit is not None
and not self.archive_commit.startswith('$Form... | [
"\n The commit is known to be from a file (and therefore stale) if a\n SHA is supplied by git archive and doesn't match the parsed commit.\n "
] |
Please provide a description of the function:def _output_from_file(self, entry='git_describe'):
try:
vfile = os.path.join(os.path.dirname(self.fpath), '.version')
with open(vfile, 'r') as f:
return json.loads(f.read()).get(entry, None)
except: # File may ... | [
"\n Read the version from a .version file that may exist alongside __init__.py.\n\n This file can be generated by piping the following output to file:\n\n git describe --long --match v*.*\n "
] |
Please provide a description of the function:def _update_from_vcs(self, output):
"Update state based on the VCS state e.g the output of git describe"
split = output[1:].split('-')
dot_split = split[0].split('.')
for prefix in ['a','b','rc']:
if prefix in dot_split[-1]:
... | [] |
Please provide a description of the function:def get_setup_version(cls, setup_path, reponame, describe=False,
dirty='report', pkgname=None, archive_commit=None):
pkgname = reponame if pkgname is None else pkgname
policies = ['raise','report', 'strip']
if dirty ... | [
"\n Helper for use in setup.py to get the version from the .version file (if available)\n or more up-to-date information from git describe (if available).\n\n Assumes the __init__.py will be found in the directory\n {reponame}/__init__.py relative to setup.py unless pkgname is\n e... |
Please provide a description of the function:def _update_from_vcs(self, output):
"Update state based on the VCS state e.g the output of git describe"
split = output[1:].split('-')
if 'dev' in split[0]:
dev_split = split[0].split('dev')
self.dev = int(dev_split[1])
... | [] |
Please provide a description of the function:def abbrev(self,dev_suffix=""):
return '.'.join(str(el) for el in self.release) + \
(dev_suffix if self.commit_count > 0 or self.dirty else "") | [
"\n Abbreviated string representation, optionally declaring whether it is\n a development version.\n "
] |
Please provide a description of the function:def verify(self, string_version=None):
if string_version and string_version != str(self):
raise Exception("Supplied string version does not match current version.")
if self.dirty:
raise Exception("Current working directory is... | [
"\n Check that the version information is consistent with the VCS\n before doing a release. If supplied with a string version,\n this is also checked against the current version. Should be\n called from setup.py with the declared package version before\n releasing to PyPI.\n ... |
Please provide a description of the function:def _check_time_fn(self, time_instance=False):
if time_instance and not isinstance(self.time_fn, param.Time):
raise AssertionError("%s requires a Time object"
% self.__class__.__name__)
if self.time_depen... | [
"\n If time_fn is the global time function supplied by\n param.Dynamic.time_fn, make sure Dynamic parameters are using\n this time function to control their behaviour.\n\n If time_instance is True, time_fn must be a param.Time instance.\n "
] |
Please provide a description of the function:def _rational(self, val):
I32 = 4294967296 # Maximum 32 bit unsigned int (i.e. 'I') value
if isinstance(val, int):
numer, denom = val, 1
elif isinstance(val, fractions.Fraction):
numer, denom = val.numerator, val.den... | [
"Convert the given value to a rational, if necessary."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.