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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
05e68fb1e4ca21dbdf93356e93c4bad856e03e00 | [
"out_list = []\nfor time_range in time_ranges:\n time = time_range[0]\n begin_time = time_range[1]\n train_begin_time = datetime.datetime.strptime(begin_time, '%d.%m.%Y %H:%M')\n train_arrive_time = train_begin_time + datetime.timedelta(minutes=time)\n out_list.append((train_begin_time, train_arrive_... | <|body_start_0|>
out_list = []
for time_range in time_ranges:
time = time_range[0]
begin_time = time_range[1]
train_begin_time = datetime.datetime.strptime(begin_time, '%d.%m.%Y %H:%M')
train_arrive_time = train_begin_time + datetime.timedelta(minutes=time... | UniversalClass | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniversalClass:
def get_train_time(*time_ranges):
"""Метод для вычисления времени прибытия поезда Необходим для проверки на то, успевает ли человек на свой поезд"""
<|body_0|>
def detect_station_waiting_time(station_name, all_wait_list):
"""Определяем, есть ли станци... | stack_v2_sparse_classes_75kplus_train_069700 | 2,494 | permissive | [
{
"docstring": "Метод для вычисления времени прибытия поезда Необходим для проверки на то, успевает ли человек на свой поезд",
"name": "get_train_time",
"signature": "def get_train_time(*time_ranges)"
},
{
"docstring": "Определяем, есть ли станция в словаре ожидания - Если есть такая станция, то... | 3 | stack_v2_sparse_classes_30k_train_013937 | Implement the Python class `UniversalClass` described below.
Class description:
Implement the UniversalClass class.
Method signatures and docstrings:
- def get_train_time(*time_ranges): Метод для вычисления времени прибытия поезда Необходим для проверки на то, успевает ли человек на свой поезд
- def detect_station_wa... | Implement the Python class `UniversalClass` described below.
Class description:
Implement the UniversalClass class.
Method signatures and docstrings:
- def get_train_time(*time_ranges): Метод для вычисления времени прибытия поезда Необходим для проверки на то, успевает ли человек на свой поезд
- def detect_station_wa... | 9575c43fa01c261ea1ed573df9b5686b5a6f4211 | <|skeleton|>
class UniversalClass:
def get_train_time(*time_ranges):
"""Метод для вычисления времени прибытия поезда Необходим для проверки на то, успевает ли человек на свой поезд"""
<|body_0|>
def detect_station_waiting_time(station_name, all_wait_list):
"""Определяем, есть ли станци... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniversalClass:
def get_train_time(*time_ranges):
"""Метод для вычисления времени прибытия поезда Необходим для проверки на то, успевает ли человек на свой поезд"""
out_list = []
for time_range in time_ranges:
time = time_range[0]
begin_time = time_range[1]
... | the_stack_v2_python_sparse | Course_I/Алгоритмы Python/Part1/семинары/pract5/task3/universal_module.py | GeorgiyDemo/FA | train | 46 | |
771ec820281805b5e5a7a0d06a5d59f11ab63ac5 | [
"usuario = getAbogadoById(pk)\nserializer = self.serializer_class(usuario)\nif usuario is not None:\n return Response(serializer.data, status=status.HTTP_200_OK)\nelse:\n return Response(serializer.data, status=status.HTTP_404_NOT_FOUND)",
"serializer = self.serializer_class(data=request.data)\nif serialize... | <|body_start_0|>
usuario = getAbogadoById(pk)
serializer = self.serializer_class(usuario)
if usuario is not None:
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.data, status=status.HTTP_404_NOT_FOUND)
<|end_body_0|>
<... | Maneja el Detail de usuario Abogado Args: viewsets ([type]): [description] | usuarioAbogadoViewDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class usuarioAbogadoViewDetail:
"""Maneja el Detail de usuario Abogado Args: viewsets ([type]): [description]"""
def get(self, request, pk, format=None):
"""Metodo Get By Id de Usuario Abogado Args: request ([type]): [description] pk ([type]): [description] format ([type], optional): [desc... | stack_v2_sparse_classes_75kplus_train_069701 | 18,724 | no_license | [
{
"docstring": "Metodo Get By Id de Usuario Abogado Args: request ([type]): [description] pk ([type]): [description] format ([type], optional): [description]. Defaults to None. Returns: HTTP200 si se encontro HTTP404 si no se encontro",
"name": "get",
"signature": "def get(self, request, pk, format=None... | 3 | stack_v2_sparse_classes_30k_train_008383 | Implement the Python class `usuarioAbogadoViewDetail` described below.
Class description:
Maneja el Detail de usuario Abogado Args: viewsets ([type]): [description]
Method signatures and docstrings:
- def get(self, request, pk, format=None): Metodo Get By Id de Usuario Abogado Args: request ([type]): [description] pk... | Implement the Python class `usuarioAbogadoViewDetail` described below.
Class description:
Maneja el Detail de usuario Abogado Args: viewsets ([type]): [description]
Method signatures and docstrings:
- def get(self, request, pk, format=None): Metodo Get By Id de Usuario Abogado Args: request ([type]): [description] pk... | 5edfc0fb9316c899dbd5cd5607989300c75ab4e8 | <|skeleton|>
class usuarioAbogadoViewDetail:
"""Maneja el Detail de usuario Abogado Args: viewsets ([type]): [description]"""
def get(self, request, pk, format=None):
"""Metodo Get By Id de Usuario Abogado Args: request ([type]): [description] pk ([type]): [description] format ([type], optional): [desc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class usuarioAbogadoViewDetail:
"""Maneja el Detail de usuario Abogado Args: viewsets ([type]): [description]"""
def get(self, request, pk, format=None):
"""Metodo Get By Id de Usuario Abogado Args: request ([type]): [description] pk ([type]): [description] format ([type], optional): [description]. Def... | the_stack_v2_python_sparse | usuarios_API/views.py | MartinGalvanCastro/ApoyaFem-API | train | 0 |
c68673dc26d8cd9e067fd8dfeeeadf4269c7f239 | [
"len_list = 0\np = head\nwhile p:\n len_list = len_list + 1\n p = p.next\nif len_list == 0:\n return head\nfrom_front = len_list - n + 1\nif from_front == 1:\n return head.next\ncurr = head\nprev = head\nx = 1\nwhile x != from_front:\n prev = curr\n curr = curr.next\n x = x + 1\nprev.next = cur... | <|body_start_0|>
len_list = 0
p = head
while p:
len_list = len_list + 1
p = p.next
if len_list == 0:
return head
from_front = len_list - n + 1
if from_front == 1:
return head.next
curr = head
prev = head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069702 | 1,363 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd2",
"signature": "def removeNthFromEnd2(sel... | 2 | stack_v2_sparse_classes_30k_train_022372 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): :type head: ListNode :type n: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd2(self, head, n): :type head: ListNode :type n: int :rtype: ListNode... | cd8470b4a7ee47b872b590b3682d0f3c59aa2199 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd2(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
len_list = 0
p = head
while p:
len_list = len_list + 1
p = p.next
if len_list == 0:
return head
from_front = len_list - n ... | the_stack_v2_python_sparse | delete_nth_node_from_end.py | manika1511/interview_prep | train | 0 | |
858bb48d002fd887898df3c64bf9136ba57b5bab | [
"try:\n from markdown import Markdown\n\n def markdown_converter(file):\n text = file.data.decode('utf-8')\n return Markdown().convert(text)\n for ext in ['markdown', 'md']:\n File.add_html_converter_by_ext(markdown_converter, ext)\nexcept ImportError:\n pass",
"skip = lambda f: f... | <|body_start_0|>
try:
from markdown import Markdown
def markdown_converter(file):
text = file.data.decode('utf-8')
return Markdown().convert(text)
for ext in ['markdown', 'md']:
File.add_html_converter_by_ext(markdown_converter... | Converters | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Converters:
def add_markdown_converter(self):
"""Adds a markdown converter if :mod:`markdown` exists."""
<|body_0|>
def add_html_converter(self):
"""Adds a HTML converter."""
<|body_1|>
def add_plain_converter(self):
"""Adds a plain text converte... | stack_v2_sparse_classes_75kplus_train_069703 | 1,254 | no_license | [
{
"docstring": "Adds a markdown converter if :mod:`markdown` exists.",
"name": "add_markdown_converter",
"signature": "def add_markdown_converter(self)"
},
{
"docstring": "Adds a HTML converter.",
"name": "add_html_converter",
"signature": "def add_html_converter(self)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_test_001987 | Implement the Python class `Converters` described below.
Class description:
Implement the Converters class.
Method signatures and docstrings:
- def add_markdown_converter(self): Adds a markdown converter if :mod:`markdown` exists.
- def add_html_converter(self): Adds a HTML converter.
- def add_plain_converter(self):... | Implement the Python class `Converters` described below.
Class description:
Implement the Converters class.
Method signatures and docstrings:
- def add_markdown_converter(self): Adds a markdown converter if :mod:`markdown` exists.
- def add_html_converter(self): Adds a HTML converter.
- def add_plain_converter(self):... | 8a36ac4c92b1c29102029b0f678311d11cff542c | <|skeleton|>
class Converters:
def add_markdown_converter(self):
"""Adds a markdown converter if :mod:`markdown` exists."""
<|body_0|>
def add_html_converter(self):
"""Adds a HTML converter."""
<|body_1|>
def add_plain_converter(self):
"""Adds a plain text converte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Converters:
def add_markdown_converter(self):
"""Adds a markdown converter if :mod:`markdown` exists."""
try:
from markdown import Markdown
def markdown_converter(file):
text = file.data.decode('utf-8')
return Markdown().convert(text)
... | the_stack_v2_python_sparse | site-packages/flaskext/autoindex/converters.py | rljacobson/Guru-NB | train | 1 | |
47e211d89632b08e7f4f49391b730b0fc7badcca | [
"Muscle.__init__(self, params_, simulator)\nself.k = self.params['k'] if 'k' in self.params else 100\nself.c = self.params['c'] if 'c' in self.params else 10\nself.k_cont = self.params['kc'] if 'kc' in self.params else 0\nif self.active:\n v = self.velocity_2 - self.velocity_1\n self.v_norm = v.dot(self.lengt... | <|body_start_0|>
Muscle.__init__(self, params_, simulator)
self.k = self.params['k'] if 'k' in self.params else 100
self.c = self.params['c'] if 'c' in self.params else 10
self.k_cont = self.params['kc'] if 'kc' in self.params else 0
if self.active:
v = self.velocity_... | This class implements a simple muscle composed by a spring and a damping in parallel | DampedSpringMuscle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DampedSpringMuscle:
"""This class implements a simple muscle composed by a spring and a damping in parallel"""
def __init__(self, params_, simulator):
"""Class initialization. Requires controller as well as two object and the local point of application of the spring forces :param par... | stack_v2_sparse_classes_75kplus_train_069704 | 7,044 | no_license | [
{
"docstring": "Class initialization. Requires controller as well as two object and the local point of application of the spring forces :param params_: Dictionary containing parameter for the muscle :param simulator: SimulatorUtils class to access utility functions",
"name": "__init__",
"signature": "de... | 3 | stack_v2_sparse_classes_30k_train_012752 | Implement the Python class `DampedSpringMuscle` described below.
Class description:
This class implements a simple muscle composed by a spring and a damping in parallel
Method signatures and docstrings:
- def __init__(self, params_, simulator): Class initialization. Requires controller as well as two object and the l... | Implement the Python class `DampedSpringMuscle` described below.
Class description:
This class implements a simple muscle composed by a spring and a damping in parallel
Method signatures and docstrings:
- def __init__(self, params_, simulator): Class initialization. Requires controller as well as two object and the l... | f4f212a7533a63d1148068bacf1cc13d3f64db49 | <|skeleton|>
class DampedSpringMuscle:
"""This class implements a simple muscle composed by a spring and a damping in parallel"""
def __init__(self, params_, simulator):
"""Class initialization. Requires controller as well as two object and the local point of application of the spring forces :param par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DampedSpringMuscle:
"""This class implements a simple muscle composed by a spring and a damping in parallel"""
def __init__(self, params_, simulator):
"""Class initialization. Requires controller as well as two object and the local point of application of the spring forces :param params_: Diction... | the_stack_v2_python_sparse | src/musculoskeletals/muscles/dampedSprings.py | mahedjaved/mouse_locomotion | train | 0 |
83a381ebbccdeef2948219c604a114278863fb17 | [
"assert direction in ['vertical']\nsuper(EpiEncoder, self).__init__()\nself.direction = direction\nif direction == 'vertical':\n pad_top = tilesize // 2\n self.conv1 = nn.Conv2d(1, 16, kernel_size=tilesize, stride=(1, tilesize), padding=(pad_top, 0))\nself.relu1 = nn.ReLU(inplace=True)",
"inp_height, inp_wi... | <|body_start_0|>
assert direction in ['vertical']
super(EpiEncoder, self).__init__()
self.direction = direction
if direction == 'vertical':
pad_top = tilesize // 2
self.conv1 = nn.Conv2d(1, 16, kernel_size=tilesize, stride=(1, tilesize), padding=(pad_top, 0))
... | Learns an encoding of epipolar images when presented as a 2D grid of epipolar slices. | EpiEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpiEncoder:
"""Learns an encoding of epipolar images when presented as a 2D grid of epipolar slices."""
def __init__(self, direction, tilesize):
"""Arguments: - direction: "vertical" or "horizontal" # TODO: this - tilesize: width (for vertical) or height (for horizontal) of epipolar ... | stack_v2_sparse_classes_75kplus_train_069705 | 3,862 | no_license | [
{
"docstring": "Arguments: - direction: \"vertical\" or \"horizontal\" # TODO: this - tilesize: width (for vertical) or height (for horizontal) of epipolar slice Returns: - neural layer that encodes an EPI",
"name": "__init__",
"signature": "def __init__(self, direction, tilesize)"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_040283 | Implement the Python class `EpiEncoder` described below.
Class description:
Learns an encoding of epipolar images when presented as a 2D grid of epipolar slices.
Method signatures and docstrings:
- def __init__(self, direction, tilesize): Arguments: - direction: "vertical" or "horizontal" # TODO: this - tilesize: wid... | Implement the Python class `EpiEncoder` described below.
Class description:
Learns an encoding of epipolar images when presented as a 2D grid of epipolar slices.
Method signatures and docstrings:
- def __init__(self, direction, tilesize): Arguments: - direction: "vertical" or "horizontal" # TODO: this - tilesize: wid... | 96a941151b2bfcc9d45e15d0d1570041dbf00561 | <|skeleton|>
class EpiEncoder:
"""Learns an encoding of epipolar images when presented as a 2D grid of epipolar slices."""
def __init__(self, direction, tilesize):
"""Arguments: - direction: "vertical" or "horizontal" # TODO: this - tilesize: width (for vertical) or height (for horizontal) of epipolar ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EpiEncoder:
"""Learns an encoding of epipolar images when presented as a 2D grid of epipolar slices."""
def __init__(self, direction, tilesize):
"""Arguments: - direction: "vertical" or "horizontal" # TODO: this - tilesize: width (for vertical) or height (for horizontal) of epipolar slice Returns... | the_stack_v2_python_sparse | lfmodels/EpiEncoder.py | josepdaniel/thesis-experiments | train | 0 |
e14369191795f048feb9ede9b84bada35b943687 | [
"if chunk_size < 1:\n raise ValueError('The chunk_size must be greater than zero.')\nself.chunk_size = chunk_size\nself.all_reduce_spec = all_reduce_spec\nself.compressor = compressor",
"expr = Strategy()\nexpr.graph_config.replicas.extend([k for k, v in resource_spec.gpu_devices])\nfor k, v in resource_spec.n... | <|body_start_0|>
if chunk_size < 1:
raise ValueError('The chunk_size must be greater than zero.')
self.chunk_size = chunk_size
self.all_reduce_spec = all_reduce_spec
self.compressor = compressor
<|end_body_0|>
<|body_start_1|>
expr = Strategy()
expr.graph_con... | AllReduce StrategyBuilder. This StrategyBuilder generates a strategy that synchronizes every dense variable using AllReduce. It will sequentially merge collective ops into a single collective group based on chunk_size. This strategy does not support synchronizing sparse updates with >1 nodes due to the TF AllGather bug... | AllReduce | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllReduce:
"""AllReduce StrategyBuilder. This StrategyBuilder generates a strategy that synchronizes every dense variable using AllReduce. It will sequentially merge collective ops into a single collective group based on chunk_size. This strategy does not support synchronizing sparse updates with... | stack_v2_sparse_classes_75kplus_train_069706 | 3,860 | permissive | [
{
"docstring": "Init function. Args: chunk_size (int): chunk_size is a positive integer indicating how many variables will be merged sequentially as a group by scoped allocator. all_reduce_spec (str): 'AUTO', 'NCCL', 'RING'. compressor (str): Gradient compression algorithm to use.",
"name": "__init__",
... | 3 | stack_v2_sparse_classes_30k_train_006548 | Implement the Python class `AllReduce` described below.
Class description:
AllReduce StrategyBuilder. This StrategyBuilder generates a strategy that synchronizes every dense variable using AllReduce. It will sequentially merge collective ops into a single collective group based on chunk_size. This strategy does not su... | Implement the Python class `AllReduce` described below.
Class description:
AllReduce StrategyBuilder. This StrategyBuilder generates a strategy that synchronizes every dense variable using AllReduce. It will sequentially merge collective ops into a single collective group based on chunk_size. This strategy does not su... | 9bf89c90cb41eafa82d5660b979e7d0797e3cdf5 | <|skeleton|>
class AllReduce:
"""AllReduce StrategyBuilder. This StrategyBuilder generates a strategy that synchronizes every dense variable using AllReduce. It will sequentially merge collective ops into a single collective group based on chunk_size. This strategy does not support synchronizing sparse updates with... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AllReduce:
"""AllReduce StrategyBuilder. This StrategyBuilder generates a strategy that synchronizes every dense variable using AllReduce. It will sequentially merge collective ops into a single collective group based on chunk_size. This strategy does not support synchronizing sparse updates with >1 nodes due... | the_stack_v2_python_sparse | autodist/strategy/all_reduce_strategy.py | ibrandiay/autodist | train | 0 |
82478f58c632e9030cf6f45d5b0f478af37ec2c4 | [
"self.__key = key\nself.__iv = iv\nself.__block_size = block_size",
"blocks = [ciphertext[i:i + self.__block_size] for i in range(0, len(ciphertext), self.__block_size)]\nplaintext = b''\nxor_next = self.__iv\nfor block in blocks:\n plain_xored = AES_ECB_decrypt(block, self.__key)\n plaintext += xor_bytes(p... | <|body_start_0|>
self.__key = key
self.__iv = iv
self.__block_size = block_size
<|end_body_0|>
<|body_start_1|>
blocks = [ciphertext[i:i + self.__block_size] for i in range(0, len(ciphertext), self.__block_size)]
plaintext = b''
xor_next = self.__iv
for block in ... | Class enabling AES encryption and decryption in CBC mode Key and Initialization Vetor are fixed throughout lifetime of an object | AES_CBC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AES_CBC:
"""Class enabling AES encryption and decryption in CBC mode Key and Initialization Vetor are fixed throughout lifetime of an object"""
def __init__(self, key, iv=bytes([0] * 16), block_size=16):
"""Initializes class with key, IV, block_size"""
<|body_0|>
def dec... | stack_v2_sparse_classes_75kplus_train_069707 | 1,788 | no_license | [
{
"docstring": "Initializes class with key, IV, block_size",
"name": "__init__",
"signature": "def __init__(self, key, iv=bytes([0] * 16), block_size=16)"
},
{
"docstring": "decrypts `ciphertext` with `self.__key` using `self.__iv` as initialization vector.",
"name": "decrypt",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_022577 | Implement the Python class `AES_CBC` described below.
Class description:
Class enabling AES encryption and decryption in CBC mode Key and Initialization Vetor are fixed throughout lifetime of an object
Method signatures and docstrings:
- def __init__(self, key, iv=bytes([0] * 16), block_size=16): Initializes class wi... | Implement the Python class `AES_CBC` described below.
Class description:
Class enabling AES encryption and decryption in CBC mode Key and Initialization Vetor are fixed throughout lifetime of an object
Method signatures and docstrings:
- def __init__(self, key, iv=bytes([0] * 16), block_size=16): Initializes class wi... | 79889a62e81f4cfa6dce6bc9f4dbe6a53fb3b80c | <|skeleton|>
class AES_CBC:
"""Class enabling AES encryption and decryption in CBC mode Key and Initialization Vetor are fixed throughout lifetime of an object"""
def __init__(self, key, iv=bytes([0] * 16), block_size=16):
"""Initializes class with key, IV, block_size"""
<|body_0|>
def dec... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AES_CBC:
"""Class enabling AES encryption and decryption in CBC mode Key and Initialization Vetor are fixed throughout lifetime of an object"""
def __init__(self, key, iv=bytes([0] * 16), block_size=16):
"""Initializes class with key, IV, block_size"""
self.__key = key
self.__iv =... | the_stack_v2_python_sparse | chall10.py | Caroleq/cryptopals | train | 0 |
c0378ebd4b34c9de25c61a7b5fe7083c3ba1fbea | [
"azimuthT = self.app.mount.obsSite.AzTarget\naltitudeT = self.app.mount.obsSite.AltTarget\nif azimuthT is None or altitudeT is None:\n return False\nazimuthT = azimuthT.degrees\naltitudeT = altitudeT.degrees\nif self.app.deviceStat['dome']:\n delta = self.app.dome.slewDome(altitude=altitudeT, azimuth=azimuthT... | <|body_start_0|>
azimuthT = self.app.mount.obsSite.AzTarget
altitudeT = self.app.mount.obsSite.AltTarget
if azimuthT is None or altitudeT is None:
return False
azimuthT = azimuthT.degrees
altitudeT = altitudeT.degrees
if self.app.deviceStat['dome']:
... | SlewInterface | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlewInterface:
def slewSelectedTargetWithDome(self, slewType='normal'):
""":param slewType: :return: success"""
<|body_0|>
def slewTargetAltAz(self, alt, az, slewType='normal'):
""":param alt: :param az: :param slewType: :return:"""
<|body_1|>
def slewTa... | stack_v2_sparse_classes_75kplus_train_069708 | 3,313 | permissive | [
{
"docstring": ":param slewType: :return: success",
"name": "slewSelectedTargetWithDome",
"signature": "def slewSelectedTargetWithDome(self, slewType='normal')"
},
{
"docstring": ":param alt: :param az: :param slewType: :return:",
"name": "slewTargetAltAz",
"signature": "def slewTargetAl... | 3 | stack_v2_sparse_classes_30k_train_001882 | Implement the Python class `SlewInterface` described below.
Class description:
Implement the SlewInterface class.
Method signatures and docstrings:
- def slewSelectedTargetWithDome(self, slewType='normal'): :param slewType: :return: success
- def slewTargetAltAz(self, alt, az, slewType='normal'): :param alt: :param a... | Implement the Python class `SlewInterface` described below.
Class description:
Implement the SlewInterface class.
Method signatures and docstrings:
- def slewSelectedTargetWithDome(self, slewType='normal'): :param slewType: :return: success
- def slewTargetAltAz(self, alt, az, slewType='normal'): :param alt: :param a... | bcdd2d0031998661db716247ed2b0051ec9fe11f | <|skeleton|>
class SlewInterface:
def slewSelectedTargetWithDome(self, slewType='normal'):
""":param slewType: :return: success"""
<|body_0|>
def slewTargetAltAz(self, alt, az, slewType='normal'):
""":param alt: :param az: :param slewType: :return:"""
<|body_1|>
def slewTa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SlewInterface:
def slewSelectedTargetWithDome(self, slewType='normal'):
""":param slewType: :return: success"""
azimuthT = self.app.mount.obsSite.AzTarget
altitudeT = self.app.mount.obsSite.AltTarget
if azimuthT is None or altitudeT is None:
return False
azi... | the_stack_v2_python_sparse | mw4/gui/utilities/slewInterface.py | mworion/MountWizzard4 | train | 28 | |
d7cc301b431a7927576741ed488938a1d1e47cdf | [
"self.features = []\nself.csv_url = []\nreturn",
"order = FME_utils.feature_get_attribute(feature, ORDER, True)\nif order == 1:\n url_value = FME_utils.feature_get_attribute(feature, URL, True)\n self.csv_url.append(url_value)\nelse:\n self.features.append(feature)\nreturn",
"for feature in self.featur... | <|body_start_0|>
self.features = []
self.csv_url = []
return
<|end_body_0|>
<|body_start_1|>
order = FME_utils.feature_get_attribute(feature, ORDER, True)
if order == 1:
url_value = FME_utils.feature_get_attribute(feature, URL, True)
self.csv_url.append(u... | Template Class Interface: When using this class, make sure its name is set as the value of the 'Class to Process Features' transformer parameter. This class will update the FME attribute resource{} list by adding 2 attributes if the resources{x}.url attribute is contained in the list of URL read from the CSV file. | SetUrlResources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetUrlResources:
"""Template Class Interface: When using this class, make sure its name is set as the value of the 'Class to Process Features' transformer parameter. This class will update the FME attribute resource{} list by adding 2 attributes if the resources{x}.url attribute is contained in t... | stack_v2_sparse_classes_75kplus_train_069709 | 2,930 | permissive | [
{
"docstring": "Define the variables needed to load and store the incoming features. Parameters ---------- None Returns ------- None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This method stores the incoming FME features. Parameters ---------- feature: FmeFeature ... | 3 | stack_v2_sparse_classes_30k_train_017109 | Implement the Python class `SetUrlResources` described below.
Class description:
Template Class Interface: When using this class, make sure its name is set as the value of the 'Class to Process Features' transformer parameter. This class will update the FME attribute resource{} list by adding 2 attributes if the resou... | Implement the Python class `SetUrlResources` described below.
Class description:
Template Class Interface: When using this class, make sure its name is set as the value of the 'Class to Process Features' transformer parameter. This class will update the FME attribute resource{} list by adding 2 attributes if the resou... | 82368614a2658260c0f09a1b5d341918310626e5 | <|skeleton|>
class SetUrlResources:
"""Template Class Interface: When using this class, make sure its name is set as the value of the 'Class to Process Features' transformer parameter. This class will update the FME attribute resource{} list by adding 2 attributes if the resources{x}.url attribute is contained in t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SetUrlResources:
"""Template Class Interface: When using this class, make sure its name is set as the value of the 'Class to Process Features' transformer parameter. This class will update the FME attribute resource{} list by adding 2 attributes if the resources{x}.url attribute is contained in the list of UR... | the_stack_v2_python_sparse | FME_files/FME_Custom_Transformers/Python/MAP_RESOURCE_ATTRIBUTION_REMOVER_NG.py | federal-geospatial-platform/fgp-metadata-proxy | train | 10 |
95ec0c5f71a39b0a01f3e920960d02e1543c0812 | [
"self.fl_model = fl_model\nself.data_handler = data_handler\nself.hyperparams = hyperparams",
"try:\n if model_update is not None:\n self.fl_model.update_model(model_update)\n logger.info('Local model updated.')\n else:\n logger.info('No model update was provided.')\nexcept Exception as... | <|body_start_0|>
self.fl_model = fl_model
self.data_handler = data_handler
self.hyperparams = hyperparams
<|end_body_0|>
<|body_start_1|>
try:
if model_update is not None:
self.fl_model.update_model(model_update)
logger.info('Local model updat... | LocalTrainingHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalTrainingHandler:
def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs):
"""Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to obtain ... | stack_v2_sparse_classes_75kplus_train_069710 | 4,704 | no_license | [
{
"docstring": "Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to obtain data :type data_handler: `DataHandler` :param hyperparams: Hyperparameters used for training. :type hyper... | 6 | stack_v2_sparse_classes_30k_train_031808 | Implement the Python class `LocalTrainingHandler` described below.
Class description:
Implement the LocalTrainingHandler class.
Method signatures and docstrings:
- def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs): Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model... | Implement the Python class `LocalTrainingHandler` described below.
Class description:
Implement the LocalTrainingHandler class.
Method signatures and docstrings:
- def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs): Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model... | a4cd429484e857b849df08d93688d35e632b3e29 | <|skeleton|>
class LocalTrainingHandler:
def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs):
"""Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to obtain ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalTrainingHandler:
def __init__(self, fl_model, data_handler, hyperparams=None, **kwargs):
"""Initialize LocalTrainingHandler with fl_model, data_handler :param fl_model: model to be trained :type fl_model: `model.FLModel` :param data_handler: data handler that will be used to obtain data :type dat... | the_stack_v2_python_sparse | venv/Lib/site-packages/ibmfl/party/training/local_training_handler.py | yusufcet/healty-hearts | train | 0 | |
76fa9560349137f2b5fce217ef75085fc321a3a2 | [
"toSend = ''\nfor s in self.strings:\n toSend += self.receiver.encode(s)\nfor packetSize in range(1, 20):\n a = self.receiver(maxLength=699)\n got = []\n for s in diceString(toSend, packetSize):\n out, code = a.getNewFrames(s)\n self.assertEqual(decoders.OK, code)\n got.extend(out)\... | <|body_start_0|>
toSend = ''
for s in self.strings:
toSend += self.receiver.encode(s)
for packetSize in range(1, 20):
a = self.receiver(maxLength=699)
got = []
for s in diceString(toSend, packetSize):
out, code = a.getNewFrames(s)
... | CommonTests | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonTests:
def test_buffer(self):
"""Test that when strings are received in chunks of different lengths, they are still parsed correctly."""
<|body_0|>
def test_illegalWithPacketSizes(self):
"""Assert that illegal strings return the correct error code even when the... | stack_v2_sparse_classes_75kplus_train_069711 | 7,794 | permissive | [
{
"docstring": "Test that when strings are received in chunks of different lengths, they are still parsed correctly.",
"name": "test_buffer",
"signature": "def test_buffer(self)"
},
{
"docstring": "Assert that illegal strings return the correct error code even when they arrive in variable packet... | 2 | stack_v2_sparse_classes_30k_train_006003 | Implement the Python class `CommonTests` described below.
Class description:
Implement the CommonTests class.
Method signatures and docstrings:
- def test_buffer(self): Test that when strings are received in chunks of different lengths, they are still parsed correctly.
- def test_illegalWithPacketSizes(self): Assert ... | Implement the Python class `CommonTests` described below.
Class description:
Implement the CommonTests class.
Method signatures and docstrings:
- def test_buffer(self): Test that when strings are received in chunks of different lengths, they are still parsed correctly.
- def test_illegalWithPacketSizes(self): Assert ... | 386e1aeb5197e197e806b3b6a0c11ab9315c8ab5 | <|skeleton|>
class CommonTests:
def test_buffer(self):
"""Test that when strings are received in chunks of different lengths, they are still parsed correctly."""
<|body_0|>
def test_illegalWithPacketSizes(self):
"""Assert that illegal strings return the correct error code even when the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonTests:
def test_buffer(self):
"""Test that when strings are received in chunks of different lengths, they are still parsed correctly."""
toSend = ''
for s in self.strings:
toSend += self.receiver.encode(s)
for packetSize in range(1, 20):
a = self.r... | the_stack_v2_python_sparse | minerva/test_decoders.py | ludiosarchive/Minerva | train | 1 | |
d1e9c43c04e7224da1cca31423d8184a6bb0c038 | [
"self.result = 0\nif self.dfs(root) == 0:\n self.result += 1\nreturn self.result",
"if not node:\n return 2\nleft, right = (self.dfs(node.left), self.dfs(node.right))\nif left == 0 or right == 0:\n self.result += 1\n return 1\nif left == 2 and right == 2:\n return 0\nif left == 1 or right == 1:\n ... | <|body_start_0|>
self.result = 0
if self.dfs(root) == 0:
self.result += 1
return self.result
<|end_body_0|>
<|body_start_1|>
if not node:
return 2
left, right = (self.dfs(node.left), self.dfs(node.right))
if left == 0 or right == 0:
se... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCameraCover(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, node):
"""three states: 0: not cover 1: has camera 2: has no camera but is covered"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.result ... | stack_v2_sparse_classes_75kplus_train_069712 | 1,454 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "minCameraCover",
"signature": "def minCameraCover(self, root)"
},
{
"docstring": "three states: 0: not cover 1: has camera 2: has no camera but is covered",
"name": "dfs",
"signature": "def dfs(self, node)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCameraCover(self, root): :type root: TreeNode :rtype: int
- def dfs(self, node): three states: 0: not cover 1: has camera 2: has no camera but is covered | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCameraCover(self, root): :type root: TreeNode :rtype: int
- def dfs(self, node): three states: 0: not cover 1: has camera 2: has no camera but is covered
<|skeleton|>
cla... | ee79d3437cf47b26a4bca0ec798dc54d7b623453 | <|skeleton|>
class Solution:
def minCameraCover(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def dfs(self, node):
"""three states: 0: not cover 1: has camera 2: has no camera but is covered"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def minCameraCover(self, root):
""":type root: TreeNode :rtype: int"""
self.result = 0
if self.dfs(root) == 0:
self.result += 1
return self.result
def dfs(self, node):
"""three states: 0: not cover 1: has camera 2: has no camera but is covered... | the_stack_v2_python_sparse | Algorithm/Python/968.binary-tree-cameras.py | WuLC/LeetCode | train | 29 | |
3be8d7d9a61a6c4d31bfb4718c69827b0279d4d3 | [
"if slt_num == 0:\n self.MF_root = os.path.join(data_path, 'U_V', mode)\nelse:\n self.MF_root = os.path.join(data_path, 'U_V', str(slt_num) + '_' + mode)\nif not os.path.exists(self.MF_root):\n os.makedirs(self.MF_root)\nself.mashup_emb_df, self.api_emb_df = (None, None)",
"if self.mashup_emb_df is None ... | <|body_start_0|>
if slt_num == 0:
self.MF_root = os.path.join(data_path, 'U_V', mode)
else:
self.MF_root = os.path.join(data_path, 'U_V', str(slt_num) + '_' + mode)
if not os.path.exists(self.MF_root):
os.makedirs(self.MF_root)
self.mashup_emb_df, self... | MF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MF:
def __init__(self, data_path, mode, slt_num=0):
"""根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法"""
<|body_0|>
def get_mf_embedding(self, train_mashup_api_list, mode):
""":param train_mashup_api_list: 训练集 :param mode: :re... | stack_v2_sparse_classes_75kplus_train_069713 | 6,194 | no_license | [
{
"docstring": "根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法",
"name": "__init__",
"signature": "def __init__(self, data_path, mode, slt_num=0)"
},
{
"docstring": ":param train_mashup_api_list: 训练集 :param mode: :return: df形式,id是其索引, embedding列的列名是embedd... | 2 | stack_v2_sparse_classes_30k_train_002498 | Implement the Python class `MF` described below.
Class description:
Implement the MF class.
Method signatures and docstrings:
- def __init__(self, data_path, mode, slt_num=0): 根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法
- def get_mf_embedding(self, train_mashup_api_list, mo... | Implement the Python class `MF` described below.
Class description:
Implement the MF class.
Method signatures and docstrings:
- def __init__(self, data_path, mode, slt_num=0): 根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法
- def get_mf_embedding(self, train_mashup_api_list, mo... | 8acad55835cce1c76eac44e5694c89741bba12dc | <|skeleton|>
class MF:
def __init__(self, data_path, mode, slt_num=0):
"""根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法"""
<|body_0|>
def get_mf_embedding(self, train_mashup_api_list, mode):
""":param train_mashup_api_list: 训练集 :param mode: :re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MF:
def __init__(self, data_path, mode, slt_num=0):
"""根据训练集,调用其他MF/GE的库,得到mashup/api的embedding :param data_path: 哪种数据 :param mode: 使用哪种矩阵分解方法"""
if slt_num == 0:
self.MF_root = os.path.join(data_path, 'U_V', mode)
else:
self.MF_root = os.path.join(data_path, 'U... | the_stack_v2_python_sparse | mf/get_mf_embedding.py | xiaotret/DLISR | train | 0 | |
3e6a2a9ff70d1d31efee615c23678b3a41881d77 | [
"super(PositionalEncoding, self).__init__()\nposition_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for pos in range(max_seq_len)])\nposition_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])\nposition_encoding[:, 1::2] = np.cos(position_encoding[:, 1::2])\npad_... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
position_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for pos in range(max_seq_len)])
position_encoding[:, 0::2] = np.sin(position_encoding[:, 0::2])
position_encoding[:, 1::2] =... | PositionalEncoding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
<|body_0|>
def forward(self, input_len):
"""神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回... | stack_v2_sparse_classes_75kplus_train_069714 | 16,292 | permissive | [
{
"docstring": "初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度",
"name": "__init__",
"signature": "def __init__(self, d_model, max_seq_len)"
},
{
"docstring": "神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回这一批序列的位置编码,进行了对齐。",
"nam... | 2 | null | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model, max_seq_len): 初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度
- def forward(self, input_len): 神经网络的前向传播。 Args:... | Implement the Python class `PositionalEncoding` described below.
Class description:
Implement the PositionalEncoding class.
Method signatures and docstrings:
- def __init__(self, d_model, max_seq_len): 初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度
- def forward(self, input_len): 神经网络的前向传播。 Args:... | c360e81624296c9243fd662dea618042164e0aa7 | <|skeleton|>
class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
<|body_0|>
def forward(self, input_len):
"""神经网络的前向传播。 Args: input_len: 一个张量,形状为[BATCH_SIZE, 1]。每一个张量的值代表这一批文本序列中对应的长度。 Returns: 返回... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding:
def __init__(self, d_model, max_seq_len):
"""初始化。 Args: d_model: 一个标量。模型的维度,论文默认是512 max_seq_len: 一个标量。文本序列的最大长度"""
super(PositionalEncoding, self).__init__()
position_encoding = np.array([[pos / np.power(10000, 2.0 * (j // 2) / d_model) for j in range(d_model)] for... | the_stack_v2_python_sparse | torch-predict-next-word/transformer/transformer_model.py | flashlin/Samples | train | 3 | |
e62579c8fc3a3948f473d6afad99b944915599cb | [
"self.df = df\nself.stop_words = set(stopwords.words('english') + words_to_remove)\nself.f_name = f_name\nself.process_column = process_column\nself.tokenizer = RegexpTokenizer(token)\nself.__did_process = False\nself.exp_df = None",
"if self.__did_process:\n return (self.df, self.exp_df)\nself.df[self.process... | <|body_start_0|>
self.df = df
self.stop_words = set(stopwords.words('english') + words_to_remove)
self.f_name = f_name
self.process_column = process_column
self.tokenizer = RegexpTokenizer(token)
self.__did_process = False
self.exp_df = None
<|end_body_0|>
<|body... | PreProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreProcessor:
def __init__(self, df: pd.DataFrame, words_to_remove: list, f_name: str, process_column: str='sentence', token: str='\\w+'):
"""df['sentence'] needs to be string"""
<|body_0|>
def process(self) -> (pd.DataFrame, pd.DataFrame):
"""df['sentence'] is an ar... | stack_v2_sparse_classes_75kplus_train_069715 | 3,513 | permissive | [
{
"docstring": "df['sentence'] needs to be string",
"name": "__init__",
"signature": "def __init__(self, df: pd.DataFrame, words_to_remove: list, f_name: str, process_column: str='sentence', token: str='\\\\w+')"
},
{
"docstring": "df['sentence'] is an array of tokenized words based on processin... | 2 | stack_v2_sparse_classes_30k_train_018558 | Implement the Python class `PreProcessor` described below.
Class description:
Implement the PreProcessor class.
Method signatures and docstrings:
- def __init__(self, df: pd.DataFrame, words_to_remove: list, f_name: str, process_column: str='sentence', token: str='\\w+'): df['sentence'] needs to be string
- def proce... | Implement the Python class `PreProcessor` described below.
Class description:
Implement the PreProcessor class.
Method signatures and docstrings:
- def __init__(self, df: pd.DataFrame, words_to_remove: list, f_name: str, process_column: str='sentence', token: str='\\w+'): df['sentence'] needs to be string
- def proce... | 91f5ade1984e84fd252fbc76d72f0ee8bd5c96d0 | <|skeleton|>
class PreProcessor:
def __init__(self, df: pd.DataFrame, words_to_remove: list, f_name: str, process_column: str='sentence', token: str='\\w+'):
"""df['sentence'] needs to be string"""
<|body_0|>
def process(self) -> (pd.DataFrame, pd.DataFrame):
"""df['sentence'] is an ar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreProcessor:
def __init__(self, df: pd.DataFrame, words_to_remove: list, f_name: str, process_column: str='sentence', token: str='\\w+'):
"""df['sentence'] needs to be string"""
self.df = df
self.stop_words = set(stopwords.words('english') + words_to_remove)
self.f_name = f_na... | the_stack_v2_python_sparse | mini-project-2/pre_process/PreProcessor.py | ding-ma/applied-ml | train | 0 | |
ae4e3880ffa17975430fea490f616daefa904fd9 | [
"config = ContainerConfig('shipper/base', \"echo 'hi'\")\nexpected = {'AttachStderr': False, 'AttachStdin': False, 'AttachStdout': False, 'Cmd': ['echo', 'hi'], 'Dns': None, 'Env': None, 'Hostname': None, 'Image': 'shipper/base', 'Memory': 0, 'OpenStdin': False, 'StdinOnce': False, 'ExposedPorts': {}, 'Tty': False,... | <|body_start_0|>
config = ContainerConfig('shipper/base', "echo 'hi'")
expected = {'AttachStderr': False, 'AttachStdin': False, 'AttachStdout': False, 'Cmd': ['echo', 'hi'], 'Dns': None, 'Env': None, 'Hostname': None, 'Image': 'shipper/base', 'Memory': 0, 'OpenStdin': False, 'StdinOnce': False, 'Exposed... | Tests container wrappers | ShipperContainerTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShipperContainerTestCase:
"""Tests container wrappers"""
def test_container_config_defaults(self):
"""Makes sure defaults for container config function are sane."""
<|body_0|>
def test_container_config(self):
"""Make sure all parameters are converted properly and... | stack_v2_sparse_classes_75kplus_train_069716 | 49,482 | no_license | [
{
"docstring": "Makes sure defaults for container config function are sane.",
"name": "test_container_config_defaults",
"signature": "def test_container_config_defaults(self)"
},
{
"docstring": "Make sure all parameters are converted properly and to the right properties.",
"name": "test_cont... | 2 | stack_v2_sparse_classes_30k_train_004833 | Implement the Python class `ShipperContainerTestCase` described below.
Class description:
Tests container wrappers
Method signatures and docstrings:
- def test_container_config_defaults(self): Makes sure defaults for container config function are sane.
- def test_container_config(self): Make sure all parameters are c... | Implement the Python class `ShipperContainerTestCase` described below.
Class description:
Tests container wrappers
Method signatures and docstrings:
- def test_container_config_defaults(self): Makes sure defaults for container config function are sane.
- def test_container_config(self): Make sure all parameters are c... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class ShipperContainerTestCase:
"""Tests container wrappers"""
def test_container_config_defaults(self):
"""Makes sure defaults for container config function are sane."""
<|body_0|>
def test_container_config(self):
"""Make sure all parameters are converted properly and... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShipperContainerTestCase:
"""Tests container wrappers"""
def test_container_config_defaults(self):
"""Makes sure defaults for container config function are sane."""
config = ContainerConfig('shipper/base', "echo 'hi'")
expected = {'AttachStderr': False, 'AttachStdin': False, 'Atta... | the_stack_v2_python_sparse | repoData/mailgun-shipper/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
a9cb6a3513a09023b92674b7bae47bd27cbaeac7 | [
"self.gpf_core.float()\nself.likelihood.train()\noptimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)\nmll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gpf_core)\nfor _ in range(500):\n optimizer.zero_grad()\n output = self.gpf_core(self.tensor_x)\n loss = -mll... | <|body_start_0|>
self.gpf_core.float()
self.likelihood.train()
optimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gpf_core)
for _ in range(500):
optimizer.zero_grad()
... | PytorchGPFitter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PytorchGPFitter:
def fit_gp(self):
"""Fit the GP according to options."""
<|body_0|>
def get_next_gp(self):
"""Get the next GP from previously fitted. Returns: GPWrapper object."""
<|body_1|>
def _init_gpf(self):
"""Initialize the GP fitter."""
... | stack_v2_sparse_classes_75kplus_train_069717 | 6,453 | permissive | [
{
"docstring": "Fit the GP according to options.",
"name": "fit_gp",
"signature": "def fit_gp(self)"
},
{
"docstring": "Get the next GP from previously fitted. Returns: GPWrapper object.",
"name": "get_next_gp",
"signature": "def get_next_gp(self)"
},
{
"docstring": "Initialize t... | 3 | stack_v2_sparse_classes_30k_train_009441 | Implement the Python class `PytorchGPFitter` described below.
Class description:
Implement the PytorchGPFitter class.
Method signatures and docstrings:
- def fit_gp(self): Fit the GP according to options.
- def get_next_gp(self): Get the next GP from previously fitted. Returns: GPWrapper object.
- def _init_gpf(self)... | Implement the Python class `PytorchGPFitter` described below.
Class description:
Implement the PytorchGPFitter class.
Method signatures and docstrings:
- def fit_gp(self): Fit the GP according to options.
- def get_next_gp(self): Get the next GP from previously fitted. Returns: GPWrapper object.
- def _init_gpf(self)... | fb330ec4ac2ed0f6167eebd849c23fe61692c11c | <|skeleton|>
class PytorchGPFitter:
def fit_gp(self):
"""Fit the GP according to options."""
<|body_0|>
def get_next_gp(self):
"""Get the next GP from previously fitted. Returns: GPWrapper object."""
<|body_1|>
def _init_gpf(self):
"""Initialize the GP fitter."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PytorchGPFitter:
def fit_gp(self):
"""Fit the GP according to options."""
self.gpf_core.float()
self.likelihood.train()
optimizer = torch.optim.Adam([{'params': self.gpf_core.parameters()}], lr=0.1)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihood, self.gp... | the_stack_v2_python_sparse | src/gp/gpytorch_interface.py | haowenCS/OCBO_offline | train | 0 | |
c2135d848f3f8217e39450f315f2cd5057342b24 | [
"self._ownercol = None\nself._idxname = idxname\nself._is_asc: bool = True\nif isinstance(is_asc, bool):\n self._is_asc = is_asc\nself._initialed_conns: dict = {}\nself._initialed_conns_locker = threading.RLock()",
"if col is None:\n raise Exception('Invalid SqliteColumn object')\nself._ownercol = col",
"... | <|body_start_0|>
self._ownercol = None
self._idxname = idxname
self._is_asc: bool = True
if isinstance(is_asc, bool):
self._is_asc = is_asc
self._initialed_conns: dict = {}
self._initialed_conns_locker = threading.RLock()
<|end_body_0|>
<|body_start_1|>
... | represents a sqlite column index ownercol: the owner SqliteColumn object of current SqliteIndex object idxname: the name of current index, if this is None, will automatically generate an unique index name | SqliteIndex | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SqliteIndex:
"""represents a sqlite column index ownercol: the owner SqliteColumn object of current SqliteIndex object idxname: the name of current index, if this is None, will automatically generate an unique index name"""
def __init__(self, idxname: str=None, is_asc: bool=True):
""... | stack_v2_sparse_classes_75kplus_train_069718 | 17,742 | permissive | [
{
"docstring": "index name can be None",
"name": "__init__",
"signature": "def __init__(self, idxname: str=None, is_asc: bool=True)"
},
{
"docstring": "为当前SqliteIndex索引设置所属SqliteColumn列",
"name": "set_owner_column",
"signature": "def set_owner_column(self, col)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_030537 | Implement the Python class `SqliteIndex` described below.
Class description:
represents a sqlite column index ownercol: the owner SqliteColumn object of current SqliteIndex object idxname: the name of current index, if this is None, will automatically generate an unique index name
Method signatures and docstrings:
- ... | Implement the Python class `SqliteIndex` described below.
Class description:
represents a sqlite column index ownercol: the owner SqliteColumn object of current SqliteIndex object idxname: the name of current index, if this is None, will automatically generate an unique index name
Method signatures and docstrings:
- ... | 8f05a6b91fc205960edd57f9076facec04f49a1a | <|skeleton|>
class SqliteIndex:
"""represents a sqlite column index ownercol: the owner SqliteColumn object of current SqliteIndex object idxname: the name of current index, if this is None, will automatically generate an unique index name"""
def __init__(self, idxname: str=None, is_asc: bool=True):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SqliteIndex:
"""represents a sqlite column index ownercol: the owner SqliteColumn object of current SqliteIndex object idxname: the name of current index, if this is None, will automatically generate an unique index name"""
def __init__(self, idxname: str=None, is_asc: bool=True):
"""index name c... | the_stack_v2_python_sparse | savecode/pythonpackages/commonbaby/sql/sqlite/sqlitetable.py | cbbbbbbbb/sspywork | train | 0 |
9016e3e7dd1cde65bd0b6292fff87f4529038626 | [
"category_schema = CategorySchema()\ncategory_data = request.get_json()\nvalidated_category_data, errors = category_schema.load(category_data)\ncategory_name = validated_category_data.get('name', None)\nif errors:\n return (dict(status='fail', message=errors), 400)\ncategory_existant = Category.find_first(name=c... | <|body_start_0|>
category_schema = CategorySchema()
category_data = request.get_json()
validated_category_data, errors = category_schema.load(category_data)
category_name = validated_category_data.get('name', None)
if errors:
return (dict(status='fail', message=errors... | CategoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryView:
def post(self):
"""add new categories"""
<|body_0|>
def get(self):
"""Fetch categories"""
<|body_1|>
def patch(self, category_id):
"""update a category"""
<|body_2|>
def delete(self, category_id):
"""Delete a ca... | stack_v2_sparse_classes_75kplus_train_069719 | 3,327 | no_license | [
{
"docstring": "add new categories",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Fetch categories",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "update a category",
"name": "patch",
"signature": "def patch(self, category_id)"
},
... | 4 | stack_v2_sparse_classes_30k_train_019523 | Implement the Python class `CategoryView` described below.
Class description:
Implement the CategoryView class.
Method signatures and docstrings:
- def post(self): add new categories
- def get(self): Fetch categories
- def patch(self, category_id): update a category
- def delete(self, category_id): Delete a category | Implement the Python class `CategoryView` described below.
Class description:
Implement the CategoryView class.
Method signatures and docstrings:
- def post(self): add new categories
- def get(self): Fetch categories
- def patch(self, category_id): update a category
- def delete(self, category_id): Delete a category
... | a3d978140bed77ac71d62a3562fc5e38adcb66e9 | <|skeleton|>
class CategoryView:
def post(self):
"""add new categories"""
<|body_0|>
def get(self):
"""Fetch categories"""
<|body_1|>
def patch(self, category_id):
"""update a category"""
<|body_2|>
def delete(self, category_id):
"""Delete a ca... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CategoryView:
def post(self):
"""add new categories"""
category_schema = CategorySchema()
category_data = request.get_json()
validated_category_data, errors = category_schema.load(category_data)
category_name = validated_category_data.get('name', None)
if errors... | the_stack_v2_python_sparse | app/controllers/category.py | CMBTech/chatbot-server | train | 0 | |
b091b88ebb2d0e5ab42099a5555ca2a8b6e9353a | [
"super().__init__()\nself.__key = key\nself.__digest_size = dgst_size\nself.__mode_dict = {'MD5': MD5, 'SHA256': SHA256, 'SHA512': SHA512}\nif mode in self.__mode_dict.keys():\n self.__mode = self.__mode_dict[mode]\nelse:\n self.__mode = SHA512",
"h = HMAC.new(self.__key, digestmod=self.__mode)\nhmac = h.up... | <|body_start_0|>
super().__init__()
self.__key = key
self.__digest_size = dgst_size
self.__mode_dict = {'MD5': MD5, 'SHA256': SHA256, 'SHA512': SHA512}
if mode in self.__mode_dict.keys():
self.__mode = self.__mode_dict[mode]
else:
self.__mode = SHA... | Abstraction from Crypto.Hash.HMAC and some of its functionalities Attributes ---------- __key : bytes Key to be used in HMAC operations __mode : str Cryptographic hash function to be run in methods. Methods ------- compute_hmac(bytes) -> str Compute hmac verify_hmac(str, bytes) -> bool Verify hmac | OurHMAC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OurHMAC:
"""Abstraction from Crypto.Hash.HMAC and some of its functionalities Attributes ---------- __key : bytes Key to be used in HMAC operations __mode : str Cryptographic hash function to be run in methods. Methods ------- compute_hmac(bytes) -> str Compute hmac verify_hmac(str, bytes) -> boo... | stack_v2_sparse_classes_75kplus_train_069720 | 2,812 | no_license | [
{
"docstring": "Constructor for HMAC object Parameters ---------- __key : bytes Key to be used in encrypt or decrypt operations. __mode : str mode to be run in methods.",
"name": "__init__",
"signature": "def __init__(self, mode, key, dgst_size=512, **kwargs)"
},
{
"docstring": "Compute HMAC Par... | 3 | stack_v2_sparse_classes_30k_test_002273 | Implement the Python class `OurHMAC` described below.
Class description:
Abstraction from Crypto.Hash.HMAC and some of its functionalities Attributes ---------- __key : bytes Key to be used in HMAC operations __mode : str Cryptographic hash function to be run in methods. Methods ------- compute_hmac(bytes) -> str Comp... | Implement the Python class `OurHMAC` described below.
Class description:
Abstraction from Crypto.Hash.HMAC and some of its functionalities Attributes ---------- __key : bytes Key to be used in HMAC operations __mode : str Cryptographic hash function to be run in methods. Methods ------- compute_hmac(bytes) -> str Comp... | d6ddf79a9d8813eef8d9d3b8bb5ce8adbd733e01 | <|skeleton|>
class OurHMAC:
"""Abstraction from Crypto.Hash.HMAC and some of its functionalities Attributes ---------- __key : bytes Key to be used in HMAC operations __mode : str Cryptographic hash function to be run in methods. Methods ------- compute_hmac(bytes) -> str Compute hmac verify_hmac(str, bytes) -> boo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OurHMAC:
"""Abstraction from Crypto.Hash.HMAC and some of its functionalities Attributes ---------- __key : bytes Key to be used in HMAC operations __mode : str Cryptographic hash function to be run in methods. Methods ------- compute_hmac(bytes) -> str Compute hmac verify_hmac(str, bytes) -> bool Verify hmac... | the_stack_v2_python_sparse | Servidor/Service_Server/helpers/OurHMAC.py | ThePommeDeTerre/VerySpecialWill | train | 0 |
2058b3065376a3540f6ed93bac18896d8f24303f | [
"def shortpart():\n ans = ''\n temp = ''\n for i in range(6):\n temp = letters[random.randint(0, 61)]\n ans += temp\n return ans\nif longUrl in long_to_short:\n return 'http://tinyurl.com/' + long_to_short[longUrl]\nelse:\n suffix = shortpart()\n long_to_short[longUrl] = suffix\n ... | <|body_start_0|>
def shortpart():
ans = ''
temp = ''
for i in range(6):
temp = letters[random.randint(0, 61)]
ans += temp
return ans
if longUrl in long_to_short:
return 'http://tinyurl.com/' + long_to_short[longU... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def shortpart... | stack_v2_sparse_classes_75kplus_train_069721 | 1,480 | no_license | [
{
"docstring": "Encodes a URL to a shortened URL.",
"name": "encode",
"signature": "def encode(self, longUrl: str) -> str"
},
{
"docstring": "Decodes a shortened URL to its original URL.",
"name": "decode",
"signature": "def decode(self, shortUrl: str) -> str"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
<|skeleton|>
clas... | fb1a8af64f43fc3386b82a5093ff38cd0d45ebb8 | <|skeleton|>
class Solution:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
def shortpart():
ans = ''
temp = ''
for i in range(6):
temp = letters[random.randint(0, 61)]
ans += temp
return ans
i... | the_stack_v2_python_sparse | 535_Encode and Decode.py | mingyuema1217/leetcode-practice | train | 0 | |
446cc06fb6cff60bd0fb87acfd0a07165a8ef1d8 | [
"free = float(self.coordinator.data['system_stats']['memory']['free'])\nif self.entity_description.key == 'memory_free':\n return free\ntotal = float(self.coordinator.data['system_stats']['memory']['total'])\nused = total - free\nif self.entity_description.key == 'memory_used':\n return used\nif self.entity_d... | <|body_start_0|>
free = float(self.coordinator.data['system_stats']['memory']['free'])
if self.entity_description.key == 'memory_free':
return free
total = float(self.coordinator.data['system_stats']['memory']['total'])
used = total - free
if self.entity_description.k... | A QNAP sensor that monitors memory stats. | QNAPMemorySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QNAPMemorySensor:
"""A QNAP sensor that monitors memory stats."""
def native_value(self):
"""Return the state of the sensor."""
<|body_0|>
def extra_state_attributes(self):
"""Return the state attributes."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069722 | 17,563 | permissive | [
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"signature": "def native_value(self)"
},
{
"docstring": "Return the state attributes.",
"name": "extra_state_attributes",
"signature": "def extra_state_attributes(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027745 | Implement the Python class `QNAPMemorySensor` described below.
Class description:
A QNAP sensor that monitors memory stats.
Method signatures and docstrings:
- def native_value(self): Return the state of the sensor.
- def extra_state_attributes(self): Return the state attributes. | Implement the Python class `QNAPMemorySensor` described below.
Class description:
A QNAP sensor that monitors memory stats.
Method signatures and docstrings:
- def native_value(self): Return the state of the sensor.
- def extra_state_attributes(self): Return the state attributes.
<|skeleton|>
class QNAPMemorySensor:... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class QNAPMemorySensor:
"""A QNAP sensor that monitors memory stats."""
def native_value(self):
"""Return the state of the sensor."""
<|body_0|>
def extra_state_attributes(self):
"""Return the state attributes."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QNAPMemorySensor:
"""A QNAP sensor that monitors memory stats."""
def native_value(self):
"""Return the state of the sensor."""
free = float(self.coordinator.data['system_stats']['memory']['free'])
if self.entity_description.key == 'memory_free':
return free
to... | the_stack_v2_python_sparse | homeassistant/components/qnap/sensor.py | home-assistant/core | train | 35,501 |
0a76dda96da294e4b6a991576766591671bb12ed | [
"self.snmp_object = snmp_object\ntest_oid = '.1.3.6.1.4.1.9.9.128.1.1.1.1.3'\nsuper().__init__(snmp_object, test_oid, tags=['layer1'])",
"final = defaultdict(lambda: defaultdict(dict))\nvalues = self.cviroutedvlanifindex()\nfor key, value in values.items():\n final[key]['cviRoutedVlanIfIndex'] = value\nreturn ... | <|body_start_0|>
self.snmp_object = snmp_object
test_oid = '.1.3.6.1.4.1.9.9.128.1.1.1.1.3'
super().__init__(snmp_object, test_oid, tags=['layer1'])
<|end_body_0|>
<|body_start_1|>
final = defaultdict(lambda: defaultdict(dict))
values = self.cviroutedvlanifindex()
for ke... | Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the OID, False if not. layer1: Returns all needed layer 1 MIB inf... | CiscoVlanIftableRelationshipQuery | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the ... | stack_v2_sparse_classes_75kplus_train_069723 | 2,856 | permissive | [
{
"docstring": "Function for intializing the class. Args: snmp_object: SNMP Interact class object from snmp_manager.py Returns: None",
"name": "__init__",
"signature": "def __init__(self, snmp_object)"
},
{
"docstring": "Get layer 1 data from device. Args: None Returns: final: Final results",
... | 3 | stack_v2_sparse_classes_30k_train_015491 | Implement the Python class `CiscoVlanIftableRelationshipQuery` described below.
Class description:
Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True i... | Implement the Python class `CiscoVlanIftableRelationshipQuery` described below.
Class description:
Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True i... | ae82589fbbab77fef6d6be09c1fcca5846f595a8 | <|skeleton|>
class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CiscoVlanIftableRelationshipQuery:
"""Class interacts with CISCO-VLAN-IFTABLE-RELATIONSHIP-MIB. Args: None Returns: None Key Methods: supported: Queries the device to determine whether the MIB is supported using a known OID defined in the MIB. Returns True if the device returns a response to the OID, False if... | the_stack_v2_python_sparse | switchmap/snmp/cisco/mib_ciscovlaniftablerelationship.py | PalisadoesFoundation/switchmap-ng | train | 8 |
daf7ce02d1a3d3a275d7e2a771f708388619e0df | [
"self.log.info('login from GitHub')\ncode = context.get('code')\nif not code:\n return None\naccess_token = self.get_token(code)\nself.log.info('Successfully get access token from github using code %s' % code)\nuser_info = self.get_user_info(access_token)\nemail_list = self.get_emails(access_token)\nself.log.inf... | <|body_start_0|>
self.log.info('login from GitHub')
code = context.get('code')
if not code:
return None
access_token = self.get_token(code)
self.log.info('Successfully get access token from github using code %s' % code)
user_info = self.get_user_info(access_to... | Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes:: | GithubLogin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GithubLogin:
"""Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::"""
def login(self, context):
"""github Login :type context: Context :param context: :rtype: dict :return: token and instance of user... | stack_v2_sparse_classes_75kplus_train_069724 | 17,886 | permissive | [
{
"docstring": "github Login :type context: Context :param context: :rtype: dict :return: token and instance of user",
"name": "login",
"signature": "def login(self, context)"
},
{
"docstring": "Get github access token :type code: str :param code: :rtype: str :return: access token",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_053150 | Implement the Python class `GithubLogin` described below.
Class description:
Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::
Method signatures and docstrings:
- def login(self, context): github Login :type context: Context :param ... | Implement the Python class `GithubLogin` described below.
Class description:
Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::
Method signatures and docstrings:
- def login(self, context): github Login :type context: Context :param ... | 945c4fd2755f5b0dea11e54eb649eeb37ec93d01 | <|skeleton|>
class GithubLogin:
"""Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::"""
def login(self, context):
"""github Login :type context: Context :param context: :rtype: dict :return: token and instance of user... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GithubLogin:
"""Sign in with github docs: https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#web-application-flow .. notes::"""
def login(self, context):
"""github Login :type context: Context :param context: :rtype: dict :return: token and instance of user"""
s... | the_stack_v2_python_sparse | open-hackathon-server/src/hackathon/user/oauth_login.py | kaiyuanshe/open-hackathon | train | 46 |
fddfd490915390b073799abc5ff476de86978f4a | [
"if self.context.digitally_available:\n manager = queryMultiAdapter((self.context, self.request), ICheckinCheckoutManager)\n if manager:\n return manager.is_checkout_allowed()\nreturn False",
"manager = queryMultiAdapter((self.context, self.request), ICheckinCheckoutManager)\nif manager:\n return ... | <|body_start_0|>
if self.context.digitally_available:
manager = queryMultiAdapter((self.context, self.request), ICheckinCheckoutManager)
if manager:
return manager.is_checkout_allowed()
return False
<|end_body_0|>
<|body_start_1|>
manager = queryMultiAdap... | The controller view gives infos about the current document concerning checkin / checkout. | CheckinCheckoutController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckinCheckoutController:
"""The controller view gives infos about the current document concerning checkin / checkout."""
def is_checkout_allowed(self):
"""Checks whether checkout is allowed or not."""
<|body_0|>
def is_checkin_allowed(self):
"""Checks whether c... | stack_v2_sparse_classes_75kplus_train_069725 | 1,632 | no_license | [
{
"docstring": "Checks whether checkout is allowed or not.",
"name": "is_checkout_allowed",
"signature": "def is_checkout_allowed(self)"
},
{
"docstring": "Checks whether checkin is allowed or not.",
"name": "is_checkin_allowed",
"signature": "def is_checkin_allowed(self)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_005611 | Implement the Python class `CheckinCheckoutController` described below.
Class description:
The controller view gives infos about the current document concerning checkin / checkout.
Method signatures and docstrings:
- def is_checkout_allowed(self): Checks whether checkout is allowed or not.
- def is_checkin_allowed(se... | Implement the Python class `CheckinCheckoutController` described below.
Class description:
The controller view gives infos about the current document concerning checkin / checkout.
Method signatures and docstrings:
- def is_checkout_allowed(self): Checks whether checkout is allowed or not.
- def is_checkin_allowed(se... | a01bec6c00d203c21a1b0449f8d489d0033c02b7 | <|skeleton|>
class CheckinCheckoutController:
"""The controller view gives infos about the current document concerning checkin / checkout."""
def is_checkout_allowed(self):
"""Checks whether checkout is allowed or not."""
<|body_0|>
def is_checkin_allowed(self):
"""Checks whether c... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckinCheckoutController:
"""The controller view gives infos about the current document concerning checkin / checkout."""
def is_checkout_allowed(self):
"""Checks whether checkout is allowed or not."""
if self.context.digitally_available:
manager = queryMultiAdapter((self.con... | the_stack_v2_python_sparse | opengever/document/checkout/controller.py | 4teamwork/opengever.core | train | 19 |
104757768b979c59f9284a42c0d9ad5e5611bef7 | [
"self.screen_width = 1300\nself.screen_height = 800\nself.image = pygame.image.load('blue_bg.png')\nself.ship_speed_factor = 20\nself.bullet_speed_factor = 15\nself.bullet_width = 5\nself.bullet_height = 25\nself.bullet_color = (255, 0, 0)\nself.bullets_allowed = 30\nself.alien_speed_factor = 3\nself.speedup_scale ... | <|body_start_0|>
self.screen_width = 1300
self.screen_height = 800
self.image = pygame.image.load('blue_bg.png')
self.ship_speed_factor = 20
self.bullet_speed_factor = 15
self.bullet_width = 5
self.bullet_height = 25
self.bullet_color = (255, 0, 0)
... | Класс для хранения всех настроек игры Alien Invasion. | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion."""
def __init__(self):
"""Инициализирует настройки игры."""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры."""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_069726 | 2,153 | no_license | [
{
"docstring": "Инициализирует настройки игры.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Инициализирует настройки, изменяющиеся в ходе игры.",
"name": "initialize_dynamic_settings",
"signature": "def initialize_dynamic_settings(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_044265 | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion.
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры.
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры.
- def incr... | Implement the Python class `Settings` described below.
Class description:
Класс для хранения всех настроек игры Alien Invasion.
Method signatures and docstrings:
- def __init__(self): Инициализирует настройки игры.
- def initialize_dynamic_settings(self): Инициализирует настройки, изменяющиеся в ходе игры.
- def incr... | a70c56c3b3298766acfe220fc0fad7978baa3290 | <|skeleton|>
class Settings:
"""Класс для хранения всех настроек игры Alien Invasion."""
def __init__(self):
"""Инициализирует настройки игры."""
<|body_0|>
def initialize_dynamic_settings(self):
"""Инициализирует настройки, изменяющиеся в ходе игры."""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Settings:
"""Класс для хранения всех настроек игры Alien Invasion."""
def __init__(self):
"""Инициализирует настройки игры."""
self.screen_width = 1300
self.screen_height = 800
self.image = pygame.image.load('blue_bg.png')
self.ship_speed_factor = 20
self.b... | the_stack_v2_python_sparse | Game Alien/setgame.py | semen-ksv/Python_learn | train | 0 |
8784258c18c3f1c5c5f3f22bcc24532c325726a9 | [
"nodes = []\nfor inst in self.op.instances:\n if inst.iallocator is not None:\n raise errors.OpPrereqError('iallocator are not allowed to be set on instance objects', errors.ECODE_INVAL)\n nodes.append(bool(inst.pnode))\n if inst.disk_template in constants.DTS_INT_MIRROR:\n nodes.append(bool(... | <|body_start_0|>
nodes = []
for inst in self.op.instances:
if inst.iallocator is not None:
raise errors.OpPrereqError('iallocator are not allowed to be set on instance objects', errors.ECODE_INVAL)
nodes.append(bool(inst.pnode))
if inst.disk_template i... | Allocates multiple instances at the same time. | LUInstanceMultiAlloc | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LUInstanceMultiAlloc:
"""Allocates multiple instances at the same time."""
def CheckArguments(self):
"""Check arguments."""
<|body_0|>
def ExpandNames(self):
"""Calculate the locks."""
<|body_1|>
def CheckPrereq(self):
"""Check prerequisite."... | stack_v2_sparse_classes_75kplus_train_069727 | 31,763 | permissive | [
{
"docstring": "Check arguments.",
"name": "CheckArguments",
"signature": "def CheckArguments(self)"
},
{
"docstring": "Calculate the locks.",
"name": "ExpandNames",
"signature": "def ExpandNames(self)"
},
{
"docstring": "Check prerequisite.",
"name": "CheckPrereq",
"sign... | 5 | stack_v2_sparse_classes_30k_train_007347 | Implement the Python class `LUInstanceMultiAlloc` described below.
Class description:
Allocates multiple instances at the same time.
Method signatures and docstrings:
- def CheckArguments(self): Check arguments.
- def ExpandNames(self): Calculate the locks.
- def CheckPrereq(self): Check prerequisite.
- def _Construc... | Implement the Python class `LUInstanceMultiAlloc` described below.
Class description:
Allocates multiple instances at the same time.
Method signatures and docstrings:
- def CheckArguments(self): Check arguments.
- def ExpandNames(self): Calculate the locks.
- def CheckPrereq(self): Check prerequisite.
- def _Construc... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class LUInstanceMultiAlloc:
"""Allocates multiple instances at the same time."""
def CheckArguments(self):
"""Check arguments."""
<|body_0|>
def ExpandNames(self):
"""Calculate the locks."""
<|body_1|>
def CheckPrereq(self):
"""Check prerequisite."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LUInstanceMultiAlloc:
"""Allocates multiple instances at the same time."""
def CheckArguments(self):
"""Check arguments."""
nodes = []
for inst in self.op.instances:
if inst.iallocator is not None:
raise errors.OpPrereqError('iallocator are not allowed ... | the_stack_v2_python_sparse | lib/cmdlib/instance.py | ganeti/ganeti | train | 465 |
59b536f874545d188c6553b216f1b8244d745607 | [
"l_obj = IrrigationZoneData()\nXmlConfigTools.read_base_object_xml(l_obj, p_xml)\nl_obj.Duration = PutGetXML.get_time_from_xml(p_xml, 'Duration')\nl_obj.EmitterCount = PutGetXML.get_int_from_xml(p_xml, 'EmitterCount', 0)\nl_obj.EmitterType = PutGetXML.get_text_from_xml(p_xml, 'EmitterType')\nl_obj.Next = PutGetXML.... | <|body_start_0|>
l_obj = IrrigationZoneData()
XmlConfigTools.read_base_object_xml(l_obj, p_xml)
l_obj.Duration = PutGetXML.get_time_from_xml(p_xml, 'Duration')
l_obj.EmitterCount = PutGetXML.get_int_from_xml(p_xml, 'EmitterCount', 0)
l_obj.EmitterType = PutGetXML.get_text_from_xm... | Xml | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Xml:
def _read_one_zone(p_xml):
"""@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in"""
<|body_0|>
def _write_one_zone(p_obj):
"""@param p_obj: is one zone object @return the XML for one Zone"""
... | stack_v2_sparse_classes_75kplus_train_069728 | 6,327 | no_license | [
{
"docstring": "@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in",
"name": "_read_one_zone",
"signature": "def _read_one_zone(p_xml)"
},
{
"docstring": "@param p_obj: is one zone object @return the XML for one Zone",
"na... | 6 | stack_v2_sparse_classes_30k_train_044470 | Implement the Python class `Xml` described below.
Class description:
Implement the Xml class.
Method signatures and docstrings:
- def _read_one_zone(p_xml): @param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in
- def _write_one_zone(p_obj): @param p_o... | Implement the Python class `Xml` described below.
Class description:
Implement the Xml class.
Method signatures and docstrings:
- def _read_one_zone(p_xml): @param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in
- def _write_one_zone(p_obj): @param p_o... | 8ccbbd1494b7b33ff5099d321cda634fbb254ceb | <|skeleton|>
class Xml:
def _read_one_zone(p_xml):
"""@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in"""
<|body_0|>
def _write_one_zone(p_obj):
"""@param p_obj: is one zone object @return the XML for one Zone"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Xml:
def _read_one_zone(p_xml):
"""@param p_xml: XML information for one Zone. @return: an IrrigationZone object filled in with data from the XML passed in"""
l_obj = IrrigationZoneData()
XmlConfigTools.read_base_object_xml(l_obj, p_xml)
l_obj.Duration = PutGetXML.get_time_from... | the_stack_v2_python_sparse | Project/src/Modules/House/Irrigation/irrigation_xml.py | bopopescu/PyHouse | train | 0 | |
0a15d41669a326813b9736d5f679f23bfb6562c5 | [
"user_id = payload['user_id']\nprobes = await join_blueprints_with(model=mProbe, db=self.db, user_id=user_id)\nprobes_schema = ProbeSchema(many=True)\nprobes_schema.context = {'user': user_id}\ndata, errors = probes_schema.dump(probes)\nif errors:\n return json_response({'error': errors}, status=400)\nreturn jso... | <|body_start_0|>
user_id = payload['user_id']
probes = await join_blueprints_with(model=mProbe, db=self.db, user_id=user_id)
probes_schema = ProbeSchema(many=True)
probes_schema.context = {'user': user_id}
data, errors = probes_schema.dump(probes)
if errors:
r... | Get info, create and remove probes. | Probe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Probe:
"""Get info, create and remove probes."""
async def get(self, payload: type_payload):
"""Get probes."""
<|body_0|>
async def post(self, payload: type_payload):
"""Create new probes."""
<|body_1|>
async def delete(self, payload: type_payload):
... | stack_v2_sparse_classes_75kplus_train_069729 | 3,127 | permissive | [
{
"docstring": "Get probes.",
"name": "get",
"signature": "async def get(self, payload: type_payload)"
},
{
"docstring": "Create new probes.",
"name": "post",
"signature": "async def post(self, payload: type_payload)"
},
{
"docstring": "Delete probes.",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_004855 | Implement the Python class `Probe` described below.
Class description:
Get info, create and remove probes.
Method signatures and docstrings:
- async def get(self, payload: type_payload): Get probes.
- async def post(self, payload: type_payload): Create new probes.
- async def delete(self, payload: type_payload): Dele... | Implement the Python class `Probe` described below.
Class description:
Get info, create and remove probes.
Method signatures and docstrings:
- async def get(self, payload: type_payload): Get probes.
- async def post(self, payload: type_payload): Create new probes.
- async def delete(self, payload: type_payload): Dele... | e94889ce784f4399ca74f78be3bc42a5cd880d70 | <|skeleton|>
class Probe:
"""Get info, create and remove probes."""
async def get(self, payload: type_payload):
"""Get probes."""
<|body_0|>
async def post(self, payload: type_payload):
"""Create new probes."""
<|body_1|>
async def delete(self, payload: type_payload):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Probe:
"""Get info, create and remove probes."""
async def get(self, payload: type_payload):
"""Get probes."""
user_id = payload['user_id']
probes = await join_blueprints_with(model=mProbe, db=self.db, user_id=user_id)
probes_schema = ProbeSchema(many=True)
probes_... | the_stack_v2_python_sparse | probes/views.py | cassinyio/cassiny-spawner | train | 1 |
7e931e92bbc3b465d90830047e283a0f603ffc50 | [
"s1 = Snapshots.load(_id=data['snapshot1'])\ns2 = Snapshots.load(_id=data['snapshot2'])\nif not s1.exists():\n abort(404, 'snapshot1 %s not found' % data['snapshot1'])\nif not s2.exists():\n abort(404, 'snapshot2 %s not found' % data['snapshot2'])\ndata['snapshot1_description'] = s1.description\ndata['snapsho... | <|body_start_0|>
s1 = Snapshots.load(_id=data['snapshot1'])
s2 = Snapshots.load(_id=data['snapshot2'])
if not s1.exists():
abort(404, 'snapshot1 %s not found' % data['snapshot1'])
if not s2.exists():
abort(404, 'snapshot2 %s not found' % data['snapshot2'])
... | ACI Compare REST class | Compare | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Compare:
"""ACI Compare REST class"""
def before_compare_create(cls, data):
"""before compare create ensure snapshots exists and are from the same fabric"""
<|body_0|>
def before_compare_delete(cls, filters):
"""delete corresponding CompareResults when deleting C... | stack_v2_sparse_classes_75kplus_train_069730 | 39,352 | no_license | [
{
"docstring": "before compare create ensure snapshots exists and are from the same fabric",
"name": "before_compare_create",
"signature": "def before_compare_create(cls, data)"
},
{
"docstring": "delete corresponding CompareResults when deleting Compare object",
"name": "before_compare_dele... | 5 | stack_v2_sparse_classes_30k_train_002151 | Implement the Python class `Compare` described below.
Class description:
ACI Compare REST class
Method signatures and docstrings:
- def before_compare_create(cls, data): before compare create ensure snapshots exists and are from the same fabric
- def before_compare_delete(cls, filters): delete corresponding CompareRe... | Implement the Python class `Compare` described below.
Class description:
ACI Compare REST class
Method signatures and docstrings:
- def before_compare_create(cls, data): before compare create ensure snapshots exists and are from the same fabric
- def before_compare_delete(cls, filters): delete corresponding CompareRe... | d2576da2f083dfea21d28933e8eca7a8fd885b14 | <|skeleton|>
class Compare:
"""ACI Compare REST class"""
def before_compare_create(cls, data):
"""before compare create ensure snapshots exists and are from the same fabric"""
<|body_0|>
def before_compare_delete(cls, filters):
"""delete corresponding CompareResults when deleting C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Compare:
"""ACI Compare REST class"""
def before_compare_create(cls, data):
"""before compare create ensure snapshots exists and are from the same fabric"""
s1 = Snapshots.load(_id=data['snapshot1'])
s2 = Snapshots.load(_id=data['snapshot2'])
if not s1.exists():
... | the_stack_v2_python_sparse | Service/app/models/aci/compare.py | suhasjanardhan/statechecker | train | 0 |
5e9255ca5c4a452f1eac94b1a78829925f5f5318 | [
"super().__init__(*args, **kwargs)\nself.job_name = job_name\nself.step_name = step_name\nself.catalogue = catalogue\nself.collection = collection\nself.optional = optional or {}\nself.connection = Connection()",
"message = context['task_instance'].xcom_pull(key=context['dag_run'].run_id)\nif message is None:\n ... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.job_name = job_name
self.step_name = step_name
self.catalogue = catalogue
self.collection = collection
self.optional = optional or {}
self.connection = Connection()
<|end_body_0|>
<|body_start_1|>
me... | GOBOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GOBOperator:
def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs):
"""Initializes the GOB operator for the specific workflow"""
<|body_0|>
def execute(self, context):
"""Execute the workflow step Any messa... | stack_v2_sparse_classes_75kplus_train_069731 | 2,281 | no_license | [
{
"docstring": "Initializes the GOB operator for the specific workflow",
"name": "__init__",
"signature": "def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs)"
},
{
"docstring": "Execute the workflow step Any message that is the resu... | 2 | stack_v2_sparse_classes_30k_test_001085 | Implement the Python class `GOBOperator` described below.
Class description:
Implement the GOBOperator class.
Method signatures and docstrings:
- def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs): Initializes the GOB operator for the specific workflow
-... | Implement the Python class `GOBOperator` described below.
Class description:
Implement the GOBOperator class.
Method signatures and docstrings:
- def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs): Initializes the GOB operator for the specific workflow
-... | ae3bca2827a63b6c447d7117d2fb4d84fdfc6cef | <|skeleton|>
class GOBOperator:
def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs):
"""Initializes the GOB operator for the specific workflow"""
<|body_0|>
def execute(self, context):
"""Execute the workflow step Any messa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GOBOperator:
def __init__(self, job_name=None, step_name=None, catalogue=None, collection=None, optional=None, *args, **kwargs):
"""Initializes the GOB operator for the specific workflow"""
super().__init__(*args, **kwargs)
self.job_name = job_name
self.step_name = step_name
... | the_stack_v2_python_sparse | src/plugins/operators/gob_operator.py | Amsterdam/GOB-Airflow | train | 0 | |
45158fd58e4ce66b56d9a8326c5ed35d4829ad6c | [
"if self._user is None:\n self._user = await self._state.get_user(self.user_id)\nreturn self._user",
"if self._genres is None:\n self._genres = await self._state.get_related(self._relationships['genres'])\nreturn self._genres",
"if self._project_challenges is None:\n self._project_challenges = await se... | <|body_start_0|>
if self._user is None:
self._user = await self._state.get_user(self.user_id)
return self._user
<|end_body_0|>
<|body_start_1|>
if self._genres is None:
self._genres = await self._state.get_related(self._relationships['genres'])
return self._genre... | Represents a project on the Nano site | NanoProject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NanoProject:
"""Represents a project on the Nano site"""
async def get_user(self):
"""Get the user associated with this project :return: Single user"""
<|body_0|>
async def get_genres(self):
"""Get the genres associated with this project :return: List of genres""... | stack_v2_sparse_classes_75kplus_train_069732 | 39,056 | permissive | [
{
"docstring": "Get the user associated with this project :return: Single user",
"name": "get_user",
"signature": "async def get_user(self)"
},
{
"docstring": "Get the genres associated with this project :return: List of genres",
"name": "get_genres",
"signature": "async def get_genres(s... | 6 | null | Implement the Python class `NanoProject` described below.
Class description:
Represents a project on the Nano site
Method signatures and docstrings:
- async def get_user(self): Get the user associated with this project :return: Single user
- async def get_genres(self): Get the genres associated with this project :ret... | Implement the Python class `NanoProject` described below.
Class description:
Represents a project on the Nano site
Method signatures and docstrings:
- async def get_user(self): Get the user associated with this project :return: Single user
- async def get_genres(self): Get the genres associated with this project :ret... | 4bf155feec7cb983e8d283d93552902ec85178a2 | <|skeleton|>
class NanoProject:
"""Represents a project on the Nano site"""
async def get_user(self):
"""Get the user associated with this project :return: Single user"""
<|body_0|>
async def get_genres(self):
"""Get the genres associated with this project :return: List of genres""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NanoProject:
"""Represents a project on the Nano site"""
async def get_user(self):
"""Get the user associated with this project :return: Single user"""
if self._user is None:
self._user = await self._state.get_user(self.user_id)
return self._user
async def get_gen... | the_stack_v2_python_sparse | spidertools/common/nano/types.py | CraftSpider/SpiderTools | train | 6 |
4af76edc472e5a9d297e4282a38f5c5782d8d3d0 | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:\n return False\nreturn True",
"device_data = self.target\ncommand_name = 'Abort'\ndevice_data.event_track_time.set()\ncmd_ended_cb = CommandCallBack(self.logger).cmd_ended_cb\ntry:\n this_server = TangoServerHelper.get_in... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:
return False
return True
<|end_body_0|>
<|body_start_1|>
device_data = self.target
command_name = 'Abort'
device_data.event_track_time.set()
cmd_ended_cb = ... | A class for DishLeafNode's Abort command. | Abort | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Abort:
"""A class for DishLeafNode's Abort command."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean"""
<|body_0|>
def do(sel... | stack_v2_sparse_classes_75kplus_train_069733 | 2,704 | permissive | [
{
"docstring": "Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean",
"name": "check_allowed",
"signature": "def check_allowed(self)"
},
{
"docstring": "Invokes TrackStop command on th... | 2 | stack_v2_sparse_classes_30k_train_040334 | Implement the Python class `Abort` described below.
Class description:
A class for DishLeafNode's Abort command.
Method signatures and docstrings:
- def check_allowed(self): Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device st... | Implement the Python class `Abort` described below.
Class description:
A class for DishLeafNode's Abort command.
Method signatures and docstrings:
- def check_allowed(self): Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device st... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class Abort:
"""A class for DishLeafNode's Abort command."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean"""
<|body_0|>
def do(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Abort:
"""A class for DishLeafNode's Abort command."""
def check_allowed(self):
"""Checks whether this command is allowed to be run in current device state :return: True if this command is allowed to be run in current device state :rtype: boolean"""
if self.state_model.op_state in [DevSta... | the_stack_v2_python_sparse | temp_src/ska_tmc_dishleafnode_mid/abort_command.py | ska-telescope/tmc-prototype | train | 4 |
b4f0618400120c1c1b9315fdbb3f683ee10db5f5 | [
"def dfs(node, res):\n if node is None:\n return res + 'None,'\n res = res + str(node.val) + ','\n res = dfs(node.left, res)\n res = dfs(node.right, res)\n return res\nreturn dfs(root, '')",
"nodes = data.split(',')\nposi = 0\n\ndef dfs():\n nonlocal posi\n if posi == len(nodes):\n ... | <|body_start_0|>
def dfs(node, res):
if node is None:
return res + 'None,'
res = res + str(node.val) + ','
res = dfs(node.left, res)
res = dfs(node.right, res)
return res
return dfs(root, '')
<|end_body_0|>
<|body_start_1|>
... | Codec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_069734 | 1,641 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_008256 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 6f0e92fd6e225c9db5a038881fc193e4e4231c3e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def dfs(node, res):
if node is None:
return res + 'None,'
res = res + str(node.val) + ','
res = dfs(node.left, res)
res = ... | the_stack_v2_python_sparse | py/297.二叉树的序列化与反序列化.py | guojiangwei/myLeetCode | train | 0 | |
9156ea9d49cc8c34ed1a4f8620566d632ef7ff0d | [
"data_list = models.Server.objects.all()\nserializer = serializers.MySerializer(instance=data_list, many=True)\nreturn JsonResponse(serializer.data, safe=False)",
"data = JSONParser().parse(request)\nserializer = serializers.MySerializer(data=data)\nif serializer.is_valid():\n serializer.save()\nreturn HttpRes... | <|body_start_0|>
data_list = models.Server.objects.all()
serializer = serializers.MySerializer(instance=data_list, many=True)
return JsonResponse(serializer.data, safe=False)
<|end_body_0|>
<|body_start_1|>
data = JSONParser().parse(request)
serializer = serializers.MySerializer... | ServerView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServerView:
def get(self, request, *args, **kwargs):
"""获取列表 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建数据 :param request: request经过封装 :param args: :param kwargs: :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus_train_069735 | 6,597 | permissive | [
{
"docstring": "获取列表 :param request: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "创建数据 :param request: request经过封装 :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, reques... | 2 | stack_v2_sparse_classes_30k_train_050956 | Implement the Python class `ServerView` described below.
Class description:
Implement the ServerView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取列表 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建数据 :param request: request经过封... | Implement the Python class `ServerView` described below.
Class description:
Implement the ServerView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取列表 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 创建数据 :param request: request经过封... | 4ff1d02d2b6dd54e96f7179fa000548936b691e7 | <|skeleton|>
class ServerView:
def get(self, request, *args, **kwargs):
"""获取列表 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""创建数据 :param request: request经过封装 :param args: :param kwargs: :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServerView:
def get(self, request, *args, **kwargs):
"""获取列表 :param request: :param args: :param kwargs: :return:"""
data_list = models.Server.objects.all()
serializer = serializers.MySerializer(instance=data_list, many=True)
return JsonResponse(serializer.data, safe=False)
... | the_stack_v2_python_sparse | CMDB_SYSTEM/autoserver/server/views.py | MMingLeung/Python_Study | train | 3 | |
f151ddeedb43395e802a5a6cc75e5790bdb0b91a | [
"self.__camerasettings_filters = filters\nself.__camerasettings_filter = filter_name\nself.__camerasettings_binning = binning",
"if not isinstance(self, Module) or not isinstance(self, CameraSettingsMixin):\n raise ValueError('This is not a module')\nif self.__camerasettings_filters is not None and self.__came... | <|body_start_0|>
self.__camerasettings_filters = filters
self.__camerasettings_filter = filter_name
self.__camerasettings_binning = binning
<|end_body_0|>
<|body_start_1|>
if not isinstance(self, Module) or not isinstance(self, CameraSettingsMixin):
raise ValueError('This is... | Mixin for a device that should be able to set camera settings. | CameraSettingsMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraSettingsMixin:
"""Mixin for a device that should be able to set camera settings."""
def __init__(self, filters: Optional[Union[str, IFilters]]=None, filter_name: Optional[str]=None, binning: Optional[int]=None, **kwargs: Any):
"""Initializes the mixin. Args: filters: Filter whe... | stack_v2_sparse_classes_75kplus_train_069736 | 2,372 | permissive | [
{
"docstring": "Initializes the mixin. Args: filters: Filter wheel module. filter: Filter to set. binning: Binning to set.",
"name": "__init__",
"signature": "def __init__(self, filters: Optional[Union[str, IFilters]]=None, filter_name: Optional[str]=None, binning: Optional[int]=None, **kwargs: Any)"
... | 2 | null | Implement the Python class `CameraSettingsMixin` described below.
Class description:
Mixin for a device that should be able to set camera settings.
Method signatures and docstrings:
- def __init__(self, filters: Optional[Union[str, IFilters]]=None, filter_name: Optional[str]=None, binning: Optional[int]=None, **kwarg... | Implement the Python class `CameraSettingsMixin` described below.
Class description:
Mixin for a device that should be able to set camera settings.
Method signatures and docstrings:
- def __init__(self, filters: Optional[Union[str, IFilters]]=None, filter_name: Optional[str]=None, binning: Optional[int]=None, **kwarg... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class CameraSettingsMixin:
"""Mixin for a device that should be able to set camera settings."""
def __init__(self, filters: Optional[Union[str, IFilters]]=None, filter_name: Optional[str]=None, binning: Optional[int]=None, **kwargs: Any):
"""Initializes the mixin. Args: filters: Filter whe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CameraSettingsMixin:
"""Mixin for a device that should be able to set camera settings."""
def __init__(self, filters: Optional[Union[str, IFilters]]=None, filter_name: Optional[str]=None, binning: Optional[int]=None, **kwargs: Any):
"""Initializes the mixin. Args: filters: Filter wheel module. fi... | the_stack_v2_python_sparse | pyobs/mixins/camerasettings.py | pyobs/pyobs-core | train | 9 |
726f16435b94c29795767ec849fc3ed10f703704 | [
"self.plugin = plugin\nself.form_wizard_entry = form_wizard_entry\nself.as_var = as_var",
"request = context['request']\nplugin = self.plugin.resolve(context, True)\nform_wizard_entry = self.form_wizard_entry.resolve(context, True)\ncontext[self.as_var] = plugin.get_custom_actions(form_wizard_entry, request)\nret... | <|body_start_0|>
self.plugin = plugin
self.form_wizard_entry = form_wizard_entry
self.as_var = as_var
<|end_body_0|>
<|body_start_1|>
request = context['request']
plugin = self.plugin.resolve(context, True)
form_wizard_entry = self.form_wizard_entry.resolve(context, True... | Node for ``get_fobi_form_wizard_handler_plugin_custom_actions`` tag. | GetFobiFormWizardHandlerPluginCustomActionsNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetFobiFormWizardHandlerPluginCustomActionsNode:
"""Node for ``get_fobi_form_wizard_handler_plugin_custom_actions`` tag."""
def __init__(self, plugin, form_wizard_entry, as_var=None):
"""Constructor."""
<|body_0|>
def render(self, context):
"""Render."""
... | stack_v2_sparse_classes_75kplus_train_069737 | 16,666 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, plugin, form_wizard_entry, as_var=None)"
},
{
"docstring": "Render.",
"name": "render",
"signature": "def render(self, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031258 | Implement the Python class `GetFobiFormWizardHandlerPluginCustomActionsNode` described below.
Class description:
Node for ``get_fobi_form_wizard_handler_plugin_custom_actions`` tag.
Method signatures and docstrings:
- def __init__(self, plugin, form_wizard_entry, as_var=None): Constructor.
- def render(self, context)... | Implement the Python class `GetFobiFormWizardHandlerPluginCustomActionsNode` described below.
Class description:
Node for ``get_fobi_form_wizard_handler_plugin_custom_actions`` tag.
Method signatures and docstrings:
- def __init__(self, plugin, form_wizard_entry, as_var=None): Constructor.
- def render(self, context)... | 4f6ca37bc600dcba3f74400d299826882d53b7d2 | <|skeleton|>
class GetFobiFormWizardHandlerPluginCustomActionsNode:
"""Node for ``get_fobi_form_wizard_handler_plugin_custom_actions`` tag."""
def __init__(self, plugin, form_wizard_entry, as_var=None):
"""Constructor."""
<|body_0|>
def render(self, context):
"""Render."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetFobiFormWizardHandlerPluginCustomActionsNode:
"""Node for ``get_fobi_form_wizard_handler_plugin_custom_actions`` tag."""
def __init__(self, plugin, form_wizard_entry, as_var=None):
"""Constructor."""
self.plugin = plugin
self.form_wizard_entry = form_wizard_entry
self.a... | the_stack_v2_python_sparse | events/templatetags/fobi_tags.py | mansonul/events | train | 0 |
f6daa8cc87c715d5e849f60f0d177dda6f684f9e | [
"obj = self.get_object()\nviews.add_like(obj, request.user)\nreturn redirect('com_list')",
"obj = self.get_object()\nviews.remove_like(obj, request.user)\nreturn redirect('com_list')",
"obj = self.get_object()\nfans = views.get_fans(obj)\nserializer = FanSerializer(fans, many=True)\nreturn Response(serializer.d... | <|body_start_0|>
obj = self.get_object()
views.add_like(obj, request.user)
return redirect('com_list')
<|end_body_0|>
<|body_start_1|>
obj = self.get_object()
views.remove_like(obj, request.user)
return redirect('com_list')
<|end_body_1|>
<|body_start_2|>
obj = ... | LikedMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LikedMixin:
def like(self, request, pk=None):
"""Лайкает `obj`."""
<|body_0|>
def unlike(self, request, pk=None):
"""Удаляет лайк с `obj`."""
<|body_1|>
def fans(self, request, pk=None):
"""Получает всех пользователей, которые лайкнули `obj`."""
... | stack_v2_sparse_classes_75kplus_train_069738 | 1,034 | no_license | [
{
"docstring": "Лайкает `obj`.",
"name": "like",
"signature": "def like(self, request, pk=None)"
},
{
"docstring": "Удаляет лайк с `obj`.",
"name": "unlike",
"signature": "def unlike(self, request, pk=None)"
},
{
"docstring": "Получает всех пользователей, которые лайкнули `obj`."... | 3 | stack_v2_sparse_classes_30k_train_003324 | Implement the Python class `LikedMixin` described below.
Class description:
Implement the LikedMixin class.
Method signatures and docstrings:
- def like(self, request, pk=None): Лайкает `obj`.
- def unlike(self, request, pk=None): Удаляет лайк с `obj`.
- def fans(self, request, pk=None): Получает всех пользователей, ... | Implement the Python class `LikedMixin` described below.
Class description:
Implement the LikedMixin class.
Method signatures and docstrings:
- def like(self, request, pk=None): Лайкает `obj`.
- def unlike(self, request, pk=None): Удаляет лайк с `obj`.
- def fans(self, request, pk=None): Получает всех пользователей, ... | bf8d7bf0b0d2e146f3eededc2d1bfa542a897abf | <|skeleton|>
class LikedMixin:
def like(self, request, pk=None):
"""Лайкает `obj`."""
<|body_0|>
def unlike(self, request, pk=None):
"""Удаляет лайк с `obj`."""
<|body_1|>
def fans(self, request, pk=None):
"""Получает всех пользователей, которые лайкнули `obj`."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LikedMixin:
def like(self, request, pk=None):
"""Лайкает `obj`."""
obj = self.get_object()
views.add_like(obj, request.user)
return redirect('com_list')
def unlike(self, request, pk=None):
"""Удаляет лайк с `obj`."""
obj = self.get_object()
views.re... | the_stack_v2_python_sparse | OOP/proj/insta/lenta/mixins.py | killkamad/PC-home | train | 2 | |
39d0922633cf4df8a126263e4dabe2134fe0fd92 | [
"super().__init__(auth_module, setup_schema, user.id)\nself._auth_module: TotpAuthModule = auth_module\nself._user = user\nself._ota_secret: str = ''\nself._url: str | None = None\nself._image: str | None = None",
"import pyotp\nerrors: dict[str, str] = {}\nif user_input:\n verified = await self.hass.async_add... | <|body_start_0|>
super().__init__(auth_module, setup_schema, user.id)
self._auth_module: TotpAuthModule = auth_module
self._user = user
self._ota_secret: str = ''
self._url: str | None = None
self._image: str | None = None
<|end_body_0|>
<|body_start_1|>
import p... | Handler for the setup flow. | TotpSetupFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TotpSetupFlow:
"""Handler for the setup flow."""
def __init__(self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User) -> None:
"""Initialize the setup flow."""
<|body_0|>
async def async_step_init(self, user_input: dict[str, str] | None=None) -> FlowResu... | stack_v2_sparse_classes_75kplus_train_069739 | 7,812 | permissive | [
{
"docstring": "Initialize the setup flow.",
"name": "__init__",
"signature": "def __init__(self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User) -> None"
},
{
"docstring": "Handle the first step of setup flow. Return self.async_show_form(step_id='init') if user_input is None.... | 2 | stack_v2_sparse_classes_30k_train_025309 | Implement the Python class `TotpSetupFlow` described below.
Class description:
Handler for the setup flow.
Method signatures and docstrings:
- def __init__(self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User) -> None: Initialize the setup flow.
- async def async_step_init(self, user_input: dict[st... | Implement the Python class `TotpSetupFlow` described below.
Class description:
Handler for the setup flow.
Method signatures and docstrings:
- def __init__(self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User) -> None: Initialize the setup flow.
- async def async_step_init(self, user_input: dict[st... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TotpSetupFlow:
"""Handler for the setup flow."""
def __init__(self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User) -> None:
"""Initialize the setup flow."""
<|body_0|>
async def async_step_init(self, user_input: dict[str, str] | None=None) -> FlowResu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TotpSetupFlow:
"""Handler for the setup flow."""
def __init__(self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User) -> None:
"""Initialize the setup flow."""
super().__init__(auth_module, setup_schema, user.id)
self._auth_module: TotpAuthModule = auth_module
... | the_stack_v2_python_sparse | homeassistant/auth/mfa_modules/totp.py | home-assistant/core | train | 35,501 |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertIntermediate, self).__init__()\nself.dense = nn.Dense(config.hidden_size, config.intermediate_size).to_float(mindspore.float16)\nself.intermediate_act_fn = GeLU()\nself.cast = ops.Cast()",
"hidden_states = self.cast(hidden_states, mindspore.float16)\nhidden_states = self.dense(hidden_states)\nhidden_st... | <|body_start_0|>
super(BertIntermediate, self).__init__()
self.dense = nn.Dense(config.hidden_size, config.intermediate_size).to_float(mindspore.float16)
self.intermediate_act_fn = GeLU()
self.cast = ops.Cast()
<|end_body_0|>
<|body_start_1|>
hidden_states = self.cast(hidden_sta... | bert intermdiate fun | BertIntermediate | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertIntermediate:
"""bert intermdiate fun"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BertIntermediate, self).__init__()
... | stack_v2_sparse_classes_75kplus_train_069740 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004679 | Implement the Python class `BertIntermediate` described below.
Class description:
bert intermdiate fun
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states): construct fun | Implement the Python class `BertIntermediate` described below.
Class description:
bert intermdiate fun
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states): construct fun
<|skeleton|>
class BertIntermediate:
"""bert intermdiate fun"""
def __init__(sel... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertIntermediate:
"""bert intermdiate fun"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BertIntermediate:
"""bert intermdiate fun"""
def __init__(self, config):
"""init fun"""
super(BertIntermediate, self).__init__()
self.dense = nn.Dense(config.hidden_size, config.intermediate_size).to_float(mindspore.float16)
self.intermediate_act_fn = GeLU()
self.c... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
1c585f5c401c87591a6dd2ac654fcc2390ee2943 | [
"self.snake = deque()\nself.snake.append([0, 0])\nself.snake_set = set()\nself.snake_set.add((0, 0))\nself.score = 0\nself.food = deque()\nfor ele in food:\n self.food.append(ele)\nself.width = width\nself.height = height\nself.directions = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}",
"head = self.... | <|body_start_0|>
self.snake = deque()
self.snake.append([0, 0])
self.snake_set = set()
self.snake_set.add((0, 0))
self.score = 0
self.food = deque()
for ele in food:
self.food.append(ele)
self.width = width
self.height = height
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus_train_069741 | 2,425 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_018342 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 9b38a7742a819ac3795ea295e371e26bb5bfc28c | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | 353. Design Snake Game.py | dundunmao/LeetCode2019 | train | 0 | |
8e73fe7b8dd0aceaaa4c0739085c488d2649a286 | [
"new_car = Car(name=validated_data.get('name'), url=validated_data.get('url'), car_type=validated_data.get('car_type'))\nnew_car.save()\nreturn new_car",
"instance.name = validated_data.get('name', instance.name)\ninstance.url = validated_data.get('url', instance.url)\ninstance.car_type = validated_data.get('car_... | <|body_start_0|>
new_car = Car(name=validated_data.get('name'), url=validated_data.get('url'), car_type=validated_data.get('car_type'))
new_car.save()
return new_car
<|end_body_0|>
<|body_start_1|>
instance.name = validated_data.get('name', instance.name)
instance.url = validate... | CarSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CarSerializer:
def create(self, validated_data):
"""create and return new 'Car' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `Car` instance"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
new_ca... | stack_v2_sparse_classes_75kplus_train_069742 | 6,342 | no_license | [
{
"docstring": "create and return new 'Car' instance",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `Car` instance",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024833 | Implement the Python class `CarSerializer` described below.
Class description:
Implement the CarSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'Car' instance
- def update(self, instance, validated_data): Update and return an existing `Car` instance | Implement the Python class `CarSerializer` described below.
Class description:
Implement the CarSerializer class.
Method signatures and docstrings:
- def create(self, validated_data): create and return new 'Car' instance
- def update(self, instance, validated_data): Update and return an existing `Car` instance
<|ske... | dba8d1fdb96889e41328e792816a4968cbeb1ed4 | <|skeleton|>
class CarSerializer:
def create(self, validated_data):
"""create and return new 'Car' instance"""
<|body_0|>
def update(self, instance, validated_data):
"""Update and return an existing `Car` instance"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CarSerializer:
def create(self, validated_data):
"""create and return new 'Car' instance"""
new_car = Car(name=validated_data.get('name'), url=validated_data.get('url'), car_type=validated_data.get('car_type'))
new_car.save()
return new_car
def update(self, instance, valid... | the_stack_v2_python_sparse | cars_web/cars_app/serializers.py | Ignisor/cars_scrapper | train | 0 | |
818811439bdd70d0f39cb26c89a10d779695ea85 | [
"if not preorder:\n return None\nroot = TreeNode(preorder[0])\nif len(preorder) == 1 or len(inorder) == 1:\n return root\ni = inorder.index(preorder[0])\nroot.left = self.buildTree(preorder[1:i + 1], inorder[:i])\nroot.right = self.buildTree(preorder[i + 1:], inorder[i + 1:])\nreturn root",
"def build(v):\n... | <|body_start_0|>
if not preorder:
return None
root = TreeNode(preorder[0])
if len(preorder) == 1 or len(inorder) == 1:
return root
i = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:i + 1], inorder[:i])
root.right = self.buildTree... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""05/06/2018 18:23 Time complexity; O(n^2)"""
<|body_0|>
def buildTree(self, preorder, inorder):
"""05/07/2018 10:44 Time complexity: O(n)"""
<|body_1|>
def buildTree(se... | stack_v2_sparse_classes_75kplus_train_069743 | 4,039 | no_license | [
{
"docstring": "05/06/2018 18:23 Time complexity; O(n^2)",
"name": "buildTree",
"signature": "def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode"
},
{
"docstring": "05/07/2018 10:44 Time complexity: O(n)",
"name": "buildTree",
"signature": "def buildTree(self, preor... | 5 | stack_v2_sparse_classes_30k_val_002643 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 05/06/2018 18:23 Time complexity; O(n^2)
- def buildTree(self, preorder, inorder): 05/07/2018 10:44 Time... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: 05/06/2018 18:23 Time complexity; O(n^2)
- def buildTree(self, preorder, inorder): 05/07/2018 10:44 Time... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""05/06/2018 18:23 Time complexity; O(n^2)"""
<|body_0|>
def buildTree(self, preorder, inorder):
"""05/07/2018 10:44 Time complexity: O(n)"""
<|body_1|>
def buildTree(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""05/06/2018 18:23 Time complexity; O(n^2)"""
if not preorder:
return None
root = TreeNode(preorder[0])
if len(preorder) == 1 or len(inorder) == 1:
return root
i... | the_stack_v2_python_sparse | leetcode/solved/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal/solution.py | sungminoh/algorithms | train | 0 | |
1c5fa355bff71df7a5c204eebc2ef78d4c101d54 | [
"arg_is_iter = False\nif len(args) == 1:\n arg_is_iter = True\n args = args[0]\nsymb_args = []\nres = initial_val\nnum_non_symbolic_args = 0\nfor x in args:\n if isinstance(x, Expression):\n symb_args.append(x)\n else:\n num_non_symbolic_args += 1\n res = builtin_f(res, x)\nif len(s... | <|body_start_0|>
arg_is_iter = False
if len(args) == 1:
arg_is_iter = True
args = args[0]
symb_args = []
res = initial_val
num_non_symbolic_args = 0
for x in args:
if isinstance(x, Expression):
symb_args.append(x)
... | MinMax_base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MinMax_base:
def eval_helper(self, this_f, builtin_f, initial_val, args):
"""EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)"""
<|body_0|>
def __call__(self, *args, **kwds):
"""EXAMPLES:: sage: max_symbolic(3,5,x)... | stack_v2_sparse_classes_75kplus_train_069744 | 10,190 | no_license | [
{
"docstring": "EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)",
"name": "eval_helper",
"signature": "def eval_helper(self, this_f, builtin_f, initial_val, args)"
},
{
"docstring": "EXAMPLES:: sage: max_symbolic(3,5,x) max(x, 5) sage: max_sy... | 2 | stack_v2_sparse_classes_30k_train_011123 | Implement the Python class `MinMax_base` described below.
Class description:
Implement the MinMax_base class.
Method signatures and docstrings:
- def eval_helper(self, this_f, builtin_f, initial_val, args): EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)
- def __c... | Implement the Python class `MinMax_base` described below.
Class description:
Implement the MinMax_base class.
Method signatures and docstrings:
- def eval_helper(self, this_f, builtin_f, initial_val, args): EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)
- def __c... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class MinMax_base:
def eval_helper(self, this_f, builtin_f, initial_val, args):
"""EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)"""
<|body_0|>
def __call__(self, *args, **kwds):
"""EXAMPLES:: sage: max_symbolic(3,5,x)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MinMax_base:
def eval_helper(self, this_f, builtin_f, initial_val, args):
"""EXAMPLES:: sage: max_symbolic(3,5,x) # indirect doctest max(x, 5) sage: min_symbolic(3,5,x) min(x, 3)"""
arg_is_iter = False
if len(args) == 1:
arg_is_iter = True
args = args[0]
... | the_stack_v2_python_sparse | sage/src/sage/functions/min_max.py | bopopescu/geosci | train | 0 | |
01e229d56676a0cbbdc65efc3656b57d03a66cc8 | [
"config_type = request.GET.get('config_type', '')\nzone_name = request.GET.get('zone_name', '')\nfm = FirewallManger()\ninterface_list = fm.get_interface(config_type, zone_name)\nintface_dict = {'interfaces': interface_list}\nreturn Response(intface_dict, status=status.HTTP_200_OK)",
"config_type = request.DATA.g... | <|body_start_0|>
config_type = request.GET.get('config_type', '')
zone_name = request.GET.get('zone_name', '')
fm = FirewallManger()
interface_list = fm.get_interface(config_type, zone_name)
intface_dict = {'interfaces': interface_list}
return Response(intface_dict, statu... | List the interfaces in a zone | FirewallInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirewallInterface:
"""List the interfaces in a zone"""
def get(self, request, format=None):
"""Get the interfaces in a zone"""
<|body_0|>
def delete(self, request, format=None):
"""Delete an interface from a zone"""
<|body_1|>
def post(self, request,... | stack_v2_sparse_classes_75kplus_train_069745 | 21,597 | no_license | [
{
"docstring": "Get the interfaces in a zone",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Delete an interface from a zone",
"name": "delete",
"signature": "def delete(self, request, format=None)"
},
{
"docstring": "Add the interface form ... | 4 | null | Implement the Python class `FirewallInterface` described below.
Class description:
List the interfaces in a zone
Method signatures and docstrings:
- def get(self, request, format=None): Get the interfaces in a zone
- def delete(self, request, format=None): Delete an interface from a zone
- def post(self, request, for... | Implement the Python class `FirewallInterface` described below.
Class description:
List the interfaces in a zone
Method signatures and docstrings:
- def get(self, request, format=None): Get the interfaces in a zone
- def delete(self, request, format=None): Delete an interface from a zone
- def post(self, request, for... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class FirewallInterface:
"""List the interfaces in a zone"""
def get(self, request, format=None):
"""Get the interfaces in a zone"""
<|body_0|>
def delete(self, request, format=None):
"""Delete an interface from a zone"""
<|body_1|>
def post(self, request,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirewallInterface:
"""List the interfaces in a zone"""
def get(self, request, format=None):
"""Get the interfaces in a zone"""
config_type = request.GET.get('config_type', '')
zone_name = request.GET.get('zone_name', '')
fm = FirewallManger()
interface_list = fm.ge... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/firewall/views.py | sdtimothy8/Coding | train | 0 |
d1a8116281ff883b016595f35bd5089e17f5fbee | [
"assert payoff_matrix.ndim == 3\nassert payoff_matrix.shape[0] == 2\nassert np.allclose(payoff_matrix[0], payoff_matrix[1].T)\nself.payoff_matrix = payoff_matrix[0]\nself.dynamics = dynamics",
"state = np.array(state)\nassert state.ndim == 1\nassert state.shape[0] == self.payoff_matrix.shape[0]\nfitness = np.matm... | <|body_start_0|>
assert payoff_matrix.ndim == 3
assert payoff_matrix.shape[0] == 2
assert np.allclose(payoff_matrix[0], payoff_matrix[1].T)
self.payoff_matrix = payoff_matrix[0]
self.dynamics = dynamics
<|end_body_0|>
<|body_start_1|>
state = np.array(state)
asse... | Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric. dynamics: A callback function that returns the time-d... | SinglePopulationDynamicsLB | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinglePopulationDynamicsLB:
"""Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric.... | stack_v2_sparse_classes_75kplus_train_069746 | 5,588 | permissive | [
{
"docstring": "Initializes the single-population dynamics.",
"name": "__init__",
"signature": "def __init__(self, payoff_matrix, dynamics)"
},
{
"docstring": "Time derivative of the population state. Args: state: Probability distribution as list or `numpy.ndarray(shape=num_strategies)`. time: T... | 2 | null | Implement the Python class `SinglePopulationDynamicsLB` described below.
Class description:
Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second playe... | Implement the Python class `SinglePopulationDynamicsLB` described below.
Class description:
Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second playe... | f2f0c786410018675fc40e9a5b82c40814555fa8 | <|skeleton|>
class SinglePopulationDynamicsLB:
"""Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SinglePopulationDynamicsLB:
"""Continuous-time single population dynamics. Attributes: payoff_matrix: The payoff matrix as an `numpy.ndarray` of shape `[2, k_1, k_2]`, where `k_1` is the number of strategies of the first player and `k_2` for the second player. The game is assumed to be symmetric. dynamics: A ... | the_stack_v2_python_sparse | open_spiel/python/project/part_1/dynamics_lenient_boltzmannq/dynamics_lb.py | antonevenepoel/open_spiel | train | 0 |
494932d77c4577433dfa585caf83adc866bf460c | [
"obj = self.get(id=pk)\nnew_regions = []\nfor region in obj.regions.all():\n region.pk = None\n region.save()\n new_regions.append(region)\nobj.pk = None\nobj.save()\nobj.regions.set(new_regions)\nobj.title += ' (cloned)'\nobj.save()\nreturn obj",
"obj = self.select_related().get(pk=pk)\nobj_json = model... | <|body_start_0|>
obj = self.get(id=pk)
new_regions = []
for region in obj.regions.all():
region.pk = None
region.save()
new_regions.append(region)
obj.pk = None
obj.save()
obj.regions.set(new_regions)
obj.title += ' (cloned)'
... | This is a general reduction manager. | ReductionManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReductionManager:
"""This is a general reduction manager."""
def clone(self, pk):
"""Clones the Reduction object and related regions"""
<|body_0|>
def to_json(self, pk):
"""Gets this reduction object in json format serializes: reduction and related regions and as... | stack_v2_sparse_classes_75kplus_train_069747 | 4,525 | no_license | [
{
"docstring": "Clones the Reduction object and related regions",
"name": "clone",
"signature": "def clone(self, pk)"
},
{
"docstring": "Gets this reduction object in json format serializes: reduction and related regions and associated configuration Not for use in SANS: 1 Reduction has 1 Configu... | 2 | null | Implement the Python class `ReductionManager` described below.
Class description:
This is a general reduction manager.
Method signatures and docstrings:
- def clone(self, pk): Clones the Reduction object and related regions
- def to_json(self, pk): Gets this reduction object in json format serializes: reduction and r... | Implement the Python class `ReductionManager` described below.
Class description:
This is a general reduction manager.
Method signatures and docstrings:
- def clone(self, pk): Clones the Reduction object and related regions
- def to_json(self, pk): Gets this reduction object in json format serializes: reduction and r... | 507ff81617abf583edd4ef4858985daefc0afcbe | <|skeleton|>
class ReductionManager:
"""This is a general reduction manager."""
def clone(self, pk):
"""Clones the Reduction object and related regions"""
<|body_0|>
def to_json(self, pk):
"""Gets this reduction object in json format serializes: reduction and related regions and as... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReductionManager:
"""This is a general reduction manager."""
def clone(self, pk):
"""Clones the Reduction object and related regions"""
obj = self.get(id=pk)
new_regions = []
for region in obj.regions.all():
region.pk = None
region.save()
... | the_stack_v2_python_sparse | src/server/apps/reduction/models/abstract.py | bidochon/WebReduction | train | 0 |
3f6717cf63b3d68f30755333807d251e2daa76fa | [
"super().__init__()\nsigma = sigma if isinstance(sigma, tuple) else (sigma, sigma)\nself.channels = channels\nif kernel_size is None:\n kernel_size = (compute_kernel_size(sigma[0]), compute_kernel_size(sigma[1]))\nelse:\n kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size, kernel_si... | <|body_start_0|>
super().__init__()
sigma = sigma if isinstance(sigma, tuple) else (sigma, sigma)
self.channels = channels
if kernel_size is None:
kernel_size = (compute_kernel_size(sigma[0]), compute_kernel_size(sigma[1]))
else:
kernel_size = kernel_size ... | Compute GaussianBlur in 2d. Makes use of kornia functions, but most notably the kernel is not computed during the forward pass, and does not depend on the input size. As a caveat, the number of channels that are expected have to be provided during initialization. | GaussianBlur2d | [
"CC-BY-SA-4.0",
"CC-BY-SA-3.0",
"CC-BY-NC-SA-4.0",
"Python-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianBlur2d:
"""Compute GaussianBlur in 2d. Makes use of kornia functions, but most notably the kernel is not computed during the forward pass, and does not depend on the input size. As a caveat, the number of channels that are expected have to be provided during initialization."""
def __... | stack_v2_sparse_classes_75kplus_train_069748 | 3,553 | permissive | [
{
"docstring": "Initialize model, setup kernel etc.. Args: sigma (float | tuple[float, float]): standard deviation to use for constructing the Gaussian kernel. channels (int): channels of the input. Defaults to 1. kernel_size (int | tuple[int, int] | None): size of the Gaussian kernel to use. Defaults to None. ... | 2 | stack_v2_sparse_classes_30k_train_051131 | Implement the Python class `GaussianBlur2d` described below.
Class description:
Compute GaussianBlur in 2d. Makes use of kornia functions, but most notably the kernel is not computed during the forward pass, and does not depend on the input size. As a caveat, the number of channels that are expected have to be provide... | Implement the Python class `GaussianBlur2d` described below.
Class description:
Compute GaussianBlur in 2d. Makes use of kornia functions, but most notably the kernel is not computed during the forward pass, and does not depend on the input size. As a caveat, the number of channels that are expected have to be provide... | 4abfa93dcfcb98771bc768b334c929ff9a02ce8b | <|skeleton|>
class GaussianBlur2d:
"""Compute GaussianBlur in 2d. Makes use of kornia functions, but most notably the kernel is not computed during the forward pass, and does not depend on the input size. As a caveat, the number of channels that are expected have to be provided during initialization."""
def __... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianBlur2d:
"""Compute GaussianBlur in 2d. Makes use of kornia functions, but most notably the kernel is not computed during the forward pass, and does not depend on the input size. As a caveat, the number of channels that are expected have to be provided during initialization."""
def __init__(self, ... | the_stack_v2_python_sparse | src/anomalib/models/components/filters/blur.py | openvinotoolkit/anomalib | train | 2,325 |
b0bc7f952261390df420f7192ccb882f9b24aabe | [
"Utils.validate_uuid(goniometry_id)\nif not Goniometry.objects.filter(id=goniometry_id).exists():\n raise ValidationError('The goniometry is not valid!')",
"BodyZoneService.is_valid_body_zone(goniometry['body_zone'])\nnew_goniometry = Goniometry.objects.create(body_zone_id=goniometry['body_zone'], min_abductio... | <|body_start_0|>
Utils.validate_uuid(goniometry_id)
if not Goniometry.objects.filter(id=goniometry_id).exists():
raise ValidationError('The goniometry is not valid!')
<|end_body_0|>
<|body_start_1|>
BodyZoneService.is_valid_body_zone(goniometry['body_zone'])
new_goniometry =... | Service class for goniometry related operations | GoniometryService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoniometryService:
"""Service class for goniometry related operations"""
def is_valid_goniometry(goniometry_id):
"""Checks if the specified goniometry exists :param goniometry_id: if of the goniometry"""
<|body_0|>
def add_goniometry(goniometry, id_treatment):
""... | stack_v2_sparse_classes_75kplus_train_069749 | 2,899 | no_license | [
{
"docstring": "Checks if the specified goniometry exists :param goniometry_id: if of the goniometry",
"name": "is_valid_goniometry",
"signature": "def is_valid_goniometry(goniometry_id)"
},
{
"docstring": "Creates a goniometry for a new treatment :param goniometry: Goniometry info :param id_tre... | 3 | stack_v2_sparse_classes_30k_train_039173 | Implement the Python class `GoniometryService` described below.
Class description:
Service class for goniometry related operations
Method signatures and docstrings:
- def is_valid_goniometry(goniometry_id): Checks if the specified goniometry exists :param goniometry_id: if of the goniometry
- def add_goniometry(gonio... | Implement the Python class `GoniometryService` described below.
Class description:
Service class for goniometry related operations
Method signatures and docstrings:
- def is_valid_goniometry(goniometry_id): Checks if the specified goniometry exists :param goniometry_id: if of the goniometry
- def add_goniometry(gonio... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class GoniometryService:
"""Service class for goniometry related operations"""
def is_valid_goniometry(goniometry_id):
"""Checks if the specified goniometry exists :param goniometry_id: if of the goniometry"""
<|body_0|>
def add_goniometry(goniometry, id_treatment):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GoniometryService:
"""Service class for goniometry related operations"""
def is_valid_goniometry(goniometry_id):
"""Checks if the specified goniometry exists :param goniometry_id: if of the goniometry"""
Utils.validate_uuid(goniometry_id)
if not Goniometry.objects.filter(id=goniom... | the_stack_v2_python_sparse | backend/martin_helder/services/goniometry_service.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
34f98b5d7038c19c6bcb9b4abee1ebf6c10d8f34 | [
"self.corr = corr\nself.num_phi = corr.shape[-1]\nself.wavlen = wavlen\nself.q_values = q_values\nself.num_psi = num_psi",
"new_cpsi = np.linspace(-1, 1, num=self.num_psi, endpoint=True)\nif len(self.corr.shape) == 3:\n interp_corr = np.zeros((self.corr.shape[0], self.corr.shape[1], self.num_psi))\nelse:\n ... | <|body_start_0|>
self.corr = corr
self.num_phi = corr.shape[-1]
self.wavlen = wavlen
self.q_values = q_values
self.num_psi = num_psi
<|end_body_0|>
<|body_start_1|>
new_cpsi = np.linspace(-1, 1, num=self.num_psi, endpoint=True)
if len(self.corr.shape) == 3:
... | InterpCorr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpCorr:
def __init__(self, corr, wavlen, q_values, num_psi):
"""Initialize a interpolation class for interpolating correlations ================================================================ corr - 2d or 3d float np.array , shape is (num_shot x num_q x num_phi) or (num_shot x num_p... | stack_v2_sparse_classes_75kplus_train_069750 | 4,087 | no_license | [
{
"docstring": "Initialize a interpolation class for interpolating correlations ================================================================ corr - 2d or 3d float np.array , shape is (num_shot x num_q x num_phi) or (num_shot x num_phi) . it is assumed to contain difference correlation, i.e. each shot is fro... | 3 | stack_v2_sparse_classes_30k_train_025035 | Implement the Python class `InterpCorr` described below.
Class description:
Implement the InterpCorr class.
Method signatures and docstrings:
- def __init__(self, corr, wavlen, q_values, num_psi): Initialize a interpolation class for interpolating correlations =========================================================... | Implement the Python class `InterpCorr` described below.
Class description:
Implement the InterpCorr class.
Method signatures and docstrings:
- def __init__(self, corr, wavlen, q_values, num_psi): Initialize a interpolation class for interpolating correlations =========================================================... | 4c208101287c1ddf377d4a6d431fef8c44f3e9b4 | <|skeleton|>
class InterpCorr:
def __init__(self, corr, wavlen, q_values, num_psi):
"""Initialize a interpolation class for interpolating correlations ================================================================ corr - 2d or 3d float np.array , shape is (num_shot x num_q x num_phi) or (num_shot x num_p... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpCorr:
def __init__(self, corr, wavlen, q_values, num_psi):
"""Initialize a interpolation class for interpolating correlations ================================================================ corr - 2d or 3d float np.array , shape is (num_shot x num_q x num_phi) or (num_shot x num_phi) . it is as... | the_stack_v2_python_sparse | src/RingData/InterpCorr.py | dermen/loki | train | 4 | |
1048a6df81a7f8bf3035efdb8dbba8f9b4679815 | [
"self.l = l\nself.p = p\nself.k = k\nself.theta = np.ones(((self.p + 1) * (self.k + 1), 3)) * 0.5\nself.e = np.zeros((self.p + 1) * (self.k + 1))\nself.distance = np.zeros((self.p + 1) * (self.k + 1))\nself.grid = np.zeros(((self.p + 1) * (self.k + 1), 2))\ncount = 0\nfor i in range(self.p + 1):\n for j in range... | <|body_start_0|>
self.l = l
self.p = p
self.k = k
self.theta = np.ones(((self.p + 1) * (self.k + 1), 3)) * 0.5
self.e = np.zeros((self.p + 1) * (self.k + 1))
self.distance = np.zeros((self.p + 1) * (self.k + 1))
self.grid = np.zeros(((self.p + 1) * (self.k + 1), 2... | QLearningAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QLearningAgent:
def __init__(self, l, p, k, epsilon, alpha, gamma):
"""Initialize your internal state"""
<|body_0|>
def act(self):
"""Choose action depending on your internal state"""
<|body_1|>
def update(self, next_state, reward):
"""Update you... | stack_v2_sparse_classes_75kplus_train_069751 | 6,178 | no_license | [
{
"docstring": "Initialize your internal state",
"name": "__init__",
"signature": "def __init__(self, l, p, k, epsilon, alpha, gamma)"
},
{
"docstring": "Choose action depending on your internal state",
"name": "act",
"signature": "def act(self)"
},
{
"docstring": "Update your in... | 3 | stack_v2_sparse_classes_30k_train_050353 | Implement the Python class `QLearningAgent` described below.
Class description:
Implement the QLearningAgent class.
Method signatures and docstrings:
- def __init__(self, l, p, k, epsilon, alpha, gamma): Initialize your internal state
- def act(self): Choose action depending on your internal state
- def update(self, ... | Implement the Python class `QLearningAgent` described below.
Class description:
Implement the QLearningAgent class.
Method signatures and docstrings:
- def __init__(self, l, p, k, epsilon, alpha, gamma): Initialize your internal state
- def act(self): Choose action depending on your internal state
- def update(self, ... | aee821e9668702e1628d55dcbd1d0227b2c526c5 | <|skeleton|>
class QLearningAgent:
def __init__(self, l, p, k, epsilon, alpha, gamma):
"""Initialize your internal state"""
<|body_0|>
def act(self):
"""Choose action depending on your internal state"""
<|body_1|>
def update(self, next_state, reward):
"""Update you... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QLearningAgent:
def __init__(self, l, p, k, epsilon, alpha, gamma):
"""Initialize your internal state"""
self.l = l
self.p = p
self.k = k
self.theta = np.ones(((self.p + 1) * (self.k + 1), 3)) * 0.5
self.e = np.zeros((self.p + 1) * (self.k + 1))
self.dis... | the_stack_v2_python_sparse | TD3/starter2.py | bastienbrier/Reinforcement-Learning | train | 0 | |
12345da3ad71cbbda7c47bc19e76481739bfc0da | [
"with open(filepath) as fp:\n self.data = fp.read().splitlines()\nself.width = len(self.data[0])\nself.x = 0\nself.y = 0\nself.placement = (0, 0)",
"_x = (self.placement[0] + self.x) % self.width\n_y = (self.placement[0] + self.y) % self.width\nself.placement = (_x, _y)",
"self.x = x\nself.y = y\nself.placem... | <|body_start_0|>
with open(filepath) as fp:
self.data = fp.read().splitlines()
self.width = len(self.data[0])
self.x = 0
self.y = 0
self.placement = (0, 0)
<|end_body_0|>
<|body_start_1|>
_x = (self.placement[0] + self.x) % self.width
_y = (self.place... | Generic Sled class | Sled | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sled:
"""Generic Sled class"""
def __init__(self, filepath):
"""init"""
<|body_0|>
def _new_position(self):
"""calc new position"""
<|body_1|>
def find_trees(self, x, y):
"""find the trees in the way based on slope"""
<|body_2|>
<|en... | stack_v2_sparse_classes_75kplus_train_069752 | 1,345 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, filepath)"
},
{
"docstring": "calc new position",
"name": "_new_position",
"signature": "def _new_position(self)"
},
{
"docstring": "find the trees in the way based on slope",
"name": "find_trees",
... | 3 | stack_v2_sparse_classes_30k_train_005155 | Implement the Python class `Sled` described below.
Class description:
Generic Sled class
Method signatures and docstrings:
- def __init__(self, filepath): init
- def _new_position(self): calc new position
- def find_trees(self, x, y): find the trees in the way based on slope | Implement the Python class `Sled` described below.
Class description:
Generic Sled class
Method signatures and docstrings:
- def __init__(self, filepath): init
- def _new_position(self): calc new position
- def find_trees(self, x, y): find the trees in the way based on slope
<|skeleton|>
class Sled:
"""Generic S... | 9481e4b518eacb86beb42f83906872dcc871c3f7 | <|skeleton|>
class Sled:
"""Generic Sled class"""
def __init__(self, filepath):
"""init"""
<|body_0|>
def _new_position(self):
"""calc new position"""
<|body_1|>
def find_trees(self, x, y):
"""find the trees in the way based on slope"""
<|body_2|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sled:
"""Generic Sled class"""
def __init__(self, filepath):
"""init"""
with open(filepath) as fp:
self.data = fp.read().splitlines()
self.width = len(self.data[0])
self.x = 0
self.y = 0
self.placement = (0, 0)
def _new_position(self):
... | the_stack_v2_python_sparse | day3/run.py | layertwo/adventofcode2020 | train | 0 |
18b9300401a9056f8f097f43ea566ac8423a528d | [
"super(Grid3D, self).__init__(shape)\nif origin.length != 3 or shape.length != 3:\n raise IllegalArgumentException('the length of origin and shape must be 2')",
"if idx < 0 or idx >= shape[0]:\n raise IllegalArgumentException('index out of range')\nitemSize = shape[1] * shape[2] * dataType.getSize()\npos = ... | <|body_start_0|>
super(Grid3D, self).__init__(shape)
if origin.length != 3 or shape.length != 3:
raise IllegalArgumentException('the length of origin and shape must be 2')
<|end_body_0|>
<|body_start_1|>
if idx < 0 or idx >= shape[0]:
raise IllegalArgumentException('inde... | generated source for class Grid3D | Grid3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grid3D:
"""generated source for class Grid3D"""
def __init__(self, data, dataType, origin, shape):
"""generated source for method __init__"""
<|body_0|>
def getGrid2D(self, idx):
"""generated source for method getGrid2D"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_069753 | 1,110 | no_license | [
{
"docstring": "generated source for method __init__",
"name": "__init__",
"signature": "def __init__(self, data, dataType, origin, shape)"
},
{
"docstring": "generated source for method getGrid2D",
"name": "getGrid2D",
"signature": "def getGrid2D(self, idx)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023149 | Implement the Python class `Grid3D` described below.
Class description:
generated source for class Grid3D
Method signatures and docstrings:
- def __init__(self, data, dataType, origin, shape): generated source for method __init__
- def getGrid2D(self, idx): generated source for method getGrid2D | Implement the Python class `Grid3D` described below.
Class description:
generated source for class Grid3D
Method signatures and docstrings:
- def __init__(self, data, dataType, origin, shape): generated source for method __init__
- def getGrid2D(self, idx): generated source for method getGrid2D
<|skeleton|>
class Gr... | 39ec7fc72b63482032e3febfcaabae272f662ecc | <|skeleton|>
class Grid3D:
"""generated source for class Grid3D"""
def __init__(self, data, dataType, origin, shape):
"""generated source for method __init__"""
<|body_0|>
def getGrid2D(self, idx):
"""generated source for method getGrid2D"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grid3D:
"""generated source for class Grid3D"""
def __init__(self, data, dataType, origin, shape):
"""generated source for method __init__"""
super(Grid3D, self).__init__(shape)
if origin.length != 3 or shape.length != 3:
raise IllegalArgumentException('the length of o... | the_stack_v2_python_sparse | tablestore/grid/model/grid/Grid3D.py | leetcode-xu/tablestore-grid | train | 0 |
44462eb6d42cea46ad622054eac699a07e37c013 | [
"from oaautils import i4d\nself._ic = InterferometerConverter()\nself._interf = i4d.I4D()\nself._logger = logging.getLogger('4D')",
"if nframes == 1:\n masked_ima = self._getMeasurementOnTheFly(self._interf)\nelse:\n cube_images = None\n for i in range(nframes):\n ima = self._getMeasurementOnTheFl... | <|body_start_0|>
from oaautils import i4d
self._ic = InterferometerConverter()
self._interf = i4d.I4D()
self._logger = logging.getLogger('4D')
<|end_body_0|>
<|body_start_1|>
if nframes == 1:
masked_ima = self._getMeasurementOnTheFly(self._interf)
else:
... | Class for i4d interferometer | I4dArcetri | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class I4dArcetri:
"""Class for i4d interferometer"""
def __init__(self):
"""The constructor"""
<|body_0|>
def acquire_phasemap(self, nframes=1, show=0):
"""Parameters ---------- nframes: int number of frames show: int 0 to not show the image Returns ------- masked_ima:... | stack_v2_sparse_classes_75kplus_train_069754 | 4,915 | no_license | [
{
"docstring": "The constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Parameters ---------- nframes: int number of frames show: int 0 to not show the image Returns ------- masked_ima: numpy masked array interferometer image",
"name": "acquire_phasemap",
... | 4 | stack_v2_sparse_classes_30k_train_026623 | Implement the Python class `I4dArcetri` described below.
Class description:
Class for i4d interferometer
Method signatures and docstrings:
- def __init__(self): The constructor
- def acquire_phasemap(self, nframes=1, show=0): Parameters ---------- nframes: int number of frames show: int 0 to not show the image Return... | Implement the Python class `I4dArcetri` described below.
Class description:
Class for i4d interferometer
Method signatures and docstrings:
- def __init__(self): The constructor
- def acquire_phasemap(self, nframes=1, show=0): Parameters ---------- nframes: int number of frames show: int 0 to not show the image Return... | cfb3757cc491199248dba767ddf47dce9b191261 | <|skeleton|>
class I4dArcetri:
"""Class for i4d interferometer"""
def __init__(self):
"""The constructor"""
<|body_0|>
def acquire_phasemap(self, nframes=1, show=0):
"""Parameters ---------- nframes: int number of frames show: int 0 to not show the image Returns ------- masked_ima:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class I4dArcetri:
"""Class for i4d interferometer"""
def __init__(self):
"""The constructor"""
from oaautils import i4d
self._ic = InterferometerConverter()
self._interf = i4d.I4D()
self._logger = logging.getLogger('4D')
def acquire_phasemap(self, nframes=1, show=0)... | the_stack_v2_python_sparse | m4/devices/interferometer.py | alfiopuglisi/M4 | train | 0 |
95c30e8261c9ab99b9146d46209704d9556ecd03 | [
"self.r = radius\nself.x = x_center\nself.y = y_center",
"nr = math.sqrt(random.random()) * self.r\nalpha = random.random() * 2 * 3.141592653\nnewx = self.x + nr * math.cos(alpha)\nnewy = self.y + nr * math.sin(alpha)\nreturn [newx, newy]"
] | <|body_start_0|>
self.r = radius
self.x = x_center
self.y = y_center
<|end_body_0|>
<|body_start_1|>
nr = math.sqrt(random.random()) * self.r
alpha = random.random() * 2 * 3.141592653
newx = self.x + nr * math.cos(alpha)
newy = self.y + nr * math.sin(alpha)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.r = radius
... | stack_v2_sparse_classes_75kplus_train_069755 | 1,839 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_038005 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.r = radius
self.x = x_center
self.y = y_center
def randPoint(self):
""":rtype: List[float]"""
nr = math.sqrt(random.random()... | the_stack_v2_python_sparse | leetcode_python/Math/generate-random-point-in-a-circle.py | yennanliu/CS_basics | train | 64 | |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(ActivationLayer, self).__init__(trainable=trainable, name=name)\nself.num_units = num_units\nself._trainable = trainable\nif activation == 'relu':\n self._activation = relu\n self._beta_initializer = 'glorot_uniform'\nelif activation == 'exu':\n self._activation = lambda x, weight, bias: relu_n(exu(... | <|body_start_0|>
super(ActivationLayer, self).__init__(trainable=trainable, name=name)
self.num_units = num_units
self._trainable = trainable
if activation == 'relu':
self._activation = relu
self._beta_initializer = 'glorot_uniform'
elif activation == 'exu... | Custom activation Layer to support ExU hidden units. | ActivationLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationLayer:
"""Custom activation Layer to support ExU hidden units."""
def __init__(self, num_units, name=None, activation='exu', trainable=True):
"""Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. a... | stack_v2_sparse_classes_75kplus_train_069756 | 10,796 | permissive | [
{
"docstring": "Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. activation: Activation to use. The default value of `None` corresponds to using the ReLU-1 activation with ExU units while `relu` would use standard hidden units with R... | 3 | stack_v2_sparse_classes_30k_test_002439 | Implement the Python class `ActivationLayer` described below.
Class description:
Custom activation Layer to support ExU hidden units.
Method signatures and docstrings:
- def __init__(self, num_units, name=None, activation='exu', trainable=True): Initializes ActivationLayer hyperparameters. Args: num_units: Number of ... | Implement the Python class `ActivationLayer` described below.
Class description:
Custom activation Layer to support ExU hidden units.
Method signatures and docstrings:
- def __init__(self, num_units, name=None, activation='exu', trainable=True): Initializes ActivationLayer hyperparameters. Args: num_units: Number of ... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class ActivationLayer:
"""Custom activation Layer to support ExU hidden units."""
def __init__(self, num_units, name=None, activation='exu', trainable=True):
"""Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ActivationLayer:
"""Custom activation Layer to support ExU hidden units."""
def __init__(self, num_units, name=None, activation='exu', trainable=True):
"""Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. activation: Ac... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
4422472c6cc99e21c377dd924f51e7a057a7e16c | [
"self.context = None\nself.temp = tempfile.TemporaryDirectory()\ntry:\n with open(gpg_key, 'rb') as fh:\n keydata = fh.read()\nexcept Exception as e:\n cprint(e, stderr=True, style='error')\n raise GPGException('Unable to load GPG public key file: ' + gpg_key)\nelse:\n try:\n self.context ... | <|body_start_0|>
self.context = None
self.temp = tempfile.TemporaryDirectory()
try:
with open(gpg_key, 'rb') as fh:
keydata = fh.read()
except Exception as e:
cprint(e, stderr=True, style='error')
raise GPGException('Unable to load GPG ... | Basic GPG verifier, which checks a GPG signature against an existing public key. | GPGVerifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPGVerifier:
"""Basic GPG verifier, which checks a GPG signature against an existing public key."""
def __init__(self, gpg_key, gpg_fp):
"""Constructor. gpg_key -- path to the GPG public key file to import gpg_fp -- fingerprint of the GPG key (for verification)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_069757 | 4,130 | permissive | [
{
"docstring": "Constructor. gpg_key -- path to the GPG public key file to import gpg_fp -- fingerprint of the GPG key (for verification)",
"name": "__init__",
"signature": "def __init__(self, gpg_key, gpg_fp)"
},
{
"docstring": "Verifies a data file using an existing GPG context and a detached ... | 2 | stack_v2_sparse_classes_30k_train_010545 | Implement the Python class `GPGVerifier` described below.
Class description:
Basic GPG verifier, which checks a GPG signature against an existing public key.
Method signatures and docstrings:
- def __init__(self, gpg_key, gpg_fp): Constructor. gpg_key -- path to the GPG public key file to import gpg_fp -- fingerprint... | Implement the Python class `GPGVerifier` described below.
Class description:
Basic GPG verifier, which checks a GPG signature against an existing public key.
Method signatures and docstrings:
- def __init__(self, gpg_key, gpg_fp): Constructor. gpg_key -- path to the GPG public key file to import gpg_fp -- fingerprint... | 11ee24435218bbb6c2294d1bb0dd39f2cead1bee | <|skeleton|>
class GPGVerifier:
"""Basic GPG verifier, which checks a GPG signature against an existing public key."""
def __init__(self, gpg_key, gpg_fp):
"""Constructor. gpg_key -- path to the GPG public key file to import gpg_fp -- fingerprint of the GPG key (for verification)"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GPGVerifier:
"""Basic GPG verifier, which checks a GPG signature against an existing public key."""
def __init__(self, gpg_key, gpg_fp):
"""Constructor. gpg_key -- path to the GPG public key file to import gpg_fp -- fingerprint of the GPG key (for verification)"""
self.context = None
... | the_stack_v2_python_sparse | src/tealpkg/gpg_verify.py | drgibbon/tealpkg | train | 0 |
d54d1d1d65b6b11eabdd40794780fa124f3920d5 | [
"super().__init__(logger)\nself.filename = filename\nself.load()",
"for entry in FileHandler(self.logger, self.filename):\n docid = entry.get('root_id')\n self.add(key=docid, value=docid)"
] | <|body_start_0|>
super().__init__(logger)
self.filename = filename
self.load()
<|end_body_0|>
<|body_start_1|>
for entry in FileHandler(self.logger, self.filename):
docid = entry.get('root_id')
self.add(key=docid, value=docid)
<|end_body_1|>
| The container to hold CoreDocuments. | CoreDocuments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoreDocuments:
"""The container to hold CoreDocuments."""
def __init__(self, logger, filename):
"""Initialize the CoreDocuments. Parameters: logger (aida.Logger) filename (str)"""
<|body_0|>
def load(self):
"""Load the file containing core documents into the cont... | stack_v2_sparse_classes_75kplus_train_069758 | 895 | no_license | [
{
"docstring": "Initialize the CoreDocuments. Parameters: logger (aida.Logger) filename (str)",
"name": "__init__",
"signature": "def __init__(self, logger, filename)"
},
{
"docstring": "Load the file containing core documents into the container",
"name": "load",
"signature": "def load(s... | 2 | stack_v2_sparse_classes_30k_train_044572 | Implement the Python class `CoreDocuments` described below.
Class description:
The container to hold CoreDocuments.
Method signatures and docstrings:
- def __init__(self, logger, filename): Initialize the CoreDocuments. Parameters: logger (aida.Logger) filename (str)
- def load(self): Load the file containing core do... | Implement the Python class `CoreDocuments` described below.
Class description:
The container to hold CoreDocuments.
Method signatures and docstrings:
- def __init__(self, logger, filename): Initialize the CoreDocuments. Parameters: logger (aida.Logger) filename (str)
- def load(self): Load the file containing core do... | a0b379ba0e78e8e5eceeda465f75bba5c288aea4 | <|skeleton|>
class CoreDocuments:
"""The container to hold CoreDocuments."""
def __init__(self, logger, filename):
"""Initialize the CoreDocuments. Parameters: logger (aida.Logger) filename (str)"""
<|body_0|>
def load(self):
"""Load the file containing core documents into the cont... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CoreDocuments:
"""The container to hold CoreDocuments."""
def __init__(self, logger, filename):
"""Initialize the CoreDocuments. Parameters: logger (aida.Logger) filename (str)"""
super().__init__(logger)
self.filename = filename
self.load()
def load(self):
""... | the_stack_v2_python_sparse | python/aida/core_documents.py | shahraj81/aida | train | 8 |
7c6fb64589b773c34f34333e6508acfe1dec1fd9 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LifecycleManagementSettings()",
"from ..email_settings import EmailSettings\nfrom ..entity import Entity\nfrom ..email_settings import EmailSettings\nfrom ..entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'emailSettin... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LifecycleManagementSettings()
<|end_body_0|>
<|body_start_1|>
from ..email_settings import EmailSettings
from ..entity import Entity
from ..email_settings import EmailSettings
... | LifecycleManagementSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LifecycleManagementSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_75kplus_train_069759 | 2,715 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: LifecycleManagementSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_047887 | Implement the Python class `LifecycleManagementSettings` described below.
Class description:
Implement the LifecycleManagementSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings: Creates a new instance of the appr... | Implement the Python class `LifecycleManagementSettings` described below.
Class description:
Implement the LifecycleManagementSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LifecycleManagementSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LifecycleManagementSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LifecycleManagementSettings:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | the_stack_v2_python_sparse | msgraph/generated/models/identity_governance/lifecycle_management_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
e063df01da31a836e52be8c53f7d3ed55daa12a0 | [
"self.eval_model = eval_model.to(device)\nself.submission = pd.read_csv(submission_template)\nself.test_dataset = test_dataset\nself.device = device",
"for image, image_name, image_leaderboard in tqdm(self.test_dataset):\n image = image.to(self.device).unsqueeze(0)\n predicted_class, predicted_kev = self.ev... | <|body_start_0|>
self.eval_model = eval_model.to(device)
self.submission = pd.read_csv(submission_template)
self.test_dataset = test_dataset
self.device = device
<|end_body_0|>
<|body_start_1|>
for image, image_name, image_leaderboard in tqdm(self.test_dataset):
imag... | SubmissionMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubmissionMaker:
def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'):
"""[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to archi... | stack_v2_sparse_classes_75kplus_train_069760 | 3,102 | no_license | [
{
"docstring": "[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to architecture] submission_template (str): [Submission template file] test_dataset (IdaoInferenceDataset): [Pytorch dataset for private and public test] device (s... | 2 | stack_v2_sparse_classes_30k_train_011883 | Implement the Python class `SubmissionMaker` described below.
Class description:
Implement the SubmissionMaker class.
Method signatures and docstrings:
- def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'): [Use trained model to make prediction... | Implement the Python class `SubmissionMaker` described below.
Class description:
Implement the SubmissionMaker class.
Method signatures and docstrings:
- def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'): [Use trained model to make prediction... | 56fe9005ebc915acd962a4b17fb057c86ef0ebd8 | <|skeleton|>
class SubmissionMaker:
def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'):
"""[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to archi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubmissionMaker:
def __init__(self, eval_model: nn.Module, submission_template: str, test_dataset: IdaoInferenceDataset, device: str='cuda:0'):
"""[Use trained model to make prediction and generate a submission file] Args: eval_model (nn.Module): [Eval model after loading weight to architecture] submi... | the_stack_v2_python_sparse | src/submission_maker.py | 3outeille/IDAO-2021-Qualifier | train | 0 | |
091de85115b94fa0a83a87880e0d12f6ea83c386 | [
"if not isinstance(event_tag, event.EventTag):\n raise TypeError\njson_dict = {u'__type__': u'EventTag'}\nfor attribute_name, attribute_value in iter(event_tag.__dict__.items()):\n if attribute_value is None:\n continue\n if isinstance(attribute_value, py2to3.BYTES_TYPE):\n attribute_value = ... | <|body_start_0|>
if not isinstance(event_tag, event.EventTag):
raise TypeError
json_dict = {u'__type__': u'EventTag'}
for attribute_name, attribute_value in iter(event_tag.__dict__.items()):
if attribute_value is None:
continue
if isinstance(at... | A class that implements an analysis report JSON encoder. | _AnalysisReportJSONEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _AnalysisReportJSONEncoder:
"""A class that implements an analysis report JSON encoder."""
def _ConvertEventTagToDict(self, event_tag):
"""Converts an event tag object into a JSON dictionary. The resulting dictionary of the JSON serialized objects consists of: { '__type__': 'EventTag... | stack_v2_sparse_classes_75kplus_train_069761 | 28,710 | permissive | [
{
"docstring": "Converts an event tag object into a JSON dictionary. The resulting dictionary of the JSON serialized objects consists of: { '__type__': 'EventTag' ... } Here '__type__' indicates the object base type. In this case 'EventTag'. The rest of the elements of the dictionary make up the event tag objec... | 2 | stack_v2_sparse_classes_30k_train_007234 | Implement the Python class `_AnalysisReportJSONEncoder` described below.
Class description:
A class that implements an analysis report JSON encoder.
Method signatures and docstrings:
- def _ConvertEventTagToDict(self, event_tag): Converts an event tag object into a JSON dictionary. The resulting dictionary of the JSO... | Implement the Python class `_AnalysisReportJSONEncoder` described below.
Class description:
A class that implements an analysis report JSON encoder.
Method signatures and docstrings:
- def _ConvertEventTagToDict(self, event_tag): Converts an event tag object into a JSON dictionary. The resulting dictionary of the JSO... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class _AnalysisReportJSONEncoder:
"""A class that implements an analysis report JSON encoder."""
def _ConvertEventTagToDict(self, event_tag):
"""Converts an event tag object into a JSON dictionary. The resulting dictionary of the JSON serialized objects consists of: { '__type__': 'EventTag... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _AnalysisReportJSONEncoder:
"""A class that implements an analysis report JSON encoder."""
def _ConvertEventTagToDict(self, event_tag):
"""Converts an event tag object into a JSON dictionary. The resulting dictionary of the JSON serialized objects consists of: { '__type__': 'EventTag' ... } Here ... | the_stack_v2_python_sparse | plaso/serializer/json_serializer.py | CNR-ITTIG/plasodfaxp | train | 1 |
8f171c20af7b541f6281396466d4cd1114e16e99 | [
"if not head or not head.next:\n return head\nq = head.next\nhead.next = self.swapPairs(q.next)\nq.next = head\nreturn q",
"dummy = ListNode(0)\ndummy.next = head\nprev_node = dummy\nwhile head and head.next:\n p = head.next\n prev_node.next = p\n head.next, p.next = (p.next, head)\n prev_node, hea... | <|body_start_0|>
if not head or not head.next:
return head
q = head.next
head.next = self.swapPairs(q.next)
q.next = head
return q
<|end_body_0|>
<|body_start_1|>
dummy = ListNode(0)
dummy.next = head
prev_node = dummy
while head and h... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归法 交换前两个结点,递归后续链表 时间复杂度:O(N), 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :param n: :return:ListNode"""
<|body_0|>
def swapPairs_iteration(self, head: ListNode) -> ListNode:
"""迭代 A->B->C->D 交换BC: t = a t.next =... | stack_v2_sparse_classes_75kplus_train_069762 | 2,798 | no_license | [
{
"docstring": "递归法 交换前两个结点,递归后续链表 时间复杂度:O(N), 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :param n: :return:ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head: ListNode) -> ListNode"
},
{
"docstring": "迭代 A->B->C->D 交换BC: t = a t.next = c b.next, c.next = c.next, b # 清理以进行下一步 head,... | 2 | stack_v2_sparse_classes_30k_train_052509 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 递归法 交换前两个结点,递归后续链表 时间复杂度:O(N), 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :param n: :return:ListNode
- def swapPairs_iteration(self, he... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head: ListNode) -> ListNode: 递归法 交换前两个结点,递归后续链表 时间复杂度:O(N), 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :param n: :return:ListNode
- def swapPairs_iteration(self, he... | 62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c | <|skeleton|>
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归法 交换前两个结点,递归后续链表 时间复杂度:O(N), 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :param n: :return:ListNode"""
<|body_0|>
def swapPairs_iteration(self, head: ListNode) -> ListNode:
"""迭代 A->B->C->D 交换BC: t = a t.next =... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""递归法 交换前两个结点,递归后续链表 时间复杂度:O(N), 空间复杂度:O(N),递归过程使用的堆栈空间。 :param head: :param n: :return:ListNode"""
if not head or not head.next:
return head
q = head.next
head.next = self.swapPairs(q.next)
q.next ... | the_stack_v2_python_sparse | leetcode/solved/024_.py | usnnu/python_foundation | train | 0 | |
8f400e0a65dafdedd8a1eb4134c1c5e732c8b671 | [
"workout_volume = 0\nfor log in logs:\n log_sets = Set.objects.filter(log=log)\n for set in log_sets:\n if set.unit == 'lbs':\n workout_volume += set.weight * set.reps\n else:\n workout_volume += set.weight * 2.20462 * set.reps\nreturn workout_volume",
"log_volume = 0\nlo... | <|body_start_0|>
workout_volume = 0
for log in logs:
log_sets = Set.objects.filter(log=log)
for set in log_sets:
if set.unit == 'lbs':
workout_volume += set.weight * set.reps
else:
workout_volume += set.weigh... | WorkoutDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkoutDetail:
def total_volume(self, logs):
"""Function to caluclate volume of all logs"""
<|body_0|>
def get_log_volume(self, log):
"""Gets volume of a log"""
<|body_1|>
def get_chart_data(self, logs):
"""Gets data for chart.js plot"""
... | stack_v2_sparse_classes_75kplus_train_069763 | 11,288 | no_license | [
{
"docstring": "Function to caluclate volume of all logs",
"name": "total_volume",
"signature": "def total_volume(self, logs)"
},
{
"docstring": "Gets volume of a log",
"name": "get_log_volume",
"signature": "def get_log_volume(self, log)"
},
{
"docstring": "Gets data for chart.j... | 5 | null | Implement the Python class `WorkoutDetail` described below.
Class description:
Implement the WorkoutDetail class.
Method signatures and docstrings:
- def total_volume(self, logs): Function to caluclate volume of all logs
- def get_log_volume(self, log): Gets volume of a log
- def get_chart_data(self, logs): Gets data... | Implement the Python class `WorkoutDetail` described below.
Class description:
Implement the WorkoutDetail class.
Method signatures and docstrings:
- def total_volume(self, logs): Function to caluclate volume of all logs
- def get_log_volume(self, log): Gets volume of a log
- def get_chart_data(self, logs): Gets data... | 9b0ee1f2a7f15225dd7b8be09862b3d6419d6297 | <|skeleton|>
class WorkoutDetail:
def total_volume(self, logs):
"""Function to caluclate volume of all logs"""
<|body_0|>
def get_log_volume(self, log):
"""Gets volume of a log"""
<|body_1|>
def get_chart_data(self, logs):
"""Gets data for chart.js plot"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkoutDetail:
def total_volume(self, logs):
"""Function to caluclate volume of all logs"""
workout_volume = 0
for log in logs:
log_sets = Set.objects.filter(log=log)
for set in log_sets:
if set.unit == 'lbs':
workout_volume +... | the_stack_v2_python_sparse | workout/views.py | chrislockard21/workout_app | train | 0 | |
90b61c67022ddea582804ac8952d825dac68f539 | [
"result = api.neutron.subnet_list(request, **request.GET)\nif request.GET.get('ensure_with_router', False):\n result = rest_utils.ensure_subnet_with_router(request, result)\nresult = rest_utils.ensure_network_detial_for_subnet(request, [n.to_dict() for n in result])\nreturn {'items': result}",
"new_subnet = ap... | <|body_start_0|>
result = api.neutron.subnet_list(request, **request.GET)
if request.GET.get('ensure_with_router', False):
result = rest_utils.ensure_subnet_with_router(request, result)
result = rest_utils.ensure_network_detial_for_subnet(request, [n.to_dict() for n in result])
... | API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets | Subnets | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subnets:
"""API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets"""
def get(self, request):
"""Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet."""
<|body_0|>
def post(se... | stack_v2_sparse_classes_75kplus_train_069764 | 30,067 | permissive | [
{
"docstring": "Get a list of subnets for a project The listing result is an object with property \"items\". Each item is a subnet.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Create a Subnet for a given Network :param name (optional): The subnet name. :param networ... | 2 | stack_v2_sparse_classes_30k_train_043704 | Implement the Python class `Subnets` described below.
Class description:
API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets
Method signatures and docstrings:
- def get(self, request): Get a list of subnets for a project The listing result is an object with property "items". Each... | Implement the Python class `Subnets` described below.
Class description:
API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets
Method signatures and docstrings:
- def get(self, request): Get a list of subnets for a project The listing result is an object with property "items". Each... | 9524f1952461c83db485d5d1702c350b158d7ce0 | <|skeleton|>
class Subnets:
"""API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets"""
def get(self, request):
"""Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet."""
<|body_0|>
def post(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Subnets:
"""API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets"""
def get(self, request):
"""Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet."""
result = api.neutron.subnet_list(request... | the_stack_v2_python_sparse | easystack_dashboard/api/rest/neutron.py | oksbsb/horizon-acc | train | 0 |
c6e1b2e3f9b1b14f4881ee9baa0e1999835e5ac2 | [
"width = 3.0\ntriangular_weights_instance = ChooseDefaultWeightsTriangular(width, units='hours')\nresult = str(triangular_weights_instance)\nexpected = '<ChooseDefaultTriangularWeights width=3.0, parameters_units=hours>'\nself.assertEqual(result, expected)",
"width = 3.0\ntriangular_weights_instance = ChooseDefau... | <|body_start_0|>
width = 3.0
triangular_weights_instance = ChooseDefaultWeightsTriangular(width, units='hours')
result = str(triangular_weights_instance)
expected = '<ChooseDefaultTriangularWeights width=3.0, parameters_units=hours>'
self.assertEqual(result, expected)
<|end_body_... | Tests for the __repr__function | Test___repr__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test___repr__:
"""Tests for the __repr__function"""
def test_basic(self):
"""Test the repr function formats the arguments correctly"""
<|body_0|>
def test_basic_no_units(self):
"""Test the repr function formats the arguments correctly"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_069765 | 13,166 | permissive | [
{
"docstring": "Test the repr function formats the arguments correctly",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test the repr function formats the arguments correctly",
"name": "test_basic_no_units",
"signature": "def test_basic_no_units(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_047044 | Implement the Python class `Test___repr__` described below.
Class description:
Tests for the __repr__function
Method signatures and docstrings:
- def test_basic(self): Test the repr function formats the arguments correctly
- def test_basic_no_units(self): Test the repr function formats the arguments correctly | Implement the Python class `Test___repr__` described below.
Class description:
Tests for the __repr__function
Method signatures and docstrings:
- def test_basic(self): Test the repr function formats the arguments correctly
- def test_basic_no_units(self): Test the repr function formats the arguments correctly
<|skel... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test___repr__:
"""Tests for the __repr__function"""
def test_basic(self):
"""Test the repr function formats the arguments correctly"""
<|body_0|>
def test_basic_no_units(self):
"""Test the repr function formats the arguments correctly"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test___repr__:
"""Tests for the __repr__function"""
def test_basic(self):
"""Test the repr function formats the arguments correctly"""
width = 3.0
triangular_weights_instance = ChooseDefaultWeightsTriangular(width, units='hours')
result = str(triangular_weights_instance)
... | the_stack_v2_python_sparse | improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py | metoppv/improver | train | 101 |
a52197b59eda44c3b937a925affb83433f628d98 | [
"super().__init__()\nKp = diagonalize_gain(to_tensor(Kp))\nKd = diagonalize_gain(to_tensor(Kd))\nassert Kp.shape == torch.Size([6, 6])\nassert Kd.shape == torch.Size([6, 6])\nself.Kp = torch.nn.Parameter(Kp)\nself.Kd = torch.nn.Parameter(Kd)",
"ee_pose_err = (ee_pose_current.inv() * ee_pose_desired).as_twist()\ne... | <|body_start_0|>
super().__init__()
Kp = diagonalize_gain(to_tensor(Kp))
Kd = diagonalize_gain(to_tensor(Kd))
assert Kp.shape == torch.Size([6, 6])
assert Kd.shape == torch.Size([6, 6])
self.Kp = torch.nn.Parameter(Kp)
self.Kd = torch.nn.Parameter(Kd)
<|end_body_0... | PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6) | CartesianSpacePD | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartesianSpacePD:
"""PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)"""
def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor):
"""Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-... | stack_v2_sparse_classes_75kplus_train_069766 | 9,060 | permissive | [
{
"docstring": "Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal matrix Kd: D gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal matrix",
"name": "__init__",
"signature": "def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_015886 | Implement the Python class `CartesianSpacePD` described below.
Class description:
PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)
Method signatures and docstrings:
- def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor): Args: Kp: P ga... | Implement the Python class `CartesianSpacePD` described below.
Class description:
PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)
Method signatures and docstrings:
- def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor): Args: Kp: P ga... | 1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18 | <|skeleton|>
class CartesianSpacePD:
"""PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)"""
def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor):
"""Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CartesianSpacePD:
"""PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)"""
def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor):
"""Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal... | the_stack_v2_python_sparse | polymetis/python/torchcontrol/modules/feedback.py | facebookresearch/polymetis | train | 44 |
964e6eb1bc64379672c99bf5e2df0d8aa023642f | [
"A = list(set(A))\nlength = len(A)\nstart = 0\nend = length - 1\nwhile start <= end:\n mid = (start + end) / 2\n if A[mid] == target:\n return True\n if A[start] < A[mid] < A[end]:\n if target > A[mid]:\n start = mid + 1\n else:\n end = mid - 1\n elif A[start] ... | <|body_start_0|>
A = list(set(A))
length = len(A)
start = 0
end = length - 1
while start <= end:
mid = (start + end) / 2
if A[mid] == target:
return True
if A[start] < A[mid] < A[end]:
if target > A[mid]:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search_set(self, A, target):
"""Follow up 033 Search in Rotated Sorted Array Duplicate allowed rotated cases: target is 3 start mid end case 1: 1, 1, 1, 1, 1, 3, 1 case 2: 1, 3, 1, 1, 1, 1, 1 Algorithm: eliminate duplicates :param A: a list of integers :param target: an int... | stack_v2_sparse_classes_75kplus_train_069767 | 3,172 | permissive | [
{
"docstring": "Follow up 033 Search in Rotated Sorted Array Duplicate allowed rotated cases: target is 3 start mid end case 1: 1, 1, 1, 1, 1, 3, 1 case 2: 1, 3, 1, 1, 1, 1, 1 Algorithm: eliminate duplicates :param A: a list of integers :param target: an integer :return: a boolean",
"name": "search_set",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search_set(self, A, target): Follow up 033 Search in Rotated Sorted Array Duplicate allowed rotated cases: target is 3 start mid end case 1: 1, 1, 1, 1, 1, 3, 1 case 2: 1, 3,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search_set(self, A, target): Follow up 033 Search in Rotated Sorted Array Duplicate allowed rotated cases: target is 3 start mid end case 1: 1, 1, 1, 1, 1, 3, 1 case 2: 1, 3,... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def search_set(self, A, target):
"""Follow up 033 Search in Rotated Sorted Array Duplicate allowed rotated cases: target is 3 start mid end case 1: 1, 1, 1, 1, 1, 3, 1 case 2: 1, 3, 1, 1, 1, 1, 1 Algorithm: eliminate duplicates :param A: a list of integers :param target: an int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search_set(self, A, target):
"""Follow up 033 Search in Rotated Sorted Array Duplicate allowed rotated cases: target is 3 start mid end case 1: 1, 1, 1, 1, 1, 3, 1 case 2: 1, 3, 1, 1, 1, 1, 1 Algorithm: eliminate duplicates :param A: a list of integers :param target: an integer :return: ... | the_stack_v2_python_sparse | 080 Search in Rotated Sorted Array II.py | Aminaba123/LeetCode | train | 1 | |
5f8d630ae8bed336ba8b3708f5cd597b7bdce910 | [
"check_scalar(self.epsilon, 'epsilon', float, min_val=0.0, max_val=1.0)\nself.policy_name = f'logistic_egreedy_{self.epsilon}'\nsuper().__post_init__()",
"if self.random_.rand() > self.epsilon:\n theta = np.array([model.predict_proba(context) for model in self.model_list]).flatten()\n return theta.argsort()... | <|body_start_0|>
check_scalar(self.epsilon, 'epsilon', float, min_val=0.0, max_val=1.0)
self.policy_name = f'logistic_egreedy_{self.epsilon}'
super().__post_init__()
<|end_body_0|>
<|body_start_1|>
if self.random_.rand() > self.epsilon:
theta = np.array([model.predict_proba(... | Logistic Epsilon Greedy. Parameters ----------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_size: int, default=1 Number of samples used in... | LogisticEpsilonGreedy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticEpsilonGreedy:
"""Logistic Epsilon Greedy. Parameters ----------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. bat... | stack_v2_sparse_classes_75kplus_train_069768 | 10,908 | permissive | [
{
"docstring": "Initialize class.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Select action for new data. Parameters ---------- context: array-like, shape (1, dim_context) Observed context vector. Returns ---------- selected_actions: array-like, s... | 2 | stack_v2_sparse_classes_30k_train_050387 | Implement the Python class `LogisticEpsilonGreedy` described below.
Class description:
Logistic Epsilon Greedy. Parameters ----------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandi... | Implement the Python class `LogisticEpsilonGreedy` described below.
Class description:
Logistic Epsilon Greedy. Parameters ----------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandi... | 53598edab284b4364d127ec5662137de3f9c1206 | <|skeleton|>
class LogisticEpsilonGreedy:
"""Logistic Epsilon Greedy. Parameters ----------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. bat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogisticEpsilonGreedy:
"""Logistic Epsilon Greedy. Parameters ----------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_size: int,... | the_stack_v2_python_sparse | obp/policy/logistic.py | han20192019/newRL | train | 0 |
bcd288a07504223350863aebc93d3e5b7953e458 | [
"parent = self.cleaned_data['parent']\nif parent is None:\n return parent\nif parent.id == self.instance.id:\n raise forms.ValidationError(\"Comment cannot be it's reply\")\nchecked_comment = parent\nwhile checked_comment is not None:\n throw = False\n if checked_comment.id == self.instance.id:\n ... | <|body_start_0|>
parent = self.cleaned_data['parent']
if parent is None:
return parent
if parent.id == self.instance.id:
raise forms.ValidationError("Comment cannot be it's reply")
checked_comment = parent
while checked_comment is not None:
thr... | CommentAdminForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentAdminForm:
def clean_parent(self):
"""Check that it doesnt refer to itself, and that theres no reply loop"""
<|body_0|>
def clean(self):
"""A Comment should not be attached to a post and a comment"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069769 | 2,510 | no_license | [
{
"docstring": "Check that it doesnt refer to itself, and that theres no reply loop",
"name": "clean_parent",
"signature": "def clean_parent(self)"
},
{
"docstring": "A Comment should not be attached to a post and a comment",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000433 | Implement the Python class `CommentAdminForm` described below.
Class description:
Implement the CommentAdminForm class.
Method signatures and docstrings:
- def clean_parent(self): Check that it doesnt refer to itself, and that theres no reply loop
- def clean(self): A Comment should not be attached to a post and a co... | Implement the Python class `CommentAdminForm` described below.
Class description:
Implement the CommentAdminForm class.
Method signatures and docstrings:
- def clean_parent(self): Check that it doesnt refer to itself, and that theres no reply loop
- def clean(self): A Comment should not be attached to a post and a co... | 8abf6b77fdf4c692b456c8c062d3114aaeb16c04 | <|skeleton|>
class CommentAdminForm:
def clean_parent(self):
"""Check that it doesnt refer to itself, and that theres no reply loop"""
<|body_0|>
def clean(self):
"""A Comment should not be attached to a post and a comment"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommentAdminForm:
def clean_parent(self):
"""Check that it doesnt refer to itself, and that theres no reply loop"""
parent = self.cleaned_data['parent']
if parent is None:
return parent
if parent.id == self.instance.id:
raise forms.ValidationError("Comme... | the_stack_v2_python_sparse | api/apps/posts/admin.py | dstarner/townvisor-backend | train | 0 | |
a107d7d6c158e813ba4fdcbe3a97f9dd21d3f30f | [
"if not digits:\n return []\nd = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\nn = len(digits)\ndp = [[] for _ in range(n)]\ndp[0] = [x for x in d[digits[0]]]\nfor i in range(1, n):\n dp[i] = [x + y for x in dp[i - 1] for y in d[digits[i]]]\nreturn dp[-1]"... | <|body_start_0|>
if not digits:
return []
d = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
n = len(digits)
dp = [[] for _ in range(n)]
dp[0] = [x for x in d[digits[0]]]
for i in range(1, n):
dp[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
"""动态规划 dp[i]: 前i个字母的所有组合 由于dp[i]只与dp[i-1]有关,可以使用变量代替列表存储降低空间复杂度 :type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations2(self, digits):
"""使用变量代替上面的列表 降低空间复杂度 :type digits: str :rtype: List[str]"""
... | stack_v2_sparse_classes_75kplus_train_069770 | 2,073 | no_license | [
{
"docstring": "动态规划 dp[i]: 前i个字母的所有组合 由于dp[i]只与dp[i-1]有关,可以使用变量代替列表存储降低空间复杂度 :type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
},
{
"docstring": "使用变量代替上面的列表 降低空间复杂度 :type digits: str :rtype: List[str]",
"name": "letterCo... | 3 | stack_v2_sparse_classes_30k_train_029602 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): 动态规划 dp[i]: 前i个字母的所有组合 由于dp[i]只与dp[i-1]有关,可以使用变量代替列表存储降低空间复杂度 :type digits: str :rtype: List[str]
- def letterCombinations2(self, digits): 使... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits): 动态规划 dp[i]: 前i个字母的所有组合 由于dp[i]只与dp[i-1]有关,可以使用变量代替列表存储降低空间复杂度 :type digits: str :rtype: List[str]
- def letterCombinations2(self, digits): 使... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def letterCombinations(self, digits):
"""动态规划 dp[i]: 前i个字母的所有组合 由于dp[i]只与dp[i-1]有关,可以使用变量代替列表存储降低空间复杂度 :type digits: str :rtype: List[str]"""
<|body_0|>
def letterCombinations2(self, digits):
"""使用变量代替上面的列表 降低空间复杂度 :type digits: str :rtype: List[str]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def letterCombinations(self, digits):
"""动态规划 dp[i]: 前i个字母的所有组合 由于dp[i]只与dp[i-1]有关,可以使用变量代替列表存储降低空间复杂度 :type digits: str :rtype: List[str]"""
if not digits:
return []
d = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'w... | the_stack_v2_python_sparse | 17_电话号码的字母组合.py | lovehhf/LeetCode | train | 0 | |
ee26eb86a6a90c6b4badd59216bb48100934e49e | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('medinad', 'medinad')\npolice = repo.medinad.police\nneighborhoods = repo.medinad.neighbor\n\ndef product(R, S):\n return [(t, u) for t in R for u in S]\n\ndef project(R, p):\n return [p(t) for t in... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('medinad', 'medinad')
police = repo.medinad.police
neighborhoods = repo.medinad.neighbor
def product(R, S):
return [(t, u) for... | policeneighbors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class policeneighbors:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_75kplus_train_069771 | 5,402 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_009188 | Implement the Python class `policeneighbors` described below.
Class description:
Implement the policeneighbors class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | Implement the Python class `policeneighbors` described below.
Class description:
Implement the policeneighbors class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=Non... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class policeneighbors:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everythi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class policeneighbors:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('medinad', 'medinad')
police... | the_stack_v2_python_sparse | jtbloom_rfballes_medinad/medinad/policeneighbors.py | ROODAY/course-2017-fal-proj | train | 3 | |
95a471991bc9e5dd14f77180b6e002b3a149a142 | [
"self.t = self.ctx.convert(t)\nif 'degree' in kwargs:\n self.degree = kwargs['degree']\n self.dps_goal = int(1.38 * self.degree)\nelse:\n self.dps_goal = int(2.93 * self.ctx.dps)\n self.degree = max(16, self.dps_goal)\nif self.degree % 2 > 0:\n self.degree += 1\nM = self.degree\nself.dps_orig = self.... | <|body_start_0|>
self.t = self.ctx.convert(t)
if 'degree' in kwargs:
self.degree = kwargs['degree']
self.dps_goal = int(1.38 * self.degree)
else:
self.dps_goal = int(2.93 * self.ctx.dps)
self.degree = max(16, self.dps_goal)
if self.degree %... | Stehfest | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stehfest:
def calc_laplace_parameter(self, t, **kwargs):
"""The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of the Bromwich contour integral. The method abscissa along the real axis, and therefore has issues... | stack_v2_sparse_classes_75kplus_train_069772 | 36,056 | permissive | [
{
"docstring": "The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of the Bromwich contour integral. The method abscissa along the real axis, and therefore has issues inverting oscillatory functions (which have poles in pairs away fro... | 3 | stack_v2_sparse_classes_30k_train_052941 | Implement the Python class `Stehfest` described below.
Class description:
Implement the Stehfest class.
Method signatures and docstrings:
- def calc_laplace_parameter(self, t, **kwargs): The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of... | Implement the Python class `Stehfest` described below.
Class description:
Implement the Stehfest class.
Method signatures and docstrings:
- def calc_laplace_parameter(self, t, **kwargs): The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class Stehfest:
def calc_laplace_parameter(self, t, **kwargs):
"""The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of the Bromwich contour integral. The method abscissa along the real axis, and therefore has issues... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Stehfest:
def calc_laplace_parameter(self, t, **kwargs):
"""The Gaver-Stehfest method is a discrete approximation of the Widder-Post inversion algorithm, rather than a direct approximation of the Bromwich contour integral. The method abscissa along the real axis, and therefore has issues inverting osc... | the_stack_v2_python_sparse | contrib/python/mpmath/mpmath/calculus/inverselaplace.py | catboost/catboost | train | 8,012 | |
7a9a12f511c5ba3661570e3a207ca114377adffa | [
"delimiter = kwargs.get('delimiter', ',')\nwith open(filename, 'r') as csv_file:\n reader = csv.reader(csv_file, delimiter=delimiter)\n csv_headers = next(reader)\n csv_entries = list(reader)\nreturn (csv_headers, cls()._get_entries(csv_headers, csv_entries))",
"delimiter = kwargs.get('delimiter', ',')\n... | <|body_start_0|>
delimiter = kwargs.get('delimiter', ',')
with open(filename, 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=delimiter)
csv_headers = next(reader)
csv_entries = list(reader)
return (csv_headers, cls()._get_entries(csv_headers, csv_en... | Class to save or load data from .csv tables | CSVDataProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVDataProvider:
"""Class to save or load data from .csv tables"""
def load_data(cls, filename, **kwargs):
"""Method to get data from csv file Args: filename (str): source filename with extension **kwargs : optional argument for opening csv file *23/03/18 - defined only for csv delim... | stack_v2_sparse_classes_75kplus_train_069773 | 26,005 | no_license | [
{
"docstring": "Method to get data from csv file Args: filename (str): source filename with extension **kwargs : optional argument for opening csv file *23/03/18 - defined only for csv delimiter symbol Returns: csv_headers (list): headers of csv table csv_entries (list): rows of csv table. Each row is list of v... | 2 | null | Implement the Python class `CSVDataProvider` described below.
Class description:
Class to save or load data from .csv tables
Method signatures and docstrings:
- def load_data(cls, filename, **kwargs): Method to get data from csv file Args: filename (str): source filename with extension **kwargs : optional argument fo... | Implement the Python class `CSVDataProvider` described below.
Class description:
Class to save or load data from .csv tables
Method signatures and docstrings:
- def load_data(cls, filename, **kwargs): Method to get data from csv file Args: filename (str): source filename with extension **kwargs : optional argument fo... | c627dd404e5073eff6093bbd2b35273be77520a9 | <|skeleton|>
class CSVDataProvider:
"""Class to save or load data from .csv tables"""
def load_data(cls, filename, **kwargs):
"""Method to get data from csv file Args: filename (str): source filename with extension **kwargs : optional argument for opening csv file *23/03/18 - defined only for csv delim... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSVDataProvider:
"""Class to save or load data from .csv tables"""
def load_data(cls, filename, **kwargs):
"""Method to get data from csv file Args: filename (str): source filename with extension **kwargs : optional argument for opening csv file *23/03/18 - defined only for csv delimiter symbol R... | the_stack_v2_python_sparse | task_6/data_reader.py | de-don/PyCamp2018-1 | train | 0 |
05ff7165c3accbfe91245fa3717df4bb146813d1 | [
"self.shape = shape\nif 'reduction' in additional_params:\n self.dim_reduction_alg = additional_params['reduction']\nelse:\n self.dim_reduction_alg = identity_mapping\nself.stats = {}\nself.project = project",
"cluster_centers = []\nmarkings_per_cluster = []\nusers_per_cluster = []\ntime_to_cluster = 0\nret... | <|body_start_0|>
self.shape = shape
if 'reduction' in additional_params:
self.dim_reduction_alg = additional_params['reduction']
else:
self.dim_reduction_alg = identity_mapping
self.stats = {}
self.project = project
<|end_body_0|>
<|body_start_1|>
... | Cluster | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cluster:
def __init__(self, shape, project, additional_params):
""":param project_api: how to talk to whatever project we are clustering for (Panoptes/Ouroboros shouldn't matter) :param min_cluster_size: minimum number of points in a cluster to not be considered noise :return:"""
... | stack_v2_sparse_classes_75kplus_train_069774 | 5,424 | permissive | [
{
"docstring": ":param project_api: how to talk to whatever project we are clustering for (Panoptes/Ouroboros shouldn't matter) :param min_cluster_size: minimum number of points in a cluster to not be considered noise :return:",
"name": "__init__",
"signature": "def __init__(self, shape, project, additi... | 3 | null | Implement the Python class `Cluster` described below.
Class description:
Implement the Cluster class.
Method signatures and docstrings:
- def __init__(self, shape, project, additional_params): :param project_api: how to talk to whatever project we are clustering for (Panoptes/Ouroboros shouldn't matter) :param min_cl... | Implement the Python class `Cluster` described below.
Class description:
Implement the Cluster class.
Method signatures and docstrings:
- def __init__(self, shape, project, additional_params): :param project_api: how to talk to whatever project we are clustering for (Panoptes/Ouroboros shouldn't matter) :param min_cl... | 82dce87eaaf14b0b2bedd29fc82c026fda2a0138 | <|skeleton|>
class Cluster:
def __init__(self, shape, project, additional_params):
""":param project_api: how to talk to whatever project we are clustering for (Panoptes/Ouroboros shouldn't matter) :param min_cluster_size: minimum number of points in a cluster to not be considered noise :return:"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cluster:
def __init__(self, shape, project, additional_params):
""":param project_api: how to talk to whatever project we are clustering for (Panoptes/Ouroboros shouldn't matter) :param min_cluster_size: minimum number of points in a cluster to not be considered noise :return:"""
self.shape = ... | the_stack_v2_python_sparse | engine/clustering.py | visenger/aggregation | train | 0 | |
2cf41dcdb4ababc9e237bf4b4f9bbefe0d070df5 | [
"memory = [0, 0, 0]\nfor n in nums:\n if n == 0:\n memory[0] += 1\n elif n == 1:\n memory[1] += 1\n elif n == 2:\n memory[2] += 1\n else:\n print('Unexpceted Value Error! ')\n break\nfor i in range(len(nums)):\n if memory[0] > 0:\n nums[i] = 0\n memory... | <|body_start_0|>
memory = [0, 0, 0]
for n in nums:
if n == 0:
memory[0] += 1
elif n == 1:
memory[1] += 1
elif n == 2:
memory[2] += 1
else:
print('Unexpceted Value Error! ')
bre... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColorsII(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body... | stack_v2_sparse_classes_75kplus_train_069775 | 2,335 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.",
"name": "sortColors",
"signature": "def sortColors(self, nums)"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "sortColorsII",
"signature": "def ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def sortColorsII(self, nums: List[int]) -> None: Do not ret... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
- def sortColorsII(self, nums: List[int]) -> None: Do not ret... | d1666d44226274f13af25cf878cd63a24e1c5528 | <|skeleton|>
class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
<|body_0|>
def sortColorsII(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors(self, nums):
""":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead."""
memory = [0, 0, 0]
for n in nums:
if n == 0:
memory[0] += 1
elif n == 1:
memory[1] += 1
... | the_stack_v2_python_sparse | TwoPointers/LeetCode075_SortColors.py | rexhzhang/LeetCodeProbelms | train | 0 | |
e4bd4e026014f0d9e649587f4fdf315675b26680 | [
"if self.birth_date:\n d1 = datetime.strptime(self.birth_date, '%Y-%m-%d').date()\n d2 = date.today()\n self.age = relativedelta(d2, d1).years",
"for rec in self.env['res.partner'].search([]):\n if rec.birth_date:\n d1 = datetime.strptime(rec.birth_date, '%Y-%m-%d').date()\n d2 = date.to... | <|body_start_0|>
if self.birth_date:
d1 = datetime.strptime(self.birth_date, '%Y-%m-%d').date()
d2 = date.today()
self.age = relativedelta(d2, d1).years
<|end_body_0|>
<|body_start_1|>
for rec in self.env['res.partner'].search([]):
if rec.birth_date:
... | ResPartnerWebsiteDating | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResPartnerWebsiteDating:
def _onchange_birth_date(self):
"""Updates age when DOB is changed"""
<|body_0|>
def update_ages(self):
"""Updates the ages of all partners in the database once a day"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.b... | stack_v2_sparse_classes_75kplus_train_069776 | 4,355 | no_license | [
{
"docstring": "Updates age when DOB is changed",
"name": "_onchange_birth_date",
"signature": "def _onchange_birth_date(self)"
},
{
"docstring": "Updates the ages of all partners in the database once a day",
"name": "update_ages",
"signature": "def update_ages(self)"
}
] | 2 | null | Implement the Python class `ResPartnerWebsiteDating` described below.
Class description:
Implement the ResPartnerWebsiteDating class.
Method signatures and docstrings:
- def _onchange_birth_date(self): Updates age when DOB is changed
- def update_ages(self): Updates the ages of all partners in the database once a day | Implement the Python class `ResPartnerWebsiteDating` described below.
Class description:
Implement the ResPartnerWebsiteDating class.
Method signatures and docstrings:
- def _onchange_birth_date(self): Updates age when DOB is changed
- def update_ages(self): Updates the ages of all partners in the database once a day... | 244027275aa92c0b40a0929854797ca4d173269d | <|skeleton|>
class ResPartnerWebsiteDating:
def _onchange_birth_date(self):
"""Updates age when DOB is changed"""
<|body_0|>
def update_ages(self):
"""Updates the ages of all partners in the database once a day"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResPartnerWebsiteDating:
def _onchange_birth_date(self):
"""Updates age when DOB is changed"""
if self.birth_date:
d1 = datetime.strptime(self.birth_date, '%Y-%m-%d').date()
d2 = date.today()
self.age = relativedelta(d2, d1).years
def update_ages(self):... | the_stack_v2_python_sparse | website_dating/models/res_partner.py | Openworx/Odoo9 | train | 1 | |
a5b8998b949eb91845c969352a5609834ae8907f | [
"super(Test200SmartSanityClear005, self).prepare()\nself.logger.info('Preconditions:')\nself.logger.info('1. Open Micro/WINr; ')\nself.logger.info('2. Set up connection with PLC;')\nself.logger.info('3. Download a project which has OB,DB,SDB;')\nself.MicroWIN.test_prepare('reset_factory_01.smart', False)\nself.PLC... | <|body_start_0|>
super(Test200SmartSanityClear005, self).prepare()
self.logger.info('Preconditions:')
self.logger.info('1. Open Micro/WINr; ')
self.logger.info('2. Set up connection with PLC;')
self.logger.info('3. Download a project which has OB,DB,SDB;')
self.MicroWIN.... | Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected results: 1. Clear successful, all blocks is cleared, all use... | Test200SmartSanityClear005 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test200SmartSanityClear005:
"""Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected result... | stack_v2_sparse_classes_75kplus_train_069777 | 3,885 | no_license | [
{
"docstring": "the preparation before executing the test steps Args: Example: Return: Author: Cai, Yong IsInterface: False ChangeInfo: Cai, Yong 2019-09-20 create",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "execute the test steps Args: Example: Return: Author: Cai, ... | 3 | stack_v2_sparse_classes_30k_train_000485 | Implement the Python class `Test200SmartSanityClear005` described below.
Class description:
Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in cle... | Implement the Python class `Test200SmartSanityClear005` described below.
Class description:
Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in cle... | 2d3490393737b3e5f086cb6623369b988ffce67f | <|skeleton|>
class Test200SmartSanityClear005:
"""Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected result... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test200SmartSanityClear005:
"""Reset to factory defaults No.: test_200smart_sanity_clear_005 Preconditions: 1. Open Micro/WINr; 2. Set up connection with PLC; 3. Download a project which has OB,DB,SDB; Step actions: 1. Select Reset to factory defaults in clear popup; 2. Compare; ; Expected results: 1. Clear s... | the_stack_v2_python_sparse | test_case/no_piling/sanity/base/clear/test_200smart_sanity_clear_005.py | Lewescaiyong/auto_test_framework | train | 1 |
b865b540d99e98095237d2a540ea8eca96493564 | [
"try:\n User.objects.get(username__iexact=self.cleaned_data['username'])\nexcept User.DoesNotExist:\n return self.cleaned_data['username']\nraise forms.ValidationError(_('A user with that username already exists.'))",
"if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.Valida... | <|body_start_0|>
try:
User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_('A user with that username already exists.'))
<|end_body_0|>
<|body_start_1|>
if Us... | Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user... | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m... | stack_v2_sparse_classes_75kplus_train_069778 | 8,195 | no_license | [
{
"docstring": "Validate that the username is alphanumeric and is not already in use.",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Validate that the supplied email address is unique for the site.",
"name": "clean_email",
"signature": "def clean_e... | 3 | stack_v2_sparse_classes_30k_train_051292 | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b... | 3cfb196f10c384adc3212c9b202def2398043059 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegistrationForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the ... | the_stack_v2_python_sparse | funnybag/core/forms.py | xando/funnybag | train | 0 |
c512c29e936921f2ad8fd937d3100dea310ce9eb | [
"response = await self.client(Operation(operation_type='RUNNER_READ', kwargs={'runner_id': runner_id}))\nself.set_header('Content-Type', 'application/json; charset=UTF-8')\nself.write(response)",
"response = await self.client(Operation(operation_type='RUNNER_DELETE', kwargs={'runner_id': runner_id, 'remove': True... | <|body_start_0|>
response = await self.client(Operation(operation_type='RUNNER_READ', kwargs={'runner_id': runner_id}))
self.set_header('Content-Type', 'application/json; charset=UTF-8')
self.write(response)
<|end_body_0|>
<|body_start_1|>
response = await self.client(Operation(operatio... | RunnerAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunnerAPI:
async def get(self, runner_id):
"""--- summary: Get a runner parameters: - name: runner_id in: path required: true description: The ID of the Runner type: string responses: 200: description: List of runner states schema: $ref: '#/definitions/Runner' 404: $ref: '#/definitions/4... | stack_v2_sparse_classes_75kplus_train_069779 | 6,146 | permissive | [
{
"docstring": "--- summary: Get a runner parameters: - name: runner_id in: path required: true description: The ID of the Runner type: string responses: 200: description: List of runner states schema: $ref: '#/definitions/Runner' 404: $ref: '#/definitions/404Error' 50x: $ref: '#/definitions/50xError' tags: - R... | 3 | stack_v2_sparse_classes_30k_train_043231 | Implement the Python class `RunnerAPI` described below.
Class description:
Implement the RunnerAPI class.
Method signatures and docstrings:
- async def get(self, runner_id): --- summary: Get a runner parameters: - name: runner_id in: path required: true description: The ID of the Runner type: string responses: 200: d... | Implement the Python class `RunnerAPI` described below.
Class description:
Implement the RunnerAPI class.
Method signatures and docstrings:
- async def get(self, runner_id): --- summary: Get a runner parameters: - name: runner_id in: path required: true description: The ID of the Runner type: string responses: 200: d... | a5fd2dcc2444409e243d3fdaa43d86695e5cb142 | <|skeleton|>
class RunnerAPI:
async def get(self, runner_id):
"""--- summary: Get a runner parameters: - name: runner_id in: path required: true description: The ID of the Runner type: string responses: 200: description: List of runner states schema: $ref: '#/definitions/Runner' 404: $ref: '#/definitions/4... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RunnerAPI:
async def get(self, runner_id):
"""--- summary: Get a runner parameters: - name: runner_id in: path required: true description: The ID of the Runner type: string responses: 200: description: List of runner states schema: $ref: '#/definitions/Runner' 404: $ref: '#/definitions/404Error' 50x: ... | the_stack_v2_python_sparse | src/app/beer_garden/api/http/handlers/vbeta/runner.py | beer-garden/beer-garden | train | 254 | |
1d5e8c1aed8fca029bb79de412e54c937e8ed5ec | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.aadUserConversationMember'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | ConversationMember | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConversationMember:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_75kplus_train_069780 | 6,677 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ConversationMember",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_019871 | Implement the Python class `ConversationMember` described below.
Class description:
Implement the ConversationMember class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember: Creates a new instance of the appropriate class based on disc... | Implement the Python class `ConversationMember` described below.
Class description:
Implement the ConversationMember class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ConversationMember:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConversationMember:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ConversationMember:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Co... | the_stack_v2_python_sparse | msgraph/generated/models/conversation_member.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
7c1ca75a4f218e02e1c9b99c1c60a43e56d3f8f6 | [
"super().__init__(game, mode_label=mode_selector_ui)\nself.mode_selector_ui = mode_selector_ui\nself.mission_selector_ui = mission_selector_ui\nself.mission_selector_label_ui = mission_selector_label_ui\nself.stage_selector_ui = stage_selector_ui\nself.mode_name = stage_name if stage_name else self.stage_selector_u... | <|body_start_0|>
super().__init__(game, mode_label=mode_selector_ui)
self.mode_selector_ui = mode_selector_ui
self.mission_selector_ui = mission_selector_ui
self.mission_selector_label_ui = mission_selector_label_ui
self.stage_selector_ui = stage_selector_ui
self.mode_nam... | Class for working with Epic Quests with 10 stages (usual missions without difficulty). | TenStageEpicQuest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenStageEpicQuest:
"""Class for working with Epic Quests with 10 stages (usual missions without difficulty)."""
def __init__(self, game, mode_selector_ui, mission_selector_ui, mission_selector_label_ui, stage_selector_ui, stage_name=None):
"""Class initialization. :param lib.game.gam... | stack_v2_sparse_classes_75kplus_train_069781 | 26,035 | permissive | [
{
"docstring": "Class initialization. :param lib.game.game.Game game: instance of the game. :param ui.UIElement mode_selector_ui: UI element of Epic Quest selector. :param ui.UIElement mission_selector_ui: UI element of Epic Quest's mission selector. :param ui.UIElement mission_selector_label_ui: UI element of ... | 6 | stack_v2_sparse_classes_30k_train_034922 | Implement the Python class `TenStageEpicQuest` described below.
Class description:
Class for working with Epic Quests with 10 stages (usual missions without difficulty).
Method signatures and docstrings:
- def __init__(self, game, mode_selector_ui, mission_selector_ui, mission_selector_label_ui, stage_selector_ui, st... | Implement the Python class `TenStageEpicQuest` described below.
Class description:
Class for working with Epic Quests with 10 stages (usual missions without difficulty).
Method signatures and docstrings:
- def __init__(self, game, mode_selector_ui, mission_selector_ui, mission_selector_label_ui, stage_selector_ui, st... | fd3f0bd45aea45e2e8ad8e8fc73a8953c96d350a | <|skeleton|>
class TenStageEpicQuest:
"""Class for working with Epic Quests with 10 stages (usual missions without difficulty)."""
def __init__(self, game, mode_selector_ui, mission_selector_ui, mission_selector_label_ui, stage_selector_ui, stage_name=None):
"""Class initialization. :param lib.game.gam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TenStageEpicQuest:
"""Class for working with Epic Quests with 10 stages (usual missions without difficulty)."""
def __init__(self, game, mode_selector_ui, mission_selector_ui, mission_selector_label_ui, stage_selector_ui, stage_name=None):
"""Class initialization. :param lib.game.game.Game game: ... | the_stack_v2_python_sparse | lib/game/missions/epic_quest.py | th3f1v3/mff_auto | train | 0 |
577b02ee3b258f052cbcd7f2243f345fa3046f2f | [
"super().__init__()\nif not isinstance(input_files, list):\n raise ConfigError('Given parameter is not a List')\nelse:\n for filename in input_files:\n utils.check_file_readable(filename)\nself.ndocs = [count_file_lines(fn) for fn in input_files]\nself.logger.info('Available data for training: {}'.form... | <|body_start_0|>
super().__init__()
if not isinstance(input_files, list):
raise ConfigError('Given parameter is not a List')
else:
for filename in input_files:
utils.check_file_readable(filename)
self.ndocs = [count_file_lines(fn) for fn in input_f... | Merge documents corpora; input is an array of data filenames: one file for each category (sport, ...) => return a data subset containing 'chunk_size' documents from each file. (used for sklearn document classification training) | MergeCorpora | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeCorpora:
"""Merge documents corpora; input is an array of data filenames: one file for each category (sport, ...) => return a data subset containing 'chunk_size' documents from each file. (used for sklearn document classification training)"""
def __init__(self, input_files):
"""... | stack_v2_sparse_classes_75kplus_train_069782 | 2,913 | permissive | [
{
"docstring": "Initialize with the list of filenames",
"name": "__init__",
"signature": "def __init__(self, input_files)"
},
{
"docstring": "Return 'chunk_size' documents from each input file",
"name": "load_data",
"signature": "def load_data(self, chunk_size=-1)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051181 | Implement the Python class `MergeCorpora` described below.
Class description:
Merge documents corpora; input is an array of data filenames: one file for each category (sport, ...) => return a data subset containing 'chunk_size' documents from each file. (used for sklearn document classification training)
Method signa... | Implement the Python class `MergeCorpora` described below.
Class description:
Merge documents corpora; input is an array of data filenames: one file for each category (sport, ...) => return a data subset containing 'chunk_size' documents from each file. (used for sklearn document classification training)
Method signa... | 38dc998e0cf4ef7572d542aafe80f8b95865c464 | <|skeleton|>
class MergeCorpora:
"""Merge documents corpora; input is an array of data filenames: one file for each category (sport, ...) => return a data subset containing 'chunk_size' documents from each file. (used for sklearn document classification training)"""
def __init__(self, input_files):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MergeCorpora:
"""Merge documents corpora; input is an array of data filenames: one file for each category (sport, ...) => return a data subset containing 'chunk_size' documents from each file. (used for sklearn document classification training)"""
def __init__(self, input_files):
"""Initialize wi... | the_stack_v2_python_sparse | python/lib/xi/ml/corpus/merge_corpora.py | lorosanu/xi-ml-topicdiscovery | train | 0 |
4756a2386132422394d1644a981bf57faa3618af | [
"nn.Module.__init__(self)\nself.net_u = net_u\nself.nu = nu",
"u = self.net_u(x, t)\nu_t = torch.autograd.grad(u, t, grad_outputs=torch.ones_like(u), retain_graph=True, create_graph=True)[0]\nu_x = torch.autograd.grad(u, x, grad_outputs=torch.ones_like(u), retain_graph=True, create_graph=True)[0]\nu_xx = torch.au... | <|body_start_0|>
nn.Module.__init__(self)
self.net_u = net_u
self.nu = nu
<|end_body_0|>
<|body_start_1|>
u = self.net_u(x, t)
u_t = torch.autograd.grad(u, t, grad_outputs=torch.ones_like(u), retain_graph=True, create_graph=True)[0]
u_x = torch.autograd.grad(u, x, grad_o... | Net_F | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Net_F:
def __init__(self, net_u, nu):
"""Compute the residuals Inputs : net_u : nu : device : self explenatory, cuda if possible"""
<|body_0|>
def forward(self, x, t):
"""The pytorch autograd version of calculating residual"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_069783 | 1,587 | no_license | [
{
"docstring": "Compute the residuals Inputs : net_u : nu : device : self explenatory, cuda if possible",
"name": "__init__",
"signature": "def __init__(self, net_u, nu)"
},
{
"docstring": "The pytorch autograd version of calculating residual",
"name": "forward",
"signature": "def forwar... | 2 | stack_v2_sparse_classes_30k_train_004959 | Implement the Python class `Net_F` described below.
Class description:
Implement the Net_F class.
Method signatures and docstrings:
- def __init__(self, net_u, nu): Compute the residuals Inputs : net_u : nu : device : self explenatory, cuda if possible
- def forward(self, x, t): The pytorch autograd version of calcul... | Implement the Python class `Net_F` described below.
Class description:
Implement the Net_F class.
Method signatures and docstrings:
- def __init__(self, net_u, nu): Compute the residuals Inputs : net_u : nu : device : self explenatory, cuda if possible
- def forward(self, x, t): The pytorch autograd version of calcul... | ff19f529d1f548c16ebc41aef2ac3d1c14732c77 | <|skeleton|>
class Net_F:
def __init__(self, net_u, nu):
"""Compute the residuals Inputs : net_u : nu : device : self explenatory, cuda if possible"""
<|body_0|>
def forward(self, x, t):
"""The pytorch autograd version of calculating residual"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Net_F:
def __init__(self, net_u, nu):
"""Compute the residuals Inputs : net_u : nu : device : self explenatory, cuda if possible"""
nn.Module.__init__(self)
self.net_u = net_u
self.nu = nu
def forward(self, x, t):
"""The pytorch autograd version of calculating resi... | the_stack_v2_python_sparse | MLP_Burgers_1D/model_burger_pinn.py | WWIIWWIIWW/PDM_PINN | train | 0 | |
5451e1ed5dab5e3d125841c52dd919d132efc88c | [
"self._attributeMapping = {}\nself._attributeMapping['hasComponentID'] = 'http://www.imi.kit.edu/abstract-pass-ont#hasModelComponentID'\nself._attributeMapping['hasAbstractVisualRepresentation'] = 'http://www.imi.kit.edu/abstract-pass-ont#hasAbstractVisualRepresentation'\nself._attributeMapping['label'] = 'http://w... | <|body_start_0|>
self._attributeMapping = {}
self._attributeMapping['hasComponentID'] = 'http://www.imi.kit.edu/abstract-pass-ont#hasModelComponentID'
self._attributeMapping['hasAbstractVisualRepresentation'] = 'http://www.imi.kit.edu/abstract-pass-ont#hasAbstractVisualRepresentation'
se... | Class that is responsible to represent a mapping between the attribute names an instance might have and their representation in rdfs (= their resource name). :version: 2015-12-04 :author: Lukas Block | AttributeMapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttributeMapper:
"""Class that is responsible to represent a mapping between the attribute names an instance might have and their representation in rdfs (= their resource name). :version: 2015-12-04 :author: Lukas Block"""
def __init__(self):
"""Construcotr @return : @author"""
... | stack_v2_sparse_classes_75kplus_train_069784 | 5,116 | no_license | [
{
"docstring": "Construcotr @return : @author",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns the name of an attribute for a given uri (representing an attribute in rdfs). If this attribute uri is currently unknwon a new resource object is created, linking to t... | 3 | stack_v2_sparse_classes_30k_train_000113 | Implement the Python class `AttributeMapper` described below.
Class description:
Class that is responsible to represent a mapping between the attribute names an instance might have and their representation in rdfs (= their resource name). :version: 2015-12-04 :author: Lukas Block
Method signatures and docstrings:
- d... | Implement the Python class `AttributeMapper` described below.
Class description:
Class that is responsible to represent a mapping between the attribute names an instance might have and their representation in rdfs (= their resource name). :version: 2015-12-04 :author: Lukas Block
Method signatures and docstrings:
- d... | f7a0f19c5c697f0050db94e1aca669ea3d2f3d34 | <|skeleton|>
class AttributeMapper:
"""Class that is responsible to represent a mapping between the attribute names an instance might have and their representation in rdfs (= their resource name). :version: 2015-12-04 :author: Lukas Block"""
def __init__(self):
"""Construcotr @return : @author"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AttributeMapper:
"""Class that is responsible to represent a mapping between the attribute names an instance might have and their representation in rdfs (= their resource name). :version: 2015-12-04 :author: Lukas Block"""
def __init__(self):
"""Construcotr @return : @author"""
self._attr... | the_stack_v2_python_sparse | Model/PASS/AttributeMapper.py | uagnd/S-BPM_VR | train | 0 |
b410da82ce1241cf2323610802211b47a8d15870 | [
"average_fund = numpy.average(month_fund_yield)\nfund_difference_sum = 0\nfor i in range(len(month_fund_yield)):\n fund_difference_sum += pow(month_fund_yield[i] - average_fund, 3)\nstandard_deviation = StandardDeviation.standard_deviation(month_earning_list=month_fund_yield)\nskewness = len(month_fund_yield) / ... | <|body_start_0|>
average_fund = numpy.average(month_fund_yield)
fund_difference_sum = 0
for i in range(len(month_fund_yield)):
fund_difference_sum += pow(month_fund_yield[i] - average_fund, 3)
standard_deviation = StandardDeviation.standard_deviation(month_earning_list=month_... | Skewness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Skewness:
def skewness(month_fund_yield: list):
"""计算偏度,需要对应的基金月度收益率和标准差"""
<|body_0|>
def skewness_pandas(month_fund_yield: list):
"""使用pandas函数计算偏度,需要对应的基金月度收益率和标准差"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
average_fund = numpy.average(month... | stack_v2_sparse_classes_75kplus_train_069785 | 1,893 | no_license | [
{
"docstring": "计算偏度,需要对应的基金月度收益率和标准差",
"name": "skewness",
"signature": "def skewness(month_fund_yield: list)"
},
{
"docstring": "使用pandas函数计算偏度,需要对应的基金月度收益率和标准差",
"name": "skewness_pandas",
"signature": "def skewness_pandas(month_fund_yield: list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019510 | Implement the Python class `Skewness` described below.
Class description:
Implement the Skewness class.
Method signatures and docstrings:
- def skewness(month_fund_yield: list): 计算偏度,需要对应的基金月度收益率和标准差
- def skewness_pandas(month_fund_yield: list): 使用pandas函数计算偏度,需要对应的基金月度收益率和标准差 | Implement the Python class `Skewness` described below.
Class description:
Implement the Skewness class.
Method signatures and docstrings:
- def skewness(month_fund_yield: list): 计算偏度,需要对应的基金月度收益率和标准差
- def skewness_pandas(month_fund_yield: list): 使用pandas函数计算偏度,需要对应的基金月度收益率和标准差
<|skeleton|>
class Skewness:
def ... | eae782a78ffde1276a0812a43d7deefb0bdedeb4 | <|skeleton|>
class Skewness:
def skewness(month_fund_yield: list):
"""计算偏度,需要对应的基金月度收益率和标准差"""
<|body_0|>
def skewness_pandas(month_fund_yield: list):
"""使用pandas函数计算偏度,需要对应的基金月度收益率和标准差"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Skewness:
def skewness(month_fund_yield: list):
"""计算偏度,需要对应的基金月度收益率和标准差"""
average_fund = numpy.average(month_fund_yield)
fund_difference_sum = 0
for i in range(len(month_fund_yield)):
fund_difference_sum += pow(month_fund_yield[i] - average_fund, 3)
standa... | the_stack_v2_python_sparse | public_method/indicator_calculation_method/skewness.py | liufubin-git/python | train | 0 | |
58b82c587add08b24b1801d4ff5855279ff0bb3f | [
"try:\n status = ResetPassword.objects.get(activation_key=value)\nexcept ResetPassword.DoesNotExist:\n raise serializers.ValidationError('The code does not exist')\nif status.is_activated:\n raise serializers.ValidationError('The code has already been used')\nif status.key_expired:\n raise serializers.V... | <|body_start_0|>
try:
status = ResetPassword.objects.get(activation_key=value)
except ResetPassword.DoesNotExist:
raise serializers.ValidationError('The code does not exist')
if status.is_activated:
raise serializers.ValidationError('The code has already been ... | Serializer for change password. | ChangePasswordSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangePasswordSerializer:
"""Serializer for change password."""
def validate_token(self, value):
"""Validation token"""
<|body_0|>
def create(self, validated_data):
"""Change password"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_069786 | 13,633 | permissive | [
{
"docstring": "Validation token",
"name": "validate_token",
"signature": "def validate_token(self, value)"
},
{
"docstring": "Change password",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | null | Implement the Python class `ChangePasswordSerializer` described below.
Class description:
Serializer for change password.
Method signatures and docstrings:
- def validate_token(self, value): Validation token
- def create(self, validated_data): Change password | Implement the Python class `ChangePasswordSerializer` described below.
Class description:
Serializer for change password.
Method signatures and docstrings:
- def validate_token(self, value): Validation token
- def create(self, validated_data): Change password
<|skeleton|>
class ChangePasswordSerializer:
"""Seria... | 7349ce18f56658d67daedf5e1abb352b5c15a029 | <|skeleton|>
class ChangePasswordSerializer:
"""Serializer for change password."""
def validate_token(self, value):
"""Validation token"""
<|body_0|>
def create(self, validated_data):
"""Change password"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChangePasswordSerializer:
"""Serializer for change password."""
def validate_token(self, value):
"""Validation token"""
try:
status = ResetPassword.objects.get(activation_key=value)
except ResetPassword.DoesNotExist:
raise serializers.ValidationError('The c... | the_stack_v2_python_sparse | src/tandlr/registration/serializers.py | shrmoud/schoolapp | train | 0 |
d4e2a0df87f091a6f573c49f5817d6cb699a8958 | [
"list = []\nif root is None:\n return []\nlist += self.inorderTraversal(root.left)\nlist.append(root.val)\nlist += self.inorderTraversal(root.right)\nreturn list",
"WHITE, GRAY = (0, 1)\nres = []\nstack = [(WHITE, root)]\nwhile stack:\n color, node = stack.pop()\n if node is None:\n continue\n ... | <|body_start_0|>
list = []
if root is None:
return []
list += self.inorderTraversal(root.left)
list.append(root.val)
list += self.inorderTraversal(root.right)
return list
<|end_body_0|>
<|body_start_1|>
WHITE, GRAY = (0, 1)
res = []
st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_iter(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
list = []
if... | stack_v2_sparse_classes_75kplus_train_069787 | 1,450 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal_iter",
"signature": "def inorderTraversal_iter(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002459 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_iter(self, root): :type root: TreeNode :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def inorderTraversal_iter(self, root): :type root: TreeNode :rtype: List[int]
<|skeleton|>
class Solut... | 3f4284330f9771037ca59e2e6a94122e51e58540 | <|skeleton|>
class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def inorderTraversal_iter(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
list = []
if root is None:
return []
list += self.inorderTraversal(root.left)
list.append(root.val)
list += self.inorderTraversal(root.right)
return list... | the_stack_v2_python_sparse | Leetcode/94.二叉树的中序遍历.py | myf-algorithm/Leetcode | train | 1 | |
b86e50c3dfed87ea01d8661824c4675b3b94f83c | [
"with transaction.atomic():\n self.model.objects.filter(player_unit__unit=unit).delete()\n if unit.stat_medal_rule_set.count() + unit.zeta_medal_rule_set.count() != 7:\n return\n stat_rules = StatMedalRule.objects.filter(unit=unit)\n zeta_rules = ZetaMedalRule.objects.filter(unit=unit)\n medal... | <|body_start_0|>
with transaction.atomic():
self.model.objects.filter(player_unit__unit=unit).delete()
if unit.stat_medal_rule_set.count() + unit.zeta_medal_rule_set.count() != 7:
return
stat_rules = StatMedalRule.objects.filter(unit=unit)
zeta_rul... | MedalManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedalManager:
def update_for_unit(self, unit):
"""Update medals for all player units of `unit` type. :param unit: unit to update :return:"""
<|body_0|>
def update_all(self, ally_codes=None):
"""Update medals for all toons. If ally codes are provided, update medals on... | stack_v2_sparse_classes_75kplus_train_069788 | 5,562 | permissive | [
{
"docstring": "Update medals for all player units of `unit` type. :param unit: unit to update :return:",
"name": "update_for_unit",
"signature": "def update_for_unit(self, unit)"
},
{
"docstring": "Update medals for all toons. If ally codes are provided, update medals only for these ally codes.... | 2 | stack_v2_sparse_classes_30k_test_000636 | Implement the Python class `MedalManager` described below.
Class description:
Implement the MedalManager class.
Method signatures and docstrings:
- def update_for_unit(self, unit): Update medals for all player units of `unit` type. :param unit: unit to update :return:
- def update_all(self, ally_codes=None): Update m... | Implement the Python class `MedalManager` described below.
Class description:
Implement the MedalManager class.
Method signatures and docstrings:
- def update_for_unit(self, unit): Update medals for all player units of `unit` type. :param unit: unit to update :return:
- def update_all(self, ally_codes=None): Update m... | acab1d9c6d4a010fff9d8e89a5fdd9d94def7c89 | <|skeleton|>
class MedalManager:
def update_for_unit(self, unit):
"""Update medals for all player units of `unit` type. :param unit: unit to update :return:"""
<|body_0|>
def update_all(self, ally_codes=None):
"""Update medals for all toons. If ally codes are provided, update medals on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedalManager:
def update_for_unit(self, unit):
"""Update medals for all player units of `unit` type. :param unit: unit to update :return:"""
with transaction.atomic():
self.model.objects.filter(player_unit__unit=unit).delete()
if unit.stat_medal_rule_set.count() + unit.... | the_stack_v2_python_sparse | sqds_medals/models.py | abey79/sqds | train | 0 | |
c5e075de3267a6d2978643f4c3bd52778b4433d2 | [
"values = []\n\ndef preorder(root):\n if root is None:\n return\n values.append(root.val)\n preorder(root.left)\n preorder(root.right)\npreorder(root)\nreturn ' '.join(map(str, values))",
"values = collections.deque((int(val) for val in data.split()))\n\ndef build(min_value, max_value):\n if... | <|body_start_0|>
values = []
def preorder(root):
if root is None:
return
values.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return ' '.join(map(str, values))
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_069789 | 2,125 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_032846 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 5f98270fbcd2d28d0f2abd344c3348255a12882a | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
values = []
def preorder(root):
if root is None:
return
values.append(root.val)
preorder(root.left)
preorder(root... | the_stack_v2_python_sparse | 449. Serialize and Deserialize BST.py | lxyshuai/leetcode | train | 0 | |
60a425403ee3cccc682d8f9949ee1f2732dc6239 | [
"mock_path.isfile.return_value = True\nrm('any path')\nmock_os.remove.assert_called_with('any path')",
"mock_path.isfile.return_value = False\nrm('any path')\nself.assertFalse(mock_os.remove.called, 'Failed to not remove the file if not present.')"
] | <|body_start_0|>
mock_path.isfile.return_value = True
rm('any path')
mock_os.remove.assert_called_with('any path')
<|end_body_0|>
<|body_start_1|>
mock_path.isfile.return_value = False
rm('any path')
self.assertFalse(mock_os.remove.called, 'Failed to not remove the file ... | RmTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RmTestCase:
def test_rm(self, mock_os, mock_path):
"""Make sure rm() calls os.remove() as expected."""
<|body_0|>
def test_no_rm(self, mock_os, mock_path):
"""Make sure we don't try to remove nonexistent files"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_069790 | 1,613 | no_license | [
{
"docstring": "Make sure rm() calls os.remove() as expected.",
"name": "test_rm",
"signature": "def test_rm(self, mock_os, mock_path)"
},
{
"docstring": "Make sure we don't try to remove nonexistent files",
"name": "test_no_rm",
"signature": "def test_no_rm(self, mock_os, mock_path)"
... | 2 | stack_v2_sparse_classes_30k_train_009229 | Implement the Python class `RmTestCase` described below.
Class description:
Implement the RmTestCase class.
Method signatures and docstrings:
- def test_rm(self, mock_os, mock_path): Make sure rm() calls os.remove() as expected.
- def test_no_rm(self, mock_os, mock_path): Make sure we don't try to remove nonexistent ... | Implement the Python class `RmTestCase` described below.
Class description:
Implement the RmTestCase class.
Method signatures and docstrings:
- def test_rm(self, mock_os, mock_path): Make sure rm() calls os.remove() as expected.
- def test_no_rm(self, mock_os, mock_path): Make sure we don't try to remove nonexistent ... | 5e47e93c32bc85f986f39b1d4df8a384c7ff0019 | <|skeleton|>
class RmTestCase:
def test_rm(self, mock_os, mock_path):
"""Make sure rm() calls os.remove() as expected."""
<|body_0|>
def test_no_rm(self, mock_os, mock_path):
"""Make sure we don't try to remove nonexistent files"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RmTestCase:
def test_rm(self, mock_os, mock_path):
"""Make sure rm() calls os.remove() as expected."""
mock_path.isfile.return_value = True
rm('any path')
mock_os.remove.assert_called_with('any path')
def test_no_rm(self, mock_os, mock_path):
"""Make sure we don't ... | the_stack_v2_python_sparse | python/graveyard/mock_demo.py | von/sandbox | train | 4 | |
4fe0c9c7a136266379b0ae15649fca977ee3e72d | [
"self.current_chapter = 0\nself.current_section = 0\nself.current_step = 0\nself.start_times_stack = []\nself.indentation_stack = 0\ntup = tuple(['', '', '', '', ''])\ntitle_tup = tuple(['Time', 'Symbol', 'Index', 'Delta', 'Message'])\nself.regular_divider = '+{:-<10}+{:-<8}+{:-<10}+{:-<12}+{:-<74}+'.format(*tup)\n... | <|body_start_0|>
self.current_chapter = 0
self.current_section = 0
self.current_step = 0
self.start_times_stack = []
self.indentation_stack = 0
tup = tuple(['', '', '', '', ''])
title_tup = tuple(['Time', 'Symbol', 'Index', 'Delta', 'Message'])
self.regula... | SerialPrinter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerialPrinter:
def __init__(self):
"""Constructor method to instantiate the serial printer class. It will initialize the printing messages."""
<|body_0|>
def print_serial_printer_start(self):
"""Method to print the beginning of the program. It will only print once an... | stack_v2_sparse_classes_75kplus_train_069791 | 5,159 | no_license | [
{
"docstring": "Constructor method to instantiate the serial printer class. It will initialize the printing messages.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to print the beginning of the program. It will only print once and then set the program_started ... | 5 | stack_v2_sparse_classes_30k_train_009557 | Implement the Python class `SerialPrinter` described below.
Class description:
Implement the SerialPrinter class.
Method signatures and docstrings:
- def __init__(self): Constructor method to instantiate the serial printer class. It will initialize the printing messages.
- def print_serial_printer_start(self): Method... | Implement the Python class `SerialPrinter` described below.
Class description:
Implement the SerialPrinter class.
Method signatures and docstrings:
- def __init__(self): Constructor method to instantiate the serial printer class. It will initialize the printing messages.
- def print_serial_printer_start(self): Method... | 0ae85251a24d59f1a9f71f8fb812b4e586cb21b9 | <|skeleton|>
class SerialPrinter:
def __init__(self):
"""Constructor method to instantiate the serial printer class. It will initialize the printing messages."""
<|body_0|>
def print_serial_printer_start(self):
"""Method to print the beginning of the program. It will only print once an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SerialPrinter:
def __init__(self):
"""Constructor method to instantiate the serial printer class. It will initialize the printing messages."""
self.current_chapter = 0
self.current_section = 0
self.current_step = 0
self.start_times_stack = []
self.indentation_st... | the_stack_v2_python_sparse | printers/SerialPrinter.py | Lucas-Frey/quantpy | train | 0 | |
93324e9ecc3126097e8095b01fee12e8f048537a | [
"u = self.uniform(size=size)\nvalues = -tau * np.log(1 - u)\nreturn values",
"u = self.uniform(size=size)\nvalues = (u * (x_max ** (1 - n) - x_min ** (1 - n)) + x_min ** (1 - n)) ** (1 / (1 - n))\nreturn values",
"u = self.uniform(size=size)\nvalues = np.tan(np.pi * u - np.pi / 2)\nvalues = np.zeros(size)\nretu... | <|body_start_0|>
u = self.uniform(size=size)
values = -tau * np.log(1 - u)
return values
<|end_body_0|>
<|body_start_1|>
u = self.uniform(size=size)
values = (u * (x_max ** (1 - n) - x_min ** (1 - n)) + x_min ** (1 - n)) ** (1 / (1 - n))
return values
<|end_body_1|>
<|b... | Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers. | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers."""
def exponential(self, tau, size=None):
"""Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)"""
<|body_0|>
def power(sel... | stack_v2_sparse_classes_75kplus_train_069792 | 4,178 | no_license | [
{
"docstring": "Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)",
"name": "exponential",
"signature": "def exponential(self, tau, size=None)"
},
{
"docstring": "Draw random numbers from a power law distribution with index n between x_min and x_max Blatt 3, Aufgabe 2b)",
"... | 5 | stack_v2_sparse_classes_30k_train_004569 | Implement the Python class `Generator` described below.
Class description:
Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers.
Method signatures and docstrings:
- def exponential(self, tau, size=None): Draw exponentially distributed random numbers. Blat... | Implement the Python class `Generator` described below.
Class description:
Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers.
Method signatures and docstrings:
- def exponential(self, tau, size=None): Draw exponentially distributed random numbers. Blat... | 0d7442bd78f9899536a109e87a4c4639ade82a58 | <|skeleton|>
class Generator:
"""Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers."""
def exponential(self, tau, size=None):
"""Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)"""
<|body_0|>
def power(sel... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Generator:
"""Generate random numbers from different distribtions self.uniform(size=size) creates standard uniform random numbers."""
def exponential(self, tau, size=None):
"""Draw exponentially distributed random numbers. Blatt 3, Aufgabe 2a)"""
u = self.uniform(size=size)
values... | the_stack_v2_python_sparse | Blatt05/Blatt05_Mang_Rezik_Scheugenpflug/random.py | yungsalami/linuxtest | train | 0 |
7139b232aea473b1f9747a8e08ad10d3b69fe7fa | [
"assert isinstance(arg1, ClinicalConcept)\nassert isinstance(arg2, ClinicalConcept)\nself.rid = str(rid).strip()\nself.arg1 = arg1\nself.arg2 = arg2\nself.rtype = str(rtype).strip()",
"assert mode in ('strict', 'lenient')\nif self.arg1.equals(other.arg1, mode) and self.arg2.equals(other.arg2, mode) and (self.rtyp... | <|body_start_0|>
assert isinstance(arg1, ClinicalConcept)
assert isinstance(arg2, ClinicalConcept)
self.rid = str(rid).strip()
self.arg1 = arg1
self.arg2 = arg2
self.rtype = str(rtype).strip()
<|end_body_0|>
<|body_start_1|>
assert mode in ('strict', 'lenient')
... | Relation class. | Relation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Relation:
"""Relation class."""
def __init__(self, rid, arg1, arg2, rtype):
"""Init."""
<|body_0|>
def equals(self, other, mode='strict'):
"""Return whether the current tag is equal to the one provided."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_069793 | 19,757 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, rid, arg1, arg2, rtype)"
},
{
"docstring": "Return whether the current tag is equal to the one provided.",
"name": "equals",
"signature": "def equals(self, other, mode='strict')"
}
] | 2 | null | Implement the Python class `Relation` described below.
Class description:
Relation class.
Method signatures and docstrings:
- def __init__(self, rid, arg1, arg2, rtype): Init.
- def equals(self, other, mode='strict'): Return whether the current tag is equal to the one provided. | Implement the Python class `Relation` described below.
Class description:
Relation class.
Method signatures and docstrings:
- def __init__(self, rid, arg1, arg2, rtype): Init.
- def equals(self, other, mode='strict'): Return whether the current tag is equal to the one provided.
<|skeleton|>
class Relation:
"""Re... | bd40bbee46e0e6a8379730c90783363122bd6886 | <|skeleton|>
class Relation:
"""Relation class."""
def __init__(self, rid, arg1, arg2, rtype):
"""Init."""
<|body_0|>
def equals(self, other, mode='strict'):
"""Return whether the current tag is equal to the one provided."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Relation:
"""Relation class."""
def __init__(self, rid, arg1, arg2, rtype):
"""Init."""
assert isinstance(arg1, ClinicalConcept)
assert isinstance(arg2, ClinicalConcept)
self.rid = str(rid).strip()
self.arg1 = arg1
self.arg2 = arg2
self.rtype = str(... | the_stack_v2_python_sparse | iaa.py | dokato/c2s2 | train | 3 |
0bf275c889e2f5d4cfb7b0f6fa3704fc1b7d9365 | [
"n = len(A)\nlo = 0\nhi = n - k\nwhile lo < hi:\n mid = (lo + hi) // 2\n if abs(x - A[mid]) > abs(A[mid + k] - x):\n lo = mid + 1\n else:\n hi = mid\nreturn A[lo:lo + k]",
"n = len(A)\nidx = bisect_left(A, x)\nret = deque()\ni = idx - 1\nj = idx\nwhile k:\n if 0 <= i < n and 0 <= j < n:\... | <|body_start_0|>
n = len(A)
lo = 0
hi = n - k
while lo < hi:
mid = (lo + hi) // 2
if abs(x - A[mid]) > abs(A[mid + k] - x):
lo = mid + 1
else:
hi = mid
return A[lo:lo + k]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]:
"""binary search without two pointers scanning"""
<|body_0|>
def findClosestElements2(self, A: List[int], k: int, x: int) -> List[int]:
"""input sorted arrya two pointers"""
<... | stack_v2_sparse_classes_75kplus_train_069794 | 2,116 | no_license | [
{
"docstring": "binary search without two pointers scanning",
"name": "findClosestElements",
"signature": "def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]"
},
{
"docstring": "input sorted arrya two pointers",
"name": "findClosestElements2",
"signature": "def find... | 2 | stack_v2_sparse_classes_30k_train_033947 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]: binary search without two pointers scanning
- def findClosestElements2(self, A: List[int], k: int, x: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]: binary search without two pointers scanning
- def findClosestElements2(self, A: List[int], k: int, x: in... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]:
"""binary search without two pointers scanning"""
<|body_0|>
def findClosestElements2(self, A: List[int], k: int, x: int) -> List[int]:
"""input sorted arrya two pointers"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findClosestElements(self, A: List[int], k: int, x: int) -> List[int]:
"""binary search without two pointers scanning"""
n = len(A)
lo = 0
hi = n - k
while lo < hi:
mid = (lo + hi) // 2
if abs(x - A[mid]) > abs(A[mid + k] - x):
... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/658 Find K Closest Elements.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
86df5f8b13401771eef7316d913ac9570fc5e948 | [
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nmy_survey.store_responses('English')\nself.assertIn('English', my_survey.responses)",
"question = 'What language did you first learn to speak?'\nmy_survey = AnonymousSurvey(question)\nresponses = ['English', 'Spanish... | <|body_start_0|>
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_responses('English')
self.assertIn('English', my_survey.responses)
<|end_body_0|>
<|body_start_1|>
question = 'What language did you first learn to spe... | Tests for the class AnonymousSurvey | TestAnonymousSurvey | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAnonymousSurvey:
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
<|body_0|>
def test_store_three_responses(self):
"""Test that three individual responses are stored properly... | stack_v2_sparse_classes_75kplus_train_069795 | 850 | no_license | [
{
"docstring": "Test that a single response is stored properly.",
"name": "test_store_single_response",
"signature": "def test_store_single_response(self)"
},
{
"docstring": "Test that three individual responses are stored properly.",
"name": "test_store_three_responses",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_test_000072 | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
Tests for the class AnonymousSurvey
Method signatures and docstrings:
- def test_store_single_response(self): Test that a single response is stored properly.
- def test_store_three_responses(self): Test that three individual response... | Implement the Python class `TestAnonymousSurvey` described below.
Class description:
Tests for the class AnonymousSurvey
Method signatures and docstrings:
- def test_store_single_response(self): Test that a single response is stored properly.
- def test_store_three_responses(self): Test that three individual response... | cc8bf7577c69544e67bf1ddada6dd4f3165610cb | <|skeleton|>
class TestAnonymousSurvey:
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
<|body_0|>
def test_store_three_responses(self):
"""Test that three individual responses are stored properly... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAnonymousSurvey:
"""Tests for the class AnonymousSurvey"""
def test_store_single_response(self):
"""Test that a single response is stored properly."""
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_respons... | the_stack_v2_python_sparse | chapter11_tetsting/2_test_class/test_survey.py | yigitkarabiyik/python_crash_course_answers | train | 1 |
948828e5464d4d07cb1299bb678291e4a74e6529 | [
"import Dice\nnumber = Dice.dice.Dicerolling(self)\nres = number\nexp = Dice.dice.rollGet(self)\nself.assertEqual(res, exp)",
"import Dice\nnumber = Dice.dice.Dicerolling(self)\nres = number\nexp = 1 <= res <= 6\nself.assertTrue(exp)"
] | <|body_start_0|>
import Dice
number = Dice.dice.Dicerolling(self)
res = number
exp = Dice.dice.rollGet(self)
self.assertEqual(res, exp)
<|end_body_0|>
<|body_start_1|>
import Dice
number = Dice.dice.Dicerolling(self)
res = number
exp = 1 <= res <=... | This is the unittest for the class Dice | dicetest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dicetest:
"""This is the unittest for the class Dice"""
def testdice1(self):
"""Tests if rollGet returns the correct number"""
<|body_0|>
def testdice2(self):
"""Tests if the dice rolling works, giving a number between 1-6"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_069796 | 637 | permissive | [
{
"docstring": "Tests if rollGet returns the correct number",
"name": "testdice1",
"signature": "def testdice1(self)"
},
{
"docstring": "Tests if the dice rolling works, giving a number between 1-6",
"name": "testdice2",
"signature": "def testdice2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013926 | Implement the Python class `dicetest` described below.
Class description:
This is the unittest for the class Dice
Method signatures and docstrings:
- def testdice1(self): Tests if rollGet returns the correct number
- def testdice2(self): Tests if the dice rolling works, giving a number between 1-6 | Implement the Python class `dicetest` described below.
Class description:
This is the unittest for the class Dice
Method signatures and docstrings:
- def testdice1(self): Tests if rollGet returns the correct number
- def testdice2(self): Tests if the dice rolling works, giving a number between 1-6
<|skeleton|>
class... | 73a8962c762ff48da331c9212f10676f066ed940 | <|skeleton|>
class dicetest:
"""This is the unittest for the class Dice"""
def testdice1(self):
"""Tests if rollGet returns the correct number"""
<|body_0|>
def testdice2(self):
"""Tests if the dice rolling works, giving a number between 1-6"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class dicetest:
"""This is the unittest for the class Dice"""
def testdice1(self):
"""Tests if rollGet returns the correct number"""
import Dice
number = Dice.dice.Dicerolling(self)
res = number
exp = Dice.dice.rollGet(self)
self.assertEqual(res, exp)
def te... | the_stack_v2_python_sparse | methoddice/testdice.py | JohanK91/MethodDice | train | 0 |
8b7d3075a2cd9a1ab33e8cb56a8421854dc981fb | [
"super(Rhea, self).__init__(name='Rhea', url=Rhea._url, verbose=verbose, cache=cache)\nself.version = version\nself.format_entry = ['cmlreact', 'biopax2', 'rxn']",
"if frmt is None:\n frmt = 'cmlreact'\nif frmt not in ['biopax2', 'cmlreact']:\n raise ValueError('format must be either cmlreact (default) or b... | <|body_start_0|>
super(Rhea, self).__init__(name='Rhea', url=Rhea._url, verbose=verbose, cache=cache)
self.version = version
self.format_entry = ['cmlreact', 'biopax2', 'rxn']
<|end_body_0|>
<|body_start_1|>
if frmt is None:
frmt = 'cmlreact'
if frmt not in ['biopax2... | Interface to the `Rhea <http://www.ebi.ac.uk/rhea/rest/1.0/>`_ service You can search by compound name, ChEBI ID, reaction ID, cross reference (e.g., EC number) or citation (author name, title, abstract text, publication ID). You can use double quotes - to match an exact phrase - and the following wildcards: * ? (quest... | Rhea | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rhea:
"""Interface to the `Rhea <http://www.ebi.ac.uk/rhea/rest/1.0/>`_ service You can search by compound name, ChEBI ID, reaction ID, cross reference (e.g., EC number) or citation (author name, title, abstract text, publication ID). You can use double quotes - to match an exact phrase - and the... | stack_v2_sparse_classes_75kplus_train_069797 | 5,424 | no_license | [
{
"docstring": ".. rubric:: Rhea constructor :param str version: the current version of the interface (1.0) :param bool verbose: True by default :: >>> from bioservices import Rhea >>> r = Rhea()",
"name": "__init__",
"signature": "def __init__(self, version='1.0', verbose=True, cache=False)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_028624 | Implement the Python class `Rhea` described below.
Class description:
Interface to the `Rhea <http://www.ebi.ac.uk/rhea/rest/1.0/>`_ service You can search by compound name, ChEBI ID, reaction ID, cross reference (e.g., EC number) or citation (author name, title, abstract text, publication ID). You can use double quot... | Implement the Python class `Rhea` described below.
Class description:
Interface to the `Rhea <http://www.ebi.ac.uk/rhea/rest/1.0/>`_ service You can search by compound name, ChEBI ID, reaction ID, cross reference (e.g., EC number) or citation (author name, title, abstract text, publication ID). You can use double quot... | cc425321293285b29640b40c003ff220fc5acbe7 | <|skeleton|>
class Rhea:
"""Interface to the `Rhea <http://www.ebi.ac.uk/rhea/rest/1.0/>`_ service You can search by compound name, ChEBI ID, reaction ID, cross reference (e.g., EC number) or citation (author name, title, abstract text, publication ID). You can use double quotes - to match an exact phrase - and the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rhea:
"""Interface to the `Rhea <http://www.ebi.ac.uk/rhea/rest/1.0/>`_ service You can search by compound name, ChEBI ID, reaction ID, cross reference (e.g., EC number) or citation (author name, title, abstract text, publication ID). You can use double quotes - to match an exact phrase - and the following wi... | the_stack_v2_python_sparse | src/bioservices/rhea.py | jlanga/bioservices | train | 0 |
97f7abfcd6b16daa7fc082c01160cc04e44160fe | [
"ret = m\ndiff = n - m\ni = 0\nlast = 0\nx = 1\nwhile m != 0:\n if m % 2 == 1:\n last += x\n if x * 2 - last <= diff:\n ret -= x\n m >>= 1\n i += 1\n x *= 2\nreturn ret",
"ret = m\nbuff = bin(ret)[-1::-1][:-2]\ni = 0\nlast = 0\nwhile i < len(buff):\n if buff[i] == '1':\n ... | <|body_start_0|>
ret = m
diff = n - m
i = 0
last = 0
x = 1
while m != 0:
if m % 2 == 1:
last += x
if x * 2 - last <= diff:
ret -= x
m >>= 1
i += 1
x *= 2
return ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def rangeBitwiseAnd1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = m
diff = n - m... | stack_v2_sparse_classes_75kplus_train_069798 | 1,182 | no_license | [
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "rangeBitwiseAnd",
"signature": "def rangeBitwiseAnd(self, m, n)"
},
{
"docstring": ":type m: int :type n: int :rtype: int",
"name": "rangeBitwiseAnd1",
"signature": "def rangeBitwiseAnd1(self, m, n)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001761 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeBitwiseAnd(self, m, n): :type m: int :type n: int :rtype: int
- def rangeBitwiseAnd1(self, m, n): :type m: int :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rangeBitwiseAnd(self, m, n): :type m: int :type n: int :rtype: int
- def rangeBitwiseAnd1(self, m, n): :type m: int :type n: int :rtype: int
<|skeleton|>
class Solution:
... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_0|>
def rangeBitwiseAnd1(self, m, n):
""":type m: int :type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rangeBitwiseAnd(self, m, n):
""":type m: int :type n: int :rtype: int"""
ret = m
diff = n - m
i = 0
last = 0
x = 1
while m != 0:
if m % 2 == 1:
last += x
if x * 2 - last <= diff:
... | the_stack_v2_python_sparse | python/leetcode/201_Bitwise_AND_of_Numbers_Range.py | bobcaoge/my-code | train | 0 | |
ddc304c2429249dcd6e6d556229135bbbf3c478e | [
"if not words:\n return -1\nstart = 0\nend = len(words) - 1\nwhile start + 1 < end:\n mid = end + (start - end) / 2\n compare_result = self.compare(prefix, words[mid])\n if compare_result == 0:\n end = mid\n if compare_result > 0:\n start = mid\n else:\n end = mid\nif self.com... | <|body_start_0|>
if not words:
return -1
start = 0
end = len(words) - 1
while start + 1 < end:
mid = end + (start - end) / 2
compare_result = self.compare(prefix, words[mid])
if compare_result == 0:
end = mid
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search_first(self, prefix, words):
"""Search the first prefix from a list of words."""
<|body_0|>
def compare(self, prefix, word):
"""Compare prefix with word. :return int: 0 if prefix is a prefix or word 1 if prefix is lexically larger than word -1 oth... | stack_v2_sparse_classes_75kplus_train_069799 | 1,881 | no_license | [
{
"docstring": "Search the first prefix from a list of words.",
"name": "search_first",
"signature": "def search_first(self, prefix, words)"
},
{
"docstring": "Compare prefix with word. :return int: 0 if prefix is a prefix or word 1 if prefix is lexically larger than word -1 otherwise (if prefix... | 2 | stack_v2_sparse_classes_30k_train_018857 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search_first(self, prefix, words): Search the first prefix from a list of words.
- def compare(self, prefix, word): Compare prefix with word. :return int: 0 if prefix is a pr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search_first(self, prefix, words): Search the first prefix from a list of words.
- def compare(self, prefix, word): Compare prefix with word. :return int: 0 if prefix is a pr... | d634941087bc51869f43c0d8044db09b7bdbaf58 | <|skeleton|>
class Solution:
def search_first(self, prefix, words):
"""Search the first prefix from a list of words."""
<|body_0|>
def compare(self, prefix, word):
"""Compare prefix with word. :return int: 0 if prefix is a prefix or word 1 if prefix is lexically larger than word -1 oth... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search_first(self, prefix, words):
"""Search the first prefix from a list of words."""
if not words:
return -1
start = 0
end = len(words) - 1
while start + 1 < end:
mid = end + (start - end) / 2
compare_result = self.com... | the_stack_v2_python_sparse | Twitter_Find_First_Prefix_Match_From_a_Sorted_String_Array.py | susunini/leetcode | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.