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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20ec5cb3cff18943c4d0fe657a804672a45b9845 | [
"samples = [sample]\ncollate_task = collate_microbe_directory.s(samples)\nreducer_task = microbe_directory_reducer.s()\nanalysis_result_uuid = sample['analysis_result']\npersist_task = persist_result.s(analysis_result_uuid, MODULE_NAME)\ntask_chain = chain(collate_task, reducer_task, persist_task)\nresult = task_ch... | <|body_start_0|>
samples = [sample]
collate_task = collate_microbe_directory.s(samples)
reducer_task = microbe_directory_reducer.s()
analysis_result_uuid = sample['analysis_result']
persist_task = persist_result.s(analysis_result_uuid, MODULE_NAME)
task_chain = chain(coll... | Tasks for generating virulence results. | MicrobeDirectoryWrangler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicrobeDirectoryWrangler:
"""Tasks for generating virulence results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
<|body_0|>
def run_sample_group(cls, sample_group, samples):
"""Gather and process samples."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_070600 | 1,346 | permissive | [
{
"docstring": "Gather single sample and process.",
"name": "run_sample",
"signature": "def run_sample(cls, sample_id, sample)"
},
{
"docstring": "Gather and process samples.",
"name": "run_sample_group",
"signature": "def run_sample_group(cls, sample_group, samples)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043499 | Implement the Python class `MicrobeDirectoryWrangler` described below.
Class description:
Tasks for generating virulence results.
Method signatures and docstrings:
- def run_sample(cls, sample_id, sample): Gather single sample and process.
- def run_sample_group(cls, sample_group, samples): Gather and process samples... | Implement the Python class `MicrobeDirectoryWrangler` described below.
Class description:
Tasks for generating virulence results.
Method signatures and docstrings:
- def run_sample(cls, sample_id, sample): Gather single sample and process.
- def run_sample_group(cls, sample_group, samples): Gather and process samples... | 609cd57c626c857c8efde8237a1f22f4d1e6065d | <|skeleton|>
class MicrobeDirectoryWrangler:
"""Tasks for generating virulence results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
<|body_0|>
def run_sample_group(cls, sample_group, samples):
"""Gather and process samples."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MicrobeDirectoryWrangler:
"""Tasks for generating virulence results."""
def run_sample(cls, sample_id, sample):
"""Gather single sample and process."""
samples = [sample]
collate_task = collate_microbe_directory.s(samples)
reducer_task = microbe_directory_reducer.s()
... | the_stack_v2_python_sparse | app/display_modules/microbe_directory/wrangler.py | MetaGenScope/metagenscope-server | train | 0 |
1a4ee4664525da3082e070eaa359ef95c3c63e50 | [
"super(FactorizedReduce, self).__init__()\nif desc.channel_out % 2 != 0:\n raise Exception('channel_out must be divided by 2.')\naffine = desc.get('affine', True)\nself.relu = nn.ReLU(inplace=False)\nself.conv1 = nn.Conv2d(desc.channel_in, desc.channel_out // 2, 1, stride=2, padding=0, bias=False)\nself.conv2 = ... | <|body_start_0|>
super(FactorizedReduce, self).__init__()
if desc.channel_out % 2 != 0:
raise Exception('channel_out must be divided by 2.')
affine = desc.get('affine', True)
self.relu = nn.ReLU(inplace=False)
self.conv1 = nn.Conv2d(desc.channel_in, desc.channel_out /... | Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config | FactorizedReduce | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactorizedReduce:
"""Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config"""
def __init__(self, desc):
"""Init FactorizedReduce."""
<|body_0|>
def forward(self, x):
"""Forward function of FactorizedReduce."""
... | stack_v2_sparse_classes_75kplus_train_070601 | 5,395 | permissive | [
{
"docstring": "Init FactorizedReduce.",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward function of FactorizedReduce.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002981 | Implement the Python class `FactorizedReduce` described below.
Class description:
Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init FactorizedReduce.
- def forward(self, x): Forward function of Facto... | Implement the Python class `FactorizedReduce` described below.
Class description:
Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init FactorizedReduce.
- def forward(self, x): Forward function of Facto... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class FactorizedReduce:
"""Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config"""
def __init__(self, desc):
"""Init FactorizedReduce."""
<|body_0|>
def forward(self, x):
"""Forward function of FactorizedReduce."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FactorizedReduce:
"""Class of Factorized Reduce operation. :param desc: description of FactorizedReduce :type desc: Config"""
def __init__(self, desc):
"""Init FactorizedReduce."""
super(FactorizedReduce, self).__init__()
if desc.channel_out % 2 != 0:
raise Exception('... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/pytorch/blocks/operations.py | Huawei-Ascend/modelzoo | train | 1 |
96a1d7b58328b30fde41e93d4831caca9bf6fc36 | [
"self.capacity = capacity\nself.cache = {}\nself.keys = collections.deque()\nself.exist_keys = set()",
"if key in self.exist_keys:\n self.keys.remove(key)\n self.keys.append(key)\n return self.cache[key]\nreturn -1",
"if key not in self.exist_keys:\n self.exist_keys.add(key)\n if len(self.keys) =... | <|body_start_0|>
self.capacity = capacity
self.cache = {}
self.keys = collections.deque()
self.exist_keys = set()
<|end_body_0|>
<|body_start_1|>
if key in self.exist_keys:
self.keys.remove(key)
self.keys.append(key)
return self.cache[key]
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_070602 | 1,259 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | ee79d3437cf47b26a4bca0ec798dc54d7b623453 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.cache = {}
self.keys = collections.deque()
self.exist_keys = set()
def get(self, key):
""":rtype: int"""
if key in self.exist_keys:
self.keys... | the_stack_v2_python_sparse | Algorithm/Python/146. LRU Cache.py | WuLC/LeetCode | train | 29 | |
5548bd278c2892e7e07e9ca044aa124ae25ad776 | [
"if not nums:\n return 0\ndp = [0] * len(nums)\nfor i in range(len(nums)):\n dp[i] = 1\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[j] + 1, dp[i])\nreturn max(dp)",
"dp = []\nfor num in nums:\n index = bisect.bisect_left(dp, num)\n if index == len(dp):\n dp... | <|body_start_0|>
if not nums:
return 0
dp = [0] * len(nums)
for i in range(len(nums)):
dp[i] = 1
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[j] + 1, dp[i])
return max(dp)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS_MK1(self, nums: List[int]) -> int:
"""Dynamic Programming Time Complexity: O(n^2) Space complexity: O(n)"""
<|body_0|>
def lengthOfLIS_MK2(self, nums: List[int]) -> int:
"""Dynamic Programming with Binary Search Time Complexity: O(nlgn) Spac... | stack_v2_sparse_classes_75kplus_train_070603 | 914 | no_license | [
{
"docstring": "Dynamic Programming Time Complexity: O(n^2) Space complexity: O(n)",
"name": "lengthOfLIS_MK1",
"signature": "def lengthOfLIS_MK1(self, nums: List[int]) -> int"
},
{
"docstring": "Dynamic Programming with Binary Search Time Complexity: O(nlgn) Space Complexity: O(n)",
"name":... | 2 | stack_v2_sparse_classes_30k_test_001184 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS_MK1(self, nums: List[int]) -> int: Dynamic Programming Time Complexity: O(n^2) Space complexity: O(n)
- def lengthOfLIS_MK2(self, nums: List[int]) -> int: Dynamic... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS_MK1(self, nums: List[int]) -> int: Dynamic Programming Time Complexity: O(n^2) Space complexity: O(n)
- def lengthOfLIS_MK2(self, nums: List[int]) -> int: Dynamic... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def lengthOfLIS_MK1(self, nums: List[int]) -> int:
"""Dynamic Programming Time Complexity: O(n^2) Space complexity: O(n)"""
<|body_0|>
def lengthOfLIS_MK2(self, nums: List[int]) -> int:
"""Dynamic Programming with Binary Search Time Complexity: O(nlgn) Spac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lengthOfLIS_MK1(self, nums: List[int]) -> int:
"""Dynamic Programming Time Complexity: O(n^2) Space complexity: O(n)"""
if not nums:
return 0
dp = [0] * len(nums)
for i in range(len(nums)):
dp[i] = 1
for j in range(i):
... | the_stack_v2_python_sparse | 0300. Longest Increasing Subsequence/longest_increasing_subsequence.py | faterazer/LeetCode | train | 4 | |
c8a1032f2784190f899ad853120136dfcb1b4b51 | [
"super(GraduatedCircleViz, self).__init__(data, *args, **kwargs)\nself.template = 'graduated_circle'\nself.check_vector_template()\nself.color_property = color_property\nself.color_stops = color_stops\nself.radius_property = radius_property\nself.radius_stops = radius_stops\nself.color_function_type = color_functio... | <|body_start_0|>
super(GraduatedCircleViz, self).__init__(data, *args, **kwargs)
self.template = 'graduated_circle'
self.check_vector_template()
self.color_property = color_property
self.color_stops = color_stops
self.radius_property = radius_property
self.radius_... | Create a graduated circle map | GraduatedCircleViz | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraduatedCircleViz:
"""Create a graduated circle map"""
def __init__(self, data, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', stroke_color='grey', stroke_width=0.1, radius_property=None, radius_stops=None, radius_default=2, radius_function_t... | stack_v2_sparse_classes_75kplus_train_070604 | 40,505 | permissive | [
{
"docstring": "Construct a Mapviz object :param color_property: property to determine circle color :param color_stops: property to determine circle color :param color_default: property to determine default circle color if match lookup fails :param color_function_type: property to determine `type` used by Mapbo... | 2 | stack_v2_sparse_classes_30k_train_039992 | Implement the Python class `GraduatedCircleViz` described below.
Class description:
Create a graduated circle map
Method signatures and docstrings:
- def __init__(self, data, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', stroke_color='grey', stroke_width=0.1, radius_p... | Implement the Python class `GraduatedCircleViz` described below.
Class description:
Create a graduated circle map
Method signatures and docstrings:
- def __init__(self, data, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', stroke_color='grey', stroke_width=0.1, radius_p... | c74665dc5e1818b2c49eccb60175b1d741ec188b | <|skeleton|>
class GraduatedCircleViz:
"""Create a graduated circle map"""
def __init__(self, data, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', stroke_color='grey', stroke_width=0.1, radius_property=None, radius_stops=None, radius_default=2, radius_function_t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraduatedCircleViz:
"""Create a graduated circle map"""
def __init__(self, data, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', stroke_color='grey', stroke_width=0.1, radius_property=None, radius_stops=None, radius_default=2, radius_function_type='interpol... | the_stack_v2_python_sparse | requires/mapboxgl-jupyter/mapboxgl/viz.py | ch-liuzhide/geogenius-python-sdk | train | 1 |
3d781147b6b6859dfc2d94f90633fb7bb8827ee0 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Service to manage customer client links. | CustomerClientLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerClientLinkServiceServicer:
"""Service to manage customer client links."""
def GetCustomerClientLink(self, request, context):
"""Returns the requested CustomerClientLink in full detail."""
<|body_0|>
def MutateCustomerClientLink(self, request, context):
""... | stack_v2_sparse_classes_75kplus_train_070605 | 5,740 | permissive | [
{
"docstring": "Returns the requested CustomerClientLink in full detail.",
"name": "GetCustomerClientLink",
"signature": "def GetCustomerClientLink(self, request, context)"
},
{
"docstring": "Creates or updates a customer client link. Operation statuses are returned.",
"name": "MutateCustome... | 2 | stack_v2_sparse_classes_30k_train_014585 | Implement the Python class `CustomerClientLinkServiceServicer` described below.
Class description:
Service to manage customer client links.
Method signatures and docstrings:
- def GetCustomerClientLink(self, request, context): Returns the requested CustomerClientLink in full detail.
- def MutateCustomerClientLink(sel... | Implement the Python class `CustomerClientLinkServiceServicer` described below.
Class description:
Service to manage customer client links.
Method signatures and docstrings:
- def GetCustomerClientLink(self, request, context): Returns the requested CustomerClientLink in full detail.
- def MutateCustomerClientLink(sel... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class CustomerClientLinkServiceServicer:
"""Service to manage customer client links."""
def GetCustomerClientLink(self, request, context):
"""Returns the requested CustomerClientLink in full detail."""
<|body_0|>
def MutateCustomerClientLink(self, request, context):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomerClientLinkServiceServicer:
"""Service to manage customer client links."""
def GetCustomerClientLink(self, request, context):
"""Returns the requested CustomerClientLink in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | google/ads/google_ads/v5/proto/services/customer_client_link_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
e7aa2f9259bc238675bf044adfb6db87fafe15f8 | [
"code, data = self.httpGet('http://api.twitter.com/1/users/show.json?screen_name=%s' % accountname)\nif code == 200:\n obj = json.loads(data)\nelse:\n return 'Problem with Twitter: ' + data\nreturn obj['status']['text']",
"self.httpSetCredentials(accountname, password)\ncode, data = self.httpPost('http://ap... | <|body_start_0|>
code, data = self.httpGet('http://api.twitter.com/1/users/show.json?screen_name=%s' % accountname)
if code == 200:
obj = json.loads(data)
else:
return 'Problem with Twitter: ' + data
return obj['status']['text']
<|end_body_0|>
<|body_start_1|>
... | TwitterComponent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterComponent:
def __get_status(self, accountname):
"""Get a the latest twitter status for the specified account. @param accountname: Name of the account for which we get the status. @type accountname: string @return: The status text. @rtype: string"""
<|body_0|>
def __po... | stack_v2_sparse_classes_75kplus_train_070606 | 4,684 | no_license | [
{
"docstring": "Get a the latest twitter status for the specified account. @param accountname: Name of the account for which we get the status. @type accountname: string @return: The status text. @rtype: string",
"name": "__get_status",
"signature": "def __get_status(self, accountname)"
},
{
"do... | 4 | stack_v2_sparse_classes_30k_train_044993 | Implement the Python class `TwitterComponent` described below.
Class description:
Implement the TwitterComponent class.
Method signatures and docstrings:
- def __get_status(self, accountname): Get a the latest twitter status for the specified account. @param accountname: Name of the account for which we get the statu... | Implement the Python class `TwitterComponent` described below.
Class description:
Implement the TwitterComponent class.
Method signatures and docstrings:
- def __get_status(self, accountname): Get a the latest twitter status for the specified account. @param accountname: Name of the account for which we get the statu... | e97f6a5a07bad39403ebb0b435f8e055298839d3 | <|skeleton|>
class TwitterComponent:
def __get_status(self, accountname):
"""Get a the latest twitter status for the specified account. @param accountname: Name of the account for which we get the status. @type accountname: string @return: The status text. @rtype: string"""
<|body_0|>
def __po... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterComponent:
def __get_status(self, accountname):
"""Get a the latest twitter status for the specified account. @param accountname: Name of the account for which we get the status. @type accountname: string @return: The status text. @rtype: string"""
code, data = self.httpGet('http://api.... | the_stack_v2_python_sparse | src/python/glu/components/twitter_component.py | rossmason/glu | train | 0 | |
f654f9119cb03fabe3f5db4b93ba7e5cb6e08e51 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | SCPStorageServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCPStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listSCPStorage(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getSCPStorage(self, request, context):
"""Missing a... | stack_v2_sparse_classes_75kplus_train_070607 | 9,639 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "listSCPStorage",
"signature": "def listSCPStorage(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "getSCPStorage",
"signature": "def getSCPSt... | 5 | stack_v2_sparse_classes_30k_train_001800 | Implement the Python class `SCPStorageServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def listSCPStorage(self, request, context): Missing associated documentation comment in .proto file.
- def getSCPStorage(self, request... | Implement the Python class `SCPStorageServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def listSCPStorage(self, request, context): Missing associated documentation comment in .proto file.
- def getSCPStorage(self, request... | c69e14b409add099d151434b9add711e41f41b20 | <|skeleton|>
class SCPStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listSCPStorage(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def getSCPStorage(self, request, context):
"""Missing a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SCPStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listSCPStorage(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not impl... | the_stack_v2_python_sparse | python-sdk/src/airavata_mft_sdk/scp/SCPStorageService_pb2_grpc.py | apache/airavata-mft | train | 23 |
f71dbbae927fe13ef250bde6a7d167083652e69f | [
"self.check_parameters(params)\nexp = np.exp(1j * params[0])\nreturn UnitaryMatrix([[1, 0], [0, exp]])",
"self.check_parameters(params)\ndexp = 1j * np.exp(1j * params[0])\nreturn np.array([[[0, 0], [0, dexp]]], dtype=np.complex128)",
"self.check_env_matrix(env_matrix)\na = np.real(env_matrix[1, 1])\nb = np.ima... | <|body_start_0|>
self.check_parameters(params)
exp = np.exp(1j * params[0])
return UnitaryMatrix([[1, 0], [0, exp]])
<|end_body_0|>
<|body_start_1|>
self.check_parameters(params)
dexp = 1j * np.exp(1j * params[0])
return np.array([[[0, 0], [0, dexp]]], dtype=np.complex12... | The U1 single qubit gate. | U1Gate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class U1Gate:
"""The U1 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) -> np.ndarray:
"""Returns the... | stack_v2_sparse_classes_75kplus_train_070608 | 1,728 | permissive | [
{
"docstring": "Returns the unitary for this gate, see Unitary for more info.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix"
},
{
"docstring": "Returns the gradient for this gate, see Gate for more info.",
"name": "get_grad",
"s... | 3 | stack_v2_sparse_classes_30k_train_037707 | Implement the Python class `U1Gate` described below.
Class description:
The U1 single qubit gate.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(self, params: Sequence[float]=[]) -> np... | Implement the Python class `U1Gate` described below.
Class description:
The U1 single qubit gate.
Method signatures and docstrings:
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the unitary for this gate, see Unitary for more info.
- def get_grad(self, params: Sequence[float]=[]) -> np... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class U1Gate:
"""The U1 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
<|body_0|>
def get_grad(self, params: Sequence[float]=[]) -> np.ndarray:
"""Returns the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class U1Gate:
"""The U1 single qubit gate."""
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gate, see Unitary for more info."""
self.check_parameters(params)
exp = np.exp(1j * params[0])
return UnitaryMatrix([[1, 0], [0, exp]... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/u1.py | mtreinish/bqskit | train | 0 |
b998610e6ab9cbfa1ef1766d705ba51903a42a1b | [
"try:\n return self._metadata\nexcept AttributeError:\n self._metadata = {'pages': 0, 'original_height': 0, 'original_width': 0, 'original_color_space': 'TBD'}\n return self._metadata",
"print('+- %s.generate_previews called' % self.__class__.__name__)\nprint(' +- Get original file-name')\nprint('+- Fi... | <|body_start_0|>
try:
return self._metadata
except AttributeError:
self._metadata = {'pages': 0, 'original_height': 0, 'original_width': 0, 'original_color_space': 'TBD'}
return self._metadata
<|end_body_0|>
<|body_start_1|>
print('+- %s.generate_previews cal... | Provides concrete implementation of functionality required by BaseAsset that is common to all assets that are layout-documents of some sort (InDesign INDD files, for example) | LayoutAsset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayoutAsset:
"""Provides concrete implementation of functionality required by BaseAsset that is common to all assets that are layout-documents of some sort (InDesign INDD files, for example)"""
def metadata(self):
"""Gets the metadata associated with the instance"""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_070609 | 13,347 | permissive | [
{
"docstring": "Gets the metadata associated with the instance",
"name": "metadata",
"signature": "def metadata(self)"
},
{
"docstring": "Generates a set of preview-images of the asset.",
"name": "generate_previews",
"signature": "def generate_previews(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019356 | Implement the Python class `LayoutAsset` described below.
Class description:
Provides concrete implementation of functionality required by BaseAsset that is common to all assets that are layout-documents of some sort (InDesign INDD files, for example)
Method signatures and docstrings:
- def metadata(self): Gets the m... | Implement the Python class `LayoutAsset` described below.
Class description:
Provides concrete implementation of functionality required by BaseAsset that is common to all assets that are layout-documents of some sort (InDesign INDD files, for example)
Method signatures and docstrings:
- def metadata(self): Gets the m... | 4840b0ee9e155c8ed664886c0aad20d44d48dac2 | <|skeleton|>
class LayoutAsset:
"""Provides concrete implementation of functionality required by BaseAsset that is common to all assets that are layout-documents of some sort (InDesign INDD files, for example)"""
def metadata(self):
"""Gets the metadata associated with the instance"""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LayoutAsset:
"""Provides concrete implementation of functionality required by BaseAsset that is common to all assets that are layout-documents of some sort (InDesign INDD files, for example)"""
def metadata(self):
"""Gets the metadata associated with the instance"""
try:
retur... | the_stack_v2_python_sparse | Chapter04/C04R03_SubclassRegistrationMetaclass.py | PacktPublishing/Python-Object-Oriented-Programming-Cookbook | train | 17 |
1fd63650323be9b69abc24f01f34b991ff5f1d5b | [
"def inner(result):\n pbar.update(1)\n self.results.append(result)\nreturn inner",
"if not os.path.exists(self.target):\n os.makedirs(self.target)\nself.replicate(self.corpus.root)\nself.results = []\nfileids = self.fileids(fileids, categories)\nwith tqdm(total=len(fileids), unit='Docs') as pbar:\n po... | <|body_start_0|>
def inner(result):
pbar.update(1)
self.results.append(result)
return inner
<|end_body_0|>
<|body_start_1|>
if not os.path.exists(self.target):
os.makedirs(self.target)
self.replicate(self.corpus.root)
self.results = []
... | Preprocessor that implements both multiprocessing and a progress bar. Note: had to jump through a lot of hoops just to get a progress bar, not sure it was worth it or that this performs the most effectively ... | ProgressParallelPreprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressParallelPreprocessor:
"""Preprocessor that implements both multiprocessing and a progress bar. Note: had to jump through a lot of hoops just to get a progress bar, not sure it was worth it or that this performs the most effectively ..."""
def on_result(self, pbar):
"""Indicat... | stack_v2_sparse_classes_75kplus_train_070610 | 13,132 | no_license | [
{
"docstring": "Indicates progress on result.",
"name": "on_result",
"signature": "def on_result(self, pbar)"
},
{
"docstring": "Setup the progress bar before conducting multiprocess transform.",
"name": "transform",
"signature": "def transform(self, fileids=None, categories=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031856 | Implement the Python class `ProgressParallelPreprocessor` described below.
Class description:
Preprocessor that implements both multiprocessing and a progress bar. Note: had to jump through a lot of hoops just to get a progress bar, not sure it was worth it or that this performs the most effectively ...
Method signat... | Implement the Python class `ProgressParallelPreprocessor` described below.
Class description:
Preprocessor that implements both multiprocessing and a progress bar. Note: had to jump through a lot of hoops just to get a progress bar, not sure it was worth it or that this performs the most effectively ...
Method signat... | 22395f7c83c9b561ec75e7ac8729f92444bd799b | <|skeleton|>
class ProgressParallelPreprocessor:
"""Preprocessor that implements both multiprocessing and a progress bar. Note: had to jump through a lot of hoops just to get a progress bar, not sure it was worth it or that this performs the most effectively ..."""
def on_result(self, pbar):
"""Indicat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgressParallelPreprocessor:
"""Preprocessor that implements both multiprocessing and a progress bar. Note: had to jump through a lot of hoops just to get a progress bar, not sure it was worth it or that this performs the most effectively ..."""
def on_result(self, pbar):
"""Indicates progress o... | the_stack_v2_python_sparse | benjamin_bengfort_applied_text_analysis/10_parallell/multi_preprocess.py | olegzinkevich/programming_books_notes_and_codes | train | 0 |
f67d6a00ba1fbfd7e0edbf48bc60f882199c37ea | [
"v = 2.0\nr = conversion.cm2mm(v)\nself.assertTrue(r == v * 10.0)",
"v = np.NaN\nwith self.assertRaises(ValueError):\n conversion.cm2mm(v)",
"v = 2.0\nr = conversion.mm2cm(v)\nself.assertTrue(r == v * 0.1)",
"v = np.NaN\nwith self.assertRaises(ValueError):\n conversion.mm2cm(v)"
] | <|body_start_0|>
v = 2.0
r = conversion.cm2mm(v)
self.assertTrue(r == v * 10.0)
<|end_body_0|>
<|body_start_1|>
v = np.NaN
with self.assertRaises(ValueError):
conversion.cm2mm(v)
<|end_body_1|>
<|body_start_2|>
v = 2.0
r = conversion.mm2cm(v)
... | Unit tests to check conversion | TestConversion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestConversion:
"""Unit tests to check conversion"""
def test_cm2mm(self):
"""test passable cm2mm conversion"""
<|body_0|>
def test_cm2mmA(self):
"""test not-passable cm2mm conversion"""
<|body_1|>
def test_mm2cm(self):
"""test passable mm2cm... | stack_v2_sparse_classes_75kplus_train_070611 | 968 | permissive | [
{
"docstring": "test passable cm2mm conversion",
"name": "test_cm2mm",
"signature": "def test_cm2mm(self)"
},
{
"docstring": "test not-passable cm2mm conversion",
"name": "test_cm2mmA",
"signature": "def test_cm2mmA(self)"
},
{
"docstring": "test passable mm2cm conversion",
"... | 4 | stack_v2_sparse_classes_30k_train_007148 | Implement the Python class `TestConversion` described below.
Class description:
Unit tests to check conversion
Method signatures and docstrings:
- def test_cm2mm(self): test passable cm2mm conversion
- def test_cm2mmA(self): test not-passable cm2mm conversion
- def test_mm2cm(self): test passable mm2cm conversion
- d... | Implement the Python class `TestConversion` described below.
Class description:
Unit tests to check conversion
Method signatures and docstrings:
- def test_cm2mm(self): test passable cm2mm conversion
- def test_cm2mmA(self): test not-passable cm2mm conversion
- def test_mm2cm(self): test passable mm2cm conversion
- d... | d95952d48c01866ee44ff40814c49e0fbd2489ad | <|skeleton|>
class TestConversion:
"""Unit tests to check conversion"""
def test_cm2mm(self):
"""test passable cm2mm conversion"""
<|body_0|>
def test_cm2mmA(self):
"""test not-passable cm2mm conversion"""
<|body_1|>
def test_mm2cm(self):
"""test passable mm2cm... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestConversion:
"""Unit tests to check conversion"""
def test_cm2mm(self):
"""test passable cm2mm conversion"""
v = 2.0
r = conversion.cm2mm(v)
self.assertTrue(r == v * 10.0)
def test_cm2mmA(self):
"""test not-passable cm2mm conversion"""
v = np.NaN
... | the_stack_v2_python_sparse | XcMath_Tests/test_conversion.py | Iwan-Zotow/runEGS | train | 2 |
2f5b0f76bfd9ad332fc0a652e74b06fd355e6433 | [
"if len(A) == 0:\n return A\nelse:\n return sortColors([c for c in A if c < A[0]]) + [c for c in A if c == A[0]] + sortColors([c for c in A if c > A[0]])",
"ret = [0, 0, 0]\nfor i in A:\n ret[i] += 1\nreturn [0] * ret[0] + [1] * ret[1] + [2] * ret[2]"
] | <|body_start_0|>
if len(A) == 0:
return A
else:
return sortColors([c for c in A if c < A[0]]) + [c for c in A if c == A[0]] + sortColors([c for c in A if c > A[0]])
<|end_body_0|>
<|body_start_1|>
ret = [0, 0, 0]
for i in A:
ret[i] += 1
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortColors(A):
"""Naive solution: implemented a Quicksort. Time complexity: O(nlgn) or O(n^2)"""
<|body_0|>
def sortColors2(A):
"""There are only 3 different values: 0, 1 and 2. We can count the occurrences of each value and get the resulting sorted arr... | stack_v2_sparse_classes_75kplus_train_070612 | 1,104 | no_license | [
{
"docstring": "Naive solution: implemented a Quicksort. Time complexity: O(nlgn) or O(n^2)",
"name": "sortColors",
"signature": "def sortColors(A)"
},
{
"docstring": "There are only 3 different values: 0, 1 and 2. We can count the occurrences of each value and get the resulting sorted array in ... | 2 | stack_v2_sparse_classes_30k_train_014728 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(A): Naive solution: implemented a Quicksort. Time complexity: O(nlgn) or O(n^2)
- def sortColors2(A): There are only 3 different values: 0, 1 and 2. We can count t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortColors(A): Naive solution: implemented a Quicksort. Time complexity: O(nlgn) or O(n^2)
- def sortColors2(A): There are only 3 different values: 0, 1 and 2. We can count t... | 6280203b0adaf6fc0770094deb2c0b6a88c5f64d | <|skeleton|>
class Solution:
def sortColors(A):
"""Naive solution: implemented a Quicksort. Time complexity: O(nlgn) or O(n^2)"""
<|body_0|>
def sortColors2(A):
"""There are only 3 different values: 0, 1 and 2. We can count the occurrences of each value and get the resulting sorted arr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sortColors(A):
"""Naive solution: implemented a Quicksort. Time complexity: O(nlgn) or O(n^2)"""
if len(A) == 0:
return A
else:
return sortColors([c for c in A if c < A[0]]) + [c for c in A if c == A[0]] + sortColors([c for c in A if c > A[0]])
... | the_stack_v2_python_sparse | Two_Pointers/sort_by_color.py | Zahidsqldba07/Interviewbit | train | 0 | |
04334445b42d53e46e4fba9551cc43133686f543 | [
"self.total = sum(w)\nfor i in range(1, len(w)):\n w[i] += w[i - 1]\nself.w = w",
"ind = random.randint(0, self.total - 1)\nl, r = (0, len(self.w))\nwhile l + 1 < r:\n mid = (l + r) / 2\n if ind <= self.w[mid]:\n r = mid\n else:\n l = mid\nif ind <= self.w[l]:\n return l\nreturn r"
] | <|body_start_0|>
self.total = sum(w)
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
<|end_body_0|>
<|body_start_1|>
ind = random.randint(0, self.total - 1)
l, r = (0, len(self.w))
while l + 1 < r:
mid = (l + r) / 2
if ind <= se... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.total = sum(w)
for i in range(1, len(w)):
w[i] += w[i - 1]
self... | stack_v2_sparse_classes_75kplus_train_070613 | 824 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | bcb79f329bcb133e6421db8fc1f4780a4eedec39 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.total = sum(w)
for i in range(1, len(w)):
w[i] += w[i - 1]
self.w = w
def pickIndex(self):
""":rtype: int"""
ind = random.randint(0, self.total - 1)
l, r = (0, len(self.w))
... | the_stack_v2_python_sparse | 528. Random Pick with Weight.py | havenshi/leetcode | train | 1 | |
14b58931768b5f5b41b6c43f33542a9821d5df43 | [
"matrix = [[1, 2, 3, 4, 5], [16, 1, 2, 3, 6], [15, 8, 3, 4, 7], [14, 7, 6, 5, 8], [13, 12, 11, 10, 9]]\nrotated_matrix = [[13, 14, 15, 16, 1], [12, 7, 8, 1, 2], [11, 6, 3, 2, 3], [10, 5, 4, 3, 4], [9, 8, 7, 6, 5]]\nself.assertEqual(rotation.rotate(matrix), rotated_matrix)",
"matrix = [[1, 2], [3, 4]]\nrotated_mat... | <|body_start_0|>
matrix = [[1, 2, 3, 4, 5], [16, 1, 2, 3, 6], [15, 8, 3, 4, 7], [14, 7, 6, 5, 8], [13, 12, 11, 10, 9]]
rotated_matrix = [[13, 14, 15, 16, 1], [12, 7, 8, 1, 2], [11, 6, 3, 2, 3], [10, 5, 4, 3, 4], [9, 8, 7, 6, 5]]
self.assertEqual(rotation.rotate(matrix), rotated_matrix)
<|end_bod... | rotation. | TestCompression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCompression:
"""rotation."""
def test_rotation(self):
"""5x5."""
<|body_0|>
def test_simple_rotation(self):
"""2x2."""
<|body_1|>
def test_nine_by_nine_rotation(self):
"""3x3."""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070614 | 1,325 | no_license | [
{
"docstring": "5x5.",
"name": "test_rotation",
"signature": "def test_rotation(self)"
},
{
"docstring": "2x2.",
"name": "test_simple_rotation",
"signature": "def test_simple_rotation(self)"
},
{
"docstring": "3x3.",
"name": "test_nine_by_nine_rotation",
"signature": "def... | 3 | null | Implement the Python class `TestCompression` described below.
Class description:
rotation.
Method signatures and docstrings:
- def test_rotation(self): 5x5.
- def test_simple_rotation(self): 2x2.
- def test_nine_by_nine_rotation(self): 3x3. | Implement the Python class `TestCompression` described below.
Class description:
rotation.
Method signatures and docstrings:
- def test_rotation(self): 5x5.
- def test_simple_rotation(self): 2x2.
- def test_nine_by_nine_rotation(self): 3x3.
<|skeleton|>
class TestCompression:
"""rotation."""
def test_rotati... | 7ea89298b0491878e5be5d5c48112a6cd6e1c0ad | <|skeleton|>
class TestCompression:
"""rotation."""
def test_rotation(self):
"""5x5."""
<|body_0|>
def test_simple_rotation(self):
"""2x2."""
<|body_1|>
def test_nine_by_nine_rotation(self):
"""3x3."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCompression:
"""rotation."""
def test_rotation(self):
"""5x5."""
matrix = [[1, 2, 3, 4, 5], [16, 1, 2, 3, 6], [15, 8, 3, 4, 7], [14, 7, 6, 5, 8], [13, 12, 11, 10, 9]]
rotated_matrix = [[13, 14, 15, 16, 1], [12, 7, 8, 1, 2], [11, 6, 3, 2, 3], [10, 5, 4, 3, 4], [9, 8, 7, 6, 5]]
... | the_stack_v2_python_sparse | ch-1/1-7/python/test_rotation.py | zoltankiss/ctci_problems | train | 0 |
5de4c6c144ed05b31ba1a0991e18e2f3dc3fb7eb | [
"self.classifiers = list()\nfor f in args:\n if not isinstance(f, ValueFunction):\n f = CallableWrapper(func=f)\n self.classifiers.append(f)\nself.none_label = kwargs.get('none_label')\nself.default_label = kwargs.get('default_label')\nself.raise_error = kwargs.get('raise_error', False)",
"for classi... | <|body_start_0|>
self.classifiers = list()
for f in args:
if not isinstance(f, ValueFunction):
f = CallableWrapper(func=f)
self.classifiers.append(f)
self.none_label = kwargs.get('none_label')
self.default_label = kwargs.get('default_label')
... | The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result. If no predicate is satisfied by a given va... | ValueClassifier | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueClassifier:
"""The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result.... | stack_v2_sparse_classes_75kplus_train_070615 | 7,355 | permissive | [
{
"docstring": "Initialize the individual classifier and object properties. Parameters ---------- args: list of callable or openclean.function.value.base.ValueFunction List of functions that accept a scalar value as input and that return a class label as output. none_label: string, default=None Label that is re... | 4 | stack_v2_sparse_classes_30k_train_048997 | Implement the Python class `ValueClassifier` described below.
Class description:
The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is... | Implement the Python class `ValueClassifier` described below.
Class description:
The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class ValueClassifier:
"""The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValueClassifier:
"""The value classifier evaluates a list of predicates or conditions on a given value (scalar or tuple). Each predicate is associated with a class label. The corresponding class label for the first predicate that is satisfied by the value is returned as the classification result. If no predic... | the_stack_v2_python_sparse | openclean/function/value/classifier.py | Denisfench/openclean-core | train | 0 |
d2b361ecc343acaf651d4b33353a0a55e37514d0 | [
"self.path = path or getcwd()\nif not op.isdir(self.path):\n self.path = op.dirname(self.path)\nif not op.exists(self.path):\n raise GitException('Path doesnt exists: %s' % self.path)",
"cmd = ' '.join((self.git_cmd, cmd))\ntry:\n proc = Popen(cmd.split(), stderr=stderr, stdout=stdout, close_fds=name == ... | <|body_start_0|>
self.path = path or getcwd()
if not op.isdir(self.path):
self.path = op.dirname(self.path)
if not op.exists(self.path):
raise GitException('Path doesnt exists: %s' % self.path)
<|end_body_0|>
<|body_start_1|>
cmd = ' '.join((self.git_cmd, cmd))
... | Initialize Git repository. | GitRepo | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitRepo:
"""Initialize Git repository."""
def __init__(self, path):
"""Init backend."""
<|body_0|>
def git(self, cmd, stderr=PIPE, stdout=PIPE, **kwargs):
"""Run git command. :return str: The command output."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_070616 | 1,868 | permissive | [
{
"docstring": "Init backend.",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Run git command. :return str: The command output.",
"name": "git",
"signature": "def git(self, cmd, stderr=PIPE, stdout=PIPE, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026173 | Implement the Python class `GitRepo` described below.
Class description:
Initialize Git repository.
Method signatures and docstrings:
- def __init__(self, path): Init backend.
- def git(self, cmd, stderr=PIPE, stdout=PIPE, **kwargs): Run git command. :return str: The command output. | Implement the Python class `GitRepo` described below.
Class description:
Initialize Git repository.
Method signatures and docstrings:
- def __init__(self, path): Init backend.
- def git(self, cmd, stderr=PIPE, stdout=PIPE, **kwargs): Run git command. :return str: The command output.
<|skeleton|>
class GitRepo:
"... | 6becc485fd13458ee982265ef8ed9b7e008d808b | <|skeleton|>
class GitRepo:
"""Initialize Git repository."""
def __init__(self, path):
"""Init backend."""
<|body_0|>
def git(self, cmd, stderr=PIPE, stdout=PIPE, **kwargs):
"""Run git command. :return str: The command output."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GitRepo:
"""Initialize Git repository."""
def __init__(self, path):
"""Init backend."""
self.path = path or getcwd()
if not op.isdir(self.path):
self.path = op.dirname(self.path)
if not op.exists(self.path):
raise GitException('Path doesnt exists: %... | the_stack_v2_python_sparse | dealer/git.py | klen/dealer | train | 42 |
246ca2da71204c4bb176ba5e8f94186150326516 | [
"obj_repr = json.loads(self.object_json_repr)\nfields = obj_repr[0]['fields']\nreturn fields",
"if self.content_type.model != 'joboffercomment':\n raise ValueError('Unexpected model. Expected a JobOfferComment instance.')\nreturn JobOfferComment.objects.get(id=self.object_id)",
"if self.changed_fields:\n ... | <|body_start_0|>
obj_repr = json.loads(self.object_json_repr)
fields = obj_repr[0]['fields']
return fields
<|end_body_0|>
<|body_start_1|>
if self.content_type.model != 'joboffercomment':
raise ValueError('Unexpected model. Expected a JobOfferComment instance.')
retu... | This is a proxy model used to simplify the code take away all the logic from the controller | JobOfferHistory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobOfferHistory:
"""This is a proxy model used to simplify the code take away all the logic from the controller"""
def fields(self):
"""Return the representation of the joboffer after this particular change is applied. It returns a python dict that can contain different fields that t... | stack_v2_sparse_classes_75kplus_train_070617 | 13,164 | permissive | [
{
"docstring": "Return the representation of the joboffer after this particular change is applied. It returns a python dict that can contain different fields that the current model.",
"name": "fields",
"signature": "def fields(self)"
},
{
"docstring": "Return the JobOfferComment instance for the... | 5 | stack_v2_sparse_classes_30k_train_030603 | Implement the Python class `JobOfferHistory` described below.
Class description:
This is a proxy model used to simplify the code take away all the logic from the controller
Method signatures and docstrings:
- def fields(self): Return the representation of the joboffer after this particular change is applied. It retur... | Implement the Python class `JobOfferHistory` described below.
Class description:
This is a proxy model used to simplify the code take away all the logic from the controller
Method signatures and docstrings:
- def fields(self): Return the representation of the joboffer after this particular change is applied. It retur... | 5f88d1ea0cea9bd67547b70dc2c8bbaa3b8b9d03 | <|skeleton|>
class JobOfferHistory:
"""This is a proxy model used to simplify the code take away all the logic from the controller"""
def fields(self):
"""Return the representation of the joboffer after this particular change is applied. It returns a python dict that can contain different fields that t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JobOfferHistory:
"""This is a proxy model used to simplify the code take away all the logic from the controller"""
def fields(self):
"""Return the representation of the joboffer after this particular change is applied. It returns a python dict that can contain different fields that the current mo... | the_stack_v2_python_sparse | joboffers/models.py | PyAr/pyarweb | train | 64 |
0cd749904aaf54fac18d4bd9ccfae52f98167463 | [
"self.data = []\n\ndef helper(node):\n if node is None:\n self.data.append(None)\n else:\n self.data.append(node.val)\n helper(node.left)\n helper(node.right)\nhelper(root)\nreturn self.data",
"def rebuild(data):\n if len(data) > 0:\n val = data.pop(0)\n if val i... | <|body_start_0|>
self.data = []
def helper(node):
if node is None:
self.data.append(None)
else:
self.data.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return self.data
<|end_bod... | 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_070618 | 1,286 | 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_005882 | 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:... | 355c0dbd32ad201800901f1bcc110550696bc96d | <|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"""
self.data = []
def helper(node):
if node is None:
self.data.append(None)
else:
self.data.append(node.val)
... | the_stack_v2_python_sparse | LeetCode/codes/297.py | adreena/MyStudyCorner | train | 0 | |
88ff85d2f3f17a9f59c0a21a36dc97c677666be6 | [
"start = time.time()\nself.df_covid = df_covid\nself.granularity = granularity\nself.cases = cases\nself.granularity = self.granularity.assign(cases=0)\nself.df_sort = pd.DataFrame(self.df_covid.sort_values(['date']))\nself.date_record = self.df_covid.groupby(['date']).size()\nif self.granularity.code[0] == '11':\n... | <|body_start_0|>
start = time.time()
self.df_covid = df_covid
self.granularity = granularity
self.cases = cases
self.granularity = self.granularity.assign(cases=0)
self.df_sort = pd.DataFrame(self.df_covid.sort_values(['date']))
self.date_record = self.df_covid.gr... | Creates an animated map. :param df_covid: dataframe with covid data :type df_covid: dataframe :param granularity: dep or region :type granularity: dataframe :param cases: column from df_covid :type cases: str | Map_covid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Map_covid:
"""Creates an animated map. :param df_covid: dataframe with covid data :type df_covid: dataframe :param granularity: dep or region :type granularity: dataframe :param cases: column from df_covid :type cases: str"""
def __init__(self, df_covid, granularity, cases):
"""Const... | stack_v2_sparse_classes_75kplus_train_070619 | 4,276 | no_license | [
{
"docstring": "Construction method. Create an initial map.",
"name": "__init__",
"signature": "def __init__(self, df_covid, granularity, cases)"
},
{
"docstring": "Update the map plot accordign to a slider widget. :param date_index: time slider with all the date in df_covid :type date_index: ip... | 4 | stack_v2_sparse_classes_30k_val_002968 | Implement the Python class `Map_covid` described below.
Class description:
Creates an animated map. :param df_covid: dataframe with covid data :type df_covid: dataframe :param granularity: dep or region :type granularity: dataframe :param cases: column from df_covid :type cases: str
Method signatures and docstrings:
... | Implement the Python class `Map_covid` described below.
Class description:
Creates an animated map. :param df_covid: dataframe with covid data :type df_covid: dataframe :param granularity: dep or region :type granularity: dataframe :param cases: column from df_covid :type cases: str
Method signatures and docstrings:
... | 78c16989389fba070f2253a0b8fae69d8cc3af15 | <|skeleton|>
class Map_covid:
"""Creates an animated map. :param df_covid: dataframe with covid data :type df_covid: dataframe :param granularity: dep or region :type granularity: dataframe :param cases: column from df_covid :type cases: str"""
def __init__(self, df_covid, granularity, cases):
"""Const... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Map_covid:
"""Creates an animated map. :param df_covid: dataframe with covid data :type df_covid: dataframe :param granularity: dep or region :type granularity: dataframe :param cases: column from df_covid :type cases: str"""
def __init__(self, df_covid, granularity, cases):
"""Construction metho... | the_stack_v2_python_sparse | covidviz/covidmap/plot_map.py | chloesrcb/covidviz | train | 0 |
f4ef440dae38e55531a5805a7406a892668a9984 | [
"TestPage(self.selenium).console_login(self.login_name, self.password)\ntext = ManagerAllocation(self.selenium).allocation_button()\nself.assertEqual(text, u'分配专员')",
"TestPage(self.selenium).console_login(self.login_name, self.password)\nManagerAllocation(self.selenium).allocation_role(self.name)\ntime.sleep(2)\... | <|body_start_0|>
TestPage(self.selenium).console_login(self.login_name, self.password)
text = ManagerAllocation(self.selenium).allocation_button()
self.assertEqual(text, u'分配专员')
<|end_body_0|>
<|body_start_1|>
TestPage(self.selenium).console_login(self.login_name, self.password)
... | 验证信审经理分配角色 | TestManagerAllocation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestManagerAllocation:
"""验证信审经理分配角色"""
def test_allocation_button_true(self):
"""验证分配按钮是否存在"""
<|body_0|>
def test_manual_allocation(self):
"""验证手动分配"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
TestPage(self.selenium).console_login(self.log... | stack_v2_sparse_classes_75kplus_train_070620 | 1,339 | no_license | [
{
"docstring": "验证分配按钮是否存在",
"name": "test_allocation_button_true",
"signature": "def test_allocation_button_true(self)"
},
{
"docstring": "验证手动分配",
"name": "test_manual_allocation",
"signature": "def test_manual_allocation(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019112 | Implement the Python class `TestManagerAllocation` described below.
Class description:
验证信审经理分配角色
Method signatures and docstrings:
- def test_allocation_button_true(self): 验证分配按钮是否存在
- def test_manual_allocation(self): 验证手动分配 | Implement the Python class `TestManagerAllocation` described below.
Class description:
验证信审经理分配角色
Method signatures and docstrings:
- def test_allocation_button_true(self): 验证分配按钮是否存在
- def test_manual_allocation(self): 验证手动分配
<|skeleton|>
class TestManagerAllocation:
"""验证信审经理分配角色"""
def test_allocation_bu... | 9904e47cfc4bce8759b4ff158e8a85391d8c7772 | <|skeleton|>
class TestManagerAllocation:
"""验证信审经理分配角色"""
def test_allocation_button_true(self):
"""验证分配按钮是否存在"""
<|body_0|>
def test_manual_allocation(self):
"""验证手动分配"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestManagerAllocation:
"""验证信审经理分配角色"""
def test_allocation_button_true(self):
"""验证分配按钮是否存在"""
TestPage(self.selenium).console_login(self.login_name, self.password)
text = ManagerAllocation(self.selenium).allocation_button()
self.assertEqual(text, u'分配专员')
def test_m... | the_stack_v2_python_sparse | test_f_manager_allocation.py | doujs666/zsph_ft_ui | train | 0 |
d277cc6819383f75eb9462fb8f06f3b66478069b | [
"self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t... | <|body_start_0|>
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_user.is_superuser = True
self.test_user.is_active = True
self.test_user.save()
self.assertEqual(self.test_user.is_superuser, True)
... | This class tests the views for the :class:`~mousedb.veterinary.MedicalIssue` objects. | MedicalIssueViewTests | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedicalIssueViewTests:
"""This class tests the views for the :class:`~mousedb.veterinary.MedicalIssue` objects."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from t... | stack_v2_sparse_classes_75kplus_train_070621 | 26,324 | permissive | [
{
"docstring": "Instantiate the test client. Creates a test user.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Depopulate created model instances from test database.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "This tests the ... | 6 | null | Implement the Python class `MedicalIssueViewTests` described below.
Class description:
This class tests the views for the :class:`~mousedb.veterinary.MedicalIssue` objects.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created m... | Implement the Python class `MedicalIssueViewTests` described below.
Class description:
This class tests the views for the :class:`~mousedb.veterinary.MedicalIssue` objects.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created m... | 7e423991f72c89468010c99865e3c70c22044df3 | <|skeleton|>
class MedicalIssueViewTests:
"""This class tests the views for the :class:`~mousedb.veterinary.MedicalIssue` objects."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MedicalIssueViewTests:
"""This class tests the views for the :class:`~mousedb.veterinary.MedicalIssue` objects."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com',... | the_stack_v2_python_sparse | mousedb/veterinary/tests.py | BridgesLab/mousedb | train | 0 |
0a9d33eea2d268ae3fe814ddacdf66a3c86f3764 | [
"super().__init__()\nself.keys = parse_lookup_key(target_field)\nself.key = self.keys[-1]",
"try:\n if record.access:\n tokens = [grant.to_token() for grant in record.access.grants]\n parent_data = dict_lookup(data, self.keys, parent=True)\n parent_data[self.key] = tokens\nexcept KeyError:... | <|body_start_0|>
super().__init__()
self.keys = parse_lookup_key(target_field)
self.key = self.keys[-1]
<|end_body_0|>
<|body_start_1|>
try:
if record.access:
tokens = [grant.to_token() for grant in record.access.grants]
parent_data = dict_loo... | Elasticsearch dumper extension for access grant tokens support. On dump, it uses the record's ``Access`` system field to generate tokens from the record's (access) ``Grants`` and dump them in the specified target field in the dictionary (per default: ``access.grant_tokens``). On load, it simply removes the target field... | GrantTokensDumperExt | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GrantTokensDumperExt:
"""Elasticsearch dumper extension for access grant tokens support. On dump, it uses the record's ``Access`` system field to generate tokens from the record's (access) ``Grants`` and dump them in the specified target field in the dictionary (per default: ``access.grant_tokens... | stack_v2_sparse_classes_75kplus_train_070622 | 1,783 | permissive | [
{
"docstring": "Constructor. :param target_field: dot separated path where to dump the tokens.",
"name": "__init__",
"signature": "def __init__(self, target_field)"
},
{
"docstring": "Dump the grant tokens to the data dictionary.",
"name": "dump",
"signature": "def dump(self, record, dat... | 3 | stack_v2_sparse_classes_30k_train_045838 | Implement the Python class `GrantTokensDumperExt` described below.
Class description:
Elasticsearch dumper extension for access grant tokens support. On dump, it uses the record's ``Access`` system field to generate tokens from the record's (access) ``Grants`` and dump them in the specified target field in the diction... | Implement the Python class `GrantTokensDumperExt` described below.
Class description:
Elasticsearch dumper extension for access grant tokens support. On dump, it uses the record's ``Access`` system field to generate tokens from the record's (access) ``Grants`` and dump them in the specified target field in the diction... | b4bcc2e16df6048149177a6e1ebd514bdb6b0626 | <|skeleton|>
class GrantTokensDumperExt:
"""Elasticsearch dumper extension for access grant tokens support. On dump, it uses the record's ``Access`` system field to generate tokens from the record's (access) ``Grants`` and dump them in the specified target field in the dictionary (per default: ``access.grant_tokens... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GrantTokensDumperExt:
"""Elasticsearch dumper extension for access grant tokens support. On dump, it uses the record's ``Access`` system field to generate tokens from the record's (access) ``Grants`` and dump them in the specified target field in the dictionary (per default: ``access.grant_tokens``). On load,... | the_stack_v2_python_sparse | invenio_rdm_records/records/dumpers/access.py | ppanero/invenio-rdm-records | train | 0 |
168a5c61824136861c43cb0137bf3385ede0a6a0 | [
"self.source = source\nself.values = values\nself.before = before\nself._columns_out = None\nself._const_values = [self.values[tag] for tag in self.values]",
"if self._columns_out is None:\n new_columns = [HXLColumn(hxlTag=tag) for tag in self.values]\n if self.before:\n self._columns_out = new_colum... | <|body_start_0|>
self.source = source
self.values = values
self.before = before
self._columns_out = None
self._const_values = [self.values[tag] for tag in self.values]
<|end_body_0|>
<|body_start_1|>
if self._columns_out is None:
new_columns = [HXLColumn(hxlT... | Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single-threaded processing pipeli... | HXLAddFilter | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HXLAddFilter:
"""Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dy... | stack_v2_sparse_classes_75kplus_train_070623 | 4,076 | permissive | [
{
"docstring": "@param source a HXL data source @param values a dictionary of tags and constant values @param before True to add new columns before existing ones",
"name": "__init__",
"signature": "def __init__(self, source, values, before=False)"
},
{
"docstring": "Add the constant columns to t... | 3 | stack_v2_sparse_classes_30k_train_022184 | Implement the Python class `HXLAddFilter` described below.
Class description:
Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instanc... | Implement the Python class `HXLAddFilter` described below.
Class description:
Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instanc... | b0209e75789501d99a2fb2df8a30cf55a383065a | <|skeleton|>
class HXLAddFilter:
"""Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dy... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HXLAddFilter:
"""Composable filter class to add constant values to every row of a HXL dataset. This is the class supporting the hxladd command-line utility. Because this class is a {@link hxl.model.HXLDataProvider}, you can use it as the source to an instance of another filter class to build a dynamic, single... | the_stack_v2_python_sparse | hxl/filters/add.py | jayvdb/libhxl-python | train | 0 |
2e56f7458de7172fce86ef388881bd22b670308d | [
"super(Encoder, self).__init__()\nself.hidden_dim = hidden_dim // 2 if bidir else hidden_dim\nself.n_layers = n_layers * 2 if bidir else n_layers\nself.bidir = bidir\nself.lstm = nn.LSTM(embedding_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=bidir)\nself.h0 = Parameter(torch.zeros(1), requires_gra... | <|body_start_0|>
super(Encoder, self).__init__()
self.hidden_dim = hidden_dim // 2 if bidir else hidden_dim
self.n_layers = n_layers * 2 if bidir else n_layers
self.bidir = bidir
self.lstm = nn.LSTM(embedding_dim, self.hidden_dim, n_layers, dropout=dropout, bidirectional=bidir)
... | Encoder class for Pointer-Net | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number o... | stack_v2_sparse_classes_75kplus_train_070624 | 14,528 | no_license | [
{
"docstring": "Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers for LSTMs :param float dropout: Float between 0-1 :param bool bidir: Bidirectional",
"name": "__init__",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_039953 | Implement the Python class `Encoder` described below.
Class description:
Encoder class for Pointer-Net
Method signatures and docstrings:
- def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir): Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number o... | Implement the Python class `Encoder` described below.
Class description:
Encoder class for Pointer-Net
Method signatures and docstrings:
- def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir): Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number o... | f4b63e6643fe5e2112cc5afa5915a2b847c29e06 | <|skeleton|>
class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
"""Encoder class for Pointer-Net"""
def __init__(self, embedding_dim, hidden_dim, n_layers, dropout, bidir):
"""Initiate Encoder :param Tensor embedding_dim: Number of embbeding channels :param int hidden_dim: Number of hidden units for the LSTM :param int n_layers: Number of layers for ... | the_stack_v2_python_sparse | PointerNet.py | Nishad94/SQuAD_PtrNets | train | 0 |
4ee497b7f98bcf0a485b67feca2c4de1e5c8f359 | [
"self.insurance_policy_id = insurance_policy_id\nself.travel_duration_param = travel_duration_param\nself.passengers_count = passengers_count\nself.birth_date = birth_date\nself.birth_date_persian = birth_date_persian\nself.risk_level_discount = risk_level_discount\nself.base_premium = base_premium\nself.all_premiu... | <|body_start_0|>
self.insurance_policy_id = insurance_policy_id
self.travel_duration_param = travel_duration_param
self.passengers_count = passengers_count
self.birth_date = birth_date
self.birth_date_persian = birth_date_persian
self.risk_level_discount = risk_level_disc... | Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type description here. birth_date (string): TODO: type description ... | TravelInsurancePolicyExtend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TravelInsurancePolicyExtend:
"""Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type descrip... | stack_v2_sparse_classes_75kplus_train_070625 | 7,484 | permissive | [
{
"docstring": "Constructor for the TravelInsurancePolicyExtend class",
"name": "__init__",
"signature": "def __init__(self, insurance_policy_id=None, passengers_count=None, risk_level_discount=None, insurance_company_discount_rate=None, insurance_company_discount=None, insurance_centre_discount=None, c... | 2 | stack_v2_sparse_classes_30k_train_003172 | Implement the Python class `TravelInsurancePolicyExtend` described below.
Class description:
Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. pas... | Implement the Python class `TravelInsurancePolicyExtend` described below.
Class description:
Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. pas... | b574a76a8805b306a423229b572c36dae0159def | <|skeleton|>
class TravelInsurancePolicyExtend:
"""Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type descrip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TravelInsurancePolicyExtend:
"""Implementation of the 'TravelInsurancePolicyExtend' model. TODO: type model description here. Attributes: insurance_policy_id (int): TODO: type description here. travel_duration_param (string): TODO: type description here. passengers_count (int): TODO: type description here. bi... | the_stack_v2_python_sparse | easybimehlanding/models/travel_insurance_policy_extend.py | kmelodi/EasyBimehLanding_Python | train | 0 |
74e1a8d745d8263614e8b7e080fedc65d9709b81 | [
"self.years = [year for year in range(year_i, year_f + 1)]\nself.type_AOD = type_AOD\nself.year_i = year_i\nself.year_f = year_f\nself.file = file",
"self.data = pd.read_csv(path + self.file + '.csv')\nself.clean_data()\nself.data = self.data.fillna(-1)\nself.len_data = len(self.data[self.type_AOD])",
"for key ... | <|body_start_0|>
self.years = [year for year in range(year_i, year_f + 1)]
self.type_AOD = type_AOD
self.year_i = year_i
self.year_f = year_f
self.file = file
<|end_body_0|>
<|body_start_1|>
self.data = pd.read_csv(path + self.file + '.csv')
self.clean_data()
... | Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS | MODIS_data | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MODIS_data:
"""Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS"""
def __init__(self, file, year_i, year_f, type_AOD):
"""Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> ... | stack_v2_sparse_classes_75kplus_train_070626 | 2,794 | no_license | [
{
"docstring": "Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> año en el que inicia el analisis year_f ---> año en el que finaliza el analisis",
"name": "__init__",
"signature": "def __init__(self, file, year_i, year_f, ty... | 5 | stack_v2_sparse_classes_30k_train_045157 | Implement the Python class `MODIS_data` described below.
Class description:
Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS
Method signatures and docstrings:
- def __init__(self, file, year_i, year_f, type_AOD): Describcion de variables: type_AOD---> columna de AOD que leer file --->... | Implement the Python class `MODIS_data` described below.
Class description:
Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS
Method signatures and docstrings:
- def __init__(self, file, year_i, year_f, type_AOD): Describcion de variables: type_AOD---> columna de AOD que leer file --->... | 43c7c6e6c57e76a0f80a3052a9060161d9b9dd41 | <|skeleton|>
class MODIS_data:
"""Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS"""
def __init__(self, file, year_i, year_f, type_AOD):
"""Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MODIS_data:
"""Clase que contiene los metodos y lectura que se le aplicaran a los datos de MODIS"""
def __init__(self, file, year_i, year_f, type_AOD):
"""Describcion de variables: type_AOD---> columna de AOD que leer file ---> archivo que contiene la informacion del AOD year_i ---> año en el que... | the_stack_v2_python_sparse | Scripts/functions_MODIS.py | iphadra/SIMA | train | 0 |
ba13b496d044f7952aa7a73c2009a2eae65bb6f9 | [
"ls_x = len(height)\nres = 0\nfor x in range(0, ls_x):\n for m in range(x + 1, ls_x):\n tmp = min(height[m], height[x]) * (m - x)\n res = max(tmp, res)\nreturn res",
"res = 0\nstart = 0\nend = len(height) - 1\nwhile end > start:\n if height[end] >= height[start]:\n res = max(res, (end -... | <|body_start_0|>
ls_x = len(height)
res = 0
for x in range(0, ls_x):
for m in range(x + 1, ls_x):
tmp = min(height[m], height[x]) * (m - x)
res = max(tmp, res)
return res
<|end_body_0|>
<|body_start_1|>
res = 0
start = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea(self, height: list) -> int:
"""暴力法: 双重循环 直接求出所有可能的容量,取最大值,但是如果数组太大运行时间太长 :param height: :return:"""
<|body_0|>
def maxArea2(self, height: list) -> int:
"""双指针: 从首尾开始搜索, 根据木桶原理装多少水取决于最小的那个木块 所以用尾元素减去首元素 乘以 较小的木块就是容器体积了 如果较小的木块是首元素 那么首元素就+1,如果是尾元素... | stack_v2_sparse_classes_75kplus_train_070627 | 2,144 | no_license | [
{
"docstring": "暴力法: 双重循环 直接求出所有可能的容量,取最大值,但是如果数组太大运行时间太长 :param height: :return:",
"name": "maxArea",
"signature": "def maxArea(self, height: list) -> int"
},
{
"docstring": "双指针: 从首尾开始搜索, 根据木桶原理装多少水取决于最小的那个木块 所以用尾元素减去首元素 乘以 较小的木块就是容器体积了 如果较小的木块是首元素 那么首元素就+1,如果是尾元素就-1 这样比较出最大的就好了 :param height:... | 2 | stack_v2_sparse_classes_30k_train_042039 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height: list) -> int: 暴力法: 双重循环 直接求出所有可能的容量,取最大值,但是如果数组太大运行时间太长 :param height: :return:
- def maxArea2(self, height: list) -> int: 双指针: 从首尾开始搜索, 根据木桶原理装多少水取决于最小... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea(self, height: list) -> int: 暴力法: 双重循环 直接求出所有可能的容量,取最大值,但是如果数组太大运行时间太长 :param height: :return:
- def maxArea2(self, height: list) -> int: 双指针: 从首尾开始搜索, 根据木桶原理装多少水取决于最小... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def maxArea(self, height: list) -> int:
"""暴力法: 双重循环 直接求出所有可能的容量,取最大值,但是如果数组太大运行时间太长 :param height: :return:"""
<|body_0|>
def maxArea2(self, height: list) -> int:
"""双指针: 从首尾开始搜索, 根据木桶原理装多少水取决于最小的那个木块 所以用尾元素减去首元素 乘以 较小的木块就是容器体积了 如果较小的木块是首元素 那么首元素就+1,如果是尾元素... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxArea(self, height: list) -> int:
"""暴力法: 双重循环 直接求出所有可能的容量,取最大值,但是如果数组太大运行时间太长 :param height: :return:"""
ls_x = len(height)
res = 0
for x in range(0, ls_x):
for m in range(x + 1, ls_x):
tmp = min(height[m], height[x]) * (m - x)
... | the_stack_v2_python_sparse | 盛水最多的容器.py | cjrzs/MyLeetCode | train | 8 | |
4b0ca654890636bef3171c2594336dd66966253f | [
"valid_event_types = {'medication': (medications, 'dmd_code'), 'clinical': (clinical_events, 'snomedct_code')}\ntry:\n self.event, self.code_column = valid_event_types[event_type]\nexcept KeyError:\n raise ValueError(\"Invalid event_type. Expected 'medication' or 'clinical'.\")",
"if ever:\n return self.... | <|body_start_0|>
valid_event_types = {'medication': (medications, 'dmd_code'), 'clinical': (clinical_events, 'snomedct_code')}
try:
self.event, self.code_column = valid_event_types[event_type]
except KeyError:
raise ValueError("Invalid event_type. Expected 'medication' or... | HistoricalEvent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistoricalEvent:
def __init__(self, event_type: str) -> None:
"""Initialize the HistoricalEvent based on the event type. Args: - event_type (str): Type of event. Can be 'medication' or 'clinical'."""
<|body_0|>
def fetch(self, codelist: List[Union[str, int]], n_months: Optio... | stack_v2_sparse_classes_75kplus_train_070628 | 10,309 | permissive | [
{
"docstring": "Initialize the HistoricalEvent based on the event type. Args: - event_type (str): Type of event. Can be 'medication' or 'clinical'.",
"name": "__init__",
"signature": "def __init__(self, event_type: str) -> None"
},
{
"docstring": "Fetch the relevant data based on the codelist an... | 2 | stack_v2_sparse_classes_30k_train_024967 | Implement the Python class `HistoricalEvent` described below.
Class description:
Implement the HistoricalEvent class.
Method signatures and docstrings:
- def __init__(self, event_type: str) -> None: Initialize the HistoricalEvent based on the event type. Args: - event_type (str): Type of event. Can be 'medication' or... | Implement the Python class `HistoricalEvent` described below.
Class description:
Implement the HistoricalEvent class.
Method signatures and docstrings:
- def __init__(self, event_type: str) -> None: Initialize the HistoricalEvent based on the event type. Args: - event_type (str): Type of event. Can be 'medication' or... | f75e403c6f094dd58bb4a65ab9540869b0220e6c | <|skeleton|>
class HistoricalEvent:
def __init__(self, event_type: str) -> None:
"""Initialize the HistoricalEvent based on the event type. Args: - event_type (str): Type of event. Can be 'medication' or 'clinical'."""
<|body_0|>
def fetch(self, codelist: List[Union[str, int]], n_months: Optio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HistoricalEvent:
def __init__(self, event_type: str) -> None:
"""Initialize the HistoricalEvent based on the event type. Args: - event_type (str): Type of event. Can be 'medication' or 'clinical'."""
valid_event_types = {'medication': (medications, 'dmd_code'), 'clinical': (clinical_events, 's... | the_stack_v2_python_sparse | analysis/ehrQL/utils.py | opensafely/pincer-measures | train | 1 | |
fa7c14d16e88ca37b378614013319cfe61b5fa58 | [
"super(DigitCaps, self).__init__()\nself.opt = opt\nself.W = nn.Parameter(torch.randn(1, 1152, 10, 8, 16))",
"batch_size = u.size(0)\nassert u.size() == torch.Size([batch_size, 1152, 8])\nu = torch.unsqueeze(u, dim=2)\nu = torch.unsqueeze(u, dim=2)\nu_hat = torch.matmul(u, self.W).squeeze()\nb = Variable(torch.ze... | <|body_start_0|>
super(DigitCaps, self).__init__()
self.opt = opt
self.W = nn.Parameter(torch.randn(1, 1152, 10, 8, 16))
<|end_body_0|>
<|body_start_1|>
batch_size = u.size(0)
assert u.size() == torch.Size([batch_size, 1152, 8])
u = torch.unsqueeze(u, dim=2)
u = ... | The `DigitCaps` layer consists of 10 16D capsules. Compared to the traditional scalar output neurons in fully connected networks(FCN), the `DigitCaps` layer can be seen as an FCN with ten 16-dimensional output neurons, which we call these neurons "capsules". In this layer, we take the input `[1152, 8]` tensor `u` as 11... | DigitCaps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DigitCaps:
"""The `DigitCaps` layer consists of 10 16D capsules. Compared to the traditional scalar output neurons in fully connected networks(FCN), the `DigitCaps` layer can be seen as an FCN with ten 16-dimensional output neurons, which we call these neurons "capsules". In this layer, we take t... | stack_v2_sparse_classes_75kplus_train_070629 | 14,893 | no_license | [
{
"docstring": "There is only one parameter in this layer, `W` [1, 1152, 10, 16, 8], where every [8, 16] is a weight matrix W_ij in Eq.2, that is, there are 11520 `W_ij`s in total. The the coupling coefficients `b` [64, 1152, 10, 1] is a temporary variable which does NOT belong to the layer's parameters. In oth... | 3 | stack_v2_sparse_classes_30k_train_045653 | Implement the Python class `DigitCaps` described below.
Class description:
The `DigitCaps` layer consists of 10 16D capsules. Compared to the traditional scalar output neurons in fully connected networks(FCN), the `DigitCaps` layer can be seen as an FCN with ten 16-dimensional output neurons, which we call these neuro... | Implement the Python class `DigitCaps` described below.
Class description:
The `DigitCaps` layer consists of 10 16D capsules. Compared to the traditional scalar output neurons in fully connected networks(FCN), the `DigitCaps` layer can be seen as an FCN with ten 16-dimensional output neurons, which we call these neuro... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class DigitCaps:
"""The `DigitCaps` layer consists of 10 16D capsules. Compared to the traditional scalar output neurons in fully connected networks(FCN), the `DigitCaps` layer can be seen as an FCN with ten 16-dimensional output neurons, which we call these neurons "capsules". In this layer, we take t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DigitCaps:
"""The `DigitCaps` layer consists of 10 16D capsules. Compared to the traditional scalar output neurons in fully connected networks(FCN), the `DigitCaps` layer can be seen as an FCN with ten 16-dimensional output neurons, which we call these neurons "capsules". In this layer, we take the input `[11... | the_stack_v2_python_sparse | generated/test_laubonghaudoi_CapsNet_guide_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 |
b4a0283660077290ce061ffd6589449961dda2ca | [
"ans = [0 for _ in range(length + 1)]\nfor start, end, inc in updates:\n ans[start] += -inc\n ans[end + 1] += inc\ns = 0\nfor i in reversed(range(length + 1)):\n s, ans[i] = (ans[i] + s, s)\nreturn ans[:length]",
"l = []\nfor start, end, inc in updates:\n l.append((start, -inc))\n l.append((end + 1... | <|body_start_0|>
ans = [0 for _ in range(length + 1)]
for start, end, inc in updates:
ans[start] += -inc
ans[end + 1] += inc
s = 0
for i in reversed(range(length + 1)):
s, ans[i] = (ans[i] + s, s)
return ans[:length]
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
"""update를 [0ㅡendIdx,inc] + [0~startIdx, -inc] 로 나눠서 생각. 아래 방법과 동일한데, 굳이 sorting 할 필요 없이 ans에 저장해놓고 거꾸로 오면된다. O(n+k) / O(1)"""
<|body_0|>
def getModifiedArray(self, length: int, updates... | stack_v2_sparse_classes_75kplus_train_070630 | 1,299 | no_license | [
{
"docstring": "update를 [0ㅡendIdx,inc] + [0~startIdx, -inc] 로 나눠서 생각. 아래 방법과 동일한데, 굳이 sorting 할 필요 없이 ans에 저장해놓고 거꾸로 오면된다. O(n+k) / O(1)",
"name": "getModifiedArray",
"signature": "def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]"
},
{
"docstring": "update를 [0ㅡendId... | 2 | stack_v2_sparse_classes_30k_train_047876 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: update를 [0ㅡendIdx,inc] + [0~startIdx, -inc] 로 나눠서 생각. 아래 방법과 동일한데, 굳이 sorting 할 필요 없이 ans에 저장해놓고 거... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: update를 [0ㅡendIdx,inc] + [0~startIdx, -inc] 로 나눠서 생각. 아래 방법과 동일한데, 굳이 sorting 할 필요 없이 ans에 저장해놓고 거... | c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1 | <|skeleton|>
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
"""update를 [0ㅡendIdx,inc] + [0~startIdx, -inc] 로 나눠서 생각. 아래 방법과 동일한데, 굳이 sorting 할 필요 없이 ans에 저장해놓고 거꾸로 오면된다. O(n+k) / O(1)"""
<|body_0|>
def getModifiedArray(self, length: int, updates... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
"""update를 [0ㅡendIdx,inc] + [0~startIdx, -inc] 로 나눠서 생각. 아래 방법과 동일한데, 굳이 sorting 할 필요 없이 ans에 저장해놓고 거꾸로 오면된다. O(n+k) / O(1)"""
ans = [0 for _ in range(length + 1)]
for start, end, inc in updates:
... | the_stack_v2_python_sparse | Leetcode/370.py | hanwgyu/algorithm_problem_solving | train | 5 | |
f091c8fc1a283d9a4c368c057d635ffd87c749cf | [
"try:\n pecan.request.db_api.delete_subscriber(uuid=uuid)\nexcept exception.SubscriberNotFound as e:\n raise wsme.exc.ClientSideError(e.message, status_code=e.code)",
"project_id = pecan.request.headers.get('X-Tenant-Id')\nres = pecan.request.db_api.list_subscribers(project_id=project_id)\nreturn res",
"t... | <|body_start_0|>
try:
pecan.request.db_api.delete_subscriber(uuid=uuid)
except exception.SubscriberNotFound as e:
raise wsme.exc.ClientSideError(e.message, status_code=e.code)
<|end_body_0|>
<|body_start_1|>
project_id = pecan.request.headers.get('X-Tenant-Id')
r... | REST Controller for Subscriber. | SubscribersController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubscribersController:
"""REST Controller for Subscriber."""
def delete(self, uuid):
"""Delete an subscriber."""
<|body_0|>
def get_all(self):
"""Retrieve a list of subscribers."""
<|body_1|>
def get_one(self, uuid):
"""Retrieve information a... | stack_v2_sparse_classes_75kplus_train_070631 | 4,227 | permissive | [
{
"docstring": "Delete an subscriber.",
"name": "delete",
"signature": "def delete(self, uuid)"
},
{
"docstring": "Retrieve a list of subscribers.",
"name": "get_all",
"signature": "def get_all(self)"
},
{
"docstring": "Retrieve information about the given subscriber.",
"name... | 5 | stack_v2_sparse_classes_30k_val_000750 | Implement the Python class `SubscribersController` described below.
Class description:
REST Controller for Subscriber.
Method signatures and docstrings:
- def delete(self, uuid): Delete an subscriber.
- def get_all(self): Retrieve a list of subscribers.
- def get_one(self, uuid): Retrieve information about the given ... | Implement the Python class `SubscribersController` described below.
Class description:
REST Controller for Subscriber.
Method signatures and docstrings:
- def delete(self, uuid): Delete an subscriber.
- def get_all(self): Retrieve a list of subscribers.
- def get_one(self, uuid): Retrieve information about the given ... | 6a9a59df834f08dad001a8439447ed4b699639ed | <|skeleton|>
class SubscribersController:
"""REST Controller for Subscriber."""
def delete(self, uuid):
"""Delete an subscriber."""
<|body_0|>
def get_all(self):
"""Retrieve a list of subscribers."""
<|body_1|>
def get_one(self, uuid):
"""Retrieve information a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SubscribersController:
"""REST Controller for Subscriber."""
def delete(self, uuid):
"""Delete an subscriber."""
try:
pecan.request.db_api.delete_subscriber(uuid=uuid)
except exception.SubscriberNotFound as e:
raise wsme.exc.ClientSideError(e.message, statu... | the_stack_v2_python_sparse | ripcord/api/controllers/v1/subscriber.py | kickstandproject/ripcord | train | 1 |
684cf50e3bf47574aeca2d5807cc200b5c728fd3 | [
"self._cache_dir = os.path.normpath(cache)\nself._get_safe_name = safe\ntry:\n os.makedirs(self._cache_dir)\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise",
"safe_key = self._get_safe_name(key)\nif safe_key.startswith(self.TEMPFILE_PREFIX):\n raise ValueError(\"Cache key cannot start ... | <|body_start_0|>
self._cache_dir = os.path.normpath(cache)
self._get_safe_name = safe
try:
os.makedirs(self._cache_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
<|end_body_0|>
<|body_start_1|>
safe_key = self._get_safe_name(k... | A FileCache that can be shared by multiple processes. Based on a patch found at <http://code.google.com/p/httplib2/issues/detail?id=125>. | AtomicFileCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtomicFileCache:
"""A FileCache that can be shared by multiple processes. Based on a patch found at <http://code.google.com/p/httplib2/issues/detail?id=125>."""
def __init__(self, cache, safe=safename):
"""Construct an ``AtomicFileCache``. :param cache: The directory to use as a cach... | stack_v2_sparse_classes_75kplus_train_070632 | 19,171 | permissive | [
{
"docstring": "Construct an ``AtomicFileCache``. :param cache: The directory to use as a cache. :param safe: A function that takes a key and returns a name that's safe to use as a filename. The key must never return a string that begins with ``TEMPFILE_PREFIX``. By default uses ``safename``.",
"name": "__i... | 5 | stack_v2_sparse_classes_30k_train_054209 | Implement the Python class `AtomicFileCache` described below.
Class description:
A FileCache that can be shared by multiple processes. Based on a patch found at <http://code.google.com/p/httplib2/issues/detail?id=125>.
Method signatures and docstrings:
- def __init__(self, cache, safe=safename): Construct an ``Atomic... | Implement the Python class `AtomicFileCache` described below.
Class description:
A FileCache that can be shared by multiple processes. Based on a patch found at <http://code.google.com/p/httplib2/issues/detail?id=125>.
Method signatures and docstrings:
- def __init__(self, cache, safe=safename): Construct an ``Atomic... | a5520738e6c5924b94f69980eba49a565c2561d7 | <|skeleton|>
class AtomicFileCache:
"""A FileCache that can be shared by multiple processes. Based on a patch found at <http://code.google.com/p/httplib2/issues/detail?id=125>."""
def __init__(self, cache, safe=safename):
"""Construct an ``AtomicFileCache``. :param cache: The directory to use as a cach... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AtomicFileCache:
"""A FileCache that can be shared by multiple processes. Based on a patch found at <http://code.google.com/p/httplib2/issues/detail?id=125>."""
def __init__(self, cache, safe=safename):
"""Construct an ``AtomicFileCache``. :param cache: The directory to use as a cache. :param saf... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/lazr/restfulclient/_browser.py | crazyzete/AppSecAssignment2 | train | 0 |
21b80de28a1487f3254ee247d598c872f89396a1 | [
"super(SymmetricCrossEntropyLoss, self).__init__()\nself.alpha = alpha\nself.beta = beta",
"num_classes = input_.shape[1]\ntarget_one_hot = F.one_hot(target, num_classes).float()\nassert target_one_hot.shape == input_.shape\ninput_ = torch.clamp(input_, min=1e-07, max=1.0)\ntarget_one_hot = torch.clamp(target_one... | <|body_start_0|>
super(SymmetricCrossEntropyLoss, self).__init__()
self.alpha = alpha
self.beta = beta
<|end_body_0|>
<|body_start_1|>
num_classes = input_.shape[1]
target_one_hot = F.one_hot(target, num_classes).float()
assert target_one_hot.shape == input_.shape
... | The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112 | SymmetricCrossEntropyLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SymmetricCrossEntropyLoss:
"""The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112"""
def __init__(self, alpha: float=1.0... | stack_v2_sparse_classes_75kplus_train_070633 | 3,544 | permissive | [
{
"docstring": "Args: alpha(float): corresponds to overfitting issue of CE beta(float): corresponds to flexible exploration on the robustness of RCE",
"name": "__init__",
"signature": "def __init__(self, alpha: float=1.0, beta: float=1.0)"
},
{
"docstring": "Calculates loss between ``input_`` an... | 2 | stack_v2_sparse_classes_30k_train_014749 | Implement the Python class `SymmetricCrossEntropyLoss` described below.
Class description:
The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112
Met... | Implement the Python class `SymmetricCrossEntropyLoss` described below.
Class description:
The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112
Met... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class SymmetricCrossEntropyLoss:
"""The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112"""
def __init__(self, alpha: float=1.0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SymmetricCrossEntropyLoss:
"""The Symmetric Cross Entropy loss. It has been proposed in `Symmetric Cross Entropy for Robust Learning with Noisy Labels`_. .. _Symmetric Cross Entropy for Robust Learning with Noisy Labels: https://arxiv.org/abs/1908.06112"""
def __init__(self, alpha: float=1.0, beta: float... | the_stack_v2_python_sparse | catalyst/contrib/losses/ce.py | catalyst-team/catalyst | train | 3,038 |
f50189600c2125c7eb8b00b45307d116be643287 | [
"curr_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))\nassert os.path.exists(curr_path), 'Path does not exist: {}'.format(curr_path)\nself.root_path = root_path\nself.data_path = os.path.join(curr_path, self.root_path, image_set)\nself.image_set = image_set\nself.class_names = class_names.stri... | <|body_start_0|>
curr_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
assert os.path.exists(curr_path), 'Path does not exist: {}'.format(curr_path)
self.root_path = root_path
self.data_path = os.path.join(curr_path, self.root_path, image_set)
self.image_set ... | FruitDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FruitDataset:
def __init__(self, root_path, image_set, class_names='apple,banana,orange'):
""":param root_path: 数据集所在根目录 :param image_set: 数据属性 train or val :param class_names: 类别名称,默认全部导入"""
<|body_0|>
def _load_img_xml_path(self):
"""加载img和xml文件,生成分别包含image和xml文件的两... | stack_v2_sparse_classes_75kplus_train_070634 | 8,039 | no_license | [
{
"docstring": ":param root_path: 数据集所在根目录 :param image_set: 数据属性 train or val :param class_names: 类别名称,默认全部导入",
"name": "__init__",
"signature": "def __init__(self, root_path, image_set, class_names='apple,banana,orange')"
},
{
"docstring": "加载img和xml文件,生成分别包含image和xml文件的两个列表",
"name": "_lo... | 6 | stack_v2_sparse_classes_30k_train_011743 | Implement the Python class `FruitDataset` described below.
Class description:
Implement the FruitDataset class.
Method signatures and docstrings:
- def __init__(self, root_path, image_set, class_names='apple,banana,orange'): :param root_path: 数据集所在根目录 :param image_set: 数据属性 train or val :param class_names: 类别名称,默认全部导... | Implement the Python class `FruitDataset` described below.
Class description:
Implement the FruitDataset class.
Method signatures and docstrings:
- def __init__(self, root_path, image_set, class_names='apple,banana,orange'): :param root_path: 数据集所在根目录 :param image_set: 数据属性 train or val :param class_names: 类别名称,默认全部导... | 33302a42b6002e1007e2e407bf5bfcde3527e780 | <|skeleton|>
class FruitDataset:
def __init__(self, root_path, image_set, class_names='apple,banana,orange'):
""":param root_path: 数据集所在根目录 :param image_set: 数据属性 train or val :param class_names: 类别名称,默认全部导入"""
<|body_0|>
def _load_img_xml_path(self):
"""加载img和xml文件,生成分别包含image和xml文件的两... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FruitDataset:
def __init__(self, root_path, image_set, class_names='apple,banana,orange'):
""":param root_path: 数据集所在根目录 :param image_set: 数据属性 train or val :param class_names: 类别名称,默认全部导入"""
curr_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
assert os.path.exis... | the_stack_v2_python_sparse | tools/fruit_dataset.py | Sparks-zs/mxnet-object-detection | train | 4 | |
2c0d00c2af7a6273121e53efd372ed4124ae294e | [
"try:\n doc = schemaService.get_by_id(schema_id_or_name)\nexcept SchemaNotFound:\n try:\n doc = schemaService.get_by_name(schema_id_or_name)\n except SchemaNotFound:\n return (\"Requested schema with name/id '{}' not found\".format(schema_id_or_name), 404)\nreturn (doc, 200)",
"try:\n sc... | <|body_start_0|>
try:
doc = schemaService.get_by_id(schema_id_or_name)
except SchemaNotFound:
try:
doc = schemaService.get_by_name(schema_id_or_name)
except SchemaNotFound:
return ("Requested schema with name/id '{}' not found".format(s... | GET/UPDATE/DELETE validation schemas | SchemaController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemaController:
"""GET/UPDATE/DELETE validation schemas"""
def get(self, schema_id_or_name):
"""Get a validation schema by ID"""
<|body_0|>
def delete(self, schema_id_or_name):
"""Delete a validation schema from the database"""
<|body_1|>
def put(s... | stack_v2_sparse_classes_75kplus_train_070635 | 3,102 | permissive | [
{
"docstring": "Get a validation schema by ID",
"name": "get",
"signature": "def get(self, schema_id_or_name)"
},
{
"docstring": "Delete a validation schema from the database",
"name": "delete",
"signature": "def delete(self, schema_id_or_name)"
},
{
"docstring": "Delete a valida... | 3 | stack_v2_sparse_classes_30k_train_042390 | Implement the Python class `SchemaController` described below.
Class description:
GET/UPDATE/DELETE validation schemas
Method signatures and docstrings:
- def get(self, schema_id_or_name): Get a validation schema by ID
- def delete(self, schema_id_or_name): Delete a validation schema from the database
- def put(self,... | Implement the Python class `SchemaController` described below.
Class description:
GET/UPDATE/DELETE validation schemas
Method signatures and docstrings:
- def get(self, schema_id_or_name): Get a validation schema by ID
- def delete(self, schema_id_or_name): Delete a validation schema from the database
- def put(self,... | 4573deec9b8206179ff6e61f37b4ba1847b3dbfb | <|skeleton|>
class SchemaController:
"""GET/UPDATE/DELETE validation schemas"""
def get(self, schema_id_or_name):
"""Get a validation schema by ID"""
<|body_0|>
def delete(self, schema_id_or_name):
"""Delete a validation schema from the database"""
<|body_1|>
def put(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchemaController:
"""GET/UPDATE/DELETE validation schemas"""
def get(self, schema_id_or_name):
"""Get a validation schema by ID"""
try:
doc = schemaService.get_by_id(schema_id_or_name)
except SchemaNotFound:
try:
doc = schemaService.get_by_n... | the_stack_v2_python_sparse | esdlvalidator/api/controller/schema.py | ESDLMapEditorESSIM/ESDLValidator | train | 0 |
2a722b884d8c600f292c6061008c45b917386149 | [
"extra_data = self.clean_keys_of_slashes(data.json)\ndata_value = MetaData.textit(data.xform)\nif data_value:\n token, flow, contacts = data_value.split(METADATA_SEPARATOR)\n post_data = {'extra': extra_data, 'flow': flow, 'contacts': contacts.split(',')}\n headers = {'Content-Type': 'application/json', 'A... | <|body_start_0|>
extra_data = self.clean_keys_of_slashes(data.json)
data_value = MetaData.textit(data.xform)
if data_value:
token, flow, contacts = data_value.split(METADATA_SEPARATOR)
post_data = {'extra': extra_data, 'flow': flow, 'contacts': contacts.split(',')}
... | Post submission data to a textit/rapidpro server. | ServiceDefinition | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceDefinition:
"""Post submission data to a textit/rapidpro server."""
def send(self, url, data=None):
"""Sends the submission to the configured rest service :param url: :param data: :return:"""
<|body_0|>
def clean_keys_of_slashes(self, record):
"""Replaces ... | stack_v2_sparse_classes_75kplus_train_070636 | 2,305 | permissive | [
{
"docstring": "Sends the submission to the configured rest service :param url: :param data: :return:",
"name": "send",
"signature": "def send(self, url, data=None)"
},
{
"docstring": "Replaces the slashes found in a dataset keys with underscores :param record: list containing a couple of dictio... | 2 | stack_v2_sparse_classes_30k_val_001605 | Implement the Python class `ServiceDefinition` described below.
Class description:
Post submission data to a textit/rapidpro server.
Method signatures and docstrings:
- def send(self, url, data=None): Sends the submission to the configured rest service :param url: :param data: :return:
- def clean_keys_of_slashes(sel... | Implement the Python class `ServiceDefinition` described below.
Class description:
Post submission data to a textit/rapidpro server.
Method signatures and docstrings:
- def send(self, url, data=None): Sends the submission to the configured rest service :param url: :param data: :return:
- def clean_keys_of_slashes(sel... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class ServiceDefinition:
"""Post submission data to a textit/rapidpro server."""
def send(self, url, data=None):
"""Sends the submission to the configured rest service :param url: :param data: :return:"""
<|body_0|>
def clean_keys_of_slashes(self, record):
"""Replaces ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ServiceDefinition:
"""Post submission data to a textit/rapidpro server."""
def send(self, url, data=None):
"""Sends the submission to the configured rest service :param url: :param data: :return:"""
extra_data = self.clean_keys_of_slashes(data.json)
data_value = MetaData.textit(da... | the_stack_v2_python_sparse | onadata/apps/restservice/services/textit.py | onaio/onadata | train | 177 |
5500cd86914e48c0f808bc3c35ac9dd28d730ce3 | [
"if not self.enabled:\n comm = getattr(communicator, self.__class__.__name__)(self._PyTravisCI['com']['requester'])\n self.__dict__ = comm.update(beta_feature_id=self.id, data={'beta_feature.enabled': False}, **self._PyTravisCI['shared']).__dict__\nreturn self.enabled",
"if self.enabled:\n comm = getattr... | <|body_start_0|>
if not self.enabled:
comm = getattr(communicator, self.__class__.__name__)(self._PyTravisCI['com']['requester'])
self.__dict__ = comm.update(beta_feature_id=self.id, data={'beta_feature.enabled': False}, **self._PyTravisCI['shared']).__dict__
return self.enabled
... | Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description of the feature. :ivar bool enabled: Indi... | BetaFeature | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BetaFeature:
"""Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description o... | stack_v2_sparse_classes_75kplus_train_070637 | 3,908 | permissive | [
{
"docstring": "Enables the current beta feature.",
"name": "enable",
"signature": "def enable(self) -> bool"
},
{
"docstring": "Disables the current beta feature.",
"name": "disable",
"signature": "def disable(self) -> bool"
},
{
"docstring": "Deletes the current beta feature. :... | 3 | stack_v2_sparse_classes_30k_train_034898 | Implement the Python class `BetaFeature` described below.
Class description:
Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :iva... | Implement the Python class `BetaFeature` described below.
Class description:
Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :iva... | 20a4bad3b05908b7371744b367ba7a33c289b83e | <|skeleton|>
class BetaFeature:
"""Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BetaFeature:
"""Provides the description of a beta feature. Official Travis CI API documentation: - https://developer.travis-ci.org/resource/beta_feature :ivar int id: Value uniquely identifying the beta feature. :ivar str name: The name of the feature. :ivar str description: Longer description of the feature... | the_stack_v2_python_sparse | PyTravisCI/resource_types/beta_feature.py | funilrys/PyTravisCI | train | 4 |
e8c5ec6b6bb9472db9e0d2be57d6d16e0478ee20 | [
"if not Cert(cert).exists():\n pub_ns.abort(400, \"can't publish non-existent certificate\")\nif Cert(cert).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin':\n pub_ns.abort(401, \"you don't own this certificate\")\nc = Cert(cert).publish()\nif c.is_publish():\n return (c.json(), 202)\ne... | <|body_start_0|>
if not Cert(cert).exists():
pub_ns.abort(400, "can't publish non-existent certificate")
if Cert(cert).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin':
pub_ns.abort(401, "you don't own this certificate")
c = Cert(cert).publish()
... | publish one certificate | PublishOneCert | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublishOneCert:
"""publish one certificate"""
def put(self, cert):
"""Publish one owned cert"""
<|body_0|>
def delete(self, cert):
"""Unpublish one owned cert"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not Cert(cert).exists():
... | stack_v2_sparse_classes_75kplus_train_070638 | 5,403 | permissive | [
{
"docstring": "Publish one owned cert",
"name": "put",
"signature": "def put(self, cert)"
},
{
"docstring": "Unpublish one owned cert",
"name": "delete",
"signature": "def delete(self, cert)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009390 | Implement the Python class `PublishOneCert` described below.
Class description:
publish one certificate
Method signatures and docstrings:
- def put(self, cert): Publish one owned cert
- def delete(self, cert): Unpublish one owned cert | Implement the Python class `PublishOneCert` described below.
Class description:
publish one certificate
Method signatures and docstrings:
- def put(self, cert): Publish one owned cert
- def delete(self, cert): Unpublish one owned cert
<|skeleton|>
class PublishOneCert:
"""publish one certificate"""
def put(... | 6a9bf3a3d73fb3faa7cf1e5cfc757cc360fbafde | <|skeleton|>
class PublishOneCert:
"""publish one certificate"""
def put(self, cert):
"""Publish one owned cert"""
<|body_0|>
def delete(self, cert):
"""Unpublish one owned cert"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PublishOneCert:
"""publish one certificate"""
def put(self, cert):
"""Publish one owned cert"""
if not Cert(cert).exists():
pub_ns.abort(400, "can't publish non-existent certificate")
if Cert(cert).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin':
... | the_stack_v2_python_sparse | haprestio/api_v1/pub.py | innofocus/haprestio | train | 0 |
f062a5234186a39ba3633b801d1c1d56dbf13132 | [
"if n == 0:\n return []\nres = []\nself._dfs(n, '', res, 0, 0)\nreturn res",
"if len(path) == 2 * n:\n res.append(path)\n return\nchooses = []\nif left_num < n:\n chooses.append('(')\nif right_num < left_num:\n chooses.append(')')\nfor i in chooses:\n path += i\n if i == '(':\n self._d... | <|body_start_0|>
if n == 0:
return []
res = []
self._dfs(n, '', res, 0, 0)
return res
<|end_body_0|>
<|body_start_1|>
if len(path) == 2 * n:
res.append(path)
return
chooses = []
if left_num < n:
chooses.append('(')
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
""":param n: :return:"""
<|body_0|>
def _dfs(self, n, path, res, left_num, right_num):
"""nums, res, path, choose :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
... | stack_v2_sparse_classes_75kplus_train_070639 | 1,085 | no_license | [
{
"docstring": ":param n: :return:",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n: int) -> List[str]"
},
{
"docstring": "nums, res, path, choose :return:",
"name": "_dfs",
"signature": "def _dfs(self, n, path, res, left_num, right_num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031760 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: :param n: :return:
- def _dfs(self, n, path, res, left_num, right_num): nums, res, path, choose :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: :param n: :return:
- def _dfs(self, n, path, res, left_num, right_num): nums, res, path, choose :return:
<|skeleton|>
class S... | 6708479302cca3ea3d930e6e80264f213ea29c5f | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
""":param n: :return:"""
<|body_0|>
def _dfs(self, n, path, res, left_num, right_num):
"""nums, res, path, choose :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
""":param n: :return:"""
if n == 0:
return []
res = []
self._dfs(n, '', res, 0, 0)
return res
def _dfs(self, n, path, res, left_num, right_num):
"""nums, res, path, choose :return:"""... | the_stack_v2_python_sparse | DFS回溯/leetcode_22_括号生成.py | Gyczero/Leetcode_practice | train | 0 | |
c9beeca6e4553388f17074b1ac382178ed627721 | [
"self._state = state\nself._action_dispatcher = action_dispatcher\nself._plugins: List[AbstractPlugin] = []",
"plugin._configure(state=self._state, action_dispatcher=self._action_dispatcher)\nself._plugins.append(plugin)\nself._action_dispatcher.add_handler(plugin)\nplugin.setup()",
"for p in self._plugins:\n ... | <|body_start_0|>
self._state = state
self._action_dispatcher = action_dispatcher
self._plugins: List[AbstractPlugin] = []
<|end_body_0|>
<|body_start_1|>
plugin._configure(state=self._state, action_dispatcher=self._action_dispatcher)
self._plugins.append(plugin)
self._ac... | Configure, setup, and tear down engine plugins. | PluginStarter | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginStarter:
"""Configure, setup, and tear down engine plugins."""
def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None:
"""Create a PluginStarter interface with access to its dependencies."""
<|body_0|>
def start(self, plugin: AbstractPlug... | stack_v2_sparse_classes_75kplus_train_070640 | 3,443 | permissive | [
{
"docstring": "Create a PluginStarter interface with access to its dependencies.",
"name": "__init__",
"signature": "def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None"
},
{
"docstring": "Configure a given plugin and add it to the dispatch pipeline.",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_032275 | Implement the Python class `PluginStarter` described below.
Class description:
Configure, setup, and tear down engine plugins.
Method signatures and docstrings:
- def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: Create a PluginStarter interface with access to its dependencies.
- def ... | Implement the Python class `PluginStarter` described below.
Class description:
Configure, setup, and tear down engine plugins.
Method signatures and docstrings:
- def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None: Create a PluginStarter interface with access to its dependencies.
- def ... | 026b523c8c9e5d45910c490efb89194d72595be9 | <|skeleton|>
class PluginStarter:
"""Configure, setup, and tear down engine plugins."""
def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None:
"""Create a PluginStarter interface with access to its dependencies."""
<|body_0|>
def start(self, plugin: AbstractPlug... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PluginStarter:
"""Configure, setup, and tear down engine plugins."""
def __init__(self, state: StateView, action_dispatcher: ActionDispatcher) -> None:
"""Create a PluginStarter interface with access to its dependencies."""
self._state = state
self._action_dispatcher = action_disp... | the_stack_v2_python_sparse | api/src/opentrons/protocol_engine/plugins.py | Opentrons/opentrons | train | 326 |
00b04820f6e5984036a41b2d56633ecfd8fb70ae | [
"data = request.data\ntry:\n token = jwt_decode_handler(data['token'])\nexcept Exception as e:\n return Response({'token_state': False})\ntry:\n obj = Template.objects.filter(template_name=data['template_name'], user=token['user_id'])\nexcept:\n return Response({'message': '查询出错'})\nif obj:\n return ... | <|body_start_0|>
data = request.data
try:
token = jwt_decode_handler(data['token'])
except Exception as e:
return Response({'token_state': False})
try:
obj = Template.objects.filter(template_name=data['template_name'], user=token['user_id'])
ex... | 模板增删改 | CreateDeleteTemplateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateDeleteTemplateView:
"""模板增删改"""
def post(self, request, *args, **kwargs):
"""保存功能"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""删除操作"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = request.data
try:
... | stack_v2_sparse_classes_75kplus_train_070641 | 38,327 | no_license | [
{
"docstring": "保存功能",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "删除操作",
"name": "delete",
"signature": "def delete(self, request, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `CreateDeleteTemplateView` described below.
Class description:
模板增删改
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): 保存功能
- def delete(self, request, *args, **kwargs): 删除操作 | Implement the Python class `CreateDeleteTemplateView` described below.
Class description:
模板增删改
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): 保存功能
- def delete(self, request, *args, **kwargs): 删除操作
<|skeleton|>
class CreateDeleteTemplateView:
"""模板增删改"""
def post(self, reques... | 3c18d5d5727db1562438edea66ef15f54b378e33 | <|skeleton|>
class CreateDeleteTemplateView:
"""模板增删改"""
def post(self, request, *args, **kwargs):
"""保存功能"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""删除操作"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateDeleteTemplateView:
"""模板增删改"""
def post(self, request, *args, **kwargs):
"""保存功能"""
data = request.data
try:
token = jwt_decode_handler(data['token'])
except Exception as e:
return Response({'token_state': False})
try:
obj... | the_stack_v2_python_sparse | up_down_chain/up_down_chain/app/Users/views.py | wang18722/Up_down_chain | train | 0 |
8eb79998d207f97000902786ea60215a1f5151bd | [
"super().__init__(enc_dim, dec_dim, att_dim, dirac_at_first_step, discreteness)\nself.chunk_size = chunk_size\nself.chunk_energy = Energy(enc_dim, dec_dim, att_dim)\nself.unfold = nn.Unfold(kernel_size=(self.chunk_size, 1))\nself.softmax = nn.Softmax(dim=1)",
"batch_size, _ = emit_probs.size()\nframed_chunk_energ... | <|body_start_0|>
super().__init__(enc_dim, dec_dim, att_dim, dirac_at_first_step, discreteness)
self.chunk_size = chunk_size
self.chunk_energy = Energy(enc_dim, dec_dim, att_dim)
self.unfold = nn.Unfold(kernel_size=(self.chunk_size, 1))
self.softmax = nn.Softmax(dim=1)
<|end_body... | MoChA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoChA:
def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None:
"""[Monotonic Chunkwise Attention] from "Monotonic Chunkwise Attention" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW"""
... | stack_v2_sparse_classes_75kplus_train_070642 | 23,577 | no_license | [
{
"docstring": "[Monotonic Chunkwise Attention] from \"Monotonic Chunkwise Attention\" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW",
"name": "__init__",
"signature": "def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: fl... | 6 | stack_v2_sparse_classes_30k_train_025703 | Implement the Python class `MoChA` described below.
Class description:
Implement the MoChA class.
Method signatures and docstrings:
- def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None: [Monotonic Chunkwise Attention] from "M... | Implement the Python class `MoChA` described below.
Class description:
Implement the MoChA class.
Method signatures and docstrings:
- def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None: [Monotonic Chunkwise Attention] from "M... | 9f9a55f8020ac05b7bb84746a62a83950fe833a2 | <|skeleton|>
class MoChA:
def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None:
"""[Monotonic Chunkwise Attention] from "Monotonic Chunkwise Attention" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MoChA:
def __init__(self, chunk_size: int, enc_dim: int, dec_dim: int, att_dim: int, dirac_at_first_step: bool=False, discreteness: float=4.0) -> None:
"""[Monotonic Chunkwise Attention] from "Monotonic Chunkwise Attention" (ICLR 2018) https://openreview.net/forum?id=Hko85plCW"""
super().__ini... | the_stack_v2_python_sparse | stt/modules/attention.py | Chung-I/tsm-rnnt | train | 4 | |
24afe08196974e94b7463e4bd76b024529fbe545 | [
"self.Wz = np.random.normal(size=(i + h, h))\nself.Wr = np.random.normal(size=(i + h, h))\nself.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bz = np.zeros((1, h))\nself.br = np.zeros((1, h))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"concat = np.concatenate... | <|body_start_0|>
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bz = np.zeros((1, h))
self.br = np.zeros((1, h))
self.bh = np.zeros((1... | Represents a gated recurrent unit | GRUCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""Class constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Performs forward propagation for one time step. Returns: h_next, y"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_070643 | 1,724 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Performs forward propagation for one time step. Returns: h_next, y",
"name": "forward",
"signature": "def forward(self, h_prev, x_t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051815 | Implement the Python class `GRUCell` described below.
Class description:
Represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): Class constructor
- def forward(self, h_prev, x_t): Performs forward propagation for one time step. Returns: h_next, y | Implement the Python class `GRUCell` described below.
Class description:
Represents a gated recurrent unit
Method signatures and docstrings:
- def __init__(self, i, h, o): Class constructor
- def forward(self, h_prev, x_t): Performs forward propagation for one time step. Returns: h_next, y
<|skeleton|>
class GRUCell... | 161e33b23d398d7d01ad0d7740b78dda3f27e787 | <|skeleton|>
class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""Class constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Performs forward propagation for one time step. Returns: h_next, y"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRUCell:
"""Represents a gated recurrent unit"""
def __init__(self, i, h, o):
"""Class constructor"""
self.Wz = np.random.normal(size=(i + h, h))
self.Wr = np.random.normal(size=(i + h, h))
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/2-gru_cell.py | felipeserna/holbertonschool-machine_learning | train | 0 |
32fb3ef3de512b341f78036edfecd21f3e4e9498 | [
"self.__dict__['LANG'] = {'value': LANG, 'required': True, 'description': 'bash, perl, php, python, ruby, netcat, telnet'}\nself.__dict__['LHOST'] = {'value': LHOST, 'required': True, 'description': 'Local listening host'}\nself.__dict__['LPORT'] = {'value': LPORT, 'required': True, 'description': 'Local listening ... | <|body_start_0|>
self.__dict__['LANG'] = {'value': LANG, 'required': True, 'description': 'bash, perl, php, python, ruby, netcat, telnet'}
self.__dict__['LHOST'] = {'value': LHOST, 'required': True, 'description': 'Local listening host'}
self.__dict__['LPORT'] = {'value': LPORT, 'required': True... | Module Class | Module | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Module:
"""Module Class"""
def __init__(self, LANG='bash', LHOST=None, LPORT=4444):
"""__init__(self, LANG='bash', LHOST=None, LPORT=4444) :param LANG: :param LHOST: :param LPORT: Initialize the module with the module's desired options"""
<|body_0|>
def run(self):
... | stack_v2_sparse_classes_75kplus_train_070644 | 4,889 | no_license | [
{
"docstring": "__init__(self, LANG='bash', LHOST=None, LPORT=4444) :param LANG: :param LHOST: :param LPORT: Initialize the module with the module's desired options",
"name": "__init__",
"signature": "def __init__(self, LANG='bash', LHOST=None, LPORT=4444)"
},
{
"docstring": "run(self) :return: ... | 2 | null | Implement the Python class `Module` described below.
Class description:
Module Class
Method signatures and docstrings:
- def __init__(self, LANG='bash', LHOST=None, LPORT=4444): __init__(self, LANG='bash', LHOST=None, LPORT=4444) :param LANG: :param LHOST: :param LPORT: Initialize the module with the module's desired... | Implement the Python class `Module` described below.
Class description:
Module Class
Method signatures and docstrings:
- def __init__(self, LANG='bash', LHOST=None, LPORT=4444): __init__(self, LANG='bash', LHOST=None, LPORT=4444) :param LANG: :param LHOST: :param LPORT: Initialize the module with the module's desired... | 99e1d75b3d1af2e44740584be6c2ef1c1601c43c | <|skeleton|>
class Module:
"""Module Class"""
def __init__(self, LANG='bash', LHOST=None, LPORT=4444):
"""__init__(self, LANG='bash', LHOST=None, LPORT=4444) :param LANG: :param LHOST: :param LPORT: Initialize the module with the module's desired options"""
<|body_0|>
def run(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Module:
"""Module Class"""
def __init__(self, LANG='bash', LHOST=None, LPORT=4444):
"""__init__(self, LANG='bash', LHOST=None, LPORT=4444) :param LANG: :param LHOST: :param LPORT: Initialize the module with the module's desired options"""
self.__dict__['LANG'] = {'value': LANG, 'required'... | the_stack_v2_python_sparse | modules/payload/rsh.py | h4cklife/intrukit | train | 3 |
7c100d7880a2d943909f8b02b5e843ca7a67175c | [
"super(ResNet, self).__init__()\nself.base_layers = get_encoder(encoder_name, pretrained)\nself.layer0 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False), nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), nn.ReLU(inplace=True))\nself.lay... | <|body_start_0|>
super(ResNet, self).__init__()
self.base_layers = get_encoder(encoder_name, pretrained)
self.layer0 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False), nn.BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)... | ResNet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResNet:
def __init__(self, encoder_name: str, pretrained: bool=False):
""":param encoder_name: :param pretrained:"""
<|body_0|>
def forward(self, x):
"""Forward pass through feature extraction network :param x: Input image :return: Returns feature outputs at differen... | stack_v2_sparse_classes_75kplus_train_070645 | 2,657 | permissive | [
{
"docstring": ":param encoder_name: :param pretrained:",
"name": "__init__",
"signature": "def __init__(self, encoder_name: str, pretrained: bool=False)"
},
{
"docstring": "Forward pass through feature extraction network :param x: Input image :return: Returns feature outputs at different stages... | 2 | stack_v2_sparse_classes_30k_train_025966 | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def __init__(self, encoder_name: str, pretrained: bool=False): :param encoder_name: :param pretrained:
- def forward(self, x): Forward pass through feature extraction network :param ... | Implement the Python class `ResNet` described below.
Class description:
Implement the ResNet class.
Method signatures and docstrings:
- def __init__(self, encoder_name: str, pretrained: bool=False): :param encoder_name: :param pretrained:
- def forward(self, x): Forward pass through feature extraction network :param ... | 4091e8a5ba22c1db28b4accd71cf2994d544ffab | <|skeleton|>
class ResNet:
def __init__(self, encoder_name: str, pretrained: bool=False):
""":param encoder_name: :param pretrained:"""
<|body_0|>
def forward(self, x):
"""Forward pass through feature extraction network :param x: Input image :return: Returns feature outputs at differen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResNet:
def __init__(self, encoder_name: str, pretrained: bool=False):
""":param encoder_name: :param pretrained:"""
super(ResNet, self).__init__()
self.base_layers = get_encoder(encoder_name, pretrained)
self.layer0 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(... | the_stack_v2_python_sparse | src/segmentation/networks/resnetunet/encoder.py | sunayana/Burned_Area_Detection | train | 0 | |
9e69619658940bcee8ddcd2d1218ac3300684465 | [
"rles = []\nfor seg in segs:\n rle = cocomask.frPyObjects(seg, img_shape[0], img_shape[1])\n if isinstance(rle, list):\n rles.extend(rle)\n else:\n rles.append(rle)\nif rles:\n mask = cocomask.decode(cocomask.merge(rles))\nelse:\n mask = np.zeros(img_shape, dtype=np.uint8)\nreturn mask"... | <|body_start_0|>
rles = []
for seg in segs:
rle = cocomask.frPyObjects(seg, img_shape[0], img_shape[1])
if isinstance(rle, list):
rles.extend(rle)
else:
rles.append(rle)
if rles:
mask = cocomask.decode(cocomask.merge... | Generate the mask of valid regions from the segmentation annotation. Required Keys: - img_shape - invalid_segs (optional) - warp_mat (optional) - flip (optional) - flip_direction (optional) - heatmaps (optional) Added Keys: - heatmap_mask | BottomupGetHeatmapMask | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottomupGetHeatmapMask:
"""Generate the mask of valid regions from the segmentation annotation. Required Keys: - img_shape - invalid_segs (optional) - warp_mat (optional) - flip (optional) - flip_direction (optional) - heatmaps (optional) Added Keys: - heatmap_mask"""
def _segs_to_mask(self,... | stack_v2_sparse_classes_75kplus_train_070646 | 18,636 | permissive | [
{
"docstring": "Calculate mask from object segmentations. Args: segs (List): The object segmentation annotations in COCO format img_shape (Tuple): The image shape in (h, w) Returns: np.ndarray: The binary object mask in size (h, w), where the object pixels are 1 and background pixels are 0",
"name": "_segs_... | 2 | null | Implement the Python class `BottomupGetHeatmapMask` described below.
Class description:
Generate the mask of valid regions from the segmentation annotation. Required Keys: - img_shape - invalid_segs (optional) - warp_mat (optional) - flip (optional) - flip_direction (optional) - heatmaps (optional) Added Keys: - heatm... | Implement the Python class `BottomupGetHeatmapMask` described below.
Class description:
Generate the mask of valid regions from the segmentation annotation. Required Keys: - img_shape - invalid_segs (optional) - warp_mat (optional) - flip (optional) - flip_direction (optional) - heatmaps (optional) Added Keys: - heatm... | 537bd8e543ab463fb55120d5caaa1ae22d6aaf06 | <|skeleton|>
class BottomupGetHeatmapMask:
"""Generate the mask of valid regions from the segmentation annotation. Required Keys: - img_shape - invalid_segs (optional) - warp_mat (optional) - flip (optional) - flip_direction (optional) - heatmaps (optional) Added Keys: - heatmap_mask"""
def _segs_to_mask(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BottomupGetHeatmapMask:
"""Generate the mask of valid regions from the segmentation annotation. Required Keys: - img_shape - invalid_segs (optional) - warp_mat (optional) - flip (optional) - flip_direction (optional) - heatmaps (optional) Added Keys: - heatmap_mask"""
def _segs_to_mask(self, segs: list, ... | the_stack_v2_python_sparse | mmpose/datasets/transforms/bottomup_transforms.py | open-mmlab/mmpose | train | 4,037 |
e64d0d4e9e87e5d2df9a2fa7566610d35c0ea8a9 | [
"password = attrs[source]\nif len(password) < PASSWORD_MIN_LENGTH:\n raise serializers.ValidationError(code['E_INVALID_PASSWORD'])\nreturn attrs",
"password_confirmation = attrs[source]\npassword = attrs['password']\nif password_confirmation != password:\n raise serializers.ValidationError(code['E_PASSWORD_... | <|body_start_0|>
password = attrs[source]
if len(password) < PASSWORD_MIN_LENGTH:
raise serializers.ValidationError(code['E_INVALID_PASSWORD'])
return attrs
<|end_body_0|>
<|body_start_1|>
password_confirmation = attrs[source]
password = attrs['password']
if ... | ResetPasswordKeySerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResetPasswordKeySerializer:
def validate_password(attrs, source):
"""Check valid password"""
<|body_0|>
def validate_password_confirmation(attrs, source):
"""Password2 check"""
<|body_1|>
def restore_object(self, attrs, instance):
"""Change passw... | stack_v2_sparse_classes_75kplus_train_070647 | 4,776 | no_license | [
{
"docstring": "Check valid password",
"name": "validate_password",
"signature": "def validate_password(attrs, source)"
},
{
"docstring": "Password2 check",
"name": "validate_password_confirmation",
"signature": "def validate_password_confirmation(attrs, source)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_017677 | Implement the Python class `ResetPasswordKeySerializer` described below.
Class description:
Implement the ResetPasswordKeySerializer class.
Method signatures and docstrings:
- def validate_password(attrs, source): Check valid password
- def validate_password_confirmation(attrs, source): Password2 check
- def restore_... | Implement the Python class `ResetPasswordKeySerializer` described below.
Class description:
Implement the ResetPasswordKeySerializer class.
Method signatures and docstrings:
- def validate_password(attrs, source): Check valid password
- def validate_password_confirmation(attrs, source): Password2 check
- def restore_... | 28d5f3fd0b4deb6909aeda97f17f2994eaffd48a | <|skeleton|>
class ResetPasswordKeySerializer:
def validate_password(attrs, source):
"""Check valid password"""
<|body_0|>
def validate_password_confirmation(attrs, source):
"""Password2 check"""
<|body_1|>
def restore_object(self, attrs, instance):
"""Change passw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResetPasswordKeySerializer:
def validate_password(attrs, source):
"""Check valid password"""
password = attrs[source]
if len(password) < PASSWORD_MIN_LENGTH:
raise serializers.ValidationError(code['E_INVALID_PASSWORD'])
return attrs
def validate_password_confir... | the_stack_v2_python_sparse | api/authMana/serializers.py | minhdo6487/api-proto | train | 0 | |
cb7b642492e476a613dcb222623b48999c748b01 | [
"self.val_list = list()\nself.map = dict()\nrandom.seed()",
"if val in self.map:\n if self.val_list[self.map[val]]:\n res = False\n else:\n res = True\n self.val_list[self.map[val]].append(val)\nelse:\n self.val_list.append([val])\n self.map[val] = len(self.val_list) - 1\n res = Tr... | <|body_start_0|>
self.val_list = list()
self.map = dict()
random.seed()
<|end_body_0|>
<|body_start_1|>
if val in self.map:
if self.val_list[self.map[val]]:
res = False
else:
res = True
self.val_list[self.map[val]].appe... | RandomizedCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool"""
... | stack_v2_sparse_classes_75kplus_train_070648 | 1,540 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
... | 4 | stack_v2_sparse_classes_30k_train_017088 | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the collection. Returns true if the collection did no... | Implement the Python class `RandomizedCollection` described below.
Class description:
Implement the RandomizedCollection class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the collection. Returns true if the collection did no... | 131fe3d622aa765a044fede9d38c9b3fbcd26966 | <|skeleton|>
class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the specified element. :type val: int :rtype: bool"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomizedCollection:
def __init__(self):
"""Initialize your data structure here."""
self.val_list = list()
self.map = dict()
random.seed()
def insert(self, val):
"""Inserts a value to the collection. Returns true if the collection did not already contain the speci... | the_stack_v2_python_sparse | leetcode/insert-delete-getrandom-o1-duplicates-allowed.py | Vspick/python_interview | train | 0 | |
5b7726e87609fa7da164348566c732cbfa7eece7 | [
"real_url = url1 + REGISTER\nr = base_requests.post(real_url, data=data)\nreturn r",
"real_url = url1 + LOGIN\nr = base_requests.post(real_url, data=data)\nreturn r"
] | <|body_start_0|>
real_url = url1 + REGISTER
r = base_requests.post(real_url, data=data)
return r
<|end_body_0|>
<|body_start_1|>
real_url = url1 + LOGIN
r = base_requests.post(real_url, data=data)
return r
<|end_body_1|>
| Member | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Member:
def register(self, url1, base_requests, data):
"""用户注册的接口 :param url: 环境信息 http://host:post/ :param base_requests: :param data:数据 :return:响应信息"""
<|body_0|>
def login(self, url1, base_requests, data):
""":param url: :param data: :param base_requests: :return:... | stack_v2_sparse_classes_75kplus_train_070649 | 1,040 | no_license | [
{
"docstring": "用户注册的接口 :param url: 环境信息 http://host:post/ :param base_requests: :param data:数据 :return:响应信息",
"name": "register",
"signature": "def register(self, url1, base_requests, data)"
},
{
"docstring": ":param url: :param data: :param base_requests: :return:",
"name": "login",
"s... | 2 | stack_v2_sparse_classes_30k_val_002185 | Implement the Python class `Member` described below.
Class description:
Implement the Member class.
Method signatures and docstrings:
- def register(self, url1, base_requests, data): 用户注册的接口 :param url: 环境信息 http://host:post/ :param base_requests: :param data:数据 :return:响应信息
- def login(self, url1, base_requests, dat... | Implement the Python class `Member` described below.
Class description:
Implement the Member class.
Method signatures and docstrings:
- def register(self, url1, base_requests, data): 用户注册的接口 :param url: 环境信息 http://host:post/ :param base_requests: :param data:数据 :return:响应信息
- def login(self, url1, base_requests, dat... | 153edbbed368725cda4ce254abb50394f8b5d19b | <|skeleton|>
class Member:
def register(self, url1, base_requests, data):
"""用户注册的接口 :param url: 环境信息 http://host:post/ :param base_requests: :param data:数据 :return:响应信息"""
<|body_0|>
def login(self, url1, base_requests, data):
""":param url: :param data: :param base_requests: :return:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Member:
def register(self, url1, base_requests, data):
"""用户注册的接口 :param url: 环境信息 http://host:post/ :param base_requests: :param data:数据 :return:响应信息"""
real_url = url1 + REGISTER
r = base_requests.post(real_url, data=data)
return r
def login(self, url1, base_requests, da... | the_stack_v2_python_sparse | JinRong/baw/Member.py | Zhangyang12138/API | train | 0 | |
4852ff1b1828f27cf5f2836369d830decb5b8a01 | [
"if not self.start:\n return None\nperiod = timedelta(hours=3)\nreturn datetime.utcfromtimestamp(random.randrange(int(self.start.timestamp()), int((self.start + period).timestamp()))).replace(tzinfo=ZoneInfo('UTC'))",
"if create and extracted:\n for item in extracted:\n core_models.MeetingAccess.obje... | <|body_start_0|>
if not self.start:
return None
period = timedelta(hours=3)
return datetime.utcfromtimestamp(random.randrange(int(self.start.timestamp()), int((self.start + period).timestamp()))).replace(tzinfo=ZoneInfo('UTC'))
<|end_body_0|>
<|body_start_1|>
if create and e... | Create fake meetings for testing. | MeetingFactory | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeetingFactory:
"""Create fake meetings for testing."""
def end(self):
"""The end datetime is at a random duration after the start datetme (we pick within 3 hours)."""
<|body_0|>
def users(self, create, extracted, **kwargs):
"""Add users to meeting from a given l... | stack_v2_sparse_classes_75kplus_train_070650 | 6,667 | permissive | [
{
"docstring": "The end datetime is at a random duration after the start datetme (we pick within 3 hours).",
"name": "end",
"signature": "def end(self)"
},
{
"docstring": "Add users to meeting from a given list of users.",
"name": "users",
"signature": "def users(self, create, extracted,... | 3 | null | Implement the Python class `MeetingFactory` described below.
Class description:
Create fake meetings for testing.
Method signatures and docstrings:
- def end(self): The end datetime is at a random duration after the start datetme (we pick within 3 hours).
- def users(self, create, extracted, **kwargs): Add users to m... | Implement the Python class `MeetingFactory` described below.
Class description:
Create fake meetings for testing.
Method signatures and docstrings:
- def end(self): The end datetime is at a random duration after the start datetme (we pick within 3 hours).
- def users(self, create, extracted, **kwargs): Add users to m... | a4f563e9a56a1948f0ae4e21dcbfb9d9ef51483e | <|skeleton|>
class MeetingFactory:
"""Create fake meetings for testing."""
def end(self):
"""The end datetime is at a random duration after the start datetme (we pick within 3 hours)."""
<|body_0|>
def users(self, create, extracted, **kwargs):
"""Add users to meeting from a given l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MeetingFactory:
"""Create fake meetings for testing."""
def end(self):
"""The end datetime is at a random duration after the start datetme (we pick within 3 hours)."""
if not self.start:
return None
period = timedelta(hours=3)
return datetime.utcfromtimestamp(r... | the_stack_v2_python_sparse | src/magnify/apps/core/factories.py | openfun/jitsi-magnify | train | 23 |
4f49e1a2abd36f9b4bef6fc464a8ed851b6e0bee | [
"if 'id' in request.GET:\n project_id = 'new_app:vote:%s' % request.GET.get('related_page_id', 0)\n try:\n vote = app_models.vote.objects.get(id=request.GET['id'])\n except:\n c = RequestContext(request, {'first_nav_name': FIRST_NAV, 'second_navs': export.get_promotion_and_apps_second_navs(re... | <|body_start_0|>
if 'id' in request.GET:
project_id = 'new_app:vote:%s' % request.GET.get('related_page_id', 0)
try:
vote = app_models.vote.objects.get(id=request.GET['id'])
except:
c = RequestContext(request, {'first_nav_name': FIRST_NAV, 'sec... | vote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vote:
def get(request):
"""响应GET"""
<|body_0|>
def api_put(request):
"""响应PUT"""
<|body_1|>
def api_post(request):
"""响应POST"""
<|body_2|>
def api_delete(request):
"""响应DELETE"""
<|body_3|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_070651 | 3,437 | no_license | [
{
"docstring": "响应GET",
"name": "get",
"signature": "def get(request)"
},
{
"docstring": "响应PUT",
"name": "api_put",
"signature": "def api_put(request)"
},
{
"docstring": "响应POST",
"name": "api_post",
"signature": "def api_post(request)"
},
{
"docstring": "响应DELET... | 4 | stack_v2_sparse_classes_30k_train_052235 | Implement the Python class `vote` described below.
Class description:
Implement the vote class.
Method signatures and docstrings:
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE | Implement the Python class `vote` described below.
Class description:
Implement the vote class.
Method signatures and docstrings:
- def get(request): 响应GET
- def api_put(request): 响应PUT
- def api_post(request): 响应POST
- def api_delete(request): 响应DELETE
<|skeleton|>
class vote:
def get(request):
"""响应GE... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class vote:
def get(request):
"""响应GET"""
<|body_0|>
def api_put(request):
"""响应PUT"""
<|body_1|>
def api_post(request):
"""响应POST"""
<|body_2|>
def api_delete(request):
"""响应DELETE"""
<|body_3|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class vote:
def get(request):
"""响应GET"""
if 'id' in request.GET:
project_id = 'new_app:vote:%s' % request.GET.get('related_page_id', 0)
try:
vote = app_models.vote.objects.get(id=request.GET['id'])
except:
c = RequestContext(reques... | the_stack_v2_python_sparse | weapp/apps/customerized_apps/vote/vote.py | chengdg/weizoom | train | 1 | |
11ff52aedd964ab60cc3b06b5edb5088a6aa9e74 | [
"self._backend = backend\nself._shots = shots\nself._clf = svm.SVC()\nself._num_evaluation = 0\nself._kernel_matrix = None\nself._normalized_training_vectors = None\nself._unnormalized_training_vectors = None\nself._training_labels = None\nif kernel_type == 'qke':\n self._kernel_circuit = KernelEstimationCircuit... | <|body_start_0|>
self._backend = backend
self._shots = shots
self._clf = svm.SVC()
self._num_evaluation = 0
self._kernel_matrix = None
self._normalized_training_vectors = None
self._unnormalized_training_vectors = None
self._training_labels = None
... | Kernel Classifier class | KernelClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KernelClassifier:
"""Kernel Classifier class"""
def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024):
"""The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum... | stack_v2_sparse_classes_75kplus_train_070652 | 5,902 | permissive | [
{
"docstring": "The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum-hub.baidu.com/quickGuide for details encoding_style (str): Encoding scheme to be used, defaults to 'IQP', which uses the default encoding scheme kernel_type (str): ... | 5 | stack_v2_sparse_classes_30k_train_011151 | Implement the Python class `KernelClassifier` described below.
Class description:
Kernel Classifier class
Method signatures and docstrings:
- def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024): The constructor of the KernelClassifier class Args: backend (str): Backend... | Implement the Python class `KernelClassifier` described below.
Class description:
Kernel Classifier class
Method signatures and docstrings:
- def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024): The constructor of the KernelClassifier class Args: backend (str): Backend... | 8bc3c7238b5b6825eb63ded8d65afb08b389941f | <|skeleton|>
class KernelClassifier:
"""Kernel Classifier class"""
def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024):
"""The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KernelClassifier:
"""Kernel Classifier class"""
def __init__(self, backend: str, encoding_style: str='IQP', kernel_type: str='qke', shots: int=1024):
"""The constructor of the KernelClassifier class Args: backend (str): Backend to be used in this task. Please refer to https://quantum-hub.baidu.co... | the_stack_v2_python_sparse | Extensions/QuantumApp/qcompute_qapp/algorithm/kernel_classifier.py | baidu/QCompute | train | 86 |
c87ead78bd14ca7ec3d015fdaab4213591348bb9 | [
"ret = dict([(p, unicode(getattr(self, p))) for p in self.properties()])\nret['id'] = self.key().id_or_name()\nret['items'] = self.items\nreturn ret",
"if description is None or description == '':\n raise ValueError(' description not set')\nproduct = None\nif key is not None:\n product = Product.get_by_id(i... | <|body_start_0|>
ret = dict([(p, unicode(getattr(self, p))) for p in self.properties()])
ret['id'] = self.key().id_or_name()
ret['items'] = self.items
return ret
<|end_body_0|>
<|body_start_1|>
if description is None or description == '':
raise ValueError(' descripti... | Model class for ShoppingList | ShoppingList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShoppingList:
"""Model class for ShoppingList"""
def to_dict(self):
"""For JSON serialization"""
<|body_0|>
def add_item(self, description, key, quantity):
"""Add an item to the list"""
<|body_1|>
def get_items(self):
"""Get all items"""
... | stack_v2_sparse_classes_75kplus_train_070653 | 3,485 | no_license | [
{
"docstring": "For JSON serialization",
"name": "to_dict",
"signature": "def to_dict(self)"
},
{
"docstring": "Add an item to the list",
"name": "add_item",
"signature": "def add_item(self, description, key, quantity)"
},
{
"docstring": "Get all items",
"name": "get_items",
... | 5 | stack_v2_sparse_classes_30k_train_034413 | Implement the Python class `ShoppingList` described below.
Class description:
Model class for ShoppingList
Method signatures and docstrings:
- def to_dict(self): For JSON serialization
- def add_item(self, description, key, quantity): Add an item to the list
- def get_items(self): Get all items
- def delete_item(self... | Implement the Python class `ShoppingList` described below.
Class description:
Model class for ShoppingList
Method signatures and docstrings:
- def to_dict(self): For JSON serialization
- def add_item(self, description, key, quantity): Add an item to the list
- def get_items(self): Get all items
- def delete_item(self... | 394b4821b65191df221d62f807ba2895f38e86a3 | <|skeleton|>
class ShoppingList:
"""Model class for ShoppingList"""
def to_dict(self):
"""For JSON serialization"""
<|body_0|>
def add_item(self, description, key, quantity):
"""Add an item to the list"""
<|body_1|>
def get_items(self):
"""Get all items"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ShoppingList:
"""Model class for ShoppingList"""
def to_dict(self):
"""For JSON serialization"""
ret = dict([(p, unicode(getattr(self, p))) for p in self.properties()])
ret['id'] = self.key().id_or_name()
ret['items'] = self.items
return ret
def add_item(self,... | the_stack_v2_python_sparse | model/shoppinglist.py | szilardhuber/shopper | train | 1 |
b53b6846a85579c35f8cd74aaaa6735f14c962ce | [
"async for position in drone.telemetry.position():\n altitude: float = round(position.relative_altitude_m, 2)\n if altitude >= config.MAST_ALT:\n return True",
"async for gps in drone.telemetry.position():\n config.takeoff_pos = LatLon(round(gps.latitude_deg, 8), round(gps.longitude_deg, 8))\n ... | <|body_start_0|>
async for position in drone.telemetry.position():
altitude: float = round(position.relative_altitude_m, 2)
if altitude >= config.MAST_ALT:
return True
<|end_body_0|>
<|body_start_1|>
async for gps in drone.telemetry.position():
config... | The state that performs straight-vertical takeoff | SimpleTakeoff | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTakeoff:
"""The state that performs straight-vertical takeoff"""
async def check_altitude(self, drone: System) -> bool:
"""Checks the altitude of the drone to make sure that we are at our target Parameters: drone(System): Our drone object"""
<|body_0|>
async def ru... | stack_v2_sparse_classes_75kplus_train_070654 | 2,096 | permissive | [
{
"docstring": "Checks the altitude of the drone to make sure that we are at our target Parameters: drone(System): Our drone object",
"name": "check_altitude",
"signature": "async def check_altitude(self, drone: System) -> bool"
},
{
"docstring": "Arms and takes off the drone",
"name": "run"... | 2 | stack_v2_sparse_classes_30k_train_052322 | Implement the Python class `SimpleTakeoff` described below.
Class description:
The state that performs straight-vertical takeoff
Method signatures and docstrings:
- async def check_altitude(self, drone: System) -> bool: Checks the altitude of the drone to make sure that we are at our target Parameters: drone(System):... | Implement the Python class `SimpleTakeoff` described below.
Class description:
The state that performs straight-vertical takeoff
Method signatures and docstrings:
- async def check_altitude(self, drone: System) -> bool: Checks the altitude of the drone to make sure that we are at our target Parameters: drone(System):... | 91a6f3f2f621205a500a7d5e13effbd7ba29cc24 | <|skeleton|>
class SimpleTakeoff:
"""The state that performs straight-vertical takeoff"""
async def check_altitude(self, drone: System) -> bool:
"""Checks the altitude of the drone to make sure that we are at our target Parameters: drone(System): Our drone object"""
<|body_0|>
async def ru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SimpleTakeoff:
"""The state that performs straight-vertical takeoff"""
async def check_altitude(self, drone: System) -> bool:
"""Checks the altitude of the drone to make sure that we are at our target Parameters: drone(System): Our drone object"""
async for position in drone.telemetry.pos... | the_stack_v2_python_sparse | flight/states/simple_takeoff.py | MissouriMRR/IARC-2020 | train | 12 |
eeaaec1c161e7ff9975456fe0b01e427e45a1068 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('sbrz_nedg', 'sbrz_nedg')\ndb = client.repo\ncollection = db['sbrz_nedg.property_assessment']\nx = []\naddresses = collection.find({}, {'MAIL_ADDRESS': 1, 'MAIL CS': 1, 'ZIPCODE': 1})\nfor address in addr... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('sbrz_nedg', 'sbrz_nedg')
db = client.repo
collection = db['sbrz_nedg.property_assessment']
x = []
addresses = collection.find({}, ... | selectAddresses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class selectAddresses:
def execute(trial=False):
"""Select all of the addresses from the Property Assessment data set"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happenin... | stack_v2_sparse_classes_75kplus_train_070655 | 3,463 | no_license | [
{
"docstring": "Select all of the addresses from the Property Assessment data set",
"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 document des... | 2 | stack_v2_sparse_classes_30k_train_006463 | Implement the Python class `selectAddresses` described below.
Class description:
Implement the selectAddresses class.
Method signatures and docstrings:
- def execute(trial=False): Select all of the addresses from the Property Assessment data set
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=... | Implement the Python class `selectAddresses` described below.
Class description:
Implement the selectAddresses class.
Method signatures and docstrings:
- def execute(trial=False): Select all of the addresses from the Property Assessment data set
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class selectAddresses:
def execute(trial=False):
"""Select all of the addresses from the Property Assessment data set"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happenin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class selectAddresses:
def execute(trial=False):
"""Select all of the addresses from the Property Assessment data set"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('sbrz_nedg', 'sbrz_nedg')
db = client.r... | the_stack_v2_python_sparse | sbrz_nedg/selectAddresses.py | ROODAY/course-2017-fal-proj | train | 3 | |
904d8a88ecd4141c40221a2ff3a1f008dc4dc068 | [
"file_obj = self.files.get('path')\nattachment_kwargs = {'uuid': uuid4(), 'user': user, 'local_site': local_site}\nif file_obj:\n mimetype = get_uploaded_file_mimetype(file_obj)\n filename = get_unique_filename(file_obj.name)\n extra_data = self.cleaned_data['extra_data']\n attachment_kwargs.update({'ca... | <|body_start_0|>
file_obj = self.files.get('path')
attachment_kwargs = {'uuid': uuid4(), 'user': user, 'local_site': local_site}
if file_obj:
mimetype = get_uploaded_file_mimetype(file_obj)
filename = get_unique_filename(file_obj.name)
extra_data = self.cleane... | A form that handles uploading of user files. | UploadUserFileForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadUserFileForm:
"""A form that handles uploading of user files."""
def create(self, user, local_site=None):
"""Create a FileAttachment based on this form. Args: user (django.contrib.auth.models.User): The user who owns this file attachment. local_site (reviewboard.site.models.Loc... | stack_v2_sparse_classes_75kplus_train_070656 | 8,310 | permissive | [
{
"docstring": "Create a FileAttachment based on this form. Args: user (django.contrib.auth.models.User): The user who owns this file attachment. local_site (reviewboard.site.models.LocalSite, optional): The optional local site. Returns: reviewboard.attachments.models.FileAttachment: The new file attachment mod... | 2 | null | Implement the Python class `UploadUserFileForm` described below.
Class description:
A form that handles uploading of user files.
Method signatures and docstrings:
- def create(self, user, local_site=None): Create a FileAttachment based on this form. Args: user (django.contrib.auth.models.User): The user who owns this... | Implement the Python class `UploadUserFileForm` described below.
Class description:
A form that handles uploading of user files.
Method signatures and docstrings:
- def create(self, user, local_site=None): Create a FileAttachment based on this form. Args: user (django.contrib.auth.models.User): The user who owns this... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class UploadUserFileForm:
"""A form that handles uploading of user files."""
def create(self, user, local_site=None):
"""Create a FileAttachment based on this form. Args: user (django.contrib.auth.models.User): The user who owns this file attachment. local_site (reviewboard.site.models.Loc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UploadUserFileForm:
"""A form that handles uploading of user files."""
def create(self, user, local_site=None):
"""Create a FileAttachment based on this form. Args: user (django.contrib.auth.models.User): The user who owns this file attachment. local_site (reviewboard.site.models.LocalSite, optio... | the_stack_v2_python_sparse | reviewboard/attachments/forms.py | reviewboard/reviewboard | train | 1,141 |
86779baf5c60f884580f9bd4ad0b16f3eff85afc | [
"try:\n data = fits.open(path)\nexcept FileNotFoundError:\n data = None\nreturn data",
"if not isinstance(inMemoryDataset, fits.HDUList):\n raise NotImplementedError('Unable to write this representation of FITS into a file.')\ninMemoryDataset.writeto(self.fileDescriptor.location.path)"
] | <|body_start_0|>
try:
data = fits.open(path)
except FileNotFoundError:
data = None
return data
<|end_body_0|>
<|body_start_1|>
if not isinstance(inMemoryDataset, fits.HDUList):
raise NotImplementedError('Unable to write this representation of FITS int... | Interface for reading and writing astropy image objects to and from FITS files. | AstropyImageFormatter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AstropyImageFormatter:
"""Interface for reading and writing astropy image objects to and from FITS files."""
def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any:
"""Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JS... | stack_v2_sparse_classes_75kplus_train_070657 | 1,661 | no_license | [
{
"docstring": "Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JSON format file. pytype : `class`, optional Not used by this implementation. Returns ------- data : `object` Either data as Python object read from JSON file, or None if the file could not be opened... | 2 | stack_v2_sparse_classes_30k_train_010819 | Implement the Python class `AstropyImageFormatter` described below.
Class description:
Interface for reading and writing astropy image objects to and from FITS files.
Method signatures and docstrings:
- def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any: Read a file from the path in FITS format. ... | Implement the Python class `AstropyImageFormatter` described below.
Class description:
Interface for reading and writing astropy image objects to and from FITS files.
Method signatures and docstrings:
- def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any: Read a file from the path in FITS format. ... | 4a292c3c42a094c87bb62a9afd97cff68878d2d2 | <|skeleton|>
class AstropyImageFormatter:
"""Interface for reading and writing astropy image objects to and from FITS files."""
def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any:
"""Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JS... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AstropyImageFormatter:
"""Interface for reading and writing astropy image objects to and from FITS files."""
def _readFile(self, path: str, pytype: Optional[Type[Any]]=None) -> Any:
"""Read a file from the path in FITS format. Parameters ---------- path : `str` Path to use to open JSON format fil... | the_stack_v2_python_sparse | python/spherex/formatters/astropy_image.py | Caltech-IPAC/spherex_butler_poc | train | 0 |
82b9754421ab4fae69abad4022d2f1e1b26ecf69 | [
"self.heuristic = heuristic\nself.region = None\nself._locked = []\nself._resource_entity = {}\nself._entity_resource = {}\nfor key, entity in entity_config.statics.items():\n if entity.resource:\n self._entity_resource[key] = entity.resource.type",
"if entity.id not in self._entity_resource:\n retur... | <|body_start_0|>
self.heuristic = heuristic
self.region = None
self._locked = []
self._resource_entity = {}
self._entity_resource = {}
for key, entity in entity_config.statics.items():
if entity.resource:
self._entity_resource[key] = entity.res... | Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (list): _resource_entity -- Maps resource typ... | ResourceManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceManager:
"""Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (l... | stack_v2_sparse_classes_75kplus_train_070658 | 7,472 | no_license | [
{
"docstring": "Test: >>> from ai import pathfinding >>> from data.config import entity as config >>> heuristic = pathfinding.EuclideanDistance() >>> entity_config = config.Entity() >>> entity = config.StaticEntity() >>> entity.resource = config.Resource() >>> entity.resource.type = 'resource1' >>> entity_confi... | 5 | stack_v2_sparse_classes_30k_train_044062 | Implement the Python class `ResourceManager` described below.
Class description:
Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dic... | Implement the Python class `ResourceManager` described below.
Class description:
Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dic... | c38b43edb7ec54f18768564c42859195bc2477e4 | <|skeleton|>
class ResourceManager:
"""Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceManager:
"""Manages resources in the world and finds them. Member: heuristic -- Heuristic which calculates the distance of two points. region -- The region of the manager (data.world.region). _entity_resource -- Maps entity ids to resource types (dict). _locked -- List of locked entity (list): _resour... | the_stack_v2_python_sparse | python-prototype/data/world/resourcemanager.py | tea2code/fantasy-rts | train | 0 |
90e91b39492215f3cb8f4f64052bf392ef086be5 | [
"if not prices:\n return 0\ndp = [[0] * (2 + 1) for _ in range(len(prices))]\nfor k in range(1, 3):\n for i in range(1, len(prices)):\n temp = prices[i] - prices[0]\n for j in range(1, i):\n temp = max(temp, prices[i] - prices[j] + dp[j - 1][k - 1])\n dp[i][k] = max(dp[i - 1][k... | <|body_start_0|>
if not prices:
return 0
dp = [[0] * (2 + 1) for _ in range(len(prices))]
for k in range(1, 3):
for i in range(1, len(prices)):
temp = prices[i] - prices[0]
for j in range(1, i):
temp = max(temp, prices[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit_1(self, prices: List[int]) -> int:
"""FIXME: 超时 动态规划,辅助数组: dp[i][1] 表示前 i 天内 1 笔交易的最大利润 dp[i][2] 表示前 i 天内 2 笔交易的最大利润 - 第 i 天无动作, 则 dp[i][2] = dp[i-1][2] - 第 i 天卖出,则必须在第 j 天买入,此时利润 prices[i] - prices[j] + dp[j - 1][1]"""
<|body_0|>
def maxProfit(self, ... | stack_v2_sparse_classes_75kplus_train_070659 | 3,489 | no_license | [
{
"docstring": "FIXME: 超时 动态规划,辅助数组: dp[i][1] 表示前 i 天内 1 笔交易的最大利润 dp[i][2] 表示前 i 天内 2 笔交易的最大利润 - 第 i 天无动作, 则 dp[i][2] = dp[i-1][2] - 第 i 天卖出,则必须在第 j 天买入,此时利润 prices[i] - prices[j] + dp[j - 1][1]",
"name": "maxProfit_1",
"signature": "def maxProfit_1(self, prices: List[int]) -> int"
},
{
"docstri... | 2 | stack_v2_sparse_classes_30k_train_017326 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit_1(self, prices: List[int]) -> int: FIXME: 超时 动态规划,辅助数组: dp[i][1] 表示前 i 天内 1 笔交易的最大利润 dp[i][2] 表示前 i 天内 2 笔交易的最大利润 - 第 i 天无动作, 则 dp[i][2] = dp[i-1][2] - 第 i 天卖出,则必须在... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit_1(self, prices: List[int]) -> int: FIXME: 超时 动态规划,辅助数组: dp[i][1] 表示前 i 天内 1 笔交易的最大利润 dp[i][2] 表示前 i 天内 2 笔交易的最大利润 - 第 i 天无动作, 则 dp[i][2] = dp[i-1][2] - 第 i 天卖出,则必须在... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def maxProfit_1(self, prices: List[int]) -> int:
"""FIXME: 超时 动态规划,辅助数组: dp[i][1] 表示前 i 天内 1 笔交易的最大利润 dp[i][2] 表示前 i 天内 2 笔交易的最大利润 - 第 i 天无动作, 则 dp[i][2] = dp[i-1][2] - 第 i 天卖出,则必须在第 j 天买入,此时利润 prices[i] - prices[j] + dp[j - 1][1]"""
<|body_0|>
def maxProfit(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProfit_1(self, prices: List[int]) -> int:
"""FIXME: 超时 动态规划,辅助数组: dp[i][1] 表示前 i 天内 1 笔交易的最大利润 dp[i][2] 表示前 i 天内 2 笔交易的最大利润 - 第 i 天无动作, 则 dp[i][2] = dp[i-1][2] - 第 i 天卖出,则必须在第 j 天买入,此时利润 prices[i] - prices[j] + dp[j - 1][1]"""
if not prices:
return 0
dp = [... | the_stack_v2_python_sparse | .leetcode/123.买卖股票的最佳时机-iii.py | xiaoruijiang/algorithm | train | 0 | |
bd4f9e9a87bdf74bc54a5fd50ec1a4461c46dc6b | [
"super().__init__()\nself.hidden_dim = hidden_dim\nself.self_attention = self_attention\nif self.self_attention:\n self.control = xavier_uniform_linear(self.hidden_dim, self.hidden_dim)\n self.attn = xavier_uniform_linear(self.hidden_dim, 1)\n self.concat = xavier_uniform_linear(self.hidden_dim * 3, self.h... | <|body_start_0|>
super().__init__()
self.hidden_dim = hidden_dim
self.self_attention = self_attention
if self.self_attention:
self.control = xavier_uniform_linear(self.hidden_dim, self.hidden_dim)
self.attn = xavier_uniform_linear(self.hidden_dim, 1)
s... | A MAC recurrent cell write unit. | WriteUnit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WriteUnit:
"""A MAC recurrent cell write unit."""
def __init__(self, hidden_dim: int=512, self_attention: bool=False) -> None:
"""Initialise the write unit."""
<|body_0|>
def forward(self, memories: Sequence[torch.Tensor], retrieved: torch.Tensor, controls: Sequence[torc... | stack_v2_sparse_classes_75kplus_train_070660 | 2,523 | no_license | [
{
"docstring": "Initialise the write unit.",
"name": "__init__",
"signature": "def __init__(self, hidden_dim: int=512, self_attention: bool=False) -> None"
},
{
"docstring": "Propagate data through the model.",
"name": "forward",
"signature": "def forward(self, memories: Sequence[torch.T... | 2 | stack_v2_sparse_classes_30k_train_019400 | Implement the Python class `WriteUnit` described below.
Class description:
A MAC recurrent cell write unit.
Method signatures and docstrings:
- def __init__(self, hidden_dim: int=512, self_attention: bool=False) -> None: Initialise the write unit.
- def forward(self, memories: Sequence[torch.Tensor], retrieved: torch... | Implement the Python class `WriteUnit` described below.
Class description:
A MAC recurrent cell write unit.
Method signatures and docstrings:
- def __init__(self, hidden_dim: int=512, self_attention: bool=False) -> None: Initialise the write unit.
- def forward(self, memories: Sequence[torch.Tensor], retrieved: torch... | 78c479f8d0b3209ece9f9ccbbf63810802293f61 | <|skeleton|>
class WriteUnit:
"""A MAC recurrent cell write unit."""
def __init__(self, hidden_dim: int=512, self_attention: bool=False) -> None:
"""Initialise the write unit."""
<|body_0|>
def forward(self, memories: Sequence[torch.Tensor], retrieved: torch.Tensor, controls: Sequence[torc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WriteUnit:
"""A MAC recurrent cell write unit."""
def __init__(self, hidden_dim: int=512, self_attention: bool=False) -> None:
"""Initialise the write unit."""
super().__init__()
self.hidden_dim = hidden_dim
self.self_attention = self_attention
if self.self_attenti... | the_stack_v2_python_sparse | gat_vqa/modules/reasoning/mac/write.py | alexmirrington/gat-vqa | train | 4 |
d5cd8da27f4cf029279d14fbd9fd3e964211bbc1 | [
"Shape.__init__(self, turtle, color)\nself._x1 = x1\nself._x = x\nself._y1 = y1\nself._y = y",
"self._turtle.setColor(self._color[0], self._color[1], self._color[2])\nself._turtle.up()\nself._turtle.move(self._x, self._y)\nself._turtle.down()\nself._turtle.move(self._x1, self._y1)\nself._turtle.up()"
] | <|body_start_0|>
Shape.__init__(self, turtle, color)
self._x1 = x1
self._x = x
self._y1 = y1
self._y = y
<|end_body_0|>
<|body_start_1|>
self._turtle.setColor(self._color[0], self._color[1], self._color[2])
self._turtle.up()
self._turtle.move(self._x, sel... | Line | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Line:
def __init__(self, turtle, color, x, y, x1, y1):
"""Initializes the derived shape, Line."""
<|body_0|>
def draw(self):
"""Draws the line that is represented by the stored variables."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Shape.__init_... | stack_v2_sparse_classes_75kplus_train_070661 | 7,146 | permissive | [
{
"docstring": "Initializes the derived shape, Line.",
"name": "__init__",
"signature": "def __init__(self, turtle, color, x, y, x1, y1)"
},
{
"docstring": "Draws the line that is represented by the stored variables.",
"name": "draw",
"signature": "def draw(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051684 | Implement the Python class `Line` described below.
Class description:
Implement the Line class.
Method signatures and docstrings:
- def __init__(self, turtle, color, x, y, x1, y1): Initializes the derived shape, Line.
- def draw(self): Draws the line that is represented by the stored variables. | Implement the Python class `Line` described below.
Class description:
Implement the Line class.
Method signatures and docstrings:
- def __init__(self, turtle, color, x, y, x1, y1): Initializes the derived shape, Line.
- def draw(self): Draws the line that is represented by the stored variables.
<|skeleton|>
class Li... | ab7d24bd78719842f8790cc0e6c06dd1b327e416 | <|skeleton|>
class Line:
def __init__(self, turtle, color, x, y, x1, y1):
"""Initializes the derived shape, Line."""
<|body_0|>
def draw(self):
"""Draws the line that is represented by the stored variables."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Line:
def __init__(self, turtle, color, x, y, x1, y1):
"""Initializes the derived shape, Line."""
Shape.__init__(self, turtle, color)
self._x1 = x1
self._x = x
self._y1 = y1
self._y = y
def draw(self):
"""Draws the line that is represented by the st... | the_stack_v2_python_sparse | CS111_CS213/TreeGenerator/Lab3-Korey and Jake.py | jawaff/CollegeCS | train | 0 | |
03996e46d36097b2ad9622ffadbdd2f800de11b7 | [
"if word_vectors is None:\n word_vectors = data_directory / 'movie_reviews_word_vectors.txt'\nself.run_model = utils.get_function(model)\nself.vocab = Vectors(word_vectors, cache=os.path.dirname(word_vectors))\nself.max_filter_size = max_filter_size\nself.tokenizer = SpacyTokenizer()",
"if isinstance(sentences... | <|body_start_0|>
if word_vectors is None:
word_vectors = data_directory / 'movie_reviews_word_vectors.txt'
self.run_model = utils.get_function(model)
self.vocab = Vectors(word_vectors, cache=os.path.dirname(word_vectors))
self.max_filter_size = max_filter_size
self.to... | Creates runner for movie review model. | MovieReviewsModelRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovieReviewsModelRunner:
"""Creates runner for movie review model."""
def __init__(self, model, word_vectors=None, max_filter_size=5):
"""Initializes the class."""
<|body_0|>
def __call__(self, sentences):
"""Call Runner."""
<|body_1|>
def tokenize(s... | stack_v2_sparse_classes_75kplus_train_070662 | 2,277 | permissive | [
{
"docstring": "Initializes the class.",
"name": "__init__",
"signature": "def __init__(self, model, word_vectors=None, max_filter_size=5)"
},
{
"docstring": "Call Runner.",
"name": "__call__",
"signature": "def __call__(self, sentences)"
},
{
"docstring": "Tokenize sentence.",
... | 3 | stack_v2_sparse_classes_30k_train_037982 | Implement the Python class `MovieReviewsModelRunner` described below.
Class description:
Creates runner for movie review model.
Method signatures and docstrings:
- def __init__(self, model, word_vectors=None, max_filter_size=5): Initializes the class.
- def __call__(self, sentences): Call Runner.
- def tokenize(self,... | Implement the Python class `MovieReviewsModelRunner` described below.
Class description:
Creates runner for movie review model.
Method signatures and docstrings:
- def __init__(self, model, word_vectors=None, max_filter_size=5): Initializes the class.
- def __call__(self, sentences): Call Runner.
- def tokenize(self,... | 3284afe6aee489afecb3754aba9fad851b66e56f | <|skeleton|>
class MovieReviewsModelRunner:
"""Creates runner for movie review model."""
def __init__(self, model, word_vectors=None, max_filter_size=5):
"""Initializes the class."""
<|body_0|>
def __call__(self, sentences):
"""Call Runner."""
<|body_1|>
def tokenize(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MovieReviewsModelRunner:
"""Creates runner for movie review model."""
def __init__(self, model, word_vectors=None, max_filter_size=5):
"""Initializes the class."""
if word_vectors is None:
word_vectors = data_directory / 'movie_reviews_word_vectors.txt'
self.run_model ... | the_stack_v2_python_sparse | dianna/dashboard/_movie_model.py | dianna-ai/dianna | train | 37 |
e54e2cb30ccc3f1ae2ada5fb4a3bf2e0f33ea757 | [
"objects = FirewallObject.query.all()\nschema = FirewallObjectSchema(many=True)\nreturn schema.dump(objects)",
"json_data = request.get_json()\ntry:\n data = FirewallObjectSchema().load(json_data)\nexcept ValidationError as err:\n return ({'messages': err.messages}, 422)\nobject = FirewallObject()\nerror = ... | <|body_start_0|>
objects = FirewallObject.query.all()
schema = FirewallObjectSchema(many=True)
return schema.dump(objects)
<|end_body_0|>
<|body_start_1|>
json_data = request.get_json()
try:
data = FirewallObjectSchema().load(json_data)
except ValidationError... | FirewallObjectCollectionResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirewallObjectCollectionResource:
def get(self):
"""List firewall objects --- description: List all firewall objects tags: - Firewalls responses: 200: content: application/json: schema: type: array items: FirewallObjectSchema"""
<|body_0|>
def post(self):
"""Create f... | stack_v2_sparse_classes_75kplus_train_070663 | 2,303 | permissive | [
{
"docstring": "List firewall objects --- description: List all firewall objects tags: - Firewalls responses: 200: content: application/json: schema: type: array items: FirewallObjectSchema",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create firewall object --- description: C... | 2 | stack_v2_sparse_classes_30k_val_001850 | Implement the Python class `FirewallObjectCollectionResource` described below.
Class description:
Implement the FirewallObjectCollectionResource class.
Method signatures and docstrings:
- def get(self): List firewall objects --- description: List all firewall objects tags: - Firewalls responses: 200: content: applica... | Implement the Python class `FirewallObjectCollectionResource` described below.
Class description:
Implement the FirewallObjectCollectionResource class.
Method signatures and docstrings:
- def get(self): List firewall objects --- description: List all firewall objects tags: - Firewalls responses: 200: content: applica... | 7232975711ad01b031ed50d7f26936afcfe5312a | <|skeleton|>
class FirewallObjectCollectionResource:
def get(self):
"""List firewall objects --- description: List all firewall objects tags: - Firewalls responses: 200: content: application/json: schema: type: array items: FirewallObjectSchema"""
<|body_0|>
def post(self):
"""Create f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FirewallObjectCollectionResource:
def get(self):
"""List firewall objects --- description: List all firewall objects tags: - Firewalls responses: 200: content: application/json: schema: type: array items: FirewallObjectSchema"""
objects = FirewallObject.query.all()
schema = FirewallObj... | the_stack_v2_python_sparse | nfmanagementapi/resources/FirewallObjectCollectionResource.py | nfirewall/nfmapi | train | 0 | |
0ff40cbf2ac376f4e94e8977b6616fdf70826b82 | [
"self.n_head = n_head\nself.d_k = self.d_v = d_k = d_v = d_model // n_head\nself.dropout = dropout\nself.seed = seed\nself.qs_layers = []\nself.ks_layers = []\nself.vs_layers = []\nvs_layer = Dense(d_v, use_bias=False)\nfor _ in range(n_head):\n self.qs_layers.append(Dense(d_k, use_bias=False))\n self.ks_laye... | <|body_start_0|>
self.n_head = n_head
self.d_k = self.d_v = d_k = d_v = d_model // n_head
self.dropout = dropout
self.seed = seed
self.qs_layers = []
self.ks_layers = []
self.vs_layers = []
vs_layer = Dense(d_v, use_bias=False)
for _ in range(n_hea... | Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs_layers: List of values across heads attention: Scaled dot ... | InterpretableMultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs... | stack_v2_sparse_classes_75kplus_train_070664 | 13,910 | permissive | [
{
"docstring": "Initialises layer. Args: n_head: Number of heads d_model: TFT state dimensionality dropout: Dropout discard rate",
"name": "__init__",
"signature": "def __init__(self, n_head, d_model, dropout, seed=313, **kwargs)"
},
{
"docstring": "Applies interpretable multihead attention. Usi... | 2 | stack_v2_sparse_classes_30k_train_029109 | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ... | Implement the Python class `InterpretableMultiHeadAttention` described below.
Class description:
Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ... | ec2a4a426673b11e3589b64cef9d7160b1de28d4 | <|skeleton|>
class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterpretableMultiHeadAttention:
"""Defines interpretable multi-head attention layer. Attributes: n_head: Number of heads d_k: Key/query dimensionality per head d_v: Value dimensionality dropout: Dropout rate to apply qs_layers: List of queries across heads ks_layers: List of keys across heads vs_layers: List... | the_stack_v2_python_sparse | ai4water/models/_tensorflow/utils.py | AtrCheema/AI4Water | train | 47 |
2d3630b1020becc71eff0b291ee9a0dcf790862c | [
"self.L_layers = L_layers\nself.k_hashes_per_layer = k_hashes_per_layer\nself.feature_size = 0\nself.W_parameter = W_parameter\nself.hash_tables = []\nself.images = []\nself.data_matrix = None",
"self.dataset = dataset\nself.images = list(self.dataset.keys())\nself.data_matrix = np.asarray(list(self.dataset.value... | <|body_start_0|>
self.L_layers = L_layers
self.k_hashes_per_layer = k_hashes_per_layer
self.feature_size = 0
self.W_parameter = W_parameter
self.hash_tables = []
self.images = []
self.data_matrix = None
<|end_body_0|>
<|body_start_1|>
self.dataset = datas... | LSH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSH:
def __init__(self, L_layers, k_hashes_per_layer, W_parameter=0.5):
"""Must call build_structure with the dataset after creating current instance"""
<|body_0|>
def build_structure(self, dataset: dict):
"""- Initialization of the current instance with given datase... | stack_v2_sparse_classes_75kplus_train_070665 | 9,323 | no_license | [
{
"docstring": "Must call build_structure with the dataset after creating current instance",
"name": "__init__",
"signature": "def __init__(self, L_layers, k_hashes_per_layer, W_parameter=0.5)"
},
{
"docstring": "- Initialization of the current instance with given dataset. - Create L new hash ta... | 5 | null | Implement the Python class `LSH` described below.
Class description:
Implement the LSH class.
Method signatures and docstrings:
- def __init__(self, L_layers, k_hashes_per_layer, W_parameter=0.5): Must call build_structure with the dataset after creating current instance
- def build_structure(self, dataset: dict): - ... | Implement the Python class `LSH` described below.
Class description:
Implement the LSH class.
Method signatures and docstrings:
- def __init__(self, L_layers, k_hashes_per_layer, W_parameter=0.5): Must call build_structure with the dataset after creating current instance
- def build_structure(self, dataset: dict): - ... | 9af36c6039df4f8c3060db571e4b99cc35b6a7e0 | <|skeleton|>
class LSH:
def __init__(self, L_layers, k_hashes_per_layer, W_parameter=0.5):
"""Must call build_structure with the dataset after creating current instance"""
<|body_0|>
def build_structure(self, dataset: dict):
"""- Initialization of the current instance with given datase... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LSH:
def __init__(self, L_layers, k_hashes_per_layer, W_parameter=0.5):
"""Must call build_structure with the dataset after creating current instance"""
self.L_layers = L_layers
self.k_hashes_per_layer = k_hashes_per_layer
self.feature_size = 0
self.W_parameter = W_para... | the_stack_v2_python_sparse | Code/module/lsh.py | ktshen/cse515-project | train | 0 | |
7a55dd3ef77189945314f1ab370a88f26746ee83 | [
"connection = smtplib.SMTP(cls.host, port=cls.port)\nif cls.user is not None:\n connection.login(cls.user, cls.password)\nreturn connection",
"def reconnect():\n if cls.connection is None or cls.connection.noop()[0] == 421:\n return True\n else:\n return False\ncount = 0\nfor i in range(cls... | <|body_start_0|>
connection = smtplib.SMTP(cls.host, port=cls.port)
if cls.user is not None:
connection.login(cls.user, cls.password)
return connection
<|end_body_0|>
<|body_start_1|>
def reconnect():
if cls.connection is None or cls.connection.noop()[0] == 421:
... | SendEmail | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmail:
def _connect(cls):
"""Establish a SMTP connection"""
<|body_0|>
def connect(cls):
"""Connect or reconnect if a connection has timed out"""
<|body_1|>
def send(cls, to, email_template, email_template_args=None, from_=None, attachment_filepath=N... | stack_v2_sparse_classes_75kplus_train_070666 | 3,893 | permissive | [
{
"docstring": "Establish a SMTP connection",
"name": "_connect",
"signature": "def _connect(cls)"
},
{
"docstring": "Connect or reconnect if a connection has timed out",
"name": "connect",
"signature": "def connect(cls)"
},
{
"docstring": "Send a message Parameters ---------- to... | 3 | null | Implement the Python class `SendEmail` described below.
Class description:
Implement the SendEmail class.
Method signatures and docstrings:
- def _connect(cls): Establish a SMTP connection
- def connect(cls): Connect or reconnect if a connection has timed out
- def send(cls, to, email_template, email_template_args=No... | Implement the Python class `SendEmail` described below.
Class description:
Implement the SendEmail class.
Method signatures and docstrings:
- def _connect(cls): Establish a SMTP connection
- def connect(cls): Connect or reconnect if a connection has timed out
- def send(cls, to, email_template, email_template_args=No... | e580c3576f8cb7d657fdf7a12449cbbd81df36b7 | <|skeleton|>
class SendEmail:
def _connect(cls):
"""Establish a SMTP connection"""
<|body_0|>
def connect(cls):
"""Connect or reconnect if a connection has timed out"""
<|body_1|>
def send(cls, to, email_template, email_template_args=None, from_=None, attachment_filepath=N... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SendEmail:
def _connect(cls):
"""Establish a SMTP connection"""
connection = smtplib.SMTP(cls.host, port=cls.port)
if cls.user is not None:
connection.login(cls.user, cls.password)
return connection
def connect(cls):
"""Connect or reconnect if a connect... | the_stack_v2_python_sparse | microsetta_private_api/util/email.py | biocore/microsetta-private-api | train | 5 | |
0905a0083b6582eadfcaffd6e73f0eefda52046d | [
"logging.info('clicking MAC image to get MAC Product Page')\nself.driver.find_element(*ProductsPageLocators.MAC_PRODUCT_IMAGE).click()\nreturn ProductPage(self.driver)",
"self.driver.find_element(*ProductsPageLocators.find_product_link(product_name)).click()\nlogging.info('You went to {} product page!'.format(pro... | <|body_start_0|>
logging.info('clicking MAC image to get MAC Product Page')
self.driver.find_element(*ProductsPageLocators.MAC_PRODUCT_IMAGE).click()
return ProductPage(self.driver)
<|end_body_0|>
<|body_start_1|>
self.driver.find_element(*ProductsPageLocators.find_product_link(product_... | Products Page methods come here. | ProductsPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductsPage:
"""Products Page methods come here."""
def goto_mac_desktops(self) -> 'ProductPage':
"""Make webdriver click MAC desktop. :return: Product MAC Page Object."""
<|body_0|>
def goto_product_page(self, product_name: str) -> 'ProductPage':
"""Click on se... | stack_v2_sparse_classes_75kplus_train_070667 | 1,124 | no_license | [
{
"docstring": "Make webdriver click MAC desktop. :return: Product MAC Page Object.",
"name": "goto_mac_desktops",
"signature": "def goto_mac_desktops(self) -> 'ProductPage'"
},
{
"docstring": "Click on selected product link. :param product_name: Name of product you want to add :return: ProductP... | 2 | stack_v2_sparse_classes_30k_test_000601 | Implement the Python class `ProductsPage` described below.
Class description:
Products Page methods come here.
Method signatures and docstrings:
- def goto_mac_desktops(self) -> 'ProductPage': Make webdriver click MAC desktop. :return: Product MAC Page Object.
- def goto_product_page(self, product_name: str) -> 'Prod... | Implement the Python class `ProductsPage` described below.
Class description:
Products Page methods come here.
Method signatures and docstrings:
- def goto_mac_desktops(self) -> 'ProductPage': Make webdriver click MAC desktop. :return: Product MAC Page Object.
- def goto_product_page(self, product_name: str) -> 'Prod... | 6bb7214c6362aa27ddd4d3ece65e7e0fc3c46d93 | <|skeleton|>
class ProductsPage:
"""Products Page methods come here."""
def goto_mac_desktops(self) -> 'ProductPage':
"""Make webdriver click MAC desktop. :return: Product MAC Page Object."""
<|body_0|>
def goto_product_page(self, product_name: str) -> 'ProductPage':
"""Click on se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductsPage:
"""Products Page methods come here."""
def goto_mac_desktops(self) -> 'ProductPage':
"""Make webdriver click MAC desktop. :return: Product MAC Page Object."""
logging.info('clicking MAC image to get MAC Product Page')
self.driver.find_element(*ProductsPageLocators.MA... | the_stack_v2_python_sparse | pages/products.py | Lv296TAQC/OpenCart_TA | train | 0 |
9ed37e96f9a4e4c1d78d3805e440779da1f9e17c | [
"payload, user = self.get_payload(request)\nif not payload:\n return Response(status=status.HTTP_401_UNAUTHORIZED)\nif user.profile != 'admin':\n return Response(status=status.HTTP_403_FORBIDDEN)\nvalidator = Validator({'reservation': {'required': True, 'type': 'integer'}, 'price': {'required': True, 'type': ... | <|body_start_0|>
payload, user = self.get_payload(request)
if not payload:
return Response(status=status.HTTP_401_UNAUTHORIZED)
if user.profile != 'admin':
return Response(status=status.HTTP_403_FORBIDDEN)
validator = Validator({'reservation': {'required': True, '... | Defines the HTTP verbs to payment model management. | PaymentApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaymentApi:
"""Defines the HTTP verbs to payment model management."""
def post(self, request):
"""Create a payment. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_070668 | 4,096 | permissive | [
{
"docstring": "Create a payment. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "retrieve a payment, but in plural lmao. Pa... | 2 | stack_v2_sparse_classes_30k_train_051495 | Implement the Python class `PaymentApi` described below.
Class description:
Defines the HTTP verbs to payment model management.
Method signatures and docstrings:
- def post(self, request): Create a payment. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int... | Implement the Python class `PaymentApi` described below.
Class description:
Defines the HTTP verbs to payment model management.
Method signatures and docstrings:
- def post(self, request): Create a payment. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int... | d56d365dd840ecd272ce933c26f2d408e01c44c7 | <|skeleton|>
class PaymentApi:
"""Defines the HTTP verbs to payment model management."""
def post(self, request):
"""Create a payment. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PaymentApi:
"""Defines the HTTP verbs to payment model management."""
def post(self, request):
"""Create a payment. Parameters ---------- request (dict) Contains http transaction information. Returns ------- Response (JSON, int) Body response and status code."""
payload, user = self.get_p... | the_stack_v2_python_sparse | api/views/payment.py | santiagoSSAA/ParkingLot_Back | train | 0 |
36609279cce4904b105e5587adb4f7422cadeaf8 | [
"super().__init__()\nself.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])\nlayer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])\nself.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])\nself.output = nn.Linear(hidden_layers[-1], output_size)\nself.dropout = nn.Dropout(p... | <|body_start_0|>
super().__init__()
self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])
layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])
self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])
self.output = nn.Linear(hidden_layer... | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input layer output_size: integer, size of the output layer hidden_layers: list of integers, ... | stack_v2_sparse_classes_75kplus_train_070669 | 5,507 | no_license | [
{
"docstring": "Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input layer output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hidden layers",
"name": "__init__",
"signature": "def __init__(self... | 2 | stack_v2_sparse_classes_30k_train_006621 | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of ... | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of ... | 3e7e33b94e5eb3e4a8fba866132bcce9635b44f0 | <|skeleton|>
class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input layer output_size: integer, size of the output layer hidden_layers: list of integers, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input layer output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of t... | the_stack_v2_python_sparse | Intro_Pytorch_Lecture/codes/18_load_cat_dog_data.py | pelinbalci/Intro_Deep_Learning | train | 1 | |
aaab82149b0f00287a29b9afb8cda85599dcd5df | [
"mock_input = MockInputApi()\nmock_input.files = [MockFile('path/One.java', ['new Notification.Builder()']), MockFile('path/Two.java', ['new NotificationCompat.Builder()'])]\nerrors = PRESUBMIT._CheckNotificationConstructors(mock_input, MockOutputApi())\nself.assertEqual(1, len(errors))\nself.assertEqual(2, len(err... | <|body_start_0|>
mock_input = MockInputApi()
mock_input.files = [MockFile('path/One.java', ['new Notification.Builder()']), MockFile('path/Two.java', ['new NotificationCompat.Builder()'])]
errors = PRESUBMIT._CheckNotificationConstructors(mock_input, MockOutputApi())
self.assertEqual(1, ... | Test the _CheckNotificationConstructors presubmit check. | CheckNotificationConstructors | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckNotificationConstructors:
"""Test the _CheckNotificationConstructors presubmit check."""
def testTruePositives(self):
"""Examples of when Notification.Builder use is correctly flagged."""
<|body_0|>
def testFalsePositives(self):
"""Examples of when Notificat... | stack_v2_sparse_classes_75kplus_train_070670 | 4,016 | permissive | [
{
"docstring": "Examples of when Notification.Builder use is correctly flagged.",
"name": "testTruePositives",
"signature": "def testTruePositives(self)"
},
{
"docstring": "Examples of when Notification.Builder should not be flagged.",
"name": "testFalsePositives",
"signature": "def test... | 2 | stack_v2_sparse_classes_30k_train_020079 | Implement the Python class `CheckNotificationConstructors` described below.
Class description:
Test the _CheckNotificationConstructors presubmit check.
Method signatures and docstrings:
- def testTruePositives(self): Examples of when Notification.Builder use is correctly flagged.
- def testFalsePositives(self): Examp... | Implement the Python class `CheckNotificationConstructors` described below.
Class description:
Test the _CheckNotificationConstructors presubmit check.
Method signatures and docstrings:
- def testTruePositives(self): Examples of when Notification.Builder use is correctly flagged.
- def testFalsePositives(self): Examp... | d92465f71fb8e4345e27bd889532339204b26f1e | <|skeleton|>
class CheckNotificationConstructors:
"""Test the _CheckNotificationConstructors presubmit check."""
def testTruePositives(self):
"""Examples of when Notification.Builder use is correctly flagged."""
<|body_0|>
def testFalsePositives(self):
"""Examples of when Notificat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CheckNotificationConstructors:
"""Test the _CheckNotificationConstructors presubmit check."""
def testTruePositives(self):
"""Examples of when Notification.Builder use is correctly flagged."""
mock_input = MockInputApi()
mock_input.files = [MockFile('path/One.java', ['new Notifica... | the_stack_v2_python_sparse | chromium/chrome/android/java/src/PRESUBMIT_test.py | Csineneo/Vivaldi | train | 5 |
c042f42d783c5e61ec6d6e7ae7f488a725e2ae6f | [
"self.carrier_direct_port = carrier_direct_port\nself.http_direct_port = http_direct_port\nself.requires_ssl = requires_ssl\nself.seeds = seeds",
"if dictionary is None:\n return None\ncarrier_direct_port = dictionary.get('carrierDirectPort')\nhttp_direct_port = dictionary.get('httpDirectPort')\nrequires_ssl =... | <|body_start_0|>
self.carrier_direct_port = carrier_direct_port
self.http_direct_port = http_direct_port
self.requires_ssl = requires_ssl
self.seeds = seeds
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
carrier_direct_port = dictionary.ge... | Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port. requires_ssl (bool): Specifies whether this clus... | CouchbaseConnectParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouchbaseConnectParams:
"""Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port... | stack_v2_sparse_classes_75kplus_train_070671 | 2,287 | permissive | [
{
"docstring": "Constructor for the CouchbaseConnectParams class",
"name": "__init__",
"signature": "def __init__(self, carrier_direct_port=None, http_direct_port=None, requires_ssl=None, seeds=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | stack_v2_sparse_classes_30k_train_028940 | Implement the Python class `CouchbaseConnectParams` described below.
Class description:
Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (i... | Implement the Python class `CouchbaseConnectParams` described below.
Class description:
Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (i... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class CouchbaseConnectParams:
"""Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CouchbaseConnectParams:
"""Implementation of the 'CouchbaseConnectParams' model. Specifies an Object containing information about a registered couchbase source. Attributes: carrier_direct_port (int): Specifies the Carrier direct/sll port. http_direct_port (int): Specifies the HTTP direct/sll port. requires_ss... | the_stack_v2_python_sparse | cohesity_management_sdk/models/couchbase_connect_params.py | cohesity/management-sdk-python | train | 24 |
8e627f6a98b682f3548a107d7e810e776bab6680 | [
"self.id = id\nself.status = status\nself.completed_time = completed_time\nself.url = url",
"if dictionary is None:\n return None\nid = dictionary.get('id')\nstatus = dictionary.get('status')\ncompleted_time = dictionary.get('completedTime')\nurl = dictionary.get('url')\nreturn cls(id, status, completed_time, ... | <|body_start_0|>
self.id = id
self.status = status
self.completed_time = completed_time
self.url = url
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
id = dictionary.get('id')
status = dictionary.get('status')
completed_tim... | Implementation of the 'TranscriptionMetadata' model. TODO: type model description here. Attributes: id (string): TODO: type description here. status (string): The current status of the transcription. Current values are 'none', 'processing', 'available', 'error', 'timeout', 'file-size-too-big', and 'file-size-too-small'... | TranscriptionMetadata | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TranscriptionMetadata:
"""Implementation of the 'TranscriptionMetadata' model. TODO: type model description here. Attributes: id (string): TODO: type description here. status (string): The current status of the transcription. Current values are 'none', 'processing', 'available', 'error', 'timeout... | stack_v2_sparse_classes_75kplus_train_070672 | 2,346 | permissive | [
{
"docstring": "Constructor for the TranscriptionMetadata class",
"name": "__init__",
"signature": "def __init__(self, id=None, status=None, completed_time=None, url=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary represen... | 2 | null | Implement the Python class `TranscriptionMetadata` described below.
Class description:
Implementation of the 'TranscriptionMetadata' model. TODO: type model description here. Attributes: id (string): TODO: type description here. status (string): The current status of the transcription. Current values are 'none', 'proc... | Implement the Python class `TranscriptionMetadata` described below.
Class description:
Implementation of the 'TranscriptionMetadata' model. TODO: type model description here. Attributes: id (string): TODO: type description here. status (string): The current status of the transcription. Current values are 'none', 'proc... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class TranscriptionMetadata:
"""Implementation of the 'TranscriptionMetadata' model. TODO: type model description here. Attributes: id (string): TODO: type description here. status (string): The current status of the transcription. Current values are 'none', 'processing', 'available', 'error', 'timeout... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TranscriptionMetadata:
"""Implementation of the 'TranscriptionMetadata' model. TODO: type model description here. Attributes: id (string): TODO: type description here. status (string): The current status of the transcription. Current values are 'none', 'processing', 'available', 'error', 'timeout', 'file-size... | the_stack_v2_python_sparse | bandwidth/voice/models/transcription_metadata.py | Bandwidth/python-sdk | train | 10 |
0b7c1249c998eb7f46d58860bee250a179e6acb4 | [
"self.args = args\nself.nights_dict = None\nself.instrument = None\nself.image_collection = None\nself.objects_collection = None\nself.technique = None",
"self.nights_dict = {}\nlog.debug('Raw path: ' + self.args.raw_path)\nself.get_instrument(self.args.raw_path)\nlog.info('Instrument: ' + self.instrument + ' Cam... | <|body_start_0|>
self.args = args
self.nights_dict = None
self.instrument = None
self.image_collection = None
self.objects_collection = None
self.technique = None
<|end_body_0|>
<|body_start_1|>
self.nights_dict = {}
log.debug('Raw path: ' + self.args.raw... | Class Definition Data classifier is intended to define the camera that is being used and the technique in use. This will be used later to make important decisions regarding the process to be used. | DataClassifier | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataClassifier:
"""Class Definition Data classifier is intended to define the camera that is being used and the technique in use. This will be used later to make important decisions regarding the process to be used."""
def __init__(self, args):
"""Initialization method for the DataCl... | stack_v2_sparse_classes_75kplus_train_070673 | 6,469 | permissive | [
{
"docstring": "Initialization method for the DataClassifier class The general arguments of the program are parsed and become part of the class attributes. The rest of attributes are initialized as None. Args: args (object): Argparse object",
"name": "__init__",
"signature": "def __init__(self, args)"
... | 4 | stack_v2_sparse_classes_30k_train_042838 | Implement the Python class `DataClassifier` described below.
Class description:
Class Definition Data classifier is intended to define the camera that is being used and the technique in use. This will be used later to make important decisions regarding the process to be used.
Method signatures and docstrings:
- def _... | Implement the Python class `DataClassifier` described below.
Class description:
Class Definition Data classifier is intended to define the camera that is being used and the technique in use. This will be used later to make important decisions regarding the process to be used.
Method signatures and docstrings:
- def _... | 167dcbd1bd66d938103964d725b92f2e3cc3a281 | <|skeleton|>
class DataClassifier:
"""Class Definition Data classifier is intended to define the camera that is being used and the technique in use. This will be used later to make important decisions regarding the process to be used."""
def __init__(self, args):
"""Initialization method for the DataCl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataClassifier:
"""Class Definition Data classifier is intended to define the camera that is being used and the technique in use. This will be used later to make important decisions regarding the process to be used."""
def __init__(self, args):
"""Initialization method for the DataClassifier clas... | the_stack_v2_python_sparse | goodman_ccd/data_classifier.py | wschoenell/goodman | train | 0 |
8ff439ea58283a670d4946e8c36332923a914901 | [
"self.mockInit = MagicMock()\nexpected = {'product_code': '23', 'description': 'toaster', 'market_price': 49.99, 'rental_price': 37.95, 'material': 'Velvet', 'size': 'xl'}\n_ = self.mockInit(*expected.values())\nself.mockInit.assert_called_with(*expected.values())\nself.mockInit.assert_called_with('23', 'toaster', ... | <|body_start_0|>
self.mockInit = MagicMock()
expected = {'product_code': '23', 'description': 'toaster', 'market_price': 49.99, 'rental_price': 37.95, 'material': 'Velvet', 'size': 'xl'}
_ = self.mockInit(*expected.values())
self.mockInit.assert_called_with(*expected.values())
se... | TestFurnitureClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFurnitureClass:
def test_Furniture_init(self):
"""Mock test that a furniture.__init__ is called with the correct parameters"""
<|body_0|>
def test_Furniture_return(self):
"""Test that a inventory object is created"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_070674 | 8,711 | no_license | [
{
"docstring": "Mock test that a furniture.__init__ is called with the correct parameters",
"name": "test_Furniture_init",
"signature": "def test_Furniture_init(self)"
},
{
"docstring": "Test that a inventory object is created",
"name": "test_Furniture_return",
"signature": "def test_Fur... | 2 | stack_v2_sparse_classes_30k_train_019605 | Implement the Python class `TestFurnitureClass` described below.
Class description:
Implement the TestFurnitureClass class.
Method signatures and docstrings:
- def test_Furniture_init(self): Mock test that a furniture.__init__ is called with the correct parameters
- def test_Furniture_return(self): Test that a invent... | Implement the Python class `TestFurnitureClass` described below.
Class description:
Implement the TestFurnitureClass class.
Method signatures and docstrings:
- def test_Furniture_init(self): Mock test that a furniture.__init__ is called with the correct parameters
- def test_Furniture_return(self): Test that a invent... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestFurnitureClass:
def test_Furniture_init(self):
"""Mock test that a furniture.__init__ is called with the correct parameters"""
<|body_0|>
def test_Furniture_return(self):
"""Test that a inventory object is created"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestFurnitureClass:
def test_Furniture_init(self):
"""Mock test that a furniture.__init__ is called with the correct parameters"""
self.mockInit = MagicMock()
expected = {'product_code': '23', 'description': 'toaster', 'market_price': 49.99, 'rental_price': 37.95, 'material': 'Velvet',... | the_stack_v2_python_sparse | students/erica_edwards/lesson01/assignment/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 | |
f1fa07cddae915f983c12d45c68b2710eeba8510 | [
"def inner(func):\n assert inspect.getfullargspec(func).args[:2] == ['self', 'predictions']\n func.metric_name = name\n return func\nreturn inner",
"klass = super().__new__(meta, name, bases, class_dict)\ni = 0\nfor key in class_dict:\n value = class_dict[key]\n if isinstance(value, Callable) and h... | <|body_start_0|>
def inner(func):
assert inspect.getfullargspec(func).args[:2] == ['self', 'predictions']
func.metric_name = name
return func
return inner
<|end_body_0|>
<|body_start_1|>
klass = super().__new__(meta, name, bases, class_dict)
i = 0
... | Metrics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Metrics:
def register(name: str=None):
"""Decorator function to register a metric name value to a input function"""
<|body_0|>
def __new__(meta, name, bases, class_dict):
"""Metaclass instantiation to put all functions registered as metrics into a instance dictionary... | stack_v2_sparse_classes_75kplus_train_070675 | 12,254 | permissive | [
{
"docstring": "Decorator function to register a metric name value to a input function",
"name": "register",
"signature": "def register(name: str=None)"
},
{
"docstring": "Metaclass instantiation to put all functions registered as metrics into a instance dictionary variable `metrics`",
"name... | 2 | null | Implement the Python class `Metrics` described below.
Class description:
Implement the Metrics class.
Method signatures and docstrings:
- def register(name: str=None): Decorator function to register a metric name value to a input function
- def __new__(meta, name, bases, class_dict): Metaclass instantiation to put al... | Implement the Python class `Metrics` described below.
Class description:
Implement the Metrics class.
Method signatures and docstrings:
- def register(name: str=None): Decorator function to register a metric name value to a input function
- def __new__(meta, name, bases, class_dict): Metaclass instantiation to put al... | d6e9bf81204a01545a3edb165c5724eb24f37c18 | <|skeleton|>
class Metrics:
def register(name: str=None):
"""Decorator function to register a metric name value to a input function"""
<|body_0|>
def __new__(meta, name, bases, class_dict):
"""Metaclass instantiation to put all functions registered as metrics into a instance dictionary... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Metrics:
def register(name: str=None):
"""Decorator function to register a metric name value to a input function"""
def inner(func):
assert inspect.getfullargspec(func).args[:2] == ['self', 'predictions']
func.metric_name = name
return func
return in... | the_stack_v2_python_sparse | python_data_utils/spark/ml/base.py | rpkuppala/python-data-utils | train | 0 | |
1dbea07d24a3dd4cd802ad9c72a117c351f0eb12 | [
"self.template_path = template_path\nfrom qmxgraph.configuration import GraphStyles\nfrom qmxgraph.configuration import GraphOptions\nif options is None:\n options = GraphOptions()\nif styles is None:\n styles = GraphStyles()\nself.options = options\nself.styles = styles\nself.stencils = stencils",
"from qm... | <|body_start_0|>
self.template_path = template_path
from qmxgraph.configuration import GraphStyles
from qmxgraph.configuration import GraphOptions
if options is None:
options = GraphOptions()
if styles is None:
styles = GraphStyles()
self.options =... | A simple page showing a graph drawing widget using mxGraph as its backend. | GraphPage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphPage:
"""A simple page showing a graph drawing widget using mxGraph as its backend."""
def __init__(self, template_path, options=None, styles=None, stencils=tuple()):
""":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options o... | stack_v2_sparse_classes_75kplus_train_070676 | 7,800 | permissive | [
{
"docstring": ":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options of graph drawing widget, uses default if not given. :param GraphStyles styles: Styles available in graph drawing widget, uses default if not given. :param iterable[str] stencils: Stencils ... | 2 | stack_v2_sparse_classes_30k_train_005397 | Implement the Python class `GraphPage` described below.
Class description:
A simple page showing a graph drawing widget using mxGraph as its backend.
Method signatures and docstrings:
- def __init__(self, template_path, options=None, styles=None, stencils=tuple()): :param str template_path: Path where graph HTML temp... | Implement the Python class `GraphPage` described below.
Class description:
A simple page showing a graph drawing widget using mxGraph as its backend.
Method signatures and docstrings:
- def __init__(self, template_path, options=None, styles=None, stencils=tuple()): :param str template_path: Path where graph HTML temp... | e5dcf6294bd06ed08e61be5ac18a5aaa13613923 | <|skeleton|>
class GraphPage:
"""A simple page showing a graph drawing widget using mxGraph as its backend."""
def __init__(self, template_path, options=None, styles=None, stencils=tuple()):
""":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphPage:
"""A simple page showing a graph drawing widget using mxGraph as its backend."""
def __init__(self, template_path, options=None, styles=None, stencils=tuple()):
""":param str template_path: Path where graph HTML templates are located. :param GraphOptions options: Options of graph drawi... | the_stack_v2_python_sparse | src/qmxgraph/server.py | ESSS/qmxgraph | train | 27 |
f9fc0e7a1409420dda7a43256546132fb9c72db4 | [
"if not nums:\n self.sums = None\nelse:\n size = len(nums)\n self.sums = [0] * (size + 1)\n for i in range(size):\n self.sums[i + 1] = self.sums[i] + nums[i]",
"if not self.sums:\n return None\nreturn self.sums[j + 1] - self.sums[i]"
] | <|body_start_0|>
if not nums:
self.sums = None
else:
size = len(nums)
self.sums = [0] * (size + 1)
for i in range(size):
self.sums[i + 1] = self.sums[i] + nums[i]
<|end_body_0|>
<|body_start_1|>
if not self.sums:
return... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_070677 | 1,676 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, ... | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | 6355113b51067e2a730285e8a80acdb49bc57e43 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
if not nums:
self.sums = None
else:
size = len(nums)
self.sums = [0] * (size + 1)
for i in range(size):
self.sums[i + 1] ... | the_stack_v2_python_sparse | Algorithms/range_sum_query_immutable.py | xxiang13/leetcode | train | 2 | |
9b79995109b8357e190639140342e3a94ec5b2de | [
"self.mod_dir = mod_dir\nconfig_dir = os.path.join(mod_dir, constant.VSCODE_CONFIG_DIR)\nif not os.path.isdir(config_dir):\n os.mkdir(config_dir)\nself.config_dir = config_dir",
"native_mod_info = native_module_info.NativeModuleInfo()\nroot_dir = common_util.get_android_root_dir()\nmod_names = native_mod_info.... | <|body_start_0|>
self.mod_dir = mod_dir
config_dir = os.path.join(mod_dir, constant.VSCODE_CONFIG_DIR)
if not os.path.isdir(config_dir):
os.mkdir(config_dir)
self.config_dir = config_dir
<|end_body_0|>
<|body_start_1|>
native_mod_info = native_module_info.NativeModul... | VSCode native project file generator. Attributes: mod_dir: A string of native project path. config_dir: A string of native project's configuration path. | VSCodeNativeProjectFileGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VSCodeNativeProjectFileGenerator:
"""VSCode native project file generator. Attributes: mod_dir: A string of native project path. config_dir: A string of native project's configuration path."""
def __init__(self, mod_dir):
"""VSCodeNativeProjectFileGenerator initialize. Args: mod_dir:... | stack_v2_sparse_classes_75kplus_train_070678 | 5,145 | no_license | [
{
"docstring": "VSCodeNativeProjectFileGenerator initialize. Args: mod_dir: An absolute path of native project directory.",
"name": "__init__",
"signature": "def __init__(self, mod_dir)"
},
{
"docstring": "Generates c_cpp_properties.json file for VSCode project.",
"name": "generate_c_cpp_pro... | 3 | stack_v2_sparse_classes_30k_train_039948 | Implement the Python class `VSCodeNativeProjectFileGenerator` described below.
Class description:
VSCode native project file generator. Attributes: mod_dir: A string of native project path. config_dir: A string of native project's configuration path.
Method signatures and docstrings:
- def __init__(self, mod_dir): VS... | Implement the Python class `VSCodeNativeProjectFileGenerator` described below.
Class description:
VSCode native project file generator. Attributes: mod_dir: A string of native project path. config_dir: A string of native project's configuration path.
Method signatures and docstrings:
- def __init__(self, mod_dir): VS... | 78a61ca023cbf1a0cecfef8b97df2b274ac3a988 | <|skeleton|>
class VSCodeNativeProjectFileGenerator:
"""VSCode native project file generator. Attributes: mod_dir: A string of native project path. config_dir: A string of native project's configuration path."""
def __init__(self, mod_dir):
"""VSCodeNativeProjectFileGenerator initialize. Args: mod_dir:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VSCodeNativeProjectFileGenerator:
"""VSCode native project file generator. Attributes: mod_dir: A string of native project path. config_dir: A string of native project's configuration path."""
def __init__(self, mod_dir):
"""VSCodeNativeProjectFileGenerator initialize. Args: mod_dir: An absolute ... | the_stack_v2_python_sparse | tools/asuite/aidegen/vscode/vscode_native_project_file_gen.py | ZYHGOD-1/Aosp11 | train | 0 |
4b2eac6f553af3085ab970dad457b97b7cf495e4 | [
"self.include_extras = None\nself.include_all_extras = None\nself.extra_pkgs = []",
"include_extras = self.include_extras.split(',')\ntry:\n for name, pkgs in self.distribution.extras_require.items():\n if self.include_all_extras or name in include_extras:\n self.extra_pkgs.extend(pkgs)\nexce... | <|body_start_0|>
self.include_extras = None
self.include_all_extras = None
self.extra_pkgs = []
<|end_body_0|>
<|body_start_1|>
include_extras = self.include_extras.split(',')
try:
for name, pkgs in self.distribution.extras_require.items():
if self.in... | A custom command to list the dependencies of the current. | GenerateRequirementFile | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateRequirementFile:
"""A custom command to list the dependencies of the current."""
def initialize_options(self):
"""Initialize this command's options."""
<|body_0|>
def finalize_options(self):
"""Finalize this command's options."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus_train_070679 | 23,915 | permissive | [
{
"docstring": "Initialize this command's options.",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Finalize this command's options.",
"name": "finalize_options",
"signature": "def finalize_options(self)"
},
{
"docstring": "Execute th... | 3 | stack_v2_sparse_classes_30k_train_007094 | Implement the Python class `GenerateRequirementFile` described below.
Class description:
A custom command to list the dependencies of the current.
Method signatures and docstrings:
- def initialize_options(self): Initialize this command's options.
- def finalize_options(self): Finalize this command's options.
- def r... | Implement the Python class `GenerateRequirementFile` described below.
Class description:
A custom command to list the dependencies of the current.
Method signatures and docstrings:
- def initialize_options(self): Initialize this command's options.
- def finalize_options(self): Finalize this command's options.
- def r... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class GenerateRequirementFile:
"""A custom command to list the dependencies of the current."""
def initialize_options(self):
"""Initialize this command's options."""
<|body_0|>
def finalize_options(self):
"""Finalize this command's options."""
<|body_1|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenerateRequirementFile:
"""A custom command to list the dependencies of the current."""
def initialize_options(self):
"""Initialize this command's options."""
self.include_extras = None
self.include_all_extras = None
self.extra_pkgs = []
def finalize_options(self):
... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/original_commits/ProjectQ/ProjectQ#408/after/setup.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('name')\nself.parser.add_argument('token')\nsuper(CtaStrategyInit, self).__init__()",
"args = self.parser.parse_args()\ntoken = args['token']\nname = 'strategyHedge_syt'\nengine = me.getApp('CtaStrategy')\nif not name:\n engine.initAll()\nelse:\... | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyInit, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
token = args['token']
name = 'strate... | 初始化策略 | CtaStrategyInit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_a... | stack_v2_sparse_classes_75kplus_train_070680 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "订阅",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050133 | Implement the Python class `CtaStrategyInit` described below.
Class description:
初始化策略
Method signatures and docstrings:
- def __init__(self): 初始化
- def post(self): 订阅 | Implement the Python class `CtaStrategyInit` described below.
Class description:
初始化策略
Method signatures and docstrings:
- def __init__(self): 初始化
- def post(self): 订阅
<|skeleton|>
class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyInit, self).__init__()
def post(self):
"""订阅"""
args = self.pa... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
8df2789715d75225492abf20fdc7ff074be9aab4 | [
"super(ConstantGuessModel, self).__init__(**kwargs)\nself.model = sklearn_models.ConstantGuess(**kwargs)\nself.regression = regression",
"labels = train_dataset.get_labels()\nif self.regression:\n ec_nums = train_dataset.get_ec_nums()\n labels = train_dataset.get_labels()\n freq_dict = defaultdict(lambda... | <|body_start_0|>
super(ConstantGuessModel, self).__init__(**kwargs)
self.model = sklearn_models.ConstantGuess(**kwargs)
self.regression = regression
<|end_body_0|>
<|body_start_1|>
labels = train_dataset.get_labels()
if self.regression:
ec_nums = train_dataset.get_ec... | ConstantGuessModel. | ConstantGuessModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstantGuessModel:
"""ConstantGuessModel."""
def __init__(self, regression: bool, **kwargs):
"""__init__. Args: regression (bool): If true, guess based on EC averages for each value kwargs: kwargs"""
<|body_0|>
def train(self, train_dataset: TorchDataset, val_dataset: T... | stack_v2_sparse_classes_75kplus_train_070681 | 37,814 | no_license | [
{
"docstring": "__init__. Args: regression (bool): If true, guess based on EC averages for each value kwargs: kwargs",
"name": "__init__",
"signature": "def __init__(self, regression: bool, **kwargs)"
},
{
"docstring": "fit. Fit the model on the torch datasets Args: train_dataset (TorchDataset):... | 3 | null | Implement the Python class `ConstantGuessModel` described below.
Class description:
ConstantGuessModel.
Method signatures and docstrings:
- def __init__(self, regression: bool, **kwargs): __init__. Args: regression (bool): If true, guess based on EC averages for each value kwargs: kwargs
- def train(self, train_datas... | Implement the Python class `ConstantGuessModel` described below.
Class description:
ConstantGuessModel.
Method signatures and docstrings:
- def __init__(self, regression: bool, **kwargs): __init__. Args: regression (bool): If true, guess based on EC averages for each value kwargs: kwargs
- def train(self, train_datas... | 84c9026c78bec9a2267960a87080b71beba5c305 | <|skeleton|>
class ConstantGuessModel:
"""ConstantGuessModel."""
def __init__(self, regression: bool, **kwargs):
"""__init__. Args: regression (bool): If true, guess based on EC averages for each value kwargs: kwargs"""
<|body_0|>
def train(self, train_dataset: TorchDataset, val_dataset: T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConstantGuessModel:
"""ConstantGuessModel."""
def __init__(self, regression: bool, **kwargs):
"""__init__. Args: regression (bool): If true, guess based on EC averages for each value kwargs: kwargs"""
super(ConstantGuessModel, self).__init__(**kwargs)
self.model = sklearn_models.C... | the_stack_v2_python_sparse | enzpred/models/dense_models.py | liudongliangHI/enz-pred | train | 0 |
3d0f4d69c6646b6c39e6b9c4300419777c35b64b | [
"super().__init__(convert_charrefs=True)\nself.url = urlparse(url)\nself.generator = None\nself.version = None\nself._parsed_url = None\nself.server = None\nself.scriptpath = None",
"if self.version and value < self.version:\n return\nself.version = value",
"url = url.split('.php', 1)[0]\ntry:\n value, sc... | <|body_start_0|>
super().__init__(convert_charrefs=True)
self.url = urlparse(url)
self.generator = None
self.version = None
self._parsed_url = None
self.server = None
self.scriptpath = None
<|end_body_0|>
<|body_start_1|>
if self.version and value < self.... | Wiki HTML page parser. | WikiHTMLPageParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiHTMLPageParser:
"""Wiki HTML page parser."""
def __init__(self, url) -> None:
"""Initializer."""
<|body_0|>
def set_version(self, value) -> None:
"""Set highest version."""
<|body_1|>
def set_api_url(self, url) -> None:
"""Set api_url."""... | stack_v2_sparse_classes_75kplus_train_070682 | 10,845 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, url) -> None"
},
{
"docstring": "Set highest version.",
"name": "set_version",
"signature": "def set_version(self, value) -> None"
},
{
"docstring": "Set api_url.",
"name": "set_api_url",
... | 4 | stack_v2_sparse_classes_30k_train_029716 | Implement the Python class `WikiHTMLPageParser` described below.
Class description:
Wiki HTML page parser.
Method signatures and docstrings:
- def __init__(self, url) -> None: Initializer.
- def set_version(self, value) -> None: Set highest version.
- def set_api_url(self, url) -> None: Set api_url.
- def handle_star... | Implement the Python class `WikiHTMLPageParser` described below.
Class description:
Wiki HTML page parser.
Method signatures and docstrings:
- def __init__(self, url) -> None: Initializer.
- def set_version(self, value) -> None: Set highest version.
- def set_api_url(self, url) -> None: Set api_url.
- def handle_star... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class WikiHTMLPageParser:
"""Wiki HTML page parser."""
def __init__(self, url) -> None:
"""Initializer."""
<|body_0|>
def set_version(self, value) -> None:
"""Set highest version."""
<|body_1|>
def set_api_url(self, url) -> None:
"""Set api_url."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WikiHTMLPageParser:
"""Wiki HTML page parser."""
def __init__(self, url) -> None:
"""Initializer."""
super().__init__(convert_charrefs=True)
self.url = urlparse(url)
self.generator = None
self.version = None
self._parsed_url = None
self.server = Non... | the_stack_v2_python_sparse | pywikibot/site_detect.py | wikimedia/pywikibot | train | 432 |
ae12dc5b76fb51e151aa3e6542bb5d920cc689e1 | [
"graph = dict(enumerate(graph))\nmemo = [[] for _ in range(len(graph))]\n\ndef paths(s, e):\n if s == e:\n return [[e]]\n if memo[s]:\n return memo[s]\n ret = []\n for n in graph[s]:\n ret.extend(([s] + p for p in paths(n, e)))\n memo[s] = ret\n return ret\nreturn paths(0, len... | <|body_start_0|>
graph = dict(enumerate(graph))
memo = [[] for _ in range(len(graph))]
def paths(s, e):
if s == e:
return [[e]]
if memo[s]:
return memo[s]
ret = []
for n in graph[s]:
ret.extend(([s] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""09/17/2020 22:46"""
<|body_0|>
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""Dec 09, 2021 10:57"""
<|body_1|>
def allPathsSourceTarget... | stack_v2_sparse_classes_75kplus_train_070683 | 2,892 | no_license | [
{
"docstring": "09/17/2020 22:46",
"name": "allPathsSourceTarget",
"signature": "def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]"
},
{
"docstring": "Dec 09, 2021 10:57",
"name": "allPathsSourceTarget",
"signature": "def allPathsSourceTarget(self, graph: List[Lis... | 3 | stack_v2_sparse_classes_30k_train_015799 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 09/17/2020 22:46
- def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: Dec 09, 2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 09/17/2020 22:46
- def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: Dec 09, 2... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""09/17/2020 22:46"""
<|body_0|>
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""Dec 09, 2021 10:57"""
<|body_1|>
def allPathsSourceTarget... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
"""09/17/2020 22:46"""
graph = dict(enumerate(graph))
memo = [[] for _ in range(len(graph))]
def paths(s, e):
if s == e:
return [[e]]
if memo[s]:
... | the_stack_v2_python_sparse | leetcode/solved/813_All_Paths_From_Source_to_Target/solution.py | sungminoh/algorithms | train | 0 | |
abf3673ccd30f6bcf34f1a578f558857f3a93c3a | [
"self.submodels = submodels\nself.obstypes = [obstype for submodel in submodels for obstype in submodel.obstypes]\ngauges = list()\nfor submodel in submodels:\n gauges.extend((gauge for gauge in submodel.gauges if gauge not in gauges))\nsuper().__init__(gauges)",
"model_output = list()\nfor submodel in submode... | <|body_start_0|>
self.submodels = submodels
self.obstypes = [obstype for submodel in submodels for obstype in submodel.obstypes]
gauges = list()
for submodel in submodels:
gauges.extend((gauge for gauge in submodel.gauges if gauge not in gauges))
super().__init__(gaug... | CompositeForwardModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompositeForwardModel:
def __init__(self, submodels):
"""Extracts all the gauge objects found within each element of the submodels lists and pases those gauges into the constructor of the parent class. Parameters ---------- submodels : (list) of ForwardModel objects A list of GeoClawForw... | stack_v2_sparse_classes_75kplus_train_070684 | 17,205 | no_license | [
{
"docstring": "Extracts all the gauge objects found within each element of the submodels lists and pases those gauges into the constructor of the parent class. Parameters ---------- submodels : (list) of ForwardModel objects A list of GeoClawForwardModel or TestForwardModel objects that each contain their own ... | 3 | stack_v2_sparse_classes_30k_train_054594 | Implement the Python class `CompositeForwardModel` described below.
Class description:
Implement the CompositeForwardModel class.
Method signatures and docstrings:
- def __init__(self, submodels): Extracts all the gauge objects found within each element of the submodels lists and pases those gauges into the construct... | Implement the Python class `CompositeForwardModel` described below.
Class description:
Implement the CompositeForwardModel class.
Method signatures and docstrings:
- def __init__(self, submodels): Extracts all the gauge objects found within each element of the submodels lists and pases those gauges into the construct... | c537a77ea071d4d8fc0590771efe1ec7646536e5 | <|skeleton|>
class CompositeForwardModel:
def __init__(self, submodels):
"""Extracts all the gauge objects found within each element of the submodels lists and pases those gauges into the constructor of the parent class. Parameters ---------- submodels : (list) of ForwardModel objects A list of GeoClawForw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompositeForwardModel:
def __init__(self, submodels):
"""Extracts all the gauge objects found within each element of the submodels lists and pases those gauges into the constructor of the parent class. Parameters ---------- submodels : (list) of ForwardModel objects A list of GeoClawForwardModel or Te... | the_stack_v2_python_sparse | tsunamibayes/forward.py | jpw37/tsunamibayes | train | 11 | |
afc3da1256b8e755dfc3d9f092015dc1c7c332ca | [
"login_driver[0].merchant_login(cd.merchant_user['user'], cd.merchant_user['pwd'])\ntry:\n assert login_driver[1].get_merchant_name() == '兴和网络测试'\n assert cd.merchant_user['user'] in login_driver[1].get_user()\nexcept Exception as e:\n raise e",
"login_driver[0].merchant_login_unverify(cd.merchant_user['... | <|body_start_0|>
login_driver[0].merchant_login(cd.merchant_user['user'], cd.merchant_user['pwd'])
try:
assert login_driver[1].get_merchant_name() == '兴和网络测试'
assert cd.merchant_user['user'] in login_driver[1].get_user()
except Exception as e:
raise e
<|end_bo... | 运营商登录 | TestLogin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLogin:
"""运营商登录"""
def test01_merchant_login_success(self, login_driver):
"""运营商正常登录 :return:"""
<|body_0|>
def test02_merchant_login_unverify(self, login_driver):
"""运营商登录不滑动验证 :return:"""
<|body_1|>
def test03_merchant_login_unnormale(self, mer... | stack_v2_sparse_classes_75kplus_train_070685 | 1,519 | no_license | [
{
"docstring": "运营商正常登录 :return:",
"name": "test01_merchant_login_success",
"signature": "def test01_merchant_login_success(self, login_driver)"
},
{
"docstring": "运营商登录不滑动验证 :return:",
"name": "test02_merchant_login_unverify",
"signature": "def test02_merchant_login_unverify(self, login... | 3 | stack_v2_sparse_classes_30k_val_002161 | Implement the Python class `TestLogin` described below.
Class description:
运营商登录
Method signatures and docstrings:
- def test01_merchant_login_success(self, login_driver): 运营商正常登录 :return:
- def test02_merchant_login_unverify(self, login_driver): 运营商登录不滑动验证 :return:
- def test03_merchant_login_unnormale(self, merchan... | Implement the Python class `TestLogin` described below.
Class description:
运营商登录
Method signatures and docstrings:
- def test01_merchant_login_success(self, login_driver): 运营商正常登录 :return:
- def test02_merchant_login_unverify(self, login_driver): 运营商登录不滑动验证 :return:
- def test03_merchant_login_unnormale(self, merchan... | 0f7fe7eca64d767f8950ed0eb97790ba12344d9c | <|skeleton|>
class TestLogin:
"""运营商登录"""
def test01_merchant_login_success(self, login_driver):
"""运营商正常登录 :return:"""
<|body_0|>
def test02_merchant_login_unverify(self, login_driver):
"""运营商登录不滑动验证 :return:"""
<|body_1|>
def test03_merchant_login_unnormale(self, mer... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestLogin:
"""运营商登录"""
def test01_merchant_login_success(self, login_driver):
"""运营商正常登录 :return:"""
login_driver[0].merchant_login(cd.merchant_user['user'], cd.merchant_user['pwd'])
try:
assert login_driver[1].get_merchant_name() == '兴和网络测试'
assert cd.merc... | the_stack_v2_python_sparse | TestCases/test_01_merchant_login.py | Dake-M/merchant_web_framework | train | 0 |
e045d4ac1722c890fd280e01adf854a370600d2e | [
"value = cast_to_bytes(value)\nsecret_key = cast_to_bytes(secret_key)\nauthenticator = cast_to_bytes(authenticator)\nif len(authenticator) != 16:\n raise EncryptionError('Length of authenticator must be 16 bytes')\nresult = b''\ncurrent_chunk_result = authenticator\nidx = 0\nwhile idx < len(value):\n value_ch... | <|body_start_0|>
value = cast_to_bytes(value)
secret_key = cast_to_bytes(secret_key)
authenticator = cast_to_bytes(authenticator)
if len(authenticator) != 16:
raise EncryptionError('Length of authenticator must be 16 bytes')
result = b''
current_chunk_result =... | Class `UserPasswordCrypt` implement crypt method for User-Password RADIUS attribute See RFC2865 sec 5.2 for details Usage: crypted = UserPasswordCrypt.encrypt(cleartext_password, secret, authenticator) decrypted = UserPasswordCrypt.decrypt(crypted_password, secret, authenticator) | UserPasswordCrypt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPasswordCrypt:
"""Class `UserPasswordCrypt` implement crypt method for User-Password RADIUS attribute See RFC2865 sec 5.2 for details Usage: crypted = UserPasswordCrypt.encrypt(cleartext_password, secret, authenticator) decrypted = UserPasswordCrypt.decrypt(crypted_password, secret, authentic... | stack_v2_sparse_classes_75kplus_train_070686 | 4,146 | no_license | [
{
"docstring": "Return encrypted value of password Params: value - cleartext password for encrypt secret_key - shared secret for Server and NAS authenticator - value of authenticator from request packet",
"name": "encrypt",
"signature": "def encrypt(value, secret_key, authenticator)"
},
{
"docst... | 2 | null | Implement the Python class `UserPasswordCrypt` described below.
Class description:
Class `UserPasswordCrypt` implement crypt method for User-Password RADIUS attribute See RFC2865 sec 5.2 for details Usage: crypted = UserPasswordCrypt.encrypt(cleartext_password, secret, authenticator) decrypted = UserPasswordCrypt.decr... | Implement the Python class `UserPasswordCrypt` described below.
Class description:
Class `UserPasswordCrypt` implement crypt method for User-Password RADIUS attribute See RFC2865 sec 5.2 for details Usage: crypted = UserPasswordCrypt.encrypt(cleartext_password, secret, authenticator) decrypted = UserPasswordCrypt.decr... | d0feac20492bca048386980537bfc0715cb5b0c2 | <|skeleton|>
class UserPasswordCrypt:
"""Class `UserPasswordCrypt` implement crypt method for User-Password RADIUS attribute See RFC2865 sec 5.2 for details Usage: crypted = UserPasswordCrypt.encrypt(cleartext_password, secret, authenticator) decrypted = UserPasswordCrypt.decrypt(crypted_password, secret, authentic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserPasswordCrypt:
"""Class `UserPasswordCrypt` implement crypt method for User-Password RADIUS attribute See RFC2865 sec 5.2 for details Usage: crypted = UserPasswordCrypt.encrypt(cleartext_password, secret, authenticator) decrypted = UserPasswordCrypt.decrypt(crypted_password, secret, authenticator)"""
... | the_stack_v2_python_sparse | aioradius/protocol/crypt.py | arusinov/aioradius | train | 0 |
b369c93ba7777240f783e9dd5d09d8b89c9521ac | [
"issue_tracker_data = self.get('issue_tracker', {})\nparameters = issue_tracker_data.get('parameters', {})\nurl = parameters.get('url', '')\nissue_parameters = IssueParameters(parameters.get('project_key', ''), parameters.get('issue_type', ''), parameters.get('issue_labels', []), parameters.get('epic_link', ''))\nc... | <|body_start_0|>
issue_tracker_data = self.get('issue_tracker', {})
parameters = issue_tracker_data.get('parameters', {})
url = parameters.get('url', '')
issue_parameters = IssueParameters(parameters.get('project_key', ''), parameters.get('issue_type', ''), parameters.get('issue_labels',... | Subclass the shared report class to add methods specific for the API-server. | Report | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Report:
"""Subclass the shared report class to add methods specific for the API-server."""
def issue_tracker(self) -> IssueTracker:
"""Return the issue tracker of the report."""
<|body_0|>
def desired_response_time(self, status: str) -> int:
"""Return the desired... | stack_v2_sparse_classes_75kplus_train_070687 | 2,013 | permissive | [
{
"docstring": "Return the issue tracker of the report.",
"name": "issue_tracker",
"signature": "def issue_tracker(self) -> IssueTracker"
},
{
"docstring": "Return the desired response time for the metric status.",
"name": "desired_response_time",
"signature": "def desired_response_time(... | 3 | stack_v2_sparse_classes_30k_train_043829 | Implement the Python class `Report` described below.
Class description:
Subclass the shared report class to add methods specific for the API-server.
Method signatures and docstrings:
- def issue_tracker(self) -> IssueTracker: Return the issue tracker of the report.
- def desired_response_time(self, status: str) -> in... | Implement the Python class `Report` described below.
Class description:
Subclass the shared report class to add methods specific for the API-server.
Method signatures and docstrings:
- def issue_tracker(self) -> IssueTracker: Return the issue tracker of the report.
- def desired_response_time(self, status: str) -> in... | 5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3 | <|skeleton|>
class Report:
"""Subclass the shared report class to add methods specific for the API-server."""
def issue_tracker(self) -> IssueTracker:
"""Return the issue tracker of the report."""
<|body_0|>
def desired_response_time(self, status: str) -> int:
"""Return the desired... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Report:
"""Subclass the shared report class to add methods specific for the API-server."""
def issue_tracker(self) -> IssueTracker:
"""Return the issue tracker of the report."""
issue_tracker_data = self.get('issue_tracker', {})
parameters = issue_tracker_data.get('parameters', {}... | the_stack_v2_python_sparse | components/api_server/src/model/report.py | ICTU/quality-time | train | 43 |
3ff7f330123f71e7f7aef30cd8cc0712cb1a2cea | [
"self.source_view_id = source_view_id\nself.use_same_view_name = use_same_view_name\nself.view_name = view_name",
"if dictionary is None:\n return None\nsource_view_id = dictionary.get('sourceViewId')\nuse_same_view_name = dictionary.get('useSameViewName')\nview_name = dictionary.get('viewName')\nreturn cls(so... | <|body_start_0|>
self.source_view_id = source_view_id
self.use_same_view_name = use_same_view_name
self.view_name = view_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
source_view_id = dictionary.get('sourceViewId')
use_same_view_name... | Implementation of the 'RemoteViewConfig' model. Specifies the remote view config for a view protected in a view job. This field is only used when the view job has a replication policy. Attributes: source_view_id (long|int): Specifies the view Id of the view protected by the view protection job. use_same_view_name (bool... | RemoteViewConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemoteViewConfig:
"""Implementation of the 'RemoteViewConfig' model. Specifies the remote view config for a view protected in a view job. This field is only used when the view job has a replication policy. Attributes: source_view_id (long|int): Specifies the view Id of the view protected by the v... | stack_v2_sparse_classes_75kplus_train_070688 | 2,406 | permissive | [
{
"docstring": "Constructor for the RemoteViewConfig class",
"name": "__init__",
"signature": "def __init__(self, source_view_id=None, use_same_view_name=None, view_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary repr... | 2 | stack_v2_sparse_classes_30k_train_007329 | Implement the Python class `RemoteViewConfig` described below.
Class description:
Implementation of the 'RemoteViewConfig' model. Specifies the remote view config for a view protected in a view job. This field is only used when the view job has a replication policy. Attributes: source_view_id (long|int): Specifies the... | Implement the Python class `RemoteViewConfig` described below.
Class description:
Implementation of the 'RemoteViewConfig' model. Specifies the remote view config for a view protected in a view job. This field is only used when the view job has a replication policy. Attributes: source_view_id (long|int): Specifies the... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RemoteViewConfig:
"""Implementation of the 'RemoteViewConfig' model. Specifies the remote view config for a view protected in a view job. This field is only used when the view job has a replication policy. Attributes: source_view_id (long|int): Specifies the view Id of the view protected by the v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RemoteViewConfig:
"""Implementation of the 'RemoteViewConfig' model. Specifies the remote view config for a view protected in a view job. This field is only used when the view job has a replication policy. Attributes: source_view_id (long|int): Specifies the view Id of the view protected by the view protectio... | the_stack_v2_python_sparse | cohesity_management_sdk/models/remote_view_config.py | cohesity/management-sdk-python | train | 24 |
07e7f4057b4235b3d2eae99e4100952c8134a4af | [
"connected_nodes = []\nfringe = [start_cell]\nwhile len(fringe) > 0:\n current = fringe.pop(0)\n if current in connected_nodes:\n continue\n connected_neighbours = Utils.get_connected_neighbour(current, walled_edges, max_row, max_col)\n connected_nodes.append(current)\n for neighbour in connec... | <|body_start_0|>
connected_nodes = []
fringe = [start_cell]
while len(fringe) > 0:
current = fringe.pop(0)
if current in connected_nodes:
continue
connected_neighbours = Utils.get_connected_neighbour(current, walled_edges, max_row, max_col)
... | Utils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Utils:
def get_connected_nodes(start_cell, walled_edges, max_row, max_col):
"""Find the connected graph starting from ``start_cell`` in a grid of size ``max_row`` x ``max_col``. All the edges except ``walled_edges`` are considered as connected. :param start_cell: starting position of the... | stack_v2_sparse_classes_75kplus_train_070689 | 3,272 | no_license | [
{
"docstring": "Find the connected graph starting from ``start_cell`` in a grid of size ``max_row`` x ``max_col``. All the edges except ``walled_edges`` are considered as connected. :param start_cell: starting position of the robot in grid :type start_cell: tuple (int, int) :param walled_edges: edges in a graph... | 3 | stack_v2_sparse_classes_30k_train_010286 | Implement the Python class `Utils` described below.
Class description:
Implement the Utils class.
Method signatures and docstrings:
- def get_connected_nodes(start_cell, walled_edges, max_row, max_col): Find the connected graph starting from ``start_cell`` in a grid of size ``max_row`` x ``max_col``. All the edges ex... | Implement the Python class `Utils` described below.
Class description:
Implement the Utils class.
Method signatures and docstrings:
- def get_connected_nodes(start_cell, walled_edges, max_row, max_col): Find the connected graph starting from ``start_cell`` in a grid of size ``max_row`` x ``max_col``. All the edges ex... | 8129cd48351159508cae3438a8b8b3d776c771ca | <|skeleton|>
class Utils:
def get_connected_nodes(start_cell, walled_edges, max_row, max_col):
"""Find the connected graph starting from ``start_cell`` in a grid of size ``max_row`` x ``max_col``. All the edges except ``walled_edges`` are considered as connected. :param start_cell: starting position of the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Utils:
def get_connected_nodes(start_cell, walled_edges, max_row, max_col):
"""Find the connected graph starting from ``start_cell`` in a grid of size ``max_row`` x ``max_col``. All the edges except ``walled_edges`` are considered as connected. :param start_cell: starting position of the robot in grid... | the_stack_v2_python_sparse | mir_simulation/mir_world_generation/common/mir_world_generation/utils.py | b-it-bots/mas_industrial_robotics | train | 25 | |
2bd6a5b6804b37d8349b5cf1512d564ac77dcf6d | [
"super(BcombLmsCombiner, self).__init__(prob_estimators=prob_estimators, verbose=verbose)\nself.alpha = alpha\nself.beta = beta",
"assert len(log_probs) == 2\nfwd_log_probs, bwd_log_probs = log_probs\nlog_probs = (fwd_log_probs + bwd_log_probs) * self.alpha\nx, y = log_probs.shape\nrank_w = 1.0 / np.arange(1, y +... | <|body_start_0|>
super(BcombLmsCombiner, self).__init__(prob_estimators=prob_estimators, verbose=verbose)
self.alpha = alpha
self.beta = beta
<|end_body_0|>
<|body_start_1|>
assert len(log_probs) == 2
fwd_log_probs, bwd_log_probs = log_probs
log_probs = (fwd_log_probs + ... | BcombLmsCombiner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BcombLmsCombiner:
def __init__(self, prob_estimators: List[BaseProbEstimator], alpha: float=1.0, beta: float=1.0, verbose: bool=False):
"""Combines two models distributions into one according to the formula: :math:`P(w|M_1, M_2) \\propto \\displaystyle \\frac{(P(w|M_1)P(w|M_2))^\\alpha}{... | stack_v2_sparse_classes_75kplus_train_070690 | 12,750 | permissive | [
{
"docstring": "Combines two models distributions into one according to the formula: :math:`P(w|M_1, M_2) \\\\propto \\\\displaystyle \\\\frac{(P(w|M_1)P(w|M_2))^\\\\alpha}{P(w)^\\\\beta}` and :math:`P(w) = \\\\displaystyle \\\\frac{1}{1 + \\\\text{rank}(w)}` is a prior word distribution. It's supposed that wor... | 2 | stack_v2_sparse_classes_30k_train_050010 | Implement the Python class `BcombLmsCombiner` described below.
Class description:
Implement the BcombLmsCombiner class.
Method signatures and docstrings:
- def __init__(self, prob_estimators: List[BaseProbEstimator], alpha: float=1.0, beta: float=1.0, verbose: bool=False): Combines two models distributions into one a... | Implement the Python class `BcombLmsCombiner` described below.
Class description:
Implement the BcombLmsCombiner class.
Method signatures and docstrings:
- def __init__(self, prob_estimators: List[BaseProbEstimator], alpha: float=1.0, beta: float=1.0, verbose: bool=False): Combines two models distributions into one a... | c87f67e5fe51fc8307b5d5ff8f404f202f17ab5e | <|skeleton|>
class BcombLmsCombiner:
def __init__(self, prob_estimators: List[BaseProbEstimator], alpha: float=1.0, beta: float=1.0, verbose: bool=False):
"""Combines two models distributions into one according to the formula: :math:`P(w|M_1, M_2) \\propto \\displaystyle \\frac{(P(w|M_1)P(w|M_2))^\\alpha}{... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BcombLmsCombiner:
def __init__(self, prob_estimators: List[BaseProbEstimator], alpha: float=1.0, beta: float=1.0, verbose: bool=False):
"""Combines two models distributions into one according to the formula: :math:`P(w|M_1, M_2) \\propto \\displaystyle \\frac{(P(w|M_1)P(w|M_2))^\\alpha}{P(w)^\\beta}` ... | the_stack_v2_python_sparse | lexsubgen/prob_estimators/combiner.py | agoel00/LexSubGen | train | 0 | |
201496e5694d4607e3ddba735373ef19957571fc | [
"ents: Tuple[str, int, Tuple[int, int]] = []\ndoc: FeatureDocument\nfor six, (cls, doc) in enumerate(zip(classes, docs)):\n tok: FeatureToken\n start_ix = None\n start_lab = None\n ent: str\n for stix, (ent, tok) in enumerate(zip(cls, doc.tokens)):\n pos: int = ent.find('-')\n bio, lab ... | <|body_start_0|>
ents: Tuple[str, int, Tuple[int, int]] = []
doc: FeatureDocument
for six, (cls, doc) in enumerate(zip(classes, docs)):
tok: FeatureToken
start_ix = None
start_lab = None
ent: str
for stix, (ent, tok) in enumerate(zip(cl... | Matches feature documents/tokens with spaCy document/tokens and entity labels. | BioSequenceAnnotationMapper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BioSequenceAnnotationMapper:
"""Matches feature documents/tokens with spaCy document/tokens and entity labels."""
def _map_entities(self, classes: Tuple[List[str]], docs: Tuple[FeatureDocument]) -> Tuple[str, int, Tuple[int, int]]:
"""Map BIO entities and documents to a pairing of bo... | stack_v2_sparse_classes_75kplus_train_070691 | 7,916 | permissive | [
{
"docstring": "Map BIO entities and documents to a pairing of both. :param classes: the clases (labels, or usually, predictions) :param docs: the feature documents to assign labels :return: a tuple of label, sentence index and lexical feature document index interval of tokens",
"name": "_map_entities",
... | 3 | stack_v2_sparse_classes_30k_train_004898 | Implement the Python class `BioSequenceAnnotationMapper` described below.
Class description:
Matches feature documents/tokens with spaCy document/tokens and entity labels.
Method signatures and docstrings:
- def _map_entities(self, classes: Tuple[List[str]], docs: Tuple[FeatureDocument]) -> Tuple[str, int, Tuple[int,... | Implement the Python class `BioSequenceAnnotationMapper` described below.
Class description:
Matches feature documents/tokens with spaCy document/tokens and entity labels.
Method signatures and docstrings:
- def _map_entities(self, classes: Tuple[List[str]], docs: Tuple[FeatureDocument]) -> Tuple[str, int, Tuple[int,... | d2735848199741e818a49efb5197eb4a716fd96f | <|skeleton|>
class BioSequenceAnnotationMapper:
"""Matches feature documents/tokens with spaCy document/tokens and entity labels."""
def _map_entities(self, classes: Tuple[List[str]], docs: Tuple[FeatureDocument]) -> Tuple[str, int, Tuple[int, int]]:
"""Map BIO entities and documents to a pairing of bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BioSequenceAnnotationMapper:
"""Matches feature documents/tokens with spaCy document/tokens and entity labels."""
def _map_entities(self, classes: Tuple[List[str]], docs: Tuple[FeatureDocument]) -> Tuple[str, int, Tuple[int, int]]:
"""Map BIO entities and documents to a pairing of both. :param cl... | the_stack_v2_python_sparse | src/python/zensols/deepnlp/model/sequence.py | plandes/deepnlp | train | 9 |
59e386cde413e8380d0c0b165cc3f4a3d7e0353a | [
"super().__init__(cost_multiplier=cost_multiplier)\nself.forbidden_states_dagger = conjugate_transpose(forbidden_states)\nstate_count = forbidden_states.shape[0]\nself.normalization_constant = state_count * system_step_count\nself.state_normalization_constants = np.array([state_forbidden_states.shape[0] for state_f... | <|body_start_0|>
super().__init__(cost_multiplier=cost_multiplier)
self.forbidden_states_dagger = conjugate_transpose(forbidden_states)
state_count = forbidden_states.shape[0]
self.normalization_constant = state_count * system_step_count
self.state_normalization_constants = np.ar... | This class encapsulates a cost function that penalizes the occupation of forbidden states. Fields: cost_multiplier :: float - the wieght factor for this cost forbidden_states_dagger :: ndarray - the conjugate transpose of the forbidden states name :: str - a unique identifier for this cost normalization_constant :: int... | ForbidStates | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForbidStates:
"""This class encapsulates a cost function that penalizes the occupation of forbidden states. Fields: cost_multiplier :: float - the wieght factor for this cost forbidden_states_dagger :: ndarray - the conjugate transpose of the forbidden states name :: str - a unique identifier for... | stack_v2_sparse_classes_75kplus_train_070692 | 4,085 | permissive | [
{
"docstring": "See class definition for arguments not listed here. Args: forbidden_states :: ndarray - an array where each entry in the first axis is an array of states that the corresponding evolving state is forbidden from, that is, each evolving state has its own list of forbidden states system_step_count :... | 2 | stack_v2_sparse_classes_30k_train_039373 | Implement the Python class `ForbidStates` described below.
Class description:
This class encapsulates a cost function that penalizes the occupation of forbidden states. Fields: cost_multiplier :: float - the wieght factor for this cost forbidden_states_dagger :: ndarray - the conjugate transpose of the forbidden state... | Implement the Python class `ForbidStates` described below.
Class description:
This class encapsulates a cost function that penalizes the occupation of forbidden states. Fields: cost_multiplier :: float - the wieght factor for this cost forbidden_states_dagger :: ndarray - the conjugate transpose of the forbidden state... | 64c1eed34c9a4200a01a7152932482a29a1fd89e | <|skeleton|>
class ForbidStates:
"""This class encapsulates a cost function that penalizes the occupation of forbidden states. Fields: cost_multiplier :: float - the wieght factor for this cost forbidden_states_dagger :: ndarray - the conjugate transpose of the forbidden states name :: str - a unique identifier for... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ForbidStates:
"""This class encapsulates a cost function that penalizes the occupation of forbidden states. Fields: cost_multiplier :: float - the wieght factor for this cost forbidden_states_dagger :: ndarray - the conjugate transpose of the forbidden states name :: str - a unique identifier for this cost no... | the_stack_v2_python_sparse | qoc/standard/costs/forbidstates.py | jmbaker94/qoc | train | 0 |
a4cad17e17816abd3cf2690a7eec7784fe28c8d6 | [
"try:\n payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])\nexcept jwt.ExpiredSignatureError:\n raise serializers.ValidationError('Link de Verificacion expiro.')\nexcept jwt.PyJWTError:\n raise serializers.ValidationError('Token Invalido')\nif payload['type'] != 'email_confirmation':\n ... | <|body_start_0|>
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('Link de Verificacion expiro.')
except jwt.PyJWTError:
raise serializers.ValidationError('Token Inva... | Account verification serializer. | AccountVerificationSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_75kplus_train_070693 | 5,812 | no_license | [
{
"docstring": "Verify token is valid.",
"name": "validate_token",
"signature": "def validate_token(self, data)"
},
{
"docstring": "Update user's verified status.",
"name": "save",
"signature": "def save(self)"
}
] | 2 | null | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def save(self): Update user's verified status. | Implement the Python class `AccountVerificationSerializer` described below.
Class description:
Account verification serializer.
Method signatures and docstrings:
- def validate_token(self, data): Verify token is valid.
- def save(self): Update user's verified status.
<|skeleton|>
class AccountVerificationSerializer:... | 9742d244526374aa4bbcb6c338b33a698c751a1d | <|skeleton|>
class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
<|body_0|>
def save(self):
"""Update user's verified status."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountVerificationSerializer:
"""Account verification serializer."""
def validate_token(self, data):
"""Verify token is valid."""
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers... | the_stack_v2_python_sparse | restapi/serializers.py | frankbriones/fundacion | train | 3 |
0b7f2fdb3076978075259e1735b13c0350529477 | [
"if self.with_bbox or self.with_mask:\n num_imgs = len(img_metas)\n if gt_bboxes_ignore is None:\n gt_bboxes_ignore = [None for _ in range(num_imgs)]\n sampling_results = []\n for i in range(num_imgs):\n assign_result = self.bbox_assigner.assign(proposal_list[i], gt_bboxes[i], gt_bboxes_ig... | <|body_start_0|>
if self.with_bbox or self.with_mask:
num_imgs = len(img_metas)
if gt_bboxes_ignore is None:
gt_bboxes_ignore = [None for _ in range(num_imgs)]
sampling_results = []
for i in range(num_imgs):
assign_result = self.bbo... | selsa roi head. | SelsaRoIHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelsaRoIHead:
"""selsa roi head."""
def forward_train(self, x, ref_x, img_metas, proposal_list, ref_proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None):
"""Args: x (list[Tensor]): list of multi-level img features. ref_x (list[Tensor]): list of multi-level ref_i... | stack_v2_sparse_classes_75kplus_train_070694 | 7,948 | permissive | [
{
"docstring": "Args: x (list[Tensor]): list of multi-level img features. ref_x (list[Tensor]): list of multi-level ref_img features. img_metas (list[dict]): list of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm... | 5 | null | Implement the Python class `SelsaRoIHead` described below.
Class description:
selsa roi head.
Method signatures and docstrings:
- def forward_train(self, x, ref_x, img_metas, proposal_list, ref_proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None): Args: x (list[Tensor]): list of multi-level img ... | Implement the Python class `SelsaRoIHead` described below.
Class description:
selsa roi head.
Method signatures and docstrings:
- def forward_train(self, x, ref_x, img_metas, proposal_list, ref_proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None): Args: x (list[Tensor]): list of multi-level img ... | e79491ec8f0b8c86fda947fbaaa824c66ab2a991 | <|skeleton|>
class SelsaRoIHead:
"""selsa roi head."""
def forward_train(self, x, ref_x, img_metas, proposal_list, ref_proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None):
"""Args: x (list[Tensor]): list of multi-level img features. ref_x (list[Tensor]): list of multi-level ref_i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelsaRoIHead:
"""selsa roi head."""
def forward_train(self, x, ref_x, img_metas, proposal_list, ref_proposal_list, gt_bboxes, gt_labels, gt_bboxes_ignore=None, gt_masks=None):
"""Args: x (list[Tensor]): list of multi-level img features. ref_x (list[Tensor]): list of multi-level ref_img features. ... | the_stack_v2_python_sparse | mmtrack/models/roi_heads/selsa_roi_head.py | open-mmlab/mmtracking | train | 3,263 |
a653bb09a47780f0cb6911ed039f330ccc90b336 | [
"self.link = L\nif L is None:\n self.head = None\n self.tail = None\n return\nif not len(L[:1]):\n self.head = None\n self.tail = None\n return\nnode = Node(L[0])\nself.head = node\nfor e in L[1:]:\n node.next_node = Node(e)\n node.next_node.previous_node = node\n node = node.next_node\ns... | <|body_start_0|>
self.link = L
if L is None:
self.head = None
self.tail = None
return
if not len(L[:1]):
self.head = None
self.tail = None
return
node = Node(L[0])
self.head = node
for e in L[1:]:
... | DoublyLinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoublyLinkedList:
def __init__(self, L=None):
"""Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]... | stack_v2_sparse_classes_75kplus_train_070695 | 4,348 | no_license | [
{
"docstring": "Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]).print_from_tail_to_head() >>> DoublyLinkedList((0,)).pr... | 4 | stack_v2_sparse_classes_30k_train_022662 | Implement the Python class `DoublyLinkedList` described below.
Class description:
Implement the DoublyLinkedList class.
Method signatures and docstrings:
- def __init__(self, L=None): Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedLi... | Implement the Python class `DoublyLinkedList` described below.
Class description:
Implement the DoublyLinkedList class.
Method signatures and docstrings:
- def __init__(self, L=None): Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedLi... | 4d0d4a2d719745528bf84ed0dfb88a43f858be7e | <|skeleton|>
class DoublyLinkedList:
def __init__(self, L=None):
"""Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DoublyLinkedList:
def __init__(self, L=None):
"""Creates an empty list or a list built from a subscriptable object. >>> DoublyLinkedList().print_from_head_to_tail() >>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList([]).print_from_head_to_tail() >>> DoublyLinkedList([]).print_from_t... | the_stack_v2_python_sparse | Sample_Exam_Questions_2/sample_5.py | gakkistyle/comp9021 | train | 14 | |
41f8b541d5c7fa8ab68a5ae0cb8ecb1662349996 | [
"command_name = args.pop(1)\nsuper().__init__(args=args, path=path)\nmachine_path, remaining_args = self.parse_args()\nself.machine_path = machine_path\nself.args = remaining_args\nparser = argparse.ArgumentParser(description='Build MPF production config.')\nparser.add_argument('-c', action='store', dest='configfil... | <|body_start_0|>
command_name = args.pop(1)
super().__init__(args=args, path=path)
machine_path, remaining_args = self.parse_args()
self.machine_path = machine_path
self.args = remaining_args
parser = argparse.ArgumentParser(description='Build MPF production config.')
... | Build artifacts. | Command | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Build artifacts."""
def __init__(self, args, path):
"""Parse args."""
<|body_0|>
def production_bundle(self):
"""Create a production bundle."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
command_name = args.pop(1)
super()._... | stack_v2_sparse_classes_75kplus_train_070696 | 2,600 | permissive | [
{
"docstring": "Parse args.",
"name": "__init__",
"signature": "def __init__(self, args, path)"
},
{
"docstring": "Create a production bundle.",
"name": "production_bundle",
"signature": "def production_bundle(self)"
}
] | 2 | null | Implement the Python class `Command` described below.
Class description:
Build artifacts.
Method signatures and docstrings:
- def __init__(self, args, path): Parse args.
- def production_bundle(self): Create a production bundle. | Implement the Python class `Command` described below.
Class description:
Build artifacts.
Method signatures and docstrings:
- def __init__(self, args, path): Parse args.
- def production_bundle(self): Create a production bundle.
<|skeleton|>
class Command:
"""Build artifacts."""
def __init__(self, args, pat... | 9f90c8b1586363b65340017bfa3af5d56d32c6d9 | <|skeleton|>
class Command:
"""Build artifacts."""
def __init__(self, args, path):
"""Parse args."""
<|body_0|>
def production_bundle(self):
"""Create a production bundle."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Command:
"""Build artifacts."""
def __init__(self, args, path):
"""Parse args."""
command_name = args.pop(1)
super().__init__(args=args, path=path)
machine_path, remaining_args = self.parse_args()
self.machine_path = machine_path
self.args = remaining_args
... | the_stack_v2_python_sparse | mpf/commands/build.py | missionpinball/mpf | train | 191 |
3e21061207c8af6753ebbaa3da10e0d0d988afc1 | [
"lti = LTI(request_type='any', role_type='any')\ntry:\n lti.verify(request)\nexcept LTIException:\n return render(request, 'lti_failure.html')\nif not request.user.is_authenticated:\n try:\n lti_user = login_existing_user(request)\n except EmailAddress.DoesNotExist:\n lti_email = request.P... | <|body_start_0|>
lti = LTI(request_type='any', role_type='any')
try:
lti.verify(request)
except LTIException:
return render(request, 'lti_failure.html')
if not request.user.is_authenticated:
try:
lti_user = login_existing_user(request)
... | LtiInitializerView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handle the POST coming directly from Canvas"""
<|body_1|>
def create_lti_user(... | stack_v2_sparse_classes_75kplus_train_070697 | 4,866 | permissive | [
{
"docstring": "Handle LTI verification and user authentication",
"name": "dispatch",
"signature": "def dispatch(self, request, *args, **kwargs)"
},
{
"docstring": "Handle the POST coming directly from Canvas",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
... | 6 | stack_v2_sparse_classes_30k_train_042558 | Implement the Python class `LtiInitializerView` described below.
Class description:
Implement the LtiInitializerView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Handle LTI verification and user authentication
- def post(self, request, *args, **kwargs): Handle the POST comi... | Implement the Python class `LtiInitializerView` described below.
Class description:
Implement the LtiInitializerView class.
Method signatures and docstrings:
- def dispatch(self, request, *args, **kwargs): Handle LTI verification and user authentication
- def post(self, request, *args, **kwargs): Handle the POST comi... | f44773bcf7695f4f73f0cd71daed7767902bcfd4 | <|skeleton|>
class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handle the POST coming directly from Canvas"""
<|body_1|>
def create_lti_user(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LtiInitializerView:
def dispatch(self, request, *args, **kwargs):
"""Handle LTI verification and user authentication"""
lti = LTI(request_type='any', role_type='any')
try:
lti.verify(request)
except LTIException:
return render(request, 'lti_failure.html'... | the_stack_v2_python_sparse | lti/views.py | Hedera-Lang-Learn/hedera | train | 9 | |
01adba14499d24e53c38eef3f27e9fe5ad9ac5f5 | [
"self.k = k\nself.queue = nums\nheapq.heapify(self.queue)",
"heapq.heappush(self.queue, val)\nwhile len(self.queue) > self.k:\n heapq.heappop(self.queue)\nreturn self.queue[0]"
] | <|body_start_0|>
self.k = k
self.queue = nums
heapq.heapify(self.queue)
<|end_body_0|>
<|body_start_1|>
heapq.heappush(self.queue, val)
while len(self.queue) > self.k:
heapq.heappop(self.queue)
return self.queue[0]
<|end_body_1|>
| KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.queue = nums
heapq.heapify... | stack_v2_sparse_classes_75kplus_train_070698 | 648 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010118 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 82ece6ed353235dcd36face80f5d87df12d56a2c | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.queue = nums
heapq.heapify(self.queue)
def add(self, val):
""":type val: int :rtype: int"""
heapq.heappush(self.queue, val)
while len(self.queue) > sel... | the_stack_v2_python_sparse | 排序/703. 数据流中的第 K 大元素.py | pulinghao/LeetCode_Python | train | 2 | |
ccfd49bc7d3ae389000d0010b55c5cbec2f39d54 | [
"super(self.__class__, self).__init__()\nimport sklearn.metrics as metrics\nfrom metrician.configs.interface import DefaultConfigInterface\nself.cfg = DefaultCFG(cfg if isinstance(cfg, dict) else None) if not issubclass(cfg.__class__, DefaultConfigInterface) else cfg\nself.metrics = metrics\nself.custom_functions =... | <|body_start_0|>
super(self.__class__, self).__init__()
import sklearn.metrics as metrics
from metrician.configs.interface import DefaultConfigInterface
self.cfg = DefaultCFG(cfg if isinstance(cfg, dict) else None) if not issubclass(cfg.__class__, DefaultConfigInterface) else cfg
... | Metric Writer is a lightweight class that will automatically log metrics during a training loop. | MetricWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricWriter:
"""Metric Writer is a lightweight class that will automatically log metrics during a training loop."""
def __init__(self, cfg: Union[dict, DefaultCFG]=None):
"""Args: cfg (Union[dict,DefaultCFG], optional): [description]. Defaults to None."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_070699 | 2,879 | permissive | [
{
"docstring": "Args: cfg (Union[dict,DefaultCFG], optional): [description]. Defaults to None.",
"name": "__init__",
"signature": "def __init__(self, cfg: Union[dict, DefaultCFG]=None)"
},
{
"docstring": "[summary] Returns: [type]: [description]",
"name": "forward",
"signature": "def for... | 2 | stack_v2_sparse_classes_30k_train_028499 | Implement the Python class `MetricWriter` described below.
Class description:
Metric Writer is a lightweight class that will automatically log metrics during a training loop.
Method signatures and docstrings:
- def __init__(self, cfg: Union[dict, DefaultCFG]=None): Args: cfg (Union[dict,DefaultCFG], optional): [descr... | Implement the Python class `MetricWriter` described below.
Class description:
Metric Writer is a lightweight class that will automatically log metrics during a training loop.
Method signatures and docstrings:
- def __init__(self, cfg: Union[dict, DefaultCFG]=None): Args: cfg (Union[dict,DefaultCFG], optional): [descr... | d4164dbff8db5645ee8beca11dc55ba6c26c4cb6 | <|skeleton|>
class MetricWriter:
"""Metric Writer is a lightweight class that will automatically log metrics during a training loop."""
def __init__(self, cfg: Union[dict, DefaultCFG]=None):
"""Args: cfg (Union[dict,DefaultCFG], optional): [description]. Defaults to None."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MetricWriter:
"""Metric Writer is a lightweight class that will automatically log metrics during a training loop."""
def __init__(self, cfg: Union[dict, DefaultCFG]=None):
"""Args: cfg (Union[dict,DefaultCFG], optional): [description]. Defaults to None."""
super(self.__class__, self).__in... | the_stack_v2_python_sparse | metrician/writers/writer.py | tedtroxell/metrician | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.