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 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9b58f896e190c2494e9f7d106abbcd014d7140d1 | [
"self._wrapped = wrapped\nself._aspect = aspect\nself.__init_interceptor_members()",
"members = inspect.getmembers(self._wrapped, predicate=inspect.ismethod)\nfor name, member in members:\n if name.startswith('_'):\n continue\n else:\n setattr(self, name, self._aspect(member))",
"wrapped_att... | <|body_start_0|>
self._wrapped = wrapped
self._aspect = aspect
self.__init_interceptor_members()
<|end_body_0|>
<|body_start_1|>
members = inspect.getmembers(self._wrapped, predicate=inspect.ismethod)
for name, member in members:
if name.startswith('_'):
... | SimpleInterceptor is a class which implements an Interceptor pattern. SimpleInterceptor class is a class that mimics an interface of another class, intercepts calls to the methods of original class and are able to execute some code before, after or instead the original method. .. WARNING: SimpleInterceptor only mimics ... | SimpleInterceptor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleInterceptor:
"""SimpleInterceptor is a class which implements an Interceptor pattern. SimpleInterceptor class is a class that mimics an interface of another class, intercepts calls to the methods of original class and are able to execute some code before, after or instead the original metho... | stack_v2_sparse_classes_75kplus_train_069100 | 4,206 | permissive | [
{
"docstring": "Constructor if an interceptor object. :param wrapped: an instance to be wrapped by SimpleInterceptor :param aspect: a decorator function or other callable to be used for wrapping; this decorator function must to accept a callable to be wrapped as the first argument and return a function to be ca... | 3 | null | Implement the Python class `SimpleInterceptor` described below.
Class description:
SimpleInterceptor is a class which implements an Interceptor pattern. SimpleInterceptor class is a class that mimics an interface of another class, intercepts calls to the methods of original class and are able to execute some code befo... | Implement the Python class `SimpleInterceptor` described below.
Class description:
SimpleInterceptor is a class which implements an Interceptor pattern. SimpleInterceptor class is a class that mimics an interface of another class, intercepts calls to the methods of original class and are able to execute some code befo... | 029ee77d8512aeda1e15b486642db9692234f0cc | <|skeleton|>
class SimpleInterceptor:
"""SimpleInterceptor is a class which implements an Interceptor pattern. SimpleInterceptor class is a class that mimics an interface of another class, intercepts calls to the methods of original class and are able to execute some code before, after or instead the original metho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleInterceptor:
"""SimpleInterceptor is a class which implements an Interceptor pattern. SimpleInterceptor class is a class that mimics an interface of another class, intercepts calls to the methods of original class and are able to execute some code before, after or instead the original method. .. WARNING... | the_stack_v2_python_sparse | dpl/utils/simple_interceptor.py | s-kostyuk/everpl | train | 0 |
312588e7ffe7dd1fc6b11cd866583e8563f9c34f | [
"if m >= n:\n return head\nparent = None\np = head\nfor _ in range(m - 1):\n parent = p\n p = p.next\nt = p\ntmp = p.next\nchild = tmp\nfor _ in range(n - m):\n child = tmp\n if child:\n tmp = child.next\n child.next = p\n p = child\n else:\n break\nt.next = tmp\nif par... | <|body_start_0|>
if m >= n:
return head
parent = None
p = head
for _ in range(m - 1):
parent = p
p = p.next
t = p
tmp = p.next
child = tmp
for _ in range(n - m):
child = tmp
if child:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseBetween(self, head, m, n):
"""05/06/2018 01:00"""
<|body_0|>
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
"""08/08/2021 17:38"""
<|body_1|>
def reverseBetween(self, head: Optional[L... | stack_v2_sparse_classes_75kplus_train_069101 | 3,687 | no_license | [
{
"docstring": "05/06/2018 01:00",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head, m, n)"
},
{
"docstring": "08/08/2021 17:38",
"name": "reverseBetween",
"signature": "def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]"
... | 3 | stack_v2_sparse_classes_30k_train_043006 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head, m, n): 05/06/2018 01:00
- def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 08/08/2021 17:38
- def r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseBetween(self, head, m, n): 05/06/2018 01:00
- def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 08/08/2021 17:38
- def r... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def reverseBetween(self, head, m, n):
"""05/06/2018 01:00"""
<|body_0|>
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
"""08/08/2021 17:38"""
<|body_1|>
def reverseBetween(self, head: Optional[L... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseBetween(self, head, m, n):
"""05/06/2018 01:00"""
if m >= n:
return head
parent = None
p = head
for _ in range(m - 1):
parent = p
p = p.next
t = p
tmp = p.next
child = tmp
for _ in ... | the_stack_v2_python_sparse | leetcode/solved/92_Reverse_Linked_List_II/solution.py | sungminoh/algorithms | train | 0 | |
2e1d6c4b27da27a3747f05cb64b031592b664e5c | [
"Connector.__init__(self)\nself.client = client\nself.login = login\nif client is None or login is None:\n _LOG.error(\"sorry, you asked for an SSH connector but you don't have enough info\")\n _LOG.error('SSH connectors require, a client and a login')\n sys.exit(1)",
"cmd = 'ssh ' + self.login + '@' + s... | <|body_start_0|>
Connector.__init__(self)
self.client = client
self.login = login
if client is None or login is None:
_LOG.error("sorry, you asked for an SSH connector but you don't have enough info")
_LOG.error('SSH connectors require, a client and a login')
... | A connector which runs external commands on a remote machine through SSH. No password is required as this class assumes you have previously setup a password-less bridge between the local machine and the remote machine by exchanging certificates. Of course, an ssh executable should be installed on the local machine and ... | SSHconnector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHconnector:
"""A connector which runs external commands on a remote machine through SSH. No password is required as this class assumes you have previously setup a password-less bridge between the local machine and the remote machine by exchanging certificates. Of course, an ssh executable shoul... | stack_v2_sparse_classes_75kplus_train_069102 | 3,272 | no_license | [
{
"docstring": "Create a connector that runs commands on the specified client through SSH. The client argument should be a hostname or IP address of the remote machine where the command will run. The login is required.",
"name": "__init__",
"signature": "def __init__(self, client=None, login=None)"
},... | 4 | stack_v2_sparse_classes_30k_train_010780 | Implement the Python class `SSHconnector` described below.
Class description:
A connector which runs external commands on a remote machine through SSH. No password is required as this class assumes you have previously setup a password-less bridge between the local machine and the remote machine by exchanging certifica... | Implement the Python class `SSHconnector` described below.
Class description:
A connector which runs external commands on a remote machine through SSH. No password is required as this class assumes you have previously setup a password-less bridge between the local machine and the remote machine by exchanging certifica... | 24a74926170cbdfafa47e972644e2fe5b627d8ff | <|skeleton|>
class SSHconnector:
"""A connector which runs external commands on a remote machine through SSH. No password is required as this class assumes you have previously setup a password-less bridge between the local machine and the remote machine by exchanging certificates. Of course, an ssh executable shoul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSHconnector:
"""A connector which runs external commands on a remote machine through SSH. No password is required as this class assumes you have previously setup a password-less bridge between the local machine and the remote machine by exchanging certificates. Of course, an ssh executable should be installe... | the_stack_v2_python_sparse | robo4.2/4.2/lib/python2.7/site-packages/RoboGalaxyLibrary/configmgr/vulcanlib/ssh.py | richa92/Jenkin_Regression_Testing | train | 0 |
d8e10ba53d21360d27236c6a9c75ac9a0a26fdad | [
"self.data = data\nself.page_size = page_size\nself.is_start = False\nself.is_end = False\nself.page_count = len(data)\nself.next_page = 0\nself.previous_page = 0\nself.page_nmuber = self.page_count / page_size\nif self.page_nmuber == int(self.page_nmuber):\n self.page_nmuber = int(self.page_nmuber)\nelse:\n ... | <|body_start_0|>
self.data = data
self.page_size = page_size
self.is_start = False
self.is_end = False
self.page_count = len(data)
self.next_page = 0
self.previous_page = 0
self.page_nmuber = self.page_count / page_size
if self.page_nmuber == int(s... | flask分页通过sqlalachemy查询进行分页 offset 偏移,开始查询的位置 limit 单页条数 分页器需要具备的功能 页码 分页数据 是否第一页 是否最后一页 | Pager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pager:
"""flask分页通过sqlalachemy查询进行分页 offset 偏移,开始查询的位置 limit 单页条数 分页器需要具备的功能 页码 分页数据 是否第一页 是否最后一页"""
def __init__(self, data, page_size):
""":param data: 要分页的数据 :param page_size: 每页多少条"""
<|body_0|>
def page_data(self, page):
"""返回分页数据 :param page: 页码 page_size =... | stack_v2_sparse_classes_75kplus_train_069103 | 12,240 | permissive | [
{
"docstring": ":param data: 要分页的数据 :param page_size: 每页多少条",
"name": "__init__",
"signature": "def __init__(self, data, page_size)"
},
{
"docstring": "返回分页数据 :param page: 页码 page_size = 10 1 offect 0 limit(10) 2 offect 10 limit(10) page_size = 10 1 start 0 end 10 2 start 10 end 20 3 start 20 en... | 2 | stack_v2_sparse_classes_30k_train_005322 | Implement the Python class `Pager` described below.
Class description:
flask分页通过sqlalachemy查询进行分页 offset 偏移,开始查询的位置 limit 单页条数 分页器需要具备的功能 页码 分页数据 是否第一页 是否最后一页
Method signatures and docstrings:
- def __init__(self, data, page_size): :param data: 要分页的数据 :param page_size: 每页多少条
- def page_data(self, page): 返回分页数据 :param... | Implement the Python class `Pager` described below.
Class description:
flask分页通过sqlalachemy查询进行分页 offset 偏移,开始查询的位置 limit 单页条数 分页器需要具备的功能 页码 分页数据 是否第一页 是否最后一页
Method signatures and docstrings:
- def __init__(self, data, page_size): :param data: 要分页的数据 :param page_size: 每页多少条
- def page_data(self, page): 返回分页数据 :param... | 2fce76763eee9a177ace466c43169e80d5c5b73c | <|skeleton|>
class Pager:
"""flask分页通过sqlalachemy查询进行分页 offset 偏移,开始查询的位置 limit 单页条数 分页器需要具备的功能 页码 分页数据 是否第一页 是否最后一页"""
def __init__(self, data, page_size):
""":param data: 要分页的数据 :param page_size: 每页多少条"""
<|body_0|>
def page_data(self, page):
"""返回分页数据 :param page: 页码 page_size =... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Pager:
"""flask分页通过sqlalachemy查询进行分页 offset 偏移,开始查询的位置 limit 单页条数 分页器需要具备的功能 页码 分页数据 是否第一页 是否最后一页"""
def __init__(self, data, page_size):
""":param data: 要分页的数据 :param page_size: 每页多少条"""
self.data = data
self.page_size = page_size
self.is_start = False
self.is_end... | the_stack_v2_python_sparse | Flasknew/app/main/views.py | bestwishfang/PersonWork | train | 0 |
a2a4effc8b949d4162f295d13dab690a5b62ad61 | [
"try:\n horaDesde = horario_[0]\n horaHasta = horario_[1]\n dia = horario_[2]\n if horaDesde == '' and horaHasta != '':\n raise custom_exceptions.ErrorDeNegocio(origen='neogocio_horarios.valida_horarios()', msj_adicional='Error al añadir el Horario. El horario de cierre no puede quedar vacío si e... | <|body_start_0|>
try:
horaDesde = horario_[0]
horaHasta = horario_[1]
dia = horario_[2]
if horaDesde == '' and horaHasta != '':
raise custom_exceptions.ErrorDeNegocio(origen='neogocio_horarios.valida_horarios()', msj_adicional='Error al añadir el H... | NegocioHorario | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NegocioHorario:
def valida_horarios(cls, horario_):
"""Valida las RN referidas a los horarios."""
<|body_0|>
def alta_horarios(cls, horarios, idPuntoDep, pd=True, validar=False):
"""Añade los horarios de un PD o un PR a la BD."""
<|body_1|>
def mod_horar... | stack_v2_sparse_classes_75kplus_train_069104 | 5,384 | no_license | [
{
"docstring": "Valida las RN referidas a los horarios.",
"name": "valida_horarios",
"signature": "def valida_horarios(cls, horario_)"
},
{
"docstring": "Añade los horarios de un PD o un PR a la BD.",
"name": "alta_horarios",
"signature": "def alta_horarios(cls, horarios, idPuntoDep, pd=... | 3 | stack_v2_sparse_classes_30k_train_037784 | Implement the Python class `NegocioHorario` described below.
Class description:
Implement the NegocioHorario class.
Method signatures and docstrings:
- def valida_horarios(cls, horario_): Valida las RN referidas a los horarios.
- def alta_horarios(cls, horarios, idPuntoDep, pd=True, validar=False): Añade los horarios... | Implement the Python class `NegocioHorario` described below.
Class description:
Implement the NegocioHorario class.
Method signatures and docstrings:
- def valida_horarios(cls, horario_): Valida las RN referidas a los horarios.
- def alta_horarios(cls, horarios, idPuntoDep, pd=True, validar=False): Añade los horarios... | 57ca674dba4dabd2526c450ba7210933240f19c5 | <|skeleton|>
class NegocioHorario:
def valida_horarios(cls, horario_):
"""Valida las RN referidas a los horarios."""
<|body_0|>
def alta_horarios(cls, horarios, idPuntoDep, pd=True, validar=False):
"""Añade los horarios de un PD o un PR a la BD."""
<|body_1|>
def mod_horar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NegocioHorario:
def valida_horarios(cls, horario_):
"""Valida las RN referidas a los horarios."""
try:
horaDesde = horario_[0]
horaHasta = horario_[1]
dia = horario_[2]
if horaDesde == '' and horaHasta != '':
raise custom_exceptio... | the_stack_v2_python_sparse | negocio/negocio_horario.py | JoaquinCardonaRuiz/proyecto-final | train | 0 | |
e182f6aeb062aed844fff6e1b5e66deaba4ab8f6 | [
"if value != 'friends':\n raise serializers.ValidationError(\"Missing or invalid 'query: friends'\")\nreturn value",
"authors = []\nfor uuid in value:\n if Author.objects.filter(uuid=uuid).first():\n authors.append(uuid)\nreturn authors"
] | <|body_start_0|>
if value != 'friends':
raise serializers.ValidationError("Missing or invalid 'query: friends'")
return value
<|end_body_0|>
<|body_start_1|>
authors = []
for uuid in value:
if Author.objects.filter(uuid=uuid).first():
authors.appe... | Serializer for a Friend Query Object | FriendQuerySerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FriendQuerySerializer:
"""Serializer for a Friend Query Object"""
def validate_query(self, value):
"""Check that the friends: query key exists"""
<|body_0|>
def validate_authors(self, value):
"""Filter out invalid UUIDs and UUIDs that are unknown to us"""
... | stack_v2_sparse_classes_75kplus_train_069105 | 2,175 | permissive | [
{
"docstring": "Check that the friends: query key exists",
"name": "validate_query",
"signature": "def validate_query(self, value)"
},
{
"docstring": "Filter out invalid UUIDs and UUIDs that are unknown to us",
"name": "validate_authors",
"signature": "def validate_authors(self, value)"
... | 2 | null | Implement the Python class `FriendQuerySerializer` described below.
Class description:
Serializer for a Friend Query Object
Method signatures and docstrings:
- def validate_query(self, value): Check that the friends: query key exists
- def validate_authors(self, value): Filter out invalid UUIDs and UUIDs that are unk... | Implement the Python class `FriendQuerySerializer` described below.
Class description:
Serializer for a Friend Query Object
Method signatures and docstrings:
- def validate_query(self, value): Check that the friends: query key exists
- def validate_authors(self, value): Filter out invalid UUIDs and UUIDs that are unk... | a05a5161c415b546084bbe98b00e0671860c9bc6 | <|skeleton|>
class FriendQuerySerializer:
"""Serializer for a Friend Query Object"""
def validate_query(self, value):
"""Check that the friends: query key exists"""
<|body_0|>
def validate_authors(self, value):
"""Filter out invalid UUIDs and UUIDs that are unknown to us"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FriendQuerySerializer:
"""Serializer for a Friend Query Object"""
def validate_query(self, value):
"""Check that the friends: query key exists"""
if value != 'friends':
raise serializers.ValidationError("Missing or invalid 'query: friends'")
return value
def valid... | the_stack_v2_python_sparse | DistributedSocialNetworking/api/serializers/friend_serializers.py | Roshack/cmput410-project | train | 0 |
96525c26921dca755a3d635f338144a6c3fca082 | [
"super().__init__()\nself.win_size = win_size\nself.k1, self.k2 = (k1, k2)\nself.register_buffer('w', torch.ones(1, 1, win_size, win_size) / win_size ** 2)\nNP = win_size ** 2\nself.cov_norm = NP / (NP - 1)",
"if not isinstance(self.w, torch.Tensor):\n raise AssertionError\nself.w = self.w.to(X)\ndata_range = ... | <|body_start_0|>
super().__init__()
self.win_size = win_size
self.k1, self.k2 = (k1, k2)
self.register_buffer('w', torch.ones(1, 1, win_size, win_size) / win_size ** 2)
NP = win_size ** 2
self.cov_norm = NP / (NP - 1)
<|end_body_0|>
<|body_start_1|>
if not isinst... | SSIM loss module. | SSIMLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSIMLoss:
"""SSIM loss module."""
def __init__(self, win_size: int=7, k1: float=0.01, k2: float=0.03):
"""Args: win_size: Window size for SSIM calculation. k1: k1 parameter for SSIM calculation. k2: k2 parameter for SSIM calculation."""
<|body_0|>
def forward(self, X: to... | stack_v2_sparse_classes_75kplus_train_069106 | 1,882 | permissive | [
{
"docstring": "Args: win_size: Window size for SSIM calculation. k1: k1 parameter for SSIM calculation. k2: k2 parameter for SSIM calculation.",
"name": "__init__",
"signature": "def __init__(self, win_size: int=7, k1: float=0.01, k2: float=0.03)"
},
{
"docstring": "Parameters ---------- X: Fir... | 2 | null | Implement the Python class `SSIMLoss` described below.
Class description:
SSIM loss module.
Method signatures and docstrings:
- def __init__(self, win_size: int=7, k1: float=0.01, k2: float=0.03): Args: win_size: Window size for SSIM calculation. k1: k1 parameter for SSIM calculation. k2: k2 parameter for SSIM calcul... | Implement the Python class `SSIMLoss` described below.
Class description:
SSIM loss module.
Method signatures and docstrings:
- def __init__(self, win_size: int=7, k1: float=0.01, k2: float=0.03): Args: win_size: Window size for SSIM calculation. k1: k1 parameter for SSIM calculation. k2: k2 parameter for SSIM calcul... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class SSIMLoss:
"""SSIM loss module."""
def __init__(self, win_size: int=7, k1: float=0.01, k2: float=0.03):
"""Args: win_size: Window size for SSIM calculation. k1: k1 parameter for SSIM calculation. k2: k2 parameter for SSIM calculation."""
<|body_0|>
def forward(self, X: to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SSIMLoss:
"""SSIM loss module."""
def __init__(self, win_size: int=7, k1: float=0.01, k2: float=0.03):
"""Args: win_size: Window size for SSIM calculation. k1: k1 parameter for SSIM calculation. k2: k2 parameter for SSIM calculation."""
super().__init__()
self.win_size = win_size
... | the_stack_v2_python_sparse | mridc/collections/common/losses/ssim.py | wdika/mridc | train | 40 |
3acf05bcf141ed512f2b1033641a1c8336a22bbb | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"direction = choice([1, -1])\ndistance = choice([0, 1, 2, 3, 4])\nstep = direction * distance\nreturn step",
"while len(self.x_values) < self.num_points:\n x_step = self.get_step()\n y_step = self.get_step()\n if x_step == 0 and ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = direction * distance
return step
<|end_body_1|>
<|body_start_2|>
w... | Uma classe para gerar passeios aleatórios. | RandonWalk | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandonWalk:
"""Uma classe para gerar passeios aleatórios."""
def __init__(self, num_points=5000):
"""Inicia os atributos de um passeio."""
<|body_0|>
def get_step(self):
"""Decide a direção a ser seguida e a distância a ser percorrida."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_069107 | 1,317 | permissive | [
{
"docstring": "Inicia os atributos de um passeio.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Decide a direção a ser seguida e a distância a ser percorrida.",
"name": "get_step",
"signature": "def get_step(self)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_017814 | Implement the Python class `RandonWalk` described below.
Class description:
Uma classe para gerar passeios aleatórios.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Inicia os atributos de um passeio.
- def get_step(self): Decide a direção a ser seguida e a distância a ser percorrida.
- def ... | Implement the Python class `RandonWalk` described below.
Class description:
Uma classe para gerar passeios aleatórios.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Inicia os atributos de um passeio.
- def get_step(self): Decide a direção a ser seguida e a distância a ser percorrida.
- def ... | de88ba326cdd9c17a456161cdb2f9ca69f7da65e | <|skeleton|>
class RandonWalk:
"""Uma classe para gerar passeios aleatórios."""
def __init__(self, num_points=5000):
"""Inicia os atributos de um passeio."""
<|body_0|>
def get_step(self):
"""Decide a direção a ser seguida e a distância a ser percorrida."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandonWalk:
"""Uma classe para gerar passeios aleatórios."""
def __init__(self, num_points=5000):
"""Inicia os atributos de um passeio."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""Decide a direção a ser seguid... | the_stack_v2_python_sparse | PYTHON/Python-VisualizacaoDeDados/Dados-Gráficos/Random Walk/random_walk.py | sourcery-ai-bot/Estudos | train | 0 |
03f3b8a11843c08fc60b0aa8e7a4253013641031 | [
"Actor.__init__(self, name, level_logger, timeout)\nself.formula_init_function = formula_init_function\nself.state = DispatcherState(self, self._create_factory(pushers), route_table)",
"Actor.setup(self)\nif self.state.route_table.primary_dispatch_rule is None:\n raise NoPrimaryDispatchRuleRuleException()\nsel... | <|body_start_0|>
Actor.__init__(self, name, level_logger, timeout)
self.formula_init_function = formula_init_function
self.state = DispatcherState(self, self._create_factory(pushers), route_table)
<|end_body_0|>
<|body_start_1|>
Actor.setup(self)
if self.state.route_table.primar... | DispatcherActor class herited from Actor. Route message to the corresponding Formula, and create new one if no Formula exist for this message. | DispatcherActor | [
"BSD-3-Clause",
"Python-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DispatcherActor:
"""DispatcherActor class herited from Actor. Route message to the corresponding Formula, and create new one if no Formula exist for this message."""
def __init__(self, name: str, formula_init_function: Callable, pushers: [], route_table: RouteTable, level_logger: Literal=log... | stack_v2_sparse_classes_75kplus_train_069108 | 7,479 | permissive | [
{
"docstring": ":param str name: Actor name :param func formula_init_function: Function for creating Formula :param route_table: initialized route table of the DispatcherActor :param int level_logger: Define the level of the logger :param bool timeout: Define the time in millisecond to wait for a message before... | 3 | null | Implement the Python class `DispatcherActor` described below.
Class description:
DispatcherActor class herited from Actor. Route message to the corresponding Formula, and create new one if no Formula exist for this message.
Method signatures and docstrings:
- def __init__(self, name: str, formula_init_function: Calla... | Implement the Python class `DispatcherActor` described below.
Class description:
DispatcherActor class herited from Actor. Route message to the corresponding Formula, and create new one if no Formula exist for this message.
Method signatures and docstrings:
- def __init__(self, name: str, formula_init_function: Calla... | be3f1852ad38894c2bc487bbb3a30508ed8d6b50 | <|skeleton|>
class DispatcherActor:
"""DispatcherActor class herited from Actor. Route message to the corresponding Formula, and create new one if no Formula exist for this message."""
def __init__(self, name: str, formula_init_function: Callable, pushers: [], route_table: RouteTable, level_logger: Literal=log... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DispatcherActor:
"""DispatcherActor class herited from Actor. Route message to the corresponding Formula, and create new one if no Formula exist for this message."""
def __init__(self, name: str, formula_init_function: Callable, pushers: [], route_table: RouteTable, level_logger: Literal=logging.WARNING,... | the_stack_v2_python_sparse | powerapi/dispatcher/dispatcher_actor.py | powerapi-ng/powerapi | train | 143 |
adf550095a803aa4301cfad39fd497dd3c2291f7 | [
"dp = [0] * (amount + 1)\ndp[0] = 1\nfor i in coins:\n for j in range(1, amount + 1):\n if j >= i:\n dp[j] += dp[j - i]\nreturn dp[amount]",
"dp = [0] * (amount + 1)\ndp[0] = 1\nfor c in coins:\n for idx in range(1, len(dp)):\n if idx >= c:\n dp[idx] += dp[idx - c]\nretur... | <|body_start_0|>
dp = [0] * (amount + 1)
dp[0] = 1
for i in coins:
for j in range(1, amount + 1):
if j >= i:
dp[j] += dp[j - i]
return dp[amount]
<|end_body_0|>
<|body_start_1|>
dp = [0] * (amount + 1)
dp[0] = 1
for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def rewrite(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069109 | 1,745 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "rewrite",
"signature": "def rewrite(self, amount, coins)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014459 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def rewrite(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def rewrite(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
<|... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def rewrite(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
dp = [0] * (amount + 1)
dp[0] = 1
for i in coins:
for j in range(1, amount + 1):
if j >= i:
dp[j] += dp[j - i]
return dp... | the_stack_v2_python_sparse | dp/518_Coin_Change_2.py | vsdrun/lc_public | train | 6 | |
88e1f01bd2d7ab8ce73200f52accefaf782a35fb | [
"if norm_std and norm_mean and (len(norm_std) != len(norm_mean)):\n raise ValueError(f'norm_mean and norm_std are expected to be the same dim. But got {len(norm_mean)} and {len(norm_std)}')\nif tensor_type is _schema_fb.TensorType.UINT8:\n min_values = [_MIN_UINT8]\n max_values = [_MAX_UINT8]\nelif tensor_... | <|body_start_0|>
if norm_std and norm_mean and (len(norm_std) != len(norm_mean)):
raise ValueError(f'norm_mean and norm_std are expected to be the same dim. But got {len(norm_mean)} and {len(norm_std)}')
if tensor_type is _schema_fb.TensorType.UINT8:
min_values = [_MIN_UINT8]
... | A container for input image tensor metadata information. Attributes: norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same dimension. color_space_type: the color space type of the input image [2]. [1]: https://... | InputImageTensorMd | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputImageTensorMd:
"""A container for input image tensor metadata information. Attributes: norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same dimension. color_space_type: the color sp... | stack_v2_sparse_classes_75kplus_train_069110 | 32,760 | permissive | [
{
"docstring": "Initializes the instance of InputImageTensorMd. Args: name: name of the tensor. description: description of what the tensor is. norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same dime... | 2 | null | Implement the Python class `InputImageTensorMd` described below.
Class description:
A container for input image tensor metadata information. Attributes: norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same di... | Implement the Python class `InputImageTensorMd` described below.
Class description:
A container for input image tensor metadata information. Attributes: norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same di... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class InputImageTensorMd:
"""A container for input image tensor metadata information. Attributes: norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same dimension. color_space_type: the color sp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InputImageTensorMd:
"""A container for input image tensor metadata information. Attributes: norm_mean: the mean value used in tensor normalization [1]. norm_std: the std value used in the tensor normalization [1]. norm_mean and norm_std must have the same dimension. color_space_type: the color space type of t... | the_stack_v2_python_sparse | third_party/tflite_support/src/tensorflow_lite_support/metadata/python/metadata_writers/metadata_info.py | chromium/chromium | train | 17,408 |
2d75c2ea0fe56e1d5d34af2e465f157258b9179f | [
"Camera.__init__(self)\nself._installation = installation\nself._camera = camera\nself._auth = auth\nself._attr_unique_id = f'{installation.contract} {camera.id}'\nself._attr_name = camera.description\nself._attr_device_info = DeviceInfo(name=f'Contract {installation.contract}', manufacturer='Prosegur', model='smar... | <|body_start_0|>
Camera.__init__(self)
self._installation = installation
self._camera = camera
self._auth = auth
self._attr_unique_id = f'{installation.contract} {camera.id}'
self._attr_name = camera.description
self._attr_device_info = DeviceInfo(name=f'Contract ... | Representation of a Smart Prosegur Camera. | ProsegurCamera | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProsegurCamera:
"""Representation of a Smart Prosegur Camera."""
def __init__(self, installation: Installation, camera: InstallationCamera, auth: Auth) -> None:
"""Initialize Prosegur Camera component."""
<|body_0|>
async def async_camera_image(self, width: int | None=No... | stack_v2_sparse_classes_75kplus_train_069111 | 3,129 | permissive | [
{
"docstring": "Initialize Prosegur Camera component.",
"name": "__init__",
"signature": "def __init__(self, installation: Installation, camera: InstallationCamera, auth: Auth) -> None"
},
{
"docstring": "Return bytes of camera image.",
"name": "async_camera_image",
"signature": "async d... | 3 | stack_v2_sparse_classes_30k_train_016202 | Implement the Python class `ProsegurCamera` described below.
Class description:
Representation of a Smart Prosegur Camera.
Method signatures and docstrings:
- def __init__(self, installation: Installation, camera: InstallationCamera, auth: Auth) -> None: Initialize Prosegur Camera component.
- async def async_camera_... | Implement the Python class `ProsegurCamera` described below.
Class description:
Representation of a Smart Prosegur Camera.
Method signatures and docstrings:
- def __init__(self, installation: Installation, camera: InstallationCamera, auth: Auth) -> None: Initialize Prosegur Camera component.
- async def async_camera_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ProsegurCamera:
"""Representation of a Smart Prosegur Camera."""
def __init__(self, installation: Installation, camera: InstallationCamera, auth: Auth) -> None:
"""Initialize Prosegur Camera component."""
<|body_0|>
async def async_camera_image(self, width: int | None=No... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProsegurCamera:
"""Representation of a Smart Prosegur Camera."""
def __init__(self, installation: Installation, camera: InstallationCamera, auth: Auth) -> None:
"""Initialize Prosegur Camera component."""
Camera.__init__(self)
self._installation = installation
self._camera... | the_stack_v2_python_sparse | homeassistant/components/prosegur/camera.py | home-assistant/core | train | 35,501 |
9a7701153c40370d9ef8e20c5c195ba6844ee316 | [
"issue = playthrough_issue_registry.Registry.get_issue_by_type(stats_models.ISSUE_TYPE_EARLY_QUIT)\nissue_dict = issue.to_dict()\nself.assertItemsEqual(list(issue_dict.keys()), ['customization_arg_specs'])\nself.assertEqual(issue_dict['customization_arg_specs'], [{'name': 'state_name', 'description': 'State name', ... | <|body_start_0|>
issue = playthrough_issue_registry.Registry.get_issue_by_type(stats_models.ISSUE_TYPE_EARLY_QUIT)
issue_dict = issue.to_dict()
self.assertItemsEqual(list(issue_dict.keys()), ['customization_arg_specs'])
self.assertEqual(issue_dict['customization_arg_specs'], [{'name': 's... | Test that the default issues are valid. | IssueUnitTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssueUnitTests:
"""Test that the default issues are valid."""
def test_issue_properties_for_early_quit(self) -> None:
"""Test the standard properties of early quit issue."""
<|body_0|>
def test_issue_properties_for_multiple_incorrect_submissions(self) -> None:
""... | stack_v2_sparse_classes_75kplus_train_069112 | 3,980 | permissive | [
{
"docstring": "Test the standard properties of early quit issue.",
"name": "test_issue_properties_for_early_quit",
"signature": "def test_issue_properties_for_early_quit(self) -> None"
},
{
"docstring": "Test the standard properties of multiple incorrect submissions issue.",
"name": "test_i... | 3 | stack_v2_sparse_classes_30k_train_041193 | Implement the Python class `IssueUnitTests` described below.
Class description:
Test that the default issues are valid.
Method signatures and docstrings:
- def test_issue_properties_for_early_quit(self) -> None: Test the standard properties of early quit issue.
- def test_issue_properties_for_multiple_incorrect_submi... | Implement the Python class `IssueUnitTests` described below.
Class description:
Test that the default issues are valid.
Method signatures and docstrings:
- def test_issue_properties_for_early_quit(self) -> None: Test the standard properties of early quit issue.
- def test_issue_properties_for_multiple_incorrect_submi... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class IssueUnitTests:
"""Test that the default issues are valid."""
def test_issue_properties_for_early_quit(self) -> None:
"""Test the standard properties of early quit issue."""
<|body_0|>
def test_issue_properties_for_multiple_incorrect_submissions(self) -> None:
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IssueUnitTests:
"""Test that the default issues are valid."""
def test_issue_properties_for_early_quit(self) -> None:
"""Test the standard properties of early quit issue."""
issue = playthrough_issue_registry.Registry.get_issue_by_type(stats_models.ISSUE_TYPE_EARLY_QUIT)
issue_dic... | the_stack_v2_python_sparse | extensions/issues/base_test.py | oppia/oppia | train | 6,172 |
a3c9d88c3faf316543eb688ec18197ffd92631d2 | [
"self.map = map\npygame.sprite.Sprite.__init__(self)\nHero.__init__(self, self.map)\nhero_image = pygame.image.load(MC_GYVER_FILE).convert()\nself.hero_img = pygame.transform.scale(hero_image, (int(SPRITE_HEIGTH), int(SPRITE_WIDTH)))\nself.rect = self.hero_img.get_rect()\nstart_pos = self.map.get_start\nself.rect.x... | <|body_start_0|>
self.map = map
pygame.sprite.Sprite.__init__(self)
Hero.__init__(self, self.map)
hero_image = pygame.image.load(MC_GYVER_FILE).convert()
self.hero_img = pygame.transform.scale(hero_image, (int(SPRITE_HEIGTH), int(SPRITE_WIDTH)))
self.rect = self.hero_img.... | class hero --> The graphical hero : parent classes --> pygame.sprite.Sprite --> Sprites methods --> Hero (non graphical) --> the same attributes and methods instance attributes : - hero_img --> the sprite of the hero - rect -> the rectangle - rect.x - rect.y --> the position - old_x - old_y --> the old position | HeroGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeroGraph:
"""class hero --> The graphical hero : parent classes --> pygame.sprite.Sprite --> Sprites methods --> Hero (non graphical) --> the same attributes and methods instance attributes : - hero_img --> the sprite of the hero - rect -> the rectangle - rect.x - rect.y --> the position - old_x... | stack_v2_sparse_classes_75kplus_train_069113 | 2,297 | no_license | [
{
"docstring": "init of the parents + define the image and the scale of the Graphical Hero Args: map",
"name": "__init__",
"signature": "def __init__(self, map)"
},
{
"docstring": "use the parent's \"move\" method. The specificity of the graphical move is the width and the height of the sprites ... | 2 | null | Implement the Python class `HeroGraph` described below.
Class description:
class hero --> The graphical hero : parent classes --> pygame.sprite.Sprite --> Sprites methods --> Hero (non graphical) --> the same attributes and methods instance attributes : - hero_img --> the sprite of the hero - rect -> the rectangle - r... | Implement the Python class `HeroGraph` described below.
Class description:
class hero --> The graphical hero : parent classes --> pygame.sprite.Sprite --> Sprites methods --> Hero (non graphical) --> the same attributes and methods instance attributes : - hero_img --> the sprite of the hero - rect -> the rectangle - r... | d2f6e77e36dea6eb966bbfb455d16df713a42d53 | <|skeleton|>
class HeroGraph:
"""class hero --> The graphical hero : parent classes --> pygame.sprite.Sprite --> Sprites methods --> Hero (non graphical) --> the same attributes and methods instance attributes : - hero_img --> the sprite of the hero - rect -> the rectangle - rect.x - rect.y --> the position - old_x... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HeroGraph:
"""class hero --> The graphical hero : parent classes --> pygame.sprite.Sprite --> Sprites methods --> Hero (non graphical) --> the same attributes and methods instance attributes : - hero_img --> the sprite of the hero - rect -> the rectangle - rect.x - rect.y --> the position - old_x - old_y --> ... | the_stack_v2_python_sparse | models/herograph.py | jmlm74/P3-McGyver | train | 0 |
f0d1ae87e21a16855d6abe712c2858603703604f | [
"self.scenarios = scenarios\nself.output_path = Path(output_path)\nself.output_path.mkdir(exist_ok=True, parents=True)",
"for scenario in self.scenarios:\n scenario_folder = self.output_path / scenario.name\n scenario_folder.mkdir()\n pv_models = []\n pv_models.append(f'! PV Scenario for {scenario.pv_... | <|body_start_0|>
self.scenarios = scenarios
self.output_path = Path(output_path)
self.output_path.mkdir(exist_ok=True, parents=True)
<|end_body_0|>
<|body_start_1|>
for scenario in self.scenarios:
scenario_folder = self.output_path / scenario.name
scenario_folder... | Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios. | OpenDSSPVScenarioWriter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenDSSPVScenarioWriter:
"""Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios."""
def __init__(self, scenarios: List[data_model.DistPVScenarioModel... | stack_v2_sparse_classes_75kplus_train_069114 | 2,280 | permissive | [
{
"docstring": "Constructor for `OpenDSSPVScenarioWriter` class. Args: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios.",
"name": "__init__",
"signature": "def __init__(self, scenarios: List[data_model.DistPVScenarioModel], ... | 2 | stack_v2_sparse_classes_30k_train_053422 | Implement the Python class `OpenDSSPVScenarioWriter` described below.
Class description:
Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios.
Method signatures and docstrings:... | Implement the Python class `OpenDSSPVScenarioWriter` described below.
Class description:
Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios.
Method signatures and docstrings:... | 2185f4facec30b747f62618861321599b595d107 | <|skeleton|>
class OpenDSSPVScenarioWriter:
"""Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios."""
def __init__(self, scenarios: List[data_model.DistPVScenarioModel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenDSSPVScenarioWriter:
"""Writer class for exporting scenario in opendss format. Attributes: scenarios (List[data_model.DistPVScenarioModel]): List of pv scenarios output_path (str): Output path for writing the scenarios."""
def __init__(self, scenarios: List[data_model.DistPVScenarioModel], output_pat... | the_stack_v2_python_sparse | emerge/scenarios/opendss_writer.py | NREL/EMeRGE | train | 9 |
241bbd174e254690c8a3190583e377200ffc152b | [
"self._project = project\nself._zone = zone\nself._instance_group = instance_group\nself._job_name = job_name\nself._port = port\nself._credentials = credentials\nif credentials == 'default':\n if _GOOGLE_API_CLIENT_INSTALLED:\n self._credentials = GoogleCredentials.get_application_default()\nif service i... | <|body_start_0|>
self._project = project
self._zone = zone
self._instance_group = instance_group
self._job_name = job_name
self._port = port
self._credentials = credentials
if credentials == 'default':
if _GOOGLE_API_CLIENT_INSTALLED:
s... | Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance group and return a Cluster Resolver object suita... | GceClusterResolver | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GceClusterResolver:
"""Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance gr... | stack_v2_sparse_classes_75kplus_train_069115 | 5,116 | permissive | [
{
"docstring": "Creates a new GceClusterResolver object. This takes in a few parameters and creates a GceClusterResolver project. It will then use these parameters to query the GCE API for the IP addresses of each instance in the instance group. Args: project: Name of the GCE project zone: Zone of the GCE insta... | 2 | stack_v2_sparse_classes_30k_train_029825 | Implement the Python class `GceClusterResolver` described below.
Class description:
Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of a... | Implement the Python class `GceClusterResolver` described below.
Class description:
Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of a... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class GceClusterResolver:
"""Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance gr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GceClusterResolver:
"""Cluster Resolver for Google Compute Engine. This is an implementation of cluster resolvers for the Google Compute Engine instance group platform. By specifying a project, zone, and instance group, this will retrieve the IP address of all the instances within the instance group and retur... | the_stack_v2_python_sparse | Tensorflow_Pandas_Numpy/source3.6/tensorflow/contrib/cluster_resolver/python/training/gce_cluster_resolver.py | ryfeus/lambda-packs | train | 1,283 |
28ea648d324c154600ad045550dd3487c05949c4 | [
"super(DenseNetwork, self).__init__()\nassert layers_units, 'Please, set a list of units for each layer'\nassert activations, 'Please, set a list of activation functionsor a string for all of them.'\nself.gain_supported_activations = ['sigmoid', 'tanh', 'relu', 'leaky_relu']\nself.layers_units = layers_units\nself.... | <|body_start_0|>
super(DenseNetwork, self).__init__()
assert layers_units, 'Please, set a list of units for each layer'
assert activations, 'Please, set a list of activation functionsor a string for all of them.'
self.gain_supported_activations = ['sigmoid', 'tanh', 'relu', 'leaky_relu']... | DenseNetwork | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseNetwork:
def __init__(self, layers_units: list=None, activations: Union[list, str]=None, input_size: int=None, output_size: int=None, normalization: str='bypass', name: str='', last_bias: bool=True, last_activation: str='identity', **kwargs) -> None:
"""Dense (fully-connected) neura... | stack_v2_sparse_classes_75kplus_train_069116 | 21,575 | permissive | [
{
"docstring": "Dense (fully-connected) neural network written in PyTorch Parameters ---------- layers_units : list List with the number of neurons for each layer. activations : Union[list, str] List of activations for each layer or a single string informing the activation used for all of them. input_size : int... | 5 | null | Implement the Python class `DenseNetwork` described below.
Class description:
Implement the DenseNetwork class.
Method signatures and docstrings:
- def __init__(self, layers_units: list=None, activations: Union[list, str]=None, input_size: int=None, output_size: int=None, normalization: str='bypass', name: str='', la... | Implement the Python class `DenseNetwork` described below.
Class description:
Implement the DenseNetwork class.
Method signatures and docstrings:
- def __init__(self, layers_units: list=None, activations: Union[list, str]=None, input_size: int=None, output_size: int=None, normalization: str='bypass', name: str='', la... | 55c58ca0096a733559e7cc4f33d57693e75ffa37 | <|skeleton|>
class DenseNetwork:
def __init__(self, layers_units: list=None, activations: Union[list, str]=None, input_size: int=None, output_size: int=None, normalization: str='bypass', name: str='', last_bias: bool=True, last_activation: str='identity', **kwargs) -> None:
"""Dense (fully-connected) neura... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DenseNetwork:
def __init__(self, layers_units: list=None, activations: Union[list, str]=None, input_size: int=None, output_size: int=None, normalization: str='bypass', name: str='', last_bias: bool=True, last_activation: str='identity', **kwargs) -> None:
"""Dense (fully-connected) neural network writ... | the_stack_v2_python_sparse | simulai/regression/_pytorch/_dense.py | IBM/simulai | train | 73 | |
28d03ac4162639a97cb6ecfd0f3ae095d3b5bf29 | [
"num_train_examples = 1281167\nnum_validation_examples = int(num_train_examples * validation_percent)\nnum_train_examples -= num_validation_examples\nsuper(ImageNetDataset, self).__init__(name='imagenet', num_train_examples=num_train_examples, num_validation_examples=num_validation_examples, num_test_examples=50000... | <|body_start_0|>
num_train_examples = 1281167
num_validation_examples = int(num_train_examples * validation_percent)
num_train_examples -= num_validation_examples
super(ImageNetDataset, self).__init__(name='imagenet', num_train_examples=num_train_examples, num_validation_examples=num_val... | ImageNet dataset builder class. | ImageNetDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageNetDataset:
"""ImageNet dataset builder class."""
def __init__(self, batch_size: int, eval_batch_size: int, validation_percent: float=0.0, shuffle_buffer_size: int=None, num_parallel_parser_calls: int=64, data_dir: Optional[str]=None, **unused_kwargs: Dict[str, Any]):
"""Create ... | stack_v2_sparse_classes_75kplus_train_069117 | 4,922 | permissive | [
{
"docstring": "Create an ImageNet tf.data.Dataset builder. Args: batch_size: the training batch size. eval_batch_size: the validation and test batch size. validation_percent: the percent of the training set to use as a validation set. shuffle_buffer_size: the number of example to use in the shuffle buffer for ... | 3 | stack_v2_sparse_classes_30k_train_028085 | Implement the Python class `ImageNetDataset` described below.
Class description:
ImageNet dataset builder class.
Method signatures and docstrings:
- def __init__(self, batch_size: int, eval_batch_size: int, validation_percent: float=0.0, shuffle_buffer_size: int=None, num_parallel_parser_calls: int=64, data_dir: Opti... | Implement the Python class `ImageNetDataset` described below.
Class description:
ImageNet dataset builder class.
Method signatures and docstrings:
- def __init__(self, batch_size: int, eval_batch_size: int, validation_percent: float=0.0, shuffle_buffer_size: int=None, num_parallel_parser_calls: int=64, data_dir: Opti... | 88f78028fdfa6ed7a59eb79b549b14f328da5ba4 | <|skeleton|>
class ImageNetDataset:
"""ImageNet dataset builder class."""
def __init__(self, batch_size: int, eval_batch_size: int, validation_percent: float=0.0, shuffle_buffer_size: int=None, num_parallel_parser_calls: int=64, data_dir: Optional[str]=None, **unused_kwargs: Dict[str, Any]):
"""Create ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageNetDataset:
"""ImageNet dataset builder class."""
def __init__(self, batch_size: int, eval_batch_size: int, validation_percent: float=0.0, shuffle_buffer_size: int=None, num_parallel_parser_calls: int=64, data_dir: Optional[str]=None, **unused_kwargs: Dict[str, Any]):
"""Create an ImageNet t... | the_stack_v2_python_sparse | uncertainty_baselines/datasets/imagenet.py | kiminh/uncertainty-baselines | train | 1 |
0c54f863cc3b64768c2083b234c2e8d933142fc7 | [
"new_head = ListNode(None)\npointer = new_head\nwhile True:\n if l1 == None and l2 == None:\n break\n elif l1 == None:\n pointer.next = l2\n break\n elif l2 == None:\n pointer.next = l1\n break\n else:\n if l1.val < l2.val:\n pointer.next = l1\n ... | <|body_start_0|>
new_head = ListNode(None)
pointer = new_head
while True:
if l1 == None and l2 == None:
break
elif l1 == None:
pointer.next = l2
break
elif l2 == None:
pointer.next = l1
... | Iterative Solution Runtime: Runtime: 20 ms, faster than 95.09% of Python online submissions for Merge Two Sorted Lists. Memory Usage: 12.7 MB, less than 5.75% of Python online submissions for Merge Two Sorted Lists. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Iterative Solution Runtime: Runtime: 20 ms, faster than 95.09% of Python online submissions for Merge Two Sorted Lists. Memory Usage: 12.7 MB, less than 5.75% of Python online submissions for Merge Two Sorted Lists."""
def mergeTwoLists(self, l1, l2):
""":type l1: ListNo... | stack_v2_sparse_classes_75kplus_train_069118 | 2,452 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, ... | 2 | stack_v2_sparse_classes_30k_val_000822 | Implement the Python class `Solution` described below.
Class description:
Iterative Solution Runtime: Runtime: 20 ms, faster than 95.09% of Python online submissions for Merge Two Sorted Lists. Memory Usage: 12.7 MB, less than 5.75% of Python online submissions for Merge Two Sorted Lists.
Method signatures and docstr... | Implement the Python class `Solution` described below.
Class description:
Iterative Solution Runtime: Runtime: 20 ms, faster than 95.09% of Python online submissions for Merge Two Sorted Lists. Memory Usage: 12.7 MB, less than 5.75% of Python online submissions for Merge Two Sorted Lists.
Method signatures and docstr... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Iterative Solution Runtime: Runtime: 20 ms, faster than 95.09% of Python online submissions for Merge Two Sorted Lists. Memory Usage: 12.7 MB, less than 5.75% of Python online submissions for Merge Two Sorted Lists."""
def mergeTwoLists(self, l1, l2):
""":type l1: ListNo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""Iterative Solution Runtime: Runtime: 20 ms, faster than 95.09% of Python online submissions for Merge Two Sorted Lists. Memory Usage: 12.7 MB, less than 5.75% of Python online submissions for Merge Two Sorted Lists."""
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ... | the_stack_v2_python_sparse | 21-merge_two_linked_lists.py | stevestar888/leetcode-problems | train | 2 |
af449fec888454e20774a2d7dea5b75688ebc09b | [
"if request.method == 'POST':\n validator = validate_list_of_ids(request.data, max_query=500)\n if validator['has_errors']:\n return Response({'message': validator['message'], 'data': request.data})\n result, qt = timeit(get_sequence_type, request.data['ids'], request.user)\n return self.formatte... | <|body_start_0|>
if request.method == 'POST':
validator = validate_list_of_ids(request.data, max_query=500)
if validator['has_errors']:
return Response({'message': validator['message'], 'data': request.data})
result, qt = timeit(get_sequence_type, request.data... | A simple ViewSet for listing or retrieving Samples. | MLSTViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLSTViewSet:
"""A simple ViewSet for listing or retrieving Samples."""
def bulk_by_sample(self, request):
"""Given a list of sample IDs, return MLST results."""
<|body_0|>
def blast_by_sample(self, request):
"""Given a list of sample IDs, return BLAST results."""... | stack_v2_sparse_classes_75kplus_train_069119 | 3,651 | no_license | [
{
"docstring": "Given a list of sample IDs, return MLST results.",
"name": "bulk_by_sample",
"signature": "def bulk_by_sample(self, request)"
},
{
"docstring": "Given a list of sample IDs, return BLAST results.",
"name": "blast_by_sample",
"signature": "def blast_by_sample(self, request)... | 3 | stack_v2_sparse_classes_30k_train_049756 | Implement the Python class `MLSTViewSet` described below.
Class description:
A simple ViewSet for listing or retrieving Samples.
Method signatures and docstrings:
- def bulk_by_sample(self, request): Given a list of sample IDs, return MLST results.
- def blast_by_sample(self, request): Given a list of sample IDs, ret... | Implement the Python class `MLSTViewSet` described below.
Class description:
A simple ViewSet for listing or retrieving Samples.
Method signatures and docstrings:
- def bulk_by_sample(self, request): Given a list of sample IDs, return MLST results.
- def blast_by_sample(self, request): Given a list of sample IDs, ret... | 2c35ee47e131a74642e60fae6f1cc23561d8b1a6 | <|skeleton|>
class MLSTViewSet:
"""A simple ViewSet for listing or retrieving Samples."""
def bulk_by_sample(self, request):
"""Given a list of sample IDs, return MLST results."""
<|body_0|>
def blast_by_sample(self, request):
"""Given a list of sample IDs, return BLAST results."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MLSTViewSet:
"""A simple ViewSet for listing or retrieving Samples."""
def bulk_by_sample(self, request):
"""Given a list of sample IDs, return MLST results."""
if request.method == 'POST':
validator = validate_list_of_ids(request.data, max_query=500)
if validator[... | the_stack_v2_python_sparse | api/viewsets/sequence_types.py | staphopia/staphopia-web | train | 5 |
a530d99784dded41bcf36671d3bcafca36a96681 | [
"user = UserHelper.parse_from_body_request(req)\nUserHelper.save(user)\nreq.context['result'] = {'status': {'code': 200, 'message': 'success'}}\nres.status = falcon.HTTP_200",
"user = UserHelper.parse_from_query_string_request(req)\nlist_user = UserHelper.find(user)\nreq.context['result'] = {'data': [user.to_dict... | <|body_start_0|>
user = UserHelper.parse_from_body_request(req)
UserHelper.save(user)
req.context['result'] = {'status': {'code': 200, 'message': 'success'}}
res.status = falcon.HTTP_200
<|end_body_0|>
<|body_start_1|>
user = UserHelper.parse_from_query_string_request(req)
... | ListUserListener | ListUserListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListUserListener:
"""ListUserListener"""
def on_post(self, req, res):
"""handle POST requests"""
<|body_0|>
def on_get(self, req, res):
"""handle GET requests"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = UserHelper.parse_from_body_requ... | stack_v2_sparse_classes_75kplus_train_069120 | 1,694 | no_license | [
{
"docstring": "handle POST requests",
"name": "on_post",
"signature": "def on_post(self, req, res)"
},
{
"docstring": "handle GET requests",
"name": "on_get",
"signature": "def on_get(self, req, res)"
}
] | 2 | null | Implement the Python class `ListUserListener` described below.
Class description:
ListUserListener
Method signatures and docstrings:
- def on_post(self, req, res): handle POST requests
- def on_get(self, req, res): handle GET requests | Implement the Python class `ListUserListener` described below.
Class description:
ListUserListener
Method signatures and docstrings:
- def on_post(self, req, res): handle POST requests
- def on_get(self, req, res): handle GET requests
<|skeleton|>
class ListUserListener:
"""ListUserListener"""
def on_post(s... | 11b885c11fe3b506f092c9aa1c22e1062f5f1e70 | <|skeleton|>
class ListUserListener:
"""ListUserListener"""
def on_post(self, req, res):
"""handle POST requests"""
<|body_0|>
def on_get(self, req, res):
"""handle GET requests"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListUserListener:
"""ListUserListener"""
def on_post(self, req, res):
"""handle POST requests"""
user = UserHelper.parse_from_body_request(req)
UserHelper.save(user)
req.context['result'] = {'status': {'code': 200, 'message': 'success'}}
res.status = falcon.HTTP_20... | the_stack_v2_python_sparse | lib/listener/user.py | arsystem/warehouse.api | train | 0 |
844264332a6c08a280fbe4322106d8a6d92661fc | [
"self.launchpad = launchpad\nself.fworker = fworker\nself.fw_id = fw_id",
"lp = self.launchpad\nlaunch_dir = os.path.abspath(os.getcwd())\nm_fw, launch_id = lp._checkout_fw(self.fworker, launch_dir, self.fw_id)\nif not m_fw:\n raise ValueError('No FireWorks are ready to run and match query! {}'.format(self.fwo... | <|body_start_0|>
self.launchpad = launchpad
self.fworker = fworker
self.fw_id = fw_id
<|end_body_0|>
<|body_start_1|>
lp = self.launchpad
launch_dir = os.path.abspath(os.getcwd())
m_fw, launch_id = lp._checkout_fw(self.fworker, launch_dir, self.fw_id)
if not m_fw... | The Rocket fetches a workflow step from the FireWorks database and executes it. | Rocket | [
"LicenseRef-scancode-hdf5",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rocket:
"""The Rocket fetches a workflow step from the FireWorks database and executes it."""
def __init__(self, launchpad, fworker, fw_id):
""":param launchpad: A LaunchPad object for interacting with the FW database :param fworker: A FWorker object describing the computing resource... | stack_v2_sparse_classes_75kplus_train_069121 | 2,976 | permissive | [
{
"docstring": ":param launchpad: A LaunchPad object for interacting with the FW database :param fworker: A FWorker object describing the computing resource",
"name": "__init__",
"signature": "def __init__(self, launchpad, fworker, fw_id)"
},
{
"docstring": "Run the rocket (actually check out a ... | 2 | stack_v2_sparse_classes_30k_train_023704 | Implement the Python class `Rocket` described below.
Class description:
The Rocket fetches a workflow step from the FireWorks database and executes it.
Method signatures and docstrings:
- def __init__(self, launchpad, fworker, fw_id): :param launchpad: A LaunchPad object for interacting with the FW database :param fw... | Implement the Python class `Rocket` described below.
Class description:
The Rocket fetches a workflow step from the FireWorks database and executes it.
Method signatures and docstrings:
- def __init__(self, launchpad, fworker, fw_id): :param launchpad: A LaunchPad object for interacting with the FW database :param fw... | f12d2587467c89044e3778afc60782b5a1df0be2 | <|skeleton|>
class Rocket:
"""The Rocket fetches a workflow step from the FireWorks database and executes it."""
def __init__(self, launchpad, fworker, fw_id):
""":param launchpad: A LaunchPad object for interacting with the FW database :param fworker: A FWorker object describing the computing resource... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rocket:
"""The Rocket fetches a workflow step from the FireWorks database and executes it."""
def __init__(self, launchpad, fworker, fw_id):
""":param launchpad: A LaunchPad object for interacting with the FW database :param fworker: A FWorker object describing the computing resource"""
s... | the_stack_v2_python_sparse | fireworks/core/rocket.py | yanikou19/fireworks | train | 0 |
8c9ec614f83314eb3b68788a60ccd2359d719b59 | [
"super(BaselineEarlyFusionStackSE, self).__init__()\nself.multi_extractor = MultiExtractor(cfg)\nconv_style = 'Conv1d'\nself.se_layer = nn.ModuleList([SEEncoderLayer(channel=cfg.MODALITY.NUMS, reduction=1, conv_style=conv_style, max_pool=max_pool) for _ in range(n_layer)])\nif cfg.MODEL.FEATURE_FUSION == 'add':\n ... | <|body_start_0|>
super(BaselineEarlyFusionStackSE, self).__init__()
self.multi_extractor = MultiExtractor(cfg)
conv_style = 'Conv1d'
self.se_layer = nn.ModuleList([SEEncoderLayer(channel=cfg.MODALITY.NUMS, reduction=1, conv_style=conv_style, max_pool=max_pool) for _ in range(n_layer)])
... | BaselineEarlyFusionStackSE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaselineEarlyFusionStackSE:
def __init__(self, cfg, max_pool=False, n_layer=1):
""":param num_class: :param requirements: Should not include class part."""
<|body_0|>
def forward(self, x, return_feature=False):
""":param x: A list of tensor :return:"""
<|body... | stack_v2_sparse_classes_75kplus_train_069122 | 8,984 | no_license | [
{
"docstring": ":param num_class: :param requirements: Should not include class part.",
"name": "__init__",
"signature": "def __init__(self, cfg, max_pool=False, n_layer=1)"
},
{
"docstring": ":param x: A list of tensor :return:",
"name": "forward",
"signature": "def forward(self, x, ret... | 2 | stack_v2_sparse_classes_30k_train_014067 | Implement the Python class `BaselineEarlyFusionStackSE` described below.
Class description:
Implement the BaselineEarlyFusionStackSE class.
Method signatures and docstrings:
- def __init__(self, cfg, max_pool=False, n_layer=1): :param num_class: :param requirements: Should not include class part.
- def forward(self, ... | Implement the Python class `BaselineEarlyFusionStackSE` described below.
Class description:
Implement the BaselineEarlyFusionStackSE class.
Method signatures and docstrings:
- def __init__(self, cfg, max_pool=False, n_layer=1): :param num_class: :param requirements: Should not include class part.
- def forward(self, ... | 390acce96c8422fff1a6e14e86437b3cc2e414cb | <|skeleton|>
class BaselineEarlyFusionStackSE:
def __init__(self, cfg, max_pool=False, n_layer=1):
""":param num_class: :param requirements: Should not include class part."""
<|body_0|>
def forward(self, x, return_feature=False):
""":param x: A list of tensor :return:"""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaselineEarlyFusionStackSE:
def __init__(self, cfg, max_pool=False, n_layer=1):
""":param num_class: :param requirements: Should not include class part."""
super(BaselineEarlyFusionStackSE, self).__init__()
self.multi_extractor = MultiExtractor(cfg)
conv_style = 'Conv1d'
... | the_stack_v2_python_sparse | libs/models/baseline.py | wkoa/Multimodal_USMC | train | 0 | |
0960020f36e83c50446ef6ea1006b6c5531c6f8d | [
"if legacy_pyroot:\n l = ROOT.Long(pylong(42))\n self.assertEqual(l, pylong(42))\n self.assertEqual(l / 7, pylong(6))\n self.assertEqual(l * pylong(1), l)\n import math\n d = ROOT.Double(math.pi)\n self.assertEqual(d, math.pi)\n self.assertEqual(d * math.pi, math.pi * math.pi)",
"SetLongTh... | <|body_start_0|>
if legacy_pyroot:
l = ROOT.Long(pylong(42))
self.assertEqual(l, pylong(42))
self.assertEqual(l / 7, pylong(6))
self.assertEqual(l * pylong(1), l)
import math
d = ROOT.Double(math.pi)
self.assertEqual(d, math.pi)... | Cpp03PassByNonConstRef | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cpp03PassByNonConstRef:
def test1TestPlaceHolders(self):
"""Test usage of Long/Double place holders"""
<|body_0|>
def test2PassBuiltinsByNonConstRef(self):
"""Test parameter passing of builtins through non-const reference"""
<|body_1|>
def test3PassBuilt... | stack_v2_sparse_classes_75kplus_train_069123 | 30,462 | no_license | [
{
"docstring": "Test usage of Long/Double place holders",
"name": "test1TestPlaceHolders",
"signature": "def test1TestPlaceHolders(self)"
},
{
"docstring": "Test parameter passing of builtins through non-const reference",
"name": "test2PassBuiltinsByNonConstRef",
"signature": "def test2P... | 3 | stack_v2_sparse_classes_30k_val_002863 | Implement the Python class `Cpp03PassByNonConstRef` described below.
Class description:
Implement the Cpp03PassByNonConstRef class.
Method signatures and docstrings:
- def test1TestPlaceHolders(self): Test usage of Long/Double place holders
- def test2PassBuiltinsByNonConstRef(self): Test parameter passing of builtin... | Implement the Python class `Cpp03PassByNonConstRef` described below.
Class description:
Implement the Cpp03PassByNonConstRef class.
Method signatures and docstrings:
- def test1TestPlaceHolders(self): Test usage of Long/Double place holders
- def test2PassBuiltinsByNonConstRef(self): Test parameter passing of builtin... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class Cpp03PassByNonConstRef:
def test1TestPlaceHolders(self):
"""Test usage of Long/Double place holders"""
<|body_0|>
def test2PassBuiltinsByNonConstRef(self):
"""Test parameter passing of builtins through non-const reference"""
<|body_1|>
def test3PassBuilt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cpp03PassByNonConstRef:
def test1TestPlaceHolders(self):
"""Test usage of Long/Double place holders"""
if legacy_pyroot:
l = ROOT.Long(pylong(42))
self.assertEqual(l, pylong(42))
self.assertEqual(l / 7, pylong(6))
self.assertEqual(l * pylong(1), ... | the_stack_v2_python_sparse | python/cpp/PyROOT_advancedtests.py | root-project/roottest | train | 41 | |
7913190de322b4322715fefb2b0af1fb2da81421 | [
"self.latitude = latitude\nself.longitude = longitude\nself.identified_place = identified_place\nself.identified_state = identified_state\nself.distance_from = distance_from\nself.direction_from = direction_from",
"if dictionary is None:\n return None\nlatitude = dictionary.get('latitude')\nlongitude = diction... | <|body_start_0|>
self.latitude = latitude
self.longitude = longitude
self.identified_place = identified_place
self.identified_state = identified_state
self.distance_from = distance_from
self.direction_from = direction_from
<|end_body_0|>
<|body_start_1|>
if dicti... | Implementation of the 'Compliance Location' model. TODO: type model description here. Attributes: latitude (float): the latitude of this location longitude (float): the longitude of this location identified_place (string): place name of the identified geo-location identified_state (string): state/province abbreviate of... | ComplianceLocation | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplianceLocation:
"""Implementation of the 'Compliance Location' model. TODO: type model description here. Attributes: latitude (float): the latitude of this location longitude (float): the longitude of this location identified_place (string): place name of the identified geo-location identifie... | stack_v2_sparse_classes_75kplus_train_069124 | 2,865 | permissive | [
{
"docstring": "Constructor for the ComplianceLocation class",
"name": "__init__",
"signature": "def __init__(self, latitude=None, longitude=None, identified_place=None, identified_state=None, distance_from=None, direction_from=None)"
},
{
"docstring": "Creates an instance of this model from a d... | 2 | stack_v2_sparse_classes_30k_train_024264 | Implement the Python class `ComplianceLocation` described below.
Class description:
Implementation of the 'Compliance Location' model. TODO: type model description here. Attributes: latitude (float): the latitude of this location longitude (float): the longitude of this location identified_place (string): place name o... | Implement the Python class `ComplianceLocation` described below.
Class description:
Implementation of the 'Compliance Location' model. TODO: type model description here. Attributes: latitude (float): the latitude of this location longitude (float): the longitude of this location identified_place (string): place name o... | 729e9391879e273545a4818558677b2e47261f08 | <|skeleton|>
class ComplianceLocation:
"""Implementation of the 'Compliance Location' model. TODO: type model description here. Attributes: latitude (float): the latitude of this location longitude (float): the longitude of this location identified_place (string): place name of the identified geo-location identifie... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComplianceLocation:
"""Implementation of the 'Compliance Location' model. TODO: type model description here. Attributes: latitude (float): the latitude of this location longitude (float): the longitude of this location identified_place (string): place name of the identified geo-location identified_state (stri... | the_stack_v2_python_sparse | sdk/python/v0.1-rc.4/opentelematicsapi/models/compliance_location.py | nmfta-repo/nmfta-opentelematics-prototype | train | 2 |
0d9c4334fc53e39470fd64725f5aff4c93626e94 | [
"config = Configuration()\nconfig.DEFAULT['localhost'] = '192.168.0.1'\nconfig.DEFAULT['port'] = 8080\nconfig.DEFAULT['connection_timeout'] = 60\nconfig.add_section('Test')\nconfig.Test['key1'] = 100\nconfig.Test['key2'] = 123.456\nconfig.Test['key3'] = 'True'\nconfig.Test['key4'] = '123'\nconfig.Test['key5'] = 'C:... | <|body_start_0|>
config = Configuration()
config.DEFAULT['localhost'] = '192.168.0.1'
config.DEFAULT['port'] = 8080
config.DEFAULT['connection_timeout'] = 60
config.add_section('Test')
config.Test['key1'] = 100
config.Test['key2'] = 123.456
config.Test['ke... | ConfigurationUnittest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigurationUnittest:
def setUp(self):
"""从config dump到本地文件, 以供检视"""
<|body_0|>
def test_load(self):
"""测试Configuration.load()方法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
config = Configuration()
config.DEFAULT['localhost'] = '192.168... | stack_v2_sparse_classes_75kplus_train_069125 | 16,385 | no_license | [
{
"docstring": "从config dump到本地文件, 以供检视",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "测试Configuration.load()方法",
"name": "test_load",
"signature": "def test_load(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048033 | Implement the Python class `ConfigurationUnittest` described below.
Class description:
Implement the ConfigurationUnittest class.
Method signatures and docstrings:
- def setUp(self): 从config dump到本地文件, 以供检视
- def test_load(self): 测试Configuration.load()方法 | Implement the Python class `ConfigurationUnittest` described below.
Class description:
Implement the ConfigurationUnittest class.
Method signatures and docstrings:
- def setUp(self): 从config dump到本地文件, 以供检视
- def test_load(self): 测试Configuration.load()方法
<|skeleton|>
class ConfigurationUnittest:
def setUp(self)... | e4db975abf8566074cd610b1f026f858db047a9e | <|skeleton|>
class ConfigurationUnittest:
def setUp(self):
"""从config dump到本地文件, 以供检视"""
<|body_0|>
def test_load(self):
"""测试Configuration.load()方法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConfigurationUnittest:
def setUp(self):
"""从config dump到本地文件, 以供检视"""
config = Configuration()
config.DEFAULT['localhost'] = '192.168.0.1'
config.DEFAULT['port'] = 8080
config.DEFAULT['connection_timeout'] = 60
config.add_section('Test')
config.Test['key... | the_stack_v2_python_sparse | angora/GADGET/configuration.py | MacHu-GWU/Angora | train | 0 | |
d9e4c0b1e656495efe939a88b5e7ca0538eca021 | [
"self._handle = None\nself._done = False\nself.store = store\nself.options = options or {}\nself.page_size = page_size or DEFAULT_PAGE_SIZE\nself.tag_query = tag_query\nself.type_filter = type_filter",
"if self._done:\n raise StorageSearchError('Search query is complete')\nawait self._open()\ntry:\n result_... | <|body_start_0|>
self._handle = None
self._done = False
self.store = store
self.options = options or {}
self.page_size = page_size or DEFAULT_PAGE_SIZE
self.tag_query = tag_query
self.type_filter = type_filter
<|end_body_0|>
<|body_start_1|>
if self._done... | Represent an active stored records search. | IndySdkStorageSearch | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndySdkStorageSearch:
"""Represent an active stored records search."""
def __init__(self, store: IndySdkStorage, type_filter: str, tag_query: Mapping, page_size: int=None, options: Mapping=None):
"""Initialize a `IndySdkStorageSearch` instance. Args: store: `BaseStorage` to search ty... | stack_v2_sparse_classes_75kplus_train_069126 | 10,545 | permissive | [
{
"docstring": "Initialize a `IndySdkStorageSearch` instance. Args: store: `BaseStorage` to search type_filter: Filter string tag_query: Tags to search page_size: Size of page to return",
"name": "__init__",
"signature": "def __init__(self, store: IndySdkStorage, type_filter: str, tag_query: Mapping, pa... | 5 | null | Implement the Python class `IndySdkStorageSearch` described below.
Class description:
Represent an active stored records search.
Method signatures and docstrings:
- def __init__(self, store: IndySdkStorage, type_filter: str, tag_query: Mapping, page_size: int=None, options: Mapping=None): Initialize a `IndySdkStorage... | Implement the Python class `IndySdkStorageSearch` described below.
Class description:
Represent an active stored records search.
Method signatures and docstrings:
- def __init__(self, store: IndySdkStorage, type_filter: str, tag_query: Mapping, page_size: int=None, options: Mapping=None): Initialize a `IndySdkStorage... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class IndySdkStorageSearch:
"""Represent an active stored records search."""
def __init__(self, store: IndySdkStorage, type_filter: str, tag_query: Mapping, page_size: int=None, options: Mapping=None):
"""Initialize a `IndySdkStorageSearch` instance. Args: store: `BaseStorage` to search ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IndySdkStorageSearch:
"""Represent an active stored records search."""
def __init__(self, store: IndySdkStorage, type_filter: str, tag_query: Mapping, page_size: int=None, options: Mapping=None):
"""Initialize a `IndySdkStorageSearch` instance. Args: store: `BaseStorage` to search type_filter: Fi... | the_stack_v2_python_sparse | aries_cloudagent/storage/indy.py | hyperledger/aries-cloudagent-python | train | 370 |
645e1d66734a0468176f2b3c7793cdf28e37a219 | [
"def is_valid(s: str):\n char_set = set(s)\n return len(char_set) == len(s)\nmax_len = 0\nsubstr = ''\nn = len(s)\nfor i in range(n):\n for j in range(i + max_len + 1, n + 1):\n tmp = s[i:j]\n if is_valid(tmp):\n max_len = j - i\n substr = tmp\n else:\n ... | <|body_start_0|>
def is_valid(s: str):
char_set = set(s)
return len(char_set) == len(s)
max_len = 0
substr = ''
n = len(s)
for i in range(n):
for j in range(i + max_len + 1, n + 1):
tmp = s[i:j]
if is_valid(tmp):... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def method_v1(self, s: str) -> int:
"""Simple, brute force method. Complexity: All combinations: n + (n-1) + (n-2) ... + 1 ~= n(n-1)/2 Then it takes time to check validity O(n) Total is O(n^3)"""
<|body_0|>
def method_v2(self, s: str) -> int:
"""Linear time... | stack_v2_sparse_classes_75kplus_train_069127 | 2,653 | no_license | [
{
"docstring": "Simple, brute force method. Complexity: All combinations: n + (n-1) + (n-2) ... + 1 ~= n(n-1)/2 Then it takes time to check validity O(n) Total is O(n^3)",
"name": "method_v1",
"signature": "def method_v1(self, s: str) -> int"
},
{
"docstring": "Linear time. Here we track the cur... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def method_v1(self, s: str) -> int: Simple, brute force method. Complexity: All combinations: n + (n-1) + (n-2) ... + 1 ~= n(n-1)/2 Then it takes time to check validity O(n) Tota... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def method_v1(self, s: str) -> int: Simple, brute force method. Complexity: All combinations: n + (n-1) + (n-2) ... + 1 ~= n(n-1)/2 Then it takes time to check validity O(n) Tota... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def method_v1(self, s: str) -> int:
"""Simple, brute force method. Complexity: All combinations: n + (n-1) + (n-2) ... + 1 ~= n(n-1)/2 Then it takes time to check validity O(n) Total is O(n^3)"""
<|body_0|>
def method_v2(self, s: str) -> int:
"""Linear time... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def method_v1(self, s: str) -> int:
"""Simple, brute force method. Complexity: All combinations: n + (n-1) + (n-2) ... + 1 ~= n(n-1)/2 Then it takes time to check validity O(n) Total is O(n^3)"""
def is_valid(s: str):
char_set = set(s)
return len(char_set) == ... | the_stack_v2_python_sparse | python3/string_array/longest_substring_without_repeating_characters.py | victorchu/algorithms | train | 0 | |
4613ba4b57df850b287104fb0ca38e2226e75040 | [
"self.verbose(result.show(display_guest=display_guest), shift=1)\nif verbosity == 1:\n return\nassert self.step.plan.execute.workdir is not None\nfor log_file in result.log:\n log_name = log_file.name\n full_path = self.step.plan.execute.workdir / log_file\n self.verbose(log_name, str(full_path), color=... | <|body_start_0|>
self.verbose(result.show(display_guest=display_guest), shift=1)
if verbosity == 1:
return
assert self.step.plan.execute.workdir is not None
for log_file in result.log:
log_name = log_file.name
full_path = self.step.plan.execute.workdir... | Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode. | ReportDisplay | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportDisplay:
"""Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode."""
def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None:
"""Print result details based on t... | stack_v2_sparse_classes_75kplus_train_069128 | 2,618 | permissive | [
{
"docstring": "Print result details based on the verbose mode",
"name": "details",
"signature": "def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None"
},
{
"docstring": "Discover available tests",
"name": "go",
"signature": "def go(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_028051 | Implement the Python class `ReportDisplay` described below.
Class description:
Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode.
Method signatures and docstrings:
- def details(self, result: tmt.Result, verbosity: int, disp... | Implement the Python class `ReportDisplay` described below.
Class description:
Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode.
Method signatures and docstrings:
- def details(self, result: tmt.Result, verbosity: int, disp... | 805c428eaf26a1d087f4a7a2672ffd1460ffd93a | <|skeleton|>
class ReportDisplay:
"""Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode."""
def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None:
"""Print result details based on t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReportDisplay:
"""Show test results on the terminal Give a concise summary of test results directly on the terminal. List individual test results in verbose mode."""
def details(self, result: tmt.Result, verbosity: int, display_guest: bool) -> None:
"""Print result details based on the verbose mo... | the_stack_v2_python_sparse | tmt/steps/report/display.py | lukaszachy/tmt | train | 0 |
ec5c16e6b0505e1bbcec41c5e73e609eb7a11d24 | [
"self.constructeur = constructeur\nself.internes = internes\nself.l_externes = l_externes\nself.d_externes = d_externes",
"l_attributs = []\nfor attr in self.internes:\n if attr:\n l_attributs.append(getattr(objet, attr))\n else:\n l_attributs.append(objet)\nl_attributs.extend(self.l_externes)... | <|body_start_0|>
self.constructeur = constructeur
self.internes = internes
self.l_externes = l_externes
self.d_externes = d_externes
<|end_body_0|>
<|body_start_1|>
l_attributs = []
for attr in self.internes:
if attr:
l_attributs.append(getatt... | Définition d'une classe attribut. Elle prend en paramètre : - un constructeur - une liste de taille inconnue de paramètres à passer au constructeur de l'attribut Elle possède une méthode 'construire' qui retourne l'attribut construit. | Attribut | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attribut:
"""Définition d'une classe attribut. Elle prend en paramètre : - un constructeur - une liste de taille inconnue de paramètres à passer au constructeur de l'attribut Elle possède une méthode 'construire' qui retourne l'attribut construit."""
def __init__(self, constructeur=None, int... | stack_v2_sparse_classes_75kplus_train_069129 | 3,048 | permissive | [
{
"docstring": "Constructeur d'un attribut",
"name": "__init__",
"signature": "def __init__(self, constructeur=None, internes=(), l_externes=(), d_externes={})"
},
{
"docstring": "On construit et retourne l'attribut. Les paramètres internes sont rattachés à 'objet' passé en paramètre. Par exempl... | 2 | stack_v2_sparse_classes_30k_train_012934 | Implement the Python class `Attribut` described below.
Class description:
Définition d'une classe attribut. Elle prend en paramètre : - un constructeur - une liste de taille inconnue de paramètres à passer au constructeur de l'attribut Elle possède une méthode 'construire' qui retourne l'attribut construit.
Method si... | Implement the Python class `Attribut` described below.
Class description:
Définition d'une classe attribut. Elle prend en paramètre : - un constructeur - une liste de taille inconnue de paramètres à passer au constructeur de l'attribut Elle possède une méthode 'construire' qui retourne l'attribut construit.
Method si... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class Attribut:
"""Définition d'une classe attribut. Elle prend en paramètre : - un constructeur - une liste de taille inconnue de paramètres à passer au constructeur de l'attribut Elle possède une méthode 'construire' qui retourne l'attribut construit."""
def __init__(self, constructeur=None, int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Attribut:
"""Définition d'une classe attribut. Elle prend en paramètre : - un constructeur - une liste de taille inconnue de paramètres à passer au constructeur de l'attribut Elle possède une méthode 'construire' qui retourne l'attribut construit."""
def __init__(self, constructeur=None, internes=(), l_e... | the_stack_v2_python_sparse | src/bases/objet/attribut.py | vincent-lg/tsunami | train | 5 |
04b7c2113be6d958028dbd4cc0a7d45adf80a1ba | [
"self.board = board\nself.word = word\nself.visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]\nfor i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(i, j, 0):\n return True\nreturn False",
"if index == len(self.word):\n return True\nif i < 0 ... | <|body_start_0|>
self.board = board
self.word = word
self.visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(i, j, 0):
return True
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def exist(self, board, word):
"""DFS Args: board: list[list[str]] word: str Return: bool"""
<|body_0|>
def dfs(self, i: int, j: int, index: int) -> bool:
"""Args: i: int j: int index: int Return: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_069130 | 1,297 | no_license | [
{
"docstring": "DFS Args: board: list[list[str]] word: str Return: bool",
"name": "exist",
"signature": "def exist(self, board, word)"
},
{
"docstring": "Args: i: int j: int index: int Return: bool",
"name": "dfs",
"signature": "def dfs(self, i: int, j: int, index: int) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_000567 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exist(self, board, word): DFS Args: board: list[list[str]] word: str Return: bool
- def dfs(self, i: int, j: int, index: int) -> bool: Args: i: int j: int index: int Return: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def exist(self, board, word): DFS Args: board: list[list[str]] word: str Return: bool
- def dfs(self, i: int, j: int, index: int) -> bool: Args: i: int j: int index: int Return: ... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def exist(self, board, word):
"""DFS Args: board: list[list[str]] word: str Return: bool"""
<|body_0|>
def dfs(self, i: int, j: int, index: int) -> bool:
"""Args: i: int j: int index: int Return: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def exist(self, board, word):
"""DFS Args: board: list[list[str]] word: str Return: bool"""
self.board = board
self.word = word
self.visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
for i in range(len(board)):
for j in r... | the_stack_v2_python_sparse | code/79. 单词搜索.py | AiZhanghan/Leetcode | train | 0 | |
15082037857da5ac101a1023b8849f68182fd270 | [
"self.cluster_id = cluster_id\nself.cluster_incarnation_id = cluster_incarnation_id\nself.data_read_bytes = data_read_bytes\nself.data_written_bytes = data_written_bytes\nself.logical_used_bytes = logical_used_bytes\nself.peak_read_throughput = peak_read_throughput\nself.peak_write_throughput = peak_write_throughpu... | <|body_start_0|>
self.cluster_id = cluster_id
self.cluster_incarnation_id = cluster_incarnation_id
self.data_read_bytes = data_read_bytes
self.data_written_bytes = data_written_bytes
self.logical_used_bytes = logical_used_bytes
self.peak_read_throughput = peak_read_throug... | Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_written_bytes (long|int): Specifies the ... | ViewStatInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewStatInfo:
"""Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_... | stack_v2_sparse_classes_75kplus_train_069131 | 5,259 | permissive | [
{
"docstring": "Constructor for the ViewStatInfo class",
"name": "__init__",
"signature": "def __init__(self, cluster_id=None, cluster_incarnation_id=None, data_read_bytes=None, data_written_bytes=None, logical_used_bytes=None, peak_read_throughput=None, peak_write_throughput=None, physical_used_bytes=N... | 2 | stack_v2_sparse_classes_30k_train_022514 | Implement the Python class `ViewStatInfo` described below.
Class description:
Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): ... | Implement the Python class `ViewStatInfo` described below.
Class description:
Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ViewStatInfo:
"""Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ViewStatInfo:
"""Implementation of the 'ViewStatInfo' model. Specifies the View stats per view. Attributes: cluster_id (long|int): Specifies the cluster Id. cluster_incarnation_id (long|int): Specifies the cluster Incarnation Id. data_read_bytes (long|int): Specifies the data read in bytes. data_written_bytes... | the_stack_v2_python_sparse | cohesity_management_sdk/models/view_stat_info.py | cohesity/management-sdk-python | train | 24 |
3ef4cabb02db7bc37ee06d9d14952021c5757a96 | [
"super(ModularAttributeVQA, self).__init__()\nself.use_cube = use_cube\nself.attr_to_in = {'object_color_equal': 2, 'object_size_bigger': 2, 'object_size_smaller': 2, 'room_size_bigger': 2 * 4 if self.use_cube else 2, 'room_size_smaller': 2 * 4 if self.use_cube else 2, 'object_dist_farther': 2, 'object_dist_closer'... | <|body_start_0|>
super(ModularAttributeVQA, self).__init__()
self.use_cube = use_cube
self.attr_to_in = {'object_color_equal': 2, 'object_size_bigger': 2, 'object_size_smaller': 2, 'room_size_bigger': 2 * 4 if self.use_cube else 2, 'room_size_smaller': 2 * 4 if self.use_cube else 2, 'object_dist... | ModularAttributeVQA | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModularAttributeVQA:
def __init__(self, img_feat_dim, fc_dim, fc_dropout, use_cube=False, num_answers=2):
"""- img_feat_dim: input image feats dimension - fc_dim : fc dimension - fc_dropout : fc dropout - num_answers : num. answers (yes/no)"""
<|body_0|>
def forward(self, im... | stack_v2_sparse_classes_75kplus_train_069132 | 28,168 | permissive | [
{
"docstring": "- img_feat_dim: input image feats dimension - fc_dim : fc dimension - fc_dropout : fc dropout - num_answers : num. answers (yes/no)",
"name": "__init__",
"signature": "def __init__(self, img_feat_dim, fc_dim, fc_dropout, use_cube=False, num_answers=2)"
},
{
"docstring": "Inputs: ... | 2 | stack_v2_sparse_classes_30k_train_036943 | Implement the Python class `ModularAttributeVQA` described below.
Class description:
Implement the ModularAttributeVQA class.
Method signatures and docstrings:
- def __init__(self, img_feat_dim, fc_dim, fc_dropout, use_cube=False, num_answers=2): - img_feat_dim: input image feats dimension - fc_dim : fc dimension - f... | Implement the Python class `ModularAttributeVQA` described below.
Class description:
Implement the ModularAttributeVQA class.
Method signatures and docstrings:
- def __init__(self, img_feat_dim, fc_dim, fc_dropout, use_cube=False, num_answers=2): - img_feat_dim: input image feats dimension - fc_dim : fc dimension - f... | 9a5483cc29ed6ee8d00590e28264743c6bcbe7ad | <|skeleton|>
class ModularAttributeVQA:
def __init__(self, img_feat_dim, fc_dim, fc_dropout, use_cube=False, num_answers=2):
"""- img_feat_dim: input image feats dimension - fc_dim : fc dimension - fc_dropout : fc dropout - num_answers : num. answers (yes/no)"""
<|body_0|>
def forward(self, im... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModularAttributeVQA:
def __init__(self, img_feat_dim, fc_dim, fc_dropout, use_cube=False, num_answers=2):
"""- img_feat_dim: input image feats dimension - fc_dim : fc dimension - fc_dropout : fc dropout - num_answers : num. answers (yes/no)"""
super(ModularAttributeVQA, self).__init__()
... | the_stack_v2_python_sparse | nav_loc_vqa/vqa/models/modules.py | johndpope/MT-EQA | train | 0 | |
fc1d92237db965d2827ff45a986af3a991e8726c | [
"for p in [2, 3, 5]:\n while num % p == 0 and num > 0:\n num /= p\nreturn num == 1",
"ugly = [1]\ni2, i3, i5 = (0, 0, 0)\nfor _ in range(n - 1):\n u2, u3, u5 = (2 * ugly[i2], 3 * ugly[i3], 5 * ugly[i5])\n umin = min(u2, u3, u5)\n if umin == u2:\n i2 += 1\n if umin == u3:\n i3 +... | <|body_start_0|>
for p in [2, 3, 5]:
while num % p == 0 and num > 0:
num /= p
return num == 1
<|end_body_0|>
<|body_start_1|>
ugly = [1]
i2, i3, i5 = (0, 0, 0)
for _ in range(n - 1):
u2, u3, u5 = (2 * ugly[i2], 3 * ugly[i3], 5 * ugly[i5])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_1|>
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_069133 | 1,197 | no_license | [
{
"docstring": ":type num: int :rtype: bool",
"name": "isUgly",
"signature": "def isUgly(self, num)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nthUglyNumber",
"signature": "def nthUglyNumber(self, n)"
},
{
"docstring": ":type n: int :type primes: List[int] :rtype: in... | 3 | stack_v2_sparse_classes_30k_train_025106 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isUgly(self, num): :type num: int :rtype: bool
- def nthUglyNumber(self, n): :type n: int :rtype: int
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: Li... | f234bd7b62cb7bc2150faa764bf05a9095e19192 | <|skeleton|>
class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
<|body_0|>
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
<|body_1|>
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isUgly(self, num):
""":type num: int :rtype: bool"""
for p in [2, 3, 5]:
while num % p == 0 and num > 0:
num /= p
return num == 1
def nthUglyNumber(self, n):
""":type n: int :rtype: int"""
ugly = [1]
i2, i3, i5 = (0... | the_stack_v2_python_sparse | alg/ugly_number.py | nyannko/leetcode-python | train | 0 | |
b01b756a452aeb8a72bf22532397daf9d4c3037c | [
"count = 0\nfor i in range(len(dominoes) - 1):\n for j in range(i + 1, len(dominoes)):\n if dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1] or (dominoes[i][1] == dominoes[j][0] and dominoes[i][0] == dominoes[j][1]):\n count += 1\nreturn count",
"data = {}\nfor domino in ... | <|body_start_0|>
count = 0
for i in range(len(dominoes) - 1):
for j in range(i + 1, len(dominoes)):
if dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1] or (dominoes[i][1] == dominoes[j][0] and dominoes[i][0] == dominoes[j][1]):
count +... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_0|>
def numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069134 | 1,904 | permissive | [
{
"docstring": ":type dominoes: List[List[int]] :rtype: int",
"name": "_numEquivDominoPairs",
"signature": "def _numEquivDominoPairs(self, dominoes)"
},
{
"docstring": ":type dominoes: List[List[int]] :rtype: int",
"name": "numEquivDominoPairs",
"signature": "def numEquivDominoPairs(self... | 2 | stack_v2_sparse_classes_30k_train_028442 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int
- def numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int
- def numEquivDominoPairs(self, dominoes): :type dominoes: List[List[int]] :rtype: int
<|sk... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_0|>
def numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def _numEquivDominoPairs(self, dominoes):
""":type dominoes: List[List[int]] :rtype: int"""
count = 0
for i in range(len(dominoes) - 1):
for j in range(i + 1, len(dominoes)):
if dominoes[i][0] == dominoes[j][0] and dominoes[i][1] == dominoes[j][1] ... | the_stack_v2_python_sparse | 1128.number-of-equivalent-domino-pairs.py | windard/leeeeee | train | 0 | |
e519818d46b87df968a344b4952abc6198df954e | [
"super().__init__(search_key, **kwargs)\nself.search_url_prefix = kwargs.get('search_url_prefix', 'https://www.google.com.sg/search?q=')\nself.search_url_postfix = kwargs.get('search_url_postfix', '&source=lnms&tbm=isch&sa=X&ei=0eZEVbj3IJG5uATalICQAQ&ved=0CAcQ_AUoAQ&biw=939&bih=591')\nself.show_more_find_type = kwa... | <|body_start_0|>
super().__init__(search_key, **kwargs)
self.search_url_prefix = kwargs.get('search_url_prefix', 'https://www.google.com.sg/search?q=')
self.search_url_postfix = kwargs.get('search_url_postfix', '&source=lnms&tbm=isch&sa=X&ei=0eZEVbj3IJG5uATalICQAQ&ved=0CAcQ_AUoAQ&biw=939&bih=591... | docstr | GoogleCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleCrawler:
"""docstr"""
def __init__(self, search_key='', **kwargs):
"""docstr"""
<|body_0|>
def extract_pic_url(self, driver):
"""extract all the raw pic url in list"""
<|body_1|>
def load_page(self, driver):
"""docstr"""
<|body_... | stack_v2_sparse_classes_75kplus_train_069135 | 3,374 | no_license | [
{
"docstring": "docstr",
"name": "__init__",
"signature": "def __init__(self, search_key='', **kwargs)"
},
{
"docstring": "extract all the raw pic url in list",
"name": "extract_pic_url",
"signature": "def extract_pic_url(self, driver)"
},
{
"docstring": "docstr",
"name": "lo... | 3 | stack_v2_sparse_classes_30k_train_001832 | Implement the Python class `GoogleCrawler` described below.
Class description:
docstr
Method signatures and docstrings:
- def __init__(self, search_key='', **kwargs): docstr
- def extract_pic_url(self, driver): extract all the raw pic url in list
- def load_page(self, driver): docstr | Implement the Python class `GoogleCrawler` described below.
Class description:
docstr
Method signatures and docstrings:
- def __init__(self, search_key='', **kwargs): docstr
- def extract_pic_url(self, driver): extract all the raw pic url in list
- def load_page(self, driver): docstr
<|skeleton|>
class GoogleCrawler... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class GoogleCrawler:
"""docstr"""
def __init__(self, search_key='', **kwargs):
"""docstr"""
<|body_0|>
def extract_pic_url(self, driver):
"""extract all the raw pic url in list"""
<|body_1|>
def load_page(self, driver):
"""docstr"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoogleCrawler:
"""docstr"""
def __init__(self, search_key='', **kwargs):
"""docstr"""
super().__init__(search_key, **kwargs)
self.search_url_prefix = kwargs.get('search_url_prefix', 'https://www.google.com.sg/search?q=')
self.search_url_postfix = kwargs.get('search_url_pos... | the_stack_v2_python_sparse | imgscrape/sel/crawler/GoogleCrawler.py | gmonkman/python | train | 0 |
f68e8b19d2894bec38cf38127f2f74a1e3ff173b | [
"router_name = self.alias\nif undeferred:\n router_name = 'forkptyurouter'\nself.on_command = router_name\nsuper().__init__(on)",
"super().set_basic_params(**filter_locals(locals(), drop=['run_command']))\nself._set_aliased('command', run_command)\nreturn self",
"self._set_aliased('harakiri', harakiri)\nself... | <|body_start_0|>
router_name = self.alias
if undeferred:
router_name = 'forkptyurouter'
self.on_command = router_name
super().__init__(on)
<|end_body_0|>
<|body_start_1|>
super().set_basic_params(**filter_locals(locals(), drop=['run_command']))
self._set_alia... | Allows allocation of pseudoterminals in jails. Dealing with containers is now a common deployment pattern. One of the most annoying tasks when dealing with jails/namespaces is 'attaching' to already running instances. The forkpty router aims at simplifyng the process giving a pseudoterminal server to your uWSGI instanc... | RouterForkPty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RouterForkPty:
"""Allows allocation of pseudoterminals in jails. Dealing with containers is now a common deployment pattern. One of the most annoying tasks when dealing with jails/namespaces is 'attaching' to already running instances. The forkpty router aims at simplifyng the process giving a ps... | stack_v2_sparse_classes_75kplus_train_069136 | 33,586 | permissive | [
{
"docstring": "Binds router to run on the given address. :param SocketShared|str on: Activates the router on the given address. :param bool undeferred: Run router in undeferred mode.",
"name": "__init__",
"signature": "def __init__(self, on=None, undeferred=False)"
},
{
"docstring": ":param int... | 4 | stack_v2_sparse_classes_30k_train_012989 | Implement the Python class `RouterForkPty` described below.
Class description:
Allows allocation of pseudoterminals in jails. Dealing with containers is now a common deployment pattern. One of the most annoying tasks when dealing with jails/namespaces is 'attaching' to already running instances. The forkpty router aim... | Implement the Python class `RouterForkPty` described below.
Class description:
Allows allocation of pseudoterminals in jails. Dealing with containers is now a common deployment pattern. One of the most annoying tasks when dealing with jails/namespaces is 'attaching' to already running instances. The forkpty router aim... | 1060d6c9e15695b65f1875df66128fb4ff1a5c0d | <|skeleton|>
class RouterForkPty:
"""Allows allocation of pseudoterminals in jails. Dealing with containers is now a common deployment pattern. One of the most annoying tasks when dealing with jails/namespaces is 'attaching' to already running instances. The forkpty router aims at simplifyng the process giving a ps... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RouterForkPty:
"""Allows allocation of pseudoterminals in jails. Dealing with containers is now a common deployment pattern. One of the most annoying tasks when dealing with jails/namespaces is 'attaching' to already running instances. The forkpty router aims at simplifyng the process giving a pseudoterminal ... | the_stack_v2_python_sparse | uwsgiconf/options/routing_routers.py | idlesign/uwsgiconf | train | 79 |
12ce14d77568f95276cb117bef7fc10ba3a9bc86 | [
"super(FeatureNN, self).__init__(config, name)\nself._input_shape = input_shape\nself._num_units = num_units\nself._feature_num = feature_num\nself.dropout = nn.Dropout(p=self.config.dropout)\nhidden_sizes = [self._num_units] + self.config.hidden_sizes\nlayers = []\nif self.config.activation == 'exu':\n layers.a... | <|body_start_0|>
super(FeatureNN, self).__init__(config, name)
self._input_shape = input_shape
self._num_units = num_units
self._feature_num = feature_num
self.dropout = nn.Dropout(p=self.config.dropout)
hidden_sizes = [self._num_units] + self.config.hidden_sizes
... | Neural Network model for each individual feature. | FeatureNN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureNN:
"""Neural Network model for each individual feature."""
def __init__(self, config, name, *, input_shape: int, num_units: int, feature_num: int=0) -> None:
"""Initializes FeatureNN hyperparameters. Args: num_units: Number of hidden units in first hidden layer. dropout: Coef... | stack_v2_sparse_classes_75kplus_train_069137 | 1,899 | permissive | [
{
"docstring": "Initializes FeatureNN hyperparameters. Args: num_units: Number of hidden units in first hidden layer. dropout: Coefficient for dropout regularization. feature_num: Feature Index used for naming the hidden layers.",
"name": "__init__",
"signature": "def __init__(self, config, name, *, inp... | 2 | stack_v2_sparse_classes_30k_train_008957 | Implement the Python class `FeatureNN` described below.
Class description:
Neural Network model for each individual feature.
Method signatures and docstrings:
- def __init__(self, config, name, *, input_shape: int, num_units: int, feature_num: int=0) -> None: Initializes FeatureNN hyperparameters. Args: num_units: Nu... | Implement the Python class `FeatureNN` described below.
Class description:
Neural Network model for each individual feature.
Method signatures and docstrings:
- def __init__(self, config, name, *, input_shape: int, num_units: int, feature_num: int=0) -> None: Initializes FeatureNN hyperparameters. Args: num_units: Nu... | fc2da75ba008c4ef02a83747f2116036fa6fec46 | <|skeleton|>
class FeatureNN:
"""Neural Network model for each individual feature."""
def __init__(self, config, name, *, input_shape: int, num_units: int, feature_num: int=0) -> None:
"""Initializes FeatureNN hyperparameters. Args: num_units: Number of hidden units in first hidden layer. dropout: Coef... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureNN:
"""Neural Network model for each individual feature."""
def __init__(self, config, name, *, input_shape: int, num_units: int, feature_num: int=0) -> None:
"""Initializes FeatureNN hyperparameters. Args: num_units: Number of hidden units in first hidden layer. dropout: Coefficient for d... | the_stack_v2_python_sparse | nam/models/featurenn.py | AmrMKayid/nam | train | 45 |
23053d95d8ac3afd32836f7a3dd9e199df067356 | [
"now = timezone.now()\nif not username:\n raise ValueError('The given username must be set')\nu = self.model(username=username, email=GUserManager.normalize_email(email), nickname=username, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields)\nif password is None:\... | <|body_start_0|>
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
u = self.model(username=username, email=GUserManager.normalize_email(email), nickname=username, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=no... | GUser Manager for create user and superuser. You can use: u = self.model(...) password = u.make_random_password() u.set_password(password) to create a new password for users. | GUserManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GUserManager:
"""GUser Manager for create user and superuser. You can use: u = self.model(...) password = u.make_random_password() u.set_password(password) to create a new password for users."""
def create_user(self, username, email=None, password=None, nickname=None, **extra_fields):
... | stack_v2_sparse_classes_75kplus_train_069138 | 1,909 | permissive | [
{
"docstring": "Creates and saves a User with the given username, email, password and nickname.",
"name": "create_user",
"signature": "def create_user(self, username, email=None, password=None, nickname=None, **extra_fields)"
},
{
"docstring": "Create superuser",
"name": "create_superuser",
... | 2 | null | Implement the Python class `GUserManager` described below.
Class description:
GUser Manager for create user and superuser. You can use: u = self.model(...) password = u.make_random_password() u.set_password(password) to create a new password for users.
Method signatures and docstrings:
- def create_user(self, usernam... | Implement the Python class `GUserManager` described below.
Class description:
GUser Manager for create user and superuser. You can use: u = self.model(...) password = u.make_random_password() u.set_password(password) to create a new password for users.
Method signatures and docstrings:
- def create_user(self, usernam... | c5e172b896a51c15f358d3aabbcb66af837b54b2 | <|skeleton|>
class GUserManager:
"""GUser Manager for create user and superuser. You can use: u = self.model(...) password = u.make_random_password() u.set_password(password) to create a new password for users."""
def create_user(self, username, email=None, password=None, nickname=None, **extra_fields):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GUserManager:
"""GUser Manager for create user and superuser. You can use: u = self.model(...) password = u.make_random_password() u.set_password(password) to create a new password for users."""
def create_user(self, username, email=None, password=None, nickname=None, **extra_fields):
"""Creates ... | the_stack_v2_python_sparse | src/gork/contrib/gauth/managers.py | indexofire/gork | train | 0 |
0c537649fc89f3a6db7c05b8ef1c75265fe7524d | [
"selection = ~reflection_table.get_flags(reflection_table.flags.bad_for_scaling, all=False)\nreflection_table = reflection_table.select(selection)\nlogger.info('Selected %d scaled reflections', reflection_table.size())\nassert 'inverse_scale_factor' in reflection_table\nselection = reflection_table['inverse_scale_f... | <|body_start_0|>
selection = ~reflection_table.get_flags(reflection_table.flags.bad_for_scaling, all=False)
reflection_table = reflection_table.select(selection)
logger.info('Selected %d scaled reflections', reflection_table.size())
assert 'inverse_scale_factor' in reflection_table
... | Reduction methods for data with sum intensities. | ScaleIntensityReducer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaleIntensityReducer:
"""Reduction methods for data with sum intensities."""
def reduce_on_intensities(reflection_table):
"""Select intensities used for scaling and remove scaling outliers."""
<|body_0|>
def apply_scaling_factors(reflection_table):
"""Apply the ... | stack_v2_sparse_classes_75kplus_train_069139 | 38,270 | permissive | [
{
"docstring": "Select intensities used for scaling and remove scaling outliers.",
"name": "reduce_on_intensities",
"signature": "def reduce_on_intensities(reflection_table)"
},
{
"docstring": "Apply the inverse scale factor to the scale intensities.",
"name": "apply_scaling_factors",
"s... | 2 | stack_v2_sparse_classes_30k_train_031696 | Implement the Python class `ScaleIntensityReducer` described below.
Class description:
Reduction methods for data with sum intensities.
Method signatures and docstrings:
- def reduce_on_intensities(reflection_table): Select intensities used for scaling and remove scaling outliers.
- def apply_scaling_factors(reflecti... | Implement the Python class `ScaleIntensityReducer` described below.
Class description:
Reduction methods for data with sum intensities.
Method signatures and docstrings:
- def reduce_on_intensities(reflection_table): Select intensities used for scaling and remove scaling outliers.
- def apply_scaling_factors(reflecti... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class ScaleIntensityReducer:
"""Reduction methods for data with sum intensities."""
def reduce_on_intensities(reflection_table):
"""Select intensities used for scaling and remove scaling outliers."""
<|body_0|>
def apply_scaling_factors(reflection_table):
"""Apply the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScaleIntensityReducer:
"""Reduction methods for data with sum intensities."""
def reduce_on_intensities(reflection_table):
"""Select intensities used for scaling and remove scaling outliers."""
selection = ~reflection_table.get_flags(reflection_table.flags.bad_for_scaling, all=False)
... | the_stack_v2_python_sparse | src/dials/util/filter_reflections.py | dials/dials | train | 71 |
8554b1ec57fdead1ab65a8b3414d2ad3526be770 | [
"if value is None:\n return ''\nelse:\n return value",
"if value == '':\n return None\nelse:\n return value"
] | <|body_start_0|>
if value is None:
return ''
else:
return value
<|end_body_0|>
<|body_start_1|>
if value == '':
return None
else:
return value
<|end_body_1|>
| Subclass of the CharField that allows empty strings to be stored as NULL. | CharNullField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharNullField:
"""Subclass of the CharField that allows empty strings to be stored as NULL."""
def from_db_value(self, value, expression, connection, contex):
"""Gets value right out of the db and changes it if its ``None``."""
<|body_0|>
def get_prep_value(self, value):... | stack_v2_sparse_classes_75kplus_train_069140 | 1,583 | no_license | [
{
"docstring": "Gets value right out of the db and changes it if its ``None``.",
"name": "from_db_value",
"signature": "def from_db_value(self, value, expression, connection, contex)"
},
{
"docstring": "Catches value right before sending to db.",
"name": "get_prep_value",
"signature": "d... | 2 | null | Implement the Python class `CharNullField` described below.
Class description:
Subclass of the CharField that allows empty strings to be stored as NULL.
Method signatures and docstrings:
- def from_db_value(self, value, expression, connection, contex): Gets value right out of the db and changes it if its ``None``.
- ... | Implement the Python class `CharNullField` described below.
Class description:
Subclass of the CharField that allows empty strings to be stored as NULL.
Method signatures and docstrings:
- def from_db_value(self, value, expression, connection, contex): Gets value right out of the db and changes it if its ``None``.
- ... | 399064b62a7c8049b37efd77a98f17a903754070 | <|skeleton|>
class CharNullField:
"""Subclass of the CharField that allows empty strings to be stored as NULL."""
def from_db_value(self, value, expression, connection, contex):
"""Gets value right out of the db and changes it if its ``None``."""
<|body_0|>
def get_prep_value(self, value):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CharNullField:
"""Subclass of the CharField that allows empty strings to be stored as NULL."""
def from_db_value(self, value, expression, connection, contex):
"""Gets value right out of the db and changes it if its ``None``."""
if value is None:
return ''
else:
... | the_stack_v2_python_sparse | nanum/users/fields.py | markui/nanum-project | train | 1 |
301d75a534aea9eefb43b223f8f8041d56b2cd13 | [
"if not root:\n return None\nleft = self.invertTree(root.left)\nright = self.invertTree(root.right)\nroot.left = right\nroot.right = left\nreturn root",
"if not root:\n return None\nq = deque([root])\nwhile len(q) > 0:\n node = q.popleft()\n temp = node.left\n node.left = node.right\n node.right... | <|body_start_0|>
if not root:
return None
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left = right
root.right = left
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return None
q = deque([roo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode Recursive solution"""
<|body_0|>
def invertTree1(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_75kplus_train_069141 | 1,056 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: TreeNode Recursive solution",
"name": "invertTree",
"signature": "def invertTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: TreeNode",
"name": "invertTree1",
"signature": "def invertTree1(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021044 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode Recursive solution
- def invertTree1(self, root): :type root: TreeNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root): :type root: TreeNode :rtype: TreeNode Recursive solution
- def invertTree1(self, root): :type root: TreeNode :rtype: TreeNode
<|skeleton|>
class Solu... | 385ca03d51c8892eccf9ca5b920158d569edc375 | <|skeleton|>
class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode Recursive solution"""
<|body_0|>
def invertTree1(self, root):
""":type root: TreeNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def invertTree(self, root):
""":type root: TreeNode :rtype: TreeNode Recursive solution"""
if not root:
return None
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left = right
root.right = left
return roo... | the_stack_v2_python_sparse | Leetcode/BSTQuestions/invertbinarytree.py | nanaboat/data-structures | train | 0 | |
e8808fed0f85eed450f5cb1055d9576e2a270b95 | [
"ret = super(Spm99AnalyzeImage, klass).from_file_map(file_map, mmap=mmap, keep_file_open=keep_file_open)\ntry:\n matf = file_map['mat'].get_prepare_fileobj()\nexcept IOError:\n return ret\nwith matf:\n contents = matf.read()\nif len(contents) == 0:\n return ret\nimport scipy.io as sio\nmats = sio.loadma... | <|body_start_0|>
ret = super(Spm99AnalyzeImage, klass).from_file_map(file_map, mmap=mmap, keep_file_open=keep_file_open)
try:
matf = file_map['mat'].get_prepare_fileobj()
except IOError:
return ret
with matf:
contents = matf.read()
if len(conte... | Class for SPM99 variant of basic Analyze image | Spm99AnalyzeImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spm99AnalyzeImage:
"""Class for SPM99 variant of basic Analyze image"""
def from_file_map(klass, file_map, mmap=True, keep_file_open=None):
"""class method to create image from mapping in `file_map `` Parameters ---------- file_map : dict Mapping with (kay, value) pairs of (``file_ty... | stack_v2_sparse_classes_75kplus_train_069142 | 13,046 | permissive | [
{
"docstring": "class method to create image from mapping in `file_map `` Parameters ---------- file_map : dict Mapping with (kay, value) pairs of (``file_type``, FileHolder instance giving file-likes for each file needed for this image type. mmap : {True, False, 'c', 'r'}, optional, keyword only `mmap` control... | 2 | stack_v2_sparse_classes_30k_train_046163 | Implement the Python class `Spm99AnalyzeImage` described below.
Class description:
Class for SPM99 variant of basic Analyze image
Method signatures and docstrings:
- def from_file_map(klass, file_map, mmap=True, keep_file_open=None): class method to create image from mapping in `file_map `` Parameters ---------- file... | Implement the Python class `Spm99AnalyzeImage` described below.
Class description:
Class for SPM99 variant of basic Analyze image
Method signatures and docstrings:
- def from_file_map(klass, file_map, mmap=True, keep_file_open=None): class method to create image from mapping in `file_map `` Parameters ---------- file... | 3c3acc55de8ba741e673063378e6cbaf10b64c7a | <|skeleton|>
class Spm99AnalyzeImage:
"""Class for SPM99 variant of basic Analyze image"""
def from_file_map(klass, file_map, mmap=True, keep_file_open=None):
"""class method to create image from mapping in `file_map `` Parameters ---------- file_map : dict Mapping with (kay, value) pairs of (``file_ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Spm99AnalyzeImage:
"""Class for SPM99 variant of basic Analyze image"""
def from_file_map(klass, file_map, mmap=True, keep_file_open=None):
"""class method to create image from mapping in `file_map `` Parameters ---------- file_map : dict Mapping with (kay, value) pairs of (``file_type``, FileHol... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/nibabel/spm99analyze.py | Raniac/NEURO-LEARN | train | 9 |
9e9f7f72b5d574afa57205991857ca42422d31c6 | [
"self.link = link\nself.lineproto = lineproto\nself.interface_name = interface_name",
"sb = ''\nsb += '\\nInterfaceStatus [ ' + self.interface_name + ' ]\\n'\nsb += '\\tLinkState : ' + str(self.InterfaceState.enumval(self.link)) + '\\n'\nsb += '\\tLineProtoState : ' + str(self.InterfaceState.enumval(self... | <|body_start_0|>
self.link = link
self.lineproto = lineproto
self.interface_name = interface_name
<|end_body_0|>
<|body_start_1|>
sb = ''
sb += '\nInterfaceStatus [ ' + self.interface_name + ' ]\n'
sb += '\tLinkState : ' + str(self.InterfaceState.enumval(self.link... | Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceState>} @ivar lineproto: The lineproto state ... | InterfaceStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceStatus:
"""Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceSt... | stack_v2_sparse_classes_75kplus_train_069143 | 1,914 | no_license | [
{
"docstring": "Constructor of InterfaceStatus class.",
"name": "__init__",
"signature": "def __init__(self, link, lineproto, interface_name)"
},
{
"docstring": "Obtain string representation of the Interface Status object.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045591 | Implement the Python class `InterfaceStatus` described below.
Class description:
Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.Inte... | Implement the Python class `InterfaceStatus` described below.
Class description:
Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.Inte... | 54bc49eaed14f7832aca45c4f52311a00282d862 | <|skeleton|>
class InterfaceStatus:
"""Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceSt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterfaceStatus:
"""Class which handles provides information about status of the interface @ivar interface_name: The name of the interface @type interface_name: C{str} @ivar link: The link status of the interface. @type link: L{InterfaceState<interfaces.InterfaceStatus.InterfaceStatus.InterfaceState>} @ivar l... | the_stack_v2_python_sparse | onepk_without_pyc/build/lib.linux-x86_64-2.7/onep/interfaces/InterfaceStatus.py | neoyogi/onepk | train | 0 |
8d6a1029cf5e4f9797ad21c8afc18b99c3dc36a5 | [
"self.path = path\nself.name = os.path.basename(path)\nself.detector_path, self.description = self.get_data()",
"detector_path = None\ndescription = ''\nfor name in os.listdir(self.path):\n suffix = pathlib.Path(os.path.join(self.path, name)).suffix\n prefix = pathlib.Path(os.path.join(self.path, name)).ste... | <|body_start_0|>
self.path = path
self.name = os.path.basename(path)
self.detector_path, self.description = self.get_data()
<|end_body_0|>
<|body_start_1|>
detector_path = None
description = ''
for name in os.listdir(self.path):
suffix = pathlib.Path(os.path.... | This class holds the data and path of the event detector. | EventDetector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventDetector:
"""This class holds the data and path of the event detector."""
def __init__(self, path):
""":param path: the inserted path of the event detector."""
<|body_0|>
def get_data(self):
""":return: the file path, a sample image and a description of the ... | stack_v2_sparse_classes_75kplus_train_069144 | 1,161 | permissive | [
{
"docstring": ":param path: the inserted path of the event detector.",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": ":return: the file path, a sample image and a description of the event detector.",
"name": "get_data",
"signature": "def get_data(self)"
... | 2 | stack_v2_sparse_classes_30k_train_036356 | Implement the Python class `EventDetector` described below.
Class description:
This class holds the data and path of the event detector.
Method signatures and docstrings:
- def __init__(self, path): :param path: the inserted path of the event detector.
- def get_data(self): :return: the file path, a sample image and ... | Implement the Python class `EventDetector` described below.
Class description:
This class holds the data and path of the event detector.
Method signatures and docstrings:
- def __init__(self, path): :param path: the inserted path of the event detector.
- def get_data(self): :return: the file path, a sample image and ... | 8d03f5f7c85ccc113a0561c58b7e3bf76e888f03 | <|skeleton|>
class EventDetector:
"""This class holds the data and path of the event detector."""
def __init__(self, path):
""":param path: the inserted path of the event detector."""
<|body_0|>
def get_data(self):
""":return: the file path, a sample image and a description of the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EventDetector:
"""This class holds the data and path of the event detector."""
def __init__(self, path):
""":param path: the inserted path of the event detector."""
self.path = path
self.name = os.path.basename(path)
self.detector_path, self.description = self.get_data()
... | the_stack_v2_python_sparse | entities/event_detector.py | biktokle/Automated-Microscope | train | 0 |
785a0d8ace5814fc0b171658892c5f18bd0fd885 | [
"super().__init__()\nself._use_condition = use_condition\nself._model = tf.keras.Sequential([tf.keras.layers.Conv2D(128, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormalization(), tf.keras.layers.LeakyReLU(), tf.keras.layers.Conv2D(256, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormali... | <|body_start_0|>
super().__init__()
self._use_condition = use_condition
self._model = tf.keras.Sequential([tf.keras.layers.Conv2D(128, [5, 5], strides=2, padding='same'), tf.keras.layers.BatchNormalization(), tf.keras.layers.LeakyReLU(), tf.keras.layers.Conv2D(256, [5, 5], strides=2, padding='sa... | Embedding conditioned discriminator. This discriminator is used by CUB, Flowers, MSCOCO datasets. Attributes: | EmbeddingConditionedDiscriminator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmbeddingConditionedDiscriminator:
"""Embedding conditioned discriminator. This discriminator is used by CUB, Flowers, MSCOCO datasets. Attributes:"""
def __init__(self, use_condition, compression_size):
"""Initializes the object. Args: use_condition: compression_size:"""
<|b... | stack_v2_sparse_classes_75kplus_train_069145 | 12,085 | no_license | [
{
"docstring": "Initializes the object. Args: use_condition: compression_size:",
"name": "__init__",
"signature": "def __init__(self, use_condition, compression_size)"
},
{
"docstring": "Applies the model to the inputs. Args: image: embedding: Returns:",
"name": "call",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_019078 | Implement the Python class `EmbeddingConditionedDiscriminator` described below.
Class description:
Embedding conditioned discriminator. This discriminator is used by CUB, Flowers, MSCOCO datasets. Attributes:
Method signatures and docstrings:
- def __init__(self, use_condition, compression_size): Initializes the obje... | Implement the Python class `EmbeddingConditionedDiscriminator` described below.
Class description:
Embedding conditioned discriminator. This discriminator is used by CUB, Flowers, MSCOCO datasets. Attributes:
Method signatures and docstrings:
- def __init__(self, use_condition, compression_size): Initializes the obje... | 6d04861ef87ba2ba2a4182ad36f3b322fcf47cfa | <|skeleton|>
class EmbeddingConditionedDiscriminator:
"""Embedding conditioned discriminator. This discriminator is used by CUB, Flowers, MSCOCO datasets. Attributes:"""
def __init__(self, use_condition, compression_size):
"""Initializes the object. Args: use_condition: compression_size:"""
<|b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmbeddingConditionedDiscriminator:
"""Embedding conditioned discriminator. This discriminator is used by CUB, Flowers, MSCOCO datasets. Attributes:"""
def __init__(self, use_condition, compression_size):
"""Initializes the object. Args: use_condition: compression_size:"""
super().__init__... | the_stack_v2_python_sparse | gan.py | gaotianxiang/text-to-image-synthesis | train | 0 |
932625efd6a9fa9e0e1ba48067f2e0c9b698e85a | [
"test_dictionary = {'Source Name': 'Test', 'Path': 'Printflow-ToDo1.xls', 'Id Column': 3, 'Status Column': 2, 'Status': 'Dollco Printing-Proof In'}\nexcel_test = ExcelStatus(test_dictionary)\nexpected = True\nactual = excel_test.check_status('Dollco Printing-Proof In', '685597')\nself.assertEqual(actual, expected)"... | <|body_start_0|>
test_dictionary = {'Source Name': 'Test', 'Path': 'Printflow-ToDo1.xls', 'Id Column': 3, 'Status Column': 2, 'Status': 'Dollco Printing-Proof In'}
excel_test = ExcelStatus(test_dictionary)
expected = True
actual = excel_test.check_status('Dollco Printing-Proof In', '6855... | DataSource unit tests | DataSourceTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSourceTests:
"""DataSource unit tests"""
def test_excel_check_status(self):
"""Check that class implements check_status properly"""
<|body_0|>
def test_log_file_status(self):
"""Check that class implements check_status properly"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_069146 | 9,245 | no_license | [
{
"docstring": "Check that class implements check_status properly",
"name": "test_excel_check_status",
"signature": "def test_excel_check_status(self)"
},
{
"docstring": "Check that class implements check_status properly",
"name": "test_log_file_status",
"signature": "def test_log_file_s... | 5 | stack_v2_sparse_classes_30k_train_011898 | Implement the Python class `DataSourceTests` described below.
Class description:
DataSource unit tests
Method signatures and docstrings:
- def test_excel_check_status(self): Check that class implements check_status properly
- def test_log_file_status(self): Check that class implements check_status properly
- def test... | Implement the Python class `DataSourceTests` described below.
Class description:
DataSource unit tests
Method signatures and docstrings:
- def test_excel_check_status(self): Check that class implements check_status properly
- def test_log_file_status(self): Check that class implements check_status properly
- def test... | c69fe121799d72d5239d2da59577e9c1b7a9c51c | <|skeleton|>
class DataSourceTests:
"""DataSource unit tests"""
def test_excel_check_status(self):
"""Check that class implements check_status properly"""
<|body_0|>
def test_log_file_status(self):
"""Check that class implements check_status properly"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataSourceTests:
"""DataSource unit tests"""
def test_excel_check_status(self):
"""Check that class implements check_status properly"""
test_dictionary = {'Source Name': 'Test', 'Path': 'Printflow-ToDo1.xls', 'Id Column': 3, 'Status Column': 2, 'Status': 'Dollco Printing-Proof In'}
... | the_stack_v2_python_sparse | DataSources.py | McFunston/PythonScheduleTools | train | 1 |
ff9911259fae366410bbe2942ce012ffb33c8d65 | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('AllocateCustomerCredit', params, headers=headers)\n response = json.loads(body)\n model = models.AllocateCustomerCreditResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as ... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('AllocateCustomerCredit', params, headers=headers)
response = json.loads(body)
model = models.AllocateCustomerCreditResponse()
model._deserialize... | IpClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpClient:
def AllocateCustomerCredit(self, request):
"""This API is used for a partner to set credit for a customer, such as increasing or lowering the credit and setting it to 0. 1. The credit is valid permanently and will not be zeroed regularly. 2. The customer's service will be suspe... | stack_v2_sparse_classes_75kplus_train_069147 | 7,749 | no_license | [
{
"docstring": "This API is used for a partner to set credit for a customer, such as increasing or lowering the credit and setting it to 0. 1. The credit is valid permanently and will not be zeroed regularly. 2. The customer's service will be suspended when its available credit sets to 0, so caution should be e... | 6 | stack_v2_sparse_classes_30k_train_003835 | Implement the Python class `IpClient` described below.
Class description:
Implement the IpClient class.
Method signatures and docstrings:
- def AllocateCustomerCredit(self, request): This API is used for a partner to set credit for a customer, such as increasing or lowering the credit and setting it to 0. 1. The cred... | Implement the Python class `IpClient` described below.
Class description:
Implement the IpClient class.
Method signatures and docstrings:
- def AllocateCustomerCredit(self, request): This API is used for a partner to set credit for a customer, such as increasing or lowering the credit and setting it to 0. 1. The cred... | 042b4d7fb609d4d240728197901b46008b35d4b0 | <|skeleton|>
class IpClient:
def AllocateCustomerCredit(self, request):
"""This API is used for a partner to set credit for a customer, such as increasing or lowering the credit and setting it to 0. 1. The credit is valid permanently and will not be zeroed regularly. 2. The customer's service will be suspe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IpClient:
def AllocateCustomerCredit(self, request):
"""This API is used for a partner to set credit for a customer, such as increasing or lowering the credit and setting it to 0. 1. The credit is valid permanently and will not be zeroed regularly. 2. The customer's service will be suspended when its ... | the_stack_v2_python_sparse | tencentcloud/ip/v20210409/ip_client.py | TencentCloud/tencentcloud-sdk-python-intl-en | train | 4 | |
578e72500ae9eb384cb36b0d4e04c821a4527d3a | [
"email = username = None\ntry:\n validate_email(email_or_username)\n email = email_or_username\nexcept forms.ValidationError:\n username = email_or_username\nif email:\n try:\n return User.objects.get(email=email)\n except User.DoesNotExist:\n raise forms.ValidationError(cls.FAILED_AUTH... | <|body_start_0|>
email = username = None
try:
validate_email(email_or_username)
email = email_or_username
except forms.ValidationError:
username = email_or_username
if email:
try:
return User.objects.get(email=email)
... | LoginForm | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginForm:
def user_from_email_or_username(cls, email_or_username):
"""Get user from email/username"""
<|body_0|>
def clean(self):
"""Verify that user with given credentials exists"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
email = username = N... | stack_v2_sparse_classes_75kplus_train_069148 | 2,191 | permissive | [
{
"docstring": "Get user from email/username",
"name": "user_from_email_or_username",
"signature": "def user_from_email_or_username(cls, email_or_username)"
},
{
"docstring": "Verify that user with given credentials exists",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | null | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def user_from_email_or_username(cls, email_or_username): Get user from email/username
- def clean(self): Verify that user with given credentials exists | Implement the Python class `LoginForm` described below.
Class description:
Implement the LoginForm class.
Method signatures and docstrings:
- def user_from_email_or_username(cls, email_or_username): Get user from email/username
- def clean(self): Verify that user with given credentials exists
<|skeleton|>
class Logi... | ef2b87146850509e2f6f4057344fdc037c8a2808 | <|skeleton|>
class LoginForm:
def user_from_email_or_username(cls, email_or_username):
"""Get user from email/username"""
<|body_0|>
def clean(self):
"""Verify that user with given credentials exists"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginForm:
def user_from_email_or_username(cls, email_or_username):
"""Get user from email/username"""
email = username = None
try:
validate_email(email_or_username)
email = email_or_username
except forms.ValidationError:
username = email_or_... | the_stack_v2_python_sparse | order/forms.py | RevolutionTech/seared-quail | train | 1 | |
153aaffd8521adacd823cc176e1c1d6ffa7f4781 | [
"self._threshold = threshold\nif start_datetime is None:\n self._start_datetime = get_last_year_date()\nelse:\n self._start_datetime = start_datetime",
"valid_entries = date_values_after(fin.debt_to_equity, self._start_datetime)\navg_debt_to_equity = sum([valid_entries.get(date_str) for date_str in valid_en... | <|body_start_0|>
self._threshold = threshold
if start_datetime is None:
self._start_datetime = get_last_year_date()
else:
self._start_datetime = start_datetime
<|end_body_0|>
<|body_start_1|>
valid_entries = date_values_after(fin.debt_to_equity, self._start_datet... | DebtToAssertScorer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebtToAssertScorer:
def __init__(self, threshold=0.5, start_datetime=None):
""":param threshold: :type threshold: float :param start_datetime: :type start_datetime: datetime.datetime"""
<|body_0|>
def score(self, fin, log=None):
"""Compute the score for a stock :para... | stack_v2_sparse_classes_75kplus_train_069149 | 4,516 | permissive | [
{
"docstring": ":param threshold: :type threshold: float :param start_datetime: :type start_datetime: datetime.datetime",
"name": "__init__",
"signature": "def __init__(self, threshold=0.5, start_datetime=None)"
},
{
"docstring": "Compute the score for a stock :param fin: the morningstar financi... | 2 | null | Implement the Python class `DebtToAssertScorer` described below.
Class description:
Implement the DebtToAssertScorer class.
Method signatures and docstrings:
- def __init__(self, threshold=0.5, start_datetime=None): :param threshold: :type threshold: float :param start_datetime: :type start_datetime: datetime.datetim... | Implement the Python class `DebtToAssertScorer` described below.
Class description:
Implement the DebtToAssertScorer class.
Method signatures and docstrings:
- def __init__(self, threshold=0.5, start_datetime=None): :param threshold: :type threshold: float :param start_datetime: :type start_datetime: datetime.datetim... | 88d0b3479d6bf92018335c74ef9afc4c20d61754 | <|skeleton|>
class DebtToAssertScorer:
def __init__(self, threshold=0.5, start_datetime=None):
""":param threshold: :type threshold: float :param start_datetime: :type start_datetime: datetime.datetime"""
<|body_0|>
def score(self, fin, log=None):
"""Compute the score for a stock :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DebtToAssertScorer:
def __init__(self, threshold=0.5, start_datetime=None):
""":param threshold: :type threshold: float :param start_datetime: :type start_datetime: datetime.datetime"""
self._threshold = threshold
if start_datetime is None:
self._start_datetime = get_last_y... | the_stack_v2_python_sparse | pyvalue/stock_scorer.py | ltangt/pyvalue | train | 0 | |
2ffeee91f53ed69de3fe2392bb2e44aecbbf4ac2 | [
"string_builder = ''\nif s == '':\n return True\nfor i in range(len(s)):\n string_builder += s[i]\n if string_builder in dict:\n try:\n if self.wordBreak_TLE(s[i + 1:], dict):\n return True\n else:\n continue\n except IndexError:\n ... | <|body_start_0|>
string_builder = ''
if s == '':
return True
for i in range(len(s)):
string_builder += s[i]
if string_builder in dict:
try:
if self.wordBreak_TLE(s[i + 1:], dict):
return True
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
... | stack_v2_sparse_classes_75kplus_train_069150 | 3,284 | permissive | [
{
"docstring": "TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean",
"name": "wordBreak_TLE",
"signature": "def wordBrea... | 2 | stack_v2_sparse_classes_30k_train_026217 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_TLE(self, s, dict): TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can u... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak_TLE(self, s, dict): TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can u... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wordBreak_TLE(self, s, dict):
"""TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of string :return: a boolean"""
string_bu... | the_stack_v2_python_sparse | 139 Word Break.py | Aminaba123/LeetCode | train | 1 | |
14973530cc5dc8d945ebb3f0b67b5ccc4f2f6972 | [
"super().__init__()\nself.level1 = CBR(3, 16, 3, 2)\nself.sample1 = InputProjectionA(1)\nself.sample2 = InputProjectionA(2)\nself.b1 = BR(16 + 3)\nself.level2_0 = DownSamplerB(16 + 3, 64)\nself.level2 = nn.ModuleList()\nfor i in range(0, p):\n self.level2.append(DilatedParallelResidualBlockB(64, 64))\nself.b2 = ... | <|body_start_0|>
super().__init__()
self.level1 = CBR(3, 16, 3, 2)
self.sample1 = InputProjectionA(1)
self.sample2 = InputProjectionA(2)
self.b1 = BR(16 + 3)
self.level2_0 = DownSamplerB(16 + 3, 64)
self.level2 = nn.ModuleList()
for i in range(0, p):
... | ESPNet-C encoder | ESPNetEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPNetEncoder:
"""ESPNet-C encoder"""
def __init__(self, classes=20, p=5, q=3):
""":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
<|body_0|>
def forward(self, input):
"""... | stack_v2_sparse_classes_75kplus_train_069151 | 7,920 | permissive | [
{
"docstring": ":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier",
"name": "__init__",
"signature": "def __init__(self, classes=20, p=5, q=3)"
},
{
"docstring": ":param input: Receives the input RGB image :re... | 2 | null | Implement the Python class `ESPNetEncoder` described below.
Class description:
ESPNet-C encoder
Method signatures and docstrings:
- def __init__(self, classes=20, p=5, q=3): :param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier
- def f... | Implement the Python class `ESPNetEncoder` described below.
Class description:
ESPNet-C encoder
Method signatures and docstrings:
- def __init__(self, classes=20, p=5, q=3): :param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier
- def f... | 284fed0fc2e4479ce4f30fccdcd00e469a954d09 | <|skeleton|>
class ESPNetEncoder:
"""ESPNet-C encoder"""
def __init__(self, classes=20, p=5, q=3):
""":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
<|body_0|>
def forward(self, input):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ESPNetEncoder:
"""ESPNet-C encoder"""
def __init__(self, classes=20, p=5, q=3):
""":param classes: number of classes in the dataset. Default is 20 for the cityscapes :param p: depth multiplier :param q: depth multiplier"""
super().__init__()
self.level1 = CBR(3, 16, 3, 2)
... | the_stack_v2_python_sparse | lanenet/model/encoders.py | klintan/pytorch-lanenet | train | 219 |
08cfdcc97016edc56b3a099c5f01cd65edbe7b3d | [
"PartParameterTemplate = self.old_state.apps.get_model('part', 'partparametertemplate')\ntemplate = PartParameterTemplate.objects.create(name='Template 1', description='a part parameter template')\nwith self.assertRaises(AttributeError):\n template.choices\nwith self.assertRaises(AttributeError):\n template.c... | <|body_start_0|>
PartParameterTemplate = self.old_state.apps.get_model('part', 'partparametertemplate')
template = PartParameterTemplate.objects.create(name='Template 1', description='a part parameter template')
with self.assertRaises(AttributeError):
template.choices
with se... | Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987 | TestPartParameterTemplateMigration | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPartParameterTemplateMigration:
"""Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987"""
def prepare(self):
"""Prepare some parts with units"""
<|body_0|>
def test_units_migration(self):
"""Test that the new... | stack_v2_sparse_classes_75kplus_train_069152 | 8,200 | permissive | [
{
"docstring": "Prepare some parts with units",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test that the new fields have been added correctly",
"name": "test_units_migration",
"signature": "def test_units_migration(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016225 | Implement the Python class `TestPartParameterTemplateMigration` described below.
Class description:
Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987
Method signatures and docstrings:
- def prepare(self): Prepare some parts with units
- def test_units_migration(sel... | Implement the Python class `TestPartParameterTemplateMigration` described below.
Class description:
Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987
Method signatures and docstrings:
- def prepare(self): Prepare some parts with units
- def test_units_migration(sel... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestPartParameterTemplateMigration:
"""Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987"""
def prepare(self):
"""Prepare some parts with units"""
<|body_0|>
def test_units_migration(self):
"""Test that the new... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestPartParameterTemplateMigration:
"""Test for data migration of PartParameterTemplate Ref: https://github.com/inventree/InvenTree/pull/4987"""
def prepare(self):
"""Prepare some parts with units"""
PartParameterTemplate = self.old_state.apps.get_model('part', 'partparametertemplate')
... | the_stack_v2_python_sparse | InvenTree/part/test_migrations.py | inventree/InvenTree | train | 3,077 |
2212e5f85ae948bb12cd25a03cf24d64e5eb1b53 | [
"with patch('forum.views.render_to_response') as render:\n request = MagicMock()\n render.return_value = 'template'\n self.assertEqual('template', views.thread_layout(request))\n self.assertEqual('template', views.modern(request))\n self.assertEqual('template', views.create(request))",
"with patch(... | <|body_start_0|>
with patch('forum.views.render_to_response') as render:
request = MagicMock()
render.return_value = 'template'
self.assertEqual('template', views.thread_layout(request))
self.assertEqual('template', views.modern(request))
self.assertEq... | This is forum test. | Forum_test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Forum_test:
"""This is forum test."""
def test_basic(self):
"""This function tests if thread_layout, modern, create function returns right templates."""
<|body_0|>
def test_load_data(self):
"""This function tests **load_data()** that is responsible for posts data... | stack_v2_sparse_classes_75kplus_train_069153 | 2,308 | no_license | [
{
"docstring": "This function tests if thread_layout, modern, create function returns right templates.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "This function tests **load_data()** that is responsible for posts data for the forum.",
"name": "test_load_dat... | 3 | stack_v2_sparse_classes_30k_train_012648 | Implement the Python class `Forum_test` described below.
Class description:
This is forum test.
Method signatures and docstrings:
- def test_basic(self): This function tests if thread_layout, modern, create function returns right templates.
- def test_load_data(self): This function tests **load_data()** that is respo... | Implement the Python class `Forum_test` described below.
Class description:
This is forum test.
Method signatures and docstrings:
- def test_basic(self): This function tests if thread_layout, modern, create function returns right templates.
- def test_load_data(self): This function tests **load_data()** that is respo... | 2a6d792d7638ec1c89073a5eee94a6e611c8aa83 | <|skeleton|>
class Forum_test:
"""This is forum test."""
def test_basic(self):
"""This function tests if thread_layout, modern, create function returns right templates."""
<|body_0|>
def test_load_data(self):
"""This function tests **load_data()** that is responsible for posts data... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Forum_test:
"""This is forum test."""
def test_basic(self):
"""This function tests if thread_layout, modern, create function returns right templates."""
with patch('forum.views.render_to_response') as render:
request = MagicMock()
render.return_value = 'template'
... | the_stack_v2_python_sparse | met_hunt/forum/tests.py | Melshaabiny/metscavengerhunt | train | 0 |
ead3177246d2c42e92f5d2830552894fdc49e386 | [
"self.u_href = u_href\nself.h_ref = h_ref\nself.z_0 = z_0\nself.mask = mask\narray_sizes = [np.size(u_href), np.size(h_ref), np.size(z_0), np.size(mask)]\nif not all((x == array_sizes[0] for x in array_sizes)):\n raise ValueError('Different size input arrays u_href, h_ref, z_0, mask')",
"ustar = np.full(self.u... | <|body_start_0|>
self.u_href = u_href
self.h_ref = h_ref
self.z_0 = z_0
self.mask = mask
array_sizes = [np.size(u_href), np.size(h_ref), np.size(z_0), np.size(mask)]
if not all((x == array_sizes[0] for x in array_sizes)):
raise ValueError('Different size input... | Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0. | FrictionVelocity | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrictionVelocity:
"""Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0."""
def __init__(self, u_href: ndarray, h_ref: ndarray, ... | stack_v2_sparse_classes_75kplus_train_069154 | 37,222 | permissive | [
{
"docstring": "Initialise the class. Args: u_href: A 2D array of float32 for the wind speed at h_ref h_ref: A 2D array of float32 for the reference heights z_0: A 2D array of float32 for the vegetative roughness lengths mask: A 2D array of booleans where True indicates calculate u* Notes: * z_0 and h_ref need ... | 2 | stack_v2_sparse_classes_30k_train_001346 | Implement the Python class `FrictionVelocity` described below.
Class description:
Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0.
Method signatures an... | Implement the Python class `FrictionVelocity` described below.
Class description:
Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0.
Method signatures an... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class FrictionVelocity:
"""Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0."""
def __init__(self, u_href: ndarray, h_ref: ndarray, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FrictionVelocity:
"""Class to calculate the friction velocity. This holds the function to calculate the friction velocity u_star, given a reference height h_ref, the velocity at the reference height u_href and the surface roughness z_0."""
def __init__(self, u_href: ndarray, h_ref: ndarray, z_0: ndarray,... | the_stack_v2_python_sparse | improver/wind_calculations/wind_downscaling.py | metoppv/improver | train | 101 |
3831c19b0fff938192bc36bcf098c408f524804f | [
"if 'instagram_username' in request.GET:\n instagram_username = request.GET['instagram_username']\nelif post and 'instagram_username' in request.data:\n instagram_username = request.data['instagram_username']\nelse:\n raise ValidationError(detail='instagram_username parameter is mandatory.')\nif not valida... | <|body_start_0|>
if 'instagram_username' in request.GET:
instagram_username = request.GET['instagram_username']
elif post and 'instagram_username' in request.data:
instagram_username = request.data['instagram_username']
else:
raise ValidationError(detail='inst... | Make request to retrieve information about the images selected by an instagram user, these would be the images displayed in the story creator tab. Returns only the images selected by the requesting user. | SelectedImageViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelectedImageViewSet:
"""Make request to retrieve information about the images selected by an instagram user, these would be the images displayed in the story creator tab. Returns only the images selected by the requesting user."""
def validate(self, request, post=None):
"""Validates... | stack_v2_sparse_classes_75kplus_train_069155 | 2,167 | no_license | [
{
"docstring": "Validates if the instagram user exists and it belongs to this user. Throws an error if something is wrong. Returns the instagram user otherwise.",
"name": "validate",
"signature": "def validate(self, request, post=None)"
},
{
"docstring": "GET the list of selected images for the ... | 3 | null | Implement the Python class `SelectedImageViewSet` described below.
Class description:
Make request to retrieve information about the images selected by an instagram user, these would be the images displayed in the story creator tab. Returns only the images selected by the requesting user.
Method signatures and docstr... | Implement the Python class `SelectedImageViewSet` described below.
Class description:
Make request to retrieve information about the images selected by an instagram user, these would be the images displayed in the story creator tab. Returns only the images selected by the requesting user.
Method signatures and docstr... | a5219078b6d12950fc1bb0337d91030b2db7ce70 | <|skeleton|>
class SelectedImageViewSet:
"""Make request to retrieve information about the images selected by an instagram user, these would be the images displayed in the story creator tab. Returns only the images selected by the requesting user."""
def validate(self, request, post=None):
"""Validates... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelectedImageViewSet:
"""Make request to retrieve information about the images selected by an instagram user, these would be the images displayed in the story creator tab. Returns only the images selected by the requesting user."""
def validate(self, request, post=None):
"""Validates if the insta... | the_stack_v2_python_sparse | back-end/application/database/viewsets.py | RUGSoftEng/2018-JuicyStory | train | 0 |
a2a147dbe419e37265932ccc25777cfc00ebb345 | [
"if len(parts) != 2:\n self.client.sendServerMessage('Please include a height and no more.')\nelse:\n height = int(parts[1])\n x, y, z, h, p = (self.client.x >> 5, self.client.y >> 5, self.client.z >> 5, self.client.h, self.client.p)\n self.client.teleportTo(x, y + height, z, h, p)\n self.client.send... | <|body_start_0|>
if len(parts) != 2:
self.client.sendServerMessage('Please include a height and no more.')
else:
height = int(parts[1])
x, y, z, h, p = (self.client.x >> 5, self.client.y >> 5, self.client.z >> 5, self.client.h, self.client.p)
self.client.t... | AscendDescendPlugin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AscendDescendPlugin:
def commandAscend(self, parts, fromloc, overriderank):
"""/ascend <height> - Admin Ascend a given height."""
<|body_0|>
def commandDescend(self, parts, fromloc, overriderank):
"""/descend <height> - Admin Descend a given height."""
<|body... | stack_v2_sparse_classes_75kplus_train_069156 | 1,353 | permissive | [
{
"docstring": "/ascend <height> - Admin Ascend a given height.",
"name": "commandAscend",
"signature": "def commandAscend(self, parts, fromloc, overriderank)"
},
{
"docstring": "/descend <height> - Admin Descend a given height.",
"name": "commandDescend",
"signature": "def commandDescen... | 2 | stack_v2_sparse_classes_30k_train_008683 | Implement the Python class `AscendDescendPlugin` described below.
Class description:
Implement the AscendDescendPlugin class.
Method signatures and docstrings:
- def commandAscend(self, parts, fromloc, overriderank): /ascend <height> - Admin Ascend a given height.
- def commandDescend(self, parts, fromloc, overridera... | Implement the Python class `AscendDescendPlugin` described below.
Class description:
Implement the AscendDescendPlugin class.
Method signatures and docstrings:
- def commandAscend(self, parts, fromloc, overriderank): /ascend <height> - Admin Ascend a given height.
- def commandDescend(self, parts, fromloc, overridera... | 5482def8b50562fdbae980cda9b1708bfad8bffb | <|skeleton|>
class AscendDescendPlugin:
def commandAscend(self, parts, fromloc, overriderank):
"""/ascend <height> - Admin Ascend a given height."""
<|body_0|>
def commandDescend(self, parts, fromloc, overriderank):
"""/descend <height> - Admin Descend a given height."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AscendDescendPlugin:
def commandAscend(self, parts, fromloc, overriderank):
"""/ascend <height> - Admin Ascend a given height."""
if len(parts) != 2:
self.client.sendServerMessage('Please include a height and no more.')
else:
height = int(parts[1])
x... | the_stack_v2_python_sparse | core/plugins/ascend.py | TheArchives/Nexus | train | 1 | |
e13a6c96f2a47c4e2eb2a4e2f8cb831efd593e3d | [
"assert alpha >= 0\nsuper(PrioritizedReplayBuffer, self).__init__(obs_dim, size, batch_size)\nself.max_priority, self.tree_ptr = (1.0, 0)\nself.alpha = alpha\ntree_capacity = 1\nwhile tree_capacity < self.max_size:\n tree_capacity *= 2\nself.sum_tree = SumSegmentTree(tree_capacity)\nself.min_tree = MinSegmentTre... | <|body_start_0|>
assert alpha >= 0
super(PrioritizedReplayBuffer, self).__init__(obs_dim, size, batch_size)
self.max_priority, self.tree_ptr = (1.0, 0)
self.alpha = alpha
tree_capacity = 1
while tree_capacity < self.max_size:
tree_capacity *= 2
self.su... | Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weight | PrioritizedReplayBuffer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrioritizedReplayBuffer:
"""Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to ... | stack_v2_sparse_classes_75kplus_train_069157 | 19,863 | no_license | [
{
"docstring": "Initialization.",
"name": "__init__",
"signature": "def __init__(self, obs_dim: int, size: int, batch_size: int=32, alpha: float=0.6)"
},
{
"docstring": "Store experience and priority.",
"name": "store",
"signature": "def store(self, obs: np.ndarray, act: int, rew: float,... | 6 | stack_v2_sparse_classes_30k_train_005672 | Implement the Python class `PrioritizedReplayBuffer` described below.
Class description:
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinS... | Implement the Python class `PrioritizedReplayBuffer` described below.
Class description:
Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinS... | 99472f5f6b37bc421e31b145ace55bb175c5b2c4 | <|skeleton|>
class PrioritizedReplayBuffer:
"""Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrioritizedReplayBuffer:
"""Prioritized Replay buffer. Attributes: max_priority (float): max priority tree_ptr (int): next index of tree alpha (float): alpha parameter for prioritized replay buffer sum_tree (SumSegmentTree): sum tree for prior min_tree (MinSegmentTree): min tree for min prior to get max weigh... | the_stack_v2_python_sparse | agent/agent_D3QN_PER_48_torch.py | ZJ96/City_Brain_TSC | train | 4 |
631836f7da85434f1ae1fb81e3ebb35065638ca6 | [
"binds = []\nfor jid, fid, run, lumi in jobFileRunLumis:\n binds.append({'jobid': jid, 'fileid': fid, 'run': run, 'lumi': lumi})\nreturn binds",
"if jobFileRunLumis:\n binds = self.getBinds(jobFileRunLumis)\nelif jobid and fileid and run and lumi:\n binds = DBFormatter.getBinds(self, jobid=jobid, fileid=... | <|body_start_0|>
binds = []
for jid, fid, run, lumi in jobFileRunLumis:
binds.append({'jobid': jid, 'fileid': fid, 'run': run, 'lumi': lumi})
return binds
<|end_body_0|>
<|body_start_1|>
if jobFileRunLumis:
binds = self.getBinds(jobFileRunLumis)
elif jobi... | Add WorkUnit associations to jobs | AddWorkUnits | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddWorkUnits:
"""Add WorkUnit associations to jobs"""
def getBinds(self, jobFileRunLumis):
"""Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A"""
<|body_0|>
def execute(self,... | stack_v2_sparse_classes_75kplus_train_069158 | 2,035 | permissive | [
{
"docstring": "Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A",
"name": "getBinds",
"signature": "def getBinds(self, jobFileRunLumis)"
},
{
"docstring": "Args: jobid: The id of a single job fileid... | 2 | stack_v2_sparse_classes_30k_train_033162 | Implement the Python class `AddWorkUnits` described below.
Class description:
Add WorkUnit associations to jobs
Method signatures and docstrings:
- def getBinds(self, jobFileRunLumis): Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] ... | Implement the Python class `AddWorkUnits` described below.
Class description:
Add WorkUnit associations to jobs
Method signatures and docstrings:
- def getBinds(self, jobFileRunLumis): Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] ... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class AddWorkUnits:
"""Add WorkUnit associations to jobs"""
def getBinds(self, jobFileRunLumis):
"""Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A"""
<|body_0|>
def execute(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddWorkUnits:
"""Add WorkUnit associations to jobs"""
def getBinds(self, jobFileRunLumis):
"""Translate a bulk list into a number of inserts Args: jobFileRunLumis: a list of tuples of the form [(jobid, fileid, run, lumi), ...] Returns: N/A"""
binds = []
for jid, fid, run, lumi in ... | the_stack_v2_python_sparse | src/python/WMCore/WMBS/MySQL/Jobs/AddWorkUnits.py | vkuznet/WMCore | train | 0 |
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6 | [
"key = LibraryUsageLocatorV2.from_string(usage_key_str)\napi.require_permission_for_library_key(key.lib_key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY)\nfiles = api.get_library_block_static_asset_files(key)\nfor f in files:\n if f.path == file_path:\n return Response(LibraryXBlockStaticFileS... | <|body_start_0|>
key = LibraryUsageLocatorV2.from_string(usage_key_str)
api.require_permission_for_library_key(key.lib_key, request.user, permissions.CAN_VIEW_THIS_CONTENT_LIBRARY)
files = api.get_library_block_static_asset_files(key)
for f in files:
if f.path == file_path:
... | Views to work with an existing XBlock's static asset files | LibraryBlockAssetView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LibraryBlockAssetView:
"""Views to work with an existing XBlock's static asset files"""
def get(self, request, usage_key_str, file_path):
"""Get a static asset file belonging to this block."""
<|body_0|>
def put(self, request, usage_key_str, file_path):
"""Replac... | stack_v2_sparse_classes_75kplus_train_069159 | 42,120 | permissive | [
{
"docstring": "Get a static asset file belonging to this block.",
"name": "get",
"signature": "def get(self, request, usage_key_str, file_path)"
},
{
"docstring": "Replace a static asset file belonging to this block.",
"name": "put",
"signature": "def put(self, request, usage_key_str, f... | 3 | stack_v2_sparse_classes_30k_train_015587 | Implement the Python class `LibraryBlockAssetView` described below.
Class description:
Views to work with an existing XBlock's static asset files
Method signatures and docstrings:
- def get(self, request, usage_key_str, file_path): Get a static asset file belonging to this block.
- def put(self, request, usage_key_st... | Implement the Python class `LibraryBlockAssetView` described below.
Class description:
Views to work with an existing XBlock's static asset files
Method signatures and docstrings:
- def get(self, request, usage_key_str, file_path): Get a static asset file belonging to this block.
- def put(self, request, usage_key_st... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LibraryBlockAssetView:
"""Views to work with an existing XBlock's static asset files"""
def get(self, request, usage_key_str, file_path):
"""Get a static asset file belonging to this block."""
<|body_0|>
def put(self, request, usage_key_str, file_path):
"""Replac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LibraryBlockAssetView:
"""Views to work with an existing XBlock's static asset files"""
def get(self, request, usage_key_str, file_path):
"""Get a static asset file belonging to this block."""
key = LibraryUsageLocatorV2.from_string(usage_key_str)
api.require_permission_for_librar... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py | luque/better-ways-of-thinking-about-software | train | 3 |
874f2758d308d84738a862299237ad40e4b004b0 | [
"self.args = args\nself.gcp_env = gcp_env\nself.db_conn = None\nself.id_list = id_list\nself.recipients, self.cc_recipients = self._get_email_addresses(self.args.to, self.args.cc)",
"recipients, cc_recipients = (None, None)\nif to_list:\n recipients = list(to_list.split(','))\nif cc_list:\n cc_recipients = ... | <|body_start_0|>
self.args = args
self.gcp_env = gcp_env
self.db_conn = None
self.id_list = id_list
self.recipients, self.cc_recipients = self._get_email_addresses(self.args.to, self.args.cc)
<|end_body_0|>
<|body_start_1|>
recipients, cc_recipients = (None, None)
... | " The ConsentReport class will contain attributes and methods common to both the daily consent validation report and the weekly consent validation status report. | ConsentErrorReportTool | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConsentErrorReportTool:
"""" The ConsentReport class will contain attributes and methods common to both the daily consent validation report and the weekly consent validation status report."""
def __init__(self, args, gcp_env: GCPEnvConfigObject, id_list=None):
""":param args: command... | stack_v2_sparse_classes_75kplus_train_069160 | 8,187 | permissive | [
{
"docstring": ":param args: command line arguments. :param gcp_env: gcp environment information, see: gcp_initialize().",
"name": "__init__",
"signature": "def __init__(self, args, gcp_env: GCPEnvConfigObject, id_list=None)"
},
{
"docstring": "Transform comma-separated strings passed as tool pa... | 4 | null | Implement the Python class `ConsentErrorReportTool` described below.
Class description:
" The ConsentReport class will contain attributes and methods common to both the daily consent validation report and the weekly consent validation status report.
Method signatures and docstrings:
- def __init__(self, args, gcp_env... | Implement the Python class `ConsentErrorReportTool` described below.
Class description:
" The ConsentReport class will contain attributes and methods common to both the daily consent validation report and the weekly consent validation status report.
Method signatures and docstrings:
- def __init__(self, args, gcp_env... | 461ae46aeda21d54de8a91aa5ef677676d5db541 | <|skeleton|>
class ConsentErrorReportTool:
"""" The ConsentReport class will contain attributes and methods common to both the daily consent validation report and the weekly consent validation status report."""
def __init__(self, args, gcp_env: GCPEnvConfigObject, id_list=None):
""":param args: command... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConsentErrorReportTool:
"""" The ConsentReport class will contain attributes and methods common to both the daily consent validation report and the weekly consent validation status report."""
def __init__(self, args, gcp_env: GCPEnvConfigObject, id_list=None):
""":param args: command line argumen... | the_stack_v2_python_sparse | rdr_service/tools/tool_libs/consent_error_report.py | all-of-us/raw-data-repository | train | 46 |
3ea6fb833b7088257aeeaf88948364efe7913ad4 | [
"if len(nums) < 2:\n return False\ns = sum(nums)\nif s % 2 == 1:\n return False\nhalf = s // 2\ndp = []\nfor i in range(len(nums) + 1):\n dp.append([False for i in range(half + 1)])\nfor j in range(half + 1):\n dp[0][j] = False\nfor i in range(len(nums) + 1):\n dp[i][0] = True\ndp[0][0] = True\nfor i... | <|body_start_0|>
if len(nums) < 2:
return False
s = sum(nums)
if s % 2 == 1:
return False
half = s // 2
dp = []
for i in range(len(nums) + 1):
dp.append([False for i in range(half + 1)])
for j in range(half + 1):
dp[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartitionV2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 2:
return Fa... | stack_v2_sparse_classes_75kplus_train_069161 | 1,939 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartition",
"signature": "def canPartition(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canPartitionV2",
"signature": "def canPartitionV2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007768 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): :type nums: List[int] :rtype: bool
- def canPartitionV2(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): :type nums: List[int] :rtype: bool
- def canPartitionV2(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def canPa... | d6ddbef76dd8630234f669d272d1f8065c6be128 | <|skeleton|>
class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartitionV2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canPartition(self, nums):
""":type nums: List[int] :rtype: bool"""
if len(nums) < 2:
return False
s = sum(nums)
if s % 2 == 1:
return False
half = s // 2
dp = []
for i in range(len(nums) + 1):
dp.append([... | the_stack_v2_python_sparse | dp/knapsack/416. Partition Equal Subset Sum.py | Mang0o/leetcode | train | 0 | |
205198a8f93a8f1cfbc4229460dd12f7b9c693ac | [
"if rss_source_feed is not None:\n self.rss_feed = rss_source_feed\nelse:\n self.rss_feed = feedparser.parse(self.all_rss_address)\nself.source = source",
"for job_info in self.rss_feed.entries:\n post = self.parse_job_to_post(job_info)\n yield post",
"created = timezone.make_aware(datetime.datetime... | <|body_start_0|>
if rss_source_feed is not None:
self.rss_feed = rss_source_feed
else:
self.rss_feed = feedparser.parse(self.all_rss_address)
self.source = source
<|end_body_0|>
<|body_start_1|>
for job_info in self.rss_feed.entries:
post = self.parse... | Wrapper for the FossJobs source. | FossJobs | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FossJobs:
"""Wrapper for the FossJobs source."""
def __init__(self, source, rss_source_feed=None):
"""Parse the feed or accept the incoming one (for testing)."""
<|body_0|>
def jobs(self):
"""Iterate through all available jobs."""
<|body_1|>
def pars... | stack_v2_sparse_classes_75kplus_train_069162 | 1,382 | permissive | [
{
"docstring": "Parse the feed or accept the incoming one (for testing).",
"name": "__init__",
"signature": "def __init__(self, source, rss_source_feed=None)"
},
{
"docstring": "Iterate through all available jobs.",
"name": "jobs",
"signature": "def jobs(self)"
},
{
"docstring": ... | 3 | null | Implement the Python class `FossJobs` described below.
Class description:
Wrapper for the FossJobs source.
Method signatures and docstrings:
- def __init__(self, source, rss_source_feed=None): Parse the feed or accept the incoming one (for testing).
- def jobs(self): Iterate through all available jobs.
- def parse_jo... | Implement the Python class `FossJobs` described below.
Class description:
Wrapper for the FossJobs source.
Method signatures and docstrings:
- def __init__(self, source, rss_source_feed=None): Parse the feed or accept the incoming one (for testing).
- def jobs(self): Iterate through all available jobs.
- def parse_jo... | 7882aa8ed42afe689e594a3e10c9fc6369f70bf5 | <|skeleton|>
class FossJobs:
"""Wrapper for the FossJobs source."""
def __init__(self, source, rss_source_feed=None):
"""Parse the feed or accept the incoming one (for testing)."""
<|body_0|>
def jobs(self):
"""Iterate through all available jobs."""
<|body_1|>
def pars... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FossJobs:
"""Wrapper for the FossJobs source."""
def __init__(self, source, rss_source_feed=None):
"""Parse the feed or accept the incoming one (for testing)."""
if rss_source_feed is not None:
self.rss_feed = rss_source_feed
else:
self.rss_feed = feedparse... | the_stack_v2_python_sparse | freelancefinder/remotes/sources/fossjobs/fossjobs.py | simo97/freelancefinder | train | 0 |
02bfe0ce1c76ab1c2e117d7156375206e62f8fbc | [
"repository = PostRepository(info.context.get('client_motor'))\npost = await repository.get_item_post_by_alias(alias)\nreturn PostObjectType(alias=post.alias, title=post.title, text=post.text)",
"repository = PostRepository(info.context.get('client_motor'))\nlist_posts = await repository.get_list_posts(alias_tag=... | <|body_start_0|>
repository = PostRepository(info.context.get('client_motor'))
post = await repository.get_item_post_by_alias(alias)
return PostObjectType(alias=post.alias, title=post.title, text=post.text)
<|end_body_0|>
<|body_start_1|>
repository = PostRepository(info.context.get('cl... | Обработка запросов блога с использованием GraphQL. | BlogQuery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogQuery:
"""Обработка запросов блога с использованием GraphQL."""
async def resolve_post(self, info, alias) -> PostObjectType:
"""Запрос поста по его псевдониму."""
<|body_0|>
async def resolve_list_posts_by_tag(self, info, alias_tag, current_page=0) -> ListPostsObject... | stack_v2_sparse_classes_75kplus_train_069163 | 5,222 | no_license | [
{
"docstring": "Запрос поста по его псевдониму.",
"name": "resolve_post",
"signature": "async def resolve_post(self, info, alias) -> PostObjectType"
},
{
"docstring": "Запрос на получение информации по содержимому определенного тега.",
"name": "resolve_list_posts_by_tag",
"signature": "a... | 3 | stack_v2_sparse_classes_30k_train_004298 | Implement the Python class `BlogQuery` described below.
Class description:
Обработка запросов блога с использованием GraphQL.
Method signatures and docstrings:
- async def resolve_post(self, info, alias) -> PostObjectType: Запрос поста по его псевдониму.
- async def resolve_list_posts_by_tag(self, info, alias_tag, cu... | Implement the Python class `BlogQuery` described below.
Class description:
Обработка запросов блога с использованием GraphQL.
Method signatures and docstrings:
- async def resolve_post(self, info, alias) -> PostObjectType: Запрос поста по его псевдониму.
- async def resolve_list_posts_by_tag(self, info, alias_tag, cu... | c22b3bc4c533b2e1508dfbd211ce98e26517d079 | <|skeleton|>
class BlogQuery:
"""Обработка запросов блога с использованием GraphQL."""
async def resolve_post(self, info, alias) -> PostObjectType:
"""Запрос поста по его псевдониму."""
<|body_0|>
async def resolve_list_posts_by_tag(self, info, alias_tag, current_page=0) -> ListPostsObject... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlogQuery:
"""Обработка запросов блога с использованием GraphQL."""
async def resolve_post(self, info, alias) -> PostObjectType:
"""Запрос поста по его псевдониму."""
repository = PostRepository(info.context.get('client_motor'))
post = await repository.get_item_post_by_alias(alias... | the_stack_v2_python_sparse | server/modules/blog/schema.py | Rey8d01/chimera | train | 10 |
90c7db22428a08c218ca90a408ed99828138981a | [
"search_direct = request.GET.get('search_direction', '')\nsearch_state = request.GET.get('search_state')\nfound_direct = ''\nfound_state = ''\nall_values = request.GET.get('all_values')\nif all_values:\n vacancies = Vacancy.objects.all().order_by(Lower('organization'))\nelif search_direct and search_state:\n ... | <|body_start_0|>
search_direct = request.GET.get('search_direction', '')
search_state = request.GET.get('search_state')
found_direct = ''
found_state = ''
all_values = request.GET.get('all_values')
if all_values:
vacancies = Vacancy.objects.all().order_by(Lowe... | Vacancies | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vacancies:
def get(self, request):
"""Вывод на экран базы работодателей. Поиск и вывод результата на экран."""
<|body_0|>
def post(self, request):
"""Создание карточки вакансии."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
search_direct = request... | stack_v2_sparse_classes_75kplus_train_069164 | 34,934 | no_license | [
{
"docstring": "Вывод на экран базы работодателей. Поиск и вывод результата на экран.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Создание карточки вакансии.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014131 | Implement the Python class `Vacancies` described below.
Class description:
Implement the Vacancies class.
Method signatures and docstrings:
- def get(self, request): Вывод на экран базы работодателей. Поиск и вывод результата на экран.
- def post(self, request): Создание карточки вакансии. | Implement the Python class `Vacancies` described below.
Class description:
Implement the Vacancies class.
Method signatures and docstrings:
- def get(self, request): Вывод на экран базы работодателей. Поиск и вывод результата на экран.
- def post(self, request): Создание карточки вакансии.
<|skeleton|>
class Vacanci... | ca0fd60217b946f16a64e24fa091c0f155c452bc | <|skeleton|>
class Vacancies:
def get(self, request):
"""Вывод на экран базы работодателей. Поиск и вывод результата на экран."""
<|body_0|>
def post(self, request):
"""Создание карточки вакансии."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vacancies:
def get(self, request):
"""Вывод на экран базы работодателей. Поиск и вывод результата на экран."""
search_direct = request.GET.get('search_direction', '')
search_state = request.GET.get('search_state')
found_direct = ''
found_state = ''
all_values = ... | the_stack_v2_python_sparse | recruit/views.py | Sanello2010/BelHardCMS | train | 1 | |
b4d5f9d41d2de4f8f37d32a98b1b3037b0efa458 | [
"if bits % 8 != 0:\n raise ValueError('not implemented')\nself.a = a\nself.mod = mod\nself.bits = bits",
"if seed is None:\n while True:\n seed = int.from_bytes(os.urandom(self.mod.bit_length() // 8 + 8), 'little') % self.mod\n if math.gcd(seed, self.mod) == 1:\n break\nstate = seed... | <|body_start_0|>
if bits % 8 != 0:
raise ValueError('not implemented')
self.a = a
self.mod = mod
self.bits = bits
<|end_body_0|>
<|body_start_1|>
if seed is None:
while True:
seed = int.from_bytes(os.urandom(self.mod.bit_length() // 8 + 8)... | Lehmer pseudorandom number generator. https://en.wikipedia.org/wiki/Lehmer_random_number_generator. Default parameters use a 128 bit instance proposed by L'Ecuyer. FindBias can detect this pseudorandom number generator. Detection still works if the output is truncated to 16 bits, but fails when only 8 bits per step are... | Lehmer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lehmer:
"""Lehmer pseudorandom number generator. https://en.wikipedia.org/wiki/Lehmer_random_number_generator. Default parameters use a 128 bit instance proposed by L'Ecuyer. FindBias can detect this pseudorandom number generator. Detection still works if the output is truncated to 16 bits, but f... | stack_v2_sparse_classes_75kplus_train_069165 | 19,579 | permissive | [
{
"docstring": "Constructs a Lehmer pseudo random number generator. Args: a: the multiplier mod: the modulus bits: the number of bits of output per step. This implementation only supports output sizes that are a multiple of 8.",
"name": "__init__",
"signature": "def __init__(self, a: int=250962815189121... | 2 | stack_v2_sparse_classes_30k_train_025736 | Implement the Python class `Lehmer` described below.
Class description:
Lehmer pseudorandom number generator. https://en.wikipedia.org/wiki/Lehmer_random_number_generator. Default parameters use a 128 bit instance proposed by L'Ecuyer. FindBias can detect this pseudorandom number generator. Detection still works if th... | Implement the Python class `Lehmer` described below.
Class description:
Lehmer pseudorandom number generator. https://en.wikipedia.org/wiki/Lehmer_random_number_generator. Default parameters use a 128 bit instance proposed by L'Ecuyer. FindBias can detect this pseudorandom number generator. Detection still works if th... | 16e5f47fcc11f51d3fb58b50adddd075f4373bbc | <|skeleton|>
class Lehmer:
"""Lehmer pseudorandom number generator. https://en.wikipedia.org/wiki/Lehmer_random_number_generator. Default parameters use a 128 bit instance proposed by L'Ecuyer. FindBias can detect this pseudorandom number generator. Detection still works if the output is truncated to 16 bits, but f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lehmer:
"""Lehmer pseudorandom number generator. https://en.wikipedia.org/wiki/Lehmer_random_number_generator. Default parameters use a 128 bit instance proposed by L'Ecuyer. FindBias can detect this pseudorandom number generator. Detection still works if the output is truncated to 16 bits, but fails when onl... | the_stack_v2_python_sparse | paranoid_crypto/lib/randomness_tests/rng.py | google/paranoid_crypto | train | 766 |
33f01f6a41f63f4a22c9c3457d71ed2d44853e5e | [
"super(SyncArrival, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._control = carla.VehicleControl()\nself._actor = actor\nself._actor_reference = actor_reference\nself._target_location = target_location\nself._gain = gain\nself._control.steering = 0",
"new_status = py_tr... | <|body_start_0|>
super(SyncArrival, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._control = carla.VehicleControl()
self._actor = actor
self._actor_reference = actor_reference
self._target_location = target_location
self._g... | This class contains an atomic behavior to set velocity of actor so that it reaches location at the same time as actor_reference. The behaviour assumes that the two actors are moving towards location in a straight line. Note: In parallel to this behavior a termination behavior has to be used to keep continue scynhronisa... | SyncArrival | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyncArrival:
"""This class contains an atomic behavior to set velocity of actor so that it reaches location at the same time as actor_reference. The behaviour assumes that the two actors are moving towards location in a straight line. Note: In parallel to this behavior a termination behavior has ... | stack_v2_sparse_classes_75kplus_train_069166 | 25,380 | permissive | [
{
"docstring": "actor : actor to be controlled actor_ reference : reference actor with which arrival has to be synchronised gain : coefficient for actor's throttle and break controls",
"name": "__init__",
"signature": "def __init__(self, actor, actor_reference, target_location, gain=1, name='SyncArrival... | 3 | stack_v2_sparse_classes_30k_train_005572 | Implement the Python class `SyncArrival` described below.
Class description:
This class contains an atomic behavior to set velocity of actor so that it reaches location at the same time as actor_reference. The behaviour assumes that the two actors are moving towards location in a straight line. Note: In parallel to th... | Implement the Python class `SyncArrival` described below.
Class description:
This class contains an atomic behavior to set velocity of actor so that it reaches location at the same time as actor_reference. The behaviour assumes that the two actors are moving towards location in a straight line. Note: In parallel to th... | 1d3e8339f8e60f7bdcaefeff49ec238b1746b047 | <|skeleton|>
class SyncArrival:
"""This class contains an atomic behavior to set velocity of actor so that it reaches location at the same time as actor_reference. The behaviour assumes that the two actors are moving towards location in a straight line. Note: In parallel to this behavior a termination behavior has ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SyncArrival:
"""This class contains an atomic behavior to set velocity of actor so that it reaches location at the same time as actor_reference. The behaviour assumes that the two actors are moving towards location in a straight line. Note: In parallel to this behavior a termination behavior has to be used to... | the_stack_v2_python_sparse | srunner/scenariomanager/atomic_scenario_behavior.py | chauvinSimon/scenario_runner | train | 2 |
10f3c7eff353d95ffa12f9b2c373def929c32c3a | [
"question_tokens = set(get_cleaned_seq_tokens(question.text))\ncolumns_queue = queue.PriorityQueue()\nfor i in range(len(interaction.table.columns)):\n column_tokens = self._get_column_tokens(interaction, i)\n score = _get_question_column_similarity(set(column_tokens), question_tokens)\n columns_queue.put(... | <|body_start_0|>
question_tokens = set(get_cleaned_seq_tokens(question.text))
columns_queue = queue.PriorityQueue()
for i in range(len(interaction.table.columns)):
column_tokens = self._get_column_tokens(interaction, i)
score = _get_question_column_similarity(set(column_t... | Extracts columns that contain tokens'strings match a subset of the question's string. | HeuristicExactMatchTokenSelector | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HeuristicExactMatchTokenSelector:
"""Extracts columns that contain tokens'strings match a subset of the question's string."""
def _select_columns(self, interaction, question):
"""Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: ... | stack_v2_sparse_classes_75kplus_train_069167 | 22,320 | permissive | [
{
"docstring": "Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: contains the cells. question: contains the original text of the question. Returns: The set of selected columns' indexes.",
"name": "_select_columns",
"signature": "def _select_columns... | 2 | stack_v2_sparse_classes_30k_val_001760 | Implement the Python class `HeuristicExactMatchTokenSelector` described below.
Class description:
Extracts columns that contain tokens'strings match a subset of the question's string.
Method signatures and docstrings:
- def _select_columns(self, interaction, question): Extracts columns that contain tokens'strings mat... | Implement the Python class `HeuristicExactMatchTokenSelector` described below.
Class description:
Extracts columns that contain tokens'strings match a subset of the question's string.
Method signatures and docstrings:
- def _select_columns(self, interaction, question): Extracts columns that contain tokens'strings mat... | 569a3c31451d941165bd10783f73f494406b3906 | <|skeleton|>
class HeuristicExactMatchTokenSelector:
"""Extracts columns that contain tokens'strings match a subset of the question's string."""
def _select_columns(self, interaction, question):
"""Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HeuristicExactMatchTokenSelector:
"""Extracts columns that contain tokens'strings match a subset of the question's string."""
def _select_columns(self, interaction, question):
"""Extracts columns that contain tokens'strings match a subset of the question's string. Args: interaction: contains the ... | the_stack_v2_python_sparse | tapas/utils/pruning_utils.py | google-research/tapas | train | 1,043 |
524e78fb44a0f8ae3b27933adb91f971404b640b | [
"self.inputs = inputs\nself.target_attribute_name = target_attribute_name\nself.compression = compression\nself.channel_type = channel_type\nself.content_type = content_type\nself.s3_data_type = s3_data_type\nself.sample_weight_attribute_name = sample_weight_attribute_name",
"auto_ml_input = []\nif isinstance(sel... | <|body_start_0|>
self.inputs = inputs
self.target_attribute_name = target_attribute_name
self.compression = compression
self.channel_type = channel_type
self.content_type = content_type
self.s3_data_type = s3_data_type
self.sample_weight_attribute_name = sample_we... | Accepts parameters that specify an S3 input for an auto ml job Provides a method to turn those parameters into a dictionary. | AutoMLInput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoMLInput:
"""Accepts parameters that specify an S3 input for an auto ml job Provides a method to turn those parameters into a dictionary."""
def __init__(self, inputs, target_attribute_name, compression=None, channel_type=None, content_type=None, s3_data_type=None, sample_weight_attribute... | stack_v2_sparse_classes_75kplus_train_069168 | 48,374 | permissive | [
{
"docstring": "Convert an S3 Uri or a list of S3 Uri to an AutoMLInput object. Args: inputs (str, list[str], PipelineVariable): a string or a list of string or a PipelineVariable that points to (a) S3 location(s) where input data is stored. target_attribute_name (str, PipelineVariable): the target attribute na... | 2 | null | Implement the Python class `AutoMLInput` described below.
Class description:
Accepts parameters that specify an S3 input for an auto ml job Provides a method to turn those parameters into a dictionary.
Method signatures and docstrings:
- def __init__(self, inputs, target_attribute_name, compression=None, channel_type... | Implement the Python class `AutoMLInput` described below.
Class description:
Accepts parameters that specify an S3 input for an auto ml job Provides a method to turn those parameters into a dictionary.
Method signatures and docstrings:
- def __init__(self, inputs, target_attribute_name, compression=None, channel_type... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class AutoMLInput:
"""Accepts parameters that specify an S3 input for an auto ml job Provides a method to turn those parameters into a dictionary."""
def __init__(self, inputs, target_attribute_name, compression=None, channel_type=None, content_type=None, s3_data_type=None, sample_weight_attribute... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AutoMLInput:
"""Accepts parameters that specify an S3 input for an auto ml job Provides a method to turn those parameters into a dictionary."""
def __init__(self, inputs, target_attribute_name, compression=None, channel_type=None, content_type=None, s3_data_type=None, sample_weight_attribute_name=None):
... | the_stack_v2_python_sparse | src/sagemaker/automl/automl.py | aws/sagemaker-python-sdk | train | 2,050 |
8fc206fc9eeae79ce01009dc624a6fe55d8ab0c8 | [
"self.X = X_init\nself.Y = Y_init\nself.l = l\nself.sigma_f = sigma_f\nself.K = self.kernel(self.X, self.X)",
"dist = np.sum(X1 ** 2, 1).reshape(-1, 1) + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)\nK = self.sigma_f ** 2 * np.exp(-dist / (2 * self.l ** 2))\nreturn K",
"k = self.kernel(self.X, self.X)\nk_inv = np.... | <|body_start_0|>
self.X = X_init
self.Y = Y_init
self.l = l
self.sigma_f = sigma_f
self.K = self.kernel(self.X, self.X)
<|end_body_0|>
<|body_start_1|>
dist = np.sum(X1 ** 2, 1).reshape(-1, 1) + np.sum(X2 ** 2, 1) - 2 * np.dot(X1, X2.T)
K = self.sigma_f ** 2 * np... | Represents a noiseless 1D Gaussian process | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor @X_init: np.ndarray shape(t, 1) inputs already sampled with the black-box funtion @Y_init: np.ndarray shape(t, 1) outputs of the black-box functi... | stack_v2_sparse_classes_75kplus_train_069169 | 2,914 | no_license | [
{
"docstring": "Class constructor @X_init: np.ndarray shape(t, 1) inputs already sampled with the black-box funtion @Y_init: np.ndarray shape(t, 1) outputs of the black-box function for each input in X_init @t: number of initial samples @l: length parameter for the kernel @sigma_f: standard deviation given to t... | 4 | stack_v2_sparse_classes_30k_train_002464 | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor @X_init: np.ndarray shape(t, 1) inputs already sampled with the black-box funtion @Y_ini... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process
Method signatures and docstrings:
- def __init__(self, X_init, Y_init, l=1, sigma_f=1): Class constructor @X_init: np.ndarray shape(t, 1) inputs already sampled with the black-box funtion @Y_ini... | e20b284d5f1841952104d7d9a0274cff80eb304d | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor @X_init: np.ndarray shape(t, 1) inputs already sampled with the black-box funtion @Y_init: np.ndarray shape(t, 1) outputs of the black-box functi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process"""
def __init__(self, X_init, Y_init, l=1, sigma_f=1):
"""Class constructor @X_init: np.ndarray shape(t, 1) inputs already sampled with the black-box funtion @Y_init: np.ndarray shape(t, 1) outputs of the black-box function for each i... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/2-gp.py | jgadelugo/holbertonschool-machine_learning | train | 1 |
63bbe8f7d77741dfc788f3417aa42f93ac6222d0 | [
"super(PanopticClassMapper, self).__init__(nusc)\nself.things = self.get_things()\nself.stuff = self.get_stuff()",
"stuff_names = {'driveable_surface', 'other_flat', 'sidewalk', 'terrain', 'manmade', 'vegetation'}\ncoarse_name_to_id = self.get_coarse2idx()\nassert stuff_names <= set(coarse_name_to_id.keys()), 'In... | <|body_start_0|>
super(PanopticClassMapper, self).__init__(nusc)
self.things = self.get_things()
self.stuff = self.get_stuff()
<|end_body_0|>
<|body_start_1|>
stuff_names = {'driveable_surface', 'other_flat', 'sidewalk', 'terrain', 'manmade', 'vegetation'}
coarse_name_to_id = se... | Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_) | PanopticClassMapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PanopticClassMapper:
"""Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)"""
def __init__(self, nusc: N... | stack_v2_sparse_classes_75kplus_train_069170 | 2,913 | permissive | [
{
"docstring": "Initialize a PanopticClassMapper object. :param nusc: A NuScenes object.",
"name": "__init__",
"signature": "def __init__(self, nusc: NuScenes)"
},
{
"docstring": "Returns the mapping from the challenge (coarse) class names to the challenge class indices for stuff. :return: A dic... | 3 | stack_v2_sparse_classes_30k_train_010188 | Implement the Python class `PanopticClassMapper` described below.
Class description:
Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nu... | Implement the Python class `PanopticClassMapper` described below.
Class description:
Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nu... | a5c089133baa001d3ab3c5583a103957e4ae8375 | <|skeleton|>
class PanopticClassMapper:
"""Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)"""
def __init__(self, nusc: N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PanopticClassMapper:
"""Maps the general (fine) classes to the challenge (coarse) classes in the Panoptic nuScenes challenge. Example usage:: nusc_ = NuScenes(version='v1.0-mini', dataroot='/data/sets/nuscenes', verbose=True) mapper_ = PanopticClassMapper(nusc_)"""
def __init__(self, nusc: NuScenes):
... | the_stack_v2_python_sparse | python-sdk/nuscenes/eval/panoptic/utils.py | nutonomy/nuscenes-devkit | train | 1,945 |
2dc784993669e5e4178f6ddf5b3188731b4f8ee3 | [
"self.image = pygame.image.load('resources/TurnCoordinatorAircraft.png').convert()\nself.frameImage = pygame.image.load('resources/TurnCoordinator_Background.png').convert()\nself.marks = pygame.image.load('resources/TurnCoordinatorMarks.png').convert()\nself.ball = pygame.image.load('resources/TurnCoordinatorBall.... | <|body_start_0|>
self.image = pygame.image.load('resources/TurnCoordinatorAircraft.png').convert()
self.frameImage = pygame.image.load('resources/TurnCoordinator_Background.png').convert()
self.marks = pygame.image.load('resources/TurnCoordinatorMarks.png').convert()
self.ball = pygame.i... | Turn Coordinator dial. | TurnCoord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TurnCoord:
"""Turn Coordinator dial."""
def __init__(self, x=0, y=0, w=0, h=0):
"""Initialise dial at x,y. Default size of 300px can be overidden using w,h."""
<|body_0|>
def update(self, screen, angleX, angleY):
"""Called to update a Turn Coordinator dial. "angl... | stack_v2_sparse_classes_75kplus_train_069171 | 18,287 | no_license | [
{
"docstring": "Initialise dial at x,y. Default size of 300px can be overidden using w,h.",
"name": "__init__",
"signature": "def __init__(self, x=0, y=0, w=0, h=0)"
},
{
"docstring": "Called to update a Turn Coordinator dial. \"angleX\" and \"angleY\" are the inputs. \"screen\" is the surface t... | 2 | stack_v2_sparse_classes_30k_train_014643 | Implement the Python class `TurnCoord` described below.
Class description:
Turn Coordinator dial.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, w=0, h=0): Initialise dial at x,y. Default size of 300px can be overidden using w,h.
- def update(self, screen, angleX, angleY): Called to update a Turn Co... | Implement the Python class `TurnCoord` described below.
Class description:
Turn Coordinator dial.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, w=0, h=0): Initialise dial at x,y. Default size of 300px can be overidden using w,h.
- def update(self, screen, angleX, angleY): Called to update a Turn Co... | 60520a770d935e5dc40cc92940e01c378b2df610 | <|skeleton|>
class TurnCoord:
"""Turn Coordinator dial."""
def __init__(self, x=0, y=0, w=0, h=0):
"""Initialise dial at x,y. Default size of 300px can be overidden using w,h."""
<|body_0|>
def update(self, screen, angleX, angleY):
"""Called to update a Turn Coordinator dial. "angl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TurnCoord:
"""Turn Coordinator dial."""
def __init__(self, x=0, y=0, w=0, h=0):
"""Initialise dial at x,y. Default size of 300px can be overidden using w,h."""
self.image = pygame.image.load('resources/TurnCoordinatorAircraft.png').convert()
self.frameImage = pygame.image.load('re... | the_stack_v2_python_sparse | code/python/dials.py | MarkAhlbrecht/DasBoot | train | 2 |
b776d785af58ad2396163f60decc67de683b300b | [
"if self._python_type == decimal.Decimal and isinstance(value, (decimal.Decimal,)):\n return str(value)\nelse:\n raise exceptions.pyOrmEngineAdapterError(\"InternalError : Unexpected value {} rec'd in Decimal adapter\".format(value.__class__.__name__))",
"if self._python_type == decimal.Decimal:\n return... | <|body_start_0|>
if self._python_type == decimal.Decimal and isinstance(value, (decimal.Decimal,)):
return str(value)
else:
raise exceptions.pyOrmEngineAdapterError("InternalError : Unexpected value {} rec'd in Decimal adapter".format(value.__class__.__name__))
<|end_body_0|>
<|... | Adapter for the decimal db_type Decimals are stored as strings in the database | DecimalAdapter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecimalAdapter:
"""Adapter for the decimal db_type Decimals are stored as strings in the database"""
def adapt(self, value):
"""Convert the value to the representation to be stored into the database"""
<|body_0|>
def convert(self, data):
"""Convert the bytes valu... | stack_v2_sparse_classes_75kplus_train_069172 | 11,033 | permissive | [
{
"docstring": "Convert the value to the representation to be stored into the database",
"name": "adapt",
"signature": "def adapt(self, value)"
},
{
"docstring": "Convert the bytes value from the database to the relevant python type",
"name": "convert",
"signature": "def convert(self, da... | 2 | stack_v2_sparse_classes_30k_val_000916 | Implement the Python class `DecimalAdapter` described below.
Class description:
Adapter for the decimal db_type Decimals are stored as strings in the database
Method signatures and docstrings:
- def adapt(self, value): Convert the value to the representation to be stored into the database
- def convert(self, data): C... | Implement the Python class `DecimalAdapter` described below.
Class description:
Adapter for the decimal db_type Decimals are stored as strings in the database
Method signatures and docstrings:
- def adapt(self, value): Convert the value to the representation to be stored into the database
- def convert(self, data): C... | 6d811fa32d3ba4c4a013fbb8f627277fa9d20b64 | <|skeleton|>
class DecimalAdapter:
"""Adapter for the decimal db_type Decimals are stored as strings in the database"""
def adapt(self, value):
"""Convert the value to the representation to be stored into the database"""
<|body_0|>
def convert(self, data):
"""Convert the bytes valu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecimalAdapter:
"""Adapter for the decimal db_type Decimals are stored as strings in the database"""
def adapt(self, value):
"""Convert the value to the representation to be stored into the database"""
if self._python_type == decimal.Decimal and isinstance(value, (decimal.Decimal,)):
... | the_stack_v2_python_sparse | pyorm/db/engine/sqlite.py | TonyFlury/pyorm | train | 0 |
a4e7c18c934dd008a98f26af20a3872652372edf | [
"super().__init__()\nself.embed, self.encoders, self.enc_out = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwise_layer_type, positionwise_activation_type=positionwise_... | <|body_start_0|>
super().__init__()
self.embed, self.encoders, self.enc_out = build_blocks('encoder', idim, input_layer, enc_arch, repeat_block=repeat_block, self_attn_type=self_attn_type, positional_encoding_type=positional_encoding_type, positionwise_layer_type=positionwise_layer_type, positionwise_ac... | Transformer encoder module. Args: idim (int): input dim enc_arch (list): list of encoder blocks (type and parameters) input_layer (str): input layer type repeat_block (int): repeat provided block N times if N > 1 self_attn_type (str): type of self-attention positional_encoding_type (str): positional encoding type posit... | Encoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Transformer encoder module. Args: idim (int): input dim enc_arch (list): list of encoder blocks (type and parameters) input_layer (str): input layer type repeat_block (int): repeat provided block N times if N > 1 self_attn_type (str): type of self-attention positional_encoding_type (s... | stack_v2_sparse_classes_75kplus_train_069173 | 2,962 | permissive | [
{
"docstring": "Construct an Transformer encoder object.",
"name": "__init__",
"signature": "def __init__(self, idim, enc_arch, input_layer='linear', repeat_block=0, self_attn_type='selfattn', positional_encoding_type='abs_pos', positionwise_layer_type='linear', positionwise_activation_type='relu', conv... | 2 | stack_v2_sparse_classes_30k_train_010302 | Implement the Python class `Encoder` described below.
Class description:
Transformer encoder module. Args: idim (int): input dim enc_arch (list): list of encoder blocks (type and parameters) input_layer (str): input layer type repeat_block (int): repeat provided block N times if N > 1 self_attn_type (str): type of sel... | Implement the Python class `Encoder` described below.
Class description:
Transformer encoder module. Args: idim (int): input dim enc_arch (list): list of encoder blocks (type and parameters) input_layer (str): input layer type repeat_block (int): repeat provided block N times if N > 1 self_attn_type (str): type of sel... | 6ecde88045e1b706b2390f98eb1950ce4075a07d | <|skeleton|>
class Encoder:
"""Transformer encoder module. Args: idim (int): input dim enc_arch (list): list of encoder blocks (type and parameters) input_layer (str): input layer type repeat_block (int): repeat provided block N times if N > 1 self_attn_type (str): type of self-attention positional_encoding_type (s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""Transformer encoder module. Args: idim (int): input dim enc_arch (list): list of encoder blocks (type and parameters) input_layer (str): input layer type repeat_block (int): repeat provided block N times if N > 1 self_attn_type (str): type of self-attention positional_encoding_type (str): position... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/transformer_encoder.py | sw005320/espnet-1 | train | 4 |
5128d21897591fcb97daa2913be1c0a109d8c41e | [
"res = super(ProductConfigSession, self).get_session_search_domain(product_tmpl_id=product_tmpl_id, state=state, parent_id=parent_id)\nif 'website_id' in self._context:\n public_user_id = request.env.ref('base.public_user').id\n res.append(('website', '=', True))\n if request.env.uid == public_user_id:\n ... | <|body_start_0|>
res = super(ProductConfigSession, self).get_session_search_domain(product_tmpl_id=product_tmpl_id, state=state, parent_id=parent_id)
if 'website_id' in self._context:
public_user_id = request.env.ref('base.public_user').id
res.append(('website', '=', True))
... | ProductConfigSession | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductConfigSession:
def get_session_search_domain(self, product_tmpl_id, state='draft', parent_id=None):
"""Add website relevant arguments to the standard search domain"""
<|body_0|>
def get_session_vals(self, product_tmpl_id, parent_id=None):
"""Add website releva... | stack_v2_sparse_classes_75kplus_train_069174 | 2,409 | no_license | [
{
"docstring": "Add website relevant arguments to the standard search domain",
"name": "get_session_search_domain",
"signature": "def get_session_search_domain(self, product_tmpl_id, state='draft', parent_id=None)"
},
{
"docstring": "Add website relevant arguments to the session create values",
... | 2 | stack_v2_sparse_classes_30k_train_017067 | Implement the Python class `ProductConfigSession` described below.
Class description:
Implement the ProductConfigSession class.
Method signatures and docstrings:
- def get_session_search_domain(self, product_tmpl_id, state='draft', parent_id=None): Add website relevant arguments to the standard search domain
- def ge... | Implement the Python class `ProductConfigSession` described below.
Class description:
Implement the ProductConfigSession class.
Method signatures and docstrings:
- def get_session_search_domain(self, product_tmpl_id, state='draft', parent_id=None): Add website relevant arguments to the standard search domain
- def ge... | 5a235827896e6d7bff420f85228d7609715a2efb | <|skeleton|>
class ProductConfigSession:
def get_session_search_domain(self, product_tmpl_id, state='draft', parent_id=None):
"""Add website relevant arguments to the standard search domain"""
<|body_0|>
def get_session_vals(self, product_tmpl_id, parent_id=None):
"""Add website releva... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductConfigSession:
def get_session_search_domain(self, product_tmpl_id, state='draft', parent_id=None):
"""Add website relevant arguments to the standard search domain"""
res = super(ProductConfigSession, self).get_session_search_domain(product_tmpl_id=product_tmpl_id, state=state, parent_i... | the_stack_v2_python_sparse | website_product_configurator/models/product_config.py | AULODE/somafish_2019 | train | 1 | |
399cf3f219844e13954e6be8f5e8d3d2d2e9b6a1 | [
"self.io_q = Queue()\nself.process = None\nself.streamieolog = LogIt().default(logname='%s - streamieo' % logname, logfile=None)",
"self.process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, encoding='utf-8')\nself.io_q.put(('STDIN', cmd))\nThread(target=self._stream_watcher, name='stdout-watcher', args=('ST... | <|body_start_0|>
self.io_q = Queue()
self.process = None
self.streamieolog = LogIt().default(logname='%s - streamieo' % logname, logfile=None)
<|end_body_0|>
<|body_start_1|>
self.process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True, encoding='utf-8')
self.io_q.put(('STDIN'... | Stream stdout or stderr of a command to the shell. | StreamIEO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamIEO:
"""Stream stdout or stderr of a command to the shell."""
def __init__(self, logname):
"""A class that individually threads the capture of the stdout stream and the stderr stream of a system command. The stdout/stderr are queued in the order they occur. As the queue populat... | stack_v2_sparse_classes_75kplus_train_069175 | 3,079 | permissive | [
{
"docstring": "A class that individually threads the capture of the stdout stream and the stderr stream of a system command. The stdout/stderr are queued in the order they occur. As the queue populates another thread, parse the que and prints to the screen using the LogIT class. :param logname: The name of you... | 4 | null | Implement the Python class `StreamIEO` described below.
Class description:
Stream stdout or stderr of a command to the shell.
Method signatures and docstrings:
- def __init__(self, logname): A class that individually threads the capture of the stdout stream and the stderr stream of a system command. The stdout/stderr... | Implement the Python class `StreamIEO` described below.
Class description:
Stream stdout or stderr of a command to the shell.
Method signatures and docstrings:
- def __init__(self, logname): A class that individually threads the capture of the stdout stream and the stderr stream of a system command. The stdout/stderr... | 5b39aa22fe9897322014a7fdad4f25bbceec5fcb | <|skeleton|>
class StreamIEO:
"""Stream stdout or stderr of a command to the shell."""
def __init__(self, logname):
"""A class that individually threads the capture of the stdout stream and the stderr stream of a system command. The stdout/stderr are queued in the order they occur. As the queue populat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamIEO:
"""Stream stdout or stderr of a command to the shell."""
def __init__(self, logname):
"""A class that individually threads the capture of the stdout stream and the stderr stream of a system command. The stdout/stderr are queued in the order they occur. As the queue populates another th... | the_stack_v2_python_sparse | OrthoEvol/Tools/streamieo/streamieo.py | But-I-Play-One-On-TV/OrthoEvolution | train | 0 |
02371dc25138fe118ea617a67b428dc90db544d2 | [
"output, stack = ([], [(root, False)])\nwhile stack:\n node, is_visited = stack.pop()\n if not node:\n continue\n if is_visited:\n output.append(node.val)\n else:\n stack.append((node.right, False))\n stack.append((node.left, False))\n stack.append((node, True))\nretur... | <|body_start_0|>
output, stack = ([], [(root, False)])
while stack:
node, is_visited = stack.pop()
if not node:
continue
if is_visited:
output.append(node.val)
else:
stack.append((node.right, False))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal_iterative2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def preorderTraversal_recursive(self, root):
... | stack_v2_sparse_classes_75kplus_train_069176 | 3,212 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal",
"signature": "def preorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "preorderTraversal_iterative2",
"signature": "def preorderTraversal_iterative2(self, ... | 4 | stack_v2_sparse_classes_30k_train_016429 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal_iterative2(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTra... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTraversal_iterative2(self, root): :type root: TreeNode :rtype: List[int]
- def preorderTra... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def preorderTraversal_iterative2(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
def preorderTraversal_recursive(self, root):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def preorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
output, stack = ([], [(root, False)])
while stack:
node, is_visited = stack.pop()
if not node:
continue
if is_visited:
output.ap... | the_stack_v2_python_sparse | src/lt_144.py | oxhead/CodingYourWay | train | 0 | |
8fed59678ddeabe8b7060bdccc4745817cd442ab | [
"if random_seed is not None:\n self.random_generator = random.Random(random_seed)\nelse:\n self.random_generator = random.Random()\nsuper().__init__(expression_data=expression_data, calculator=calculator, rm_outliers=rm_outliers)",
"n_genes = self.expression_data.n_points\npairs = self.get_random_pairs(n_pa... | <|body_start_0|>
if random_seed is not None:
self.random_generator = random.Random(random_seed)
else:
self.random_generator = random.Random()
super().__init__(expression_data=expression_data, calculator=calculator, rm_outliers=rm_outliers)
<|end_body_0|>
<|body_start_1|>... | Navigate similarity calculation between random points. | RandomSimilarityCalculatorNavigator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomSimilarityCalculatorNavigator:
"""Navigate similarity calculation between random points."""
def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, random_seed: int=None, rm_outliers: bool=True):
""":param expression_data: Data for all genes :param... | stack_v2_sparse_classes_75kplus_train_069177 | 43,977 | no_license | [
{
"docstring": ":param expression_data: Data for all genes :param calculator: SimilarityCalculator used for all calculations :param random_seed: seed to be used for random number generator, used to determine which pairs will be used for distance calculations None sets the default random library seed :param rm_o... | 4 | stack_v2_sparse_classes_30k_train_040295 | Implement the Python class `RandomSimilarityCalculatorNavigator` described below.
Class description:
Navigate similarity calculation between random points.
Method signatures and docstrings:
- def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, random_seed: int=None, rm_outliers: bool... | Implement the Python class `RandomSimilarityCalculatorNavigator` described below.
Class description:
Navigate similarity calculation between random points.
Method signatures and docstrings:
- def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, random_seed: int=None, rm_outliers: bool... | 6d11df5e8ca37e53e048d261ac287f859ba6e9b9 | <|skeleton|>
class RandomSimilarityCalculatorNavigator:
"""Navigate similarity calculation between random points."""
def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, random_seed: int=None, rm_outliers: bool=True):
""":param expression_data: Data for all genes :param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomSimilarityCalculatorNavigator:
"""Navigate similarity calculation between random points."""
def __init__(self, expression_data: GeneExpression, calculator: SimilarityCalculator, random_seed: int=None, rm_outliers: bool=True):
""":param expression_data: Data for all genes :param calculator: ... | the_stack_v2_python_sparse | correlation_enrichment/library_correlation_enrichment.py | biolab/baylor-dicty | train | 0 |
11905d7ea6dd82aae43feca2811db862ab980437 | [
"super().__init__(name=name)\nself.input_keys = input_keys\nself.output_splits = output_splits\nmomentum = 0.5\nself.bins_per_oct = bins_per_oct\nself.activation = activation\nself.batchnorm_1 = BatchNormalization(momentum=momentum)\nself.batchnorm_2 = BatchNormalization(momentum=momentum)\nself.batchnorm_3 = Batch... | <|body_start_0|>
super().__init__(name=name)
self.input_keys = input_keys
self.output_splits = output_splits
momentum = 0.5
self.bins_per_oct = bins_per_oct
self.activation = activation
self.batchnorm_1 = BatchNormalization(momentum=momentum)
self.batchnor... | Predicts shapes of drum theta from scattering transform. | wav2shapeEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wav2shapeEncoder:
"""Predicts shapes of drum theta from scattering transform."""
def __init__(self, bins_per_oct, activation, lr, input_keys='feat', output_splits=('y_predicted', 5), name='wav2shape_encoder'):
"""Constructor."""
<|body_0|>
def call(self, feat) -> ['y_pre... | stack_v2_sparse_classes_75kplus_train_069178 | 4,443 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, bins_per_oct, activation, lr, input_keys='feat', output_splits=('y_predicted', 5), name='wav2shape_encoder')"
},
{
"docstring": "Converts features to (w11,tau11,p,D,alpha). Args: cqt features Returns: physical pa... | 2 | stack_v2_sparse_classes_30k_train_029697 | Implement the Python class `wav2shapeEncoder` described below.
Class description:
Predicts shapes of drum theta from scattering transform.
Method signatures and docstrings:
- def __init__(self, bins_per_oct, activation, lr, input_keys='feat', output_splits=('y_predicted', 5), name='wav2shape_encoder'): Constructor.
-... | Implement the Python class `wav2shapeEncoder` described below.
Class description:
Predicts shapes of drum theta from scattering transform.
Method signatures and docstrings:
- def __init__(self, bins_per_oct, activation, lr, input_keys='feat', output_splits=('y_predicted', 5), name='wav2shape_encoder'): Constructor.
-... | 80d93a54e49ecb0855b441af15661ae091358031 | <|skeleton|>
class wav2shapeEncoder:
"""Predicts shapes of drum theta from scattering transform."""
def __init__(self, bins_per_oct, activation, lr, input_keys='feat', output_splits=('y_predicted', 5), name='wav2shape_encoder'):
"""Constructor."""
<|body_0|>
def call(self, feat) -> ['y_pre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class wav2shapeEncoder:
"""Predicts shapes of drum theta from scattering transform."""
def __init__(self, bins_per_oct, activation, lr, input_keys='feat', output_splits=('y_predicted', 5), name='wav2shape_encoder'):
"""Constructor."""
super().__init__(name=name)
self.input_keys = input_... | the_stack_v2_python_sparse | src/ddsp/encoder.py | lylyhan/wave2shape | train | 5 |
8d9f3a02c27515ccbadf492fef34f614bb9fb234 | [
"any_ones = 0\nall_ones = FULL_MASK\nall_selected = FULL_MASK\nself.defaultable = True\nfor i in entries:\n entry = routing_table[i]\n any_ones |= entry.key\n all_ones &= entry.key\n all_selected &= entry.mask\n self.defaultable = self.defaultable and entry.defaultable\nany_zeros = ~all_ones\nnew_xs ... | <|body_start_0|>
any_ones = 0
all_ones = FULL_MASK
all_selected = FULL_MASK
self.defaultable = True
for i in entries:
entry = routing_table[i]
any_ones |= entry.key
all_ones &= entry.key
all_selected &= entry.mask
self.d... | Represents a potential merge of routing table entries. | _Merge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Merge:
"""Represents a potential merge of routing table entries."""
def __init__(self, routing_table, entries=tuple()):
""":param list(RoutingTableEntry) routing_table: :param set(int) entries:"""
<|body_0|>
def apply(self, aliases):
"""Apply the merge to the ro... | stack_v2_sparse_classes_75kplus_train_069179 | 29,821 | permissive | [
{
"docstring": ":param list(RoutingTableEntry) routing_table: :param set(int) entries:",
"name": "__init__",
"signature": "def __init__(self, routing_table, entries=tuple())"
},
{
"docstring": "Apply the merge to the routing table it is defined against and get a new routing table and alias dicti... | 2 | stack_v2_sparse_classes_30k_train_018659 | Implement the Python class `_Merge` described below.
Class description:
Represents a potential merge of routing table entries.
Method signatures and docstrings:
- def __init__(self, routing_table, entries=tuple()): :param list(RoutingTableEntry) routing_table: :param set(int) entries:
- def apply(self, aliases): Appl... | Implement the Python class `_Merge` described below.
Class description:
Represents a potential merge of routing table entries.
Method signatures and docstrings:
- def __init__(self, routing_table, entries=tuple()): :param list(RoutingTableEntry) routing_table: :param set(int) entries:
- def apply(self, aliases): Appl... | c6207b4619bd45c91c25a17f55ddda4dcb1da4bc | <|skeleton|>
class _Merge:
"""Represents a potential merge of routing table entries."""
def __init__(self, routing_table, entries=tuple()):
""":param list(RoutingTableEntry) routing_table: :param set(int) entries:"""
<|body_0|>
def apply(self, aliases):
"""Apply the merge to the ro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Merge:
"""Represents a potential merge of routing table entries."""
def __init__(self, routing_table, entries=tuple()):
""":param list(RoutingTableEntry) routing_table: :param set(int) entries:"""
any_ones = 0
all_ones = FULL_MASK
all_selected = FULL_MASK
self.def... | the_stack_v2_python_sparse | pacman/operations/router_compressors/ordered_covering_router_compressor/ordered_covering.py | SpiNNakerManchester/PACMAN | train | 11 |
6ddb590d6c32cc58ea32f739a7ad4a9b3ebc772c | [
"try:\n likers = self.db.query(PostLike.author_id).filter(PostLike.post_id == post_id).filter(PostLike.recall == False).all()\n if not likers:\n self.set_status(404)\n self.finish()\n return\n likers = [l[0] for l in likers]\n for_export = {}\n for_export['post_likes'] = {post_id... | <|body_start_0|>
try:
likers = self.db.query(PostLike.author_id).filter(PostLike.post_id == post_id).filter(PostLike.recall == False).all()
if not likers:
self.set_status(404)
self.finish()
return
likers = [l[0] for l in likers]... | API_PostLike | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class API_PostLike:
def get(self, post_id):
"""get array of user's id who did like the post example: GET /post_like/post_id returns array with user's id"""
<|body_0|>
def post(self, post_id):
"""add like to a post example: POST /post_like/post_id returns: 200 - the comment... | stack_v2_sparse_classes_75kplus_train_069180 | 6,879 | no_license | [
{
"docstring": "get array of user's id who did like the post example: GET /post_like/post_id returns array with user's id",
"name": "get",
"signature": "def get(self, post_id)"
},
{
"docstring": "add like to a post example: POST /post_like/post_id returns: 200 - the comment created 406 - incorre... | 3 | stack_v2_sparse_classes_30k_train_016870 | Implement the Python class `API_PostLike` described below.
Class description:
Implement the API_PostLike class.
Method signatures and docstrings:
- def get(self, post_id): get array of user's id who did like the post example: GET /post_like/post_id returns array with user's id
- def post(self, post_id): add like to a... | Implement the Python class `API_PostLike` described below.
Class description:
Implement the API_PostLike class.
Method signatures and docstrings:
- def get(self, post_id): get array of user's id who did like the post example: GET /post_like/post_id returns array with user's id
- def post(self, post_id): add like to a... | 0eab54eb283e7434734b9fbeabd7d3ba249772af | <|skeleton|>
class API_PostLike:
def get(self, post_id):
"""get array of user's id who did like the post example: GET /post_like/post_id returns array with user's id"""
<|body_0|>
def post(self, post_id):
"""add like to a post example: POST /post_like/post_id returns: 200 - the comment... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class API_PostLike:
def get(self, post_id):
"""get array of user's id who did like the post example: GET /post_like/post_id returns array with user's id"""
try:
likers = self.db.query(PostLike.author_id).filter(PostLike.post_id == post_id).filter(PostLike.recall == False).all()
... | the_stack_v2_python_sparse | backend/main_app/api_v1/post_like.py | zzzevaka/findchat | train | 0 | |
44619a16965598eaa195f3a2beb0e89c1c00f5d2 | [
"habr_parser = HabrParser()\ntry:\n user_info = habr_parser.get_user_info(tag)\nexcept AttributeError as a:\n logger.info(f'Видимо DOM у habr изменился, либо надо проверить ссылку. {a}')\n raise\nreturn user_info",
"medium_parser = MediumParcer()\ntry:\n user_info = medium_parser.get_user_info(tag)\ne... | <|body_start_0|>
habr_parser = HabrParser()
try:
user_info = habr_parser.get_user_info(tag)
except AttributeError as a:
logger.info(f'Видимо DOM у habr изменился, либо надо проверить ссылку. {a}')
raise
return user_info
<|end_body_0|>
<|body_start_1|>... | PapersParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PapersParser:
def get_habr_user_info(self, tag):
"""Получить информацию о пользователе с хабра :param tag: url или ник пользователя на Хабре :return: словарь с параметрами и постами"""
<|body_0|>
def get_medium_user_info(self, tag):
"""Получить информацию о пользоват... | stack_v2_sparse_classes_75kplus_train_069181 | 3,434 | no_license | [
{
"docstring": "Получить информацию о пользователе с хабра :param tag: url или ник пользователя на Хабре :return: словарь с параметрами и постами",
"name": "get_habr_user_info",
"signature": "def get_habr_user_info(self, tag)"
},
{
"docstring": "Получить информацию о пользователе с medium :param... | 4 | stack_v2_sparse_classes_30k_train_029144 | Implement the Python class `PapersParser` described below.
Class description:
Implement the PapersParser class.
Method signatures and docstrings:
- def get_habr_user_info(self, tag): Получить информацию о пользователе с хабра :param tag: url или ник пользователя на Хабре :return: словарь с параметрами и постами
- def... | Implement the Python class `PapersParser` described below.
Class description:
Implement the PapersParser class.
Method signatures and docstrings:
- def get_habr_user_info(self, tag): Получить информацию о пользователе с хабра :param tag: url или ник пользователя на Хабре :return: словарь с параметрами и постами
- def... | 5109e7456d33cf1c15b0b6cce5e6d26f5a47e7b4 | <|skeleton|>
class PapersParser:
def get_habr_user_info(self, tag):
"""Получить информацию о пользователе с хабра :param tag: url или ник пользователя на Хабре :return: словарь с параметрами и постами"""
<|body_0|>
def get_medium_user_info(self, tag):
"""Получить информацию о пользоват... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PapersParser:
def get_habr_user_info(self, tag):
"""Получить информацию о пользователе с хабра :param tag: url или ник пользователя на Хабре :return: словарь с параметрами и постами"""
habr_parser = HabrParser()
try:
user_info = habr_parser.get_user_info(tag)
except... | the_stack_v2_python_sparse | parsers/papers_parser.py | TimurSamigulin/scientist_info | train | 0 | |
700d7b3df1a5f97a4598fdb8caf9d8e18b5e0c5e | [
"self.pb = ProgressBar(**kwargs)\nself.pool = pool\nself.update_interval = update_interval",
"task = self.pool._cache[job._job]\nn_tasks = task._number_left * task._chunksize\nself.pb.end_value = n_tasks\nself.pb.start()\nwhile task._number_left > 0:\n self.pb.progress(n_tasks - task._number_left * task._chunk... | <|body_start_0|>
self.pb = ProgressBar(**kwargs)
self.pool = pool
self.update_interval = update_interval
<|end_body_0|>
<|body_start_1|>
task = self.pool._cache[job._job]
n_tasks = task._number_left * task._chunksize
self.pb.end_value = n_tasks
self.pb.start()
... | PoolProgress | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PoolProgress:
def __init__(self, pool, update_interval=3, **kwargs):
"""Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaul... | stack_v2_sparse_classes_75kplus_train_069182 | 4,267 | permissive | [
{
"docstring": "Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaults to 3. Interval in seconds",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_015544 | Implement the Python class `PoolProgress` described below.
Class description:
Implement the PoolProgress class.
Method signatures and docstrings:
- def __init__(self, pool, update_interval=3, **kwargs): Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of... | Implement the Python class `PoolProgress` described below.
Class description:
Implement the PoolProgress class.
Method signatures and docstrings:
- def __init__(self, pool, update_interval=3, **kwargs): Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of... | 30d37a8dd0fca0a7d9a1ed0553b2a3346dfc53e3 | <|skeleton|>
class PoolProgress:
def __init__(self, pool, update_interval=3, **kwargs):
"""Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaul... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PoolProgress:
def __init__(self, pool, update_interval=3, **kwargs):
"""Monitors progress of jobs on a python `multiprocessing` parallel pool. Args: pool (multiprocessing.Pool): A pool of workers **kwargs (dict): Additional arguments to ProgressBar update_interval (int, optional): Defaults to 3. Inter... | the_stack_v2_python_sparse | utils/progress.py | JakobHavtorn/nn | train | 1 | |
0ec9b615bcb7d1ec2f76f065e00fab27da08e0ae | [
"result = super().get_lookup_regex(viewset, lookup_prefix)\nlookup_fields = getattr(viewset, 'lookup_fields', None)\nif lookup_fields and (not self.multi):\n lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+')\n for lookup_field in lookup_fields[1:]:\n result += f'/(?P<{lookup_field}>{looku... | <|body_start_0|>
result = super().get_lookup_regex(viewset, lookup_prefix)
lookup_fields = getattr(viewset, 'lookup_fields', None)
if lookup_fields and (not self.multi):
lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+')
for lookup_field in lookup_fields[1:]:... | Support multiple lookup keys e.g. /parent_pk/pk | MultiLookupRouter | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLookupRouter:
"""Support multiple lookup keys e.g. /parent_pk/pk"""
def get_lookup_regex(self, viewset, lookup_prefix=''):
"""Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_069183 | 7,050 | permissive | [
{
"docstring": "Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property.",
"name": "get_lookup_regex",
"signature": "def get_lookup_regex(self, viewset, lookup_prefix='')"
},
{
"docstring": "Return a list of URL regexs, th... | 2 | stack_v2_sparse_classes_30k_train_003769 | Implement the Python class `MultiLookupRouter` described below.
Class description:
Support multiple lookup keys e.g. /parent_pk/pk
Method signatures and docstrings:
- def get_lookup_regex(self, viewset, lookup_prefix=''): Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by... | Implement the Python class `MultiLookupRouter` described below.
Class description:
Support multiple lookup keys e.g. /parent_pk/pk
Method signatures and docstrings:
- def get_lookup_regex(self, viewset, lookup_prefix=''): Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class MultiLookupRouter:
"""Support multiple lookup keys e.g. /parent_pk/pk"""
def get_lookup_regex(self, viewset, lookup_prefix=''):
"""Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLookupRouter:
"""Support multiple lookup keys e.g. /parent_pk/pk"""
def get_lookup_regex(self, viewset, lookup_prefix=''):
"""Returns a lookup regex, this extends the default to allow for multiple lookup keys as defined by a viewset.lookup_fields property."""
result = super().get_loo... | the_stack_v2_python_sparse | onadata/apps/api/urls/v1_urls.py | onaio/onadata | train | 177 |
fc3253a8f435fce1e554dd3bc715f9e734215f45 | [
"url = 'https://passport.cnblogs.com/user/signin'\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Accept-Encoding': 'gzip, defla... | <|body_start_0|>
url = 'https://passport.cnblogs.com/user/signin'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Acc... | BlogLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogLogin:
def login(self, user, pwd, reme=True):
"""三个参数:账号: username,密码: psw,记住登录: reme=False"""
<|body_0|>
def test01(self):
"""测试登录:正确账号,正确密码"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
url = 'https://passport.cnblogs.com/user/signin'
... | stack_v2_sparse_classes_75kplus_train_069184 | 2,451 | no_license | [
{
"docstring": "三个参数:账号: username,密码: psw,记住登录: reme=False",
"name": "login",
"signature": "def login(self, user, pwd, reme=True)"
},
{
"docstring": "测试登录:正确账号,正确密码",
"name": "test01",
"signature": "def test01(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039935 | Implement the Python class `BlogLogin` described below.
Class description:
Implement the BlogLogin class.
Method signatures and docstrings:
- def login(self, user, pwd, reme=True): 三个参数:账号: username,密码: psw,记住登录: reme=False
- def test01(self): 测试登录:正确账号,正确密码 | Implement the Python class `BlogLogin` described below.
Class description:
Implement the BlogLogin class.
Method signatures and docstrings:
- def login(self, user, pwd, reme=True): 三个参数:账号: username,密码: psw,记住登录: reme=False
- def test01(self): 测试登录:正确账号,正确密码
<|skeleton|>
class BlogLogin:
def login(self, user, p... | 7e85e9e323d43019d04194ca925e7c6d31ae470d | <|skeleton|>
class BlogLogin:
def login(self, user, pwd, reme=True):
"""三个参数:账号: username,密码: psw,记住登录: reme=False"""
<|body_0|>
def test01(self):
"""测试登录:正确账号,正确密码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BlogLogin:
def login(self, user, pwd, reme=True):
"""三个参数:账号: username,密码: psw,记住登录: reme=False"""
url = 'https://passport.cnblogs.com/user/signin'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', '... | the_stack_v2_python_sparse | jiekou/3-5/unittest_login_blog.py | 674312023/pythontest | train | 0 | |
14388c43e0808f12454f282c0f52bea3563b8e96 | [
"log.info('Setup Section verifyProcessorDetails')\nself.host_serial_handle = classparam['host_serial_handle']\nself.host_serial_handle.connect_to_host_serial()",
"expected_out = classparam['expected_out']\nvalidation_string = classparam['validation_string']\nbootdev = parameter\noptions = 'persistent'\ncmd_out = ... | <|body_start_0|>
log.info('Setup Section verifyProcessorDetails')
self.host_serial_handle = classparam['host_serial_handle']
self.host_serial_handle.connect_to_host_serial()
<|end_body_0|>
<|body_start_1|>
expected_out = classparam['expected_out']
validation_string = classparam[... | Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI | PersistentBootDevice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersistentBootDevice:
"""Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI"""
def setup(self):
"""Test Case Setup"""
<|body_0|>
def test(self, cimc_util_obj, config, parameter):
"""ipmi command to set boot ... | stack_v2_sparse_classes_75kplus_train_069185 | 19,363 | no_license | [
{
"docstring": "Test Case Setup",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "ipmi command to set boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode",
"name": "test",
"signature": "def test(self, cimc_util_obj, config, parameter)"
},
{
"... | 3 | stack_v2_sparse_classes_30k_train_022571 | Implement the Python class `PersistentBootDevice` described below.
Class description:
Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI
Method signatures and docstrings:
- def setup(self): Test Case Setup
- def test(self, cimc_util_obj, config, parameter): ipmi... | Implement the Python class `PersistentBootDevice` described below.
Class description:
Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI
Method signatures and docstrings:
- def setup(self): Test Case Setup
- def test(self, cimc_util_obj, config, parameter): ipmi... | c255e045a4950a0d8868a10012d5ce6e5c6a9c23 | <|skeleton|>
class PersistentBootDevice:
"""Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI"""
def setup(self):
"""Test Case Setup"""
<|body_0|>
def test(self, cimc_util_obj, config, parameter):
"""ipmi command to set boot ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PersistentBootDevice:
"""Configure boot device to boot to bios, pxe, hdd, cdrom, floppy drive options in persistent mode using IPMI"""
def setup(self):
"""Test Case Setup"""
log.info('Setup Section verifyProcessorDetails')
self.host_serial_handle = classparam['host_serial_handle']... | the_stack_v2_python_sparse | ipmi_cmnd_bootorder.py | jrchanda/MyRepo | train | 0 |
941113470896a1e32203d151082431c80f53885c | [
"self.commission_dict = commission_dict\nself.df_columns = ['type', 'date', 'symbol', 'commission']\nself.commission_df = pd.DataFrame(columns=self.df_columns)",
"if self.commission_df.shape[0] == 0:\n return str(self.commission_df.info())\nreturn str(self.commission_df)",
"market = ABuEnv.g_market_target if... | <|body_start_0|>
self.commission_dict = commission_dict
self.df_columns = ['type', 'date', 'symbol', 'commission']
self.commission_df = pd.DataFrame(columns=self.df_columns)
<|end_body_0|>
<|body_start_1|>
if self.commission_df.shape[0] == 0:
return str(self.commission_df.in... | 交易手续费计算,记录,分析类,在AbuCapital中实例化 | AbuCommission | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbuCommission:
"""交易手续费计算,记录,分析类,在AbuCapital中实例化"""
def __init__(self, commission_dict):
""":param commission_dict: 代表用户自定义手续费计算dict对象, key:buy_commission_func, 代表用户自定义买入计算费用方法 key:sell_commission_func,代表用户自定义卖出计算费用方法"""
<|body_0|>
def __str__(self):
"""打印对象显示:如果... | stack_v2_sparse_classes_75kplus_train_069186 | 9,854 | permissive | [
{
"docstring": ":param commission_dict: 代表用户自定义手续费计算dict对象, key:buy_commission_func, 代表用户自定义买入计算费用方法 key:sell_commission_func,代表用户自定义卖出计算费用方法",
"name": "__init__",
"signature": "def __init__(self, commission_dict)"
},
{
"docstring": "打印对象显示:如果有手续费记录,打印记录df,否则打印commission_df.info",
"name": "_... | 5 | stack_v2_sparse_classes_30k_train_044832 | Implement the Python class `AbuCommission` described below.
Class description:
交易手续费计算,记录,分析类,在AbuCapital中实例化
Method signatures and docstrings:
- def __init__(self, commission_dict): :param commission_dict: 代表用户自定义手续费计算dict对象, key:buy_commission_func, 代表用户自定义买入计算费用方法 key:sell_commission_func,代表用户自定义卖出计算费用方法
- def __s... | Implement the Python class `AbuCommission` described below.
Class description:
交易手续费计算,记录,分析类,在AbuCapital中实例化
Method signatures and docstrings:
- def __init__(self, commission_dict): :param commission_dict: 代表用户自定义手续费计算dict对象, key:buy_commission_func, 代表用户自定义买入计算费用方法 key:sell_commission_func,代表用户自定义卖出计算费用方法
- def __s... | 2e5ab17f2d20deb3c68c927f6208ea89db7c639d | <|skeleton|>
class AbuCommission:
"""交易手续费计算,记录,分析类,在AbuCapital中实例化"""
def __init__(self, commission_dict):
""":param commission_dict: 代表用户自定义手续费计算dict对象, key:buy_commission_func, 代表用户自定义买入计算费用方法 key:sell_commission_func,代表用户自定义卖出计算费用方法"""
<|body_0|>
def __str__(self):
"""打印对象显示:如果... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbuCommission:
"""交易手续费计算,记录,分析类,在AbuCapital中实例化"""
def __init__(self, commission_dict):
""":param commission_dict: 代表用户自定义手续费计算dict对象, key:buy_commission_func, 代表用户自定义买入计算费用方法 key:sell_commission_func,代表用户自定义卖出计算费用方法"""
self.commission_dict = commission_dict
self.df_columns = ['t... | the_stack_v2_python_sparse | abupy/TradeBu/ABuCommission.py | luqin/firefly | train | 1 |
d87ed6207cea9e51f7d11e9625baf5148d1c3c33 | [
"self.model = model\nself.lmbda = lmbda\nself.layers = layers",
"for n_m, mo in self.model.named_modules():\n if isinstance(mo, self.layers):\n for n_p, p in mo.named_parameters():\n name = '{}.{}'.format(n_m, n_p)\n insensitivity = torch.nn.functional.relu(1 - torch.abs(p.grad))\n... | <|body_start_0|>
self.model = model
self.lmbda = lmbda
self.layers = layers
<|end_body_0|>
<|body_start_1|>
for n_m, mo in self.model.named_modules():
if isinstance(mo, self.layers):
for n_p, p in mo.named_parameters():
name = '{}.{}'.form... | LOBSTER | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LOBSTER:
def __init__(self, model, lmbda, layers):
"""Initialize the LOBSTER regularizer. :param model: PyTorch model. :param lmbda: Lambda hyperparameter. :param layers: Tuple of layer on which apply the regularization e.g. (nn.modules.Conv2d, nn.modules.Linear)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_069187 | 1,288 | permissive | [
{
"docstring": "Initialize the LOBSTER regularizer. :param model: PyTorch model. :param lmbda: Lambda hyperparameter. :param layers: Tuple of layer on which apply the regularization e.g. (nn.modules.Conv2d, nn.modules.Linear)",
"name": "__init__",
"signature": "def __init__(self, model, lmbda, layers)"
... | 2 | null | Implement the Python class `LOBSTER` described below.
Class description:
Implement the LOBSTER class.
Method signatures and docstrings:
- def __init__(self, model, lmbda, layers): Initialize the LOBSTER regularizer. :param model: PyTorch model. :param lmbda: Lambda hyperparameter. :param layers: Tuple of layer on whi... | Implement the Python class `LOBSTER` described below.
Class description:
Implement the LOBSTER class.
Method signatures and docstrings:
- def __init__(self, model, lmbda, layers): Initialize the LOBSTER regularizer. :param model: PyTorch model. :param lmbda: Lambda hyperparameter. :param layers: Tuple of layer on whi... | dafa8c9b8425e87ab43484d8da9a241f27b7a237 | <|skeleton|>
class LOBSTER:
def __init__(self, model, lmbda, layers):
"""Initialize the LOBSTER regularizer. :param model: PyTorch model. :param lmbda: Lambda hyperparameter. :param layers: Tuple of layer on which apply the regularization e.g. (nn.modules.Conv2d, nn.modules.Linear)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LOBSTER:
def __init__(self, model, lmbda, layers):
"""Initialize the LOBSTER regularizer. :param model: PyTorch model. :param lmbda: Lambda hyperparameter. :param layers: Tuple of layer on which apply the regularization e.g. (nn.modules.Conv2d, nn.modules.Linear)"""
self.model = model
... | the_stack_v2_python_sparse | NetworkPruning/src/EIDOSearch/pruning/sensitivity/LOBSTER.py | jorickdefraine/serene2020 | train | 0 | |
852d747b43a63cccaedfd6a77a1248f772c33014 | [
"len_n, right_most = (len(nums), 0)\nfor i in range(len_n):\n if i <= right_most:\n right_most = max(nums[i] + i, right_most)\n if right_most >= len_n - 1:\n return True\nreturn False",
"len_n = len(nums)\ndp = [False] * len_n\ndp[0] = True\nfor i in range(len_n):\n if dp[i]:\n ... | <|body_start_0|>
len_n, right_most = (len(nums), 0)
for i in range(len_n):
if i <= right_most:
right_most = max(nums[i] + i, right_most)
if right_most >= len_n - 1:
return True
return False
<|end_body_0|>
<|body_start_1|>
l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户"""
<|body_0|>
def canJump1(self, nums: List[int]) -> bool:
"""超时"""
<|body_1|>
def jump1(self, nums: List[int... | stack_v2_sparse_classes_75kplus_train_069188 | 4,093 | no_license | [
{
"docstring": "执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户",
"name": "canJump",
"signature": "def canJump(self, nums: List[int]) -> bool"
},
{
"docstring": "超时",
"name": "canJump1",
"signature": "def canJump1(self, nums: List[int]) -> bool"
... | 4 | stack_v2_sparse_classes_30k_test_000119 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: List[int]) -> bool: 执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户
- def canJump1(self, nums: List[int]) -> bool:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: List[int]) -> bool: 执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户
- def canJump1(self, nums: List[int]) -> bool:... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def canJump(self, nums: List[int]) -> bool:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户"""
<|body_0|>
def canJump1(self, nums: List[int]) -> bool:
"""超时"""
<|body_1|>
def jump1(self, nums: List[int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def canJump(self, nums: List[int]) -> bool:
"""执行用时: 52 ms , 在所有 Python3 提交中击败了 52.08% 的用户 内存消耗: 16 MB , 在所有 Python3 提交中击败了 73.49% 的用户"""
len_n, right_most = (len(nums), 0)
for i in range(len_n):
if i <= right_most:
right_most = max(nums[i] + i, ri... | the_stack_v2_python_sparse | 跳跃游戏1&2.py | nomboy/leetcode | train | 0 | |
a0be54ea24ea73962408b5f1ad06910f47d63a5b | [
"super(ConvolutionalClassHead, self).__init__(name=name)\nself._is_training = is_training\nself._use_dropout = use_dropout\nself._dropout_keep_prob = dropout_keep_prob\nself._kernel_size = kernel_size\nself._class_prediction_bias_init = class_prediction_bias_init\nself._use_depthwise = use_depthwise\nself._num_clas... | <|body_start_0|>
super(ConvolutionalClassHead, self).__init__(name=name)
self._is_training = is_training
self._use_dropout = use_dropout
self._dropout_keep_prob = dropout_keep_prob
self._kernel_size = kernel_size
self._class_prediction_bias_init = class_prediction_bias_in... | Convolutional class prediction head. | ConvolutionalClassHead | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolutionalClassHead:
"""Convolutional class prediction head."""
def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, class_prediction_bias_init=0.0, use_depthwise=False, name=None):
... | stack_v2_sparse_classes_75kplus_train_069189 | 6,360 | permissive | [
{
"docstring": "Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_class_slots: number of class slots. Note that num_class_slots may or may not include an implicit background category. use_dropout: Option to use dropout or not. Note that a single dropout op is applied he... | 2 | stack_v2_sparse_classes_30k_train_018220 | Implement the Python class `ConvolutionalClassHead` described below.
Class description:
Convolutional class prediction head.
Method signatures and docstrings:
- def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnor... | Implement the Python class `ConvolutionalClassHead` described below.
Class description:
Convolutional class prediction head.
Method signatures and docstrings:
- def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnor... | d32cf96575c995f4d5b634e4dbb876845e3bcd2a | <|skeleton|>
class ConvolutionalClassHead:
"""Convolutional class prediction head."""
def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, class_prediction_bias_init=0.0, use_depthwise=False, name=None):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvolutionalClassHead:
"""Convolutional class prediction head."""
def __init__(self, is_training, num_class_slots, use_dropout, dropout_keep_prob, kernel_size, num_predictions_per_location, conv_hyperparams, freeze_batchnorm, class_prediction_bias_init=0.0, use_depthwise=False, name=None):
"""Co... | the_stack_v2_python_sparse | research/object_detection/predictors/heads/keras_class_head.py | apacha/MusicObjectDetector-TF | train | 83 |
fa806ae87b567dddad8bc4f7564f14111ef7cada | [
"self._schema = customer_schema\nself._provider_uuid = provider_uuid\nself._manifest = None\nif manifest_id is not None:\n with ReportManifestDBAccessor() as manifest_accessor:\n self._manifest = manifest_accessor.get_manifest_by_id(manifest_id)\nself._date_accessor = DateAccessor()\nwith ProviderDBAccess... | <|body_start_0|>
self._schema = customer_schema
self._provider_uuid = provider_uuid
self._manifest = None
if manifest_id is not None:
with ReportManifestDBAccessor() as manifest_accessor:
self._manifest = manifest_accessor.get_manifest_by_id(manifest_id)
... | Update reporting summary tables. | ReportSummaryUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportSummaryUpdater:
"""Update reporting summary tables."""
def __init__(self, customer_schema, provider_uuid, manifest_id=None):
"""Initializer. Args: customer_schema (str): Schema name for given customer. provider (str): The provider type."""
<|body_0|>
def _set_updat... | stack_v2_sparse_classes_75kplus_train_069190 | 7,462 | permissive | [
{
"docstring": "Initializer. Args: customer_schema (str): Schema name for given customer. provider (str): The provider type.",
"name": "__init__",
"signature": "def __init__(self, customer_schema, provider_uuid, manifest_id=None)"
},
{
"docstring": "Create the report summary updater object. Obje... | 5 | stack_v2_sparse_classes_30k_train_047522 | Implement the Python class `ReportSummaryUpdater` described below.
Class description:
Update reporting summary tables.
Method signatures and docstrings:
- def __init__(self, customer_schema, provider_uuid, manifest_id=None): Initializer. Args: customer_schema (str): Schema name for given customer. provider (str): The... | Implement the Python class `ReportSummaryUpdater` described below.
Class description:
Update reporting summary tables.
Method signatures and docstrings:
- def __init__(self, customer_schema, provider_uuid, manifest_id=None): Initializer. Args: customer_schema (str): Schema name for given customer. provider (str): The... | 2979f03fbdd1c20c3abc365a963a1282b426f321 | <|skeleton|>
class ReportSummaryUpdater:
"""Update reporting summary tables."""
def __init__(self, customer_schema, provider_uuid, manifest_id=None):
"""Initializer. Args: customer_schema (str): Schema name for given customer. provider (str): The provider type."""
<|body_0|>
def _set_updat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReportSummaryUpdater:
"""Update reporting summary tables."""
def __init__(self, customer_schema, provider_uuid, manifest_id=None):
"""Initializer. Args: customer_schema (str): Schema name for given customer. provider (str): The provider type."""
self._schema = customer_schema
self... | the_stack_v2_python_sparse | koku/masu/processor/report_summary_updater.py | luisfdez/koku | train | 0 |
001b741da45e448a5123dd87c8be7c9dea066e5e | [
"config_info = ConfigInfo()\nself.utils = Utilities()\nself.load_table_name = LoadHistoryLister.load_table_name\nif unittests:\n self.aux_db = 'Unittest'\nelse:\n self.aux_db = config_info.canvas_db_aux\nif unittests:\n self.db_obj = self.utils.log_into_mysql(config_info.test_default_user, self.utils.get_d... | <|body_start_0|>
config_info = ConfigInfo()
self.utils = Utilities()
self.load_table_name = LoadHistoryLister.load_table_name
if unittests:
self.aux_db = 'Unittest'
else:
self.aux_db = config_info.canvas_db_aux
if unittests:
self.db_obj... | Reads table LoadLog. Lists date of latest refresh for each table. Lists missing tables, and list of all tables. | LoadHistoryLister | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadHistoryLister:
"""Reads table LoadLog. Lists date of latest refresh for each table. Lists missing tables, and list of all tables."""
def __init__(self, latest_only=False, unittests=False):
"""Constructor"""
<|body_0|>
def print_latest_refresh(self, latest_only=False,... | stack_v2_sparse_classes_75kplus_train_069191 | 9,206 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, latest_only=False, unittests=False)"
},
{
"docstring": "Pretty print a list of aux tables that exist in the database. @param latest_only: if True, only the most recent refresh event for each table will be shown. @... | 4 | null | Implement the Python class `LoadHistoryLister` described below.
Class description:
Reads table LoadLog. Lists date of latest refresh for each table. Lists missing tables, and list of all tables.
Method signatures and docstrings:
- def __init__(self, latest_only=False, unittests=False): Constructor
- def print_latest_... | Implement the Python class `LoadHistoryLister` described below.
Class description:
Reads table LoadLog. Lists date of latest refresh for each table. Lists missing tables, and list of all tables.
Method signatures and docstrings:
- def __init__(self, latest_only=False, unittests=False): Constructor
- def print_latest_... | 6b7d9d4ccf93d034c88ed058ed06ddf02f124785 | <|skeleton|>
class LoadHistoryLister:
"""Reads table LoadLog. Lists date of latest refresh for each table. Lists missing tables, and list of all tables."""
def __init__(self, latest_only=False, unittests=False):
"""Constructor"""
<|body_0|>
def print_latest_refresh(self, latest_only=False,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoadHistoryLister:
"""Reads table LoadLog. Lists date of latest refresh for each table. Lists missing tables, and list of all tables."""
def __init__(self, latest_only=False, unittests=False):
"""Constructor"""
config_info = ConfigInfo()
self.utils = Utilities()
self.load_... | the_stack_v2_python_sparse | src/canvas_utils/refresh_history.py | paepcke/canvas_utils | train | 3 |
d2e7d46f5cdeb69140574ed57b1b244ac413e1a3 | [
"nums_map = dict()\nfor num in nums:\n nums_map[num] = True\nmiss_num = 1\nwhile miss_num in nums_map:\n miss_num += 1\nreturn miss_num",
"nums_len = len(nums)\nfor i in range(nums_len):\n while nums[i] != i + 1 and 0 < nums[i] <= nums_len and (nums[nums[i] - 1] != nums[i]):\n nums[nums[i] - 1], n... | <|body_start_0|>
nums_map = dict()
for num in nums:
nums_map[num] = True
miss_num = 1
while miss_num in nums_map:
miss_num += 1
return miss_num
<|end_body_0|>
<|body_start_1|>
nums_len = len(nums)
for i in range(nums_len):
whil... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums_map = dict()
f... | stack_v2_sparse_classes_75kplus_train_069192 | 799 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045640 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 052bd7915257679877dbe55b60ed1abb7528eaa2 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
nums_map = dict()
for num in nums:
nums_map[num] = True
miss_num = 1
while miss_num in nums_map:
miss_num += 1
return miss_num
def firstMissingPo... | the_stack_v2_python_sparse | python_solution/Array/41_FirstMissingPositive.py | Dimen61/leetcode | train | 4 | |
b855737247c0564a662b6259d8d82088439625fc | [
"parser.add_argument('hostname', nargs='+', type=str)\nparser.add_argument('-nh', '--new_host', action='store', nargs=1, help='Change the site hostname.')\nparser.add_argument('-p', '--port', action='store', nargs=1, help='Change the site port.')",
"current_host = options['hostname'][0]\nnew_host = options['new_h... | <|body_start_0|>
parser.add_argument('hostname', nargs='+', type=str)
parser.add_argument('-nh', '--new_host', action='store', nargs=1, help='Change the site hostname.')
parser.add_argument('-p', '--port', action='store', nargs=1, help='Change the site port.')
<|end_body_0|>
<|body_start_1|>
... | Updates data for a site with a given hostname. Required args: hostname: string, current hostname of the Wagtail site object to be updated Optional args: new_host: string, a new and different hostname for the site Returns: None, saves an updated version of the Wagtail site object with the given input parameters | Command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Updates data for a site with a given hostname. Required args: hostname: string, current hostname of the Wagtail site object to be updated Optional args: new_host: string, a new and different hostname for the site Returns: None, saves an updated version of the Wagtail site object with ... | stack_v2_sparse_classes_75kplus_train_069193 | 1,903 | no_license | [
{
"docstring": "Add required positional options and optional named arguments.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Meat of the command.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
}
] | 2 | null | Implement the Python class `Command` described below.
Class description:
Updates data for a site with a given hostname. Required args: hostname: string, current hostname of the Wagtail site object to be updated Optional args: new_host: string, a new and different hostname for the site Returns: None, saves an updated v... | Implement the Python class `Command` described below.
Class description:
Updates data for a site with a given hostname. Required args: hostname: string, current hostname of the Wagtail site object to be updated Optional args: new_host: string, a new and different hostname for the site Returns: None, saves an updated v... | e5912a17ed2de3a61ede2fbebda4a258664ff696 | <|skeleton|>
class Command:
"""Updates data for a site with a given hostname. Required args: hostname: string, current hostname of the Wagtail site object to be updated Optional args: new_host: string, a new and different hostname for the site Returns: None, saves an updated version of the Wagtail site object with ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""Updates data for a site with a given hostname. Required args: hostname: string, current hostname of the Wagtail site object to be updated Optional args: new_host: string, a new and different hostname for the site Returns: None, saves an updated version of the Wagtail site object with the given inp... | the_stack_v2_python_sparse | base/management/commands/update_site_data.py | uchicago-library/library_website | train | 5 |
248e3625e1487fe59e3872acf5142b5f5235baf9 | [
"comment = get_object_or_404(Comment, pk=self.kwargs.get('pk'))\nif comment.author_id != request.user.id:\n return Response(data={'message': 'You can only delete your comment'}, status=status.HTTP_403_FORBIDDEN)\ncomment = self.queryset.get(pk=kwargs['pk'])\ncomment.delete()\nreturn Response(data={'message': 'Co... | <|body_start_0|>
comment = get_object_or_404(Comment, pk=self.kwargs.get('pk'))
if comment.author_id != request.user.id:
return Response(data={'message': 'You can only delete your comment'}, status=status.HTTP_403_FORBIDDEN)
comment = self.queryset.get(pk=kwargs['pk'])
commen... | class to delete a comment on an article | DeleteUpdateCommentAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteUpdateCommentAPIView:
"""class to delete a comment on an article"""
def delete(self, request, *args, **kwargs):
"""Method to delete a comment"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Method to update a comment"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_069194 | 14,561 | permissive | [
{
"docstring": "Method to delete a comment",
"name": "delete",
"signature": "def delete(self, request, *args, **kwargs)"
},
{
"docstring": "Method to update a comment",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002277 | Implement the Python class `DeleteUpdateCommentAPIView` described below.
Class description:
class to delete a comment on an article
Method signatures and docstrings:
- def delete(self, request, *args, **kwargs): Method to delete a comment
- def put(self, request, *args, **kwargs): Method to update a comment | Implement the Python class `DeleteUpdateCommentAPIView` described below.
Class description:
class to delete a comment on an article
Method signatures and docstrings:
- def delete(self, request, *args, **kwargs): Method to delete a comment
- def put(self, request, *args, **kwargs): Method to update a comment
<|skelet... | fcc394e486a736993702bfa1e6fd9e9b189b93ae | <|skeleton|>
class DeleteUpdateCommentAPIView:
"""class to delete a comment on an article"""
def delete(self, request, *args, **kwargs):
"""Method to delete a comment"""
<|body_0|>
def put(self, request, *args, **kwargs):
"""Method to update a comment"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeleteUpdateCommentAPIView:
"""class to delete a comment on an article"""
def delete(self, request, *args, **kwargs):
"""Method to delete a comment"""
comment = get_object_or_404(Comment, pk=self.kwargs.get('pk'))
if comment.author_id != request.user.id:
return Respons... | the_stack_v2_python_sparse | authors/apps/articles/views.py | andela/ah-backend-sparta | train | 1 |
147726cb2dbbf0d7f211e519ca599ebd3c360140 | [
"if not head:\n return head\ncount = 0\ndummy = ListNode(0)\ndummy.next = head\ncur = dummy\nwhile cur.next:\n count += 1\n cur = cur.next\nk %= count\nif k == 0:\n return head\ncur = dummy\nfor _ in range(count - k):\n cur = cur.next\nnew_head = cur.next\ncur.next = None\ndummy.next = new_head\nwhil... | <|body_start_0|>
if not head:
return head
count = 0
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next:
count += 1
cur = cur.next
k %= count
if k == 0:
return head
cur = dummy
fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n... | stack_v2_sparse_classes_75kplus_train_069195 | 1,706 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight1",
"signature": "def rotateRight1(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight",
"signature": "def rotateRight(self, head, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017200 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight1(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def rotateRight(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skelet... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def rotateRight(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotateRight1(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
if not head:
return head
count = 0
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur.next:
count += 1
cur = ... | the_stack_v2_python_sparse | LinkedList/q061_rotate_list.py | sevenhe716/LeetCode | train | 0 | |
d6f27bcfb0d08383ccfb9223ea591afc61e6e847 | [
"session = info.context.get('session')\nfunc_count_citations = sqlalchemy_func.count(sqlalchemy_func.distinct(ModelCitation.citation_id))\nquery = session.query(ModelAffiliationCanonical.country, func_count_citations)\nquery = query.join(ModelArticleAuthorAffiliation, ModelAffiliationCanonical.affiliation_canonical... | <|body_start_0|>
session = info.context.get('session')
func_count_citations = sqlalchemy_func.count(sqlalchemy_func.distinct(ModelCitation.citation_id))
query = session.query(ModelAffiliationCanonical.country, func_count_citations)
query = query.join(ModelArticleAuthorAffiliation, ModelA... | TypeCitationsStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeCitationsStats:
def resolve_count_citations_by_country(args: dict, info: graphene.ResolveInfo, citation_ids: List[int], limit: Optional[int]=None) -> List[TypeCountCitationsCountry]:
"""Creates a list of `TypeCountCitationsCountry` objects with the number of citations per country. Ar... | stack_v2_sparse_classes_75kplus_train_069196 | 11,665 | no_license | [
{
"docstring": "Creates a list of `TypeCountCitationsCountry` objects with the number of citations per country. Args: args (dict): The resolver arguments. info (graphene.ResolveInfo): The resolver info. citation_ids (List[int]): A list of citation IDs. limit (Optional[int]): The number of results to return. Def... | 3 | stack_v2_sparse_classes_30k_train_015278 | Implement the Python class `TypeCitationsStats` described below.
Class description:
Implement the TypeCitationsStats class.
Method signatures and docstrings:
- def resolve_count_citations_by_country(args: dict, info: graphene.ResolveInfo, citation_ids: List[int], limit: Optional[int]=None) -> List[TypeCountCitationsC... | Implement the Python class `TypeCitationsStats` described below.
Class description:
Implement the TypeCitationsStats class.
Method signatures and docstrings:
- def resolve_count_citations_by_country(args: dict, info: graphene.ResolveInfo, citation_ids: List[int], limit: Optional[int]=None) -> List[TypeCountCitationsC... | 275d0f5f437e09cb477600f48080d921301238e6 | <|skeleton|>
class TypeCitationsStats:
def resolve_count_citations_by_country(args: dict, info: graphene.ResolveInfo, citation_ids: List[int], limit: Optional[int]=None) -> List[TypeCountCitationsCountry]:
"""Creates a list of `TypeCountCitationsCountry` objects with the number of citations per country. Ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TypeCitationsStats:
def resolve_count_citations_by_country(args: dict, info: graphene.ResolveInfo, citation_ids: List[int], limit: Optional[int]=None) -> List[TypeCountCitationsCountry]:
"""Creates a list of `TypeCountCitationsCountry` objects with the number of citations per country. Args: args (dict... | the_stack_v2_python_sparse | ffgraphql/types/citations_stats.py | bearnd/fightfor-graphql | train | 0 | |
44330ff170aadd8d8b8b5c2c0fb7ece56cb69b39 | [
"class dummy_manager(object):\n\n def communicator(self):\n return Communicate()\n\n def perspective(self):\n return MyPerspective()\nf = DroppableDataLoadWidget(None, guimanager=dummy_manager())\nself.mime_data = QtCore.QMimeData()\nself.testfile = 'testfile.txt'\nself.mime_data.setUrls([QtCore... | <|body_start_0|>
class dummy_manager(object):
def communicator(self):
return Communicate()
def perspective(self):
return MyPerspective()
f = DroppableDataLoadWidget(None, guimanager=dummy_manager())
self.mime_data = QtCore.QMimeData()
... | Test the DroppableDataLoadWidget GUI | DroppableDataLoadWidgetTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DroppableDataLoadWidgetTest:
"""Test the DroppableDataLoadWidget GUI"""
def form(self, qapp):
"""Create/Destroy the DroppableDataLoadWidget"""
<|body_0|>
def testDragIsOK(self, form):
"""Test the item being dragged over the load widget"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_069197 | 2,643 | permissive | [
{
"docstring": "Create/Destroy the DroppableDataLoadWidget",
"name": "form",
"signature": "def form(self, qapp)"
},
{
"docstring": "Test the item being dragged over the load widget",
"name": "testDragIsOK",
"signature": "def testDragIsOK(self, form)"
},
{
"docstring": "Test what ... | 3 | stack_v2_sparse_classes_30k_train_010013 | Implement the Python class `DroppableDataLoadWidgetTest` described below.
Class description:
Test the DroppableDataLoadWidget GUI
Method signatures and docstrings:
- def form(self, qapp): Create/Destroy the DroppableDataLoadWidget
- def testDragIsOK(self, form): Test the item being dragged over the load widget
- def ... | Implement the Python class `DroppableDataLoadWidgetTest` described below.
Class description:
Test the DroppableDataLoadWidget GUI
Method signatures and docstrings:
- def form(self, qapp): Create/Destroy the DroppableDataLoadWidget
- def testDragIsOK(self, form): Test the item being dragged over the load widget
- def ... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class DroppableDataLoadWidgetTest:
"""Test the DroppableDataLoadWidget GUI"""
def form(self, qapp):
"""Create/Destroy the DroppableDataLoadWidget"""
<|body_0|>
def testDragIsOK(self, form):
"""Test the item being dragged over the load widget"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DroppableDataLoadWidgetTest:
"""Test the DroppableDataLoadWidget GUI"""
def form(self, qapp):
"""Create/Destroy the DroppableDataLoadWidget"""
class dummy_manager(object):
def communicator(self):
return Communicate()
def perspective(self):
... | the_stack_v2_python_sparse | src/sas/qtgui/MainWindow/UnitTesting/DroppableDataLoadWidgetTest.py | SasView/sasview | train | 48 |
8e51d2c74dde536203c5c9ae13e5cd4376c14322 | [
"user = request.user\nif self._should_redirect(request, user):\n return TOSPage.as_view()(request, *view_args, **view_kwarg)\nelse:\n return None",
"if request.method != 'GET' or user.is_anonymous() or any((request.path.startswith(p) for p in self.UNPROTECTED_PATHS)):\n return False\naccepted_tos = reque... | <|body_start_0|>
user = request.user
if self._should_redirect(request, user):
return TOSPage.as_view()(request, *view_args, **view_kwarg)
else:
return None
<|end_body_0|>
<|body_start_1|>
if request.method != 'GET' or user.is_anonymous() or any((request.path.star... | ElvisTermsOfServiceMiddleware | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElvisTermsOfServiceMiddleware:
def process_view(self, request, view_func, view_args, view_kwarg):
"""Redirect request to TOS page if user has not accepted yet."""
<|body_0|>
def _should_redirect(self, request, user):
"""Figure out if user should be redirected to TOS ... | stack_v2_sparse_classes_75kplus_train_069198 | 1,219 | no_license | [
{
"docstring": "Redirect request to TOS page if user has not accepted yet.",
"name": "process_view",
"signature": "def process_view(self, request, view_func, view_args, view_kwarg)"
},
{
"docstring": "Figure out if user should be redirected to TOS screen.",
"name": "_should_redirect",
"s... | 2 | stack_v2_sparse_classes_30k_test_002551 | Implement the Python class `ElvisTermsOfServiceMiddleware` described below.
Class description:
Implement the ElvisTermsOfServiceMiddleware class.
Method signatures and docstrings:
- def process_view(self, request, view_func, view_args, view_kwarg): Redirect request to TOS page if user has not accepted yet.
- def _sho... | Implement the Python class `ElvisTermsOfServiceMiddleware` described below.
Class description:
Implement the ElvisTermsOfServiceMiddleware class.
Method signatures and docstrings:
- def process_view(self, request, view_func, view_args, view_kwarg): Redirect request to TOS page if user has not accepted yet.
- def _sho... | 3df64dd8d257af33984fe133be0e4170330a713a | <|skeleton|>
class ElvisTermsOfServiceMiddleware:
def process_view(self, request, view_func, view_args, view_kwarg):
"""Redirect request to TOS page if user has not accepted yet."""
<|body_0|>
def _should_redirect(self, request, user):
"""Figure out if user should be redirected to TOS ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElvisTermsOfServiceMiddleware:
def process_view(self, request, view_func, view_args, view_kwarg):
"""Redirect request to TOS page if user has not accepted yet."""
user = request.user
if self._should_redirect(request, user):
return TOSPage.as_view()(request, *view_args, **vi... | the_stack_v2_python_sparse | elvis/middleware/terms_of_service.py | ELVIS-Project/elvis-database | train | 15 | |
ac716d818e9110d426ab5cf390859452f3eee713 | [
"col_update_params = {}\nfiscal_year = self.object.fiscal_year\nfor form in LIST_INTERNAL_AFFAIRS_STATE:\n if ROUTE_LINK[form]['form_field'] in ['action_plan_implementation']:\n form_obj = ROUTE_LINK[form]['model'].objects.create(body=self.object.body, create_user=self.request.user)\n elif ROUTE_LINK[f... | <|body_start_0|>
col_update_params = {}
fiscal_year = self.object.fiscal_year
for form in LIST_INTERNAL_AFFAIRS_STATE:
if ROUTE_LINK[form]['form_field'] in ['action_plan_implementation']:
form_obj = ROUTE_LINK[form]['model'].objects.create(body=self.object.body, creat... | Creates form collection and initializes all forms in the collection | InternalAffairFormCollectionCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InternalAffairFormCollectionCreateView:
"""Creates form collection and initializes all forms in the collection"""
def init_forms(self):
"""Initializes(creates) forms of the collection and links them to it."""
<|body_0|>
def get(self, request, *args, **kwargs):
""... | stack_v2_sparse_classes_75kplus_train_069199 | 15,180 | no_license | [
{
"docstring": "Initializes(creates) forms of the collection and links them to it.",
"name": "init_forms",
"signature": "def init_forms(self)"
},
{
"docstring": "renders forms initial page to fill initial data like province, fiscal year",
"name": "get",
"signature": "def get(self, reques... | 3 | stack_v2_sparse_classes_30k_train_054702 | Implement the Python class `InternalAffairFormCollectionCreateView` described below.
Class description:
Creates form collection and initializes all forms in the collection
Method signatures and docstrings:
- def init_forms(self): Initializes(creates) forms of the collection and links them to it.
- def get(self, reque... | Implement the Python class `InternalAffairFormCollectionCreateView` described below.
Class description:
Creates form collection and initializes all forms in the collection
Method signatures and docstrings:
- def init_forms(self): Initializes(creates) forms of the collection and links them to it.
- def get(self, reque... | 38c0bf763ae0a15c301c020d76ff0596c561da14 | <|skeleton|>
class InternalAffairFormCollectionCreateView:
"""Creates form collection and initializes all forms in the collection"""
def init_forms(self):
"""Initializes(creates) forms of the collection and links them to it."""
<|body_0|>
def get(self, request, *args, **kwargs):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InternalAffairFormCollectionCreateView:
"""Creates form collection and initializes all forms in the collection"""
def init_forms(self):
"""Initializes(creates) forms of the collection and links them to it."""
col_update_params = {}
fiscal_year = self.object.fiscal_year
for... | the_stack_v2_python_sparse | collection/views/internal_affairs_form_collection_views.py | Rabin5/formcollection | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.