repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
JoeVirtual/KonFoo | konfoo/core.py | Pointer.read_from | def read_from(self, provider, null_allowed=False, **options):
""" Reads from the data :class:`Provider` the necessary number of bytes
for the :attr:`data` object referenced by the `Pointer` field.
A `Pointer` field stores the binary data read from the data
:class:`Provider` in its :attr... | python | def read_from(self, provider, null_allowed=False, **options):
""" Reads from the data :class:`Provider` the necessary number of bytes
for the :attr:`data` object referenced by the `Pointer` field.
A `Pointer` field stores the binary data read from the data
:class:`Provider` in its :attr... | [
"def",
"read_from",
"(",
"self",
",",
"provider",
",",
"null_allowed",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"pass",
"elif",
"is_provider",
"(",
"provider",
")",
":",
"if",
"self",
".",
"_val... | Reads from the data :class:`Provider` the necessary number of bytes
for the :attr:`data` object referenced by the `Pointer` field.
A `Pointer` field stores the binary data read from the data
:class:`Provider` in its :attr:`bytestream`.
:param Provider provider: data :class:`Provider`.
... | [
"Reads",
"from",
"the",
"data",
":",
"class",
":",
"Provider",
"the",
"necessary",
"number",
"of",
"bytes",
"for",
"the",
":",
"attr",
":",
"data",
"object",
"referenced",
"by",
"the",
"Pointer",
"field",
"."
] | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5017-L5054 | train | Reads from the data provider and populates the internal state of the object. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.patch | def patch(self, item, byte_order=BYTEORDER):
""" Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteorder`, :class... | python | def patch(self, item, byte_order=BYTEORDER):
""" Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteorder`, :class... | [
"def",
"patch",
"(",
"self",
",",
"item",
",",
"byte_order",
"=",
"BYTEORDER",
")",
":",
"# Re-index the data object",
"self",
".",
"index_data",
"(",
")",
"if",
"is_container",
"(",
"item",
")",
":",
"length",
"=",
"item",
".",
"container_size",
"(",
")",... | Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteorder`, :class:`str` | [
"Returns",
"a",
"memory",
":",
"class",
":",
"Patch",
"for",
"the",
"given",
"*",
"item",
"*",
"that",
"shall",
"be",
"patched",
"in",
"the",
"data",
"source",
"."
] | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5056-L5159 | train | Returns a memory object that shall be patched in the data source. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.write_to | def write_to(self, provider, item, byte_order=BYTEORDER):
""" Writes via a data :class:`Provider` the :class:`Field` values of
the given *item* to the `data source`.
:param Provider provider: data :class:`Provider`.
:param item: item to write.
:param byte_order: encoding :class:... | python | def write_to(self, provider, item, byte_order=BYTEORDER):
""" Writes via a data :class:`Provider` the :class:`Field` values of
the given *item* to the `data source`.
:param Provider provider: data :class:`Provider`.
:param item: item to write.
:param byte_order: encoding :class:... | [
"def",
"write_to",
"(",
"self",
",",
"provider",
",",
"item",
",",
"byte_order",
"=",
"BYTEORDER",
")",
":",
"# Create memory patch for the item to write",
"patch",
"=",
"self",
".",
"patch",
"(",
"item",
",",
"byte_order",
")",
"if",
"patch",
"is",
"None",
... | Writes via a data :class:`Provider` the :class:`Field` values of
the given *item* to the `data source`.
:param Provider provider: data :class:`Provider`.
:param item: item to write.
:param byte_order: encoding :class:`Byteorder`.
:type byte_order: :class:`Byteorder`, :class:`str... | [
"Writes",
"via",
"a",
"data",
":",
"class",
":",
"Provider",
"the",
":",
"class",
":",
"Field",
"values",
"of",
"the",
"given",
"*",
"item",
"*",
"to",
"the",
"data",
"source",
"."
] | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5161-L5196 | train | Writes the contents of the given item to the given data source. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.deserialize | def deserialize(self, buffer=bytes(), index=Index(), **options):
""" De-serializes the `Pointer` field from the byte *buffer* starting
at the begin of the *buffer* or with the given *index* by mapping the
bytes to the :attr:`value` of the `Pointer` field in accordance with
the decoding *... | python | def deserialize(self, buffer=bytes(), index=Index(), **options):
""" De-serializes the `Pointer` field from the byte *buffer* starting
at the begin of the *buffer* or with the given *index* by mapping the
bytes to the :attr:`value` of the `Pointer` field in accordance with
the decoding *... | [
"def",
"deserialize",
"(",
"self",
",",
"buffer",
"=",
"bytes",
"(",
")",
",",
"index",
"=",
"Index",
"(",
")",
",",
"*",
"*",
"options",
")",
":",
"# Field",
"index",
"=",
"super",
"(",
")",
".",
"deserialize",
"(",
"buffer",
",",
"index",
",",
... | De-serializes the `Pointer` field from the byte *buffer* starting
at the begin of the *buffer* or with the given *index* by mapping the
bytes to the :attr:`value` of the `Pointer` field in accordance with
the decoding *byte order* for the de-serialization and the decoding
:attr:`byte_ord... | [
"De",
"-",
"serializes",
"the",
"Pointer",
"field",
"from",
"the",
"byte",
"*",
"buffer",
"*",
"starting",
"at",
"the",
"begin",
"of",
"the",
"*",
"buffer",
"*",
"or",
"with",
"the",
"given",
"*",
"index",
"*",
"by",
"mapping",
"the",
"bytes",
"to",
... | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5200-L5234 | train | Deserializes the current record into a new index. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.initialize_fields | def initialize_fields(self, content):
""" Initializes the `Pointer` field itself and the :class:`Field` items
in the :attr:`data` object referenced by the `Pointer` field with the
*values* in the *content* dictionary.
The ``['value']`` key in the *content* dictionary refers to the `Poin... | python | def initialize_fields(self, content):
""" Initializes the `Pointer` field itself and the :class:`Field` items
in the :attr:`data` object referenced by the `Pointer` field with the
*values* in the *content* dictionary.
The ``['value']`` key in the *content* dictionary refers to the `Poin... | [
"def",
"initialize_fields",
"(",
"self",
",",
"content",
")",
":",
"for",
"name",
",",
"value",
"in",
"content",
".",
"items",
"(",
")",
":",
"if",
"name",
"is",
"'value'",
":",
"self",
".",
"value",
"=",
"value",
"elif",
"name",
"is",
"'data'",
":",... | Initializes the `Pointer` field itself and the :class:`Field` items
in the :attr:`data` object referenced by the `Pointer` field with the
*values* in the *content* dictionary.
The ``['value']`` key in the *content* dictionary refers to the `Pointer`
field itself and the ``['data']`` key... | [
"Initializes",
"the",
"Pointer",
"field",
"itself",
"and",
"the",
":",
"class",
":",
"Field",
"items",
"in",
"the",
":",
"attr",
":",
"data",
"object",
"referenced",
"by",
"the",
"Pointer",
"field",
"with",
"the",
"*",
"values",
"*",
"in",
"the",
"*",
... | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5276-L5299 | train | Initializes the fields of the items of the object with the values in the content dictionary. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.index_fields | def index_fields(self, index=Index(), **options):
""" Indexes the `Pointer` field and the :attr:`data` object referenced
by the `Pointer` field starting with the given *index* and returns the
:class:`Index` after the `Pointer` field.
:param Index index: :class:`Index` for the `Pointer` ... | python | def index_fields(self, index=Index(), **options):
""" Indexes the `Pointer` field and the :attr:`data` object referenced
by the `Pointer` field starting with the given *index* and returns the
:class:`Index` after the `Pointer` field.
:param Index index: :class:`Index` for the `Pointer` ... | [
"def",
"index_fields",
"(",
"self",
",",
"index",
"=",
"Index",
"(",
")",
",",
"*",
"*",
"options",
")",
":",
"index",
"=",
"self",
".",
"index_field",
"(",
"index",
")",
"# Container",
"if",
"is_container",
"(",
"self",
".",
"_data",
")",
":",
"self... | Indexes the `Pointer` field and the :attr:`data` object referenced
by the `Pointer` field starting with the given *index* and returns the
:class:`Index` after the `Pointer` field.
:param Index index: :class:`Index` for the `Pointer` field.
:keyword bool nested: if ``True`` all :class:`P... | [
"Indexes",
"the",
"Pointer",
"field",
"and",
"the",
":",
"attr",
":",
"data",
"object",
"referenced",
"by",
"the",
"Pointer",
"field",
"starting",
"with",
"the",
"given",
"*",
"index",
"*",
"and",
"returns",
"the",
":",
"class",
":",
"Index",
"after",
"t... | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5302-L5332 | train | Indexes the fields of the Nested Nested |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.view_fields | def view_fields(self, *attributes, **options):
""" Returns an :class:`ordered dictionary <collections.OrderedDict>` which
contains the selected field *attributes* of the `Pointer` field itself
extended with a ``['data']`` key which contains the selected field *attribute*
or the dictionar... | python | def view_fields(self, *attributes, **options):
""" Returns an :class:`ordered dictionary <collections.OrderedDict>` which
contains the selected field *attributes* of the `Pointer` field itself
extended with a ``['data']`` key which contains the selected field *attribute*
or the dictionar... | [
"def",
"view_fields",
"(",
"self",
",",
"*",
"attributes",
",",
"*",
"*",
"options",
")",
":",
"items",
"=",
"OrderedDict",
"(",
")",
"# Pointer field",
"if",
"attributes",
":",
"field_getter",
"=",
"attrgetter",
"(",
"*",
"attributes",
")",
"else",
":",
... | Returns an :class:`ordered dictionary <collections.OrderedDict>` which
contains the selected field *attributes* of the `Pointer` field itself
extended with a ``['data']`` key which contains the selected field *attribute*
or the dictionaries of the selected field *attributes* for each :class:`Fie... | [
"Returns",
"an",
":",
"class",
":",
"ordered",
"dictionary",
"<collections",
".",
"OrderedDict",
">",
"which",
"contains",
"the",
"selected",
"field",
"*",
"attributes",
"*",
"of",
"the",
"Pointer",
"field",
"itself",
"extended",
"with",
"a",
"[",
"data",
"]... | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5335-L5390 | train | Returns an ordered dictionary of the selected fields of the current object. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.field_items | def field_items(self, path=str(), **options):
""" Returns a **flatten** list of ``('field path', field item)`` tuples
for the `Pointer` field itself and for each :class:`Field` *nested* in the
:attr:`data` object referenced by the `Pointer` field.
:param str path: path of the `Pointer` ... | python | def field_items(self, path=str(), **options):
""" Returns a **flatten** list of ``('field path', field item)`` tuples
for the `Pointer` field itself and for each :class:`Field` *nested* in the
:attr:`data` object referenced by the `Pointer` field.
:param str path: path of the `Pointer` ... | [
"def",
"field_items",
"(",
"self",
",",
"path",
"=",
"str",
"(",
")",
",",
"*",
"*",
"options",
")",
":",
"items",
"=",
"list",
"(",
")",
"# Field",
"items",
".",
"append",
"(",
"(",
"path",
"if",
"path",
"else",
"'field'",
",",
"self",
")",
")",... | Returns a **flatten** list of ``('field path', field item)`` tuples
for the `Pointer` field itself and for each :class:`Field` *nested* in the
:attr:`data` object referenced by the `Pointer` field.
:param str path: path of the `Pointer` field.
:keyword bool nested: if ``True`` all :clas... | [
"Returns",
"a",
"**",
"flatten",
"**",
"list",
"of",
"(",
"field",
"path",
"field",
"item",
")",
"tuples",
"for",
"the",
"Pointer",
"field",
"itself",
"and",
"for",
"each",
":",
"class",
":",
"Field",
"*",
"nested",
"*",
"in",
"the",
":",
"attr",
":"... | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5393-L5420 | train | Returns a list of tuples containing the field path and field item for each field in the object referenced by the Pointer field. |
JoeVirtual/KonFoo | konfoo/core.py | Pointer.describe | def describe(self, name=str(), **options):
""" Returns the **metadata** of a `Pointer` as an
:class:`ordered dictionary <collections.OrderedDict>`.
.. code-block:: python
metadata = {
'address': self.index.address,
'alignment': [self.alignment.byte_s... | python | def describe(self, name=str(), **options):
""" Returns the **metadata** of a `Pointer` as an
:class:`ordered dictionary <collections.OrderedDict>`.
.. code-block:: python
metadata = {
'address': self.index.address,
'alignment': [self.alignment.byte_s... | [
"def",
"describe",
"(",
"self",
",",
"name",
"=",
"str",
"(",
")",
",",
"*",
"*",
"options",
")",
":",
"metadata",
"=",
"super",
"(",
")",
".",
"describe",
"(",
"name",
",",
"*",
"*",
"options",
")",
"metadata",
"[",
"'class'",
"]",
"=",
"self",
... | Returns the **metadata** of a `Pointer` as an
:class:`ordered dictionary <collections.OrderedDict>`.
.. code-block:: python
metadata = {
'address': self.index.address,
'alignment': [self.alignment.byte_size, self.alignment.bit_offset],
'class... | [
"Returns",
"the",
"**",
"metadata",
"**",
"of",
"a",
"Pointer",
"as",
"an",
":",
"class",
":",
"ordered",
"dictionary",
"<collections",
".",
"OrderedDict",
">",
"."
] | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L5423-L5457 | train | Returns the description of a Pointer field. |
JoeVirtual/KonFoo | konfoo/core.py | ArrayPointer.resize | def resize(self, size):
""" Re-sizes the :class:`Array` by appending new :class:`Array` elements
or removing :class:`Array` elements from the end.
:param int size: new size of the :class:`Array` in number of
:class:`Array` elements.
"""
if isinstance(self._data, Arra... | python | def resize(self, size):
""" Re-sizes the :class:`Array` by appending new :class:`Array` elements
or removing :class:`Array` elements from the end.
:param int size: new size of the :class:`Array` in number of
:class:`Array` elements.
"""
if isinstance(self._data, Arra... | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_data",
",",
"Array",
")",
":",
"self",
".",
"_data",
".",
"resize",
"(",
"size",
")"
] | Re-sizes the :class:`Array` by appending new :class:`Array` elements
or removing :class:`Array` elements from the end.
:param int size: new size of the :class:`Array` in number of
:class:`Array` elements. | [
"Re",
"-",
"sizes",
"the",
":",
"class",
":",
"Array",
"by",
"appending",
"new",
":",
"class",
":",
"Array",
"elements",
"or",
"removing",
":",
"class",
":",
"Array",
"elements",
"from",
"the",
"end",
"."
] | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L6118-L6126 | train | Re - sizes the array by appending new elements to the end of the array. |
JoeVirtual/KonFoo | konfoo/core.py | StreamPointer.resize | def resize(self, size):
""" Re-sizes the :class:`Stream` field by appending zero bytes or
removing bytes from the end.
:param int size: :class:`Stream` size in number of bytes.
"""
if isinstance(self._data, Stream):
self._data.resize(size) | python | def resize(self, size):
""" Re-sizes the :class:`Stream` field by appending zero bytes or
removing bytes from the end.
:param int size: :class:`Stream` size in number of bytes.
"""
if isinstance(self._data, Stream):
self._data.resize(size) | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_data",
",",
"Stream",
")",
":",
"self",
".",
"_data",
".",
"resize",
"(",
"size",
")"
] | Re-sizes the :class:`Stream` field by appending zero bytes or
removing bytes from the end.
:param int size: :class:`Stream` size in number of bytes. | [
"Re",
"-",
"sizes",
"the",
":",
"class",
":",
"Stream",
"field",
"by",
"appending",
"zero",
"bytes",
"or",
"removing",
"bytes",
"from",
"the",
"end",
"."
] | 0c62ef5c2bed4deaf908b34082e4de2544532fdc | https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/core.py#L6343-L6350 | train | Re - sizes the internal stream field by appending zero bytes or removing bytes from the end. |
shapiromatron/bmds | bmds/datasets.py | DichotomousDataset.as_dfile | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
Example
-------
>>> print(dataset.as_dfile())
Dose Incidence NEGATIVE_RESPONSE
0.000000 5 70
1.960000 1 48
5.690000 3 47
29.750000 14 35
"""
rows ... | python | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
Example
-------
>>> print(dataset.as_dfile())
Dose Incidence NEGATIVE_RESPONSE
0.000000 5 70
1.960000 1 48
5.690000 3 47
29.750000 14 35
"""
rows ... | [
"def",
"as_dfile",
"(",
"self",
")",
":",
"rows",
"=",
"[",
"\"Dose Incidence NEGATIVE_RESPONSE\"",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"self",
".",
"doses",
")",
":",
"if",
"i",
">=",
"self",
".",
"num_dose_groups",
":",
"continue",
"rows... | Return the dataset representation in BMDS .(d) file.
Example
-------
>>> print(dataset.as_dfile())
Dose Incidence NEGATIVE_RESPONSE
0.000000 5 70
1.960000 1 48
5.690000 3 47
29.750000 14 35 | [
"Return",
"the",
"dataset",
"representation",
"in",
"BMDS",
".",
"(",
"d",
")",
"file",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L109-L127 | train | Return the dataset representation in BMDS. d file. |
shapiromatron/bmds | bmds/datasets.py | DichotomousDataset.to_dict | def to_dict(self):
"""
Returns a dictionary representation of the dataset.
"""
d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences)
d.update(self.kwargs)
return d | python | def to_dict(self):
"""
Returns a dictionary representation of the dataset.
"""
d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences)
d.update(self.kwargs)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"doses",
"=",
"self",
".",
"doses",
",",
"ns",
"=",
"self",
".",
"ns",
",",
"incidences",
"=",
"self",
".",
"incidences",
")",
"d",
".",
"update",
"(",
"self",
".",
"kwargs",
")",
... | Returns a dictionary representation of the dataset. | [
"Returns",
"a",
"dictionary",
"representation",
"of",
"the",
"dataset",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L136-L142 | train | Returns a dictionary representation of the dataset. |
shapiromatron/bmds | bmds/datasets.py | DichotomousDataset._calculate_plotting | def _calculate_plotting(n, incidence):
"""
Add confidence intervals to dichotomous datasets. From bmds231_manual.pdf, pg 124-5.
LL = {(2np + z2 - 1) - z*sqrt[z2 - (2+1/n) + 4p(nq+1)]}/[2*(n+z2)]
UL = {(2np + z2 + 1) + z*sqrt[z2 + (2-1/n) + 4p(nq-1)]}/[2*(n+z2)]
- p = the observ... | python | def _calculate_plotting(n, incidence):
"""
Add confidence intervals to dichotomous datasets. From bmds231_manual.pdf, pg 124-5.
LL = {(2np + z2 - 1) - z*sqrt[z2 - (2+1/n) + 4p(nq+1)]}/[2*(n+z2)]
UL = {(2np + z2 + 1) + z*sqrt[z2 + (2-1/n) + 4p(nq-1)]}/[2*(n+z2)]
- p = the observ... | [
"def",
"_calculate_plotting",
"(",
"n",
",",
"incidence",
")",
":",
"p",
"=",
"incidence",
"/",
"float",
"(",
"n",
")",
"z",
"=",
"stats",
".",
"norm",
".",
"ppf",
"(",
"0.975",
")",
"q",
"=",
"1.",
"-",
"p",
"ll",
"=",
"(",
"(",
"2",
"*",
"n... | Add confidence intervals to dichotomous datasets. From bmds231_manual.pdf, pg 124-5.
LL = {(2np + z2 - 1) - z*sqrt[z2 - (2+1/n) + 4p(nq+1)]}/[2*(n+z2)]
UL = {(2np + z2 + 1) + z*sqrt[z2 + (2-1/n) + 4p(nq-1)]}/[2*(n+z2)]
- p = the observed proportion
- n = the total number in the group i... | [
"Add",
"confidence",
"intervals",
"to",
"dichotomous",
"datasets",
".",
"From",
"bmds231_manual",
".",
"pdf",
"pg",
"124",
"-",
"5",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L145-L171 | train | Calculate the error bars and confidence intervals for a specific set of attributes. |
shapiromatron/bmds | bmds/datasets.py | ContinuousDataset.drop_dose | def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
for fld in ("doses", "ns", "means", "stdevs"):
arr = getattr(self, fld)[:-1]
setattr(self, fld, arr)
self._validate() | python | def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
for fld in ("doses", "ns", "means", "stdevs"):
arr = getattr(self, fld)[:-1]
setattr(self, fld, arr)
self._validate() | [
"def",
"drop_dose",
"(",
"self",
")",
":",
"for",
"fld",
"in",
"(",
"\"doses\"",
",",
"\"ns\"",
",",
"\"means\"",
",",
"\"stdevs\"",
")",
":",
"arr",
"=",
"getattr",
"(",
"self",
",",
"fld",
")",
"[",
":",
"-",
"1",
"]",
"setattr",
"(",
"self",
"... | Drop the maximum dose and related response values. | [
"Drop",
"the",
"maximum",
"dose",
"and",
"related",
"response",
"values",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L304-L311 | train | Drop the maximum dose and related response values. |
shapiromatron/bmds | bmds/datasets.py | ContinuousDataset.as_dfile | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose NumAnimals Response Stdev"]
for i, v in enumerate(self.doses):
if i >= self.num_dose_groups:
continue
rows.append(
"%f %d %f %f" ... | python | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose NumAnimals Response Stdev"]
for i, v in enumerate(self.doses):
if i >= self.num_dose_groups:
continue
rows.append(
"%f %d %f %f" ... | [
"def",
"as_dfile",
"(",
"self",
")",
":",
"rows",
"=",
"[",
"\"Dose NumAnimals Response Stdev\"",
"]",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"self",
".",
"doses",
")",
":",
"if",
"i",
">=",
"self",
".",
"num_dose_groups",
":",
"continue",
"rows",... | Return the dataset representation in BMDS .(d) file. | [
"Return",
"the",
"dataset",
"representation",
"in",
"BMDS",
".",
"(",
"d",
")",
"file",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L313-L324 | train | Return the dataset representation in BMDS. d file. |
shapiromatron/bmds | bmds/datasets.py | ContinuousDataset.to_dict | def to_dict(self):
"""
Return a dictionary representation of the dataset.
"""
d = dict(doses=self.doses, ns=self.ns, means=self.means, stdevs=self.stdevs)
d.update(self.kwargs)
return d | python | def to_dict(self):
"""
Return a dictionary representation of the dataset.
"""
d = dict(doses=self.doses, ns=self.ns, means=self.means, stdevs=self.stdevs)
d.update(self.kwargs)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"doses",
"=",
"self",
".",
"doses",
",",
"ns",
"=",
"self",
".",
"ns",
",",
"means",
"=",
"self",
".",
"means",
",",
"stdevs",
"=",
"self",
".",
"stdevs",
")",
"d",
".",
"update",
... | Return a dictionary representation of the dataset. | [
"Return",
"a",
"dictionary",
"representation",
"of",
"the",
"dataset",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L354-L360 | train | Returns a dictionary representation of the dataset. |
shapiromatron/bmds | bmds/datasets.py | ContinuousDataset.plot | def plot(self):
"""
Return a matplotlib figure of the dose-response dataset.
Examples
--------
>>> fig = dataset.plot()
>>> fig.show()
.. image:: ../tests/resources/test_cdataset_plot.png
:align: center
:alt: Example generated BMD plot
... | python | def plot(self):
"""
Return a matplotlib figure of the dose-response dataset.
Examples
--------
>>> fig = dataset.plot()
>>> fig.show()
.. image:: ../tests/resources/test_cdataset_plot.png
:align: center
:alt: Example generated BMD plot
... | [
"def",
"plot",
"(",
"self",
")",
":",
"fig",
"=",
"plotting",
".",
"create_empty_figure",
"(",
")",
"ax",
"=",
"fig",
".",
"gca",
"(",
")",
"xlabel",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"xlabel\"",
",",
"\"Dose\"",
")",
"ylabel",
"=",
"s... | Return a matplotlib figure of the dose-response dataset.
Examples
--------
>>> fig = dataset.plot()
>>> fig.show()
.. image:: ../tests/resources/test_cdataset_plot.png
:align: center
:alt: Example generated BMD plot
Returns
-------
... | [
"Return",
"a",
"matplotlib",
"figure",
"of",
"the",
"dose",
"-",
"response",
"dataset",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L372-L406 | train | Returns a matplotlib figure of the dose - response dataset. |
shapiromatron/bmds | bmds/datasets.py | ContinuousIndividualDataset.drop_dose | def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
doses = np.array(self.individual_doses)
responses = np.array(self.responses)
mask = doses != doses.max()
self.individual_doses = doses[mask].tolist()
self.responses = responses... | python | def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
doses = np.array(self.individual_doses)
responses = np.array(self.responses)
mask = doses != doses.max()
self.individual_doses = doses[mask].tolist()
self.responses = responses... | [
"def",
"drop_dose",
"(",
"self",
")",
":",
"doses",
"=",
"np",
".",
"array",
"(",
"self",
".",
"individual_doses",
")",
"responses",
"=",
"np",
".",
"array",
"(",
"self",
".",
"responses",
")",
"mask",
"=",
"doses",
"!=",
"doses",
".",
"max",
"(",
... | Drop the maximum dose and related response values. | [
"Drop",
"the",
"maximum",
"dose",
"and",
"related",
"response",
"values",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L482-L492 | train | Drop the maximum dose and related response values. |
shapiromatron/bmds | bmds/datasets.py | ContinuousIndividualDataset.as_dfile | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose Response"]
for dose, response in zip(self.individual_doses, self.responses):
dose_idx = self.doses.index(dose)
if dose_idx >= self.num_dose_groups:
... | python | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose Response"]
for dose, response in zip(self.individual_doses, self.responses):
dose_idx = self.doses.index(dose)
if dose_idx >= self.num_dose_groups:
... | [
"def",
"as_dfile",
"(",
"self",
")",
":",
"rows",
"=",
"[",
"\"Dose Response\"",
"]",
"for",
"dose",
",",
"response",
"in",
"zip",
"(",
"self",
".",
"individual_doses",
",",
"self",
".",
"responses",
")",
":",
"dose_idx",
"=",
"self",
".",
"doses",
"."... | Return the dataset representation in BMDS .(d) file. | [
"Return",
"the",
"dataset",
"representation",
"in",
"BMDS",
".",
"(",
"d",
")",
"file",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L494-L504 | train | Return the dataset representation in BMDS. d file. |
shapiromatron/bmds | bmds/datasets.py | ContinuousIndividualDataset.to_dict | def to_dict(self):
"""
Return a dictionary representation of the dataset.
"""
d = dict(individual_doses=self.individual_doses, responses=self.responses)
d.update(self.kwargs)
return d | python | def to_dict(self):
"""
Return a dictionary representation of the dataset.
"""
d = dict(individual_doses=self.individual_doses, responses=self.responses)
d.update(self.kwargs)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"individual_doses",
"=",
"self",
".",
"individual_doses",
",",
"responses",
"=",
"self",
".",
"responses",
")",
"d",
".",
"update",
"(",
"self",
".",
"kwargs",
")",
"return",
"d"
] | Return a dictionary representation of the dataset. | [
"Return",
"a",
"dictionary",
"representation",
"of",
"the",
"dataset",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L515-L521 | train | Returns a dictionary representation of the dataset. |
shapiromatron/bmds | bmds/datasets.py | ContinuousIndividualDataset.plot | def plot(self):
"""
Return a matplotlib figure of the dose-response dataset.
Examples
--------
>>> fig = dataset.plot()
>>> fig.show()
>>> fig.clear()
.. image:: ../tests/resources/test_cidataset_plot.png
:align: center
:alt: Exampl... | python | def plot(self):
"""
Return a matplotlib figure of the dose-response dataset.
Examples
--------
>>> fig = dataset.plot()
>>> fig.show()
>>> fig.clear()
.. image:: ../tests/resources/test_cidataset_plot.png
:align: center
:alt: Exampl... | [
"def",
"plot",
"(",
"self",
")",
":",
"fig",
"=",
"plotting",
".",
"create_empty_figure",
"(",
")",
"ax",
"=",
"fig",
".",
"gca",
"(",
")",
"xlabel",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"xlabel\"",
",",
"\"Dose\"",
")",
"ylabel",
"=",
"s... | Return a matplotlib figure of the dose-response dataset.
Examples
--------
>>> fig = dataset.plot()
>>> fig.show()
>>> fig.clear()
.. image:: ../tests/resources/test_cidataset_plot.png
:align: center
:alt: Example generated BMD plot
Return... | [
"Return",
"a",
"matplotlib",
"figure",
"of",
"the",
"dose",
"-",
"response",
"dataset",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L523-L557 | train | Returns a matplotlib figure of the dose - response dataset. |
marrow/util | marrow/util/context/__init__.py | cd | def cd(path, on=os):
"""Change the current working directory within this context.
Preserves the previous working directory and can be applied to remote
connections that offer @getcwd@ and @chdir@ methods using the @on@
argument.
"""
original = on.getcwd()
on.chdir(path)
yi... | python | def cd(path, on=os):
"""Change the current working directory within this context.
Preserves the previous working directory and can be applied to remote
connections that offer @getcwd@ and @chdir@ methods using the @on@
argument.
"""
original = on.getcwd()
on.chdir(path)
yi... | [
"def",
"cd",
"(",
"path",
",",
"on",
"=",
"os",
")",
":",
"original",
"=",
"on",
".",
"getcwd",
"(",
")",
"on",
".",
"chdir",
"(",
"path",
")",
"yield",
"on",
".",
"chdir",
"(",
"original",
")"
] | Change the current working directory within this context.
Preserves the previous working directory and can be applied to remote
connections that offer @getcwd@ and @chdir@ methods using the @on@
argument. | [
"Change",
"the",
"current",
"working",
"directory",
"within",
"this",
"context",
".",
"Preserves",
"the",
"previous",
"working",
"directory",
"and",
"can",
"be",
"applied",
"to",
"remote",
"connections",
"that",
"offer"
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/context/__init__.py#L13-L26 | train | Change the current working directory within this context. |
marrow/util | marrow/util/context/__init__.py | path | def path(append=None, prepend=None, replace=None, on=os):
"""Update the PATH environment variable.
Can append, prepend, or replace the path. Each of these expects a string
or a list of strings (for multiple path elements) and can operate on remote
connections that offer an @environ@ attribute usin... | python | def path(append=None, prepend=None, replace=None, on=os):
"""Update the PATH environment variable.
Can append, prepend, or replace the path. Each of these expects a string
or a list of strings (for multiple path elements) and can operate on remote
connections that offer an @environ@ attribute usin... | [
"def",
"path",
"(",
"append",
"=",
"None",
",",
"prepend",
"=",
"None",
",",
"replace",
"=",
"None",
",",
"on",
"=",
"os",
")",
":",
"original",
"=",
"on",
".",
"environ",
"[",
"'PATH'",
"]",
"if",
"replace",
"and",
"(",
"append",
"or",
"prepend",
... | Update the PATH environment variable.
Can append, prepend, or replace the path. Each of these expects a string
or a list of strings (for multiple path elements) and can operate on remote
connections that offer an @environ@ attribute using the @on@ argument. | [
"Update",
"the",
"PATH",
"environment",
"variable",
".",
"Can",
"append",
"prepend",
"or",
"replace",
"the",
"path",
".",
"Each",
"of",
"these",
"expects",
"a",
"string",
"or",
"a",
"list",
"of",
"strings",
"(",
"for",
"multiple",
"path",
"elements",
")",
... | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/context/__init__.py#L30-L66 | train | Update the PATH environment variable. |
marrow/util | marrow/util/context/__init__.py | environ | def environ(on=os, **kw):
"""Update one or more environment variables.
Preserves the previous environment variable (if available) and can be
applied to remote connections that offer an @environ@ attribute using the
@on@ argument.
"""
originals = list()
for key in kw:
o... | python | def environ(on=os, **kw):
"""Update one or more environment variables.
Preserves the previous environment variable (if available) and can be
applied to remote connections that offer an @environ@ attribute using the
@on@ argument.
"""
originals = list()
for key in kw:
o... | [
"def",
"environ",
"(",
"on",
"=",
"os",
",",
"*",
"*",
"kw",
")",
":",
"originals",
"=",
"list",
"(",
")",
"for",
"key",
"in",
"kw",
":",
"originals",
".",
"append",
"(",
"(",
"key",
",",
"on",
".",
"environ",
".",
"get",
"(",
"key",
",",
"No... | Update one or more environment variables.
Preserves the previous environment variable (if available) and can be
applied to remote connections that offer an @environ@ attribute using the
@on@ argument. | [
"Update",
"one",
"or",
"more",
"environment",
"variables",
".",
"Preserves",
"the",
"previous",
"environment",
"variable",
"(",
"if",
"available",
")",
"and",
"can",
"be",
"applied",
"to",
"remote",
"connections",
"that",
"offer",
"an"
] | abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/context/__init__.py#L70-L91 | train | Update one or more environment variables. |
textbook/atmdb | atmdb/core.py | Service.url_builder | def url_builder(self, endpoint, *, root=None, params=None, url_params=None):
"""Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
para... | python | def url_builder(self, endpoint, *, root=None, params=None, url_params=None):
"""Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
para... | [
"def",
"url_builder",
"(",
"self",
",",
"endpoint",
",",
"*",
",",
"root",
"=",
"None",
",",
"params",
"=",
"None",
",",
"url_params",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"self",
".",
"ROOT",
"return",
"''",
".",
... | Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
params: (:py:class:`dict`, optional): The values for format
into the created URL... | [
"Create",
"a",
"URL",
"for",
"the",
"specified",
"endpoint",
"."
] | cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L40-L62 | train | Creates a URL for the specified endpoint. |
textbook/atmdb | atmdb/core.py | Service.calculate_timeout | def calculate_timeout(http_date):
"""Extract request timeout from e.g. ``Retry-After`` header.
Notes:
Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can
be either an integer number of seconds or an HTTP date. This
function can handle either.
Arguments:
... | python | def calculate_timeout(http_date):
"""Extract request timeout from e.g. ``Retry-After`` header.
Notes:
Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can
be either an integer number of seconds or an HTTP date. This
function can handle either.
Arguments:
... | [
"def",
"calculate_timeout",
"(",
"http_date",
")",
":",
"try",
":",
"return",
"int",
"(",
"http_date",
")",
"except",
"ValueError",
":",
"date_after",
"=",
"parse",
"(",
"http_date",
")",
"utc_now",
"=",
"datetime",
".",
"now",
"(",
"tz",
"=",
"timezone",
... | Extract request timeout from e.g. ``Retry-After`` header.
Notes:
Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can
be either an integer number of seconds or an HTTP date. This
function can handle either.
Arguments:
http_date (:py:class:`str`): The da... | [
"Extract",
"request",
"timeout",
"from",
"e",
".",
"g",
".",
"Retry",
"-",
"After",
"header",
"."
] | cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L65-L85 | train | Extract request timeout from e. g. Retry - After header. |
textbook/atmdb | atmdb/core.py | TokenAuthMixin.from_env | def from_env(cls):
"""Create a service instance from an environment variable."""
token = getenv(cls.TOKEN_ENV_VAR)
if token is None:
msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR)
raise ValueError(msg)
return cls(api_token=token) | python | def from_env(cls):
"""Create a service instance from an environment variable."""
token = getenv(cls.TOKEN_ENV_VAR)
if token is None:
msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR)
raise ValueError(msg)
return cls(api_token=token) | [
"def",
"from_env",
"(",
"cls",
")",
":",
"token",
"=",
"getenv",
"(",
"cls",
".",
"TOKEN_ENV_VAR",
")",
"if",
"token",
"is",
"None",
":",
"msg",
"=",
"'missing environment variable: {!r}'",
".",
"format",
"(",
"cls",
".",
"TOKEN_ENV_VAR",
")",
"raise",
"Va... | Create a service instance from an environment variable. | [
"Create",
"a",
"service",
"instance",
"from",
"an",
"environment",
"variable",
"."
] | cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L104-L110 | train | Create a service instance from an environment variable. |
textbook/atmdb | atmdb/core.py | UrlParamMixin.url_builder | def url_builder(self, endpoint, params=None, url_params=None):
"""Add authentication URL parameter."""
if url_params is None:
url_params = OrderedDict()
url_params[self.AUTH_PARAM] = self.api_token
return super().url_builder(
endpoint,
params=params,
... | python | def url_builder(self, endpoint, params=None, url_params=None):
"""Add authentication URL parameter."""
if url_params is None:
url_params = OrderedDict()
url_params[self.AUTH_PARAM] = self.api_token
return super().url_builder(
endpoint,
params=params,
... | [
"def",
"url_builder",
"(",
"self",
",",
"endpoint",
",",
"params",
"=",
"None",
",",
"url_params",
"=",
"None",
")",
":",
"if",
"url_params",
"is",
"None",
":",
"url_params",
"=",
"OrderedDict",
"(",
")",
"url_params",
"[",
"self",
".",
"AUTH_PARAM",
"]"... | Add authentication URL parameter. | [
"Add",
"authentication",
"URL",
"parameter",
"."
] | cab14547d2e777a1e26c2560266365c484855789 | https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L119-L128 | train | Add authentication URL parameter. |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/random_string_finder.py | get_found_locations | def get_found_locations():
"""
INFO:__main__:found HELP in 1572
INFO:__main__:found MATHS in 1704
INFO:__main__:found ROCKS in 1975
#random.seed(1572)
#garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)])
#wrd_location = garbage.find('HELP')
#print(wrd_location) # 7383... | python | def get_found_locations():
"""
INFO:__main__:found HELP in 1572
INFO:__main__:found MATHS in 1704
INFO:__main__:found ROCKS in 1975
#random.seed(1572)
#garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)])
#wrd_location = garbage.find('HELP')
#print(wrd_location) # 7383... | [
"def",
"get_found_locations",
"(",
")",
":",
"#random.seed(1704)",
"#garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)])",
"#wrd_location = garbage.find('MATHS')",
"#print(wrd_location) # 73834",
"#print(garbage[wrd_location:wrd_location+5]) # HELP",
"random",
".",
"seed... | INFO:__main__:found HELP in 1572
INFO:__main__:found MATHS in 1704
INFO:__main__:found ROCKS in 1975
#random.seed(1572)
#garbage = ''.join([chr(random.randint(32,122)) for x in range(100000)])
#wrd_location = garbage.find('HELP')
#print(wrd_location) # 73834
#print(garbage[wrd_location:wrd_l... | [
"INFO",
":",
"__main__",
":",
"found",
"HELP",
"in",
"1572",
"INFO",
":",
"__main__",
":",
"found",
"MATHS",
"in",
"1704",
"INFO",
":",
"__main__",
":",
"found",
"ROCKS",
"in",
"1975",
"#random",
".",
"seed",
"(",
"1572",
")",
"#garbage",
"=",
".",
"... | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/random_string_finder.py#L50-L76 | train | Get a list of locations of the found files. |
Xion/taipan | taipan/api/decorators.py | decorator | def decorator(decor):
"""Decorator for decorators (sic), written either as classes or functions.
In either case, the decorator ``decor`` must be "doubly-callable":
* for classes, this means implementing ``__call__`` method
in addition to possible ``__init__``
* for functions, this me... | python | def decorator(decor):
"""Decorator for decorators (sic), written either as classes or functions.
In either case, the decorator ``decor`` must be "doubly-callable":
* for classes, this means implementing ``__call__`` method
in addition to possible ``__init__``
* for functions, this me... | [
"def",
"decorator",
"(",
"decor",
")",
":",
"ensure_callable",
"(",
"decor",
")",
"return",
"_wrap_decorator",
"(",
"decor",
",",
"\"functions or classes\"",
",",
"or_",
"(",
"inspect",
".",
"isfunction",
",",
"inspect",
".",
"isclass",
")",
")"
] | Decorator for decorators (sic), written either as classes or functions.
In either case, the decorator ``decor`` must be "doubly-callable":
* for classes, this means implementing ``__call__`` method
in addition to possible ``__init__``
* for functions, this means returning a function that... | [
"Decorator",
"for",
"decorators",
"(",
"sic",
")",
"written",
"either",
"as",
"classes",
"or",
"functions",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/api/decorators.py#L19-L50 | train | Decorator for functions and classes. |
Xion/taipan | taipan/api/decorators.py | _wrap_decorator | def _wrap_decorator(decorator, targets, is_valid_target):
"""Wraps given decorator in order to provide additional functionality:
optional arguments and verification of decorator's target type.
:param decorator: Decorator callable
:param targets: Name of the decorator targets, as plural
... | python | def _wrap_decorator(decorator, targets, is_valid_target):
"""Wraps given decorator in order to provide additional functionality:
optional arguments and verification of decorator's target type.
:param decorator: Decorator callable
:param targets: Name of the decorator targets, as plural
... | [
"def",
"_wrap_decorator",
"(",
"decorator",
",",
"targets",
",",
"is_valid_target",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"decorator",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# handle the case when decorator is app... | Wraps given decorator in order to provide additional functionality:
optional arguments and verification of decorator's target type.
:param decorator: Decorator callable
:param targets: Name of the decorator targets, as plural
(used in error messages)
:param is_valid_target: Callable... | [
"Wraps",
"given",
"decorator",
"in",
"order",
"to",
"provide",
"additional",
"functionality",
":",
"optional",
"arguments",
"and",
"verification",
"of",
"decorator",
"s",
"target",
"type",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/api/decorators.py#L159-L198 | train | Wraps given decorator in order to provide additional functionality of the functions. |
tjcsl/cslbot | cslbot/commands/reddit.py | cmd | def cmd(send, msg, args):
"""Gets a random Reddit post.
Syntax: {command} [subreddit]
"""
if msg and not check_exists(msg):
send("Non-existant subreddit.")
return
subreddit = msg if msg else None
send(random_post(subreddit, args['config']['api']['bitlykey'])) | python | def cmd(send, msg, args):
"""Gets a random Reddit post.
Syntax: {command} [subreddit]
"""
if msg and not check_exists(msg):
send("Non-existant subreddit.")
return
subreddit = msg if msg else None
send(random_post(subreddit, args['config']['api']['bitlykey'])) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"msg",
"and",
"not",
"check_exists",
"(",
"msg",
")",
":",
"send",
"(",
"\"Non-existant subreddit.\"",
")",
"return",
"subreddit",
"=",
"msg",
"if",
"msg",
"else",
"None",
"send",
"(",... | Gets a random Reddit post.
Syntax: {command} [subreddit] | [
"Gets",
"a",
"random",
"Reddit",
"post",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/reddit.py#L23-L33 | train | Gets a random Reddit post. |
tjcsl/cslbot | cslbot/commands/choose.py | cmd | def cmd(send, msg, args):
"""Chooses between multiple choices.
Syntax: {command} <object> or <object> (or <object>...)
"""
if not msg:
send("Choose what?")
return
choices = msg.split(' or ')
action = [
'draws a slip of paper from a hat and gets...', 'says eenie, menie, ... | python | def cmd(send, msg, args):
"""Chooses between multiple choices.
Syntax: {command} <object> or <object> (or <object>...)
"""
if not msg:
send("Choose what?")
return
choices = msg.split(' or ')
action = [
'draws a slip of paper from a hat and gets...', 'says eenie, menie, ... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Choose what?\"",
")",
"return",
"choices",
"=",
"msg",
".",
"split",
"(",
"' or '",
")",
"action",
"=",
"[",
"'draws a slip of paper from a hat and gets.... | Chooses between multiple choices.
Syntax: {command} <object> or <object> (or <object>...) | [
"Chooses",
"between",
"multiple",
"choices",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/choose.py#L24-L38 | train | Selects between multiple choices. |
tjcsl/cslbot | cslbot/commands/pester.py | cmd | def cmd(send, msg, args):
"""Pesters somebody.
Syntax: {command} <nick> <message>
"""
if not msg or len(msg.split()) < 2:
send("Pester needs at least two arguments.")
return
match = re.match('(%s+) (.*)' % args['config']['core']['nickregex'], msg)
if match:
message = ma... | python | def cmd(send, msg, args):
"""Pesters somebody.
Syntax: {command} <nick> <message>
"""
if not msg or len(msg.split()) < 2:
send("Pester needs at least two arguments.")
return
match = re.match('(%s+) (.*)' % args['config']['core']['nickregex'], msg)
if match:
message = ma... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
"or",
"len",
"(",
"msg",
".",
"split",
"(",
")",
")",
"<",
"2",
":",
"send",
"(",
"\"Pester needs at least two arguments.\"",
")",
"return",
"match",
"=",
"re",
".",
... | Pesters somebody.
Syntax: {command} <nick> <message> | [
"Pesters",
"somebody",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/pester.py#L24-L38 | train | Pesters somebody.
Syntax |
tethysplatform/condorpy | condorpy/node.py | Node._get_all_descendants | def _get_all_descendants(self):
"""
traverses all descendants nodes
:raises: CircularDependency if self is contained in descendants
:return: a set containing all descendant nodes
"""
descendants = set()
descendants = descendants.union(self.child_nodes)
for... | python | def _get_all_descendants(self):
"""
traverses all descendants nodes
:raises: CircularDependency if self is contained in descendants
:return: a set containing all descendant nodes
"""
descendants = set()
descendants = descendants.union(self.child_nodes)
for... | [
"def",
"_get_all_descendants",
"(",
"self",
")",
":",
"descendants",
"=",
"set",
"(",
")",
"descendants",
"=",
"descendants",
".",
"union",
"(",
"self",
".",
"child_nodes",
")",
"for",
"child",
"in",
"self",
".",
"child_nodes",
":",
"descendants",
"=",
"de... | traverses all descendants nodes
:raises: CircularDependency if self is contained in descendants
:return: a set containing all descendant nodes | [
"traverses",
"all",
"descendants",
"nodes",
":",
"raises",
":",
"CircularDependency",
"if",
"self",
"is",
"contained",
"in",
"descendants",
":",
"return",
":",
"a",
"set",
"containing",
"all",
"descendant",
"nodes"
] | a5aaaef0d73198f7d9756dda7abe98b4e209f1f4 | https://github.com/tethysplatform/condorpy/blob/a5aaaef0d73198f7d9756dda7abe98b4e209f1f4/condorpy/node.py#L449-L463 | train | Returns a set containing all descendant nodes. |
shapiromatron/bmds | bmds/session.py | BMDS.get_model | def get_model(cls, version, model_name):
"""
Return BMDS model class given BMDS version and model-name.
"""
models = cls.versions[version].model_options
for keystore in models.values():
if model_name in keystore:
return keystore[model_name]
rai... | python | def get_model(cls, version, model_name):
"""
Return BMDS model class given BMDS version and model-name.
"""
models = cls.versions[version].model_options
for keystore in models.values():
if model_name in keystore:
return keystore[model_name]
rai... | [
"def",
"get_model",
"(",
"cls",
",",
"version",
",",
"model_name",
")",
":",
"models",
"=",
"cls",
".",
"versions",
"[",
"version",
"]",
".",
"model_options",
"for",
"keystore",
"in",
"models",
".",
"values",
"(",
")",
":",
"if",
"model_name",
"in",
"k... | Return BMDS model class given BMDS version and model-name. | [
"Return",
"BMDS",
"model",
"class",
"given",
"BMDS",
"version",
"and",
"model",
"-",
"name",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L37-L45 | train | Return the model class given the BMDS version and model - name. |
shapiromatron/bmds | bmds/session.py | BMDS.execute_and_recommend | def execute_and_recommend(self, drop_doses=False):
"""
Execute and recommend a best-fitting model. If drop_doses and no model
is recommended, drop the highest dose-group and repeat until either:
1. a model is recommended, or
2. the dataset is exhausted (i.e., only 3 dose-groups ... | python | def execute_and_recommend(self, drop_doses=False):
"""
Execute and recommend a best-fitting model. If drop_doses and no model
is recommended, drop the highest dose-group and repeat until either:
1. a model is recommended, or
2. the dataset is exhausted (i.e., only 3 dose-groups ... | [
"def",
"execute_and_recommend",
"(",
"self",
",",
"drop_doses",
"=",
"False",
")",
":",
"self",
".",
"execute",
"(",
")",
"self",
".",
"recommend",
"(",
")",
"if",
"not",
"drop_doses",
":",
"return",
"while",
"self",
".",
"recommended_model",
"is",
"None",... | Execute and recommend a best-fitting model. If drop_doses and no model
is recommended, drop the highest dose-group and repeat until either:
1. a model is recommended, or
2. the dataset is exhausted (i.e., only 3 dose-groups remain).
The session instance is equal to the final run which ... | [
"Execute",
"and",
"recommend",
"a",
"best",
"-",
"fitting",
"model",
".",
"If",
"drop_doses",
"and",
"no",
"model",
"is",
"recommended",
"drop",
"the",
"highest",
"dose",
"-",
"group",
"and",
"repeat",
"until",
"either",
":"
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L165-L187 | train | Execute and recommend a best - fitting model. |
shapiromatron/bmds | bmds/session.py | BMDS._add_to_to_ordered_dict | def _add_to_to_ordered_dict(self, d, dataset_index, recommended_only=False):
"""
Save a session to an ordered dictionary. In some cases, a single session may include
a final session, as well as other BMDS executions where doses were dropped. This
will include all sessions.
"""
... | python | def _add_to_to_ordered_dict(self, d, dataset_index, recommended_only=False):
"""
Save a session to an ordered dictionary. In some cases, a single session may include
a final session, as well as other BMDS executions where doses were dropped. This
will include all sessions.
"""
... | [
"def",
"_add_to_to_ordered_dict",
"(",
"self",
",",
"d",
",",
"dataset_index",
",",
"recommended_only",
"=",
"False",
")",
":",
"if",
"self",
".",
"doses_dropped_sessions",
":",
"for",
"key",
"in",
"sorted",
"(",
"list",
"(",
"self",
".",
"doses_dropped_sessio... | Save a session to an ordered dictionary. In some cases, a single session may include
a final session, as well as other BMDS executions where doses were dropped. This
will include all sessions. | [
"Save",
"a",
"session",
"to",
"an",
"ordered",
"dictionary",
".",
"In",
"some",
"cases",
"a",
"single",
"session",
"may",
"include",
"a",
"final",
"session",
"as",
"well",
"as",
"other",
"BMDS",
"executions",
"where",
"doses",
"were",
"dropped",
".",
"This... | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L226-L236 | train | Save a single session to an ordered dictionary. |
shapiromatron/bmds | bmds/session.py | BMDS._add_single_session_to_to_ordered_dict | def _add_single_session_to_to_ordered_dict(self, d, dataset_index, recommended_only):
"""
Save a single session to an ordered dictionary.
"""
for model_index, model in enumerate(self.models):
# determine if model should be presented, or if a null-model should
# be... | python | def _add_single_session_to_to_ordered_dict(self, d, dataset_index, recommended_only):
"""
Save a single session to an ordered dictionary.
"""
for model_index, model in enumerate(self.models):
# determine if model should be presented, or if a null-model should
# be... | [
"def",
"_add_single_session_to_to_ordered_dict",
"(",
"self",
",",
"d",
",",
"dataset_index",
",",
"recommended_only",
")",
":",
"for",
"model_index",
",",
"model",
"in",
"enumerate",
"(",
"self",
".",
"models",
")",
":",
"# determine if model should be presented, or ... | Save a single session to an ordered dictionary. | [
"Save",
"a",
"single",
"session",
"to",
"an",
"ordered",
"dictionary",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L238-L265 | train | Save a single session to an ordered dictionary. |
shapiromatron/bmds | bmds/session.py | BMDS._group_models | def _group_models(self):
"""
If AIC and BMD are numeric and identical, then treat models as
identical. Returns a list of lists. The outer list is a list of related
models, the inner list contains each individual model, sorted by the
number of parameters in ascending order.
... | python | def _group_models(self):
"""
If AIC and BMD are numeric and identical, then treat models as
identical. Returns a list of lists. The outer list is a list of related
models, the inner list contains each individual model, sorted by the
number of parameters in ascending order.
... | [
"def",
"_group_models",
"(",
"self",
")",
":",
"od",
"=",
"OrderedDict",
"(",
")",
"# Add models to appropriate list. We only aggregate models which",
"# completed successfully and have a valid AIC and BMD.",
"for",
"i",
",",
"model",
"in",
"enumerate",
"(",
"self",
".",
... | If AIC and BMD are numeric and identical, then treat models as
identical. Returns a list of lists. The outer list is a list of related
models, the inner list contains each individual model, sorted by the
number of parameters in ascending order.
This is required because in some cases, a ... | [
"If",
"AIC",
"and",
"BMD",
"are",
"numeric",
"and",
"identical",
"then",
"treat",
"models",
"as",
"identical",
".",
"Returns",
"a",
"list",
"of",
"lists",
".",
"The",
"outer",
"list",
"is",
"a",
"list",
"of",
"related",
"models",
"the",
"inner",
"list",
... | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/session.py#L355-L394 | train | Groups the models in the related cache entries into a list of lists. |
rraadd88/rohan | rohan/dandage/io_nums.py | is_numeric | def is_numeric(obj):
"""
This detects whether an input object is numeric or not.
:param obj: object to be tested.
"""
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True | python | def is_numeric(obj):
"""
This detects whether an input object is numeric or not.
:param obj: object to be tested.
"""
try:
obj+obj, obj-obj, obj*obj, obj**obj, obj/obj
except ZeroDivisionError:
return True
except Exception:
return False
else:
return True | [
"def",
"is_numeric",
"(",
"obj",
")",
":",
"try",
":",
"obj",
"+",
"obj",
",",
"obj",
"-",
"obj",
",",
"obj",
"*",
"obj",
",",
"obj",
"**",
"obj",
",",
"obj",
"/",
"obj",
"except",
"ZeroDivisionError",
":",
"return",
"True",
"except",
"Exception",
... | This detects whether an input object is numeric or not.
:param obj: object to be tested. | [
"This",
"detects",
"whether",
"an",
"input",
"object",
"is",
"numeric",
"or",
"not",
"."
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_nums.py#L14-L27 | train | This function detects whether an input object is numeric or not. |
rraadd88/rohan | rohan/dandage/io_nums.py | glog | def glog(x,l = 2):
"""
Generalised logarithm
:param x: number
:param p: number added befor logarithm
"""
return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l) | python | def glog(x,l = 2):
"""
Generalised logarithm
:param x: number
:param p: number added befor logarithm
"""
return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l) | [
"def",
"glog",
"(",
"x",
",",
"l",
"=",
"2",
")",
":",
"return",
"np",
".",
"log",
"(",
"(",
"x",
"+",
"np",
".",
"sqrt",
"(",
"x",
"**",
"2",
"+",
"l",
"**",
"2",
")",
")",
"/",
"2",
")",
"/",
"np",
".",
"log",
"(",
"l",
")"
] | Generalised logarithm
:param x: number
:param p: number added befor logarithm | [
"Generalised",
"logarithm"
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_nums.py#L59-L67 | train | Generalised logarithm of a number |
rraadd88/rohan | rohan/dandage/io_nums.py | float2int | def float2int(x):
"""
converts floats to int when only float() is not enough.
:param x: float
"""
if not pd.isnull(x):
if is_numeric(x):
x=int(x)
return x | python | def float2int(x):
"""
converts floats to int when only float() is not enough.
:param x: float
"""
if not pd.isnull(x):
if is_numeric(x):
x=int(x)
return x | [
"def",
"float2int",
"(",
"x",
")",
":",
"if",
"not",
"pd",
".",
"isnull",
"(",
"x",
")",
":",
"if",
"is_numeric",
"(",
"x",
")",
":",
"x",
"=",
"int",
"(",
"x",
")",
"return",
"x"
] | converts floats to int when only float() is not enough.
:param x: float | [
"converts",
"floats",
"to",
"int",
"when",
"only",
"float",
"()",
"is",
"not",
"enough",
"."
] | b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_nums.py#L69-L78 | train | converts floats to int when only float is not enough. |
tjcsl/cslbot | cslbot/commands/dc.py | cmd | def cmd(send, msg, args):
"""Evaluates mathmatical expressions.
Syntax: {command} <expression>
"""
if not msg:
send("Calculate what?")
return
if "!" in msg:
args['do_kick'](args['target'], args['nick'], "hacking")
return
msg += '\n'
proc = subprocess.Popen... | python | def cmd(send, msg, args):
"""Evaluates mathmatical expressions.
Syntax: {command} <expression>
"""
if not msg:
send("Calculate what?")
return
if "!" in msg:
args['do_kick'](args['target'], args['nick'], "hacking")
return
msg += '\n'
proc = subprocess.Popen... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Calculate what?\"",
")",
"return",
"if",
"\"!\"",
"in",
"msg",
":",
"args",
"[",
"'do_kick'",
"]",
"(",
"args",
"[",
"'target'",
"]",
",",
"args"... | Evaluates mathmatical expressions.
Syntax: {command} <expression> | [
"Evaluates",
"mathmatical",
"expressions",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/dc.py#L24-L52 | train | Evaluates mathmatical expressions. |
tjcsl/cslbot | cslbot/hooks/scores.py | handle | def handle(send, msg, args):
"""Handles scores.
If it's a ++ add one point unless the user is trying to promote
themselves. Otherwise substract one point.
"""
session = args['db']
matches = re.findall(r"\b(?<!-)(%s{2,16})(\+\+|--)" % args['config']['core']['nickregex'], msg)
if not matches... | python | def handle(send, msg, args):
"""Handles scores.
If it's a ++ add one point unless the user is trying to promote
themselves. Otherwise substract one point.
"""
session = args['db']
matches = re.findall(r"\b(?<!-)(%s{2,16})(\+\+|--)" % args['config']['core']['nickregex'], msg)
if not matches... | [
"def",
"handle",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"session",
"=",
"args",
"[",
"'db'",
"]",
"matches",
"=",
"re",
".",
"findall",
"(",
"r\"\\b(?<!-)(%s{2,16})(\\+\\+|--)\"",
"%",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'n... | Handles scores.
If it's a ++ add one point unless the user is trying to promote
themselves. Otherwise substract one point. | [
"Handles",
"scores",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/scores.py#L25-L57 | train | Handles scores.
. |
tjcsl/cslbot | cslbot/hooks/xkcd.py | handle | def handle(send, msg, args):
"""Implements several XKCD comics."""
output = textutils.gen_xkcd_sub(msg, True)
if output is None:
return
if args['type'] == 'action':
send("correction: * %s %s" % (args['nick'], output))
else:
send("%s actually meant: %s" % (args['nick'], output... | python | def handle(send, msg, args):
"""Implements several XKCD comics."""
output = textutils.gen_xkcd_sub(msg, True)
if output is None:
return
if args['type'] == 'action':
send("correction: * %s %s" % (args['nick'], output))
else:
send("%s actually meant: %s" % (args['nick'], output... | [
"def",
"handle",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"output",
"=",
"textutils",
".",
"gen_xkcd_sub",
"(",
"msg",
",",
"True",
")",
"if",
"output",
"is",
"None",
":",
"return",
"if",
"args",
"[",
"'type'",
"]",
"==",
"'action'",
":",
"s... | Implements several XKCD comics. | [
"Implements",
"several",
"XKCD",
"comics",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/xkcd.py#L23-L31 | train | Implements several XKCD comics. |
tjcsl/cslbot | cslbot/commands/nuke.py | cmd | def cmd(send, msg, args):
"""Nukes somebody.
Syntax: {command} <target>
"""
c, nick = args['handler'].connection, args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
if not msg:
send("Nuke who?")
return
with args['hand... | python | def cmd(send, msg, args):
"""Nukes somebody.
Syntax: {command} <target>
"""
c, nick = args['handler'].connection, args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
if not msg:
send("Nuke who?")
return
with args['hand... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"c",
",",
"nick",
"=",
"args",
"[",
"'handler'",
"]",
".",
"connection",
",",
"args",
"[",
"'nick'",
"]",
"channel",
"=",
"args",
"[",
"'target'",
"]",
"if",
"args",
"[",
"'target'",
"... | Nukes somebody.
Syntax: {command} <target> | [
"Nukes",
"somebody",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/nuke.py#L23-L41 | train | Nukes somebody. |
VIVelev/PyDojoML | dojo/statistics.py | calculate_mean_vectors | def calculate_mean_vectors(X, y):
"""Calculates the mean samples per class
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
mean_vectors : array-like, shape (k, )
Those are the mean samples f... | python | def calculate_mean_vectors(X, y):
"""Calculates the mean samples per class
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
mean_vectors : array-like, shape (k, )
Those are the mean samples f... | [
"def",
"calculate_mean_vectors",
"(",
"X",
",",
"y",
")",
":",
"return",
"[",
"np",
".",
"mean",
"(",
"X",
"[",
"y",
"==",
"cl",
",",
":",
"]",
",",
"axis",
"=",
"0",
")",
"for",
"cl",
"in",
"np",
".",
"unique",
"(",
"y",
")",
"]"
] | Calculates the mean samples per class
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
mean_vectors : array-like, shape (k, )
Those are the mean samples from each k classes. | [
"Calculates",
"the",
"mean",
"samples",
"per",
"class",
"Parameters",
":",
"-----------",
"X",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
"n",
")",
"-",
"the",
"samples",
"y",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
")",
"-",
"the",
"class",... | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/statistics.py#L11-L26 | train | Calculates the mean samples per class in the cluster. |
VIVelev/PyDojoML | dojo/statistics.py | calculate_within_class_scatter_matrix | def calculate_within_class_scatter_matrix(X, y):
"""Calculates the Within-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
within_class_scatter_matrix : array-like, shape (n,... | python | def calculate_within_class_scatter_matrix(X, y):
"""Calculates the Within-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
within_class_scatter_matrix : array-like, shape (n,... | [
"def",
"calculate_within_class_scatter_matrix",
"(",
"X",
",",
"y",
")",
":",
"mean_vectors",
"=",
"calculate_mean_vectors",
"(",
"X",
",",
"y",
")",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"Sw",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_feature... | Calculates the Within-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
within_class_scatter_matrix : array-like, shape (n, n) | [
"Calculates",
"the",
"Within",
"-",
"Class",
"Scatter",
"matrix",
"Parameters",
":",
"-----------",
"X",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
"n",
")",
"-",
"the",
"samples",
"y",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
")",
"-",
"the"... | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/statistics.py#L28-L55 | train | Calculates the Within - Class Scatter matrix within the class. |
VIVelev/PyDojoML | dojo/statistics.py | calculate_between_class_scatter_matrix | def calculate_between_class_scatter_matrix(X, y):
"""Calculates the Between-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
between_class_scatter_matrix : array-like, shape (n, ... | python | def calculate_between_class_scatter_matrix(X, y):
"""Calculates the Between-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
between_class_scatter_matrix : array-like, shape (n, ... | [
"def",
"calculate_between_class_scatter_matrix",
"(",
"X",
",",
"y",
")",
":",
"mean_vectors",
"=",
"calculate_mean_vectors",
"(",
"X",
",",
"y",
")",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"Sb",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_featur... | Calculates the Between-Class Scatter matrix
Parameters:
-----------
X : array-like, shape (m, n) - the samples
y : array-like, shape (m, ) - the class labels
Returns:
--------
between_class_scatter_matrix : array-like, shape (n, n) | [
"Calculates",
"the",
"Between",
"-",
"Class",
"Scatter",
"matrix",
"Parameters",
":",
"-----------",
"X",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
"n",
")",
"-",
"the",
"samples",
"y",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
")",
"-",
"the... | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/statistics.py#L57-L80 | train | Calculates the Between - Class Scatter matrix. |
VIVelev/PyDojoML | dojo/statistics.py | calculate_covariance_matrix | def calculate_covariance_matrix(X):
"""Calculates the Variance-Covariance matrix
Parameters:
-----------
X : array-like, shape (m, n) - the data
Returns:
--------
variance_covariance_matrix : array-like, shape(n, n)
"""
n_features = X.shape[1]
S = np.zeros((n_... | python | def calculate_covariance_matrix(X):
"""Calculates the Variance-Covariance matrix
Parameters:
-----------
X : array-like, shape (m, n) - the data
Returns:
--------
variance_covariance_matrix : array-like, shape(n, n)
"""
n_features = X.shape[1]
S = np.zeros((n_... | [
"def",
"calculate_covariance_matrix",
"(",
"X",
")",
":",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"S",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_features",
",",
"n_features",
")",
")",
"m",
"=",
"np",
".",
"mean",
"(",
"X",
",",
"axis",
... | Calculates the Variance-Covariance matrix
Parameters:
-----------
X : array-like, shape (m, n) - the data
Returns:
--------
variance_covariance_matrix : array-like, shape(n, n) | [
"Calculates",
"the",
"Variance",
"-",
"Covariance",
"matrix",
"Parameters",
":",
"-----------",
"X",
":",
"array",
"-",
"like",
"shape",
"(",
"m",
"n",
")",
"-",
"the",
"data",
"Returns",
":",
"--------",
"variance_covariance_matrix",
":",
"array",
"-",
"lik... | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/statistics.py#L82-L103 | train | Calculates the variance - covariance matrix for the current node. |
Xion/taipan | taipan/strings.py | trim | def trim(s, prefix=None, suffix=None, strict=False):
"""Trim a string, removing given prefix or suffix.
:param s: String to trim
:param prefix: Prefix to remove from ``s``
:param suffix: Suffix to remove from ``s``
:param strict: Whether the prefix or suffix must be present in ``s``.
... | python | def trim(s, prefix=None, suffix=None, strict=False):
"""Trim a string, removing given prefix or suffix.
:param s: String to trim
:param prefix: Prefix to remove from ``s``
:param suffix: Suffix to remove from ``s``
:param strict: Whether the prefix or suffix must be present in ``s``.
... | [
"def",
"trim",
"(",
"s",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"ensure_string",
"(",
"s",
")",
"has_prefix",
"=",
"prefix",
"is",
"not",
"None",
"has_suffix",
"=",
"suffix",
"is",
"not",
"None"... | Trim a string, removing given prefix or suffix.
:param s: String to trim
:param prefix: Prefix to remove from ``s``
:param suffix: Suffix to remove from ``s``
:param strict: Whether the prefix or suffix must be present in ``s``.
By default, if the infix is not found, function will si... | [
"Trim",
"a",
"string",
"removing",
"given",
"prefix",
"or",
"suffix",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L82-L132 | train | Trim a string from the alphabetical order of the words in a node. |
Xion/taipan | taipan/strings.py | split | def split(s, by=None, maxsplit=None):
"""Split a string based on given delimiter(s).
Delimiters can be either strings or compiled regular expression objects.
:param s: String to split
:param by: A delimiter, or iterable thereof.
:param maxsplit: Maximum number of splits to perform.
... | python | def split(s, by=None, maxsplit=None):
"""Split a string based on given delimiter(s).
Delimiters can be either strings or compiled regular expression objects.
:param s: String to split
:param by: A delimiter, or iterable thereof.
:param maxsplit: Maximum number of splits to perform.
... | [
"def",
"split",
"(",
"s",
",",
"by",
"=",
"None",
",",
"maxsplit",
"=",
"None",
")",
":",
"ensure_string",
"(",
"s",
")",
"# TODO(xion): Consider introducing a case for ``split('')``",
"# to make it return ``['']`` rather than default ``[]`` thru ``str.split``.",
"# It's the ... | Split a string based on given delimiter(s).
Delimiters can be either strings or compiled regular expression objects.
:param s: String to split
:param by: A delimiter, or iterable thereof.
:param maxsplit: Maximum number of splits to perform.
``None`` means no limit,
... | [
"Split",
"a",
"string",
"based",
"on",
"given",
"delimiter",
"(",
"s",
")",
".",
"Delimiters",
"can",
"be",
"either",
"strings",
"or",
"compiled",
"regular",
"expression",
"objects",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L137-L185 | train | Split a string into a list of words. |
Xion/taipan | taipan/strings.py | join | def join(delimiter, iterable, **kwargs):
"""Returns a string which is a concatenation of strings in ``iterable``,
separated by given ``delimiter``.
:param delimiter: Delimiter to put between strings
:param iterable: Iterable to join
Optional keyword arguments control the exact joining strategy:
... | python | def join(delimiter, iterable, **kwargs):
"""Returns a string which is a concatenation of strings in ``iterable``,
separated by given ``delimiter``.
:param delimiter: Delimiter to put between strings
:param iterable: Iterable to join
Optional keyword arguments control the exact joining strategy:
... | [
"def",
"join",
"(",
"delimiter",
",",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_string",
"(",
"delimiter",
")",
"ensure_iterable",
"(",
"iterable",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'errors'",
",",
"'with_'",... | Returns a string which is a concatenation of strings in ``iterable``,
separated by given ``delimiter``.
:param delimiter: Delimiter to put between strings
:param iterable: Iterable to join
Optional keyword arguments control the exact joining strategy:
:param errors:
What to do with errone... | [
"Returns",
"a",
"string",
"which",
"is",
"a",
"concatenation",
"of",
"strings",
"in",
"iterable",
"separated",
"by",
"given",
"delimiter",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L188-L245 | train | Returns a string which is a concatenation of strings in iterable separated by given delimiter. |
Xion/taipan | taipan/strings.py | camel_case | def camel_case(arg, capitalize=None):
"""Converts given text with whitespaces between words
into equivalent camel-cased one.
:param capitalize: Whether result will have first letter upper case (True),
lower case (False), or left as is (None, default).
:return: String turned into... | python | def camel_case(arg, capitalize=None):
"""Converts given text with whitespaces between words
into equivalent camel-cased one.
:param capitalize: Whether result will have first letter upper case (True),
lower case (False), or left as is (None, default).
:return: String turned into... | [
"def",
"camel_case",
"(",
"arg",
",",
"capitalize",
"=",
"None",
")",
":",
"ensure_string",
"(",
"arg",
")",
"if",
"not",
"arg",
":",
"return",
"arg",
"words",
"=",
"split",
"(",
"arg",
")",
"first_word",
"=",
"words",
"[",
"0",
"]",
"if",
"len",
"... | Converts given text with whitespaces between words
into equivalent camel-cased one.
:param capitalize: Whether result will have first letter upper case (True),
lower case (False), or left as is (None, default).
:return: String turned into camel-case "equivalent" | [
"Converts",
"given",
"text",
"with",
"whitespaces",
"between",
"words",
"into",
"equivalent",
"camel",
"-",
"cased",
"one",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L254-L278 | train | Converts given text with whitespaces between words
into equivalent camel - cased one. |
Xion/taipan | taipan/strings.py | replace | def replace(needle, with_=None, in_=None):
"""Replace occurrences of string(s) with other string(s) in (a) string(s).
Unlike the built in :meth:`str.replace` method, this function provides
clean API that clearly distinguishes the "needle" (string to replace),
the replacement string, and the target stri... | python | def replace(needle, with_=None, in_=None):
"""Replace occurrences of string(s) with other string(s) in (a) string(s).
Unlike the built in :meth:`str.replace` method, this function provides
clean API that clearly distinguishes the "needle" (string to replace),
the replacement string, and the target stri... | [
"def",
"replace",
"(",
"needle",
",",
"with_",
"=",
"None",
",",
"in_",
"=",
"None",
")",
":",
"if",
"needle",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"replacement needle cannot be None\"",
")",
"if",
"not",
"needle",
":",
"raise",
"ValueError",
"(... | Replace occurrences of string(s) with other string(s) in (a) string(s).
Unlike the built in :meth:`str.replace` method, this function provides
clean API that clearly distinguishes the "needle" (string to replace),
the replacement string, and the target string to perform replacement in
(the "haystack").... | [
"Replace",
"occurrences",
"of",
"string",
"(",
"s",
")",
"with",
"other",
"string",
"(",
"s",
")",
"in",
"(",
"a",
")",
"string",
"(",
"s",
")",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L283-L337 | train | Replaces occurrences of string with other string in a base string. |
Xion/taipan | taipan/strings.py | random | def random(length, chars=None):
"""Generates a random string.
:param length: Length of the string to generate.
This can be a numbe or a pair: ``(min_length, max_length)``
:param chars: String of characters to choose from
"""
if chars is None:
chars = string.ascii_letters ... | python | def random(length, chars=None):
"""Generates a random string.
:param length: Length of the string to generate.
This can be a numbe or a pair: ``(min_length, max_length)``
:param chars: String of characters to choose from
"""
if chars is None:
chars = string.ascii_letters ... | [
"def",
"random",
"(",
"length",
",",
"chars",
"=",
"None",
")",
":",
"if",
"chars",
"is",
"None",
":",
"chars",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"else",
":",
"ensure_string",
"(",
"chars",
")",
"if",
"not",
"chars",
... | Generates a random string.
:param length: Length of the string to generate.
This can be a numbe or a pair: ``(min_length, max_length)``
:param chars: String of characters to choose from | [
"Generates",
"a",
"random",
"string",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L418-L442 | train | Generates a random string. |
Xion/taipan | taipan/strings.py | Replacer.with_ | def with_(self, replacement):
"""Provide replacement for string "needles".
:param replacement: Target replacement for needles given in constructor
:return: The :class:`Replacement` object
:raise TypeError: If ``replacement`` is not a string
:raise ReplacementError: If replaceme... | python | def with_(self, replacement):
"""Provide replacement for string "needles".
:param replacement: Target replacement for needles given in constructor
:return: The :class:`Replacement` object
:raise TypeError: If ``replacement`` is not a string
:raise ReplacementError: If replaceme... | [
"def",
"with_",
"(",
"self",
",",
"replacement",
")",
":",
"ensure_string",
"(",
"replacement",
")",
"if",
"is_mapping",
"(",
"self",
".",
"_replacements",
")",
":",
"raise",
"ReplacementError",
"(",
"\"string replacements already provided\"",
")",
"self",
".",
... | Provide replacement for string "needles".
:param replacement: Target replacement for needles given in constructor
:return: The :class:`Replacement` object
:raise TypeError: If ``replacement`` is not a string
:raise ReplacementError: If replacement has been already given | [
"Provide",
"replacement",
"for",
"string",
"needles",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L367-L381 | train | Provide replacement for string needles. |
Xion/taipan | taipan/strings.py | Replacer.in_ | def in_(self, haystack):
"""Perform replacement in given string.
:param haystack: String to perform replacements in
:return: ``haystack`` after the replacements
:raise TypeError: If ``haystack`` if not a string
:raise ReplacementError: If no replacement(s) have been provided y... | python | def in_(self, haystack):
"""Perform replacement in given string.
:param haystack: String to perform replacements in
:return: ``haystack`` after the replacements
:raise TypeError: If ``haystack`` if not a string
:raise ReplacementError: If no replacement(s) have been provided y... | [
"def",
"in_",
"(",
"self",
",",
"haystack",
")",
":",
"from",
"taipan",
".",
"collections",
"import",
"dicts",
"ensure_string",
"(",
"haystack",
")",
"if",
"not",
"is_mapping",
"(",
"self",
".",
"_replacements",
")",
":",
"raise",
"ReplacementError",
"(",
... | Perform replacement in given string.
:param haystack: String to perform replacements in
:return: ``haystack`` after the replacements
:raise TypeError: If ``haystack`` if not a string
:raise ReplacementError: If no replacement(s) have been provided yet | [
"Perform",
"replacement",
"in",
"given",
"string",
"."
] | f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/strings.py#L383-L413 | train | Perform replacement in given string. |
tylerbutler/engineer | engineer/util.py | ensure_exists | def ensure_exists(p, assume_dirs=False):
"""
Ensures a given path *p* exists.
If a path to a file is passed in, then the path to the file will be checked. This can be overridden by passing a
value of ``True`` to ``assume_dirs``, in which case the paths will be assumed to be to directories, not files.
... | python | def ensure_exists(p, assume_dirs=False):
"""
Ensures a given path *p* exists.
If a path to a file is passed in, then the path to the file will be checked. This can be overridden by passing a
value of ``True`` to ``assume_dirs``, in which case the paths will be assumed to be to directories, not files.
... | [
"def",
"ensure_exists",
"(",
"p",
",",
"assume_dirs",
"=",
"False",
")",
":",
"if",
"path",
"(",
"p",
")",
".",
"ext",
"and",
"not",
"assume_dirs",
":",
"path",
"(",
"p",
")",
".",
"dirname",
"(",
")",
".",
"makedirs_p",
"(",
")",
"else",
":",
"p... | Ensures a given path *p* exists.
If a path to a file is passed in, then the path to the file will be checked. This can be overridden by passing a
value of ``True`` to ``assume_dirs``, in which case the paths will be assumed to be to directories, not files. | [
"Ensures",
"a",
"given",
"path",
"*",
"p",
"*",
"exists",
"."
] | 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L214-L225 | train | Ensures a given path p * exists. |
tylerbutler/engineer | engineer/util.py | wrap_list | def wrap_list(item):
"""
Returns an object as a list.
If the object is a list, it is returned directly. If it is a tuple or set, it
is returned as a list. If it is another object, it is wrapped in a list and
returned.
"""
if item is None:
return []
elif isinstance(item, list):
... | python | def wrap_list(item):
"""
Returns an object as a list.
If the object is a list, it is returned directly. If it is a tuple or set, it
is returned as a list. If it is another object, it is wrapped in a list and
returned.
"""
if item is None:
return []
elif isinstance(item, list):
... | [
"def",
"wrap_list",
"(",
"item",
")",
":",
"if",
"item",
"is",
"None",
":",
"return",
"[",
"]",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"return",
"item",
"elif",
"isinstance",
"(",
"item",
",",
"(",
"tuple",
",",
"set",
")",
")",
... | Returns an object as a list.
If the object is a list, it is returned directly. If it is a tuple or set, it
is returned as a list. If it is another object, it is wrapped in a list and
returned. | [
"Returns",
"an",
"object",
"as",
"a",
"list",
"."
] | 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L228-L243 | train | Returns an object as a list. |
tylerbutler/engineer | engineer/util.py | update_additive | def update_additive(dict1, dict2):
"""
A utility method to update a dict or other mapping type with the contents of another dict.
This method updates the contents of ``dict1``, overwriting any existing key/value pairs in ``dict1`` with the
corresponding key/value pair in ``dict2``. If the value in ``di... | python | def update_additive(dict1, dict2):
"""
A utility method to update a dict or other mapping type with the contents of another dict.
This method updates the contents of ``dict1``, overwriting any existing key/value pairs in ``dict1`` with the
corresponding key/value pair in ``dict2``. If the value in ``di... | [
"def",
"update_additive",
"(",
"dict1",
",",
"dict2",
")",
":",
"for",
"key",
",",
"value",
"in",
"dict2",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"dict1",
":",
"dict1",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"# key in dict1",
"... | A utility method to update a dict or other mapping type with the contents of another dict.
This method updates the contents of ``dict1``, overwriting any existing key/value pairs in ``dict1`` with the
corresponding key/value pair in ``dict2``. If the value in ``dict2`` is a mapping type itself, then
``upda... | [
"A",
"utility",
"method",
"to",
"update",
"a",
"dict",
"or",
"other",
"mapping",
"type",
"with",
"the",
"contents",
"of",
"another",
"dict",
"."
] | 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L366-L388 | train | A utility method to update the contents of a dict or other mapping type with the contents of another dict. |
tylerbutler/engineer | engineer/util.py | diff_dir | def diff_dir(dir_cmp, left_path=True):
"""
A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works
recursively.
:param dir_cmp: A ``filecmp.dircmp`` object representing the comparison.
:param left_path: If ``True``, paths will be relative to dirc... | python | def diff_dir(dir_cmp, left_path=True):
"""
A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works
recursively.
:param dir_cmp: A ``filecmp.dircmp`` object representing the comparison.
:param left_path: If ``True``, paths will be relative to dirc... | [
"def",
"diff_dir",
"(",
"dir_cmp",
",",
"left_path",
"=",
"True",
")",
":",
"for",
"name",
"in",
"dir_cmp",
".",
"diff_files",
":",
"if",
"left_path",
":",
"path_root",
"=",
"dir_cmp",
".",
"left",
"else",
":",
"path_root",
"=",
"dir_cmp",
".",
"right",
... | A generator that, given a ``filecmp.dircmp`` object, yields the paths to all files that are different. Works
recursively.
:param dir_cmp: A ``filecmp.dircmp`` object representing the comparison.
:param left_path: If ``True``, paths will be relative to dircmp.left. Else paths will be relative to dircmp.righ... | [
"A",
"generator",
"that",
"given",
"a",
"filecmp",
".",
"dircmp",
"object",
"yields",
"the",
"paths",
"to",
"all",
"files",
"that",
"are",
"different",
".",
"Works",
"recursively",
"."
] | 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/util.py#L446-L463 | train | A generator that yields the paths to all files that are different from the dir_cmp object. |
VIVelev/PyDojoML | dojo/base/preprocessor.py | Preprocessor.get_params | def get_params(self, *keys):
"""Returns the specified parameters for the current preprocessor.
Parameters:
-----------
keys : variable sized list, containing the names of the requested parameters
Returns:
--------
values : list or dictionary, if any `keys` are s... | python | def get_params(self, *keys):
"""Returns the specified parameters for the current preprocessor.
Parameters:
-----------
keys : variable sized list, containing the names of the requested parameters
Returns:
--------
values : list or dictionary, if any `keys` are s... | [
"def",
"get_params",
"(",
"self",
",",
"*",
"keys",
")",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
":",
"return",
"vars",
"(",
"self",
")",
"else",
":",
"return",
"[",
"vars",
"(",
"self",
")",
"[",
"k",
"]",
"for",
"k",
"in",
"keys",
"]... | Returns the specified parameters for the current preprocessor.
Parameters:
-----------
keys : variable sized list, containing the names of the requested parameters
Returns:
--------
values : list or dictionary, if any `keys` are specified
those named parameters'... | [
"Returns",
"the",
"specified",
"parameters",
"for",
"the",
"current",
"preprocessor",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/base/preprocessor.py#L32-L50 | train | Returns the specified parameters for the current preprocessor. |
VIVelev/PyDojoML | dojo/base/preprocessor.py | Preprocessor.set_params | def set_params(self, **params):
"""Sets new values to the specified parameters.
Parameters:
-----------
params : variable sized dictionary, n key-word arguments
Example:
```
scaler.set_params(std=0.30)
```
Returns:
-------... | python | def set_params(self, **params):
"""Sets new values to the specified parameters.
Parameters:
-----------
params : variable sized dictionary, n key-word arguments
Example:
```
scaler.set_params(std=0.30)
```
Returns:
-------... | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
":",
"vars",
"(",
"self",
")",
"[",
"k",
"]",
"=",
"v"
] | Sets new values to the specified parameters.
Parameters:
-----------
params : variable sized dictionary, n key-word arguments
Example:
```
scaler.set_params(std=0.30)
```
Returns:
--------
void : void, returns nothing | [
"Sets",
"new",
"values",
"to",
"the",
"specified",
"parameters",
".",
"Parameters",
":",
"-----------",
"params",
":",
"variable",
"sized",
"dictionary",
"n",
"key",
"-",
"word",
"arguments",
"Example",
":",
"scaler",
".",
"set_params",
"(",
"std",
"=",
"0",... | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/base/preprocessor.py#L52-L70 | train | Sets new values to the specified parameters. |
shapiromatron/bmds | bmds/parser.py | OutputParser._import_single_searches | def _import_single_searches(self):
"""
Look for simple one-line regex searches common across dataset types.
If failed, then return -999.
AIC is only handled in this method for dichotomous continuous and
exponential and handled via separate methods.
"""
searches ... | python | def _import_single_searches(self):
"""
Look for simple one-line regex searches common across dataset types.
If failed, then return -999.
AIC is only handled in this method for dichotomous continuous and
exponential and handled via separate methods.
"""
searches ... | [
"def",
"_import_single_searches",
"(",
"self",
")",
":",
"searches",
"=",
"{",
"# (?<!Setting ) is a special case for preventing",
"# \"Setting BMD = 100*(maximum dose)\" matches",
"\"BMD\"",
":",
"r\"(?<!Setting )BMD = +(%s)\"",
"%",
"self",
".",
"re_num",
",",
"\"BMDL\"",
"... | Look for simple one-line regex searches common across dataset types.
If failed, then return -999.
AIC is only handled in this method for dichotomous continuous and
exponential and handled via separate methods. | [
"Look",
"for",
"simple",
"one",
"-",
"line",
"regex",
"searches",
"common",
"across",
"dataset",
"types",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/parser.py#L175-L203 | train | Look for simple one - line regex searches common across dataset types. |
shapiromatron/bmds | bmds/parser.py | OutputParser._import_warnings | def _import_warnings(self):
"""
Add custom warnings found in output files.
Warnings in output files are searched for using this method; if a
warning is found then it will be appended to the warnings list.
"""
warnings = (
r"Warning: BMDL computation is at bes... | python | def _import_warnings(self):
"""
Add custom warnings found in output files.
Warnings in output files are searched for using this method; if a
warning is found then it will be appended to the warnings list.
"""
warnings = (
r"Warning: BMDL computation is at bes... | [
"def",
"_import_warnings",
"(",
"self",
")",
":",
"warnings",
"=",
"(",
"r\"Warning: BMDL computation is at best imprecise for these data\"",
",",
"r\"THE MODEL HAS PROBABLY NOT CONVERGED!!!\"",
",",
"\"THIS USUALLY MEANS THE MODEL HAS NOT CONVERGED!\"",
",",
"r\"BMR value is not in th... | Add custom warnings found in output files.
Warnings in output files are searched for using this method; if a
warning is found then it will be appended to the warnings list. | [
"Add",
"custom",
"warnings",
"found",
"in",
"output",
"files",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/parser.py#L205-L226 | train | Imports custom warnings from the output text. |
shapiromatron/bmds | bmds/parser.py | OutputParser._import_dich_vals | def _import_dich_vals(self):
"""
Import simple dichotomous values.
Dichotomous values are found on one line, therefore one regex will
return up to three possible matches for the Chi^2, degrees of freedom,
and p-value.
"""
m = re.search(
r"Chi\^2 = ({0... | python | def _import_dich_vals(self):
"""
Import simple dichotomous values.
Dichotomous values are found on one line, therefore one regex will
return up to three possible matches for the Chi^2, degrees of freedom,
and p-value.
"""
m = re.search(
r"Chi\^2 = ({0... | [
"def",
"_import_dich_vals",
"(",
"self",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\"Chi\\^2 = ({0}|\\w+) +d.f. = +({0}|\\w+) +P-value = +({0}|\\w+)\"",
".",
"format",
"(",
"self",
".",
"re_num",
")",
",",
"# noqa",
"self",
".",
"output_text",
",",
")",
"c... | Import simple dichotomous values.
Dichotomous values are found on one line, therefore one regex will
return up to three possible matches for the Chi^2, degrees of freedom,
and p-value. | [
"Import",
"simple",
"dichotomous",
"values",
"."
] | 395c6ce84ad82876fd9fa4a89a3497fb61616de0 | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/parser.py#L228-L247 | train | Import simple dichotomous values. |
JIC-CSB/jicimagelib | jicimagelib/transform.py | transformation | def transformation(func):
"""Function decorator to turn another function into a transformation."""
@wraps(func)
def func_as_transformation(*args, **kwargs):
# When using transforms that return new ndarrays we lose the
# jicimagelib.image.Image type and the history of the image.
... | python | def transformation(func):
"""Function decorator to turn another function into a transformation."""
@wraps(func)
def func_as_transformation(*args, **kwargs):
# When using transforms that return new ndarrays we lose the
# jicimagelib.image.Image type and the history of the image.
... | [
"def",
"transformation",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_as_transformation",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# When using transforms that return new ndarrays we lose the",
"# jicimagelib.image.Image type and the ... | Function decorator to turn another function into a transformation. | [
"Function",
"decorator",
"to",
"turn",
"another",
"function",
"into",
"a",
"transformation",
"."
] | fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L46-L83 | train | Function decorator to turn another function into a transformation. |
JIC-CSB/jicimagelib | jicimagelib/transform.py | smooth_gaussian | def smooth_gaussian(image, sigma=1):
"""Returns Gaussian smoothed image.
:param image: numpy array or :class:`jicimagelib.image.Image`
:param sigma: standard deviation
:returns: :class:`jicimagelib.image.Image`
"""
return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest") | python | def smooth_gaussian(image, sigma=1):
"""Returns Gaussian smoothed image.
:param image: numpy array or :class:`jicimagelib.image.Image`
:param sigma: standard deviation
:returns: :class:`jicimagelib.image.Image`
"""
return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest") | [
"def",
"smooth_gaussian",
"(",
"image",
",",
"sigma",
"=",
"1",
")",
":",
"return",
"scipy",
".",
"ndimage",
".",
"filters",
".",
"gaussian_filter",
"(",
"image",
",",
"sigma",
"=",
"sigma",
",",
"mode",
"=",
"\"nearest\"",
")"
] | Returns Gaussian smoothed image.
:param image: numpy array or :class:`jicimagelib.image.Image`
:param sigma: standard deviation
:returns: :class:`jicimagelib.image.Image` | [
"Returns",
"Gaussian",
"smoothed",
"image",
"."
] | fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L109-L116 | train | Returns Gaussian smoothed image. |
JIC-CSB/jicimagelib | jicimagelib/transform.py | equalize_adaptive_clahe | def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01):
"""Return contrast limited adaptive histogram equalized image.
The return value is normalised to the range 0 to 1.
:param image: numpy array or :class:`jicimagelib.image.Image` of dtype float
:param ntiles: number of tile regions
:... | python | def equalize_adaptive_clahe(image, ntiles=8, clip_limit=0.01):
"""Return contrast limited adaptive histogram equalized image.
The return value is normalised to the range 0 to 1.
:param image: numpy array or :class:`jicimagelib.image.Image` of dtype float
:param ntiles: number of tile regions
:... | [
"def",
"equalize_adaptive_clahe",
"(",
"image",
",",
"ntiles",
"=",
"8",
",",
"clip_limit",
"=",
"0.01",
")",
":",
"# Convert input for skimage.",
"skimage_float_im",
"=",
"normalise",
"(",
"image",
")",
"if",
"np",
".",
"all",
"(",
"skimage_float_im",
")",
":... | Return contrast limited adaptive histogram equalized image.
The return value is normalised to the range 0 to 1.
:param image: numpy array or :class:`jicimagelib.image.Image` of dtype float
:param ntiles: number of tile regions
:param clip_limit: clipping limit in range 0 to 1,
... | [
"Return",
"contrast",
"limited",
"adaptive",
"histogram",
"equalized",
"image",
".",
"The",
"return",
"value",
"is",
"normalised",
"to",
"the",
"range",
"0",
"to",
"1",
"."
] | fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L120-L142 | train | Return contrast limited adaptive histogram equalized image. |
JIC-CSB/jicimagelib | jicimagelib/transform.py | threshold_otsu | def threshold_otsu(image, multiplier=1.0):
"""Return image thresholded using Otsu's method.
"""
otsu_value = skimage.filters.threshold_otsu(image)
return image > otsu_value * multiplier | python | def threshold_otsu(image, multiplier=1.0):
"""Return image thresholded using Otsu's method.
"""
otsu_value = skimage.filters.threshold_otsu(image)
return image > otsu_value * multiplier | [
"def",
"threshold_otsu",
"(",
"image",
",",
"multiplier",
"=",
"1.0",
")",
":",
"otsu_value",
"=",
"skimage",
".",
"filters",
".",
"threshold_otsu",
"(",
"image",
")",
"return",
"image",
">",
"otsu_value",
"*",
"multiplier"
] | Return image thresholded using Otsu's method. | [
"Return",
"image",
"thresholded",
"using",
"Otsu",
"s",
"method",
"."
] | fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44 | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/transform.py#L146-L150 | train | Return image thresholded using Otsu s method. |
tjcsl/cslbot | cslbot/commands/version.py | cmd | def cmd(send, msg, args):
"""Check the git revison.
Syntax: {command} [check|master]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('action', choices=['check', 'master', 'commit'], nargs='?')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentExce... | python | def cmd(send, msg, args):
"""Check the git revison.
Syntax: {command} [check|master]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('action', choices=['check', 'master', 'commit'], nargs='?')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentExce... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'action'",
",",
"choices",
"=",
"[",
"'check'",
",",
"'master'",
... | Check the git revison.
Syntax: {command} [check|master] | [
"Check",
"the",
"git",
"revison",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/version.py#L25-L56 | train | Check the git revison. |
tjcsl/cslbot | cslbot/commands/next.py | cmd | def cmd(send, _, args):
"""Ships a product.
Syntax: {command}
"""
send("%s! %s" % (args['name'].upper(), random.choice(squirrels))) | python | def cmd(send, _, args):
"""Ships a product.
Syntax: {command}
"""
send("%s! %s" % (args['name'].upper(), random.choice(squirrels))) | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"send",
"(",
"\"%s! %s\"",
"%",
"(",
"args",
"[",
"'name'",
"]",
".",
"upper",
"(",
")",
",",
"random",
".",
"choice",
"(",
"squirrels",
")",
")",
")"
] | Ships a product.
Syntax: {command} | [
"Ships",
"a",
"product",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/next.py#L38-L44 | train | Ships a product.
|
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getAsKmlGrid | def getAsKmlGrid(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', documentName='default', alpha=1.0, noDataValue=0, discreet=False):
"""
Creates a KML file with each cell in the raster represented by a polygon. The result is a vector grid representation of the raster.
... | python | def getAsKmlGrid(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', documentName='default', alpha=1.0, noDataValue=0, discreet=False):
"""
Creates a KML file with each cell in the raster represented by a polygon. The result is a vector grid representation of the raster.
... | [
"def",
"getAsKmlGrid",
"(",
"self",
",",
"tableName",
",",
"rasterId",
"=",
"1",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"documentName",
"=",
"'default'",
",",
"alpha",
"=",
"1.0",
",",
"noDataValue",
"=",
"0",
... | Creates a KML file with each cell in the raster represented by a polygon. The result is a vector grid representation of the raster.
Note that pixels with values between -1 and 0 are omitted as no data values. Also note that this method only works on the first band.
Returns the kml document as a string. | [
"Creates",
"a",
"KML",
"file",
"with",
"each",
"cell",
"in",
"the",
"raster",
"represented",
"by",
"a",
"polygon",
".",
"The",
"result",
"is",
"a",
"vector",
"grid",
"representation",
"of",
"the",
"raster",
".",
"Note",
"that",
"pixels",
"with",
"values",
... | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L49-L179 | train | Returns the KML file representation of the raster in the specified table. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getAsKmlPng | def getAsKmlPng(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', documentName='default',
alpha=1.0, drawOrder=0, noDataValue=0, cellSize=None, resampleMethod='NearestNeighbour', discreet=False):
"""
Creates a KML wrapper and PNG represent of the raster.... | python | def getAsKmlPng(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', documentName='default',
alpha=1.0, drawOrder=0, noDataValue=0, cellSize=None, resampleMethod='NearestNeighbour', discreet=False):
"""
Creates a KML wrapper and PNG represent of the raster.... | [
"def",
"getAsKmlPng",
"(",
"self",
",",
"tableName",
",",
"rasterId",
"=",
"1",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"documentName",
"=",
"'default'",
",",
"alpha",
"=",
"1.0",
",",
"drawOrder",
"=",
"0",
","... | Creates a KML wrapper and PNG represent of the raster. Returns a string of the kml file contents and
a binary string of the PNG contents. The color ramp used to generate the PNG is embedded in the ExtendedData
tag of the GroundOverlay.
IMPORTANT: The PNG image is referenced in the kml as 'raster... | [
"Creates",
"a",
"KML",
"wrapper",
"and",
"PNG",
"represent",
"of",
"the",
"raster",
".",
"Returns",
"a",
"string",
"of",
"the",
"kml",
"file",
"contents",
"and",
"a",
"binary",
"string",
"of",
"the",
"PNG",
"contents",
".",
"The",
"color",
"ramp",
"used"... | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L303-L444 | train | Returns a KML wrapper and PNG representation of the raster. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getAsKmlGridAnimation | def getAsKmlGridAnimation(self, tableName, timeStampedRasters=[], rasterIdFieldName='id', rasterFieldName='raster',
documentName='default', alpha=1.0, noDataValue=0, discreet=False):
"""
Return a sequence of rasters with timestamps as a kml with time markers for animation.... | python | def getAsKmlGridAnimation(self, tableName, timeStampedRasters=[], rasterIdFieldName='id', rasterFieldName='raster',
documentName='default', alpha=1.0, noDataValue=0, discreet=False):
"""
Return a sequence of rasters with timestamps as a kml with time markers for animation.... | [
"def",
"getAsKmlGridAnimation",
"(",
"self",
",",
"tableName",
",",
"timeStampedRasters",
"=",
"[",
"]",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"documentName",
"=",
"'default'",
",",
"alpha",
"=",
"1.0",
",",
"noDa... | Return a sequence of rasters with timestamps as a kml with time markers for animation.
:param tableName: Name of the table to extract rasters from
:param timeStampedRasters: List of dictionaries with keys: rasterId, dateTime
rasterId = a unique integer identifier used to locate the raste... | [
"Return",
"a",
"sequence",
"of",
"rasters",
"with",
"timestamps",
"as",
"a",
"kml",
"with",
"time",
"markers",
"for",
"animation",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L448-L661 | train | Returns a sequence of rasters with timestamps as a kml grid animation. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getAsKmlPngAnimation | def getAsKmlPngAnimation(self, tableName, timeStampedRasters=[], rasterIdFieldName='id', rasterFieldName='raster',
documentName='default', noDataValue=0, alpha=1.0, drawOrder=0, cellSize=None,
resampleMethod='NearestNeighbour', discreet=False):
"""
... | python | def getAsKmlPngAnimation(self, tableName, timeStampedRasters=[], rasterIdFieldName='id', rasterFieldName='raster',
documentName='default', noDataValue=0, alpha=1.0, drawOrder=0, cellSize=None,
resampleMethod='NearestNeighbour', discreet=False):
"""
... | [
"def",
"getAsKmlPngAnimation",
"(",
"self",
",",
"tableName",
",",
"timeStampedRasters",
"=",
"[",
"]",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"documentName",
"=",
"'default'",
",",
"noDataValue",
"=",
"0",
",",
"a... | Return a sequence of rasters with timestamps as a kml with time markers for animation.
:param tableName: Name of the table to extract rasters from
:param timeStampedRasters: List of dictionaries with keys: rasterId, dateTime
rasterId = a unique integer identifier used to locate the raste... | [
"Return",
"a",
"sequence",
"of",
"rasters",
"with",
"timestamps",
"as",
"a",
"kml",
"with",
"time",
"markers",
"for",
"animation",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L665-L869 | train | Returns a sequence of rasters with timestamps as a kml with time markers for animation. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getAsGrassAsciiRaster | def getAsGrassAsciiRaster(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', newSRID=None):
"""
Returns a string representation of the raster in GRASS ASCII raster format.
"""
# Get raster in ArcInfo Grid format
arcInfoGrid = self.getAsGdalRaster(raste... | python | def getAsGrassAsciiRaster(self, tableName, rasterId=1, rasterIdFieldName='id', rasterFieldName='raster', newSRID=None):
"""
Returns a string representation of the raster in GRASS ASCII raster format.
"""
# Get raster in ArcInfo Grid format
arcInfoGrid = self.getAsGdalRaster(raste... | [
"def",
"getAsGrassAsciiRaster",
"(",
"self",
",",
"tableName",
",",
"rasterId",
"=",
"1",
",",
"rasterIdFieldName",
"=",
"'id'",
",",
"rasterFieldName",
"=",
"'raster'",
",",
"newSRID",
"=",
"None",
")",
":",
"# Get raster in ArcInfo Grid format",
"arcInfoGrid",
"... | Returns a string representation of the raster in GRASS ASCII raster format. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"raster",
"in",
"GRASS",
"ASCII",
"raster",
"format",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L871-L930 | train | Returns a string representation of the raster in GRASS ASCII raster format. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getAsGdalRaster | def getAsGdalRaster(self, rasterFieldName, tableName, rasterIdFieldName, rasterId, gdalFormat, newSRID=None, **kwargs):
"""
Returns a string/buffer representation of the raster in the specified format. Wrapper for
ST_AsGDALRaster function in the database.
"""
# Check gdalFormat
... | python | def getAsGdalRaster(self, rasterFieldName, tableName, rasterIdFieldName, rasterId, gdalFormat, newSRID=None, **kwargs):
"""
Returns a string/buffer representation of the raster in the specified format. Wrapper for
ST_AsGDALRaster function in the database.
"""
# Check gdalFormat
... | [
"def",
"getAsGdalRaster",
"(",
"self",
",",
"rasterFieldName",
",",
"tableName",
",",
"rasterIdFieldName",
",",
"rasterId",
",",
"gdalFormat",
",",
"newSRID",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check gdalFormat",
"if",
"not",
"(",
"gdalFormat",... | Returns a string/buffer representation of the raster in the specified format. Wrapper for
ST_AsGDALRaster function in the database. | [
"Returns",
"a",
"string",
"/",
"buffer",
"representation",
"of",
"the",
"raster",
"in",
"the",
"specified",
"format",
".",
"Wrapper",
"for",
"ST_AsGDALRaster",
"function",
"in",
"the",
"database",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L933-L971 | train | Returns a string or buffer representation of the raster in the specified format. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.supportedGdalRasterFormats | def supportedGdalRasterFormats(cls, sqlAlchemyEngineOrSession):
"""
Return a list of the supported GDAL raster formats.
"""
if isinstance(sqlAlchemyEngineOrSession, Engine):
# Create sqlalchemy session
sessionMaker = sessionmaker(bind=sqlAlchemyEngineOrSession)
... | python | def supportedGdalRasterFormats(cls, sqlAlchemyEngineOrSession):
"""
Return a list of the supported GDAL raster formats.
"""
if isinstance(sqlAlchemyEngineOrSession, Engine):
# Create sqlalchemy session
sessionMaker = sessionmaker(bind=sqlAlchemyEngineOrSession)
... | [
"def",
"supportedGdalRasterFormats",
"(",
"cls",
",",
"sqlAlchemyEngineOrSession",
")",
":",
"if",
"isinstance",
"(",
"sqlAlchemyEngineOrSession",
",",
"Engine",
")",
":",
"# Create sqlalchemy session",
"sessionMaker",
"=",
"sessionmaker",
"(",
"bind",
"=",
"sqlAlchemyE... | Return a list of the supported GDAL raster formats. | [
"Return",
"a",
"list",
"of",
"the",
"supported",
"GDAL",
"raster",
"formats",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L974-L995 | train | Return a list of the supported GDAL raster formats. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.setColorRamp | def setColorRamp(self, colorRamp=None):
"""
Set the color ramp of the raster converter instance
"""
if not colorRamp:
self._colorRamp = RasterConverter.setDefaultColorRamp(ColorRampEnum.COLOR_RAMP_HUE)
else:
self._colorRamp = colorRamp | python | def setColorRamp(self, colorRamp=None):
"""
Set the color ramp of the raster converter instance
"""
if not colorRamp:
self._colorRamp = RasterConverter.setDefaultColorRamp(ColorRampEnum.COLOR_RAMP_HUE)
else:
self._colorRamp = colorRamp | [
"def",
"setColorRamp",
"(",
"self",
",",
"colorRamp",
"=",
"None",
")",
":",
"if",
"not",
"colorRamp",
":",
"self",
".",
"_colorRamp",
"=",
"RasterConverter",
".",
"setDefaultColorRamp",
"(",
"ColorRampEnum",
".",
"COLOR_RAMP_HUE",
")",
"else",
":",
"self",
... | Set the color ramp of the raster converter instance | [
"Set",
"the",
"color",
"ramp",
"of",
"the",
"raster",
"converter",
"instance"
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L997-L1004 | train | Sets the color ramp of the raster converter instance. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.setDefaultColorRamp | def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE):
"""
Returns the color ramp as a list of RGB tuples
"""
self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum) | python | def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE):
"""
Returns the color ramp as a list of RGB tuples
"""
self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum) | [
"def",
"setDefaultColorRamp",
"(",
"self",
",",
"colorRampEnum",
"=",
"ColorRampEnum",
".",
"COLOR_RAMP_HUE",
")",
":",
"self",
".",
"_colorRamp",
"=",
"ColorRampGenerator",
".",
"generateDefaultColorRamp",
"(",
"colorRampEnum",
")"
] | Returns the color ramp as a list of RGB tuples | [
"Returns",
"the",
"color",
"ramp",
"as",
"a",
"list",
"of",
"RGB",
"tuples"
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1006-L1010 | train | Sets the default color ramp for this locale. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.setCustomColorRamp | def setCustomColorRamp(self, colors=[], interpolatedPoints=10):
"""
Accepts a list of RGB tuples and interpolates between them to create a custom color ramp.
Returns the color ramp as a list of RGB tuples.
"""
self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, i... | python | def setCustomColorRamp(self, colors=[], interpolatedPoints=10):
"""
Accepts a list of RGB tuples and interpolates between them to create a custom color ramp.
Returns the color ramp as a list of RGB tuples.
"""
self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, i... | [
"def",
"setCustomColorRamp",
"(",
"self",
",",
"colors",
"=",
"[",
"]",
",",
"interpolatedPoints",
"=",
"10",
")",
":",
"self",
".",
"_colorRamp",
"=",
"ColorRampGenerator",
".",
"generateCustomColorRamp",
"(",
"colors",
",",
"interpolatedPoints",
")"
] | Accepts a list of RGB tuples and interpolates between them to create a custom color ramp.
Returns the color ramp as a list of RGB tuples. | [
"Accepts",
"a",
"list",
"of",
"RGB",
"tuples",
"and",
"interpolates",
"between",
"them",
"to",
"create",
"a",
"custom",
"color",
"ramp",
".",
"Returns",
"the",
"color",
"ramp",
"as",
"a",
"list",
"of",
"RGB",
"tuples",
"."
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1012-L1017 | train | Sets the color ramp for this locale. |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.getRastersAsPngs | def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField='raster', rasterIdField='id', cellSize=None, resampleMethod='NearestNeighbour'):
"""
Return the raster in a PNG format
"""
# Validate
VALID_RESAMPLE_METHODS = ('NearestNeighbour', 'Bilinear'... | python | def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField='raster', rasterIdField='id', cellSize=None, resampleMethod='NearestNeighbour'):
"""
Return the raster in a PNG format
"""
# Validate
VALID_RESAMPLE_METHODS = ('NearestNeighbour', 'Bilinear'... | [
"def",
"getRastersAsPngs",
"(",
"self",
",",
"session",
",",
"tableName",
",",
"rasterIds",
",",
"postGisRampString",
",",
"rasterField",
"=",
"'raster'",
",",
"rasterIdField",
"=",
"'id'",
",",
"cellSize",
"=",
"None",
",",
"resampleMethod",
"=",
"'NearestNeigh... | Return the raster in a PNG format | [
"Return",
"the",
"raster",
"in",
"a",
"PNG",
"format"
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1061-L1095 | train | Returns the raster in a PNG format |
CI-WATER/mapkit | mapkit/RasterConverter.py | RasterConverter.isNumber | def isNumber(self, value):
"""
Validate whether a value is a number or not
"""
try:
str(value)
float(value)
return True
except ValueError:
return False | python | def isNumber(self, value):
"""
Validate whether a value is a number or not
"""
try:
str(value)
float(value)
return True
except ValueError:
return False | [
"def",
"isNumber",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"str",
"(",
"value",
")",
"float",
"(",
"value",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | Validate whether a value is a number or not | [
"Validate",
"whether",
"a",
"value",
"is",
"a",
"number",
"or",
"not"
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/RasterConverter.py#L1097-L1107 | train | Validate whether a value is a number or not. |
tjcsl/cslbot | cslbot/helpers/reddit.py | check_exists | def check_exists(subreddit):
"""Make sure that a subreddit actually exists."""
req = get('http://www.reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'})
if req.json().get('kind') == 'Listing':
# no subreddit exists, search results page is shown
return False
ret... | python | def check_exists(subreddit):
"""Make sure that a subreddit actually exists."""
req = get('http://www.reddit.com/r/%s/about.json' % subreddit, headers={'User-Agent': 'CslBot/1.0'})
if req.json().get('kind') == 'Listing':
# no subreddit exists, search results page is shown
return False
ret... | [
"def",
"check_exists",
"(",
"subreddit",
")",
":",
"req",
"=",
"get",
"(",
"'http://www.reddit.com/r/%s/about.json'",
"%",
"subreddit",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'CslBot/1.0'",
"}",
")",
"if",
"req",
".",
"json",
"(",
")",
".",
"get",
... | Make sure that a subreddit actually exists. | [
"Make",
"sure",
"that",
"a",
"subreddit",
"actually",
"exists",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/reddit.py#L25-L31 | train | Make sure that a subreddit actually exists. |
tjcsl/cslbot | cslbot/helpers/reddit.py | random_post | def random_post(subreddit, apikey):
"""Gets a random post from a subreddit and returns a title and shortlink to it."""
subreddit = '/r/random' if subreddit is None else '/r/%s' % subreddit
urlstr = 'http://reddit.com%s/random?%s' % (subreddit, time.time())
url = get(urlstr, headers={'User-Agent': 'CslBo... | python | def random_post(subreddit, apikey):
"""Gets a random post from a subreddit and returns a title and shortlink to it."""
subreddit = '/r/random' if subreddit is None else '/r/%s' % subreddit
urlstr = 'http://reddit.com%s/random?%s' % (subreddit, time.time())
url = get(urlstr, headers={'User-Agent': 'CslBo... | [
"def",
"random_post",
"(",
"subreddit",
",",
"apikey",
")",
":",
"subreddit",
"=",
"'/r/random'",
"if",
"subreddit",
"is",
"None",
"else",
"'/r/%s'",
"%",
"subreddit",
"urlstr",
"=",
"'http://reddit.com%s/random?%s'",
"%",
"(",
"subreddit",
",",
"time",
".",
"... | Gets a random post from a subreddit and returns a title and shortlink to it. | [
"Gets",
"a",
"random",
"post",
"from",
"a",
"subreddit",
"and",
"returns",
"a",
"title",
"and",
"shortlink",
"to",
"it",
"."
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/reddit.py#L34-L39 | train | Gets a random post from a subreddit and returns a title and shortlink to it. |
CI-WATER/mapkit | mapkit/__init__.py | lookupSpatialReferenceID | def lookupSpatialReferenceID(wellKnownText):
"""
This function can be used to look up the EPSG spatial reference system using the web service available at:
http://prj2epsg.org
Args:
wellKnownText (str): The Well Known Text definition of the spatial reference system.
Returns:
int: S... | python | def lookupSpatialReferenceID(wellKnownText):
"""
This function can be used to look up the EPSG spatial reference system using the web service available at:
http://prj2epsg.org
Args:
wellKnownText (str): The Well Known Text definition of the spatial reference system.
Returns:
int: S... | [
"def",
"lookupSpatialReferenceID",
"(",
"wellKnownText",
")",
":",
"payload",
"=",
"{",
"'mode'",
":",
"'wkt'",
",",
"'terms'",
":",
"wellKnownText",
"}",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"'http://prj2epsg.org/search.json'",
",",
"params",
"=... | This function can be used to look up the EPSG spatial reference system using the web service available at:
http://prj2epsg.org
Args:
wellKnownText (str): The Well Known Text definition of the spatial reference system.
Returns:
int: Spatial Reference ID | [
"This",
"function",
"can",
"be",
"used",
"to",
"look",
"up",
"the",
"EPSG",
"spatial",
"reference",
"system",
"using",
"the",
"web",
"service",
"available",
"at",
":",
"http",
":",
"//",
"prj2epsg",
".",
"org"
] | ce5fbded6af7adabdf1eec85631c6811ef8ecc34 | https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/__init__.py#L22-L48 | train | This function is used to automatically determine the spatial reference ID for a given Well Known Text definition of the spatial reference system. |
acutesoftware/virtual-AI-simulator | vais/character.py | read_file | def read_file(fname):
"""
read a CSV file (ref_classes.csv) and return the
list of names
"""
print("NO - dont use this function read_file(fname):")
exit(1)
lst = []
with open(fname, 'r') as f:
#hdr = f.readline()
for line in f:
lst.append(line.strip('\n'))
... | python | def read_file(fname):
"""
read a CSV file (ref_classes.csv) and return the
list of names
"""
print("NO - dont use this function read_file(fname):")
exit(1)
lst = []
with open(fname, 'r') as f:
#hdr = f.readline()
for line in f:
lst.append(line.strip('\n'))
... | [
"def",
"read_file",
"(",
"fname",
")",
":",
"print",
"(",
"\"NO - dont use this function read_file(fname):\"",
")",
"exit",
"(",
"1",
")",
"lst",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"#hdr = f.readline()",
"for",
"l... | read a CSV file (ref_classes.csv) and return the
list of names | [
"read",
"a",
"CSV",
"file",
"(",
"ref_classes",
".",
"csv",
")",
"and",
"return",
"the",
"list",
"of",
"names"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L254-L266 | train | read a CSV file and return the
list of names |
acutesoftware/virtual-AI-simulator | vais/character.py | read_file_1st_col_only | def read_file_1st_col_only(fname):
"""
read a CSV file (ref_classes.csv) and return the
list of names
"""
lst = []
with open(fname, 'r') as f:
_ = f.readline() # read the header and ignore it
for line in f:
lst.append(line.split(',')[0])
return lst | python | def read_file_1st_col_only(fname):
"""
read a CSV file (ref_classes.csv) and return the
list of names
"""
lst = []
with open(fname, 'r') as f:
_ = f.readline() # read the header and ignore it
for line in f:
lst.append(line.split(',')[0])
return lst | [
"def",
"read_file_1st_col_only",
"(",
"fname",
")",
":",
"lst",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"_",
"=",
"f",
".",
"readline",
"(",
")",
"# read the header and ignore it",
"for",
"line",
"in",
"f",
":",
... | read a CSV file (ref_classes.csv) and return the
list of names | [
"read",
"a",
"CSV",
"file",
"(",
"ref_classes",
".",
"csv",
")",
"and",
"return",
"the",
"list",
"of",
"names"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L268-L278 | train | read a CSV file and return the
list of names |
acutesoftware/virtual-AI-simulator | vais/character.py | RefFile.parse_to_dict | def parse_to_dict(self):
"""
parse raw CSV into dictionary
"""
lst = []
with open(self.fname, 'r') as f:
hdr = f.readline()
self.hdrs = hdr.split(',')
#print("self.hdrs = ", self.hdrs)
for line in f:
cols = line.spli... | python | def parse_to_dict(self):
"""
parse raw CSV into dictionary
"""
lst = []
with open(self.fname, 'r') as f:
hdr = f.readline()
self.hdrs = hdr.split(',')
#print("self.hdrs = ", self.hdrs)
for line in f:
cols = line.spli... | [
"def",
"parse_to_dict",
"(",
"self",
")",
":",
"lst",
"=",
"[",
"]",
"with",
"open",
"(",
"self",
".",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"hdr",
"=",
"f",
".",
"readline",
"(",
")",
"self",
".",
"hdrs",
"=",
"hdr",
".",
"split",
"(",
"... | parse raw CSV into dictionary | [
"parse",
"raw",
"CSV",
"into",
"dictionary"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L36-L57 | train | parse raw CSV into dictionary |
acutesoftware/virtual-AI-simulator | vais/character.py | RefFile.get_random_choice | def get_random_choice(self):
"""
returns a random name from the class
"""
i = random.randint(0,len(self.dat)-1)
return self.dat[i]['name'] | python | def get_random_choice(self):
"""
returns a random name from the class
"""
i = random.randint(0,len(self.dat)-1)
return self.dat[i]['name'] | [
"def",
"get_random_choice",
"(",
"self",
")",
":",
"i",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"self",
".",
"dat",
")",
"-",
"1",
")",
"return",
"self",
".",
"dat",
"[",
"i",
"]",
"[",
"'name'",
"]"
] | returns a random name from the class | [
"returns",
"a",
"random",
"name",
"from",
"the",
"class"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L59-L64 | train | returns a random name from the class
|
acutesoftware/virtual-AI-simulator | vais/character.py | CharacterCollection.generate_random_character | def generate_random_character(self):
"""
uses the traits to create a random, but plausible
character. Sample below:
CHARACTER = Amador
Race = Halfling
Class = Priest
STATS = CON = 12, STA = 4, INT = 10, STR = 0, AGI = 5,
St... | python | def generate_random_character(self):
"""
uses the traits to create a random, but plausible
character. Sample below:
CHARACTER = Amador
Race = Halfling
Class = Priest
STATS = CON = 12, STA = 4, INT = 10, STR = 0, AGI = 5,
St... | [
"def",
"generate_random_character",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"create_name",
"(",
")",
"ch_class",
"=",
"self",
".",
"classes",
".",
"get_random_choice",
"(",
")",
"race",
"=",
"self",
".",
"races",
".",
"get_random_choice",
"(",
")"... | uses the traits to create a random, but plausible
character. Sample below:
CHARACTER = Amador
Race = Halfling
Class = Priest
STATS = CON = 12, STA = 4, INT = 10, STR = 0, AGI = 5,
Story = A brave person looking to fight evil in the dar... | [
"uses",
"the",
"traits",
"to",
"create",
"a",
"random",
"but",
"plausible",
"character",
".",
"Sample",
"below",
":",
"CHARACTER",
"=",
"Amador",
"Race",
"=",
"Halfling",
"Class",
"=",
"Priest",
"STATS",
"=",
"CON",
"=",
"12",
"STA",
"=",
"4",
"INT",
"... | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L95-L120 | train | Generate a random character. |
acutesoftware/virtual-AI-simulator | vais/character.py | CharacterCollection.random_stats | def random_stats(self, all_stats, race, ch_class):
"""
create random stats based on the characters class and race
This looks up the tables from CharacterCollection to get
base stats and applies a close random fit
"""
# create blank list of stats to be generated
... | python | def random_stats(self, all_stats, race, ch_class):
"""
create random stats based on the characters class and race
This looks up the tables from CharacterCollection to get
base stats and applies a close random fit
"""
# create blank list of stats to be generated
... | [
"def",
"random_stats",
"(",
"self",
",",
"all_stats",
",",
"race",
",",
"ch_class",
")",
":",
"# create blank list of stats to be generated",
"stats",
"=",
"[",
"]",
"res",
"=",
"{",
"}",
"for",
"s",
"in",
"all_stats",
":",
"stats",
".",
"append",
"(",
"s"... | create random stats based on the characters class and race
This looks up the tables from CharacterCollection to get
base stats and applies a close random fit | [
"create",
"random",
"stats",
"based",
"on",
"the",
"characters",
"class",
"and",
"race",
"This",
"looks",
"up",
"the",
"tables",
"from",
"CharacterCollection",
"to",
"get",
"base",
"stats",
"and",
"applies",
"a",
"close",
"random",
"fit"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L122-L153 | train | create random stats based on the characters class and race |
acutesoftware/virtual-AI-simulator | vais/character.py | Character.load_from_file | def load_from_file(self, fname):
"""
OVERWRITES the current character object from stats in file
"""
with open(fname, 'r') as f:
for line in f:
k,v = line.split(' = ')
self._parse_char_line_to_self(k,v) | python | def load_from_file(self, fname):
"""
OVERWRITES the current character object from stats in file
"""
with open(fname, 'r') as f:
for line in f:
k,v = line.split(' = ')
self._parse_char_line_to_self(k,v) | [
"def",
"load_from_file",
"(",
"self",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"k",
",",
"v",
"=",
"line",
".",
"split",
"(",
"' = '",
")",
"self",
".",
"_parse_char_lin... | OVERWRITES the current character object from stats in file | [
"OVERWRITES",
"the",
"current",
"character",
"object",
"from",
"stats",
"in",
"file"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L189-L196 | train | Loads the current character object from a file. |
acutesoftware/virtual-AI-simulator | vais/character.py | Character._parse_char_line_to_self | def _parse_char_line_to_self(self, k,v):
"""
takes a line from a saved file split into key and values
and updates the appropriate self parameters of character.
"""
k = k.strip(' ').strip('\n')
v = v.strip(' ').strip('\n')
# print('_parse_char_line_to_self(self, k,v... | python | def _parse_char_line_to_self(self, k,v):
"""
takes a line from a saved file split into key and values
and updates the appropriate self parameters of character.
"""
k = k.strip(' ').strip('\n')
v = v.strip(' ').strip('\n')
# print('_parse_char_line_to_self(self, k,v... | [
"def",
"_parse_char_line_to_self",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"k",
"=",
"k",
".",
"strip",
"(",
"' '",
")",
".",
"strip",
"(",
"'\\n'",
")",
"v",
"=",
"v",
".",
"strip",
"(",
"' '",
")",
".",
"strip",
"(",
"'\\n'",
")",
"# print... | takes a line from a saved file split into key and values
and updates the appropriate self parameters of character. | [
"takes",
"a",
"line",
"from",
"a",
"saved",
"file",
"split",
"into",
"key",
"and",
"values",
"and",
"updates",
"the",
"appropriate",
"self",
"parameters",
"of",
"character",
"."
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L198-L219 | train | Parse a single character line into the appropriate self parameters. |
acutesoftware/virtual-AI-simulator | vais/character.py | Character._extract_stats_from_line | def _extract_stats_from_line(self, txt, stats_delim=' ', val_delim=':'):
"""
extracts the stats from a line of text to the class params
STR:7 AGI:9 STA:5 INT:5 Health:21 CON:8 max_health:21
"""
result = {}
stats_txt = txt.split(stats_delim)
for s in stats_txt:
... | python | def _extract_stats_from_line(self, txt, stats_delim=' ', val_delim=':'):
"""
extracts the stats from a line of text to the class params
STR:7 AGI:9 STA:5 INT:5 Health:21 CON:8 max_health:21
"""
result = {}
stats_txt = txt.split(stats_delim)
for s in stats_txt:
... | [
"def",
"_extract_stats_from_line",
"(",
"self",
",",
"txt",
",",
"stats_delim",
"=",
"' '",
",",
"val_delim",
"=",
"':'",
")",
":",
"result",
"=",
"{",
"}",
"stats_txt",
"=",
"txt",
".",
"split",
"(",
"stats_delim",
")",
"for",
"s",
"in",
"stats_txt",
... | extracts the stats from a line of text to the class params
STR:7 AGI:9 STA:5 INT:5 Health:21 CON:8 max_health:21 | [
"extracts",
"the",
"stats",
"from",
"a",
"line",
"of",
"text",
"to",
"the",
"class",
"params",
"STR",
":",
"7",
"AGI",
":",
"9",
"STA",
":",
"5",
"INT",
":",
"5",
"Health",
":",
"21",
"CON",
":",
"8",
"max_health",
":",
"21"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L222-L234 | train | Extracts the stats from a line of text to the class params
|
acutesoftware/virtual-AI-simulator | vais/character.py | Character.save_to_file | def save_to_file(self, fname):
"""
saves a characters data to file
"""
with open(fname, 'w') as f:
f.write(str(self)) | python | def save_to_file(self, fname):
"""
saves a characters data to file
"""
with open(fname, 'w') as f:
f.write(str(self)) | [
"def",
"save_to_file",
"(",
"self",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"self",
")",
")"
] | saves a characters data to file | [
"saves",
"a",
"characters",
"data",
"to",
"file"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/character.py#L236-L241 | train | Saves a character set to file fname |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.