blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e8071aa3a0f4a9adfb5562c4982af2e83406851 | [
"args = self.get_args.parse_args()\nmy_player_id = current_user['player_id']\npg = get_playergroup(group_name, player_id)\nif player_id != my_player_id:\n secret_ok = pg['secret'] == args.get('secret')\n is_service = 'service' in current_user['roles']\n if not secret_ok and (not is_service):\n messa... | <|body_start_0|>
args = self.get_args.parse_args()
my_player_id = current_user['player_id']
pg = get_playergroup(group_name, player_id)
if player_id != my_player_id:
secret_ok = pg['secret'] == args.get('secret')
is_service = 'service' in current_user['roles']
... | Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session). | PlayerGroupsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, player_id, group_name):
"""Returns user iden... | stack_v2_sparse_classes_10k_train_001000 | 4,788 | permissive | [
{
"docstring": "Returns user identities group 'group_name' associated with 'player_id'.",
"name": "get",
"signature": "def get(self, player_id, group_name)"
},
{
"docstring": "Create a player group.",
"name": "put",
"signature": "def put(self, player_id, group_name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005636 | Implement the Python class `PlayerGroupsAPI` described below.
Class description:
Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session).
Method signatures and docstrings:
... | Implement the Python class `PlayerGroupsAPI` described below.
Class description:
Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session).
Method signatures and docstrings:
... | 58439d9398006616bbf438da6c5dbe7c32e7a379 | <|skeleton|>
class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, player_id, group_name):
"""Returns user iden... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlayerGroupsAPI:
"""Manage groups of players. Can be used as friends list and such. The groups are persisted for a period of 48 hours. Client apps should register a new group each time it connects (or initiates a session)."""
def get(self, player_id, group_name):
"""Returns user identities group ... | the_stack_v2_python_sparse | driftbase/players/playergroups/endpoints.py | 1939Games/drift-base | train | 0 |
ee8a32474724df8d9352932bf974c01dd2cd4051 | [
"self.on_cts = on_cts\nself.on_intvl = on_intvl\nself.off_cts = off_cts\nself.off_intvl = off_intvl\nself.cutoff = cutoff\nself.offset = slml_offset(on_cts, on_intvl, off_cts, off_intvl)\nself.p_signal = None",
"try:\n s = float(s)\n llike, nt, err = slmlike(s, self.on_cts, self.on_intvl, self.off_cts, self... | <|body_start_0|>
self.on_cts = on_cts
self.on_intvl = on_intvl
self.off_cts = off_cts
self.off_intvl = off_intvl
self.cutoff = cutoff
self.offset = slml_offset(on_cts, on_intvl, off_cts, off_intvl)
self.p_signal = None
<|end_body_0|>
<|body_start_1|>
try:... | Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior density for the signal rate (sigmp); * ... | OnOff | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnOff:
"""Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior densit... | stack_v2_sparse_classes_10k_train_001001 | 16,279 | no_license | [
{
"docstring": "Initialize an OnOff object. :Parameters: on_cts : int Counts observed on source (source + background) on_intvl: float Interval spanned on source off_cts: int Counts observed off source (background only) off_intvl : float Interval spanned off source :Keywords: cutoff : float Cutoff for truncation... | 4 | stack_v2_sparse_classes_30k_train_006757 | Implement the Python class `OnOff` described below.
Class description:
Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (s... | Implement the Python class `OnOff` described below.
Class description:
Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (s... | 215de4e93b5cf79a1e9f380047b4db92bfeaf45c | <|skeleton|>
class OnOff:
"""Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior densit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OnOff:
"""Model on-source (signal + background) and off-source (background only) event count data with (constant) Poisson counting processes, providing various Bayesian inferences (method names in parens): * The log marginal likelihood for the signal rate (siglml); * The marginal posterior density for the sig... | the_stack_v2_python_sparse | package/inference/count/onoff.py | tloredo/inference | train | 3 |
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9 | [
"if not is_string(name):\n raise TypeError('Instance name must be a string')\nif properties is not None and (not isinstance(properties, dict)):\n raise TypeError('Instance properties must be a dictionary or None')\nname = name.strip()\nif not name:\n raise ValueError(\"Invalid instance name '{0}'\".format(... | <|body_start_0|>
if not is_string(name):
raise TypeError('Instance name must be a string')
if properties is not None and (not isinstance(properties, dict)):
raise TypeError('Instance properties must be a dictionary or None')
name = name.strip()
if not name:
... | Decorator that sets up a future instance of a component | Instantiate | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Instantiate:
"""Decorator that sets up a future instance of a component"""
def __init__(self, name, properties=None):
"""Sets up the decorator :param name: Instance name :param properties: Instance properties"""
<|body_0|>
def __call__(self, factory_class):
"""Se... | stack_v2_sparse_classes_10k_train_001002 | 41,418 | permissive | [
{
"docstring": "Sets up the decorator :param name: Instance name :param properties: Instance properties",
"name": "__init__",
"signature": "def __init__(self, name, properties=None)"
},
{
"docstring": "Sets up and registers the instances descriptions :param factory_class: The factory class to in... | 2 | stack_v2_sparse_classes_30k_train_001057 | Implement the Python class `Instantiate` described below.
Class description:
Decorator that sets up a future instance of a component
Method signatures and docstrings:
- def __init__(self, name, properties=None): Sets up the decorator :param name: Instance name :param properties: Instance properties
- def __call__(sel... | Implement the Python class `Instantiate` described below.
Class description:
Decorator that sets up a future instance of a component
Method signatures and docstrings:
- def __init__(self, name, properties=None): Sets up the decorator :param name: Instance name :param properties: Instance properties
- def __call__(sel... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class Instantiate:
"""Decorator that sets up a future instance of a component"""
def __init__(self, name, properties=None):
"""Sets up the decorator :param name: Instance name :param properties: Instance properties"""
<|body_0|>
def __call__(self, factory_class):
"""Se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Instantiate:
"""Decorator that sets up a future instance of a component"""
def __init__(self, name, properties=None):
"""Sets up the decorator :param name: Instance name :param properties: Instance properties"""
if not is_string(name):
raise TypeError('Instance name must be a ... | the_stack_v2_python_sparse | python/src/lib/python/pelix/ipopo/decorators.py | cohorte/cohorte-runtime | train | 3 |
5240b1723e8848cc18f51f196f9265a821eb5062 | [
"if not issubclass(enum, IntEnum):\n raise TypeError('enum must be an IntEnum subclass')\nself._enum = enum\nif default is None:\n self._default = None\nelif isinstance(default, enum):\n self._default = default\nelif isinstance(default, int):\n self._default = enum(int)\nelse:\n raise TypeError('defa... | <|body_start_0|>
if not issubclass(enum, IntEnum):
raise TypeError('enum must be an IntEnum subclass')
self._enum = enum
if default is None:
self._default = None
elif isinstance(default, enum):
self._default = default
elif isinstance(default, i... | Class to create a dynamic validator for IntEnum classes | IntEnumValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntEnumValidator:
"""Class to create a dynamic validator for IntEnum classes"""
def __init__(self, enum, default=None):
"""Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the... | stack_v2_sparse_classes_10k_train_001003 | 7,524 | permissive | [
{
"docstring": "Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the enum Raises ------ TypeError if enum is not an :py:class:`enum.IntEnum` class TypeError if default parameter is of invalid type",
... | 3 | stack_v2_sparse_classes_30k_train_004601 | Implement the Python class `IntEnumValidator` described below.
Class description:
Class to create a dynamic validator for IntEnum classes
Method signatures and docstrings:
- def __init__(self, enum, default=None): Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:c... | Implement the Python class `IntEnumValidator` described below.
Class description:
Class to create a dynamic validator for IntEnum classes
Method signatures and docstrings:
- def __init__(self, enum, default=None): Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:c... | ab5377e3b16f1920d4d9ada443e1e9059715f0fb | <|skeleton|>
class IntEnumValidator:
"""Class to create a dynamic validator for IntEnum classes"""
def __init__(self, enum, default=None):
"""Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IntEnumValidator:
"""Class to create a dynamic validator for IntEnum classes"""
def __init__(self, enum, default=None):
"""Parameters ---------- enum : :py:class:`enum.IntEnum` base enum class for this validator default : :py:class:`enum.IntEnum` | int | None default attribute of the enum Raises ... | the_stack_v2_python_sparse | PyPoE/shared/config/validator.py | Openarl/PyPoE | train | 16 |
56ba4a33a842cfedb21b752c31b4dfaeeca1e292 | [
"super(DeclarativeNameError, self).__init__(name)\nself.name = name\nself.filename = filename\nself.lineno = lineno\nself.block = block",
"text = '%s\\n\\n' % self.name\ntext += _format_source_error(self.filename, self.lineno, self.block)\ntext += \"\\n\\nNameError: global name '%s' is not defined\" % self.name\n... | <|body_start_0|>
super(DeclarativeNameError, self).__init__(name)
self.name = name
self.filename = filename
self.lineno = lineno
self.block = block
<|end_body_0|>
<|body_start_1|>
text = '%s\n\n' % self.name
text += _format_source_error(self.filename, self.lineno... | A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree. | DeclarativeNameError | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeclarativeNameError:
"""A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree."""
def __init__(self, name, filename, lineno, block):
"""I... | stack_v2_sparse_classes_10k_train_001004 | 4,784 | permissive | [
{
"docstring": "Initialize a DeclarativeNameError. Parameters ---------- name : str The name of global symbol which was not found. filename : str The filename where the lookup failed. lineno : int The line number of the error. block : str The name of the lexical block in which the lookup failed.",
"name": "... | 2 | null | Implement the Python class `DeclarativeNameError` described below.
Class description:
A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree.
Method signatures and docstring... | Implement the Python class `DeclarativeNameError` described below.
Class description:
A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree.
Method signatures and docstring... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class DeclarativeNameError:
"""A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree."""
def __init__(self, name, filename, lineno, block):
"""I... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeclarativeNameError:
"""A NameError subclass which nicely formats the exception. This class is intended for used by Declarative and its subclasses to report errors for failed global lookups when building out the object tree."""
def __init__(self, name, filename, lineno, block):
"""Initialize a D... | the_stack_v2_python_sparse | enaml/core/exceptions.py | enthought/enaml | train | 17 |
0d31caa16c0ca84ee743c74163072377f0aaa348 | [
"enum_values = self._assert_enum_valid(enum)\nif isinstance(enum, EnumMeta):\n self._enum_class = enum\n self._str2enum = dict(zip(enum_values, enum))\nelse:\n self._enum_class = None\n self._str2enum = {v: v for v in enum_values}\nsuper().__init__(type='string', default=default, enum=enum_values, descr... | <|body_start_0|>
enum_values = self._assert_enum_valid(enum)
if isinstance(enum, EnumMeta):
self._enum_class = enum
self._str2enum = dict(zip(enum_values, enum))
else:
self._enum_class = None
self._str2enum = {v: v for v in enum_values}
sup... | Enum parameter parse the value according to its enum values. | EnumInput | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumInput:
"""Enum parameter parse the value according to its enum values."""
def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs):
"""Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum... | stack_v2_sparse_classes_10k_train_001005 | 48,366 | permissive | [
{
"docstring": "Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum: Enum values. :type Union[EnumMeta, Sequence[str]] :param description: Description of the param. :type description: str :param optional: If the param is optional. :type optional: bool :raises ~azure.a... | 4 | stack_v2_sparse_classes_30k_test_000271 | Implement the Python class `EnumInput` described below.
Class description:
Enum parameter parse the value according to its enum values.
Method signatures and docstrings:
- def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs): Initialize an enum parameter, the opti... | Implement the Python class `EnumInput` described below.
Class description:
Enum parameter parse the value according to its enum values.
Method signatures and docstrings:
- def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs): Initialize an enum parameter, the opti... | 1c66defa502b754abcc9e5afa444ca03c609342f | <|skeleton|>
class EnumInput:
"""Enum parameter parse the value according to its enum values."""
def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs):
"""Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EnumInput:
"""Enum parameter parse the value according to its enum values."""
def __init__(self, *, enum: Union[EnumMeta, Sequence[str]]=None, default=None, description=None, **kwargs):
"""Initialize an enum parameter, the options of an enum parameter are the enum values. :param enum: Enum values... | the_stack_v2_python_sparse | sdk/ml/azure-ai-ml/azure/ai/ml/entities/_inputs_outputs.py | gaoyp830/azure-sdk-for-python | train | 0 |
245e26466fbd216eda585cfef1abd3c865c92162 | [
"super(AggregatorMetric, self).__init__(env, realign_fn)\nself.selection_fn = selection_fn\nself.stratify_fn = stratify_fn or (lambda x: 1)\nself.modifier_fn = modifier_fn or (lambda x, y, z: x)\nself.calc_mean = calc_mean",
"sum_aggregate_result = collections.defaultdict(int)\ngroup_count_result = collections.de... | <|body_start_0|>
super(AggregatorMetric, self).__init__(env, realign_fn)
self.selection_fn = selection_fn
self.stratify_fn = stratify_fn or (lambda x: 1)
self.modifier_fn = modifier_fn or (lambda x, y, z: x)
self.calc_mean = calc_mean
<|end_body_0|>
<|body_start_1|>
sum_... | Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate costs for each group, we might have differen... | AggregatorMetric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AggregatorMetric:
"""Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate ... | stack_v2_sparse_classes_10k_train_001006 | 7,087 | permissive | [
{
"docstring": "Initializes the metric. Args: env: A `core.FairnessEnv`. selection_fn: Returns a state variable which needs to be modified and aggregated. stratify_fn: A function that takes a (state, action) pair and returns a stratum-id to collect together pairs. By default (None), all examples are in a single... | 2 | stack_v2_sparse_classes_30k_train_003936 | Implement the Python class `AggregatorMetric` described below.
Class description:
Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based o... | Implement the Python class `AggregatorMetric` described below.
Class description:
Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based o... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class AggregatorMetric:
"""Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AggregatorMetric:
"""Metric that modifies and aggregates an env state variable. This metric can be used to calculate any value that needs to be aggregated in sum or mean over the entire history by applying some modifications to the env state variable based on group-id. For instance, to calculate costs for eac... | the_stack_v2_python_sparse | metrics/value_tracking_metrics.py | google/ml-fairness-gym | train | 310 |
68b3da295bb8e119b85a1856a60d04612e630295 | [
"if x < 0:\n return False\ndigit = 1\nwhile x / digit >= 10:\n digit *= 10\nwhile x != 0:\n left = x / digit\n right = x % 10\n if left != right:\n return False\n x = x % digit / 10\n digit /= 100\nreturn True",
"if x < 0:\n return False\noriginal_x = x\nreversed = 0\nwhile x > 0:\n... | <|body_start_0|>
if x < 0:
return False
digit = 1
while x / digit >= 10:
digit *= 10
while x != 0:
left = x / digit
right = x % 10
if left != right:
return False
x = x % digit / 10
digit /... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome1(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x < 0:
return False
digit = 1
whi... | stack_v2_sparse_classes_10k_train_001007 | 1,275 | no_license | [
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
},
{
"docstring": ":type x: int :rtype: bool",
"name": "isPalindrome1",
"signature": "def isPalindrome1(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005034 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type x: int :rtype: bool
- def isPalindrome1(self, x): :type x: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): :type x: int :rtype: bool
- def isPalindrome1(self, x): :type x: int :rtype: bool
<|skeleton|>
class Solution:
def isPalindrome(self, x):
... | eaeeb9ad2d8cf2a60517cd86f42b30678b5ad2f8 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
<|body_0|>
def isPalindrome1(self, x):
""":type x: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, x):
""":type x: int :rtype: bool"""
if x < 0:
return False
digit = 1
while x / digit >= 10:
digit *= 10
while x != 0:
left = x / digit
right = x % 10
if left != right:
... | the_stack_v2_python_sparse | Python/9. Palindrome Number.py | maiwen/LeetCode | train | 0 | |
4054cc7bb6b26dd8ee148fdd4f6089390f14e197 | [
"self.id = lot_id\nself.city = city\nself.streets = []\nself.parcels = []\nself.sides_of_street = []\nself.house_numbers = []\nself.building = None\nself.landmark = None\nself.positions_in_parcel = []\nself.neighboring_lots = set()\nself.house_number = None\nself.address = None\nself.street_address_is_on = None\nse... | <|body_start_0|>
self.id = lot_id
self.city = city
self.streets = []
self.parcels = []
self.sides_of_street = []
self.house_numbers = []
self.building = None
self.landmark = None
self.positions_in_parcel = []
self.neighboring_lots = set()
... | A lot on a block in a city, upon which buildings and houses get erected. | Lot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
<|body_0|>
def population(self):
"""Return the number of people living/working on the lot."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_001008 | 29,613 | no_license | [
{
"docstring": "Initialize a Lot object.",
"name": "__init__",
"signature": "def __init__(self, lot_id, city)"
},
{
"docstring": "Return the number of people living/working on the lot.",
"name": "population",
"signature": "def population(self)"
},
{
"docstring": "Attribute to thi... | 5 | stack_v2_sparse_classes_30k_train_000906 | Implement the Python class `Lot` described below.
Class description:
A lot on a block in a city, upon which buildings and houses get erected.
Method signatures and docstrings:
- def __init__(self, lot_id, city): Initialize a Lot object.
- def population(self): Return the number of people living/working on the lot.
- ... | Implement the Python class `Lot` described below.
Class description:
A lot on a block in a city, upon which buildings and houses get erected.
Method signatures and docstrings:
- def __init__(self, lot_id, city): Initialize a Lot object.
- def population(self): Return the number of people living/working on the lot.
- ... | 78a9df3ff66d4956f817397c82be0b4e4176e73d | <|skeleton|>
class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
<|body_0|>
def population(self):
"""Return the number of people living/working on the lot."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
self.id = lot_id
self.city = city
self.streets = []
self.parcels = []
self.sides_of_street = []
self... | the_stack_v2_python_sparse | places/city_planning.py | hanok2/national_pastime | train | 1 |
9bb59affcaf8b62f0459e74e07a828cac9e0da3a | [
"try:\n import puremagic\n clazz._log.log_d(f'\"import puremagic\" succeeds')\n return True\nexcept ModuleNotFoundError as ex:\n clazz._log.log_d(f'puremagic module not found')\n pass\nreturn False",
"filename = bf_check.check_file(filename)\nimport puremagic\ntry:\n rv = puremagic.magic_file(fi... | <|body_start_0|>
try:
import puremagic
clazz._log.log_d(f'"import puremagic" succeeds')
return True
except ModuleNotFoundError as ex:
clazz._log.log_d(f'puremagic module not found')
pass
return False
<|end_body_0|>
<|body_start_1|>
... | _bf_mime_type_detector_puremagic | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _bf_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
def _find_mime_type(clazz, ... | stack_v2_sparse_classes_10k_train_001009 | 1,494 | permissive | [
{
"docstring": "Return True if this class is supported on the current platform.",
"name": "is_supported",
"signature": "def is_supported(clazz)"
},
{
"docstring": "Detect the mime type for file.",
"name": "detect_mime_type",
"signature": "def detect_mime_type(clazz, filename)"
},
{
... | 3 | null | Implement the Python class `_bf_mime_type_detector_puremagic` described below.
Class description:
Implement the _bf_mime_type_detector_puremagic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filename): ... | Implement the Python class `_bf_mime_type_detector_puremagic` described below.
Class description:
Implement the _bf_mime_type_detector_puremagic class.
Method signatures and docstrings:
- def is_supported(clazz): Return True if this class is supported on the current platform.
- def detect_mime_type(clazz, filename): ... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class _bf_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
<|body_0|>
def detect_mime_type(clazz, filename):
"""Detect the mime type for file."""
<|body_1|>
def _find_mime_type(clazz, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _bf_mime_type_detector_puremagic:
def is_supported(clazz):
"""Return True if this class is supported on the current platform."""
try:
import puremagic
clazz._log.log_d(f'"import puremagic" succeeds')
return True
except ModuleNotFoundError as ex:
... | the_stack_v2_python_sparse | lib/bes/files/mime/_detail/_bf_mime_type_detector_puremagic.py | reconstruir/bes | train | 0 | |
be7c9168e4b071e94b6fb08daccdc01aa0c1e913 | [
"responce_map = {QUESTION: 'Sure.', ALLCAPS: 'Woah, chill out!', EMPTY: 'Fine. Be that way!', OTHER: 'Whatever.'}\nif message:\n message = message.strip()\nmessage_type = self.define_message_type(message)\nreturn responce_map[message_type]",
"if not message:\n return EMPTY\nelif message.isupper():\n retu... | <|body_start_0|>
responce_map = {QUESTION: 'Sure.', ALLCAPS: 'Woah, chill out!', EMPTY: 'Fine. Be that way!', OTHER: 'Whatever.'}
if message:
message = message.strip()
message_type = self.define_message_type(message)
return responce_map[message_type]
<|end_body_0|>
<|body_st... | Lackadaisical teenager that responds in some special way to your messages | Bob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bob:
"""Lackadaisical teenager that responds in some special way to your messages"""
def hey(self, message):
"""Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob"""
<|body_0|>
def define_message_type(sel... | stack_v2_sparse_classes_10k_train_001010 | 1,205 | no_license | [
{
"docstring": "Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob",
"name": "hey",
"signature": "def hey(self, message)"
},
{
"docstring": "Determine the type of the inbound message @param message: string that represents an inbo... | 2 | stack_v2_sparse_classes_30k_train_004395 | Implement the Python class `Bob` described below.
Class description:
Lackadaisical teenager that responds in some special way to your messages
Method signatures and docstrings:
- def hey(self, message): Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from B... | Implement the Python class `Bob` described below.
Class description:
Lackadaisical teenager that responds in some special way to your messages
Method signatures and docstrings:
- def hey(self, message): Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from B... | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | <|skeleton|>
class Bob:
"""Lackadaisical teenager that responds in some special way to your messages"""
def hey(self, message):
"""Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob"""
<|body_0|>
def define_message_type(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Bob:
"""Lackadaisical teenager that responds in some special way to your messages"""
def hey(self, message):
"""Send Bob a message @param message: string that represents an inbound message to Bob @return: responce string from Bob"""
responce_map = {QUESTION: 'Sure.', ALLCAPS: 'Woah, chill... | the_stack_v2_python_sparse | all_data/exercism_data/python/bob/400e65344f394a858eff065f563709b4.py | itsolutionscorp/AutoStyle-Clustering | train | 4 |
7de23b2baccf5e1f72ac1eb281f8ddd37e00a085 | [
"self.info('Starting tckgen creation from mrtrix on {}'.format(source))\ntmp = os.path.join(self.workingDir, 'tmp_{}.tck'.format(algorithm))\ncmd = 'tckgen {} {} -mask {} -act {} -seed_gmwmi {} -number {} -algorithm {} -nthreads {} -quiet'.format(source, tmp, mask, act, seed_gmwmi, self.get('number_tracks'), algor... | <|body_start_0|>
self.info('Starting tckgen creation from mrtrix on {}'.format(source))
tmp = os.path.join(self.workingDir, 'tmp_{}.tck'.format(algorithm))
cmd = 'tckgen {} {} -mask {} -act {} -seed_gmwmi {} -number {} -algorithm {} -nthreads {} -quiet'.format(source, tmp, mask, act, seed_gmwmi... | Tractography | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of vol... | stack_v2_sparse_classes_10k_train_001011 | 3,574 | no_license | [
{
"docstring": "perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of volumes is the X,Y,Z direction of a fibre population). - iFOD1/2 & SD_Stream: the SH image resulting from CSD. - Nulldist & SeedTes... | 3 | stack_v2_sparse_classes_30k_val_000380 | Implement the Python class `Tractography` described below.
Class description:
Implement the Tractography class.
Method signatures and docstrings:
- def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'): perform streamlines tractography. the image containing the source d... | Implement the Python class `Tractography` described below.
Class description:
Implement the Tractography class.
Method signatures and docstrings:
- def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'): perform streamlines tractography. the image containing the source d... | 99682e1a03d56bac0e078bc816d0394fe1147a1a | <|skeleton|>
class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of vol... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of volumes is the X,... | the_stack_v2_python_sparse | lib/tractography.py | alexhng/toad | train | 0 | |
ef4443389b0ca479f2db1d12f9db33545e9b5abf | [
"self.name = name\nself.sound = sound\nself.num_legs = num_legs",
"if self.sound is None and sound is None:\n raise NotImplementedError('Silent Animals are not supported!')\nout_sound = self.sound if sound is None else sound\nprint(self.says_str.format(name=self.name, sound=out_sound))"
] | <|body_start_0|>
self.name = name
self.sound = sound
self.num_legs = num_legs
<|end_body_0|>
<|body_start_1|>
if self.sound is None and sound is None:
raise NotImplementedError('Silent Animals are not supported!')
out_sound = self.sound if sound is None else sound
... | A class used to represent an Animal ... Attributes ---------- says_str : str a formatted string to print out what the animal says name : str the name of the animal sound : str the sound that the animal makes num_legs : int the number of legs the animal has (default 4) Methods ------- says(sound=None) Prints the animals... | Animal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Animal:
"""A class used to represent an Animal ... Attributes ---------- says_str : str a formatted string to print out what the animal says name : str the name of the animal sound : str the sound that the animal makes num_legs : int the number of legs the animal has (default 4) Methods ------- s... | stack_v2_sparse_classes_10k_train_001012 | 7,007 | no_license | [
{
"docstring": "Parameters ---------- name : str The name of the animal sound : str The sound the animal makes num_legs : int, optional The number of legs the animal (default is 4)",
"name": "__init__",
"signature": "def __init__(self, name, sound, num_legs)"
},
{
"docstring": "Prints what the a... | 2 | stack_v2_sparse_classes_30k_train_004058 | Implement the Python class `Animal` described below.
Class description:
A class used to represent an Animal ... Attributes ---------- says_str : str a formatted string to print out what the animal says name : str the name of the animal sound : str the sound that the animal makes num_legs : int the number of legs the a... | Implement the Python class `Animal` described below.
Class description:
A class used to represent an Animal ... Attributes ---------- says_str : str a formatted string to print out what the animal says name : str the name of the animal sound : str the sound that the animal makes num_legs : int the number of legs the a... | df4d9b85eeff4e14c91533135a347b59d52812c7 | <|skeleton|>
class Animal:
"""A class used to represent an Animal ... Attributes ---------- says_str : str a formatted string to print out what the animal says name : str the name of the animal sound : str the sound that the animal makes num_legs : int the number of legs the animal has (default 4) Methods ------- s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Animal:
"""A class used to represent an Animal ... Attributes ---------- says_str : str a formatted string to print out what the animal says name : str the name of the animal sound : str the sound that the animal makes num_legs : int the number of legs the animal has (default 4) Methods ------- says(sound=Non... | the_stack_v2_python_sparse | useful_stuff/documenting_code_explanation.py | Ze1598/Python_stuff | train | 0 |
74563a465b1f898f74de2646b95669f63f3f05d0 | [
"self._config_address = '0x0000000000000000000000000000000000001000'\nself.gasPrice = 300000000\nself.client = transaction_common.TransactionCommon(self._config_address, contract_path, 'SystemConfig')",
"fn_name = 'setValueByKey'\nfn_args = [key, value]\nreturn self.client.send_transaction_getReceipt(fn_name, fn_... | <|body_start_0|>
self._config_address = '0x0000000000000000000000000000000000001000'
self.gasPrice = 300000000
self.client = transaction_common.TransactionCommon(self._config_address, contract_path, 'SystemConfig')
<|end_body_0|>
<|body_start_1|>
fn_name = 'setValueByKey'
fn_arg... | implementation of ConfigPrecompile | ConfigPrecompile | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigPrecompile:
"""implementation of ConfigPrecompile"""
def __init__(self, contract_path):
"""init the address for SystemConfig contract"""
<|body_0|>
def setValueByKey(self, key, value):
"""set value for the givn key"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_001013 | 1,461 | permissive | [
{
"docstring": "init the address for SystemConfig contract",
"name": "__init__",
"signature": "def __init__(self, contract_path)"
},
{
"docstring": "set value for the givn key",
"name": "setValueByKey",
"signature": "def setValueByKey(self, key, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004799 | Implement the Python class `ConfigPrecompile` described below.
Class description:
implementation of ConfigPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for SystemConfig contract
- def setValueByKey(self, key, value): set value for the givn key | Implement the Python class `ConfigPrecompile` described below.
Class description:
implementation of ConfigPrecompile
Method signatures and docstrings:
- def __init__(self, contract_path): init the address for SystemConfig contract
- def setValueByKey(self, key, value): set value for the givn key
<|skeleton|>
class C... | 5fa6cc416b604de4bbd0d2407f36ed286d67a792 | <|skeleton|>
class ConfigPrecompile:
"""implementation of ConfigPrecompile"""
def __init__(self, contract_path):
"""init the address for SystemConfig contract"""
<|body_0|>
def setValueByKey(self, key, value):
"""set value for the givn key"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigPrecompile:
"""implementation of ConfigPrecompile"""
def __init__(self, contract_path):
"""init the address for SystemConfig contract"""
self._config_address = '0x0000000000000000000000000000000000001000'
self.gasPrice = 300000000
self.client = transaction_common.Tra... | the_stack_v2_python_sparse | client/precompile/config/config_precompile.py | FISCO-BCOS/python-sdk | train | 68 |
8f67d59da3bc32ceb80cb28e394e6aca85cb7f3c | [
"args = [Arping.ARPING_COMMAND_NAME, Arping.INTERFACE_OPTION, device, Arping.COUNT_OPTION, str(count), Arping.TIMEOUT_OPTION, str(timeout)]\nif quiet is True:\n args.append(Arping.QUIET_OPTION)\nif firstReply is True:\n args.append(Arping.FIRST_REPLY_OPTION)\nargs.append(destination)\nrc = Command.execute(log... | <|body_start_0|>
args = [Arping.ARPING_COMMAND_NAME, Arping.INTERFACE_OPTION, device, Arping.COUNT_OPTION, str(count), Arping.TIMEOUT_OPTION, str(timeout)]
if quiet is True:
args.append(Arping.QUIET_OPTION)
if firstReply is True:
args.append(Arping.FIRST_REPLY_OPTION)
... | Arping | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Arping:
def sendArpRequest(logger, device, destination, count=3, timeout=1, quiet=False, firstReply=False, blocking=True):
"""This function sends ARP REQUEST to a neighbour host Args: logger device - Name of network device where to send ARP REQUEST packets destination - destination IP to... | stack_v2_sparse_classes_10k_train_001014 | 10,343 | no_license | [
{
"docstring": "This function sends ARP REQUEST to a neighbour host Args: logger device - Name of network device where to send ARP REQUEST packets destination - destination IP to ping count - stop after sending X ARP REQUEST packets timeout - specify a timeout, in seconds, before arping exits quiet - quiet outp... | 2 | stack_v2_sparse_classes_30k_train_006834 | Implement the Python class `Arping` described below.
Class description:
Implement the Arping class.
Method signatures and docstrings:
- def sendArpRequest(logger, device, destination, count=3, timeout=1, quiet=False, firstReply=False, blocking=True): This function sends ARP REQUEST to a neighbour host Args: logger de... | Implement the Python class `Arping` described below.
Class description:
Implement the Arping class.
Method signatures and docstrings:
- def sendArpRequest(logger, device, destination, count=3, timeout=1, quiet=False, firstReply=False, blocking=True): This function sends ARP REQUEST to a neighbour host Args: logger de... | 81bcc74fe7c0ca036ec483f634d7be0bab19a6d0 | <|skeleton|>
class Arping:
def sendArpRequest(logger, device, destination, count=3, timeout=1, quiet=False, firstReply=False, blocking=True):
"""This function sends ARP REQUEST to a neighbour host Args: logger device - Name of network device where to send ARP REQUEST packets destination - destination IP to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Arping:
def sendArpRequest(logger, device, destination, count=3, timeout=1, quiet=False, firstReply=False, blocking=True):
"""This function sends ARP REQUEST to a neighbour host Args: logger device - Name of network device where to send ARP REQUEST packets destination - destination IP to ping count - ... | the_stack_v2_python_sparse | oscar/a/sys/net/lnx/neighbour.py | afeset/miner2-tools | train | 0 | |
81a0a6eb752781e8d106a305f2cacf0886660a8f | [
"attr = getattr(cls, name)\nif _.is_list(attr):\n return util.create_validator(lengths=attr, required=required)\nelif _.is_string(attr):\n return util.create_validator(regex=attr, required=required)\nelif _.is_function(attr):\n return attr",
"result = {}\nfor attr_name in _.reject(set(dir(cls)), lambda x... | <|body_start_0|>
attr = getattr(cls, name)
if _.is_list(attr):
return util.create_validator(lengths=attr, required=required)
elif _.is_string(attr):
return util.create_validator(regex=attr, required=required)
elif _.is_function(attr):
return attr
<|end... | Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be validated agains string function - validation... | BaseValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseValidator:
"""Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be vali... | stack_v2_sparse_classes_10k_train_001015 | 10,196 | permissive | [
{
"docstring": "Creates validation function from given attribute name Args: name (string): Name of attribute required (bool, optional) If false, empty string will be always accepted as valid Returns: function: validation function",
"name": "create",
"signature": "def create(cls, name, required=True)"
... | 2 | stack_v2_sparse_classes_30k_train_001919 | Implement the Python class `BaseValidator` described below.
Class description:
Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max leng... | Implement the Python class `BaseValidator` described below.
Class description:
Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max leng... | a82de1321abab504a0be85497587fa90d75fa62d | <|skeleton|>
class BaseValidator:
"""Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be vali... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseValidator:
"""Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be validated agains ... | the_stack_v2_python_sparse | main/model/base.py | jajberni/pcse_web | train | 3 |
5f7486ea44e0fdc3586570fe9e60b7dfff53a45f | [
"page = BaiduSearchPage(browser)\npage.search_input('pytest')\npage.search_button()\npage.sleep(1)\ntitle = page.search_title()\nassert title == 'pytest_百度搜索'",
"page = BaiduSearchPage(browser)\npage.search_input(search_key)\npage.search_button()\npage.sleep(2)\ntitle = page.search_title()\nassert title == search... | <|body_start_0|>
page = BaiduSearchPage(browser)
page.search_input('pytest')
page.search_button()
page.sleep(1)
title = page.search_title()
assert title == 'pytest_百度搜索'
<|end_body_0|>
<|body_start_1|>
page = BaiduSearchPage(browser)
page.search_input(sea... | TestSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSearch:
def test_baidu_search_case(self, browser):
"""百度搜索:pytest"""
<|body_0|>
def test_baidu_search(self, name, search_key, browser):
"""百度搜索 --参数化"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
page = BaiduSearchPage(browser)
page.se... | stack_v2_sparse_classes_10k_train_001016 | 1,494 | no_license | [
{
"docstring": "百度搜索:pytest",
"name": "test_baidu_search_case",
"signature": "def test_baidu_search_case(self, browser)"
},
{
"docstring": "百度搜索 --参数化",
"name": "test_baidu_search",
"signature": "def test_baidu_search(self, name, search_key, browser)"
}
] | 2 | null | Implement the Python class `TestSearch` described below.
Class description:
Implement the TestSearch class.
Method signatures and docstrings:
- def test_baidu_search_case(self, browser): 百度搜索:pytest
- def test_baidu_search(self, name, search_key, browser): 百度搜索 --参数化 | Implement the Python class `TestSearch` described below.
Class description:
Implement the TestSearch class.
Method signatures and docstrings:
- def test_baidu_search_case(self, browser): 百度搜索:pytest
- def test_baidu_search(self, name, search_key, browser): 百度搜索 --参数化
<|skeleton|>
class TestSearch:
def test_baid... | b3a532d33ddeb8d01fff315bcd59b451befdef23 | <|skeleton|>
class TestSearch:
def test_baidu_search_case(self, browser):
"""百度搜索:pytest"""
<|body_0|>
def test_baidu_search(self, name, search_key, browser):
"""百度搜索 --参数化"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSearch:
def test_baidu_search_case(self, browser):
"""百度搜索:pytest"""
page = BaiduSearchPage(browser)
page.search_input('pytest')
page.search_button()
page.sleep(1)
title = page.search_title()
assert title == 'pytest_百度搜索'
def test_baidu_search(s... | the_stack_v2_python_sparse | pyautoTest-master(ICF-7.5.0)/test_case/1test_baidu_search.py | lizhuoya1111/Automated_testing_practice | train | 0 | |
8bba0c546967d0c444c5bb7d6a6a8b5a78bc0df4 | [
"if description is None:\n description = ''\ndescription = ASCII_LOGO + '\\n' + description.lstrip(' ')\nsuper().__init__(usage=usage, description=description, formatter_class=argparse.RawTextHelpFormatter)",
"remaining = Options(*args)\nfor argument, options in copy.deepcopy(self.standard_arguments).items():\... | <|body_start_0|>
if description is None:
description = ''
description = ASCII_LOGO + '\n' + description.lstrip(' ')
super().__init__(usage=usage, description=description, formatter_class=argparse.RawTextHelpFormatter)
<|end_body_0|>
<|body_start_1|>
remaining = Options(*args... | Class for parsing command-line arguments. | ArgumentParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentParser:
"""Class for parsing command-line arguments."""
def __init__(self, usage: Optional[str]=None, description: Optional[str]=None):
"""Construct `ArgumentParser`."""
<|body_0|>
def with_standard_arguments(self, *args: Union[str, Tuple[str, Any]]) -> 'Argument... | stack_v2_sparse_classes_10k_train_001017 | 4,796 | permissive | [
{
"docstring": "Construct `ArgumentParser`.",
"name": "__init__",
"signature": "def __init__(self, usage: Optional[str]=None, description: Optional[str]=None)"
},
{
"docstring": "Add standard, named arguments to the `ArgumentParser`. Standard argument is given, but can be overwritten as a tuple.... | 2 | stack_v2_sparse_classes_30k_train_005560 | Implement the Python class `ArgumentParser` described below.
Class description:
Class for parsing command-line arguments.
Method signatures and docstrings:
- def __init__(self, usage: Optional[str]=None, description: Optional[str]=None): Construct `ArgumentParser`.
- def with_standard_arguments(self, *args: Union[str... | Implement the Python class `ArgumentParser` described below.
Class description:
Class for parsing command-line arguments.
Method signatures and docstrings:
- def __init__(self, usage: Optional[str]=None, description: Optional[str]=None): Construct `ArgumentParser`.
- def with_standard_arguments(self, *args: Union[str... | f6e03282dd665c81d06eaa1ab55a07d138064e9a | <|skeleton|>
class ArgumentParser:
"""Class for parsing command-line arguments."""
def __init__(self, usage: Optional[str]=None, description: Optional[str]=None):
"""Construct `ArgumentParser`."""
<|body_0|>
def with_standard_arguments(self, *args: Union[str, Tuple[str, Any]]) -> 'Argument... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArgumentParser:
"""Class for parsing command-line arguments."""
def __init__(self, usage: Optional[str]=None, description: Optional[str]=None):
"""Construct `ArgumentParser`."""
if description is None:
description = ''
description = ASCII_LOGO + '\n' + description.lstr... | the_stack_v2_python_sparse | src/graphnet/utilities/argparse.py | graphnet-team/graphnet | train | 55 |
e2d1f7a76edb600bf93a166787ffac9c9290cb3e | [
"self.rolenames = rn = {}\nself.roleids = ri = {}\nfor n, f in enumerate(fieldlist):\n rid = n + 100\n rn[rid] = f\n ri[f] = rid\nself.model = mo = QtGui.QStandardItemModel()\ntry:\n mo.setRoleNames(rn)\nexcept AttributeError:\n pass",
"si = QtGui.QStandardItem()\nfor k, v in d.items():\n rid = ... | <|body_start_0|>
self.rolenames = rn = {}
self.roleids = ri = {}
for n, f in enumerate(fieldlist):
rid = n + 100
rn[rid] = f
ri[f] = rid
self.model = mo = QtGui.QStandardItemModel()
try:
mo.setRoleNames(rn)
except AttributeE... | ModelWrapper | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelWrapper:
def __init__(self, fieldlist):
"""Ctor for ModelWrapper class."""
<|body_0|>
def mkitem(self, d):
"""dict with field->value"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rolenames = rn = {}
self.roleids = ri = {}
... | stack_v2_sparse_classes_10k_train_001018 | 4,067 | permissive | [
{
"docstring": "Ctor for ModelWrapper class.",
"name": "__init__",
"signature": "def __init__(self, fieldlist)"
},
{
"docstring": "dict with field->value",
"name": "mkitem",
"signature": "def mkitem(self, d)"
}
] | 2 | null | Implement the Python class `ModelWrapper` described below.
Class description:
Implement the ModelWrapper class.
Method signatures and docstrings:
- def __init__(self, fieldlist): Ctor for ModelWrapper class.
- def mkitem(self, d): dict with field->value | Implement the Python class `ModelWrapper` described below.
Class description:
Implement the ModelWrapper class.
Method signatures and docstrings:
- def __init__(self, fieldlist): Ctor for ModelWrapper class.
- def mkitem(self, d): dict with field->value
<|skeleton|>
class ModelWrapper:
def __init__(self, fieldl... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class ModelWrapper:
def __init__(self, fieldlist):
"""Ctor for ModelWrapper class."""
<|body_0|>
def mkitem(self, d):
"""dict with field->value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelWrapper:
def __init__(self, fieldlist):
"""Ctor for ModelWrapper class."""
self.rolenames = rn = {}
self.roleids = ri = {}
for n, f in enumerate(fieldlist):
rid = n + 100
rn[rid] = f
ri[f] = rid
self.model = mo = QtGui.QStandardI... | the_stack_v2_python_sparse | leo/plugins/notebook.py | leo-editor/leo-editor | train | 1,671 | |
1fbf9655e435ec55555a8b1d9afd1e68cb1ecdf9 | [
"num = len(temperatures)\nre = [0] * num\nfor i in range(0, num):\n day = 0\n for j in range(i + 1, num):\n if temperatures[i] < temperatures[j]:\n day = j - i\n break\n re[i] = day\nreturn re",
"num = len(temperatures)\nre = [0] * num\nstack = [0]\nfor i in range(1, num):\n ... | <|body_start_0|>
num = len(temperatures)
re = [0] * num
for i in range(0, num):
day = 0
for j in range(i + 1, num):
if temperatures[i] < temperatures[j]:
day = j - i
break
re[i] = day
return re
<|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_10k_train_001019 | 1,058 | no_license | [
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures1",
"signature": "def dailyTemperatures1(self, temperatures)"
},
{
"docstring": ":type temperatures: List[int] :rtype: List[int]",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(... | 2 | stack_v2_sparse_classes_30k_train_000469 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures1(self, temperatures): :type temperatures: List[int] :rtype: List[int]
- def dailyTemperatures(self, temperatures): :type temperatures: List[int] :rtype: Lis... | 8cde0af5a9de3f01e71093e5cdbe58908db16c69 | <|skeleton|>
class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_0|>
def dailyTemperatures(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures1(self, temperatures):
""":type temperatures: List[int] :rtype: List[int]"""
num = len(temperatures)
re = [0] * num
for i in range(0, num):
day = 0
for j in range(i + 1, num):
if temperatures[i] < temperatur... | the_stack_v2_python_sparse | test_739.py | huangbenyu/leetcode | train | 0 | |
0d81fc9b6e18818183d352510202b9634a78a5b0 | [
"developer = Developer.query.filter_by(id=id).first()\nif developer is None:\n return ({'message': 'Developer does not exist'}, 404)\nreturn developer_schema.dump(developer)",
"req = api.payload\ndeveloper = Developer.query.filter_by(id=id).first()\nif developer is None:\n return ({'message': 'Developer doe... | <|body_start_0|>
developer = Developer.query.filter_by(id=id).first()
if developer is None:
return ({'message': 'Developer does not exist'}, 404)
return developer_schema.dump(developer)
<|end_body_0|>
<|body_start_1|>
req = api.payload
developer = Developer.query.fil... | SingleDeveloper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleDeveloper:
def get(self, id):
"""Get Developer by id"""
<|body_0|>
def put(self, id):
"""Update a Developer"""
<|body_1|>
def delete(self, id):
"""Delete a Developer by id"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
de... | stack_v2_sparse_classes_10k_train_001020 | 3,376 | no_license | [
{
"docstring": "Get Developer by id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update a Developer",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Delete a Developer by id",
"name": "delete",
"signature": "def delete(self, id)... | 3 | stack_v2_sparse_classes_30k_train_006409 | Implement the Python class `SingleDeveloper` described below.
Class description:
Implement the SingleDeveloper class.
Method signatures and docstrings:
- def get(self, id): Get Developer by id
- def put(self, id): Update a Developer
- def delete(self, id): Delete a Developer by id | Implement the Python class `SingleDeveloper` described below.
Class description:
Implement the SingleDeveloper class.
Method signatures and docstrings:
- def get(self, id): Get Developer by id
- def put(self, id): Update a Developer
- def delete(self, id): Delete a Developer by id
<|skeleton|>
class SingleDeveloper:... | ae78fff9888b0f68d9403d7f65cba086dabb3802 | <|skeleton|>
class SingleDeveloper:
def get(self, id):
"""Get Developer by id"""
<|body_0|>
def put(self, id):
"""Update a Developer"""
<|body_1|>
def delete(self, id):
"""Delete a Developer by id"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SingleDeveloper:
def get(self, id):
"""Get Developer by id"""
developer = Developer.query.filter_by(id=id).first()
if developer is None:
return ({'message': 'Developer does not exist'}, 404)
return developer_schema.dump(developer)
def put(self, id):
"""... | the_stack_v2_python_sparse | api/v1/developers.py | mythril-io/flask-api | train | 0 | |
c4144cf04301498932689276bc72f74e97b9f3ff | [
"self._schema = customer_schema\nself._provider = provider\nself._months_to_keep = num_of_months_to_keep\nif self._months_to_keep is None:\n self._months_to_keep = Config.MASU_RETAIN_NUM_MONTHS\nself._line_items_months = line_items_month_to_keep\nif self._line_items_months is None:\n self._line_items_months =... | <|body_start_0|>
self._schema = customer_schema
self._provider = provider
self._months_to_keep = num_of_months_to_keep
if self._months_to_keep is None:
self._months_to_keep = Config.MASU_RETAIN_NUM_MONTHS
self._line_items_months = line_items_month_to_keep
if s... | Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable. | ExpiredDataRemover | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExpiredDataRemover:
"""Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable."""
def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None):
"""Initializer. Args: custome... | stack_v2_sparse_classes_10k_train_001021 | 5,846 | permissive | [
{
"docstring": "Initializer. Args: customer_schema (String): Schema name for given customer. num_of_months_to_keep (Int): Number of months to retain in database.",
"name": "__init__",
"signature": "def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None)"
... | 4 | null | Implement the Python class `ExpiredDataRemover` described below.
Class description:
Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable.
Method signatures and docstrings:
- def __init__(self, customer_schema, provider, num_of_months_to_keep=None, l... | Implement the Python class `ExpiredDataRemover` described below.
Class description:
Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable.
Method signatures and docstrings:
- def __init__(self, customer_schema, provider, num_of_months_to_keep=None, l... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class ExpiredDataRemover:
"""Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable."""
def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None):
"""Initializer. Args: custome... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExpiredDataRemover:
"""Removes expired report data based on masu's retention policy. Retention policy can be configured via environment variable."""
def __init__(self, customer_schema, provider, num_of_months_to_keep=None, line_items_month_to_keep=None):
"""Initializer. Args: customer_schema (Str... | the_stack_v2_python_sparse | koku/masu/processor/expired_data_remover.py | project-koku/koku | train | 225 |
a3e6239e79ebc51dafdec0c46d45694f54554dbf | [
"super(TextFileStream, self).__init__(*path)\nfrom flume.proto import entity_pb2\npb = entity_pb2.PbInputFormatEntityConfig()\npb.repeatedly = True\npb.max_record_num_per_round = options.get('max_record_num_per_round', 1000)\npb.timeout_per_round = options.get('timeout_per_round', 30)\npb.file_stream.filename_patte... | <|body_start_0|>
super(TextFileStream, self).__init__(*path)
from flume.proto import entity_pb2
pb = entity_pb2.PbInputFormatEntityConfig()
pb.repeatedly = True
pb.max_record_num_per_round = options.get('max_record_num_per_round', 1000)
pb.timeout_per_round = options.get(... | 表示读取的文本文件的无穷数据源。 Args: *path: 读取文件目录的path,必须均为str类型 读取文件数据示例::: >>> lines1 = _pipeline.read(input.TextFileStream('hdfs:///my_hdfs_dir/')) >>> lines2 = _pipeline.read(input.TextFileStream('hdfs://host:port/my_hdfs_dir/')) >>> lines3 = _pipeline.read(input.TextFileStream('hdfs:///multi_path1', 'hdfs:///multi_path2')) >>>... | TextFileStream | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextFileStream:
"""表示读取的文本文件的无穷数据源。 Args: *path: 读取文件目录的path,必须均为str类型 读取文件数据示例::: >>> lines1 = _pipeline.read(input.TextFileStream('hdfs:///my_hdfs_dir/')) >>> lines2 = _pipeline.read(input.TextFileStream('hdfs://host:port/my_hdfs_dir/')) >>> lines3 = _pipeline.read(input.TextFileStream('hdfs://... | stack_v2_sparse_classes_10k_train_001022 | 30,720 | permissive | [
{
"docstring": "内部方法",
"name": "__init__",
"signature": "def __init__(self, *path, **options)"
},
{
"docstring": "内部接口",
"name": "transform_from_node",
"signature": "def transform_from_node(self, load_node, pipeline)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004205 | Implement the Python class `TextFileStream` described below.
Class description:
表示读取的文本文件的无穷数据源。 Args: *path: 读取文件目录的path,必须均为str类型 读取文件数据示例::: >>> lines1 = _pipeline.read(input.TextFileStream('hdfs:///my_hdfs_dir/')) >>> lines2 = _pipeline.read(input.TextFileStream('hdfs://host:port/my_hdfs_dir/')) >>> lines3 = _pipe... | Implement the Python class `TextFileStream` described below.
Class description:
表示读取的文本文件的无穷数据源。 Args: *path: 读取文件目录的path,必须均为str类型 读取文件数据示例::: >>> lines1 = _pipeline.read(input.TextFileStream('hdfs:///my_hdfs_dir/')) >>> lines2 = _pipeline.read(input.TextFileStream('hdfs://host:port/my_hdfs_dir/')) >>> lines3 = _pipe... | cfcef62e8a64565b1dceb84efd4278fa83f87b7c | <|skeleton|>
class TextFileStream:
"""表示读取的文本文件的无穷数据源。 Args: *path: 读取文件目录的path,必须均为str类型 读取文件数据示例::: >>> lines1 = _pipeline.read(input.TextFileStream('hdfs:///my_hdfs_dir/')) >>> lines2 = _pipeline.read(input.TextFileStream('hdfs://host:port/my_hdfs_dir/')) >>> lines3 = _pipeline.read(input.TextFileStream('hdfs://... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TextFileStream:
"""表示读取的文本文件的无穷数据源。 Args: *path: 读取文件目录的path,必须均为str类型 读取文件数据示例::: >>> lines1 = _pipeline.read(input.TextFileStream('hdfs:///my_hdfs_dir/')) >>> lines2 = _pipeline.read(input.TextFileStream('hdfs://host:port/my_hdfs_dir/')) >>> lines3 = _pipeline.read(input.TextFileStream('hdfs:///multi_path1'... | the_stack_v2_python_sparse | bigflow_python/python/bigflow/input.py | baidu/bigflow | train | 1,279 |
f0c9bd0e9b89962c6f417af23172ea536acfe5c9 | [
"if current_user in self.event.guests:\n return jsonify({'status': 200, 'message': 'You are registered as a guest'})\nelif current_user in self.event.participants:\n return jsonify({'status': 200, 'message': 'You are registered as a participant'})\nelse:\n return jsonify({'status': 200, 'message': 'You are... | <|body_start_0|>
if current_user in self.event.guests:
return jsonify({'status': 200, 'message': 'You are registered as a guest'})
elif current_user in self.event.participants:
return jsonify({'status': 200, 'message': 'You are registered as a participant'})
else:
... | Resource for registering and unregistering as a guest fo event | UserAsGuest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAsGuest:
"""Resource for registering and unregistering as a guest fo event"""
def get(self, event_id: int) -> Response:
"""Method for checking registration as a guest Parameters ---------- event_id : int Event id Returns ------- Response Response message with status code"""
... | stack_v2_sparse_classes_10k_train_001023 | 6,917 | no_license | [
{
"docstring": "Method for checking registration as a guest Parameters ---------- event_id : int Event id Returns ------- Response Response message with status code",
"name": "get",
"signature": "def get(self, event_id: int) -> Response"
},
{
"docstring": "Method for registering as a guest Param... | 3 | stack_v2_sparse_classes_30k_train_001666 | Implement the Python class `UserAsGuest` described below.
Class description:
Resource for registering and unregistering as a guest fo event
Method signatures and docstrings:
- def get(self, event_id: int) -> Response: Method for checking registration as a guest Parameters ---------- event_id : int Event id Returns --... | Implement the Python class `UserAsGuest` described below.
Class description:
Resource for registering and unregistering as a guest fo event
Method signatures and docstrings:
- def get(self, event_id: int) -> Response: Method for checking registration as a guest Parameters ---------- event_id : int Event id Returns --... | 51e4d69f88c120cfc587fd007f21528a7bd661a0 | <|skeleton|>
class UserAsGuest:
"""Resource for registering and unregistering as a guest fo event"""
def get(self, event_id: int) -> Response:
"""Method for checking registration as a guest Parameters ---------- event_id : int Event id Returns ------- Response Response message with status code"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserAsGuest:
"""Resource for registering and unregistering as a guest fo event"""
def get(self, event_id: int) -> Response:
"""Method for checking registration as a guest Parameters ---------- event_id : int Event id Returns ------- Response Response message with status code"""
if current... | the_stack_v2_python_sparse | flask_app/resources/guest.py | Kyrylo-Kotelevets/Flask_Events | train | 0 |
fccf0a093fabd4960d36d194df00087e15c6b8d7 | [
"self.node_name = node_name\nself.batch_normalize = batch_normalize\nassert len(conv_weight_dims) == 4\nself.conv_weight_dims = conv_weight_dims",
"assert suffix\nassert param_category in ['bn', 'conv']\nassert suffix in ['scale', 'mean', 'var', 'weights', 'bias']\nif param_category == 'bn':\n assert self.batc... | <|body_start_0|>
self.node_name = node_name
self.batch_normalize = batch_normalize
assert len(conv_weight_dims) == 4
self.conv_weight_dims = conv_weight_dims
<|end_body_0|>
<|body_start_1|>
assert suffix
assert param_category in ['bn', 'conv']
assert suffix in ['... | Helper class to store the hyper parameters of a Conv layer, including its prefix name in the ONNX graph and the expected dimensions of weights for convolution, bias, and batch normalization. Additionally acts as a wrapper for generating safe names for all weights, checking on feasible combinations. | ConvParams | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"ISC",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvParams:
"""Helper class to store the hyper parameters of a Conv layer, including its prefix name in the ONNX graph and the expected dimensions of weights for convolution, bias, and batch normalization. Additionally acts as a wrapper for generating safe names for all weights, checking on feasi... | stack_v2_sparse_classes_10k_train_001024 | 29,876 | permissive | [
{
"docstring": "Constructor based on the base node name (e.g. 101_convolutional), the batch normalization setting, and the convolutional weights shape. Keyword arguments: node_name -- base name of this YOLO convolutional layer batch_normalize -- bool value if batch normalization is used conv_weight_dims -- the ... | 2 | null | Implement the Python class `ConvParams` described below.
Class description:
Helper class to store the hyper parameters of a Conv layer, including its prefix name in the ONNX graph and the expected dimensions of weights for convolution, bias, and batch normalization. Additionally acts as a wrapper for generating safe n... | Implement the Python class `ConvParams` described below.
Class description:
Helper class to store the hyper parameters of a Conv layer, including its prefix name in the ONNX graph and the expected dimensions of weights for convolution, bias, and batch normalization. Additionally acts as a wrapper for generating safe n... | a167852705d74bcc619d8fad0af4b9e4d84472fc | <|skeleton|>
class ConvParams:
"""Helper class to store the hyper parameters of a Conv layer, including its prefix name in the ONNX graph and the expected dimensions of weights for convolution, bias, and batch normalization. Additionally acts as a wrapper for generating safe names for all weights, checking on feasi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConvParams:
"""Helper class to store the hyper parameters of a Conv layer, including its prefix name in the ONNX graph and the expected dimensions of weights for convolution, bias, and batch normalization. Additionally acts as a wrapper for generating safe names for all weights, checking on feasible combinati... | the_stack_v2_python_sparse | samples/python/yolov3_onnx/yolov3_to_onnx.py | NVIDIA/TensorRT | train | 8,026 |
f0c842f71926f58aad3f2622f4b321d0548122d2 | [
"super(PixelControl, self).__init__(name=name)\nself._num_actions = num_actions\nself._activation = activation\nself._linear = snt.Linear(32 * 7 * 7, name='linear')\nself._deconv = snt.Conv2DTranspose(output_channels=32, kernel_shape=9, padding='SAME', name='deconv', stride=3, output_shape=(20, 20))\nself._value = ... | <|body_start_0|>
super(PixelControl, self).__init__(name=name)
self._num_actions = num_actions
self._activation = activation
self._linear = snt.Linear(32 * 7 * 7, name='linear')
self._deconv = snt.Conv2DTranspose(output_channels=32, kernel_shape=9, padding='SAME', name='deconv', ... | Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representing a 5 x 5 pixel area, covering a pixel ... | PixelControl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelControl:
"""Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representi... | stack_v2_sparse_classes_10k_train_001025 | 10,989 | no_license | [
{
"docstring": "Initializes the PixelControl module. Args: num_actions: number of actions in discrete action space activation: activation function to be used (after linear and deconvolutional layer) name: name for the module",
"name": "__init__",
"signature": "def __init__(self, num_actions: int, activa... | 2 | stack_v2_sparse_classes_30k_train_004256 | Implement the Python class `PixelControl` described below.
Class description:
Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a... | Implement the Python class `PixelControl` described below.
Class description:
Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a... | 1c2b2768f2c5996c8cc998d0271f3857949bdaeb | <|skeleton|>
class PixelControl:
"""Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PixelControl:
"""Module that produces a pixel control output (i.e. Q-values) from a hidden state input. This module implements the Pixel Control module from the FTW paper. Thus, it produces an output of shape [batch_size, 20, 20, num_actions], representing a grid of 20 x 20 cells, each representing a 5 x 5 pi... | the_stack_v2_python_sparse | ftw/tf/networks/auxiliary.py | RaoulDrake/ftw | train | 3 |
befb436057ad16c36ba0877c52f027d797c0dbaa | [
"user = serializer.context.get('request').user\nusername = getattr(user, 'username', 'guest')\nserializer.save(creator=username, updated_by=username)",
"user = serializer.context.get('request').user\nusername = getattr(user, 'username', 'guest')\nserializer.save(updated_by=username)"
] | <|body_start_0|>
user = serializer.context.get('request').user
username = getattr(user, 'username', 'guest')
serializer.save(creator=username, updated_by=username)
<|end_body_0|>
<|body_start_1|>
user = serializer.context.get('request').user
username = getattr(user, 'username', ... | 按需改造DRF默认的ModelViewSet类 | ModelViewSet | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
<|body_0|>
def perform_update(self, serializer):
"""更新时补充基础Model中的字段"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = serializer.conte... | stack_v2_sparse_classes_10k_train_001026 | 9,093 | permissive | [
{
"docstring": "创建时补充基础Model中的字段",
"name": "perform_create",
"signature": "def perform_create(self, serializer)"
},
{
"docstring": "更新时补充基础Model中的字段",
"name": "perform_update",
"signature": "def perform_update(self, serializer)"
}
] | 2 | null | Implement the Python class `ModelViewSet` described below.
Class description:
按需改造DRF默认的ModelViewSet类
Method signatures and docstrings:
- def perform_create(self, serializer): 创建时补充基础Model中的字段
- def perform_update(self, serializer): 更新时补充基础Model中的字段 | Implement the Python class `ModelViewSet` described below.
Class description:
按需改造DRF默认的ModelViewSet类
Method signatures and docstrings:
- def perform_create(self, serializer): 创建时补充基础Model中的字段
- def perform_update(self, serializer): 更新时补充基础Model中的字段
<|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
<|body_0|>
def perform_update(self, serializer):
"""更新时补充基础Model中的字段"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelViewSet:
"""按需改造DRF默认的ModelViewSet类"""
def perform_create(self, serializer):
"""创建时补充基础Model中的字段"""
user = serializer.context.get('request').user
username = getattr(user, 'username', 'guest')
serializer.save(creator=username, updated_by=username)
def perform_upda... | the_stack_v2_python_sparse | itsm/iadmin/views.py | TencentBlueKing/bk-itsm | train | 100 |
a5217561619533a5787509021d374c23fc27b910 | [
"self.max_vmware_http_sessions = max_vmware_http_sessions\nself.o_365_emulator_entity_info = o_365_emulator_entity_info\nself.o_365_region = o_365_region\nself.outlook_skip_creating_autodiscover_proxy = outlook_skip_creating_autodiscover_proxy\nself.registered_entity_sfdc_params = registered_entity_sfdc_params\nsel... | <|body_start_0|>
self.max_vmware_http_sessions = max_vmware_http_sessions
self.o_365_emulator_entity_info = o_365_emulator_entity_info
self.o_365_region = o_365_region
self.outlook_skip_creating_autodiscover_proxy = outlook_skip_creating_autodiscover_proxy
self.registered_entity_... | Implementation of the 'AdditionalConnectorParams' model. Message that encapsulates the additional connector params to establish a connection with a particular environment. Attributes: max_vmware_http_sessions (int): Max http sessions per context for VMWare vAPI calls. o_365_emulator_entity_info (string): A token used o... | AdditionalConnectorParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdditionalConnectorParams:
"""Implementation of the 'AdditionalConnectorParams' model. Message that encapsulates the additional connector params to establish a connection with a particular environment. Attributes: max_vmware_http_sessions (int): Max http sessions per context for VMWare vAPI calls... | stack_v2_sparse_classes_10k_train_001027 | 5,015 | permissive | [
{
"docstring": "Constructor for the AdditionalConnectorParams class",
"name": "__init__",
"signature": "def __init__(self, max_vmware_http_sessions=None, o_365_emulator_entity_info=None, o_365_region=None, outlook_skip_creating_autodiscover_proxy=None, registered_entity_sfdc_params=None, use_get_searcha... | 2 | stack_v2_sparse_classes_30k_test_000091 | Implement the Python class `AdditionalConnectorParams` described below.
Class description:
Implementation of the 'AdditionalConnectorParams' model. Message that encapsulates the additional connector params to establish a connection with a particular environment. Attributes: max_vmware_http_sessions (int): Max http ses... | Implement the Python class `AdditionalConnectorParams` described below.
Class description:
Implementation of the 'AdditionalConnectorParams' model. Message that encapsulates the additional connector params to establish a connection with a particular environment. Attributes: max_vmware_http_sessions (int): Max http ses... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AdditionalConnectorParams:
"""Implementation of the 'AdditionalConnectorParams' model. Message that encapsulates the additional connector params to establish a connection with a particular environment. Attributes: max_vmware_http_sessions (int): Max http sessions per context for VMWare vAPI calls... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdditionalConnectorParams:
"""Implementation of the 'AdditionalConnectorParams' model. Message that encapsulates the additional connector params to establish a connection with a particular environment. Attributes: max_vmware_http_sessions (int): Max http sessions per context for VMWare vAPI calls. o_365_emula... | the_stack_v2_python_sparse | cohesity_management_sdk/models/additional_connector_params.py | cohesity/management-sdk-python | train | 24 |
377682c9e234a8da72d3c1a28a6ddbf1846f0b22 | [
"self.list_of_all_labels = find_all_labels(list(frecords()), get_labels_of_record)\nself.k_list = k_list\nPRINTER('[MlKnnFractionalEnsembledStrongest: init] labels: ' + str(self.list_of_all_labels))\nPRINTER('[MlKnnFractionalEnsembledStrongest: init]: START OF TRAINING...')\nself.mlknn_fractionals = {}\nfor k in se... | <|body_start_0|>
self.list_of_all_labels = find_all_labels(list(frecords()), get_labels_of_record)
self.k_list = k_list
PRINTER('[MlKnnFractionalEnsembledStrongest: init] labels: ' + str(self.list_of_all_labels))
PRINTER('[MlKnnFractionalEnsembledStrongest: init]: START OF TRAINING...')
... | @deprecated: use MlknnTEnsembled instead. Naive Bayes with KNN as features. Modification of a classifier based on a publication: Ml-knn: A Lazy Learning Approach to Multi-Label Learning Min-Ling Zhang, Zhi-Hua Zhou. A threshold is being chosen for each class, maximizing the f-measure. Ensemble of such MlKnn's is create... | MlKnnFractionalEnsembledStrongest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MlKnnFractionalEnsembledStrongest:
"""@deprecated: use MlknnTEnsembled instead. Naive Bayes with KNN as features. Modification of a classifier based on a publication: Ml-knn: A Lazy Learning Approach to Multi-Label Learning Min-Ling Zhang, Zhi-Hua Zhou. A threshold is being chosen for each class,... | stack_v2_sparse_classes_10k_train_001028 | 4,279 | no_license | [
{
"docstring": "Constructor. @type frecords: list of records @param frecords: used to calculate parameters (probabilities) and nearest neighbours amongst the records it returns; NOTE: if a user wants to manipulate, which codes to consider(e.g. higher or lower level) it is good to give a specific frecords parame... | 2 | stack_v2_sparse_classes_30k_train_004142 | Implement the Python class `MlKnnFractionalEnsembledStrongest` described below.
Class description:
@deprecated: use MlknnTEnsembled instead. Naive Bayes with KNN as features. Modification of a classifier based on a publication: Ml-knn: A Lazy Learning Approach to Multi-Label Learning Min-Ling Zhang, Zhi-Hua Zhou. A th... | Implement the Python class `MlKnnFractionalEnsembledStrongest` described below.
Class description:
@deprecated: use MlknnTEnsembled instead. Naive Bayes with KNN as features. Modification of a classifier based on a publication: Ml-knn: A Lazy Learning Approach to Multi-Label Learning Min-Ling Zhang, Zhi-Hua Zhou. A th... | e38508de91f8a7bda3096c6f0a361734207357a5 | <|skeleton|>
class MlKnnFractionalEnsembledStrongest:
"""@deprecated: use MlknnTEnsembled instead. Naive Bayes with KNN as features. Modification of a classifier based on a publication: Ml-knn: A Lazy Learning Approach to Multi-Label Learning Min-Ling Zhang, Zhi-Hua Zhou. A threshold is being chosen for each class,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MlKnnFractionalEnsembledStrongest:
"""@deprecated: use MlknnTEnsembled instead. Naive Bayes with KNN as features. Modification of a classifier based on a publication: Ml-knn: A Lazy Learning Approach to Multi-Label Learning Min-Ling Zhang, Zhi-Hua Zhou. A threshold is being chosen for each class, maximizing t... | the_stack_v2_python_sparse | src/main/python/document_classification/mlknn/mlknn_ensembled_fractional.py | pszostek/research-python-backup | train | 0 |
972f50f66d68d56cd5f0aa063a2d86df62a83f5b | [
"self._data = data\nself._offset = offset\nself._limit = limit",
"limit = self._limit\noffset = self._offset\nvalue = limit - offset >> 2\nreturn value",
"index = index << 2\noffset = self._offset + index\nvalue = int.from_bytes(self._data[offset:offset + 4], 'big')\nreturn value",
"data = self._data\noffset ... | <|body_start_0|>
self._data = data
self._offset = offset
self._limit = limit
<|end_body_0|>
<|body_start_1|>
limit = self._limit
offset = self._offset
value = limit - offset >> 2
return value
<|end_body_1|>
<|body_start_2|>
index = index << 2
off... | Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`. | Array_uint_32b | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array_uint_32b:
"""Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`."""
def __init__(self, d... | stack_v2_sparse_classes_10k_train_001029 | 11,434 | permissive | [
{
"docstring": "Creates a new uint32 array from the given parameters. Parameters ---------- data : `bytes` The source `bytes` object. offset : `int` The first byte what is inside of the array. limit : `int` The first byte, what is not inside of the array after `._offset`.",
"name": "__init__",
"signatur... | 4 | null | Implement the Python class `Array_uint_32b` described below.
Class description:
Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `... | Implement the Python class `Array_uint_32b` described below.
Class description:
Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class Array_uint_32b:
"""Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`."""
def __init__(self, d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Array_uint_32b:
"""Implements an uint32 array casted on bytes. Attributes ---------- _data : `bytes` The source `bytes` object. _offset : `int` The first byte what is inside of the array. _limit : `int` The first byte, what is not inside of the array after `._offset`."""
def __init__(self, data, offset, ... | the_stack_v2_python_sparse | hata/discord/voice/rtp_packet.py | HuyaneMatsu/hata | train | 3 |
da9ae6207c659f85d42aa5bf7811fa3e74720908 | [
"self.host = host\nself.port = port\nself.user = user\nself.password = password\nself.database = database",
"try:\n connection = connector.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.database, use_pure=True)\n cursor = connection.cursor()\n cursor.execute... | <|body_start_0|>
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
<|end_body_0|>
<|body_start_1|>
try:
connection = connector.connect(host=self.host, port=self.port, user=self.user, password=self.password, d... | MySqlHelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySqlHelper:
def __init__(self, host, port, user, password, database):
"""[summary]: Constructor Args: host ([type]): [description] port ([type]): [description] user ([type]): [description] password ([type]): [description] database ([type]): [description]"""
<|body_0|>
def f... | stack_v2_sparse_classes_10k_train_001030 | 4,113 | permissive | [
{
"docstring": "[summary]: Constructor Args: host ([type]): [description] port ([type]): [description] user ([type]): [description] password ([type]): [description] database ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, host, port, user, password, database)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_005384 | Implement the Python class `MySqlHelper` described below.
Class description:
Implement the MySqlHelper class.
Method signatures and docstrings:
- def __init__(self, host, port, user, password, database): [summary]: Constructor Args: host ([type]): [description] port ([type]): [description] user ([type]): [description... | Implement the Python class `MySqlHelper` described below.
Class description:
Implement the MySqlHelper class.
Method signatures and docstrings:
- def __init__(self, host, port, user, password, database): [summary]: Constructor Args: host ([type]): [description] port ([type]): [description] user ([type]): [description... | 8332485421b04120924d4640d221f40cacb78741 | <|skeleton|>
class MySqlHelper:
def __init__(self, host, port, user, password, database):
"""[summary]: Constructor Args: host ([type]): [description] port ([type]): [description] user ([type]): [description] password ([type]): [description] database ([type]): [description]"""
<|body_0|>
def f... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MySqlHelper:
def __init__(self, host, port, user, password, database):
"""[summary]: Constructor Args: host ([type]): [description] port ([type]): [description] user ([type]): [description] password ([type]): [description] database ([type]): [description]"""
self.host = host
self.port ... | the_stack_v2_python_sparse | src/utils/mysql_helper.py | Supreeth-Shetty/neuro-data | train | 0 | |
034a7b4150d2147a0339a36f51a3627a4bcf232e | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jgrishey', 'jgrishey')\nclient = sodapy.Socrata('data.cityofboston.gov', dml.auth['services']['cityofbostondataportal']['token'])\nresponse = client.get('29yf-ye7n', limit=10000)\ncrimes = []\nID = 0\nfo... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jgrishey', 'jgrishey')
client = sodapy.Socrata('data.cityofboston.gov', dml.auth['services']['cityofbostondataportal']['token'])
response = client... | getCrime | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class getCrime:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_10k_train_001031 | 3,719 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `getCrime` described below.
Class description:
Implement the getCrime class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | Implement the Python class `getCrime` described below.
Class description:
Implement the getCrime class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class getCrime:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class getCrime:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jgrishey', 'jgrishey')
client = so... | the_stack_v2_python_sparse | jgrishey/getCrime.py | lingyigu/course-2017-spr-proj | train | 0 | |
230f5f17b1dc1a7d637581d25d54f89adaa38d6f | [
"msg = msg.view(size, -1, *msg.shape[1:])\nout = msg.mean(1)\nreturn out",
"col, row = es\nx_i, x_o = (x[row], x[col])\nmsg = ops.Concat(-1)((x_i, x_o))\nreturn (msg, col, len(x))"
] | <|body_start_0|>
msg = msg.view(size, -1, *msg.shape[1:])
out = msg.mean(1)
return out
<|end_body_0|>
<|body_start_1|>
col, row = es
x_i, x_o = (x[row], x[col])
msg = ops.Concat(-1)((x_i, x_o))
return (msg, col, len(x))
<|end_body_1|>
| Reimplementation of the Message-Passing class to allow more flexibility. | GNN | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GNN:
"""Reimplementation of the Message-Passing class to allow more flexibility."""
def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor:
"""Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, o... | stack_v2_sparse_classes_10k_train_001032 | 9,199 | permissive | [
{
"docstring": "Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, optional only 3 types of aggregation are supported: 'add', 'mean' or 'max'. The default is \"mean\". Returns ------- Tensor aggregated node embeddings.",
"name": "aggregate",
"s... | 2 | null | Implement the Python class `GNN` described below.
Class description:
Reimplementation of the Message-Passing class to allow more flexibility.
Method signatures and docstrings:
- def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: Parameters ---------- msg : Tensor [E, ..., dim * 2]. i... | Implement the Python class `GNN` described below.
Class description:
Reimplementation of the Message-Passing class to allow more flexibility.
Method signatures and docstrings:
- def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: Parameters ---------- msg : Tensor [E, ..., dim * 2]. i... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class GNN:
"""Reimplementation of the Message-Passing class to allow more flexibility."""
def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor:
"""Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GNN:
"""Reimplementation of the Message-Passing class to allow more flexibility."""
def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor:
"""Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, optional only ... | the_stack_v2_python_sparse | research/gnn/nri-mpm/models/base.py | mindspore-ai/models | train | 301 |
342977e676c209abdb3246d7e40f89db1bf177e3 | [
"if self.__class__.all is None:\n self.__class__.all = set()\nself.__class__.all.add(self)\nself.identifier = identifier",
"for instance in cls.all:\n if instance.identifier == identifier:\n return instance\nreturn None"
] | <|body_start_0|>
if self.__class__.all is None:
self.__class__.all = set()
self.__class__.all.add(self)
self.identifier = identifier
<|end_body_0|>
<|body_start_1|>
for instance in cls.all:
if instance.identifier == identifier:
return instance
... | base class for domain classes | Base | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""base class for domain classes"""
def __init__(self, identifier):
"""create domain object and self-register it"""
<|body_0|>
def find_instance(cls, identifier):
"""find instance with given identifier :param identifier: instance to look for :return: instan... | stack_v2_sparse_classes_10k_train_001033 | 804 | permissive | [
{
"docstring": "create domain object and self-register it",
"name": "__init__",
"signature": "def __init__(self, identifier)"
},
{
"docstring": "find instance with given identifier :param identifier: instance to look for :return: instance or None",
"name": "find_instance",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_003247 | Implement the Python class `Base` described below.
Class description:
base class for domain classes
Method signatures and docstrings:
- def __init__(self, identifier): create domain object and self-register it
- def find_instance(cls, identifier): find instance with given identifier :param identifier: instance to loo... | Implement the Python class `Base` described below.
Class description:
base class for domain classes
Method signatures and docstrings:
- def __init__(self, identifier): create domain object and self-register it
- def find_instance(cls, identifier): find instance with given identifier :param identifier: instance to loo... | e65fddb94513e7c2f54f248b4ce69e9e10ce42f5 | <|skeleton|>
class Base:
"""base class for domain classes"""
def __init__(self, identifier):
"""create domain object and self-register it"""
<|body_0|>
def find_instance(cls, identifier):
"""find instance with given identifier :param identifier: instance to look for :return: instan... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Base:
"""base class for domain classes"""
def __init__(self, identifier):
"""create domain object and self-register it"""
if self.__class__.all is None:
self.__class__.all = set()
self.__class__.all.add(self)
self.identifier = identifier
def find_instance(... | the_stack_v2_python_sparse | python/domain/base.py | jeroenpeeters/document-as-code | train | 0 |
beaa94511a3bb5f771290e123bde892849d49983 | [
"super().__init__(publishers, dev_cfg)\nself.devices = get_dict_of_sequential_param__output(dev_cfg, 'Address', 'Destination')\nverify_connections_layout(self.comm, self.log, self.name, list(self.devices.values()))\nself.states = dict.fromkeys(list(self.devices.keys()), None)\nself.log.info('Configuring BTLE sensor... | <|body_start_0|>
super().__init__(publishers, dev_cfg)
self.devices = get_dict_of_sequential_param__output(dev_cfg, 'Address', 'Destination')
verify_connections_layout(self.comm, self.log, self.name, list(self.devices.values()))
self.states = dict.fromkeys(list(self.devices.keys()), None... | Uses BluePy to scan for BTLE braodcasts from a device with a given MAC address and publishes whehter or not it is present. | BtleSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BtleSensor:
"""Uses BluePy to scan for BTLE braodcasts from a device with a given MAC address and publishes whehter or not it is present."""
def __init__(self, publishers, dev_cfg):
"""Initializes the BTLE scanner. dev_cfg: - Poll: must be > 0 and > Timeout - AddressX: sequential lis... | stack_v2_sparse_classes_10k_train_001034 | 5,150 | permissive | [
{
"docstring": "Initializes the BTLE scanner. dev_cfg: - Poll: must be > 0 and > Timeout - AddressX: sequential list of MAC addresses to look for - Timeout: Maximum amount of time to wait for BTLE packets - Values: optional, if present should have two values separated by a comma, the first value being the prese... | 3 | stack_v2_sparse_classes_30k_train_002679 | Implement the Python class `BtleSensor` described below.
Class description:
Uses BluePy to scan for BTLE braodcasts from a device with a given MAC address and publishes whehter or not it is present.
Method signatures and docstrings:
- def __init__(self, publishers, dev_cfg): Initializes the BTLE scanner. dev_cfg: - P... | Implement the Python class `BtleSensor` described below.
Class description:
Uses BluePy to scan for BTLE braodcasts from a device with a given MAC address and publishes whehter or not it is present.
Method signatures and docstrings:
- def __init__(self, publishers, dev_cfg): Initializes the BTLE scanner. dev_cfg: - P... | 6f8888ddef413fb8d58ef0ebc8fe89144c914a22 | <|skeleton|>
class BtleSensor:
"""Uses BluePy to scan for BTLE braodcasts from a device with a given MAC address and publishes whehter or not it is present."""
def __init__(self, publishers, dev_cfg):
"""Initializes the BTLE scanner. dev_cfg: - Poll: must be > 0 and > Timeout - AddressX: sequential lis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BtleSensor:
"""Uses BluePy to scan for BTLE braodcasts from a device with a given MAC address and publishes whehter or not it is present."""
def __init__(self, publishers, dev_cfg):
"""Initializes the BTLE scanner. dev_cfg: - Poll: must be > 0 and > Timeout - AddressX: sequential list of MAC addr... | the_stack_v2_python_sparse | bt/btle_sensor.py | rkoshak/sensorReporter | train | 104 |
e6ec4b41a2c3f75bf2f8ba82bd0b3c51f62fda2e | [
"schools_urls_xpath = '//*[@id=\"table10\"]/tr/td/table[2]/tr/td/font/a/@href'\nschools_urls = response.xpath(schools_urls_xpath).extract()\nfor url in schools_urls:\n yield scrapy.Request(response.urljoin(url), callback=self.parse_school)",
"school_name_xpath = '//*[@id=\"table1\"]/tr[1]/td/table/tr/td[1]/fon... | <|body_start_0|>
schools_urls_xpath = '//*[@id="table10"]/tr/td/table[2]/tr/td/font/a/@href'
schools_urls = response.xpath(schools_urls_xpath).extract()
for url in schools_urls:
yield scrapy.Request(response.urljoin(url), callback=self.parse_school)
<|end_body_0|>
<|body_start_1|>
... | a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found | MontrealLbpsbSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MontrealLbpsbSpider:
"""a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def parse(self, response):
"""get all s... | stack_v2_sparse_classes_10k_train_001035 | 3,493 | no_license | [
{
"docstring": "get all schools urls then yield a Request for each one.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "get required information for each school this method is called once for each school",
"name": "parse_school",
"signature": "def parse_sch... | 2 | stack_v2_sparse_classes_30k_train_001115 | Implement the Python class `MontrealLbpsbSpider` described below.
Class description:
a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
Method signatur... | Implement the Python class `MontrealLbpsbSpider` described below.
Class description:
a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found
Method signatur... | 350264cf6da323692c2838d8cb235ef61085851b | <|skeleton|>
class MontrealLbpsbSpider:
"""a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def parse(self, response):
"""get all s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MontrealLbpsbSpider:
"""a scrapy spider to crawl lbpsb.qc.ca domain to get school_name street_address city province postal_code phone_number school_url school_grades school_language school_type school_board response_url for each school found"""
def parse(self, response):
"""get all schools urls t... | the_stack_v2_python_sparse | school_scraping/spiders/montreal_lbpsb.py | ramadanmostafa/canada_school_scraping | train | 0 |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"super(Matern32, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)\nlogger.debug('Initializing %s kernel.' % self.name)\nself.variance = np.float64(variance)\nself.lengthscale = np.float64(lengthscale)\nself.parameter_list = ['variance', 'lengthscale']\nself.constraint_map = {'variance': '+ve', 'len... | <|body_start_0|>
super(Matern32, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)
logger.debug('Initializing %s kernel.' % self.name)
self.variance = np.float64(variance)
self.lengthscale = np.float64(lengthscale)
self.parameter_list = ['variance', 'lengthscale']... | Matern32 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matern32:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specif... | stack_v2_sparse_classes_10k_train_001036 | 9,047 | no_license | [
{
"docstring": "squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified",
"name": "__init__",
"signature": "def __init__(self, n_dims, variance=1.0, lengthscale=1.0, act... | 2 | stack_v2_sparse_classes_30k_val_000255 | Implement the Python class `Matern32` described below.
Class description:
Implement the Matern32 class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel varianc... | Implement the Python class `Matern32` described below.
Class description:
Implement the Matern32 class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel varianc... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class Matern32:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specif... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Matern32:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified"""
... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 | |
e48ecdb4971af81115051efecde872e2ebffd3c8 | [
"if N == 0:\n return '0'\nt = N\nk = 1\nr = ''\nwhile t != 0:\n if t % 2 == 1:\n r = '1' + r\n t -= k\n else:\n r = '0' + r\n t = t // 2\n k *= -1\nreturn r",
"if N == 0:\n return '0'\nlist_tail = ['0b000', '0b001', '0b110', '0b111', '0b1001']\nlist_start = [0, 0, 1, 1]\nres... | <|body_start_0|>
if N == 0:
return '0'
t = N
k = 1
r = ''
while t != 0:
if t % 2 == 1:
r = '1' + r
t -= k
else:
r = '0' + r
t = t // 2
k *= -1
return r
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def baseNeg2(self, N: int) -> str:
"""so hard 补偿的思路 :param N: :return:"""
<|body_0|>
def baseNeg2_2(self, N: int) -> str:
"""空虚解法 :param N: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if N == 0:
return '0'
... | stack_v2_sparse_classes_10k_train_001037 | 1,088 | no_license | [
{
"docstring": "so hard 补偿的思路 :param N: :return:",
"name": "baseNeg2",
"signature": "def baseNeg2(self, N: int) -> str"
},
{
"docstring": "空虚解法 :param N: :return:",
"name": "baseNeg2_2",
"signature": "def baseNeg2_2(self, N: int) -> str"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def baseNeg2(self, N: int) -> str: so hard 补偿的思路 :param N: :return:
- def baseNeg2_2(self, N: int) -> str: 空虚解法 :param N: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def baseNeg2(self, N: int) -> str: so hard 补偿的思路 :param N: :return:
- def baseNeg2_2(self, N: int) -> str: 空虚解法 :param N: :return:
<|skeleton|>
class Solution:
def baseNeg2... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def baseNeg2(self, N: int) -> str:
"""so hard 补偿的思路 :param N: :return:"""
<|body_0|>
def baseNeg2_2(self, N: int) -> str:
"""空虚解法 :param N: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def baseNeg2(self, N: int) -> str:
"""so hard 补偿的思路 :param N: :return:"""
if N == 0:
return '0'
t = N
k = 1
r = ''
while t != 0:
if t % 2 == 1:
r = '1' + r
t -= k
else:
... | the_stack_v2_python_sparse | baseNeg2.py | NeilWangziyu/Leetcode_py | train | 2 | |
69806b954a1de8eb08071a7774aacb5b8fe74dd8 | [
"dval = {}\nmodel = type(self)\nmapper = inspect(model)\nfor col in mapper.attrs:\n col_key = col.key\n dval[col_key] = str(getattr(self, col_key))\nreturn dval",
"model_dict = self.to_dict()\njson_str = json.dumps(model_dict, indent=indent)\nreturn json_str"
] | <|body_start_0|>
dval = {}
model = type(self)
mapper = inspect(model)
for col in mapper.attrs:
col_key = col.key
dval[col_key] = str(getattr(self, col_key))
return dval
<|end_body_0|>
<|body_start_1|>
model_dict = self.to_dict()
json_str =... | Mixin style class that adds serialization to data model objects. | SerializableModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerializableModel:
"""Mixin style class that adds serialization to data model objects."""
def to_dict(self):
"""Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model."""
<|body_0|>
def to_json(self, indent=4):
""... | stack_v2_sparse_classes_10k_train_001038 | 6,583 | no_license | [
{
"docstring": "Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model.",
"name": "to_dict",
"signature": "def to_dict(self)"
},
{
"docstring": "Iterates the formal data attributes of a model and creates a dictionary with the data based on the mo... | 2 | null | Implement the Python class `SerializableModel` described below.
Class description:
Mixin style class that adds serialization to data model objects.
Method signatures and docstrings:
- def to_dict(self): Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model.
- def to_... | Implement the Python class `SerializableModel` described below.
Class description:
Mixin style class that adds serialization to data model objects.
Method signatures and docstrings:
- def to_dict(self): Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model.
- def to_... | 530ea184f29add6f42bee1465343f6ddb51a1e51 | <|skeleton|>
class SerializableModel:
"""Mixin style class that adds serialization to data model objects."""
def to_dict(self):
"""Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model."""
<|body_0|>
def to_json(self, indent=4):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SerializableModel:
"""Mixin style class that adds serialization to data model objects."""
def to_dict(self):
"""Iterates the formal data attributes of a model and outputs a dictionary with the data based on the model."""
dval = {}
model = type(self)
mapper = inspect(model)... | the_stack_v2_python_sparse | packages/akit/datum/orm.py | TrendingTechnology/automationkit | train | 0 |
b7dc8a89471cf6f7a28f0fabf5af25e096e69961 | [
"length = len(data)\nif length == 0:\n return 0\nfirst = self.get_first_k(data, k, 0, length - 1)\nend = self.get_last_k(data, k, 0, length - 1)\nif first != -1 and end != -1:\n return end - first + 1\nreturn 0",
"if start > end:\n return -1\nmid = start + (end - start) / 2\nif data[mid] > k:\n return... | <|body_start_0|>
length = len(data)
if length == 0:
return 0
first = self.get_first_k(data, k, 0, length - 1)
end = self.get_last_k(data, k, 0, length - 1)
if first != -1 and end != -1:
return end - first + 1
return 0
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def GetNumberOfK(self, data, k):
"""在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:"""
<|body_0|>
def get_first_k(self, data, k, start, end):
"""递归写法二分查找 :param data: :param k: :param start: :param end: :return:"""
<|... | stack_v2_sparse_classes_10k_train_001039 | 1,814 | no_license | [
{
"docstring": "在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:",
"name": "GetNumberOfK",
"signature": "def GetNumberOfK(self, data, k)"
},
{
"docstring": "递归写法二分查找 :param data: :param k: :param start: :param end: :return:",
"name": "get_first_k",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_004212 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def GetNumberOfK(self, data, k): 在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:
- def get_first_k(self, data, k, start, end): 递归写法二分查找 :param dat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def GetNumberOfK(self, data, k): 在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:
- def get_first_k(self, data, k, start, end): 递归写法二分查找 :param dat... | c756fe54e8e17e9ba0bfdab5fccc24ac89263d90 | <|skeleton|>
class Solution:
def GetNumberOfK(self, data, k):
"""在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:"""
<|body_0|>
def get_first_k(self, data, k, start, end):
"""递归写法二分查找 :param data: :param k: :param start: :param end: :return:"""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def GetNumberOfK(self, data, k):
"""在Python中可以直接使用data.count(k)来解决 为了题目的意义,这里使用二分查找 :param data: :param k: :return:"""
length = len(data)
if length == 0:
return 0
first = self.get_first_k(data, k, 0, length - 1)
end = self.get_last_k(data, k, 0, le... | the_stack_v2_python_sparse | newcoder_offer/get_number_of_K.py | EarthChen/LeetCode_Record | train | 0 | |
6247bec60a0bc31fb748744866b29c2632956aa9 | [
"legalMoves = gameState.getLegalActions()\nscores = [self.evaluationFunction(gameState, action) for action in legalMoves]\nbestScore = max(scores)\nbestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\nchosenIndex = random.choice(bestIndices)\n'Add more of your code here if you want t... | <|body_start_0|>
legalMoves = gameState.getLegalActions()
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestInd... | A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. | ReflexAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_10k_train_001040 | 12,585 | permissive | [
{
"docstring": "You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}",
"... | 2 | stack_v2_sparse_classes_30k_train_003562 | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | Implement the Python class `ReflexAgent` described below.
Class description:
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our me... | f0fa32a4af9354177af0af9e5792c5136173f0b8 | <|skeleton|>
class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReflexAgent:
"""A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers."""
def getAction(self, gameState)... | the_stack_v2_python_sparse | ArtificialIntelligence/Project2/multiagent/multiAgents.py | iuuuuuaena/CUG-Practice | train | 7 |
683d76c9c33929407a4d8707b24e793daeefe1cc | [
"ret = 0\nD = defaultdict(lambda: defaultdict(int))\nfor i in range(len(A)):\n for j in range(i):\n d = A[i] - A[j]\n D[i][d] += 1 + D[j][d]\n if D[j][d] > 0:\n ret += D[j][d]\nreturn ret",
"ret = 0\nD = defaultdict(lambda: defaultdict(int))\nfor i in range(len(A)):\n for j i... | <|body_start_0|>
ret = 0
D = defaultdict(lambda: defaultdict(int))
for i in range(len(A)):
for j in range(i):
d = A[i] - A[j]
D[i][d] += 1 + D[j][d]
if D[j][d] > 0:
ret += D[j][d]
return ret
<|end_body_0|>
<... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numberOfArithmeticSlices(self, A):
"""Subsequence, count the number, looks like dp use defaultdict for easy dp array construction D[i][d] stores the number of arithmetic subsequence ending at A[i], with delta d result would be sum( D[i][d] if >= 3 consecutive subsequence A[... | stack_v2_sparse_classes_10k_train_001041 | 1,999 | permissive | [
{
"docstring": "Subsequence, count the number, looks like dp use defaultdict for easy dp array construction D[i][d] stores the number of arithmetic subsequence ending at A[i], with delta d result would be sum( D[i][d] if >= 3 consecutive subsequence A[i], A[j], A[k] ... for some j, k ) summing D[j][d] rather th... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberOfArithmeticSlices(self, A): Subsequence, count the number, looks like dp use defaultdict for easy dp array construction D[i][d] stores the number of arithmetic subsequ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numberOfArithmeticSlices(self, A): Subsequence, count the number, looks like dp use defaultdict for easy dp array construction D[i][d] stores the number of arithmetic subsequ... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def numberOfArithmeticSlices(self, A):
"""Subsequence, count the number, looks like dp use defaultdict for easy dp array construction D[i][d] stores the number of arithmetic subsequence ending at A[i], with delta d result would be sum( D[i][d] if >= 3 consecutive subsequence A[... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numberOfArithmeticSlices(self, A):
"""Subsequence, count the number, looks like dp use defaultdict for easy dp array construction D[i][d] stores the number of arithmetic subsequence ending at A[i], with delta d result would be sum( D[i][d] if >= 3 consecutive subsequence A[i], A[j], A[k]... | the_stack_v2_python_sparse | 446 Arithmetic Slices II - Subsequence.py | Aminaba123/LeetCode | train | 1 | |
8f330957446a85a0c05289337b71e98d81e52cdd | [
"self.words = words\nself.dictionary = defaultdict(list)\nfor index, word in enumerate(self.words):\n self.dictionary[word].append(index)",
"shortest_distance = sys.maxint\nfor index1, index2 in product(self.dictionary[word1], self.dictionary[word2]):\n if abs(index1 - index2) < shortest_distance:\n ... | <|body_start_0|>
self.words = words
self.dictionary = defaultdict(list)
for index, word in enumerate(self.words):
self.dictionary[word].append(index)
<|end_body_0|>
<|body_start_1|>
shortest_distance = sys.maxint
for index1, index2 in product(self.dictionary[word1], ... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k_train_001042 | 1,065 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 09355094c85496cc42f8cb3241da43e0ece1e45a | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.words = words
self.dictionary = defaultdict(list)
for index, word in enumerate(self.words):
self.dictionary[word].append(index)
def shortest(self, wo... | the_stack_v2_python_sparse | Rakesh/hash-table/shortest distance problem II.py | rakeshsukla53/interview-preparation | train | 9 | |
abd5c1a29f7f6d7625c832f7e1b9434b41a5d1dd | [
"self.aliyunrequest.set_action_name('DescribeDBInstances')\nif not isinstance(config, list):\n return self.MResponse(code=20001, msg='config配置不正确', status=False)\nself.Mconfig(config)\nresponse = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)\nreturn response",
"self.aliyunrequest.set_action... | <|body_start_0|>
self.aliyunrequest.set_action_name('DescribeDBInstances')
if not isinstance(config, list):
return self.MResponse(code=20001, msg='config配置不正确', status=False)
self.Mconfig(config)
response = self.aliyunapiclient.do_action_with_exception(self.aliyunrequest)
... | 查询Rds | ALiYunApiRds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ALiYunApiRds:
"""查询Rds"""
def DescribeDBInstances(self, config):
"""该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:"""
<|body_0|>
def DescribeDBInstanceAttribute(self, config):
"""该接口用于查看指定实例的详细属性。 :param config: :return:"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_001043 | 7,651 | no_license | [
{
"docstring": "该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:",
"name": "DescribeDBInstances",
"signature": "def DescribeDBInstances(self, config)"
},
{
"docstring": "该接口用于查看指定实例的详细属性。 :param config: :return:",
"name": "DescribeDBInstanceAttribute",
"signature": "def DescribeDBInstanc... | 2 | stack_v2_sparse_classes_30k_val_000079 | Implement the Python class `ALiYunApiRds` described below.
Class description:
查询Rds
Method signatures and docstrings:
- def DescribeDBInstances(self, config): 该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:
- def DescribeDBInstanceAttribute(self, config): 该接口用于查看指定实例的详细属性。 :param config: :return: | Implement the Python class `ALiYunApiRds` described below.
Class description:
查询Rds
Method signatures and docstrings:
- def DescribeDBInstances(self, config): 该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:
- def DescribeDBInstanceAttribute(self, config): 该接口用于查看指定实例的详细属性。 :param config: :return:
<|skeleton|>
class... | 401ad869298d55a6cb2f78442385f67f40b9db52 | <|skeleton|>
class ALiYunApiRds:
"""查询Rds"""
def DescribeDBInstances(self, config):
"""该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:"""
<|body_0|>
def DescribeDBInstanceAttribute(self, config):
"""该接口用于查看指定实例的详细属性。 :param config: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ALiYunApiRds:
"""查询Rds"""
def DescribeDBInstances(self, config):
"""该接口用于查看实例列表或被RAM授权的实例列表。 :param config: :return:"""
self.aliyunrequest.set_action_name('DescribeDBInstances')
if not isinstance(config, list):
return self.MResponse(code=20001, msg='config配置不正确', statu... | the_stack_v2_python_sparse | utils/maliyun/aliyunapi.py | Alotofwater/cookcmdb | train | 8 |
10425653e5a0284cff59494dc06448447e5210b7 | [
"lumMod = self._add_lumMod()\nlumMod.val = value\nreturn lumMod",
"lumOff = self._add_lumOff()\nlumOff.val = value\nreturn lumOff",
"self._remove_lumMod()\nself._remove_lumOff()\nreturn self"
] | <|body_start_0|>
lumMod = self._add_lumMod()
lumMod.val = value
return lumMod
<|end_body_0|>
<|body_start_1|>
lumOff = self._add_lumOff()
lumOff.val = value
return lumOff
<|end_body_1|>
<|body_start_2|>
self._remove_lumMod()
self._remove_lumOff()
... | Base class for <a:srgbClr> and <a:schemeClr> elements. | _BaseColorElement | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BaseColorElement:
"""Base class for <a:srgbClr> and <a:schemeClr> elements."""
def add_lumMod(self, value):
"""Return a newly added <a:lumMod> child element."""
<|body_0|>
def add_lumOff(self, value):
"""Return a newly added <a:lumOff> child element."""
... | stack_v2_sparse_classes_10k_train_001044 | 2,024 | permissive | [
{
"docstring": "Return a newly added <a:lumMod> child element.",
"name": "add_lumMod",
"signature": "def add_lumMod(self, value)"
},
{
"docstring": "Return a newly added <a:lumOff> child element.",
"name": "add_lumOff",
"signature": "def add_lumOff(self, value)"
},
{
"docstring":... | 3 | null | Implement the Python class `_BaseColorElement` described below.
Class description:
Base class for <a:srgbClr> and <a:schemeClr> elements.
Method signatures and docstrings:
- def add_lumMod(self, value): Return a newly added <a:lumMod> child element.
- def add_lumOff(self, value): Return a newly added <a:lumOff> child... | Implement the Python class `_BaseColorElement` described below.
Class description:
Base class for <a:srgbClr> and <a:schemeClr> elements.
Method signatures and docstrings:
- def add_lumMod(self, value): Return a newly added <a:lumMod> child element.
- def add_lumOff(self, value): Return a newly added <a:lumOff> child... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class _BaseColorElement:
"""Base class for <a:srgbClr> and <a:schemeClr> elements."""
def add_lumMod(self, value):
"""Return a newly added <a:lumMod> child element."""
<|body_0|>
def add_lumOff(self, value):
"""Return a newly added <a:lumOff> child element."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _BaseColorElement:
"""Base class for <a:srgbClr> and <a:schemeClr> elements."""
def add_lumMod(self, value):
"""Return a newly added <a:lumMod> child element."""
lumMod = self._add_lumMod()
lumMod.val = value
return lumMod
def add_lumOff(self, value):
"""Retur... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/pptx/oxml/dml/color.py | ryfeus/lambda-packs | train | 1,283 |
cb13c00cfb6032383b7dac6070d6bdb64fe02563 | [
"import netCDF4\nfrom netcdftime import utime\nself.nc = netCDF4.Dataset(filename)\nself.ncv = self.nc.variables\nself.lon = self.ncv['SCHISM_hgrid_node_x'][:]\nself.lat = self.ncv['SCHISM_hgrid_node_y'][:]\nself.nodeids = np.arange(len(self.lon))\nself.nv = self.ncv['SCHISM_hgrid_face_nodes'][:, :3] - 1\nself.time... | <|body_start_0|>
import netCDF4
from netcdftime import utime
self.nc = netCDF4.Dataset(filename)
self.ncv = self.nc.variables
self.lon = self.ncv['SCHISM_hgrid_node_x'][:]
self.lat = self.ncv['SCHISM_hgrid_node_y'][:]
self.nodeids = np.arange(len(self.lon))
... | schism_output | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class schism_output:
def __init__(self, filename):
"""read output filename and initialize grid"""
<|body_0|>
def init_node_tree(self, latlon=True):
"""build a node tree using cKDTree for a quick search for node coordinates"""
<|body_1|>
def find_nearest_node(s... | stack_v2_sparse_classes_10k_train_001045 | 19,398 | no_license | [
{
"docstring": "read output filename and initialize grid",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "build a node tree using cKDTree for a quick search for node coordinates",
"name": "init_node_tree",
"signature": "def init_node_tree(self, latlon=... | 3 | stack_v2_sparse_classes_30k_train_002100 | Implement the Python class `schism_output` described below.
Class description:
Implement the schism_output class.
Method signatures and docstrings:
- def __init__(self, filename): read output filename and initialize grid
- def init_node_tree(self, latlon=True): build a node tree using cKDTree for a quick search for n... | Implement the Python class `schism_output` described below.
Class description:
Implement the schism_output class.
Method signatures and docstrings:
- def __init__(self, filename): read output filename and initialize grid
- def init_node_tree(self, latlon=True): build a node tree using cKDTree for a quick search for n... | 1828b3be0531d38171e5d16f77c1c422033adb2e | <|skeleton|>
class schism_output:
def __init__(self, filename):
"""read output filename and initialize grid"""
<|body_0|>
def init_node_tree(self, latlon=True):
"""build a node tree using cKDTree for a quick search for node coordinates"""
<|body_1|>
def find_nearest_node(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class schism_output:
def __init__(self, filename):
"""read output filename and initialize grid"""
import netCDF4
from netcdftime import utime
self.nc = netCDF4.Dataset(filename)
self.ncv = self.nc.variables
self.lon = self.ncv['SCHISM_hgrid_node_x'][:]
self.la... | the_stack_v2_python_sparse | scripts/schism.py | hofmeist/schism-setups | train | 0 | |
bd55fc42feba492079bc822c9fd158e63c24c03d | [
"if db_field.name == 'groups':\n kwargs['queryset'] = Group.objects.exclude(Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='collections_'))\nreturn super(OSFUserAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)",
"groups_to_... | <|body_start_0|>
if db_field.name == 'groups':
kwargs['queryset'] = Group.objects.exclude(Q(name__startswith='preprint_') | Q(name__startswith='node_') | Q(name__startswith='osfgroup_') | Q(name__startswith='collections_'))
return super(OSFUserAdmin, self).formfield_for_manytomany(db_field, ... | OSFUserAdmin | [
"Apache-2.0",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"MIT",
"AGPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.1",
"CPAL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSFUserAdmin:
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Restricts preprint/node/osfgroup django groups from showing up in the user's groups list in the admin app"""
<|body_0|>
def save_related(self, request, form, formsets, change):
"""Since... | stack_v2_sparse_classes_10k_train_001046 | 2,154 | permissive | [
{
"docstring": "Restricts preprint/node/osfgroup django groups from showing up in the user's groups list in the admin app",
"name": "formfield_for_manytomany",
"signature": "def formfield_for_manytomany(self, db_field, request, **kwargs)"
},
{
"docstring": "Since m2m fields overridden with new f... | 2 | stack_v2_sparse_classes_30k_train_003128 | Implement the Python class `OSFUserAdmin` described below.
Class description:
Implement the OSFUserAdmin class.
Method signatures and docstrings:
- def formfield_for_manytomany(self, db_field, request, **kwargs): Restricts preprint/node/osfgroup django groups from showing up in the user's groups list in the admin app... | Implement the Python class `OSFUserAdmin` described below.
Class description:
Implement the OSFUserAdmin class.
Method signatures and docstrings:
- def formfield_for_manytomany(self, db_field, request, **kwargs): Restricts preprint/node/osfgroup django groups from showing up in the user's groups list in the admin app... | 5d632eb6d4566d7d31cd8d6b40d1bc93c60ddf5e | <|skeleton|>
class OSFUserAdmin:
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Restricts preprint/node/osfgroup django groups from showing up in the user's groups list in the admin app"""
<|body_0|>
def save_related(self, request, form, formsets, change):
"""Since... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OSFUserAdmin:
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Restricts preprint/node/osfgroup django groups from showing up in the user's groups list in the admin app"""
if db_field.name == 'groups':
kwargs['queryset'] = Group.objects.exclude(Q(name__startswith... | the_stack_v2_python_sparse | osf/admin.py | RCOSDP/RDM-osf.io | train | 12 | |
7fb69c58d063942ff64362d346c70be87e0cb7dd | [
"res = ''\nwhile n:\n res += str(n % 2)\n n //= 2\nreturn res[::-1]",
"m = 0\nwhile n:\n m += 1\n n = n & n - 1\nreturn m",
"m = 0\nflag = 1\nwhile n >= flag:\n if not n & flag:\n m += 1\n flag = flag << 1\nreturn m",
"m = 0\nflag = 2 ** 7\nwhile flag:\n if n & flag:\n break... | <|body_start_0|>
res = ''
while n:
res += str(n % 2)
n //= 2
return res[::-1]
<|end_body_0|>
<|body_start_1|>
m = 0
while n:
m += 1
n = n & n - 1
return m
<|end_body_1|>
<|body_start_2|>
m = 0
flag = 1
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def int2binaryStr(self, n: int):
"""整型int到二进制字符串"""
<|body_0|>
def nOneOfInt(self, n: int):
"""二进制中1的个数"""
<|body_1|>
def nZeroOfInt(self, n: int):
"""二进制中0的个数"""
<|body_2|>
def nZeroOfInt2(self, n: int):
"""8位二进制中0... | stack_v2_sparse_classes_10k_train_001047 | 1,382 | permissive | [
{
"docstring": "整型int到二进制字符串",
"name": "int2binaryStr",
"signature": "def int2binaryStr(self, n: int)"
},
{
"docstring": "二进制中1的个数",
"name": "nOneOfInt",
"signature": "def nOneOfInt(self, n: int)"
},
{
"docstring": "二进制中0的个数",
"name": "nZeroOfInt",
"signature": "def nZero... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def int2binaryStr(self, n: int): 整型int到二进制字符串
- def nOneOfInt(self, n: int): 二进制中1的个数
- def nZeroOfInt(self, n: int): 二进制中0的个数
- def nZeroOfInt2(self, n: int): 8位二进制中0的个数:从左开始零的个... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def int2binaryStr(self, n: int): 整型int到二进制字符串
- def nOneOfInt(self, n: int): 二进制中1的个数
- def nZeroOfInt(self, n: int): 二进制中0的个数
- def nZeroOfInt2(self, n: int): 8位二进制中0的个数:从左开始零的个... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def int2binaryStr(self, n: int):
"""整型int到二进制字符串"""
<|body_0|>
def nOneOfInt(self, n: int):
"""二进制中1的个数"""
<|body_1|>
def nZeroOfInt(self, n: int):
"""二进制中0的个数"""
<|body_2|>
def nZeroOfInt2(self, n: int):
"""8位二进制中0... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def int2binaryStr(self, n: int):
"""整型int到二进制字符串"""
res = ''
while n:
res += str(n % 2)
n //= 2
return res[::-1]
def nOneOfInt(self, n: int):
"""二进制中1的个数"""
m = 0
while n:
m += 1
n = n & n - ... | the_stack_v2_python_sparse | special/bit-opt.py | yuenliou/leetcode | train | 0 | |
761272e4bae642101536d2b152537f144ed6d25c | [
"reply = await message.get_reply_message()\nif not reply or not reply.message:\n await message.edit('<b>Reply to text!</b>')\n return\ntext = bytes(reply.raw_text, 'utf8')\nfname = utils.get_args_raw(message) or str(message.id + reply.id) + '.txt'\nfile = io.BytesIO(text)\nfile.name = fname\nfile.seek(0)\nawa... | <|body_start_0|>
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit('<b>Reply to text!</b>')
return
text = bytes(reply.raw_text, 'utf8')
fname = utils.get_args_raw(message) or str(message.id + reply.id) + '.txt'
... | send Message as file | MTFMod | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTFMod:
"""send Message as file"""
async def mtfcmd(self, message):
""".mtf <reply to text>"""
<|body_0|>
async def ftmcmd(self, message):
""".ftm <reply to file>"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
reply = await message.get_reply_me... | stack_v2_sparse_classes_10k_train_001048 | 1,000 | no_license | [
{
"docstring": ".mtf <reply to text>",
"name": "mtfcmd",
"signature": "async def mtfcmd(self, message)"
},
{
"docstring": ".ftm <reply to file>",
"name": "ftmcmd",
"signature": "async def ftmcmd(self, message)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000101 | Implement the Python class `MTFMod` described below.
Class description:
send Message as file
Method signatures and docstrings:
- async def mtfcmd(self, message): .mtf <reply to text>
- async def ftmcmd(self, message): .ftm <reply to file> | Implement the Python class `MTFMod` described below.
Class description:
send Message as file
Method signatures and docstrings:
- async def mtfcmd(self, message): .mtf <reply to text>
- async def ftmcmd(self, message): .ftm <reply to file>
<|skeleton|>
class MTFMod:
"""send Message as file"""
async def mtfcm... | d9d859ea0ed7f66bb23a6a06d1efa4c8bce9b846 | <|skeleton|>
class MTFMod:
"""send Message as file"""
async def mtfcmd(self, message):
""".mtf <reply to text>"""
<|body_0|>
async def ftmcmd(self, message):
""".ftm <reply to file>"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MTFMod:
"""send Message as file"""
async def mtfcmd(self, message):
""".mtf <reply to text>"""
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit('<b>Reply to text!</b>')
return
text = bytes(reply.raw_tex... | the_stack_v2_python_sparse | MTF.py | abdula2003/modules | train | 0 |
05d5e58eecd206a5be107e6939df042a2ec5d78b | [
"super(ItemModelMLP, self).__init__()\nself._input_embedding_dimension = input_embedding_dimension\nself.item_input_embedding = tf.keras.layers.Embedding(vocab_size, input_embedding_dimension, name='item_embedding', embeddings_initializer=tf.keras.initializers.RandomUniform(minval=-0.1, maxval=0.1))\nself.item_mode... | <|body_start_0|>
super(ItemModelMLP, self).__init__()
self._input_embedding_dimension = input_embedding_dimension
self.item_input_embedding = tf.keras.layers.Embedding(vocab_size, input_embedding_dimension, name='item_embedding', embeddings_initializer=tf.keras.initializers.RandomUniform(minval=... | An MLP model that can be used as an item tower. | ItemModelMLP | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemModelMLP:
"""An MLP model that can be used as an item tower."""
def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0):
"""Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user represent... | stack_v2_sparse_classes_10k_train_001049 | 2,480 | permissive | [
{
"docstring": "Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user representation. vocab_size: The vocabulary size for input tokens/items. input_embedding_dimension: The embedding dimension for input tokens/items. num_layers: Number of layers in the MLP. dropou... | 2 | stack_v2_sparse_classes_30k_train_000029 | Implement the Python class `ItemModelMLP` described below.
Class description:
An MLP model that can be used as an item tower.
Method signatures and docstrings:
- def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): Initializes the parameteric attention model. Args: out... | Implement the Python class `ItemModelMLP` described below.
Class description:
An MLP model that can be used as an item tower.
Method signatures and docstrings:
- def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0): Initializes the parameteric attention model. Args: out... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ItemModelMLP:
"""An MLP model that can be used as an item tower."""
def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0):
"""Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user represent... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ItemModelMLP:
"""An MLP model that can be used as an item tower."""
def __init__(self, output_dimension, vocab_size, input_embedding_dimension, num_layers, dropout=0.0):
"""Initializes the parameteric attention model. Args: output_dimension: The output dimension of the user representation. vocab_... | the_stack_v2_python_sparse | multiple_user_representations/models/mlp_item_model.py | Jimmy-INL/google-research | train | 1 |
c8fb98a6d62a13f31b5d565ca61de79d2ee540f7 | [
"super().__init__()\nself.register_buffer('unpool_mat', torch.from_numpy(np.ones((2, 2), dtype='float32')))\nself.unpool_mat.unsqueeze(0)",
"input_shape = list(x.shape)\nx = x.unsqueeze(-1)\nmat = self.unpool_mat.unsqueeze(0)\nret = torch.tensordot(x, mat, dims=1)\nret = ret.permute(0, 1, 2, 4, 3, 5)\nreturn ret.... | <|body_start_0|>
super().__init__()
self.register_buffer('unpool_mat', torch.from_numpy(np.ones((2, 2), dtype='float32')))
self.unpool_mat.unsqueeze(0)
<|end_body_0|>
<|body_start_1|>
input_shape = list(x.shape)
x = x.unsqueeze(-1)
mat = self.unpool_mat.unsqueeze(0)
... | A layer to scale input by a factor of 2. This layer uses Kronecker product underneath rather than the default pytorch interpolation. | UpSample2x | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpSample2x:
"""A layer to scale input by a factor of 2. This layer uses Kronecker product underneath rather than the default pytorch interpolation."""
def __init__(self) -> None:
"""Initialize :class:`UpSample2x`."""
<|body_0|>
def forward(self, x: torch.Tensor):
... | stack_v2_sparse_classes_10k_train_001050 | 4,059 | permissive | [
{
"docstring": "Initialize :class:`UpSample2x`.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Logic for using layers defined in init. Args: x (torch.Tensor): Input images, the tensor is in the shape of NCHW. Returns: torch.Tensor: Input images upsampled by a ... | 2 | stack_v2_sparse_classes_30k_train_004283 | Implement the Python class `UpSample2x` described below.
Class description:
A layer to scale input by a factor of 2. This layer uses Kronecker product underneath rather than the default pytorch interpolation.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize :class:`UpSample2x`.
- def forward... | Implement the Python class `UpSample2x` described below.
Class description:
A layer to scale input by a factor of 2. This layer uses Kronecker product underneath rather than the default pytorch interpolation.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize :class:`UpSample2x`.
- def forward... | f26387f46f675a7b9a8a48c95dad26e819229f2f | <|skeleton|>
class UpSample2x:
"""A layer to scale input by a factor of 2. This layer uses Kronecker product underneath rather than the default pytorch interpolation."""
def __init__(self) -> None:
"""Initialize :class:`UpSample2x`."""
<|body_0|>
def forward(self, x: torch.Tensor):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpSample2x:
"""A layer to scale input by a factor of 2. This layer uses Kronecker product underneath rather than the default pytorch interpolation."""
def __init__(self) -> None:
"""Initialize :class:`UpSample2x`."""
super().__init__()
self.register_buffer('unpool_mat', torch.from... | the_stack_v2_python_sparse | tiatoolbox/models/architecture/utils.py | TissueImageAnalytics/tiatoolbox | train | 222 |
7a46c0bd0e12585f6d99073dee22f0e9bfc94f49 | [
"if isinstance(key, int):\n return Setting(key)\nif key not in Setting._member_map_:\n extend_enum(Setting, key, default)\nreturn Setting[key]",
"if not (isinstance(value, int) and 0 <= value <= 65535):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 9 <= value <= 15:\n extend_e... | <|body_start_0|>
if isinstance(key, int):
return Setting(key)
if key not in Setting._member_map_:
extend_enum(Setting, key, default)
return Setting[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 65535):
raise Val... | [Setting] HTTP/2 Settings | Setting | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Setting:
"""[Setting] HTTP/2 Settings"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_001051 | 2,159 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000863 | Implement the Python class `Setting` described below.
Class description:
[Setting] HTTP/2 Settings
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `Setting` described below.
Class description:
[Setting] HTTP/2 Settings
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skeleton|>
class Setting:
"""[Setting]... | 71363d7948003fec88cedcf5bc80b6befa2ba244 | <|skeleton|>
class Setting:
"""[Setting] HTTP/2 Settings"""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Setting:
"""[Setting] HTTP/2 Settings"""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Setting(key)
if key not in Setting._member_map_:
extend_enum(Setting, key, default)
return Setting[key]
... | the_stack_v2_python_sparse | pcapkit/const/http/setting.py | hiok2000/PyPCAPKit | train | 0 |
dfd23da41dd63393803aa00f5af8d6519239947b | [
"if v <= 0:\n raise ValueError('max_tokens must be a positive integer')\nreturn v",
"model = available_models[self.model_name.value]\nkwargs = model._lc_kwargs\nsecrets = {secret: getattr(model, secret) for secret in model.lc_secrets.keys()}\nkwargs.update(secrets)\nmodel_kwargs = kwargs.get('model_kwargs', {}... | <|body_start_0|>
if v <= 0:
raise ValueError('max_tokens must be a positive integer')
return v
<|end_body_0|>
<|body_start_1|>
model = available_models[self.model_name.value]
kwargs = model._lc_kwargs
secrets = {secret: getattr(model, secret) for secret in model.lc_s... | OpenAI LLM configuration. | OpenAIModelConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenAIModelConfig:
"""OpenAI LLM configuration."""
def max_tokens_must_be_positive(cls, v):
"""Validate that max_tokens is a positive integer."""
<|body_0|>
def get_model(self) -> BaseLanguageModel:
"""Get the model from the configuration. Returns: BaseLanguageMo... | stack_v2_sparse_classes_10k_train_001052 | 12,618 | no_license | [
{
"docstring": "Validate that max_tokens is a positive integer.",
"name": "max_tokens_must_be_positive",
"signature": "def max_tokens_must_be_positive(cls, v)"
},
{
"docstring": "Get the model from the configuration. Returns: BaseLanguageModel: The model.",
"name": "get_model",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_001815 | Implement the Python class `OpenAIModelConfig` described below.
Class description:
OpenAI LLM configuration.
Method signatures and docstrings:
- def max_tokens_must_be_positive(cls, v): Validate that max_tokens is a positive integer.
- def get_model(self) -> BaseLanguageModel: Get the model from the configuration. Re... | Implement the Python class `OpenAIModelConfig` described below.
Class description:
OpenAI LLM configuration.
Method signatures and docstrings:
- def max_tokens_must_be_positive(cls, v): Validate that max_tokens is a positive integer.
- def get_model(self) -> BaseLanguageModel: Get the model from the configuration. Re... | 616cec5c43a0757495a4134c0c325e46a0b18d3b | <|skeleton|>
class OpenAIModelConfig:
"""OpenAI LLM configuration."""
def max_tokens_must_be_positive(cls, v):
"""Validate that max_tokens is a positive integer."""
<|body_0|>
def get_model(self) -> BaseLanguageModel:
"""Get the model from the configuration. Returns: BaseLanguageMo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpenAIModelConfig:
"""OpenAI LLM configuration."""
def max_tokens_must_be_positive(cls, v):
"""Validate that max_tokens is a positive integer."""
if v <= 0:
raise ValueError('max_tokens must be a positive integer')
return v
def get_model(self) -> BaseLanguageModel... | the_stack_v2_python_sparse | module_text_llm/module_text_llm/helpers/models/openai.py | ls1intum/Athena | train | 11 |
5e8a2e6bd65e8d78ae00f475c693e4d22231964c | [
"super().__init__(order=CallbackOrder.external)\nif mode not in ['best', 'last']:\n raise ValueError(f\"Unknown `mode` '{mode}'. Must be 'best' or 'last'\")\nself.metric = metric\nself.mode = mode\nself.do_once = do_once\nself.best_score = None\nself.is_better = None\nself.first_time = True\nif minimize:\n se... | <|body_start_0|>
super().__init__(order=CallbackOrder.external)
if mode not in ['best', 'last']:
raise ValueError(f"Unknown `mode` '{mode}'. Must be 'best' or 'last'")
self.metric = metric
self.mode = mode
self.do_once = do_once
self.best_score = None
... | Dynamic Quantization Callback This callback applying dynamic quantization to the model. | DynamicQuantizationCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicQuantizationCallback:
"""Dynamic Quantization Callback This callback applying dynamic quantization to the model."""
def __init__(self, metric: str='loss', minimize: bool=True, min_delta: float=1e-06, mode: str='best', do_once: bool=True, qconfig_spec: Optional[Union[Set, Dict]]=None, ... | stack_v2_sparse_classes_10k_train_001053 | 5,000 | permissive | [
{
"docstring": "Init method for callback Args: metric: Metric key we should trace model based on minimize: Whether do we minimize metric or not min_delta: Minimum value of change for metric to be considered as improved mode: One of `best` or `last` do_once: Whether do we trace once per stage or every epoch qcon... | 3 | stack_v2_sparse_classes_30k_train_004744 | Implement the Python class `DynamicQuantizationCallback` described below.
Class description:
Dynamic Quantization Callback This callback applying dynamic quantization to the model.
Method signatures and docstrings:
- def __init__(self, metric: str='loss', minimize: bool=True, min_delta: float=1e-06, mode: str='best',... | Implement the Python class `DynamicQuantizationCallback` described below.
Class description:
Dynamic Quantization Callback This callback applying dynamic quantization to the model.
Method signatures and docstrings:
- def __init__(self, metric: str='loss', minimize: bool=True, min_delta: float=1e-06, mode: str='best',... | 8ce39fc31635eabc348b055a2df8ec8bc5700dce | <|skeleton|>
class DynamicQuantizationCallback:
"""Dynamic Quantization Callback This callback applying dynamic quantization to the model."""
def __init__(self, metric: str='loss', minimize: bool=True, min_delta: float=1e-06, mode: str='best', do_once: bool=True, qconfig_spec: Optional[Union[Set, Dict]]=None, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DynamicQuantizationCallback:
"""Dynamic Quantization Callback This callback applying dynamic quantization to the model."""
def __init__(self, metric: str='loss', minimize: bool=True, min_delta: float=1e-06, mode: str='best', do_once: bool=True, qconfig_spec: Optional[Union[Set, Dict]]=None, dtype: Option... | the_stack_v2_python_sparse | catalyst/callbacks/quantization.py | 418sec/catalyst | train | 0 |
f41d9aa5ce5dcd04cc01b1109a73dcee668ac3df | [
"super(Decoder, self).__init__()\nself.batch_size = batch_size\nself.dec_units = dec_units\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)\nself.gru = tf.keras.layers.GRU(units=self.dec_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform... | <|body_start_0|>
super(Decoder, self).__init__()
self.batch_size = batch_size
self.dec_units = dec_units
self.embedding = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim)
self.gru = tf.keras.layers.GRU(units=self.dec_units, return_sequences=True, return_s... | The decoder model. | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""The decoder model."""
def __init__(self, vocab_size, embedding_dim, dec_units, batch_size):
"""The structure function. Args: vocab_size: The target language vocabulary size. embedding_dim: The embedding dimension. dec_units: The decoder hidden units. batch_size: The batch... | stack_v2_sparse_classes_10k_train_001054 | 20,417 | no_license | [
{
"docstring": "The structure function. Args: vocab_size: The target language vocabulary size. embedding_dim: The embedding dimension. dec_units: The decoder hidden units. batch_size: The batch size.",
"name": "__init__",
"signature": "def __init__(self, vocab_size, embedding_dim, dec_units, batch_size)... | 2 | stack_v2_sparse_classes_30k_train_004937 | Implement the Python class `Decoder` described below.
Class description:
The decoder model.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, dec_units, batch_size): The structure function. Args: vocab_size: The target language vocabulary size. embedding_dim: The embedding dimension. d... | Implement the Python class `Decoder` described below.
Class description:
The decoder model.
Method signatures and docstrings:
- def __init__(self, vocab_size, embedding_dim, dec_units, batch_size): The structure function. Args: vocab_size: The target language vocabulary size. embedding_dim: The embedding dimension. d... | d1b70b2a954f4665b628ba252b03c1a74b95559f | <|skeleton|>
class Decoder:
"""The decoder model."""
def __init__(self, vocab_size, embedding_dim, dec_units, batch_size):
"""The structure function. Args: vocab_size: The target language vocabulary size. embedding_dim: The embedding dimension. dec_units: The decoder hidden units. batch_size: The batch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Decoder:
"""The decoder model."""
def __init__(self, vocab_size, embedding_dim, dec_units, batch_size):
"""The structure function. Args: vocab_size: The target language vocabulary size. embedding_dim: The embedding dimension. dec_units: The decoder hidden units. batch_size: The batch size."""
... | the_stack_v2_python_sparse | NeuralNetworks-tensorflow/RNN/nmt_with_attention/nmt.py | zhaocc1106/machine_learn | train | 15 |
90f1b0df8e7a084a641605e530906a2c8078e3cb | [
"desired_samples = model_settings['desired_samples']\nself.wav_filename_placeholder_ = tf.placeholder(tf.string, [])\nwav_loader = io_ops.read_file(self.wav_filename_placeholder_)\nwav_decoder = contrib_audio.decode_wav(wav_loader, desired_channels=1, desired_samples=desired_samples)\nself.foreground_volume_placeho... | <|body_start_0|>
desired_samples = model_settings['desired_samples']
self.wav_filename_placeholder_ = tf.placeholder(tf.string, [])
wav_loader = io_ops.read_file(self.wav_filename_placeholder_)
wav_decoder = contrib_audio.decode_wav(wav_loader, desired_channels=1, desired_samples=desired... | AudioProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AudioProcessor:
def prepare_processing_graph(self, model_settings):
"""Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scales the volume, shifts it in time, adds in background noise, calculates a spectrogram, and then builds a... | stack_v2_sparse_classes_10k_train_001055 | 7,375 | no_license | [
{
"docstring": "Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scales the volume, shifts it in time, adds in background noise, calculates a spectrogram, and then builds an MFCC fingerprint from that. This must be called with an active TensorFlow ses... | 3 | stack_v2_sparse_classes_30k_train_005526 | Implement the Python class `AudioProcessor` described below.
Class description:
Implement the AudioProcessor class.
Method signatures and docstrings:
- def prepare_processing_graph(self, model_settings): Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scal... | Implement the Python class `AudioProcessor` described below.
Class description:
Implement the AudioProcessor class.
Method signatures and docstrings:
- def prepare_processing_graph(self, model_settings): Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scal... | 053e5842ada4a6e0b63b9a6281bf823b15b1d645 | <|skeleton|>
class AudioProcessor:
def prepare_processing_graph(self, model_settings):
"""Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scales the volume, shifts it in time, adds in background noise, calculates a spectrogram, and then builds a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AudioProcessor:
def prepare_processing_graph(self, model_settings):
"""Builds a TensorFlow graph to apply the input distortions. Creates a graph that loads a WAVE file, decodes it, scales the volume, shifts it in time, adds in background noise, calculates a spectrogram, and then builds an MFCC fingerp... | the_stack_v2_python_sparse | 呼吸声音识别呼吸系统疾病/src/audio_processor.py | yphacker/ai_yanxishe | train | 30 | |
6de0436abd47ba94fac9bb05fdbe77550bf7c91f | [
"super().__init__(*args, **kargs)\nself.set_field_from_dict('email_to')\nself.order_fields(['email_to', 'subject', 'cc_email', 'bcc_email', 'export_wf'])",
"form_data = super().clean()\nself.store_field_in_dict('email_to')\nif not is_correct_email(form_data['email_to']):\n self.add_error('email_to', _('Field n... | <|body_start_0|>
super().__init__(*args, **kargs)
self.set_field_from_dict('email_to')
self.order_fields(['email_to', 'subject', 'cc_email', 'bcc_email', 'export_wf'])
<|end_body_0|>
<|body_start_1|>
form_data = super().clean()
self.store_field_in_dict('email_to')
if not... | Form to edit the Send Email action. | SendListActionForm | [
"MIT",
"LGPL-2.0-or-later",
"Python-2.0",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendListActionForm:
"""Form to edit the Send Email action."""
def __init__(self, *args, **kargs):
"""Sort the fields."""
<|body_0|>
def clean(self):
"""Verify recipient email value"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__... | stack_v2_sparse_classes_10k_train_001056 | 20,237 | permissive | [
{
"docstring": "Sort the fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kargs)"
},
{
"docstring": "Verify recipient email value",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004553 | Implement the Python class `SendListActionForm` described below.
Class description:
Form to edit the Send Email action.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Sort the fields.
- def clean(self): Verify recipient email value | Implement the Python class `SendListActionForm` described below.
Class description:
Form to edit the Send Email action.
Method signatures and docstrings:
- def __init__(self, *args, **kargs): Sort the fields.
- def clean(self): Verify recipient email value
<|skeleton|>
class SendListActionForm:
"""Form to edit t... | 5473e9faa24c71a2a1102d47ebc2cbf27608e42a | <|skeleton|>
class SendListActionForm:
"""Form to edit the Send Email action."""
def __init__(self, *args, **kargs):
"""Sort the fields."""
<|body_0|>
def clean(self):
"""Verify recipient email value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SendListActionForm:
"""Form to edit the Send Email action."""
def __init__(self, *args, **kargs):
"""Sort the fields."""
super().__init__(*args, **kargs)
self.set_field_from_dict('email_to')
self.order_fields(['email_to', 'subject', 'cc_email', 'bcc_email', 'export_wf'])
... | the_stack_v2_python_sparse | ontask/action/forms/run.py | LucasFranciscoCorreia/ontask_b | train | 0 |
187028f13021e96f2fb9973a4c1e2a86b9b7bc96 | [
"res, index, stack = (0, 0, [])\nfor i, char in enumerate(s):\n if char == '(':\n stack.append(i)\n elif not stack:\n index = i + 1\n else:\n stack.pop()\n if stack:\n res = max(res, i - stack[-1])\n else:\n res = max(res, i - index + 1)\nreturn res"... | <|body_start_0|>
res, index, stack = (0, 0, [])
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif not stack:
index = i + 1
else:
stack.pop()
if stack:
res = max(res, i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res, index, stack = (0, 0, [])
for i... | stack_v2_sparse_classes_10k_train_001057 | 1,446 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses",
"signature": "def longestValidParentheses(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestValidParentheses1",
"signature": "def longestValidParentheses1(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003165 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses1(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses(self, s): :type s: str :rtype: int
- def longestValidParentheses1(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestVal... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestValidParentheses1(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParentheses(self, s):
""":type s: str :rtype: int"""
res, index, stack = (0, 0, [])
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif not stack:
index = i + 1
else:
... | the_stack_v2_python_sparse | leetcode/032最长有效括号.py | ShawDa/Coding | train | 0 | |
29667247d22dc35991c80e31164ebd04f75b36f4 | [
"pil_format = self.pil_format(**kwargs)\nfor av_frame in av_frame_seq:\n plane = av_frame.planes[0]\n image = Image.frombuffer(pil_format, (av_frame.width, av_frame.height), plane, 'raw', pil_format, 0, 1)\n yield image",
"av_format = self.av_format(**kwargs)\nif pil_format is None:\n pil_format = AV2... | <|body_start_0|>
pil_format = self.pil_format(**kwargs)
for av_frame in av_frame_seq:
plane = av_frame.planes[0]
image = Image.frombuffer(pil_format, (av_frame.width, av_frame.height), plane, 'raw', pil_format, 0, 1)
yield image
<|end_body_0|>
<|body_start_1|>
... | ... | ImageBased | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageBased:
"""..."""
def frame_images(self, av_frame_seq, **kwargs):
""":type av_frame_seq: collections.Iterable :param av_frame_seq: :return:"""
<|body_0|>
def pil_format(self, pil_format=None, **kwargs):
""":param pil_format: :param kwargs: :return:"""
... | stack_v2_sparse_classes_10k_train_001058 | 1,907 | permissive | [
{
"docstring": ":type av_frame_seq: collections.Iterable :param av_frame_seq: :return:",
"name": "frame_images",
"signature": "def frame_images(self, av_frame_seq, **kwargs)"
},
{
"docstring": ":param pil_format: :param kwargs: :return:",
"name": "pil_format",
"signature": "def pil_forma... | 4 | stack_v2_sparse_classes_30k_train_006875 | Implement the Python class `ImageBased` described below.
Class description:
...
Method signatures and docstrings:
- def frame_images(self, av_frame_seq, **kwargs): :type av_frame_seq: collections.Iterable :param av_frame_seq: :return:
- def pil_format(self, pil_format=None, **kwargs): :param pil_format: :param kwargs... | Implement the Python class `ImageBased` described below.
Class description:
...
Method signatures and docstrings:
- def frame_images(self, av_frame_seq, **kwargs): :type av_frame_seq: collections.Iterable :param av_frame_seq: :return:
- def pil_format(self, pil_format=None, **kwargs): :param pil_format: :param kwargs... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class ImageBased:
"""..."""
def frame_images(self, av_frame_seq, **kwargs):
""":type av_frame_seq: collections.Iterable :param av_frame_seq: :return:"""
<|body_0|>
def pil_format(self, pil_format=None, **kwargs):
""":param pil_format: :param kwargs: :return:"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageBased:
"""..."""
def frame_images(self, av_frame_seq, **kwargs):
""":type av_frame_seq: collections.Iterable :param av_frame_seq: :return:"""
pil_format = self.pil_format(**kwargs)
for av_frame in av_frame_seq:
plane = av_frame.planes[0]
image = Image.... | the_stack_v2_python_sparse | shot_detector/features/extractors/image_based.py | w495/python-video-shot-detector | train | 20 |
ba41479e5b95d63fd5f72590ed9929bcf26ac00c | [
"diff = defaultdict(int)\nfor left, right in flowers:\n diff[left] += 1\n diff[right + 1] -= 1\nkeys = sorted(diff)\ndiff = list(accumulate((diff[key] for key in keys), initial=0))\nreturn [diff[bisect_right(keys, p)] for p in persons]",
"D = Discretizer()\nfor left, right in flowers:\n D.add(left)\n ... | <|body_start_0|>
diff = defaultdict(int)
for left, right in flowers:
diff[left] += 1
diff[right + 1] -= 1
keys = sorted(diff)
diff = list(accumulate((diff[key] for key in keys), initial=0))
return [diff[bisect_right(keys, p)] for p in persons]
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
"""单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥"""
<|body_0|>
def fullBloomFlowers2(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
"""单点查询时:如果同时也把person添加到离散... | stack_v2_sparse_classes_10k_train_001059 | 1,793 | no_license | [
{
"docstring": "单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥",
"name": "fullBloomFlowers",
"signature": "def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]"
},
{
"docstring": "单点查询时:如果同时也把person添加到离散化,就不用二分查找了/不用开字典了",
"name": "fullBloomFlowers2",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_001518 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: 单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥
- def fullBloomFlowers2(self, flowers: List[List[int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]: 单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥
- def fullBloomFlowers2(self, flowers: List[List[int... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
"""单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥"""
<|body_0|>
def fullBloomFlowers2(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
"""单点查询时:如果同时也把person添加到离散... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
"""单点查询时:只对flowers离散化,开字典+二分查找query值被映射成啥"""
diff = defaultdict(int)
for left, right in flowers:
diff[left] += 1
diff[right + 1] -= 1
keys = sorted(diff)
... | the_stack_v2_python_sparse | 22_专题/前缀与差分/差分数组/离散化/6044. 花期内花的数目-单点查询-差分+离散化.py | 981377660LMT/algorithm-study | train | 225 | |
e9467da874a3d25fc155315bfa2722f9824ef0b9 | [
"super(LSTMDiscriminator, self).__init__()\nself.hidden_dim = hidden_dim\nself.layer_dim = 2\ninput_dim = 2 * obs_dim + act_dim\nself.lstm = nn.LSTM(input_dim, hidden_dim, self.layer_dim, batch_first=True)\nself.fc = nn.Linear(hidden_dim, 1)",
"x = x.unsqueeze(0)\nh0 = to.zeros(self.layer_dim, x.size(0), self.hid... | <|body_start_0|>
super(LSTMDiscriminator, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = 2
input_dim = 2 * obs_dim + act_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, self.layer_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, 1)
<|end_body_0|>
<|b... | LSTM-based discriminator | LSTMDiscriminator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
<|body_0|>
def... | stack_v2_sparse_classes_10k_train_001060 | 6,086 | permissive | [
{
"docstring": "Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size",
"name": "__init__",
"signature": "def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128)"
},
{
"docstring": ":param x: A Tensor which... | 2 | null | Implement the Python class `LSTMDiscriminator` described below.
Class description:
LSTM-based discriminator
Method signatures and docstrings:
- def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128): Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hid... | Implement the Python class `LSTMDiscriminator` described below.
Class description:
LSTM-based discriminator
Method signatures and docstrings:
- def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128): Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hid... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
<|body_0|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LSTMDiscriminator:
"""LSTM-based discriminator"""
def __init__(self, obs_dim: int, act_dim: int, hidden_dim: int=128):
"""Constructor :param obs_dim: observation space dimension :param act_dim: action space dimension :param hidden_dim: hidden layer size"""
super(LSTMDiscriminator, self)._... | the_stack_v2_python_sparse | Pyrado/pyrado/algorithms/adr_discriminator.py | jacarvalho/SimuRLacra | train | 0 |
0cec5c6ceb1df809854e5dd36576a5b0c1e6acc7 | [
"super(COMA, self).__init__()\naction_shape = squeeze(action_shape)\nactor_input_size = squeeze(obs_shape['agent_state'])\ncritic_input_size = squeeze(obs_shape['agent_state']) + squeeze(obs_shape['global_state']) + agent_num * action_shape + (agent_num - 1) * action_shape\ncritic_hidden_size = actor_hidden_size_li... | <|body_start_0|>
super(COMA, self).__init__()
action_shape = squeeze(action_shape)
actor_input_size = squeeze(obs_shape['agent_state'])
critic_input_size = squeeze(obs_shape['agent_state']) + squeeze(obs_shape['global_state']) + agent_num * action_shape + (agent_num - 1) * action_shape
... | Overview: COMA network is QAC-type actor-critic. | COMA | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COMA:
"""Overview: COMA network is QAC-type actor-critic."""
def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None:
"""Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number... | stack_v2_sparse_classes_10k_train_001061 | 7,790 | permissive | [
{
"docstring": "Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number of agent - obs_shape (:obj:`Dict`): the observation information, including agent_state and global_state - action_shape (:obj:`Union[int, SequenceType]`): the dimension of action shape - actor_hidden_size_list (:obj... | 2 | stack_v2_sparse_classes_30k_train_006140 | Implement the Python class `COMA` described below.
Class description:
Overview: COMA network is QAC-type actor-critic.
Method signatures and docstrings:
- def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None: Overview: initialize COM... | Implement the Python class `COMA` described below.
Class description:
Overview: COMA network is QAC-type actor-critic.
Method signatures and docstrings:
- def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None: Overview: initialize COM... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class COMA:
"""Overview: COMA network is QAC-type actor-critic."""
def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None:
"""Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class COMA:
"""Overview: COMA network is QAC-type actor-critic."""
def __init__(self, agent_num: int, obs_shape: Dict, action_shape: Union[int, SequenceType], actor_hidden_size_list: SequenceType) -> None:
"""Overview: initialize COMA network Arguments: - agent_num (:obj:`int`): the number of agent - o... | the_stack_v2_python_sparse | ding/model/template/coma.py | shengxuesun/DI-engine | train | 1 |
ec0e29b35151c9d2df8589121a6d5d3cbfb73e8b | [
"self.message_history_reached_end = False\nself._message_history_collector = None\nself._message_keep_limit = message_keep_limit\nself.messages = None",
"if self._message_keep_limit != message_keep_limit:\n if message_keep_limit == 0:\n new_messages = None\n else:\n old_messages = self.message... | <|body_start_0|>
self.message_history_reached_end = False
self._message_history_collector = None
self._message_keep_limit = message_keep_limit
self.messages = None
<|end_body_0|>
<|body_start_1|>
if self._message_keep_limit != message_keep_limit:
if message_keep_limi... | Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the channel's message history. message_history_r... | MessageHistory | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageHistory:
"""Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the ch... | stack_v2_sparse_classes_10k_train_001062 | 6,011 | permissive | [
{
"docstring": "Creates a nwe message history instance with it's default values. Parameters ---------- message_keep_limit : `int` The amount of messages to keep.",
"name": "__init__",
"signature": "def __init__(self, message_keep_limit)"
},
{
"docstring": "Sets the amount of messages to keep by ... | 2 | null | Implement the Python class `MessageHistory` described below.
Class description:
Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``Message... | Implement the Python class `MessageHistory` described below.
Class description:
Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``Message... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class MessageHistory:
"""Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the ch... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MessageHistory:
"""Contains message logic for message-able channels. Attributes ---------- _message_keep_limit : `int` The channel's own limit of how much messages it should keep before removing their reference. _message_history_collector : `None`, ``MessageHistoryCollector`` Collector for the channel's messa... | the_stack_v2_python_sparse | hata/discord/channel/message_history.py | HuyaneMatsu/hata | train | 3 |
47ab5ac4fc8f1707236e4b7c785c21d539943c9c | [
"self.instance = kwargs.pop('instance', None)\ninitial = kwargs.setdefault('initial', {})\ninitial['name'] = self.instance.name\ninitial['description'] = self.instance.description\ninitial['status'] = self.instance.status\ninitial['cc_version'] = self.instance.cc_version\ninitial['idprefix'] = self.instance.case.id... | <|body_start_0|>
self.instance = kwargs.pop('instance', None)
initial = kwargs.setdefault('initial', {})
initial['name'] = self.instance.name
initial['description'] = self.instance.description
initial['status'] = self.instance.status
initial['cc_version'] = self.instance.... | Form for editing a case version. | EditCaseVersionForm | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditCaseVersionForm:
"""Form for editing a case version."""
def __init__(self, *args, **kwargs):
"""Initialize EditCaseVersionForm, pulling instance from kwargs."""
<|body_0|>
def save(self, user=None):
"""Save the edited caseversion."""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k_train_001063 | 16,711 | permissive | [
{
"docstring": "Initialize EditCaseVersionForm, pulling instance from kwargs.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Save the edited caseversion.",
"name": "save",
"signature": "def save(self, user=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006663 | Implement the Python class `EditCaseVersionForm` described below.
Class description:
Form for editing a case version.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize EditCaseVersionForm, pulling instance from kwargs.
- def save(self, user=None): Save the edited caseversion. | Implement the Python class `EditCaseVersionForm` described below.
Class description:
Form for editing a case version.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize EditCaseVersionForm, pulling instance from kwargs.
- def save(self, user=None): Save the edited caseversion.
<|skel... | ee54db2fe8ffbf2216d359b7a093b51f2574878e | <|skeleton|>
class EditCaseVersionForm:
"""Form for editing a case version."""
def __init__(self, *args, **kwargs):
"""Initialize EditCaseVersionForm, pulling instance from kwargs."""
<|body_0|>
def save(self, user=None):
"""Save the edited caseversion."""
<|body_1|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EditCaseVersionForm:
"""Form for editing a case version."""
def __init__(self, *args, **kwargs):
"""Initialize EditCaseVersionForm, pulling instance from kwargs."""
self.instance = kwargs.pop('instance', None)
initial = kwargs.setdefault('initial', {})
initial['name'] = se... | the_stack_v2_python_sparse | moztrap/view/manage/cases/forms.py | isakib/moztrap | train | 1 |
0066c5bdefb2b716e3202f0c1b809dbbd2eebe69 | [
"self.name = name\nself.time_zone = time_zone\nself.tags = tags\nself.disable_my_meraki_com = disable_my_meraki_com\nself.disable_remote_status_page = disable_remote_status_page\nself.enrollment_string = enrollment_string",
"if dictionary is None:\n return None\nname = dictionary.get('name')\ntime_zone = dicti... | <|body_start_0|>
self.name = name
self.time_zone = time_zone
self.tags = tags
self.disable_my_meraki_com = disable_my_meraki_com
self.disable_remote_status_page = disable_remote_status_page
self.enrollment_string = enrollment_string
<|end_body_0|>
<|body_start_1|>
... | Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank' href='https://en.wikipedia.org/wiki/List_of_t... | UpdateNetworkModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkModel:
"""Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank'... | stack_v2_sparse_classes_10k_train_001064 | 3,938 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkModel class",
"name": "__init__",
"signature": "def __init__(self, name=None, time_zone=None, tags=None, disable_my_meraki_com=None, disable_remote_status_page=None, enrollment_string=None)"
},
{
"docstring": "Creates an instance of this model fro... | 2 | stack_v2_sparse_classes_30k_train_003399 | Implement the Python class `UpdateNetworkModel` described below.
Class description:
Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' co... | Implement the Python class `UpdateNetworkModel` described below.
Class description:
Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' co... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkModel:
"""Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank'... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateNetworkModel:
"""Implementation of the 'updateNetwork' model. TODO: type model description here. Attributes: name (string): The name of the network time_zone (string): The timezone of the network. For a list of allowed timezones, please see the 'TZ' column in the table in <a target='_blank' href='https:... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
77726f14fb35b59b344f72f0ad319f138d72dc35 | [
"super(StyleContentModel, self).__init__()\nself.vgg = vgg_layers(style_layers + content_layers)\nself.style_layers = style_layers\nself.content_layers = content_layers\nself.num_style_layers = len(style_layers)\nself.vgg.trainable = False",
"inputs = inputs * 255.0\npreprocessed_input = keras.applications.vgg19.... | <|body_start_0|>
super(StyleContentModel, self).__init__()
self.vgg = vgg_layers(style_layers + content_layers)
self.style_layers = style_layers
self.content_layers = content_layers
self.num_style_layers = len(style_layers)
self.vgg.trainable = False
<|end_body_0|>
<|bod... | StyleContentModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleContentModel:
def __init__(self, style_layers, content_layers):
"""style_layers: list, name of style layers content_layers: list, name of content_layers When called on an image, this model returns the gram matrix(style) of the style_layers and content of the content_layers"""
... | stack_v2_sparse_classes_10k_train_001065 | 12,741 | no_license | [
{
"docstring": "style_layers: list, name of style layers content_layers: list, name of content_layers When called on an image, this model returns the gram matrix(style) of the style_layers and content of the content_layers",
"name": "__init__",
"signature": "def __init__(self, style_layers, content_laye... | 2 | null | Implement the Python class `StyleContentModel` described below.
Class description:
Implement the StyleContentModel class.
Method signatures and docstrings:
- def __init__(self, style_layers, content_layers): style_layers: list, name of style layers content_layers: list, name of content_layers When called on an image,... | Implement the Python class `StyleContentModel` described below.
Class description:
Implement the StyleContentModel class.
Method signatures and docstrings:
- def __init__(self, style_layers, content_layers): style_layers: list, name of style layers content_layers: list, name of content_layers When called on an image,... | 5d4dbde8d570623fe785e78a3e45cd05ea80aa08 | <|skeleton|>
class StyleContentModel:
def __init__(self, style_layers, content_layers):
"""style_layers: list, name of style layers content_layers: list, name of content_layers When called on an image, this model returns the gram matrix(style) of the style_layers and content of the content_layers"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StyleContentModel:
def __init__(self, style_layers, content_layers):
"""style_layers: list, name of style layers content_layers: list, name of content_layers When called on an image, this model returns the gram matrix(style) of the style_layers and content of the content_layers"""
super(StyleC... | the_stack_v2_python_sparse | Tesnorflow2_05-12-20/11_generative/02_neural_style_transfer.py | behrouzmadahian/python | train | 1 | |
273c1bcea4facc5eaae4060f177765450ef8543c | [
"head0 = head\nfast = head\nslow = head\nfor i in range(n):\n fast = fast.next\nif fast == None:\n return slow.next\nwhile fast.next != None:\n fast = fast.next\n slow = slow.next\nslow.next = slow.next.next\nreturn head0",
"head0 = head\ntemp = []\nwhile head != None:\n temp.append(head)\n head... | <|body_start_0|>
head0 = head
fast = head
slow = head
for i in range(n):
fast = fast.next
if fast == None:
return slow.next
while fast.next != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
... | Ex19 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ex19:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd0(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
def removeNthFromStart(self, head, n)... | stack_v2_sparse_classes_10k_train_001066 | 2,727 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd0",
"signature": "def removeNthFromEnd0(sel... | 3 | null | Implement the Python class `Ex19` described below.
Class description:
Implement the Ex19 class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd0(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def r... | Implement the Python class `Ex19` described below.
Class description:
Implement the Ex19 class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd0(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def r... | 8f9327a1879949f61b462cc6c82e00e7c27b8b07 | <|skeleton|>
class Ex19:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd0(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
def removeNthFromStart(self, head, n)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ex19:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
head0 = head
fast = head
slow = head
for i in range(n):
fast = fast.next
if fast == None:
return slow.next
while fast.next != None... | the_stack_v2_python_sparse | LeetCode/Ex0/Ex19.py | JasonVann/CrackingCodingInterview | train | 0 | |
cb587ea5f14cc99afa4c13a7874e5650a86fb91c | [
"self.name = name\nself.concepts = concepts\nself.eggs = eggs",
"conceptList = ConceptList(name=self.name, concepts=self.concepts.values(), isWords=any([len(egg.words) > 0 for egg in self.eggs]))\nserver.db.session.add(conceptList)\nserver.db.session.commit()"
] | <|body_start_0|>
self.name = name
self.concepts = concepts
self.eggs = eggs
<|end_body_0|>
<|body_start_1|>
conceptList = ConceptList(name=self.name, concepts=self.concepts.values(), isWords=any([len(egg.words) > 0 for egg in self.eggs]))
server.db.session.add(conceptList)
... | Class to load a concept list into the database | ConceptListLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConceptListLoader:
"""Class to load a concept list into the database"""
def __init__(self, name, eggs, concepts):
"""Initialize the Concept List"""
<|body_0|>
def load(self):
"""Load the Concept List into the database"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_10k_train_001067 | 635 | no_license | [
{
"docstring": "Initialize the Concept List",
"name": "__init__",
"signature": "def __init__(self, name, eggs, concepts)"
},
{
"docstring": "Load the Concept List into the database",
"name": "load",
"signature": "def load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004330 | Implement the Python class `ConceptListLoader` described below.
Class description:
Class to load a concept list into the database
Method signatures and docstrings:
- def __init__(self, name, eggs, concepts): Initialize the Concept List
- def load(self): Load the Concept List into the database | Implement the Python class `ConceptListLoader` described below.
Class description:
Class to load a concept list into the database
Method signatures and docstrings:
- def __init__(self, name, eggs, concepts): Initialize the Concept List
- def load(self): Load the Concept List into the database
<|skeleton|>
class Conc... | f08dc4465b7e4fb32235e1647c46edd4472f9093 | <|skeleton|>
class ConceptListLoader:
"""Class to load a concept list into the database"""
def __init__(self, name, eggs, concepts):
"""Initialize the Concept List"""
<|body_0|>
def load(self):
"""Load the Concept List into the database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConceptListLoader:
"""Class to load a concept list into the database"""
def __init__(self, name, eggs, concepts):
"""Initialize the Concept List"""
self.name = name
self.concepts = concepts
self.eggs = eggs
def load(self):
"""Load the Concept List into the dat... | the_stack_v2_python_sparse | src/Import/concept_list_loader.py | cloew/VocabTester | train | 0 |
f94f13bdc2496c726a5ec344fef0b2274ee8e13c | [
"self.NAME = EVITA\nself.tarsqidoc = tarsqidoc\nself.docelement = docelement\nself.doctree = None\nself.imported_events = imported_events",
"self.doctree = create_tarsqi_tree(self.tarsqidoc, self.docelement)\nfor sentence in self.doctree:\n logger.debug('SENTENCE: %s' % get_words_as_string(sentence))\n for ... | <|body_start_0|>
self.NAME = EVITA
self.tarsqidoc = tarsqidoc
self.docelement = docelement
self.doctree = None
self.imported_events = imported_events
<|end_body_0|>
<|body_start_1|>
self.doctree = create_tarsqi_tree(self.tarsqidoc, self.docelement)
for sentence i... | Class that implements Evita's event recognizer. Instance variables contain the name of the component, the TarsqiDocument, a docelement Tag and a TarsqiTree instance. The TarsqiTree instance in the doctree variable is the tree for just one element and not for the whole document or string. | Evita | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evita:
"""Class that implements Evita's event recognizer. Instance variables contain the name of the component, the TarsqiDocument, a docelement Tag and a TarsqiTree instance. The TarsqiTree instance in the doctree variable is the tree for just one element and not for the whole document or string... | stack_v2_sparse_classes_10k_train_001068 | 1,998 | permissive | [
{
"docstring": "Set the NAME instance variable. The doctree variables is filled in during processing.",
"name": "__init__",
"signature": "def __init__(self, tarsqidoc, docelement, imported_events)"
},
{
"docstring": "Process the element slice of the TarsqiDocument. Loop through all sentences in ... | 2 | stack_v2_sparse_classes_30k_train_006591 | Implement the Python class `Evita` described below.
Class description:
Class that implements Evita's event recognizer. Instance variables contain the name of the component, the TarsqiDocument, a docelement Tag and a TarsqiTree instance. The TarsqiTree instance in the doctree variable is the tree for just one element a... | Implement the Python class `Evita` described below.
Class description:
Class that implements Evita's event recognizer. Instance variables contain the name of the component, the TarsqiDocument, a docelement Tag and a TarsqiTree instance. The TarsqiTree instance in the doctree variable is the tree for just one element a... | 085007047ab591426d5c08b123906c070deb6627 | <|skeleton|>
class Evita:
"""Class that implements Evita's event recognizer. Instance variables contain the name of the component, the TarsqiDocument, a docelement Tag and a TarsqiTree instance. The TarsqiTree instance in the doctree variable is the tree for just one element and not for the whole document or string... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Evita:
"""Class that implements Evita's event recognizer. Instance variables contain the name of the component, the TarsqiDocument, a docelement Tag and a TarsqiTree instance. The TarsqiTree instance in the doctree variable is the tree for just one element and not for the whole document or string."""
def... | the_stack_v2_python_sparse | components/evita/main.py | tarsqi/ttk | train | 26 |
7f001edfae9b7ece495014d399590655a5a88045 | [
"self.op_class = op_class\nself.op_arity = op_arity\nself.init_interval = init_interval\nself.renorm_function = renorm_function\nself.output_precision = output_precision\nself.input_precisions = input_precisions\nself.bench_name = bench_name",
"initial_inputs = [Constant(random.uniform(inf(self.init_interval), su... | <|body_start_0|>
self.op_class = op_class
self.op_arity = op_arity
self.init_interval = init_interval
self.renorm_function = renorm_function
self.output_precision = output_precision
self.input_precisions = input_precisions
self.bench_name = bench_name
<|end_body_0... | Operation Unitary Bench class | OpUnitBench | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpUnitBench:
"""Operation Unitary Bench class"""
def __init__(self, op_class, bench_name, op_arity=2, init_interval=Interval(-0.5, 0.5), renorm_function=lambda x: x, output_precision=ML_Binary32, input_precisions=[ML_Binary32, ML_Binary32]):
"""OpUnitBench ctor"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_001069 | 15,074 | permissive | [
{
"docstring": "OpUnitBench ctor",
"name": "__init__",
"signature": "def __init__(self, op_class, bench_name, op_arity=2, init_interval=Interval(-0.5, 0.5), renorm_function=lambda x: x, output_precision=ML_Binary32, input_precisions=[ML_Binary32, ML_Binary32])"
},
{
"docstring": "generate perfor... | 2 | null | Implement the Python class `OpUnitBench` described below.
Class description:
Operation Unitary Bench class
Method signatures and docstrings:
- def __init__(self, op_class, bench_name, op_arity=2, init_interval=Interval(-0.5, 0.5), renorm_function=lambda x: x, output_precision=ML_Binary32, input_precisions=[ML_Binary3... | Implement the Python class `OpUnitBench` described below.
Class description:
Operation Unitary Bench class
Method signatures and docstrings:
- def __init__(self, op_class, bench_name, op_arity=2, init_interval=Interval(-0.5, 0.5), renorm_function=lambda x: x, output_precision=ML_Binary32, input_precisions=[ML_Binary3... | f96b1bc33a1cffd14cc322a770835cc7435de599 | <|skeleton|>
class OpUnitBench:
"""Operation Unitary Bench class"""
def __init__(self, op_class, bench_name, op_arity=2, init_interval=Interval(-0.5, 0.5), renorm_function=lambda x: x, output_precision=ML_Binary32, input_precisions=[ML_Binary32, ML_Binary32]):
"""OpUnitBench ctor"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OpUnitBench:
"""Operation Unitary Bench class"""
def __init__(self, op_class, bench_name, op_arity=2, init_interval=Interval(-0.5, 0.5), renorm_function=lambda x: x, output_precision=ML_Binary32, input_precisions=[ML_Binary32, ML_Binary32]):
"""OpUnitBench ctor"""
self.op_class = op_class... | the_stack_v2_python_sparse | metalibm_functions/unit_bench.py | metalibm/metalibm | train | 23 |
907b93d07ed8e48bdf7b0666f76df96068f0b849 | [
"if user is not None and user.is_superuser and with_superuser:\n return self\nfilters_prefix = ''\nif self.model._meta.label == 'flow.Storage':\n filters_prefix = 'data__'\nfilters = dict()\nif user:\n filters['user'] = models.Q(**{f'{filters_prefix}permission_group__permissions__user': user, f'{filters_pr... | <|body_start_0|>
if user is not None and user.is_superuser and with_superuser:
return self
filters_prefix = ''
if self.model._meta.label == 'flow.Storage':
filters_prefix = 'data__'
filters = dict()
if user:
filters['user'] = models.Q(**{f'{fil... | Queryset with methods that simlify filtering by permissions. | PermissionQuerySet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermissionQuerySet:
"""Queryset with methods that simlify filtering by permissions."""
def _filter_by_permission(self, user: Optional[User], groups: models.QuerySet, permission: Permission, public: bool=True, with_superuser: bool=True) -> models.QuerySet:
"""Filter queryset by permis... | stack_v2_sparse_classes_10k_train_001070 | 19,789 | permissive | [
{
"docstring": "Filter queryset by permissions. This is a generic method that is called in public methods. :attr user: the user which permissions should be considered. :attr groups: the groups which permissions should be considered. :attr permission: the lowest permission entity must have. :attr public: when Tr... | 3 | stack_v2_sparse_classes_30k_train_000070 | Implement the Python class `PermissionQuerySet` described below.
Class description:
Queryset with methods that simlify filtering by permissions.
Method signatures and docstrings:
- def _filter_by_permission(self, user: Optional[User], groups: models.QuerySet, permission: Permission, public: bool=True, with_superuser:... | Implement the Python class `PermissionQuerySet` described below.
Class description:
Queryset with methods that simlify filtering by permissions.
Method signatures and docstrings:
- def _filter_by_permission(self, user: Optional[User], groups: models.QuerySet, permission: Permission, public: bool=True, with_superuser:... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class PermissionQuerySet:
"""Queryset with methods that simlify filtering by permissions."""
def _filter_by_permission(self, user: Optional[User], groups: models.QuerySet, permission: Permission, public: bool=True, with_superuser: bool=True) -> models.QuerySet:
"""Filter queryset by permis... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PermissionQuerySet:
"""Queryset with methods that simlify filtering by permissions."""
def _filter_by_permission(self, user: Optional[User], groups: models.QuerySet, permission: Permission, public: bool=True, with_superuser: bool=True) -> models.QuerySet:
"""Filter queryset by permissions. This i... | the_stack_v2_python_sparse | resolwe/permissions/models.py | genialis/resolwe | train | 35 |
114be6a63b7532b7a4dd36acd74b34a8c05c3549 | [
"assert len(master_key) in AES.rounds_by_key_size\nself.n_rounds = AES.rounds_by_key_size[len(master_key)]\nself._key_matrices = self._expand_key(master_key)",
"key_columns = bytes2matrix(master_key)\niteration_size = len(master_key) // 4\ni = 1\nwhile len(key_columns) < (self.n_rounds + 1) * 4:\n word = list(... | <|body_start_0|>
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
<|end_body_0|>
<|body_start_1|>
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // ... | AES | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
<|body_0|>
def _expand_key(self, master_key):
"""Expands and returns a list of key matrices for the given master_key."""
<|body_1|>
def encrypt_block(self, plaintext):
... | stack_v2_sparse_classes_10k_train_001071 | 4,275 | permissive | [
{
"docstring": "Initializes the object with a given key.",
"name": "__init__",
"signature": "def __init__(self, master_key)"
},
{
"docstring": "Expands and returns a list of key matrices for the given master_key.",
"name": "_expand_key",
"signature": "def _expand_key(self, master_key)"
... | 3 | stack_v2_sparse_classes_30k_train_005367 | Implement the Python class `AES` described below.
Class description:
Implement the AES class.
Method signatures and docstrings:
- def __init__(self, master_key): Initializes the object with a given key.
- def _expand_key(self, master_key): Expands and returns a list of key matrices for the given master_key.
- def enc... | Implement the Python class `AES` described below.
Class description:
Implement the AES class.
Method signatures and docstrings:
- def __init__(self, master_key): Initializes the object with a given key.
- def _expand_key(self, master_key): Expands and returns a list of key matrices for the given master_key.
- def enc... | cda0db4888322cce759a7362de88fff5cc79f599 | <|skeleton|>
class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
<|body_0|>
def _expand_key(self, master_key):
"""Expands and returns a list of key matrices for the given master_key."""
<|body_1|>
def encrypt_block(self, plaintext):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AES:
def __init__(self, master_key):
"""Initializes the object with a given key."""
assert len(master_key) in AES.rounds_by_key_size
self.n_rounds = AES.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
def _expand_key(self, master_key):... | the_stack_v2_python_sparse | Codegate/2022 Finals/aesmaster/aes.py | Qwaz/solved-hacking-problem | train | 100 | |
75c114df1443505704857b2feb4f6653eca15132 | [
"self.left = left\nself.right = right\nself.key = key\nself.index = index\nself.color = color\nself.p = p",
"if self.isnil() == True:\n return None\nreturn str({'key': self.key, 'index': self.index, 'color': self.color})",
"if self.key == None and self.color == BLACK:\n return True\nreturn False"
] | <|body_start_0|>
self.left = left
self.right = right
self.key = key
self.index = index
self.color = color
self.p = p
<|end_body_0|>
<|body_start_1|>
if self.isnil() == True:
return None
return str({'key': self.key, 'index': self.index, 'color'... | 红黑树结点 | RedBlackTreeNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedBlackTreeNode:
"""红黑树结点"""
def __init__(self, key, index=None, color=RED, p=None, left=None, right=None):
"""红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点"""
<|body_0|>
def __str__(self):
... | stack_v2_sparse_classes_10k_train_001072 | 13,604 | permissive | [
{
"docstring": "红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点",
"name": "__init__",
"signature": "def __init__(self, key, index=None, color=RED, p=None, left=None, right=None)"
},
{
"docstring": "str({'key' : self.key,... | 3 | stack_v2_sparse_classes_30k_train_002713 | Implement the Python class `RedBlackTreeNode` described below.
Class description:
红黑树结点
Method signatures and docstrings:
- def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): 红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `... | Implement the Python class `RedBlackTreeNode` described below.
Class description:
红黑树结点
Method signatures and docstrings:
- def __init__(self, key, index=None, color=RED, p=None, left=None, right=None): 红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `... | 33662f46dc346203b220d7481d1a4439feda05d2 | <|skeleton|>
class RedBlackTreeNode:
"""红黑树结点"""
def __init__(self, key, index=None, color=RED, p=None, left=None, right=None):
"""红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点"""
<|body_0|>
def __str__(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RedBlackTreeNode:
"""红黑树结点"""
def __init__(self, key, index=None, color=RED, p=None, left=None, right=None):
"""红黑树树结点 Args === `left` : SearchTreeNode : 左儿子结点 `right` : SearchTreeNode : 右儿子结点 `index` : 结点自身索引值 `key` : 结点自身键值 `p` : 父节点"""
self.left = left
self.right = right
... | the_stack_v2_python_sparse | src/chapter13/redblacktree.py | HideLakitu/IntroductionToAlgorithm.Python | train | 1 |
d99a8113e20a32a9462a09a070a92e09a11dec56 | [
"self.tfidf_features = {}\nself.category = None\nself.referers = []\nself.named_entities = defaultdict(int)",
"representation = 'Category: ' + self.category + '\\n'\nrepresentation += 'Named Entities:\\n'\nfor ent in self.named_entities:\n if self.named_entities[ent] > 0:\n representation += '\\t' + ent... | <|body_start_0|>
self.tfidf_features = {}
self.category = None
self.referers = []
self.named_entities = defaultdict(int)
<|end_body_0|>
<|body_start_1|>
representation = 'Category: ' + self.category + '\n'
representation += 'Named Entities:\n'
for ent in self.nam... | Object that contains the feature representation of a given clue. | FeatureRepresentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureRepresentation:
"""Object that contains the feature representation of a given clue."""
def __init__(self):
"""Constructor"""
<|body_0|>
def __str__(self):
"""Returns a string representation of this object"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_10k_train_001073 | 10,222 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns a string representation of this object",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002487 | Implement the Python class `FeatureRepresentation` described below.
Class description:
Object that contains the feature representation of a given clue.
Method signatures and docstrings:
- def __init__(self): Constructor
- def __str__(self): Returns a string representation of this object | Implement the Python class `FeatureRepresentation` described below.
Class description:
Object that contains the feature representation of a given clue.
Method signatures and docstrings:
- def __init__(self): Constructor
- def __str__(self): Returns a string representation of this object
<|skeleton|>
class FeatureRep... | 8399c88ab0fdc7736dddcf5239eea655d613c61d | <|skeleton|>
class FeatureRepresentation:
"""Object that contains the feature representation of a given clue."""
def __init__(self):
"""Constructor"""
<|body_0|>
def __str__(self):
"""Returns a string representation of this object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeatureRepresentation:
"""Object that contains the feature representation of a given clue."""
def __init__(self):
"""Constructor"""
self.tfidf_features = {}
self.category = None
self.referers = []
self.named_entities = defaultdict(int)
def __str__(self):
... | the_stack_v2_python_sparse | featurespace.py | timdestan/quiz-bowl-entity-resolution | train | 1 |
453b128fad660bb8f062b0f67c54eef6f3480b65 | [
"self.entity_domain = ENTITY_DOMAIN\nsuper().__init__(config_entry=config_entry, coordinator=coordinator, description=description)\nself._attr_entity_category = EntityCategory.DIAGNOSTIC",
"if self.coordinator.data:\n if self.entity_description.state_value:\n if self.entity_description.key:\n ... | <|body_start_0|>
self.entity_domain = ENTITY_DOMAIN
super().__init__(config_entry=config_entry, coordinator=coordinator, description=description)
self._attr_entity_category = EntityCategory.DIAGNOSTIC
<|end_body_0|>
<|body_start_1|>
if self.coordinator.data:
if self.entity_d... | Representation of an HDHomeRun sensor. | HDHomerunSensor | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDHomerunSensor:
"""Representation of an HDHomeRun sensor."""
def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None:
"""Initialise."""
<|body_0|>
def native_value(self) -> StateType | date... | stack_v2_sparse_classes_10k_train_001074 | 13,715 | permissive | [
{
"docstring": "Initialise.",
"name": "__init__",
"signature": "def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None"
},
{
"docstring": "Get the value of the sensor.",
"name": "native_value",
"signature":... | 2 | null | Implement the Python class `HDHomerunSensor` described below.
Class description:
Representation of an HDHomeRun sensor.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: Initialise.
- def native... | Implement the Python class `HDHomerunSensor` described below.
Class description:
Representation of an HDHomeRun sensor.
Method signatures and docstrings:
- def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None: Initialise.
- def native... | 8548d9999ddd54f13d6a307e013abcb8c897a74e | <|skeleton|>
class HDHomerunSensor:
"""Representation of an HDHomeRun sensor."""
def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None:
"""Initialise."""
<|body_0|>
def native_value(self) -> StateType | date... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HDHomerunSensor:
"""Representation of an HDHomeRun sensor."""
def __init__(self, config_entry: ConfigEntry, coordinator: DataUpdateCoordinator, description: HDHomerunSensorEntityDescription) -> None:
"""Initialise."""
self.entity_domain = ENTITY_DOMAIN
super().__init__(config_entr... | the_stack_v2_python_sparse | custom_components/hdhomerun/sensor.py | bacco007/HomeAssistantConfig | train | 98 |
922e39e75755aeb7f855f2618d22ce33a560477c | [
"res = []\n\ndef helper(node):\n if not node:\n return\n res.append(str(node.val))\n res.append(str(len(node.children)))\n for _ in node.children:\n helper(_)\nhelper(root)\nreturn ','.join(res)",
"if not data:\n return None\n\ndef helper(A):\n val = int(A.popleft())\n size = in... | <|body_start_0|>
res = []
def helper(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children)))
for _ in node.children:
helper(_)
helper(root)
return ','.join(res)
<|end_body_0|... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_001075 | 1,184 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def helper(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children)))
... | the_stack_v2_python_sparse | _0428_Serialize_and_Deserialize_N_ary_Tree.py | mingweihe/leetcode | train | 3 | |
fbbb0d6a9f0ee144b78aecc0f1a0cd0bad3c45ad | [
"self._data = data\nself._detail = kwargs.get('detail', False)\nself._current_data = self._data",
"data = self._current_data\nkwargs = dict()\nkwargs['name'] = data.name\nreturn kwargs",
"info = list()\nassert isinstance(self._detail, bool)\nis_iterable = isinstance(self._data, Iterable)\nif not self._data:\n ... | <|body_start_0|>
self._data = data
self._detail = kwargs.get('detail', False)
self._current_data = self._data
<|end_body_0|>
<|body_start_1|>
data = self._current_data
kwargs = dict()
kwargs['name'] = data.name
return kwargs
<|end_body_1|>
<|body_start_2|>
... | 序列化器基类 | BaseSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseSerializer:
"""序列化器基类"""
def __init__(self, data=None, **kwargs):
"""* 参数 ** detail - 详细信息 [bool]"""
<|body_0|>
def data_info(self, *args):
"""简要信息 * 返回字段 ** name"""
<|body_1|>
def data(self):
"""返回数据"""
<|body_2|>
<|end_skeleton... | stack_v2_sparse_classes_10k_train_001076 | 12,928 | no_license | [
{
"docstring": "* 参数 ** detail - 详细信息 [bool]",
"name": "__init__",
"signature": "def __init__(self, data=None, **kwargs)"
},
{
"docstring": "简要信息 * 返回字段 ** name",
"name": "data_info",
"signature": "def data_info(self, *args)"
},
{
"docstring": "返回数据",
"name": "data",
"sig... | 3 | stack_v2_sparse_classes_30k_train_005343 | Implement the Python class `BaseSerializer` described below.
Class description:
序列化器基类
Method signatures and docstrings:
- def __init__(self, data=None, **kwargs): * 参数 ** detail - 详细信息 [bool]
- def data_info(self, *args): 简要信息 * 返回字段 ** name
- def data(self): 返回数据 | Implement the Python class `BaseSerializer` described below.
Class description:
序列化器基类
Method signatures and docstrings:
- def __init__(self, data=None, **kwargs): * 参数 ** detail - 详细信息 [bool]
- def data_info(self, *args): 简要信息 * 返回字段 ** name
- def data(self): 返回数据
<|skeleton|>
class BaseSerializer:
"""序列化器基类"""... | 639f11a91ee6e8b72883300cbf297ef4c0494d52 | <|skeleton|>
class BaseSerializer:
"""序列化器基类"""
def __init__(self, data=None, **kwargs):
"""* 参数 ** detail - 详细信息 [bool]"""
<|body_0|>
def data_info(self, *args):
"""简要信息 * 返回字段 ** name"""
<|body_1|>
def data(self):
"""返回数据"""
<|body_2|>
<|end_skeleton... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseSerializer:
"""序列化器基类"""
def __init__(self, data=None, **kwargs):
"""* 参数 ** detail - 详细信息 [bool]"""
self._data = data
self._detail = kwargs.get('detail', False)
self._current_data = self._data
def data_info(self, *args):
"""简要信息 * 返回字段 ** name"""
... | the_stack_v2_python_sparse | ivmware/serializers.py | caijb007/itmsp | train | 0 |
fb503cb44b7555f2a5a564b926f72c9aa4f2a1e5 | [
"super(RandomSearch, self).assertions()\nif not isinstance(self.n_selection_iters, int):\n raise TypeError('Parameter `n_selection_iters` must be of type int')",
"self.n_selection_iters = n_selection_iters\nsuper(RandomSearch, self).__init__(optimizer, n_particles, dimensions, options, objective_func, iters, b... | <|body_start_0|>
super(RandomSearch, self).assertions()
if not isinstance(self.n_selection_iters, int):
raise TypeError('Parameter `n_selection_iters` must be of type int')
<|end_body_0|>
<|body_start_1|>
self.n_selection_iters = n_selection_iters
super(RandomSearch, self)._... | Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations. | RandomSearch | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSearch:
"""Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations."""
def assertions(self):
"""Assertion method to check :code:`n_selection_it... | stack_v2_sparse_classes_10k_train_001077 | 4,163 | permissive | [
{
"docstring": "Assertion method to check :code:`n_selection_iters` input Raises ------ TypeError When :code:`n_selection_iters` is not of type int",
"name": "assertions",
"signature": "def assertions(self)"
},
{
"docstring": "Initialize the Search Attributes ---------- n_selection_iters: int nu... | 3 | stack_v2_sparse_classes_30k_train_006599 | Implement the Python class `RandomSearch` described below.
Class description:
Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations.
Method signatures and docstrings:
- def assertio... | Implement the Python class `RandomSearch` described below.
Class description:
Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations.
Method signatures and docstrings:
- def assertio... | 70c969d929bb2dab6211765def0431680fc5cb01 | <|skeleton|>
class RandomSearch:
"""Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations."""
def assertions(self):
"""Assertion method to check :code:`n_selection_it... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomSearch:
"""Search of optimal performance on selected objective function over combinations of randomly selected hyperparameter values within specified bounds for specified number of selection iterations."""
def assertions(self):
"""Assertion method to check :code:`n_selection_iters` input Ra... | the_stack_v2_python_sparse | pyswarms/utils/search/random_search.py | ljvmiranda921/pyswarms | train | 1,194 |
f5e6b47ccceaaa36d09ebf7b000782ecdff8399d | [
"binning = '1,1' if hdu is None else f\"{hdu[0].header['CCDXBIN']},{hdu[0].header['CCDYBIN']}\"\ndetector_dict = dict(binning=binning, det=1, dataext=0, specaxis=0, specflip=True, spatflip=False, platescale=0.12, darkcurr=0.5, saturation=65535.0, nonlinear=0.99, mincounts=-10000000000.0, numamplifiers=4, gain=np.at... | <|body_start_0|>
binning = '1,1' if hdu is None else f"{hdu[0].header['CCDXBIN']},{hdu[0].header['CCDYBIN']}"
detector_dict = dict(binning=binning, det=1, dataext=0, specaxis=0, specflip=True, spatflip=False, platescale=0.12, darkcurr=0.5, saturation=65535.0, nonlinear=0.99, mincounts=-10000000000.0, nu... | Child to handle LBT/MODS1R specific code | LBTMODS1BSpectrograph | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LBTMODS1BSpectrograph:
"""Child to handle LBT/MODS1R specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the ra... | stack_v2_sparse_classes_10k_train_001078 | 35,372 | permissive | [
{
"docstring": "Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image of interest. If not provided, frame-dependent parameters are set to a default. Returns: :class:`~pypeit.images.detector_... | 4 | null | Implement the Python class `LBTMODS1BSpectrograph` described below.
Class description:
Child to handle LBT/MODS1R specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.... | Implement the Python class `LBTMODS1BSpectrograph` described below.
Class description:
Child to handle LBT/MODS1R specific code
Method signatures and docstrings:
- def get_detector_par(self, det, hdu=None): Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.... | 0d2e2196afc6904050b1af4d572f5c643bb07e38 | <|skeleton|>
class LBTMODS1BSpectrograph:
"""Child to handle LBT/MODS1R specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the ra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LBTMODS1BSpectrograph:
"""Child to handle LBT/MODS1R specific code"""
def get_detector_par(self, det, hdu=None):
"""Return metadata for the selected detector. Args: det (:obj:`int`): 1-indexed detector number. hdu (`astropy.io.fits.HDUList`_, optional): The open fits file with the raw image of in... | the_stack_v2_python_sparse | pypeit/spectrographs/lbt_mods.py | pypeit/PypeIt | train | 136 |
741c6773ee9da987a6884ccf683917d9f868c4c8 | [
"kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)\nkwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFactor': config.float('newbob_learning_rate_decay', 0.5)})\nreturn kwargs",
"super(NewbobAbs, self).__init__(**kwargs)\nself.errorThreshold = e... | <|body_start_0|>
kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)
kwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFactor': config.float('newbob_learning_rate_decay', 0.5)})
return kwargs
<|end_body_0|>
<|body_start_1|>
... | NewbobAbs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
<|body_0|>
def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs):
""":type errorThreshold: float :type learningRateDecayFactor: float"""
... | stack_v2_sparse_classes_10k_train_001079 | 19,323 | no_license | [
{
"docstring": ":type config: Config.Config :rtype: dict[str]",
"name": "load_initial_kwargs_from_config",
"signature": "def load_initial_kwargs_from_config(cls, config)"
},
{
"docstring": ":type errorThreshold: float :type learningRateDecayFactor: float",
"name": "__init__",
"signature"... | 3 | null | Implement the Python class `NewbobAbs` described below.
Class description:
Implement the NewbobAbs class.
Method signatures and docstrings:
- def load_initial_kwargs_from_config(cls, config): :type config: Config.Config :rtype: dict[str]
- def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs): :type e... | Implement the Python class `NewbobAbs` described below.
Class description:
Implement the NewbobAbs class.
Method signatures and docstrings:
- def load_initial_kwargs_from_config(cls, config): :type config: Config.Config :rtype: dict[str]
- def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs): :type e... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
<|body_0|>
def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs):
""":type errorThreshold: float :type learningRateDecayFactor: float"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)
kwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFact... | the_stack_v2_python_sparse | python/rwth-i6_returnn/returnn-master/LearningRateControl.py | LiuFang816/SALSTM_py_data | train | 10 | |
bd7e329761610555d5e8a5a3b426b8740078a656 | [
"if len(s) < len(p):\n return []\nres = []\nm, n = (len(s), len(p))\nfor i in range(m - n + 1):\n if s[i] in p:\n if Counter(s[i:i + n]) == Counter(p):\n res.append(i)\nreturn res",
"res = []\npCounter = Counter(p)\nsCounter = Counter(s[:len(p) - 1])\nfor i in range(len(p) - 1, len(s)):\n ... | <|body_start_0|>
if len(s) < len(p):
return []
res = []
m, n = (len(s), len(p))
for i in range(m - n + 1):
if s[i] in p:
if Counter(s[i:i + n]) == Counter(p):
res.append(i)
return res
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams2(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) < len(p):
... | stack_v2_sparse_classes_10k_train_001080 | 31,450 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int]",
"name": "findAnagrams2",
"signature": "def findAnagrams2(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004220 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams2(self, s, p): :type s: str :type p: str :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int]
- def findAnagrams2(self, s, p): :type s: str :type p: str :rtype: List[int]
<|skeleton|>
class Solutio... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_0|>
def findAnagrams2(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int]"""
if len(s) < len(p):
return []
res = []
m, n = (len(s), len(p))
for i in range(m - n + 1):
if s[i] in p:
if Counter(s[i:i + n]) == Counter(p)... | the_stack_v2_python_sparse | 438. Find All Anagrams in a String/allAnagrams.py | Macielyoung/LeetCode | train | 1 | |
34c9390051b20e4ba71c6b229863dabac924e83a | [
"super(SourceLoss, self).__init__()\nself.cheaptrick = CheapTrick(sampling_rate=sampling_rate, hop_size=hop_size, fft_size=fft_size, f0_floor=f0_floor, f0_ceil=f0_ceil, uv_threshold=uv_threshold, q1=q1)\nself.loss = nn.MSELoss()",
"spectral_envelope = self.cheaptrick.forward(x, f0)\nzeros = torch.zeros_like(spect... | <|body_start_0|>
super(SourceLoss, self).__init__()
self.cheaptrick = CheapTrick(sampling_rate=sampling_rate, hop_size=hop_size, fft_size=fft_size, f0_floor=f0_floor, f0_ceil=f0_ceil, uv_threshold=uv_threshold, q1=q1)
self.loss = nn.MSELoss()
<|end_body_0|>
<|body_start_1|>
spectral_env... | SourceLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceLoss:
def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15):
"""Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type."""
<|bo... | stack_v2_sparse_classes_10k_train_001081 | 1,728 | permissive | [
{
"docstring": "Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type.",
"name": "__init__",
"signature": "def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0... | 2 | stack_v2_sparse_classes_30k_test_000168 | Implement the Python class `SourceLoss` described below.
Class description:
Implement the SourceLoss class.
Method signatures and docstrings:
- def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): Initialize source loss module. Args: fft_size (int): FFT size. hop_size (i... | Implement the Python class `SourceLoss` described below.
Class description:
Implement the SourceLoss class.
Method signatures and docstrings:
- def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): Initialize source loss module. Args: fft_size (int): FFT size. hop_size (i... | 67331ddb5d6a7227120818842c61b6e07de52ba7 | <|skeleton|>
class SourceLoss:
def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15):
"""Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SourceLoss:
def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15):
"""Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type."""
super(SourceLoss, ... | the_stack_v2_python_sparse | usfgan/losses/source_loss.py | hendrikTpl/UnifiedSourceFilterGAN | train | 0 | |
833d81a482d47135e45ff8e2016166896f6f5383 | [
"if not s:\n return ''\nn, left, length = (len(s), 0, 1)\ndp = [[False] * n for _ in range(n)]\nfor i in range(n):\n dp[i][i] = True\nfor i in range(n - 1, 0, -1):\n if s[i] == s[i - 1]:\n dp[i - 1][i] = True\n length = 2\n left = i - 1\nfor k in range(3, n + 1):\n for i in range(0,... | <|body_start_0|>
if not s:
return ''
n, left, length = (len(s), 0, 1)
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
for i in range(n - 1, 0, -1):
if s[i] == s[i - 1]:
dp[i - 1][i] = True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s:
return ''
n, left, length ... | stack_v2_sparse_classes_10k_train_001082 | 1,533 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005359 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def longestPalindrome(self... | 75aef2f6c42aeb51261b9450a24099957a084d51 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if not s:
return ''
n, left, length = (len(s), 0, 1)
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
for i in range(n - 1, 0, -1):
... | the_stack_v2_python_sparse | Python/0005_LongestPalindromicSubstring/longestPalindrome.py | mtmmy/Leetcode | train | 3 | |
6f226064f895be5a5f4d529f3959ccaca29a056a | [
"rmg_path = os.path.normpath(os.path.join(get_path(), '..'))\nself.settings1 = QMSettings(software='mopac', method='pm3', fileStore=os.path.join(rmg_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=None, onlyCyclics=False, maxRadicalNumber=0)\nself.settings2 = QMSettings()",
"try:\n self.settings1.check_all... | <|body_start_0|>
rmg_path = os.path.normpath(os.path.join(get_path(), '..'))
self.settings1 = QMSettings(software='mopac', method='pm3', fileStore=os.path.join(rmg_path, 'testing', 'qm', 'QMfiles'), scratchDirectory=None, onlyCyclics=False, maxRadicalNumber=0)
self.settings2 = QMSettings()
<|end... | Contains unit tests for the QMSettings class. | TestQMSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestQMSettings:
"""Contains unit tests for the QMSettings class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_check_all_set(self):
"""Test that check_all_set() works correctly."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k_train_001083 | 14,056 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that check_all_set() works correctly.",
"name": "test_check_all_set",
"signature": "def test_check_all_set(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003086 | Implement the Python class `TestQMSettings` described below.
Class description:
Contains unit tests for the QMSettings class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_check_all_set(self): Test that check_all_set() works correctly. | Implement the Python class `TestQMSettings` described below.
Class description:
Contains unit tests for the QMSettings class.
Method signatures and docstrings:
- def setUp(self): A function run before each unit test in this class.
- def test_check_all_set(self): Test that check_all_set() works correctly.
<|skeleton|... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestQMSettings:
"""Contains unit tests for the QMSettings class."""
def setUp(self):
"""A function run before each unit test in this class."""
<|body_0|>
def test_check_all_set(self):
"""Test that check_all_set() works correctly."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestQMSettings:
"""Contains unit tests for the QMSettings class."""
def setUp(self):
"""A function run before each unit test in this class."""
rmg_path = os.path.normpath(os.path.join(get_path(), '..'))
self.settings1 = QMSettings(software='mopac', method='pm3', fileStore=os.path.... | the_stack_v2_python_sparse | rmgpy/qm/mainTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
43bc742e88650eb5c8cbe3c29336985cf2a8c8c7 | [
"super(ChamferkNNDist, self).__init__()\nself.chamfer_dist = ChamferDist(method=chamfer_method)\nself.knn_dist = KNNDist(k=knn_k, alpha=knn_alpha)\nself.w1 = chamfer_weight\nself.w2 = knn_weight",
"chamfer_loss = self.chamfer_dist(adv_pc, ori_pc, weights=weights, batch_avg=batch_avg)\nknn_loss = self.knn_dist(adv... | <|body_start_0|>
super(ChamferkNNDist, self).__init__()
self.chamfer_dist = ChamferDist(method=chamfer_method)
self.knn_dist = KNNDist(k=knn_k, alpha=knn_alpha)
self.w1 = chamfer_weight
self.w2 = knn_weight
<|end_body_0|>
<|body_start_1|>
chamfer_loss = self.chamfer_dist... | ChamferkNNDist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults... | stack_v2_sparse_classes_10k_train_001084 | 11,583 | permissive | [
{
"docstring": "Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults to 5. knn_alpha (float, optional): alpha in kNN. Defaults to 1.1. chamfer_weight (float, optional): weight factor. Defaults to 5.. kn... | 2 | stack_v2_sparse_classes_30k_train_000205 | Implement the Python class `ChamferkNNDist` described below.
Class description:
Implement the ChamferkNNDist class.
Method signatures and docstrings:
- def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0): Geometry-aware distance function of AAAI'20 paper. Args: ch... | Implement the Python class `ChamferkNNDist` described below.
Class description:
Implement the ChamferkNNDist class.
Method signatures and docstrings:
- def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0): Geometry-aware distance function of AAAI'20 paper. Args: ch... | 4e2462b66fa1eac90cfbf61fa0dc635d223fdf2f | <|skeleton|>
class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults to 5. knn_alp... | the_stack_v2_python_sparse | baselines/attack/util/dist_utils.py | code-roamer/IF-Defense | train | 0 | |
795345f5cb9f06b7a06ac5215b832f960094d58b | [
"self.xs = np.atleast_2d(xs).T\nself.freqs = np.atleast_2d(freqs)\nself.width = np.atleast_1d(width)\nself.horizon = np.pi / 2\nself.mfreq = mfreq\nself.chromaticity = chromaticity\nself.dtype = dtype",
"widths, dtype = self._process_args(width, mfreq, chromaticity, dtype)\nresponse = np.exp(-0.5 * (self.xs / np.... | <|body_start_0|>
self.xs = np.atleast_2d(xs).T
self.freqs = np.atleast_2d(freqs)
self.width = np.atleast_1d(width)
self.horizon = np.pi / 2
self.mfreq = mfreq
self.chromaticity = chromaticity
self.dtype = dtype
<|end_body_0|>
<|body_start_1|>
widths, dtyp... | Base class for constructing a 1-dimensional beam. | Beam1d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Beam1d:
"""Base class for constructing a 1-dimensional beam."""
def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32):
"""Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` p... | stack_v2_sparse_classes_10k_train_001085 | 7,041 | no_license | [
{
"docstring": "Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` parameters, or by specifying a chromaticity and reference frequency. When providing an array of frequencies along with a single width, reference frequency, and chromaticity,... | 4 | stack_v2_sparse_classes_30k_train_000036 | Implement the Python class `Beam1d` described below.
Class description:
Base class for constructing a 1-dimensional beam.
Method signatures and docstrings:
- def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32): Set up the base parameters for defining a beam. Chromatic beams may... | Implement the Python class `Beam1d` described below.
Class description:
Base class for constructing a 1-dimensional beam.
Method signatures and docstrings:
- def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32): Set up the base parameters for defining a beam. Chromatic beams may... | f9d292f4a91c0599947e3c013b48114b2097d76d | <|skeleton|>
class Beam1d:
"""Base class for constructing a 1-dimensional beam."""
def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32):
"""Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Beam1d:
"""Base class for constructing a 1-dimensional beam."""
def __init__(self, xs, freqs=0.15, width=0.2, mfreq=0.15, chromaticity=0, dtype=np.float32):
"""Set up the base parameters for defining a beam. Chromatic beams may be simulated by either providing an array of ``width`` parameters, or... | the_stack_v2_python_sparse | rfp/scripts/dewedge/beams.py | HERA-Team/hera_sandbox | train | 2 |
56d363c33e789c88e75e1dff26f8d4144e547fbe | [
"self.check_parameters(params)\ncos = np.cos(params[0] / 2)\nsin = -1j * np.sin(params[0] / 2)\nreturn UnitaryMatrix([[cos, 0, 0, sin], [0, cos, sin, 0], [0, sin, cos, 0], [sin, 0, 0, cos]])",
"self.check_parameters(params)\ndcos = -np.sin(params[0] / 2) / 2\ndsin = -1j * np.cos(params[0] / 2) / 2\nreturn np.arra... | <|body_start_0|>
self.check_parameters(params)
cos = np.cos(params[0] / 2)
sin = -1j * np.sin(params[0] / 2)
return UnitaryMatrix([[cos, 0, 0, sin], [0, cos, sin, 0], [0, sin, cos, 0], [sin, 0, 0, cos]])
<|end_body_0|>
<|body_start_1|>
self.check_parameters(params)
dcos ... | A gate representing an arbitrary rotation around the XX axis. | RXXGate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RXXGate:
"""A gate representing an arbitrary rotation around the XX axis."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) ... | stack_v2_sparse_classes_10k_train_001086 | 2,165 | permissive | [
{
"docstring": "Returns the unitary for this gate, see Unitary for more info.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix"
},
{
"docstring": "Returns the gradient for this gate, see Gate for more info.",
"name": "get_grad",
"s... | 3 | stack_v2_sparse_classes_30k_train_006768 | Implement the Python class `RXXGate` described below.
Class description:
A gate representing an arbitrary rotation around the XX axis.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(se... | Implement the Python class `RXXGate` described below.
Class description:
A gate representing an arbitrary rotation around the XX axis.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(se... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class RXXGate:
"""A gate representing an arbitrary rotation around the XX axis."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RXXGate:
"""A gate representing an arbitrary rotation around the XX axis."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
self.check_parameters(params)
cos = np.cos(params[0] / 2)
si... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/rxx.py | mtreinish/bqskit | train | 0 |
3f52819330afb8b9673a77a64adad90e525075a2 | [
"super().__init__()\nstate_dim = descript.get('state_dim')\naction_dim = descript.get('action_dim')\nself.fc2 = Sequential(Linear(state_dim, HIDDEN_SIZE), Linear(HIDDEN_SIZE, action_dim), Lambda(lambda x: softmax(x)))\nself.fc3 = Sequential(Linear(state_dim, HIDDEN_SIZE), Linear(HIDDEN_SIZE, 1))",
"outputs = []\n... | <|body_start_0|>
super().__init__()
state_dim = descript.get('state_dim')
action_dim = descript.get('action_dim')
self.fc2 = Sequential(Linear(state_dim, HIDDEN_SIZE), Linear(HIDDEN_SIZE, action_dim), Lambda(lambda x: softmax(x)))
self.fc3 = Sequential(Linear(state_dim, HIDDEN_SI... | Create DQN net with FineGrainedSpace. | ImpalaMlpNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImpalaMlpNet:
"""Create DQN net with FineGrainedSpace."""
def __init__(self, **descript):
"""Create layers."""
<|body_0|>
def __call__(self, inputs):
"""Override compile function, conect models into a seq."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_001087 | 5,106 | permissive | [
{
"docstring": "Create layers.",
"name": "__init__",
"signature": "def __init__(self, **descript)"
},
{
"docstring": "Override compile function, conect models into a seq.",
"name": "__call__",
"signature": "def __call__(self, inputs)"
}
] | 2 | null | Implement the Python class `ImpalaMlpNet` described below.
Class description:
Create DQN net with FineGrainedSpace.
Method signatures and docstrings:
- def __init__(self, **descript): Create layers.
- def __call__(self, inputs): Override compile function, conect models into a seq. | Implement the Python class `ImpalaMlpNet` described below.
Class description:
Create DQN net with FineGrainedSpace.
Method signatures and docstrings:
- def __init__(self, **descript): Create layers.
- def __call__(self, inputs): Override compile function, conect models into a seq.
<|skeleton|>
class ImpalaMlpNet:
... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class ImpalaMlpNet:
"""Create DQN net with FineGrainedSpace."""
def __init__(self, **descript):
"""Create layers."""
<|body_0|>
def __call__(self, inputs):
"""Override compile function, conect models into a seq."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImpalaMlpNet:
"""Create DQN net with FineGrainedSpace."""
def __init__(self, **descript):
"""Create layers."""
super().__init__()
state_dim = descript.get('state_dim')
action_dim = descript.get('action_dim')
self.fc2 = Sequential(Linear(state_dim, HIDDEN_SIZE), Lin... | the_stack_v2_python_sparse | xt/model/impala/impala_mlp_zeus.py | huawei-noah/xingtian | train | 308 |
73aebd39d363c78fa2ff411c2519c212f69ccc22 | [
"maps = PersonalAppealDao.PersonalAppealDao.get_dist_cert_field(field_name)\nrespond = JsonResponse(maps)\nrespond['Access-Control-Allow-Origin'] = '*'\nreturn respond",
"if request.method == 'POST':\n appeallor = request.POST.get('appeallor')\n field_name = request.POST.get('field')\nelse:\n appeallor =... | <|body_start_0|>
maps = PersonalAppealDao.PersonalAppealDao.get_dist_cert_field(field_name)
respond = JsonResponse(maps)
respond['Access-Control-Allow-Origin'] = '*'
return respond
<|end_body_0|>
<|body_start_1|>
if request.method == 'POST':
appeallor = request.POST.... | 用于写测试方法 | TestPersonalAppealDao | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPersonalAppealDao:
"""用于写测试方法"""
def test_gdocf(request, field_name):
"""测试URL模式是否生效 :param request: :param field_name: :return:"""
<|body_0|>
def test_gdocf2(request):
"""测试是否成功从request中取得参数 :param request: :return:"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_001088 | 1,217 | no_license | [
{
"docstring": "测试URL模式是否生效 :param request: :param field_name: :return:",
"name": "test_gdocf",
"signature": "def test_gdocf(request, field_name)"
},
{
"docstring": "测试是否成功从request中取得参数 :param request: :return:",
"name": "test_gdocf2",
"signature": "def test_gdocf2(request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004432 | Implement the Python class `TestPersonalAppealDao` described below.
Class description:
用于写测试方法
Method signatures and docstrings:
- def test_gdocf(request, field_name): 测试URL模式是否生效 :param request: :param field_name: :return:
- def test_gdocf2(request): 测试是否成功从request中取得参数 :param request: :return: | Implement the Python class `TestPersonalAppealDao` described below.
Class description:
用于写测试方法
Method signatures and docstrings:
- def test_gdocf(request, field_name): 测试URL模式是否生效 :param request: :param field_name: :return:
- def test_gdocf2(request): 测试是否成功从request中取得参数 :param request: :return:
<|skeleton|>
class T... | b907bb29b52047b21b79e95178b78ca033eee04f | <|skeleton|>
class TestPersonalAppealDao:
"""用于写测试方法"""
def test_gdocf(request, field_name):
"""测试URL模式是否生效 :param request: :param field_name: :return:"""
<|body_0|>
def test_gdocf2(request):
"""测试是否成功从request中取得参数 :param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestPersonalAppealDao:
"""用于写测试方法"""
def test_gdocf(request, field_name):
"""测试URL模式是否生效 :param request: :param field_name: :return:"""
maps = PersonalAppealDao.PersonalAppealDao.get_dist_cert_field(field_name)
respond = JsonResponse(maps)
respond['Access-Control-Allow-Ori... | the_stack_v2_python_sparse | code/user_profiles/service/TestService.py | gitxiangxiang/UserPortraitAnalysis | train | 1 |
dfdbab317ffa3b29e94e2c2e170bb41d630eec72 | [
"if httplib2 is None:\n raise RuntimeError('Cannot find httplib2 library. See http://bitworking.org/projects/httplib2/')\nsuper(HTTPLib2Fetcher, self).__init__()\nself.httplib2 = httplib2.Http(cache)\nself.httplib2.force_exception_to_status_code = False",
"if body:\n method = 'POST'\nelse:\n method = 'GE... | <|body_start_0|>
if httplib2 is None:
raise RuntimeError('Cannot find httplib2 library. See http://bitworking.org/projects/httplib2/')
super(HTTPLib2Fetcher, self).__init__()
self.httplib2 = httplib2.Http(cache)
self.httplib2.force_exception_to_status_code = False
<|end_body_... | A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/ | HTTPLib2Fetcher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPLib2Fetcher:
"""A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/"""
def __init__(self, cache=None):
"""@param cache: An object suitable for use as an C{httplib2} cache. If a str... | stack_v2_sparse_classes_10k_train_001089 | 15,881 | permissive | [
{
"docstring": "@param cache: An object suitable for use as an C{httplib2} cache. If a string is passed, it is assumed to be a directory name.",
"name": "__init__",
"signature": "def __init__(self, cache=None)"
},
{
"docstring": "Perform an HTTP request @raises Exception: Any exception that can ... | 2 | stack_v2_sparse_classes_30k_train_004690 | Implement the Python class `HTTPLib2Fetcher` described below.
Class description:
A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/
Method signatures and docstrings:
- def __init__(self, cache=None): @param cache: An ... | Implement the Python class `HTTPLib2Fetcher` described below.
Class description:
A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/
Method signatures and docstrings:
- def __init__(self, cache=None): @param cache: An ... | 92235252f0a18b702bc86f17c0c5f5a9d68967a7 | <|skeleton|>
class HTTPLib2Fetcher:
"""A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/"""
def __init__(self, cache=None):
"""@param cache: An object suitable for use as an C{httplib2} cache. If a str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HTTPLib2Fetcher:
"""A fetcher that uses C{httplib2} for performing HTTP requests. This implementation supports HTTP caching. @see: http://bitworking.org/projects/httplib2/"""
def __init__(self, cache=None):
"""@param cache: An object suitable for use as an C{httplib2} cache. If a string is passed... | the_stack_v2_python_sparse | openid/fetchers.py | necaris/python3-openid | train | 41 |
223fc37cf941cfa2beeb582b00d4ac7e36801f86 | [
"if self.extra_sensor_mapping is None:\n LOGGER.debug('extra_sensors: No extra_sensor_mapping defined.')\n return None\nextra_sensors = []\nfor sensor_name in self.extra_sensor_mapping.keys():\n for chan in self.extra_channels:\n if chan in self.extra_sensor_mapping[sensor_name]:\n extra_... | <|body_start_0|>
if self.extra_sensor_mapping is None:
LOGGER.debug('extra_sensors: No extra_sensor_mapping defined.')
return None
extra_sensors = []
for sensor_name in self.extra_sensor_mapping.keys():
for chan in self.extra_channels:
if chan ... | Represents a station as metadata attributes. Note - this is currently defined as a tuple and thus most properties are read-only. The 'extra_sensor_mapping' is one exception - itcan be set after object creation. | SeismicStationMetadata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeismicStationMetadata:
"""Represents a station as metadata attributes. Note - this is currently defined as a tuple and thus most properties are read-only. The 'extra_sensor_mapping' is one exception - itcan be set after object creation."""
def extra_sensors(self):
"""Sensors in addi... | stack_v2_sparse_classes_10k_train_001090 | 16,855 | no_license | [
{
"docstring": "Sensors in addition to the normal seismic suite.",
"name": "extra_sensors",
"signature": "def extra_sensors(self)"
},
{
"docstring": "Check if the station is active in the dbmaster before the given time. Args: time (numeric): Antelope timestamp value, will be compared with the st... | 4 | stack_v2_sparse_classes_30k_train_006832 | Implement the Python class `SeismicStationMetadata` described below.
Class description:
Represents a station as metadata attributes. Note - this is currently defined as a tuple and thus most properties are read-only. The 'extra_sensor_mapping' is one exception - itcan be set after object creation.
Method signatures a... | Implement the Python class `SeismicStationMetadata` described below.
Class description:
Represents a station as metadata attributes. Note - this is currently defined as a tuple and thus most properties are read-only. The 'extra_sensor_mapping' is one exception - itcan be set after object creation.
Method signatures a... | 0b30093c240a72b7cfe52ee835eafa452510b56b | <|skeleton|>
class SeismicStationMetadata:
"""Represents a station as metadata attributes. Note - this is currently defined as a tuple and thus most properties are read-only. The 'extra_sensor_mapping' is one exception - itcan be set after object creation."""
def extra_sensors(self):
"""Sensors in addi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeismicStationMetadata:
"""Represents a station as metadata attributes. Note - this is currently defined as a tuple and thus most properties are read-only. The 'extra_sensor_mapping' is one exception - itcan be set after object creation."""
def extra_sensors(self):
"""Sensors in addition to the n... | the_stack_v2_python_sparse | anf/bin/web/usarray_deploy_map/anf/deploymentmap/database.py | UCSD-ANF/anfsrc | train | 6 |
a18fa30dc9c14ec942f5644fa7a7da799adb86c2 | [
"del pipeline_info, component_info\ninput_config = example_gen_pb2.Input()\njson_format.Parse(exec_properties[utils.INPUT_CONFIG_KEY], input_config)\ninput_base = exec_properties[utils.INPUT_BASE_KEY]\nlogging.debug('Processing input %s.', input_base)\nfingerprint, span, version = utils.calculate_splits_fingerprint... | <|body_start_0|>
del pipeline_info, component_info
input_config = example_gen_pb2.Input()
json_format.Parse(exec_properties[utils.INPUT_CONFIG_KEY], input_config)
input_base = exec_properties[utils.INPUT_BASE_KEY]
logging.debug('Processing input %s.', input_base)
fingerpr... | Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen. | Driver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Driver:
"""Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen."""
def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[... | stack_v2_sparse_classes_10k_train_001091 | 3,843 | permissive | [
{
"docstring": "Overrides BaseDriver.resolve_exec_properties().",
"name": "resolve_exec_properties",
"signature": "def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[Text, Any]"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_000896 | Implement the Python class `Driver` described below.
Class description:
Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen.
Method signatures and docstrings:
- def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_ty... | Implement the Python class `Driver` described below.
Class description:
Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen.
Method signatures and docstrings:
- def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_ty... | ff6917997340401570d05a4d3ebd6e8ab5760495 | <|skeleton|>
class Driver:
"""Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen."""
def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Driver:
"""Custom driver for ExampleGen. This driver supports file based ExampleGen, e.g., for CsvExampleGen and ImportExampleGen."""
def resolve_exec_properties(self, exec_properties: Dict[Text, Any], pipeline_info: data_types.PipelineInfo, component_info: data_types.ComponentInfo) -> Dict[Text, Any]:
... | the_stack_v2_python_sparse | tfx/components/example_gen/driver.py | 18jeffreyma/tfx | train | 3 |
fc1b4d58600a9430cdde07a7721fad4500b70b80 | [
"renderer = self.renderer\nwith open(makefile, mode='w') as stream:\n contents = self._generate(**kwds)\n document = renderer.render(document=contents)\n print('\\n'.join(document), file=stream)\nreturn",
"stamp = f\"generated by '{self.pyre_name}' on {datetime.datetime.now().isoformat()}\"\nyield self.r... | <|body_start_0|>
renderer = self.renderer
with open(makefile, mode='w') as stream:
contents = self._generate(**kwds)
document = renderer.render(document=contents)
print('\n'.join(document), file=stream)
return
<|end_body_0|>
<|body_start_1|>
stamp = f... | The base makefile content generator | Generator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""The base makefile content generator"""
def generate(self, makefile, **kwds):
"""Generate the makefile preamble"""
<|body_0|>
def _generate(self, **kwds):
"""Build my contents"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
renderer... | stack_v2_sparse_classes_10k_train_001092 | 1,415 | permissive | [
{
"docstring": "Generate the makefile preamble",
"name": "generate",
"signature": "def generate(self, makefile, **kwds)"
},
{
"docstring": "Build my contents",
"name": "_generate",
"signature": "def _generate(self, **kwds)"
}
] | 2 | null | Implement the Python class `Generator` described below.
Class description:
The base makefile content generator
Method signatures and docstrings:
- def generate(self, makefile, **kwds): Generate the makefile preamble
- def _generate(self, **kwds): Build my contents | Implement the Python class `Generator` described below.
Class description:
The base makefile content generator
Method signatures and docstrings:
- def generate(self, makefile, **kwds): Generate the makefile preamble
- def _generate(self, **kwds): Build my contents
<|skeleton|>
class Generator:
"""The base makefi... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class Generator:
"""The base makefile content generator"""
def generate(self, makefile, **kwds):
"""Generate the makefile preamble"""
<|body_0|>
def _generate(self, **kwds):
"""Build my contents"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Generator:
"""The base makefile content generator"""
def generate(self, makefile, **kwds):
"""Generate the makefile preamble"""
renderer = self.renderer
with open(makefile, mode='w') as stream:
contents = self._generate(**kwds)
document = renderer.render(do... | the_stack_v2_python_sparse | packages/merlin/builders/make/Generator.py | pyre/pyre | train | 27 |
409ebe1d510a2644b274fbf98e60ac84f1bf76eb | [
"wx.Frame.__init__(self, None, title='Crosshair', style=wx.NO_BORDER)\nself.height_half = crosshair_height // 2\nself.width_half = crosshair_width // 2\nself.screenheight_half = screen_height // 2\nself.screenwidth_half = screen_width // 2\nself.thickness = thickness\nself.SetBackgroundColour(background_color)\nsel... | <|body_start_0|>
wx.Frame.__init__(self, None, title='Crosshair', style=wx.NO_BORDER)
self.height_half = crosshair_height // 2
self.width_half = crosshair_width // 2
self.screenheight_half = screen_height // 2
self.screenwidth_half = screen_width // 2
self.thickness = thi... | Crosshair | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crosshair:
def __init__(self, x_pos=-1920, y_pos=0, screen_width=1920, screen_height=1080, title='Crosshair', background_color='#686868', crosshair_height=60, crosshair_width=60, thickness=7, hide_cursor=True):
"""A wxpython Crosshair that can flash red. :param x_pos: x position (default... | stack_v2_sparse_classes_10k_train_001093 | 2,843 | no_license | [
{
"docstring": "A wxpython Crosshair that can flash red. :param x_pos: x position (defaults to 1920 pixels left of main screen) :param y_pos: y position (defaults to 0) :param screen_width: size of screen in pixels :param screen_height: height of screen in pixels :param title: Not displayed externally. Defaults... | 3 | stack_v2_sparse_classes_30k_train_000169 | Implement the Python class `Crosshair` described below.
Class description:
Implement the Crosshair class.
Method signatures and docstrings:
- def __init__(self, x_pos=-1920, y_pos=0, screen_width=1920, screen_height=1080, title='Crosshair', background_color='#686868', crosshair_height=60, crosshair_width=60, thicknes... | Implement the Python class `Crosshair` described below.
Class description:
Implement the Crosshair class.
Method signatures and docstrings:
- def __init__(self, x_pos=-1920, y_pos=0, screen_width=1920, screen_height=1080, title='Crosshair', background_color='#686868', crosshair_height=60, crosshair_width=60, thicknes... | 4eec0ea2eb3dc287d475f9ab4e0b75259c51b309 | <|skeleton|>
class Crosshair:
def __init__(self, x_pos=-1920, y_pos=0, screen_width=1920, screen_height=1080, title='Crosshair', background_color='#686868', crosshair_height=60, crosshair_width=60, thickness=7, hide_cursor=True):
"""A wxpython Crosshair that can flash red. :param x_pos: x position (default... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Crosshair:
def __init__(self, x_pos=-1920, y_pos=0, screen_width=1920, screen_height=1080, title='Crosshair', background_color='#686868', crosshair_height=60, crosshair_width=60, thickness=7, hide_cursor=True):
"""A wxpython Crosshair that can flash red. :param x_pos: x position (defaults to 1920 pixe... | the_stack_v2_python_sparse | Graphics/CursorTask/WxCrosshair.py | heathzhang35/CCDLUtil | train | 0 | |
148e912260ea4629fb87446890458ed644fdef28 | [
"self.places = {}\nself.transitions = {}\nself.successful_firings = []",
"pn_copy = PetriNetModel()\nfor place in petri_net_model.places.values():\n pn_copy.add_place(place.tokens, place.place_id, place.label)\nfor t in petri_net_model.transitions.values():\n input_place_ids = [arc.place.place_id for arc in... | <|body_start_0|>
self.places = {}
self.transitions = {}
self.successful_firings = []
<|end_body_0|>
<|body_start_1|>
pn_copy = PetriNetModel()
for place in petri_net_model.places.values():
pn_copy.add_place(place.tokens, place.place_id, place.label)
for t in ... | PetriNetModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PetriNetModel:
def __init__(self):
"""Initialize an empty Petri net."""
<|body_0|>
def make_copy_of(petri_net_model):
"""Makes a deep copy of a PetriNetModel instance. Args: petri_net_model: instance of PetriNetModel to be copied"""
<|body_1|>
def add_pl... | stack_v2_sparse_classes_10k_train_001094 | 15,780 | permissive | [
{
"docstring": "Initialize an empty Petri net.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Makes a deep copy of a PetriNetModel instance. Args: petri_net_model: instance of PetriNetModel to be copied",
"name": "make_copy_of",
"signature": "def make_copy_of(... | 5 | stack_v2_sparse_classes_30k_train_000139 | Implement the Python class `PetriNetModel` described below.
Class description:
Implement the PetriNetModel class.
Method signatures and docstrings:
- def __init__(self): Initialize an empty Petri net.
- def make_copy_of(petri_net_model): Makes a deep copy of a PetriNetModel instance. Args: petri_net_model: instance o... | Implement the Python class `PetriNetModel` described below.
Class description:
Implement the PetriNetModel class.
Method signatures and docstrings:
- def __init__(self): Initialize an empty Petri net.
- def make_copy_of(petri_net_model): Makes a deep copy of a PetriNetModel instance. Args: petri_net_model: instance o... | 8e9a3a8151069757475808c48511c9d7486ea334 | <|skeleton|>
class PetriNetModel:
def __init__(self):
"""Initialize an empty Petri net."""
<|body_0|>
def make_copy_of(petri_net_model):
"""Makes a deep copy of a PetriNetModel instance. Args: petri_net_model: instance of PetriNetModel to be copied"""
<|body_1|>
def add_pl... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PetriNetModel:
def __init__(self):
"""Initialize an empty Petri net."""
self.places = {}
self.transitions = {}
self.successful_firings = []
def make_copy_of(petri_net_model):
"""Makes a deep copy of a PetriNetModel instance. Args: petri_net_model: instance of Petri... | the_stack_v2_python_sparse | HFPN model/utils/petri_nets.py | PN-Alzheimers-Parkinsons/PN_Alzheimers_Parkinsons | train | 0 | |
ec2de037caa934fae26890a823a4795a64c0cc2f | [
"try:\n sh.zfs('list', '-t', 'volume', self.name)\nexcept sh.ErrorReturnCode_1:\n return False\nreturn True",
"try:\n opts = ['create']\n if sparse:\n opts.append('-s')\n if block_size:\n opts.extend(['-b', block_size])\n if mkparent:\n opts.append('-p')\n opts.extend(['-... | <|body_start_0|>
try:
sh.zfs('list', '-t', 'volume', self.name)
except sh.ErrorReturnCode_1:
return False
return True
<|end_body_0|>
<|body_start_1|>
try:
opts = ['create']
if sparse:
opts.append('-s')
if block_... | Volume | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Volume:
def exists(self):
"""Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()"""
<|body_0|>
def create(self, size, sparse=False, block_size=None, mkparent=False):
"""Creates storage volume. volume = Volume('dpool/tmp/test0') volume.create()... | stack_v2_sparse_classes_10k_train_001095 | 13,193 | no_license | [
{
"docstring": "Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()",
"name": "exists",
"signature": "def exists(self)"
},
{
"docstring": "Creates storage volume. volume = Volume('dpool/tmp/test0') volume.create()",
"name": "create",
"signature": "def create(self,... | 4 | stack_v2_sparse_classes_30k_train_005856 | Implement the Python class `Volume` described below.
Class description:
Implement the Volume class.
Method signatures and docstrings:
- def exists(self): Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()
- def create(self, size, sparse=False, block_size=None, mkparent=False): Creates storage... | Implement the Python class `Volume` described below.
Class description:
Implement the Volume class.
Method signatures and docstrings:
- def exists(self): Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()
- def create(self, size, sparse=False, block_size=None, mkparent=False): Creates storage... | 9bc47e6eeff2944f98a0db4fcab32c5dd95fd025 | <|skeleton|>
class Volume:
def exists(self):
"""Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()"""
<|body_0|>
def create(self, size, sparse=False, block_size=None, mkparent=False):
"""Creates storage volume. volume = Volume('dpool/tmp/test0') volume.create()... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Volume:
def exists(self):
"""Checks if volume exists. volume = Volume('dpool/tmp/test0') volume.exists()"""
try:
sh.zfs('list', '-t', 'volume', self.name)
except sh.ErrorReturnCode_1:
return False
return True
def create(self, size, sparse=False, blo... | the_stack_v2_python_sparse | solarsanweb/storage/dataset.py | akatrevorjay/solarsanweb | train | 1 | |
f1f2ab8a2dd361b8dd32ad5e25f9c3c0393a02d9 | [
"if not field:\n raise ValueError('Empty field name.')\nif not is_string(field):\n raise TypeError('The field name must be a string, not {0}'.format(type(field).__name__))\nif ' ' in field:\n raise ValueError(\"Field name can't contain spaces.\")\nself.__field = field\nspecifications = _get_specifications(... | <|body_start_0|>
if not field:
raise ValueError('Empty field name.')
if not is_string(field):
raise TypeError('The field name must be a string, not {0}'.format(type(field).__name__))
if ' ' in field:
raise ValueError("Field name can't contain spaces.")
... | @Requires decorator Defines a required service | Requires | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggr... | stack_v2_sparse_classes_10k_train_001096 | 41,418 | permissive | [
{
"docstring": "Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggregate: If true, injects a list :param optional: If true, this injection is optional :param spec_filter: An LDAP query to filter injected services upon their properties :ra... | 2 | stack_v2_sparse_classes_30k_train_005846 | Implement the Python class `Requires` described below.
Class description:
@Requires decorator Defines a required service
Method signatures and docstrings:
- def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None): Sets up the requirement :param field: The injected field :param spec... | Implement the Python class `Requires` described below.
Class description:
@Requires decorator Defines a required service
Method signatures and docstrings:
- def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None): Sets up the requirement :param field: The injected field :param spec... | 686556cdde20beba77ae202de9969be46feed5e2 | <|skeleton|>
class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Requires:
"""@Requires decorator Defines a required service"""
def __init__(self, field, specification, aggregate=False, optional=False, spec_filter=None):
"""Sets up the requirement :param field: The injected field :param specification: The injected service specification :param aggregate: If tru... | the_stack_v2_python_sparse | python/src/lib/python/pelix/ipopo/decorators.py | cohorte/cohorte-runtime | train | 3 |
7a58c3ef9345b1d72a4c280dbd2c449d896c8605 | [
"Event.__init__(self)\nself.clearnames = []\nself.role = ''\nself.note_ref = []\nself.citation_ref = []\nself.place_ref = []\nself.place = None\nself.media_ref = []\nself.note_ref = []\nself.citations = []\nself.person = None",
"with shareds.driver.session() as session:\n try:\n result = session.run(Cyp... | <|body_start_0|>
Event.__init__(self)
self.clearnames = []
self.role = ''
self.note_ref = []
self.citation_ref = []
self.place_ref = []
self.place = None
self.media_ref = []
self.note_ref = []
self.citations = []
self.person = None
... | Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho". | Event_combo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Event_combo:
"""Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho"."""
... | stack_v2_sparse_classes_10k_train_001097 | 11,789 | no_license | [
{
"docstring": "Constructor Luo uuden Event_combo -instanssin",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Read this event with uniq_id's of related Place, Note, and Citation nodes. #TODO: Tulisi lukea Notes ja Citations vasta get_persondata_by_id() lopuksi Luetaan ... | 5 | stack_v2_sparse_classes_30k_train_007115 | Implement the Python class `Event_combo` described below.
Class description:
Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt väl... | Implement the Python class `Event_combo` described below.
Class description:
Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt väl... | 0f8d6ba035e3cca8dc756531b7cc51029a549a4f | <|skeleton|>
class Event_combo:
"""Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho"."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Event_combo:
"""Tapahtumat, lähteet, huomautukset, henkilön uniq_id Event combo includes operations for accessing - Event - related Sources, Notes - related Person id Lisäksi on kätevä olla metodi __str__(), joka antaa lyhyen sanalliseen muodon "syntynyt välillä 1.3.1840...31.3.1840 Hauho"."""
def __init... | the_stack_v2_python_sparse | models/gen/event_combo.py | kkujansuu/stk | train | 0 |
4dfa09e1565b6b96a428d2fb37b9789528f35d93 | [
"self.main_path = os.getcwd()\nself.model_name = params.model_name\nself.model_path = self.main_path + '\\\\' + self.model_name\nself.check_dir(self.model_path)\nself.log_path = self.main_path + '\\\\runs\\\\' + self.model_name\nself.check_dir(self.log_path, remove=True)\nself.save_model = params.save_model\nself.c... | <|body_start_0|>
self.main_path = os.getcwd()
self.model_name = params.model_name
self.model_path = self.main_path + '\\' + self.model_name
self.check_dir(self.model_path)
self.log_path = self.main_path + '\\runs\\' + self.model_name
self.check_dir(self.log_path, remove=T... | Initialize | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Initialize:
def __init__(self):
"""Constructor"""
<|body_0|>
def determine_device(self):
"""This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, otherwise it returns the CPU. :return: The device where tensor calc... | stack_v2_sparse_classes_10k_train_001098 | 3,336 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, otherwise it returns the CPU. :return: The device where tensor calculations shall be ... | 3 | stack_v2_sparse_classes_30k_train_006820 | Implement the Python class `Initialize` described below.
Class description:
Implement the Initialize class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def determine_device(self): This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, othe... | Implement the Python class `Initialize` described below.
Class description:
Implement the Initialize class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def determine_device(self): This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, othe... | ac74f3b7dfee21835fa0a29bf8202f33b9f15e28 | <|skeleton|>
class Initialize:
def __init__(self):
"""Constructor"""
<|body_0|>
def determine_device(self):
"""This function evaluates whether a GPU is accessible at the system and returns it as device to calculate on, otherwise it returns the CPU. :return: The device where tensor calc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Initialize:
def __init__(self):
"""Constructor"""
self.main_path = os.getcwd()
self.model_name = params.model_name
self.model_path = self.main_path + '\\' + self.model_name
self.check_dir(self.model_path)
self.log_path = self.main_path + '\\runs\\' + self.model_... | the_stack_v2_python_sparse | python/diffusion_sorption/experimental_data/exp02_init.py | cryptowealth-technology/finn | train | 0 | |
7db146d574f671f6762f066c0ca9ff85878642dd | [
"indices = []\ni = 0\nwhile i < radius * radius:\n indices.append((randrange(0, input_wh[0]), randrange(0, input_wh[1])))\n i = i + 1\nreturn indices",
"if input_wh[0] < cols_wh[0] or input_wh[1] < cols_wh[1]:\n raise NameError('Колонок как минимум по одному из измерений больше, чем элементов нижлежащего... | <|body_start_0|>
indices = []
i = 0
while i < radius * radius:
indices.append((randrange(0, input_wh[0]), randrange(0, input_wh[1])))
i = i + 1
return indices
<|end_body_0|>
<|body_start_1|>
if input_wh[0] < cols_wh[0] or input_wh[1] < cols_wh[1]:
... | Класс случайного маппера | RandomMapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomMapper:
"""Класс случайного маппера"""
def map_one(self, input_wh, colcoord, radius):
"""возвращает массив кортежей координат элементов входного поля input_wh, которые отнесены к колонке с координатами colcoord :param input_wh: размеры входного поля :param colcoord: координаты ... | stack_v2_sparse_classes_10k_train_001099 | 2,747 | no_license | [
{
"docstring": "возвращает массив кортежей координат элементов входного поля input_wh, которые отнесены к колонке с координатами colcoord :param input_wh: размеры входного поля :param colcoord: координаты колонки в поле колонок (подразумевается, что размерность входного поля и поля колонок одинакова) :param rad... | 2 | stack_v2_sparse_classes_30k_train_003163 | Implement the Python class `RandomMapper` described below.
Class description:
Класс случайного маппера
Method signatures and docstrings:
- def map_one(self, input_wh, colcoord, radius): возвращает массив кортежей координат элементов входного поля input_wh, которые отнесены к колонке с координатами colcoord :param inp... | Implement the Python class `RandomMapper` described below.
Class description:
Класс случайного маппера
Method signatures and docstrings:
- def map_one(self, input_wh, colcoord, radius): возвращает массив кортежей координат элементов входного поля input_wh, которые отнесены к колонке с координатами colcoord :param inp... | 672408433a11947c4e1ee037e97e62a17944e210 | <|skeleton|>
class RandomMapper:
"""Класс случайного маппера"""
def map_one(self, input_wh, colcoord, radius):
"""возвращает массив кортежей координат элементов входного поля input_wh, которые отнесены к колонке с координатами colcoord :param input_wh: размеры входного поля :param colcoord: координаты ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomMapper:
"""Класс случайного маппера"""
def map_one(self, input_wh, colcoord, radius):
"""возвращает массив кортежей координат элементов входного поля input_wh, которые отнесены к колонке с координатами colcoord :param input_wh: размеры входного поля :param colcoord: координаты колонки в пол... | the_stack_v2_python_sparse | spatialPooler/mappers/sp_random_mapper.py | cog-isa/htm-core | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.