blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b95d712a4835f82033d7abd63d28646b75595633 | [
"i, j = (0, len(nums) - 1)\nwhile i <= j:\n mid = (i + j) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n j = mid - 1\n else:\n i = mid + 1\nreturn i",
"n = len(nums)\nif nums[n - 1] < target:\n return n\nelif nums[0] > target:\n return 0\nleft, righ... | <|body_start_0|>
i, j = (0, len(nums) - 1)
while i <= j:
mid = (i + j) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
j = mid - 1
else:
i = mid + 1
return i
<|end_body_0|>
<|body_st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
"""二分查找"""
<|body_0|>
def searchInsert2(self, nums: List[int], target: int) -> int:
"""官方答案,返回第一个大于等于 target 的下标"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i, j = (0, len(nu... | stack_v2_sparse_classes_36k_train_020300 | 2,482 | no_license | [
{
"docstring": "二分查找",
"name": "searchInsert",
"signature": "def searchInsert(self, nums: List[int], target: int) -> int"
},
{
"docstring": "官方答案,返回第一个大于等于 target 的下标",
"name": "searchInsert2",
"signature": "def searchInsert2(self, nums: List[int], target: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_018317 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums: List[int], target: int) -> int: 二分查找
- def searchInsert2(self, nums: List[int], target: int) -> int: 官方答案,返回第一个大于等于 target 的下标 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsert(self, nums: List[int], target: int) -> int: 二分查找
- def searchInsert2(self, nums: List[int], target: int) -> int: 官方答案,返回第一个大于等于 target 的下标
<|skeleton|>
class So... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
"""二分查找"""
<|body_0|>
def searchInsert2(self, nums: List[int], target: int) -> int:
"""官方答案,返回第一个大于等于 target 的下标"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
"""二分查找"""
i, j = (0, len(nums) - 1)
while i <= j:
mid = (i + j) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
j = mid - 1
... | the_stack_v2_python_sparse | 35.搜索插入位置/solution.py | QtTao/daily_leetcode | train | 0 | |
1552058a422fc9bce65570bbf0469dc7c96cdb92 | [
"post = get_post(uuid)\nif not post:\n logging.error('Could not find post. UUID: %s' % uuid)\n self.error(404)\n return\nresponse = post.to_obj()\nself.respondJSON(response.get('value'), response_key=response.get('key'))",
"params = cgi.parse_qsl(self.request.body)\nself.request.PUT = webob.MultiDict(par... | <|body_start_0|>
post = get_post(uuid)
if not post:
logging.error('Could not find post. UUID: %s' % uuid)
self.error(404)
return
response = post.to_obj()
self.respondJSON(response.get('value'), response_key=response.get('key'))
<|end_body_0|>
<|body_s... | A resource for accessing posts using JSON | ReEngagePostJSONHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReEngagePostJSONHandler:
"""A resource for accessing posts using JSON"""
def get(self, uuid):
"""Get all details for a given post"""
<|body_0|>
def put(self, uuid):
"""Update the details of a post. check ReEngageQueueHandler.put for post creation."""
<|bo... | stack_v2_sparse_classes_36k_train_020301 | 12,697 | no_license | [
{
"docstring": "Get all details for a given post",
"name": "get",
"signature": "def get(self, uuid)"
},
{
"docstring": "Update the details of a post. check ReEngageQueueHandler.put for post creation.",
"name": "put",
"signature": "def put(self, uuid)"
},
{
"docstring": "Delete an... | 3 | null | Implement the Python class `ReEngagePostJSONHandler` described below.
Class description:
A resource for accessing posts using JSON
Method signatures and docstrings:
- def get(self, uuid): Get all details for a given post
- def put(self, uuid): Update the details of a post. check ReEngageQueueHandler.put for post crea... | Implement the Python class `ReEngagePostJSONHandler` described below.
Class description:
A resource for accessing posts using JSON
Method signatures and docstrings:
- def get(self, uuid): Get all details for a given post
- def put(self, uuid): Update the details of a post. check ReEngageQueueHandler.put for post crea... | d1e046d5b7bf1ba0febb337a31ec04f5888fb341 | <|skeleton|>
class ReEngagePostJSONHandler:
"""A resource for accessing posts using JSON"""
def get(self, uuid):
"""Get all details for a given post"""
<|body_0|>
def put(self, uuid):
"""Update the details of a post. check ReEngageQueueHandler.put for post creation."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReEngagePostJSONHandler:
"""A resource for accessing posts using JSON"""
def get(self, uuid):
"""Get all details for a given post"""
post = get_post(uuid)
if not post:
logging.error('Could not find post. UUID: %s' % uuid)
self.error(404)
return
... | the_stack_v2_python_sparse | apps/reengage/resources.py | bbarclay/Willet-Referrals | train | 0 |
b828ff4e4b1825a797c76b48622e3db528ac365c | [
"hashmap = {}\nfor index in range(len(nums)):\n if target - nums[index] in hashmap:\n return (index, hashmap.get(target - nums[index]))\n else:\n hashmap[nums[index]] = index",
"lookup = {}\nfor i, num in enumerate(nums):\n if target - num in lookup:\n return [lookup[target - num], i... | <|body_start_0|>
hashmap = {}
for index in range(len(nums)):
if target - nums[index] in hashmap:
return (index, hashmap.get(target - nums[index]))
else:
hashmap[nums[index]] = index
<|end_body_0|>
<|body_start_1|>
lookup = {}
for i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_020302 | 831 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum2",
"signature": "def twoSum2(self, nums, target)"
}... | 2 | stack_v2_sparse_classes_30k_train_018348 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum2(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | b4fc2ba621f3484973c0520b02c60e5ed1930722 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
hashmap = {}
for index in range(len(nums)):
if target - nums[index] in hashmap:
return (index, hashmap.get(target - nums[index]))
else:
... | the_stack_v2_python_sparse | 001_TwoNumSum.py | Black-Mamba24/leetcode-python | train | 0 | |
7de23b2baccf5e1f72ac1eb281f8ddd37e00a085 | [
"self.info('Starting tckgen creation from mrtrix on {}'.format(source))\ntmp = os.path.join(self.workingDir, 'tmp_{}.tck'.format(algorithm))\ncmd = 'tckgen {} {} -mask {} -act {} -seed_gmwmi {} -number {} -algorithm {} -nthreads {} -quiet'.format(source, tmp, mask, act, seed_gmwmi, self.get('number_tracks'), algor... | <|body_start_0|>
self.info('Starting tckgen creation from mrtrix on {}'.format(source))
tmp = os.path.join(self.workingDir, 'tmp_{}.tck'.format(algorithm))
cmd = 'tckgen {} {} -mask {} -act {} -seed_gmwmi {} -number {} -algorithm {} -nthreads {} -quiet'.format(source, tmp, mask, act, seed_gmwmi... | Tractography | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of vol... | stack_v2_sparse_classes_36k_train_020303 | 3,574 | no_license | [
{
"docstring": "perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of volumes is the X,Y,Z direction of a fibre population). - iFOD1/2 & SD_Stream: the SH image resulting from CSD. - Nulldist & SeedTes... | 3 | stack_v2_sparse_classes_30k_train_000724 | Implement the Python class `Tractography` described below.
Class description:
Implement the Tractography class.
Method signatures and docstrings:
- def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'): perform streamlines tractography. the image containing the source d... | Implement the Python class `Tractography` described below.
Class description:
Implement the Tractography class.
Method signatures and docstrings:
- def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'): perform streamlines tractography. the image containing the source d... | 99682e1a03d56bac0e078bc816d0394fe1147a1a | <|skeleton|>
class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of vol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of volumes is the X,... | the_stack_v2_python_sparse | lib/tractography.py | alexhng/toad | train | 0 | |
161b30ad83b7b48817bf498621556cad92b15df0 | [
"rc.REG.__init__(self, indepVar, depVar)\nself.alpha = alpha\nself.regObj = linear_model.Ridge(alpha=alpha, copy_X=False)",
"self.regObj = linear_model.RidgeCV()\nself.fit_model()\nself.regObj = linear_model.Ridge(alpha=self.regObj.alpha_, copy_X=False)"
] | <|body_start_0|>
rc.REG.__init__(self, indepVar, depVar)
self.alpha = alpha
self.regObj = linear_model.Ridge(alpha=alpha, copy_X=False)
<|end_body_0|>
<|body_start_1|>
self.regObj = linear_model.RidgeCV()
self.fit_model()
self.regObj = linear_model.Ridge(alpha=self.regOb... | Object which performs ridge regression, checks assumptions, and makes plots. | RIDGE | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RIDGE:
"""Object which performs ridge regression, checks assumptions, and makes plots."""
def __init__(self, indepVar, depVar, alpha=1):
"""Ridge constructor @param indepVar Array of independent variables @param depVar Vector of dependent variables"""
<|body_0|>
def CV_m... | stack_v2_sparse_classes_36k_train_020304 | 1,041 | no_license | [
{
"docstring": "Ridge constructor @param indepVar Array of independent variables @param depVar Vector of dependent variables",
"name": "__init__",
"signature": "def __init__(self, indepVar, depVar, alpha=1)"
},
{
"docstring": "Perform cross-validation to select the correct alpha and l1_ratio par... | 2 | stack_v2_sparse_classes_30k_train_005614 | Implement the Python class `RIDGE` described below.
Class description:
Object which performs ridge regression, checks assumptions, and makes plots.
Method signatures and docstrings:
- def __init__(self, indepVar, depVar, alpha=1): Ridge constructor @param indepVar Array of independent variables @param depVar Vector o... | Implement the Python class `RIDGE` described below.
Class description:
Object which performs ridge regression, checks assumptions, and makes plots.
Method signatures and docstrings:
- def __init__(self, indepVar, depVar, alpha=1): Ridge constructor @param indepVar Array of independent variables @param depVar Vector o... | 185d49bf4a8cd7d6f417bd9265668551ee95e17c | <|skeleton|>
class RIDGE:
"""Object which performs ridge regression, checks assumptions, and makes plots."""
def __init__(self, indepVar, depVar, alpha=1):
"""Ridge constructor @param indepVar Array of independent variables @param depVar Vector of dependent variables"""
<|body_0|>
def CV_m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RIDGE:
"""Object which performs ridge regression, checks assumptions, and makes plots."""
def __init__(self, indepVar, depVar, alpha=1):
"""Ridge constructor @param indepVar Array of independent variables @param depVar Vector of dependent variables"""
rc.REG.__init__(self, indepVar, depVa... | the_stack_v2_python_sparse | reg/ridge.py | smcdonald2013/hdstats-framework | train | 0 |
190e934f86f9696378d34ce76759b0e595837599 | [
"while True:\n measurement = self.generate_message()\n measurement.save()\n print('Storing new measurement')\n time.sleep(10)",
"meter = Meter.objects.get_or_create(name='4530303237303030303130313334353136')[0]\nmeasurement = Measurement()\nmeasurement.meter = meter\nmeasurement.power_usage_current = ... | <|body_start_0|>
while True:
measurement = self.generate_message()
measurement.save()
print('Storing new measurement')
time.sleep(10)
<|end_body_0|>
<|body_start_1|>
meter = Meter.objects.get_or_create(name='4530303237303030303130313334353136')[0]
... | "Class responsible for generating fake measurements just for development and debugging purposes | Generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
""""Class responsible for generating fake measurements just for development and debugging purposes"""
def start(self):
"""Starting the generator to create messages"""
<|body_0|>
def generate_message(self):
"""Genereates a new message"""
<|body_... | stack_v2_sparse_classes_36k_train_020305 | 1,335 | no_license | [
{
"docstring": "Starting the generator to create messages",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Genereates a new message",
"name": "generate_message",
"signature": "def generate_message(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002118 | Implement the Python class `Generator` described below.
Class description:
"Class responsible for generating fake measurements just for development and debugging purposes
Method signatures and docstrings:
- def start(self): Starting the generator to create messages
- def generate_message(self): Genereates a new messa... | Implement the Python class `Generator` described below.
Class description:
"Class responsible for generating fake measurements just for development and debugging purposes
Method signatures and docstrings:
- def start(self): Starting the generator to create messages
- def generate_message(self): Genereates a new messa... | 34f7c60d029b450e567150a8ed3714604a8504d0 | <|skeleton|>
class Generator:
""""Class responsible for generating fake measurements just for development and debugging purposes"""
def start(self):
"""Starting the generator to create messages"""
<|body_0|>
def generate_message(self):
"""Genereates a new message"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Generator:
""""Class responsible for generating fake measurements just for development and debugging purposes"""
def start(self):
"""Starting the generator to create messages"""
while True:
measurement = self.generate_message()
measurement.save()
print(... | the_stack_v2_python_sparse | src/processor/generator.py | maarten-kieft/ASMP | train | 5 |
0fb98998ddaeef5c4bbfdb856d3133c142f8a643 | [
"qapp_id = request.GET.get('qapp_id', 0)\nqapp = Qapp.objects.get(id=qapp_id)\nif check_can_edit(qapp, request.user):\n form = QappLeadForm({'qapp': qapp})\n ctx = {'form': form, 'qapp_id': qapp_id}\n return render(request, self.template_name, ctx)\nreason = 'You cannot edit this QAPP.'\nreturn HttpRespons... | <|body_start_0|>
qapp_id = request.GET.get('qapp_id', 0)
qapp = Qapp.objects.get(id=qapp_id)
if check_can_edit(qapp, request.user):
form = QappLeadForm({'qapp': qapp})
ctx = {'form': form, 'qapp_id': qapp_id}
return render(request, self.template_name, ctx)
... | Class for creating new QAPP Project Lead. | ProjectLeadCreate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectLeadCreate:
"""Class for creating new QAPP Project Lead."""
def get(self, request, *args, **kwargs):
"""Return a view with an empty form for creating a new Project Lead."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request wi... | stack_v2_sparse_classes_36k_train_020306 | 36,787 | no_license | [
{
"docstring": "Return a view with an empty form for creating a new Project Lead.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Process the post request with a new Project Lead form filled out.",
"name": "post",
"signature": "def post(self, re... | 2 | null | Implement the Python class `ProjectLeadCreate` described below.
Class description:
Class for creating new QAPP Project Lead.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return a view with an empty form for creating a new Project Lead.
- def post(self, request, *args, **kwargs): Proces... | Implement the Python class `ProjectLeadCreate` described below.
Class description:
Class for creating new QAPP Project Lead.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return a view with an empty form for creating a new Project Lead.
- def post(self, request, *args, **kwargs): Proces... | ee419afa3c9f4b9ef3b30b62b693cfac956ce5b4 | <|skeleton|>
class ProjectLeadCreate:
"""Class for creating new QAPP Project Lead."""
def get(self, request, *args, **kwargs):
"""Return a view with an empty form for creating a new Project Lead."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Process the post request wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectLeadCreate:
"""Class for creating new QAPP Project Lead."""
def get(self, request, *args, **kwargs):
"""Return a view with an empty form for creating a new Project Lead."""
qapp_id = request.GET.get('qapp_id', 0)
qapp = Qapp.objects.get(id=qapp_id)
if check_can_edit... | the_stack_v2_python_sparse | DataSearch/qar5/views.py | USEPA/FoodWaste | train | 1 |
23da8c801539429ab9b99b5f824be0a48e5b3828 | [
"if PatientPhysiotherapist.objects.filter(patient=patient_id).exists():\n return True\nreturn False",
"physiotherapist_id = request['physiotherapist_id']\nreturn_value = {'patient_id': patient_id, 'physiotherapist_id': physiotherapist_id}\nPatientService.is_valid_patient(patient_id)\nPhysiotherapistService.is_... | <|body_start_0|>
if PatientPhysiotherapist.objects.filter(patient=patient_id).exists():
return True
return False
<|end_body_0|>
<|body_start_1|>
physiotherapist_id = request['physiotherapist_id']
return_value = {'patient_id': patient_id, 'physiotherapist_id': physiotherapist... | Service class for patientphysiotherapist related operations | PatientPhysioService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientPhysioService:
"""Service class for patientphysiotherapist related operations"""
def check_if_patient_has_physio(patient_id):
"""Method that checks if patient has a physio or not :param patient_id: The id of the given patient :return: boolean value containing the answer"""
... | stack_v2_sparse_classes_36k_train_020307 | 1,946 | no_license | [
{
"docstring": "Method that checks if patient has a physio or not :param patient_id: The id of the given patient :return: boolean value containing the answer",
"name": "check_if_patient_has_physio",
"signature": "def check_if_patient_has_physio(patient_id)"
},
{
"docstring": "Method that associa... | 2 | null | Implement the Python class `PatientPhysioService` described below.
Class description:
Service class for patientphysiotherapist related operations
Method signatures and docstrings:
- def check_if_patient_has_physio(patient_id): Method that checks if patient has a physio or not :param patient_id: The id of the given pa... | Implement the Python class `PatientPhysioService` described below.
Class description:
Service class for patientphysiotherapist related operations
Method signatures and docstrings:
- def check_if_patient_has_physio(patient_id): Method that checks if patient has a physio or not :param patient_id: The id of the given pa... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class PatientPhysioService:
"""Service class for patientphysiotherapist related operations"""
def check_if_patient_has_physio(patient_id):
"""Method that checks if patient has a physio or not :param patient_id: The id of the given patient :return: boolean value containing the answer"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PatientPhysioService:
"""Service class for patientphysiotherapist related operations"""
def check_if_patient_has_physio(patient_id):
"""Method that checks if patient has a physio or not :param patient_id: The id of the given patient :return: boolean value containing the answer"""
if Patie... | the_stack_v2_python_sparse | backend/martin_helder/services/patient_physiotherapist_service.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
a581818271ed4eb61e44668eab368f07706a7291 | [
"self.running = True\nself.total = 0\nself.start = time.time()",
"self.running = True\nself.total = 0\nself.start = time.time()\nreturn self",
"if not self.running:\n self.running = True\n self.start = time.time()\nreturn self",
"if self.running:\n self.running = False\n self.total += time.time() ... | <|body_start_0|>
self.running = True
self.total = 0
self.start = time.time()
<|end_body_0|>
<|body_start_1|>
self.running = True
self.total = 0
self.start = time.time()
return self
<|end_body_1|>
<|body_start_2|>
if not self.running:
self.run... | Computes elapsed time. | Timer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timer:
"""Computes elapsed time."""
def __init__(self):
"""Initialize timer."""
<|body_0|>
def reset(self):
"""Reset timer to zero."""
<|body_1|>
def resume(self):
"""Resume timer."""
<|body_2|>
def stop(self):
"""Pause t... | stack_v2_sparse_classes_36k_train_020308 | 23,309 | permissive | [
{
"docstring": "Initialize timer.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Reset timer to zero.",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "Resume timer.",
"name": "resume",
"signature": "def resume(self)"
},
... | 5 | null | Implement the Python class `Timer` described below.
Class description:
Computes elapsed time.
Method signatures and docstrings:
- def __init__(self): Initialize timer.
- def reset(self): Reset timer to zero.
- def resume(self): Resume timer.
- def stop(self): Pause timer.
- def time(self): Get current timer time. | Implement the Python class `Timer` described below.
Class description:
Computes elapsed time.
Method signatures and docstrings:
- def __init__(self): Initialize timer.
- def reset(self): Reset timer to zero.
- def resume(self): Resume timer.
- def stop(self): Pause timer.
- def time(self): Get current timer time.
<|... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class Timer:
"""Computes elapsed time."""
def __init__(self):
"""Initialize timer."""
<|body_0|>
def reset(self):
"""Reset timer to zero."""
<|body_1|>
def resume(self):
"""Resume timer."""
<|body_2|>
def stop(self):
"""Pause t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Timer:
"""Computes elapsed time."""
def __init__(self):
"""Initialize timer."""
self.running = True
self.total = 0
self.start = time.time()
def reset(self):
"""Reset timer to zero."""
self.running = True
self.total = 0
self.start = time... | the_stack_v2_python_sparse | parlai/utils/misc.py | facebookresearch/ParlAI | train | 10,943 |
018a04344df4a0136436305cd4578c677735d4da | [
"nasa_frame = pd.read_csv(path, comment='#', dtype=str)\nsimple_pl = simple_str(planet_name)\nself.frame = pd.DataFrame()\nfor n in nasa_frame.index:\n simple_name = simple_str(nasa_frame.at[n, 'pl_name'])\n if simple_name == simple_pl:\n self.frame = nasa_frame.iloc[n]\n break\nif self.frame.sh... | <|body_start_0|>
nasa_frame = pd.read_csv(path, comment='#', dtype=str)
simple_pl = simple_str(planet_name)
self.frame = pd.DataFrame()
for n in nasa_frame.index:
simple_name = simple_str(nasa_frame.at[n, 'pl_name'])
if simple_name == simple_pl:
se... | This class can be used to read data from a CSV file downloaded from the NASA Exoplanet Archive, and return requested values from that data. ..module:: read_errors ..synopsis:: Read value errors out of the data pulled from the NASA file. ..module:: read_refs ..synopsis:: Parse the reference string associated with the da... | CustomNASA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomNASA:
"""This class can be used to read data from a CSV file downloaded from the NASA Exoplanet Archive, and return requested values from that data. ..module:: read_errors ..synopsis:: Read value errors out of the data pulled from the NASA file. ..module:: read_refs ..synopsis:: Parse the r... | stack_v2_sparse_classes_36k_train_020309 | 5,149 | no_license | [
{
"docstring": "Read a provided CSV filepath into a pandas DataFrame. :param path: The filepath to the NASA CSV file with data for multiple planets. :type path: str :param planet_name: The exoplanet to pull data from the NASA file for. :type planet_name: str",
"name": "__init__",
"signature": "def __ini... | 4 | stack_v2_sparse_classes_30k_train_014348 | Implement the Python class `CustomNASA` described below.
Class description:
This class can be used to read data from a CSV file downloaded from the NASA Exoplanet Archive, and return requested values from that data. ..module:: read_errors ..synopsis:: Read value errors out of the data pulled from the NASA file. ..modu... | Implement the Python class `CustomNASA` described below.
Class description:
This class can be used to read data from a CSV file downloaded from the NASA Exoplanet Archive, and return requested values from that data. ..module:: read_errors ..synopsis:: Read value errors out of the data pulled from the NASA file. ..modu... | a2daec6ec4a85fc15e6a9a602b94eb9f847381f1 | <|skeleton|>
class CustomNASA:
"""This class can be used to read data from a CSV file downloaded from the NASA Exoplanet Archive, and return requested values from that data. ..module:: read_errors ..synopsis:: Read value errors out of the data pulled from the NASA file. ..module:: read_refs ..synopsis:: Parse the r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomNASA:
"""This class can be used to read data from a CSV file downloaded from the NASA Exoplanet Archive, and return requested values from that data. ..module:: read_errors ..synopsis:: Read value errors out of the data pulled from the NASA file. ..module:: read_refs ..synopsis:: Parse the reference stri... | the_stack_v2_python_sparse | python/lib/CustomNASA.py | pforshay/exoplanets_org_work | train | 0 |
005ca7e6d893d461da61771e1136a4cfe5640463 | [
"if context is None:\n context = {}\npartner_id_obj = self.browse(cr, uid, partner_id)\nlocations = self.pool.get('stock.location').search(cr, uid, [('partner_id', '=', partner_id)])\nif not locations:\n partner_location_id = self.pool.get('stock.location').create(cr, uid, vals={'location_id': partner_id_obj.... | <|body_start_0|>
if context is None:
context = {}
partner_id_obj = self.browse(cr, uid, partner_id)
locations = self.pool.get('stock.location').search(cr, uid, [('partner_id', '=', partner_id)])
if not locations:
partner_location_id = self.pool.get('stock.location... | inherit res.partner for adds the functionally that customer has a location | res_partner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class res_partner:
"""inherit res.partner for adds the functionally that customer has a location"""
def _set_partner_customer_location(self, cr, uid, partner_id, context=None):
"""creates customer location for partner in arguments"""
<|body_0|>
def create(self, cr, uid, vals, ... | stack_v2_sparse_classes_36k_train_020310 | 4,053 | no_license | [
{
"docstring": "creates customer location for partner in arguments",
"name": "_set_partner_customer_location",
"signature": "def _set_partner_customer_location(self, cr, uid, partner_id, context=None)"
},
{
"docstring": "Check to create customer location",
"name": "create",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_020277 | Implement the Python class `res_partner` described below.
Class description:
inherit res.partner for adds the functionally that customer has a location
Method signatures and docstrings:
- def _set_partner_customer_location(self, cr, uid, partner_id, context=None): creates customer location for partner in arguments
- ... | Implement the Python class `res_partner` described below.
Class description:
inherit res.partner for adds the functionally that customer has a location
Method signatures and docstrings:
- def _set_partner_customer_location(self, cr, uid, partner_id, context=None): creates customer location for partner in arguments
- ... | 01c8294e969cce818a33fd06682560e0344c217c | <|skeleton|>
class res_partner:
"""inherit res.partner for adds the functionally that customer has a location"""
def _set_partner_customer_location(self, cr, uid, partner_id, context=None):
"""creates customer location for partner in arguments"""
<|body_0|>
def create(self, cr, uid, vals, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class res_partner:
"""inherit res.partner for adds the functionally that customer has a location"""
def _set_partner_customer_location(self, cr, uid, partner_id, context=None):
"""creates customer location for partner in arguments"""
if context is None:
context = {}
partner_... | the_stack_v2_python_sparse | Varios/alimentacion/__unported__/sale_follow_up/partner.py | ELNOGAL/GALIPAT_LUGO | train | 0 |
a29d55f28f67e079f3bac0e8738afaf07b9f5f40 | [
"from test_selenium_1220_01.test_web_weixin.page.add_member_page import AddMember\nself.wait_click(self._location_goto_add_member)\nself.find(self._location_goto_add_member).click()\nreturn AddMember(self.driver)",
"time.sleep(1)\nelements = self.finds(*self._location_member_list)\nmember_list = [i.get_attribute(... | <|body_start_0|>
from test_selenium_1220_01.test_web_weixin.page.add_member_page import AddMember
self.wait_click(self._location_goto_add_member)
self.find(self._location_goto_add_member).click()
return AddMember(self.driver)
<|end_body_0|>
<|body_start_1|>
time.sleep(1)
... | ContactPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取成员列表"""
<|body_1|>
def add_party(self):
"""添加部门"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
from test_selenium_1220_01.test_web_weixin.... | stack_v2_sparse_classes_36k_train_020311 | 1,688 | no_license | [
{
"docstring": "添加成员",
"name": "goto_add_member",
"signature": "def goto_add_member(self)"
},
{
"docstring": "获取成员列表",
"name": "get_member",
"signature": "def get_member(self)"
},
{
"docstring": "添加部门",
"name": "add_party",
"signature": "def add_party(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_021675 | Implement the Python class `ContactPage` described below.
Class description:
Implement the ContactPage class.
Method signatures and docstrings:
- def goto_add_member(self): 添加成员
- def get_member(self): 获取成员列表
- def add_party(self): 添加部门 | Implement the Python class `ContactPage` described below.
Class description:
Implement the ContactPage class.
Method signatures and docstrings:
- def goto_add_member(self): 添加成员
- def get_member(self): 获取成员列表
- def add_party(self): 添加部门
<|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员"... | 68ba225c6340764c21640b041248d27247ff67ef | <|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员"""
<|body_0|>
def get_member(self):
"""获取成员列表"""
<|body_1|>
def add_party(self):
"""添加部门"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactPage:
def goto_add_member(self):
"""添加成员"""
from test_selenium_1220_01.test_web_weixin.page.add_member_page import AddMember
self.wait_click(self._location_goto_add_member)
self.find(self._location_goto_add_member).click()
return AddMember(self.driver)
def g... | the_stack_v2_python_sparse | test_selenium_1220_01/test_web_weixin/page/contact_page.py | z944274972/hogwarts | train | 0 | |
a8cf61280870976c63495ff6eec51123d99177ca | [
"self.days_to_keep = days_to_keep\nself.scheduling_policy = scheduling_policy\nself.worm_retention_type = worm_retention_type",
"if dictionary is None:\n return None\ndays_to_keep = dictionary.get('daysToKeep')\nscheduling_policy = cohesity_management_sdk.models.scheduling_policy.SchedulingPolicy.from_dictiona... | <|body_start_0|>
self.days_to_keep = days_to_keep
self.scheduling_policy = scheduling_policy
self.worm_retention_type = worm_retention_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
days_to_keep = dictionary.get('daysToKeep')
scheduli... | Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specifies how many days to retain Snapshots on the Co... | DataMigrationPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataMigrationPolicy:
"""Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specif... | stack_v2_sparse_classes_36k_train_020312 | 2,842 | permissive | [
{
"docstring": "Constructor for the DataMigrationPolicy class",
"name": "__init__",
"signature": "def __init__(self, days_to_keep=None, scheduling_policy=None, worm_retention_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dicti... | 2 | null | Implement the Python class `DataMigrationPolicy` described below.
Class description:
Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attr... | Implement the Python class `DataMigrationPolicy` described below.
Class description:
Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attr... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DataMigrationPolicy:
"""Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataMigrationPolicy:
"""Implementation of the 'DataMigrationPolicy' model. Specifies settings for data migration in NAS environment. This also specifies the retention policy that should be applied to files after they have been moved to cohesity cluster. Attributes: days_to_keep (long|int): Specifies how many ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/data_migration_policy.py | cohesity/management-sdk-python | train | 24 |
0e75736743add8059cec445c7b5c76e389d92d80 | [
"expected = ['man']\nactual = get_top_n_words({'happy': 2, 'man': 3}, 1)\nself.assertEqual(expected, actual)",
"expected = ['happy', 'man']\nactual = get_top_n_words({'happy': 2, 'man': 2}, 2)\nself.assertEqual(expected, actual)\nexpected = ['happy']\nactual = get_top_n_words({'happy': 2, 'man': 2}, 1)\nself.asse... | <|body_start_0|>
expected = ['man']
actual = get_top_n_words({'happy': 2, 'man': 3}, 1)
self.assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
expected = ['happy', 'man']
actual = get_top_n_words({'happy': 2, 'man': 2}, 2)
self.assertEqual(expected, actual)
... | Tests get top number of words function | GetTopNWordsTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetTopNWordsTest:
"""Tests get top number of words function"""
def test_get_top_n_words_ideal(self):
"""Ideal get top number of words scenario"""
<|body_0|>
def test_get_top_n_words_same_frequency(self):
"""Get top number of words with the same frequency check"""... | stack_v2_sparse_classes_36k_train_020313 | 2,104 | permissive | [
{
"docstring": "Ideal get top number of words scenario",
"name": "test_get_top_n_words_ideal",
"signature": "def test_get_top_n_words_ideal(self)"
},
{
"docstring": "Get top number of words with the same frequency check",
"name": "test_get_top_n_words_same_frequency",
"signature": "def t... | 6 | stack_v2_sparse_classes_30k_train_018817 | Implement the Python class `GetTopNWordsTest` described below.
Class description:
Tests get top number of words function
Method signatures and docstrings:
- def test_get_top_n_words_ideal(self): Ideal get top number of words scenario
- def test_get_top_n_words_same_frequency(self): Get top number of words with the sa... | Implement the Python class `GetTopNWordsTest` described below.
Class description:
Tests get top number of words function
Method signatures and docstrings:
- def test_get_top_n_words_ideal(self): Ideal get top number of words scenario
- def test_get_top_n_words_same_frequency(self): Get top number of words with the sa... | ada4bec878dd1cbc19058cb4e87893946ae21498 | <|skeleton|>
class GetTopNWordsTest:
"""Tests get top number of words function"""
def test_get_top_n_words_ideal(self):
"""Ideal get top number of words scenario"""
<|body_0|>
def test_get_top_n_words_same_frequency(self):
"""Get top number of words with the same frequency check"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetTopNWordsTest:
"""Tests get top number of words function"""
def test_get_top_n_words_ideal(self):
"""Ideal get top number of words scenario"""
expected = ['man']
actual = get_top_n_words({'happy': 2, 'man': 3}, 1)
self.assertEqual(expected, actual)
def test_get_top... | the_stack_v2_python_sparse | lab_1/get_top_n_words_test.py | WhiteJaeger/2020-2-level-labs | train | 0 |
5e71098618f348a7e9e63f217fd64529747478bf | [
"if not data:\n return data\nreturn cls(**data)",
"result: dict = self.dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none)\nif '_id' not in result and 'id' not in result:\n result['_... | <|body_start_0|>
if not data:
return data
return cls(**data)
<|end_body_0|>
<|body_start_1|>
result: dict = self.dict(include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclud... | Class for MongoDB (class data view) | BaseDBModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseDBModel:
"""Class for MongoDB (class data view)"""
def from_db(cls, *, data: dict):
"""Method that using in repositories when converting result from MongoDB"""
<|body_0|>
def to_db(self, *, include: typing.Union['pydantic.typing.AbstractSetIntStr', 'pydantic.typing.M... | stack_v2_sparse_classes_36k_train_020314 | 2,328 | permissive | [
{
"docstring": "Method that using in repositories when converting result from MongoDB",
"name": "from_db",
"signature": "def from_db(cls, *, data: dict)"
},
{
"docstring": "Preparing data for MongoDB",
"name": "to_db",
"signature": "def to_db(self, *, include: typing.Union['pydantic.typi... | 2 | stack_v2_sparse_classes_30k_train_008818 | Implement the Python class `BaseDBModel` described below.
Class description:
Class for MongoDB (class data view)
Method signatures and docstrings:
- def from_db(cls, *, data: dict): Method that using in repositories when converting result from MongoDB
- def to_db(self, *, include: typing.Union['pydantic.typing.Abstra... | Implement the Python class `BaseDBModel` described below.
Class description:
Class for MongoDB (class data view)
Method signatures and docstrings:
- def from_db(cls, *, data: dict): Method that using in repositories when converting result from MongoDB
- def to_db(self, *, include: typing.Union['pydantic.typing.Abstra... | 8f4fbbe6f57c4ef62c7653bafb52612bfcb85fb1 | <|skeleton|>
class BaseDBModel:
"""Class for MongoDB (class data view)"""
def from_db(cls, *, data: dict):
"""Method that using in repositories when converting result from MongoDB"""
<|body_0|>
def to_db(self, *, include: typing.Union['pydantic.typing.AbstractSetIntStr', 'pydantic.typing.M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseDBModel:
"""Class for MongoDB (class data view)"""
def from_db(cls, *, data: dict):
"""Method that using in repositories when converting result from MongoDB"""
if not data:
return data
return cls(**data)
def to_db(self, *, include: typing.Union['pydantic.typin... | the_stack_v2_python_sparse | fastapi_mongodb/models.py | flavioribs/fastapi_mongodb | train | 0 |
82394f47d07bd12e96e80790941d0a2dc086ffca | [
"kargs.update(dict(watch_list=goals))\nkargs.update(dict(success=success))\nsuper(GoalMonitor, self)._post_init(**kargs)",
"report('ALL GOALS SATISIFIED')\nself.stop()\nself.universe.halt()"
] | <|body_start_0|>
kargs.update(dict(watch_list=goals))
kargs.update(dict(success=success))
super(GoalMonitor, self)._post_init(**kargs)
<|end_body_0|>
<|body_start_1|>
report('ALL GOALS SATISIFIED')
self.stop()
self.universe.halt()
<|end_body_1|>
| the Goal Service is a watchdog who shuts down the universe when all it's goals are completed. | GoalMonitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoalMonitor:
"""the Goal Service is a watchdog who shuts down the universe when all it's goals are completed."""
def _post_init(self, goals=[], success=None, **kargs):
"""alias watchdog's "watch_list" argument to "goals" for a more intuitive api."""
<|body_0|>
def bark(s... | stack_v2_sparse_classes_36k_train_020315 | 1,460 | no_license | [
{
"docstring": "alias watchdog's \"watch_list\" argument to \"goals\" for a more intuitive api.",
"name": "_post_init",
"signature": "def _post_init(self, goals=[], success=None, **kargs)"
},
{
"docstring": "bark() is called by watchdog when everything in the goal_list tests True",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_015246 | Implement the Python class `GoalMonitor` described below.
Class description:
the Goal Service is a watchdog who shuts down the universe when all it's goals are completed.
Method signatures and docstrings:
- def _post_init(self, goals=[], success=None, **kargs): alias watchdog's "watch_list" argument to "goals" for a ... | Implement the Python class `GoalMonitor` described below.
Class description:
the Goal Service is a watchdog who shuts down the universe when all it's goals are completed.
Method signatures and docstrings:
- def _post_init(self, goals=[], success=None, **kargs): alias watchdog's "watch_list" argument to "goals" for a ... | 324b5c057a2570f84cde95ff4831e59b839858a1 | <|skeleton|>
class GoalMonitor:
"""the Goal Service is a watchdog who shuts down the universe when all it's goals are completed."""
def _post_init(self, goals=[], success=None, **kargs):
"""alias watchdog's "watch_list" argument to "goals" for a more intuitive api."""
<|body_0|>
def bark(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoalMonitor:
"""the Goal Service is a watchdog who shuts down the universe when all it's goals are completed."""
def _post_init(self, goals=[], success=None, **kargs):
"""alias watchdog's "watch_list" argument to "goals" for a more intuitive api."""
kargs.update(dict(watch_list=goals))
... | the_stack_v2_python_sparse | lib/cortex/services/goalmonitor.py | mattvonrocketstein/cortex | train | 1 |
dd61656fd3c151a1e02beae894ea6e432780eaa2 | [
"super(Bottleneck, self).__init__()\nself.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False, groups=args.num_groups)\nself.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, groups=args.num_groups)\nself.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False,... | <|body_start_0|>
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False, groups=args.num_groups)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, groups=args.num_groups)
self.conv3 = nn.Conv2d(plane... | A bottleneck block for Resnets. Used in Resnet-50, Resnet-101, and Resnet-152. | Bottleneck | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bottleneck:
"""A bottleneck block for Resnets. Used in Resnet-50, Resnet-101, and Resnet-152."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None):
"""Initializes the Bottleneck. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): T... | stack_v2_sparse_classes_36k_train_020316 | 2,091 | permissive | [
{
"docstring": "Initializes the Bottleneck. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The number of filters to use in convolutions and therefore the depth (number of channels) of the output. stride(int): The stride to use in the convolutions. downsample(func): The downs... | 2 | stack_v2_sparse_classes_30k_train_007338 | Implement the Python class `Bottleneck` described below.
Class description:
A bottleneck block for Resnets. Used in Resnet-50, Resnet-101, and Resnet-152.
Method signatures and docstrings:
- def __init__(self, args, inplanes, planes, stride=1, downsample=None): Initializes the Bottleneck. Arguments: inplanes(int): Th... | Implement the Python class `Bottleneck` described below.
Class description:
A bottleneck block for Resnets. Used in Resnet-50, Resnet-101, and Resnet-152.
Method signatures and docstrings:
- def __init__(self, args, inplanes, planes, stride=1, downsample=None): Initializes the Bottleneck. Arguments: inplanes(int): Th... | 12bace8fd6ce9c5bb129fd0d30a46a00a2f7b054 | <|skeleton|>
class Bottleneck:
"""A bottleneck block for Resnets. Used in Resnet-50, Resnet-101, and Resnet-152."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None):
"""Initializes the Bottleneck. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bottleneck:
"""A bottleneck block for Resnets. Used in Resnet-50, Resnet-101, and Resnet-152."""
def __init__(self, args, inplanes, planes, stride=1, downsample=None):
"""Initializes the Bottleneck. Arguments: inplanes(int): The depth (number of channels) of the input. planes(int): The number of ... | the_stack_v2_python_sparse | onconet/models/blocks/bottleneck.py | yala/Mirai | train | 66 |
cd1718512ffec446355644b1ccb459abbb4db480 | [
"Part.__init__(self, config_, simulator, name)\nfor muscle_config in config_['muscles']:\n self.muscles.append(eval(self.muscle_type))\nself.connection_matrix = config_['connection_matrix']",
"for i in range(len(self.muscles)):\n if len(self.connection_matrix[self.muscles[i].name]) != len(brain_output):\n ... | <|body_start_0|>
Part.__init__(self, config_, simulator, name)
for muscle_config in config_['muscles']:
self.muscles.append(eval(self.muscle_type))
self.connection_matrix = config_['connection_matrix']
<|end_body_0|>
<|body_start_1|>
for i in range(len(self.muscles)):
... | This class represents a generic leg and its current behaviour in the control process | Leg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Leg:
"""This class represents a generic leg and its current behaviour in the control process"""
def __init__(self, config_, simulator, name):
"""Class initialization :param config_: Dictionary containing part parameters :param simulator: String name of the simulator class utility :pa... | stack_v2_sparse_classes_36k_train_020317 | 8,402 | no_license | [
{
"docstring": "Class initialization :param config_: Dictionary containing part parameters :param simulator: String name of the simulator class utility :param name: String name of the part",
"name": "__init__",
"signature": "def __init__(self, config_, simulator, name)"
},
{
"docstring": "Update... | 2 | null | Implement the Python class `Leg` described below.
Class description:
This class represents a generic leg and its current behaviour in the control process
Method signatures and docstrings:
- def __init__(self, config_, simulator, name): Class initialization :param config_: Dictionary containing part parameters :param ... | Implement the Python class `Leg` described below.
Class description:
This class represents a generic leg and its current behaviour in the control process
Method signatures and docstrings:
- def __init__(self, config_, simulator, name): Class initialization :param config_: Dictionary containing part parameters :param ... | f4f212a7533a63d1148068bacf1cc13d3f64db49 | <|skeleton|>
class Leg:
"""This class represents a generic leg and its current behaviour in the control process"""
def __init__(self, config_, simulator, name):
"""Class initialization :param config_: Dictionary containing part parameters :param simulator: String name of the simulator class utility :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Leg:
"""This class represents a generic leg and its current behaviour in the control process"""
def __init__(self, config_, simulator, name):
"""Class initialization :param config_: Dictionary containing part parameters :param simulator: String name of the simulator class utility :param name: Str... | the_stack_v2_python_sparse | src/musculoskeletals/body.py | mahedjaved/mouse_locomotion | train | 0 |
3f0964fd8e66e7203a415d0a5525c3b9ae0e3d66 | [
"username = response.get('user')\nif self.setting('USERNAME_WITH_TEAM', True):\n match = re.search('//([^.]+)\\\\.slack\\\\.com', response['url'])\n username = '{0}@{1}'.format(username, match.group(1))\nout = {'username': username}\nif 'profile' in response:\n out.update({'email': response['profile'].get(... | <|body_start_0|>
username = response.get('user')
if self.setting('USERNAME_WITH_TEAM', True):
match = re.search('//([^.]+)\\.slack\\.com', response['url'])
username = '{0}@{1}'.format(username, match.group(1))
out = {'username': username}
if 'profile' in response:... | Slack OAuth authentication backend | SlackOAuth2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlackOAuth2:
"""Slack OAuth authentication backend"""
def get_user_details(self, response):
"""Return user details from Slack account"""
<|body_0|>
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_020318 | 2,414 | permissive | [
{
"docstring": "Return user details from Slack account",
"name": "get_user_details",
"signature": "def get_user_details(self, response)"
},
{
"docstring": "Loads user data from service",
"name": "user_data",
"signature": "def user_data(self, access_token, *args, **kwargs)"
}
] | 2 | null | Implement the Python class `SlackOAuth2` described below.
Class description:
Slack OAuth authentication backend
Method signatures and docstrings:
- def get_user_details(self, response): Return user details from Slack account
- def user_data(self, access_token, *args, **kwargs): Loads user data from service | Implement the Python class `SlackOAuth2` described below.
Class description:
Slack OAuth authentication backend
Method signatures and docstrings:
- def get_user_details(self, response): Return user details from Slack account
- def user_data(self, access_token, *args, **kwargs): Loads user data from service
<|skeleto... | 4d8abe7bafefae06a0e462e6a47631c2f8a1d361 | <|skeleton|>
class SlackOAuth2:
"""Slack OAuth authentication backend"""
def get_user_details(self, response):
"""Return user details from Slack account"""
<|body_0|>
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlackOAuth2:
"""Slack OAuth authentication backend"""
def get_user_details(self, response):
"""Return user details from Slack account"""
username = response.get('user')
if self.setting('USERNAME_WITH_TEAM', True):
match = re.search('//([^.]+)\\.slack\\.com', response['... | the_stack_v2_python_sparse | virtual/lib/python3.6/site-packages/social/backends/slack.py | virginiah894/Instagram-clone | train | 3 |
48f205f42f18d8fdaa43b57c6a273ed97b29ef19 | [
"if not super(DialogueSentenceView, self).parse_request():\n return False\nself.template_file = getattr(self.form_class.Meta, 'form_template', 'dialogue_sentence_form.html')\nreturn True",
"super(DialogueSentenceView, self).query_view_data()\nif self.form:\n self.form.fields['dialogue'].initial = self.reque... | <|body_start_0|>
if not super(DialogueSentenceView, self).parse_request():
return False
self.template_file = getattr(self.form_class.Meta, 'form_template', 'dialogue_sentence_form.html')
return True
<|end_body_0|>
<|body_start_1|>
super(DialogueSentenceView, self).query_view... | This object deal with dialogue_sentence's edit forms and views. | DialogueSentenceView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DialogueSentenceView:
"""This object deal with dialogue_sentence's edit forms and views."""
def parse_request(self):
"""Parse request data. Returns: boolean: Parse success."""
<|body_0|>
def query_view_data(self):
"""Get db instance for view. Returns: None"""
... | stack_v2_sparse_classes_36k_train_020319 | 2,540 | permissive | [
{
"docstring": "Parse request data. Returns: boolean: Parse success.",
"name": "parse_request",
"signature": "def parse_request(self)"
},
{
"docstring": "Get db instance for view. Returns: None",
"name": "query_view_data",
"signature": "def query_view_data(self)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_007465 | Implement the Python class `DialogueSentenceView` described below.
Class description:
This object deal with dialogue_sentence's edit forms and views.
Method signatures and docstrings:
- def parse_request(self): Parse request data. Returns: boolean: Parse success.
- def query_view_data(self): Get db instance for view.... | Implement the Python class `DialogueSentenceView` described below.
Class description:
This object deal with dialogue_sentence's edit forms and views.
Method signatures and docstrings:
- def parse_request(self): Parse request data. Returns: boolean: Parse success.
- def query_view_data(self): Get db instance for view.... | 294da6fb73cb04c62e5ba6eefe49b595ca76832a | <|skeleton|>
class DialogueSentenceView:
"""This object deal with dialogue_sentence's edit forms and views."""
def parse_request(self):
"""Parse request data. Returns: boolean: Parse success."""
<|body_0|>
def query_view_data(self):
"""Get db instance for view. Returns: None"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DialogueSentenceView:
"""This object deal with dialogue_sentence's edit forms and views."""
def parse_request(self):
"""Parse request data. Returns: boolean: Parse success."""
if not super(DialogueSentenceView, self).parse_request():
return False
self.template_file = g... | the_stack_v2_python_sparse | muddery/worlddata/editor/dialogue_sentence_view.py | noahzaozao/muddery | train | 0 |
7d62f4e02a6ea5530ca06b8f316cc604a4ed8b5b | [
"if blob.get('remaining', 0) == 1:\n self.rebuild = True\nif update:\n self.kwargs['rebuild'] = self.rebuild\n self.rebuild = False\naccept_prob = max(0.5, blob['accept']) / self.kwargs['walks']\ndelay = self.nlive // 10 - 1\nn_target = getattr(_SamplingContainer, 'naccept', 60)\nself.walks = (self.walks *... | <|body_start_0|>
if blob.get('remaining', 0) == 1:
self.rebuild = True
if update:
self.kwargs['rebuild'] = self.rebuild
self.rebuild = False
accept_prob = max(0.5, blob['accept']) / self.kwargs['walks']
delay = self.nlive // 10 - 1
n_target = g... | Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :code:`kwargs` passed to the evolve method. Not... | LivePointSampler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LivePointSampler:
"""Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :co... | stack_v2_sparse_classes_36k_train_020320 | 25,054 | permissive | [
{
"docstring": "Update the proposal parameters based on the number of accepted steps and MCMC chain length. There are a number of logical checks performed: - if the ACT tracking rwalk method is being used and any parallel process has an empty cache, set the :code:`rebuild` flag to force the cache to rebuild at ... | 2 | stack_v2_sparse_classes_30k_train_019794 | Implement the Python class `LivePointSampler` described below.
Class description:
Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`... | Implement the Python class `LivePointSampler` described below.
Class description:
Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`... | 9c1dda6cc1510692ce4ac75c608de5fae53e971c | <|skeleton|>
class LivePointSampler:
"""Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LivePointSampler:
"""Modified version of dynesty UnitCubeSampler that adapts the MCMC length in addition to the proposal scale, this corresponds to :code:`bound=live`. In order to support live-point based proposals, e.g., differential evolution (:code:`diff`), the live points are added to the :code:`kwargs` p... | the_stack_v2_python_sparse | bilby/core/sampler/dynesty_utils.py | khunsang/bilby | train | 0 |
e8346424c37be082e39871389b89b55d7120353c | [
"n = len(prices)\nmax_profit = 0\nfor buy in range(n - 1):\n curr_profit = 0\n for sell in range(buy + 1, n):\n if prices[sell] - prices[buy] > curr_profit:\n curr_profit = prices[sell] - prices[buy]\n if curr_profit > max_profit:\n max_profit = curr_profit\nreturn max_profit",
"... | <|body_start_0|>
n = len(prices)
max_profit = 0
for buy in range(n - 1):
curr_profit = 0
for sell in range(buy + 1, n):
if prices[sell] - prices[buy] > curr_profit:
curr_profit = prices[sell] - prices[buy]
if curr_profit > m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
"""Brute force"""
<|body_0|>
def maxProfit2(self, prices):
"""Single pass"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(prices)
max_profit = 0
for buy in range(n - 1):
curr... | stack_v2_sparse_classes_36k_train_020321 | 1,005 | no_license | [
{
"docstring": "Brute force",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": "Single pass",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): Brute force
- def maxProfit2(self, prices): Single pass | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): Brute force
- def maxProfit2(self, prices): Single pass
<|skeleton|>
class Solution:
def maxProfit(self, prices):
"""Brute force"""
... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
"""Brute force"""
<|body_0|>
def maxProfit2(self, prices):
"""Single pass"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
"""Brute force"""
n = len(prices)
max_profit = 0
for buy in range(n - 1):
curr_profit = 0
for sell in range(buy + 1, n):
if prices[sell] - prices[buy] > curr_profit:
curr_profit =... | the_stack_v2_python_sparse | Best Time to Buy and Sell Stock.py | aulee888/LeetCode | train | 0 | |
f32108115d31efc5130237e9f523d05e7255a515 | [
"if State.__instance is None:\n State.__instance = State()\nreturn State.__instance",
"if State.__instance is not None:\n raise Exception('This class is a singleton!')\nelse:\n State.__instance = self\n self.stocks_realtime_data = RealtimeDataState()\n self.futures_realtime_data = RealtimeDataState... | <|body_start_0|>
if State.__instance is None:
State.__instance = State()
return State.__instance
<|end_body_0|>
<|body_start_1|>
if State.__instance is not None:
raise Exception('This class is a singleton!')
else:
State.__instance = self
s... | State | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class State:
def getInstance() -> State:
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if State.__instance is None:
State.__instance = State()
... | stack_v2_sparse_classes_36k_train_020322 | 903 | no_license | [
{
"docstring": "Static access method.",
"name": "getInstance",
"signature": "def getInstance() -> State"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010272 | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def getInstance() -> State: Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `State` described below.
Class description:
Implement the State class.
Method signatures and docstrings:
- def getInstance() -> State: Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class State:
def getInstance() -> State:
"""Static acc... | a18922ebcc54af461ec9123ff0300ba2e0d1a044 | <|skeleton|>
class State:
def getInstance() -> State:
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class State:
def getInstance() -> State:
"""Static access method."""
if State.__instance is None:
State.__instance = State()
return State.__instance
def __init__(self):
"""Virtually private constructor."""
if State.__instance is not None:
raise Ex... | the_stack_v2_python_sparse | finance_app/ui/state/main.py | lukaskellerstein/FinanceApp | train | 0 | |
e3e96ce69f83555950bfde5c9626f9aff1943b09 | [
"i = 0\nfor i, val in enumerate(filter(lambda x: x, nums)):\n nums[i] = val\nfor i in range(i + 1, len(nums)):\n nums[i] = 0",
"if not nums:\n return 0\nj = 0\nfor i, val in enumerate(nums):\n if nums[i] != 0:\n nums[j], nums[i] = (nums[i], nums[j])\n j += 1"
] | <|body_start_0|>
i = 0
for i, val in enumerate(filter(lambda x: x, nums)):
nums[i] = val
for i in range(i + 1, len(nums)):
nums[i] = 0
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
j = 0
for i, val in enumerate(nums):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_... | stack_v2_sparse_classes_36k_train_020323 | 820 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes2",
"signature": "def moveZeroes2(self, nums: List[int]) -> None"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
... | 2 | stack_v2_sparse_classes_30k_train_017542 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums): :type nums: List[int] :rtype: void Do not retu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums): :type nums: List[int] :rtype: void Do not retu... | f90526c9b073165b86b933cdf7d1dc496e68f2c6 | <|skeleton|>
class Solution:
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
i = 0
for i, val in enumerate(filter(lambda x: x, nums)):
nums[i] = val
for i in range(i + 1, len(nums)):
nums[i] = 0
def moveZeroe... | the_stack_v2_python_sparse | 0283.py | mach8686devops/leetcode-100 | train | 0 | |
65e234d719cc214e5dc0196fa270295bbff27cd2 | [
"if not hasattr(self, '_proofread_index_ns') or not hasattr(self, '_proofread_page_ns') or (not hasattr(self, '_proofread_levels')):\n pirequest = self._request(expiry=pywikibot.config.API_config_expiry if expiry is False else expiry, parameters={'action': 'query', 'meta': 'proofreadinfo'})\n pidata = pireque... | <|body_start_0|>
if not hasattr(self, '_proofread_index_ns') or not hasattr(self, '_proofread_page_ns') or (not hasattr(self, '_proofread_levels')):
pirequest = self._request(expiry=pywikibot.config.API_config_expiry if expiry is False else expiry, parameters={'action': 'query', 'meta': 'proofreadin... | APISite mixin for ProofreadPage extension. | ProofreadPageMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProofreadPageMixin:
"""APISite mixin for ProofreadPage extension."""
def _cache_proofreadinfo(self, expiry=False) -> None:
"""Retrieve proofreadinfo from site and cache response. Applicable only to sites with ProofreadPage extension installed. The following info is returned by the qu... | stack_v2_sparse_classes_36k_train_020324 | 28,091 | permissive | [
{
"docstring": "Retrieve proofreadinfo from site and cache response. Applicable only to sites with ProofreadPage extension installed. The following info is returned by the query and cached: - self._proofread_index_ns: Index Namespace - self._proofread_page_ns: Page Namespace - self._proofread_levels: a dictiona... | 4 | null | Implement the Python class `ProofreadPageMixin` described below.
Class description:
APISite mixin for ProofreadPage extension.
Method signatures and docstrings:
- def _cache_proofreadinfo(self, expiry=False) -> None: Retrieve proofreadinfo from site and cache response. Applicable only to sites with ProofreadPage exte... | Implement the Python class `ProofreadPageMixin` described below.
Class description:
APISite mixin for ProofreadPage extension.
Method signatures and docstrings:
- def _cache_proofreadinfo(self, expiry=False) -> None: Retrieve proofreadinfo from site and cache response. Applicable only to sites with ProofreadPage exte... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class ProofreadPageMixin:
"""APISite mixin for ProofreadPage extension."""
def _cache_proofreadinfo(self, expiry=False) -> None:
"""Retrieve proofreadinfo from site and cache response. Applicable only to sites with ProofreadPage extension installed. The following info is returned by the qu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProofreadPageMixin:
"""APISite mixin for ProofreadPage extension."""
def _cache_proofreadinfo(self, expiry=False) -> None:
"""Retrieve proofreadinfo from site and cache response. Applicable only to sites with ProofreadPage extension installed. The following info is returned by the query and cache... | the_stack_v2_python_sparse | pywikibot/site/_extensions.py | wikimedia/pywikibot | train | 432 |
1211e5b131221213cb19ce2d4b47a69eb29ed613 | [
"super().__init__(infile, outfile)\nself.infile2 = infile2\nself._default_method = 'fastqutils'",
"self.install_tool('fastqutils')\nif self.infile2 is not None:\n cmd = 'fastqutils tobam -1 {} -2 {} -o {}'.format(self.infile, self.infile2, self.outfile)\nelse:\n cmd = 'fastqutils tobam -1 {} -o {}'.format(s... | <|body_start_0|>
super().__init__(infile, outfile)
self.infile2 = infile2
self._default_method = 'fastqutils'
<|end_body_0|>
<|body_start_1|>
self.install_tool('fastqutils')
if self.infile2 is not None:
cmd = 'fastqutils tobam -1 {} -2 {} -o {}'.format(self.infile, s... | Convert :term:`FASTQ` to :term:`BAM` | FASTQ2BAM | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FASTQ2BAM:
"""Convert :term:`FASTQ` to :term:`BAM`"""
def __init__(self, infile, outfile, infile2=None, *args, **kwargs):
""":param str infile: The path to the input FASTA file. :param str outfile: The path to the output file."""
<|body_0|>
def _method_fastqutils(self, *... | stack_v2_sparse_classes_36k_train_020325 | 1,716 | permissive | [
{
"docstring": ":param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.",
"name": "__init__",
"signature": "def __init__(self, infile, outfile, infile2=None, *args, **kwargs)"
},
{
"docstring": "Converts a fastq file to an unaligned bam file",
"n... | 2 | stack_v2_sparse_classes_30k_train_016628 | Implement the Python class `FASTQ2BAM` described below.
Class description:
Convert :term:`FASTQ` to :term:`BAM`
Method signatures and docstrings:
- def __init__(self, infile, outfile, infile2=None, *args, **kwargs): :param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.
... | Implement the Python class `FASTQ2BAM` described below.
Class description:
Convert :term:`FASTQ` to :term:`BAM`
Method signatures and docstrings:
- def __init__(self, infile, outfile, infile2=None, *args, **kwargs): :param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.
... | 60a746290e763fd1041732dab0bda123841e5b26 | <|skeleton|>
class FASTQ2BAM:
"""Convert :term:`FASTQ` to :term:`BAM`"""
def __init__(self, infile, outfile, infile2=None, *args, **kwargs):
""":param str infile: The path to the input FASTA file. :param str outfile: The path to the output file."""
<|body_0|>
def _method_fastqutils(self, *... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FASTQ2BAM:
"""Convert :term:`FASTQ` to :term:`BAM`"""
def __init__(self, infile, outfile, infile2=None, *args, **kwargs):
""":param str infile: The path to the input FASTA file. :param str outfile: The path to the output file."""
super().__init__(infile, outfile)
self.infile2 = in... | the_stack_v2_python_sparse | bioconvert/fastq2bam.py | ddesvillechabrol/bioconvert | train | 1 |
1a1a5347f97209d4ed460a704171aefcfaa72fb1 | [
"watchlist_name = kwargs.get('watchlist_name').replace('/', '%2F')\nlogger.debug(watchlist_name)\nreturn self.url().format(watchlist_name)",
"response = response.json()['response']\nsyms = response['watchlists']['watchlist']['watchlistitem']\nsyms = list(map(lambda d: d['instrument']['sym'], syms))\nreturn syms"
... | <|body_start_0|>
watchlist_name = kwargs.get('watchlist_name').replace('/', '%2F')
logger.debug(watchlist_name)
return self.url().format(watchlist_name)
<|end_body_0|>
<|body_start_1|>
response = response.json()['response']
syms = response['watchlists']['watchlist']['watchlistit... | Get the symbols from some watchlist | GetWatchlist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetWatchlist:
"""Get the symbols from some watchlist"""
def resolve(self, **kwargs):
"""Inject the account number into the call"""
<|body_0|>
def extract(self, response):
"""Extract certain fields from response"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_020326 | 3,947 | permissive | [
{
"docstring": "Inject the account number into the call",
"name": "resolve",
"signature": "def resolve(self, **kwargs)"
},
{
"docstring": "Extract certain fields from response",
"name": "extract",
"signature": "def extract(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003166 | Implement the Python class `GetWatchlist` described below.
Class description:
Get the symbols from some watchlist
Method signatures and docstrings:
- def resolve(self, **kwargs): Inject the account number into the call
- def extract(self, response): Extract certain fields from response | Implement the Python class `GetWatchlist` described below.
Class description:
Get the symbols from some watchlist
Method signatures and docstrings:
- def resolve(self, **kwargs): Inject the account number into the call
- def extract(self, response): Extract certain fields from response
<|skeleton|>
class GetWatchlis... | 46fafdd240ed1d2a65686f19b8734328f67fca9e | <|skeleton|>
class GetWatchlist:
"""Get the symbols from some watchlist"""
def resolve(self, **kwargs):
"""Inject the account number into the call"""
<|body_0|>
def extract(self, response):
"""Extract certain fields from response"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetWatchlist:
"""Get the symbols from some watchlist"""
def resolve(self, **kwargs):
"""Inject the account number into the call"""
watchlist_name = kwargs.get('watchlist_name').replace('/', '%2F')
logger.debug(watchlist_name)
return self.url().format(watchlist_name)
d... | the_stack_v2_python_sparse | ally/Watchlist/methods.py | alienbrett/PyAlly | train | 68 |
5023692fbd6f290837af53194815254f3106ce3b | [
"self.screen = screen\nself.screen_rect = screen.get_rect()\nself.set = set\nself.stats = stats\nself.text_color = (255, 158, 53)\nself.font = pygame.font.Font('wd.ttf', 38)\nself.prep_score()\nself.prep_high_score()\nself.prep_level()\nself.prep_ships()",
"rounded_score = round(self.stats.score)\nscore_str = '得分... | <|body_start_0|>
self.screen = screen
self.screen_rect = screen.get_rect()
self.set = set
self.stats = stats
self.text_color = (255, 158, 53)
self.font = pygame.font.Font('wd.ttf', 38)
self.prep_score()
self.prep_high_score()
self.prep_level()
... | 显示得分信息的类 | Scoreboard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scoreboard:
"""显示得分信息的类"""
def __init__(self, set, screen, stats):
"""初始化显示得分涉及的属性"""
<|body_0|>
def prep_score(self):
"""将得分绘制成图"""
<|body_1|>
def prep_high_score(self):
"""将最高得分转换成渲染图像"""
<|body_2|>
def prep_level(self):
... | stack_v2_sparse_classes_36k_train_020327 | 2,986 | no_license | [
{
"docstring": "初始化显示得分涉及的属性",
"name": "__init__",
"signature": "def __init__(self, set, screen, stats)"
},
{
"docstring": "将得分绘制成图",
"name": "prep_score",
"signature": "def prep_score(self)"
},
{
"docstring": "将最高得分转换成渲染图像",
"name": "prep_high_score",
"signature": "def p... | 6 | stack_v2_sparse_classes_30k_train_004219 | Implement the Python class `Scoreboard` described below.
Class description:
显示得分信息的类
Method signatures and docstrings:
- def __init__(self, set, screen, stats): 初始化显示得分涉及的属性
- def prep_score(self): 将得分绘制成图
- def prep_high_score(self): 将最高得分转换成渲染图像
- def prep_level(self): 将等级转换为渲染图像
- def prep_ships(self): 显示还剩下多少飞船
-... | Implement the Python class `Scoreboard` described below.
Class description:
显示得分信息的类
Method signatures and docstrings:
- def __init__(self, set, screen, stats): 初始化显示得分涉及的属性
- def prep_score(self): 将得分绘制成图
- def prep_high_score(self): 将最高得分转换成渲染图像
- def prep_level(self): 将等级转换为渲染图像
- def prep_ships(self): 显示还剩下多少飞船
-... | 6fb41d41e1f55cba46412375e4a947849cadb548 | <|skeleton|>
class Scoreboard:
"""显示得分信息的类"""
def __init__(self, set, screen, stats):
"""初始化显示得分涉及的属性"""
<|body_0|>
def prep_score(self):
"""将得分绘制成图"""
<|body_1|>
def prep_high_score(self):
"""将最高得分转换成渲染图像"""
<|body_2|>
def prep_level(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scoreboard:
"""显示得分信息的类"""
def __init__(self, set, screen, stats):
"""初始化显示得分涉及的属性"""
self.screen = screen
self.screen_rect = screen.get_rect()
self.set = set
self.stats = stats
self.text_color = (255, 158, 53)
self.font = pygame.font.Font('wd.ttf',... | the_stack_v2_python_sparse | 飞机大战/scoreboard.py | Daguodong/python-me | train | 1 |
dc205e46d01587362fe3d32f6eb68dc3844f760a | [
"csums = [0] + nums\nfor i in range(len(nums)):\n csums[i + 1] += csums[i]\nself.csums = csums",
"csums = self.csums\nassert -1 < i < len(csums) and -1 < j < len(csums)\nreturn csums[j + 1] - csums[i]"
] | <|body_start_0|>
csums = [0] + nums
for i in range(len(nums)):
csums[i + 1] += csums[i]
self.csums = csums
<|end_body_0|>
<|body_start_1|>
csums = self.csums
assert -1 < i < len(csums) and -1 < j < len(csums)
return csums[j + 1] - csums[i]
<|end_body_1|>
| NumArray | [
"MIT"
] | 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_36k_train_020328 | 568 | permissive | [
{
"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 ... | bc0b01e44e121ea68724da16f25f7e24386c53de | <|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_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
csums = [0] + nums
for i in range(len(nums)):
csums[i + 1] += csums[i]
self.csums = csums
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclu... | the_stack_v2_python_sparse | leetcode/303-Range-Sum-Query--Immutable/RangeSumQueryImmutable.py | cc13ny/all-in | train | 2 | |
7ebbd01376f070d2331fc01031eb60317930bf24 | [
"super().__init__()\nif not isinstance(size, int):\n raise _BeartypeUtilCacheLruException(f'LRU cache capacity {repr(size)} not integer.')\nelif size < 1:\n raise _BeartypeUtilCacheLruException(f'LRU cache capacity {size} not positive.')\nself._size = size\nself._lock = Lock()",
"with self._lock:\n if __... | <|body_start_0|>
super().__init__()
if not isinstance(size, int):
raise _BeartypeUtilCacheLruException(f'LRU cache capacity {repr(size)} not integer.')
elif size < 1:
raise _BeartypeUtilCacheLruException(f'LRU cache capacity {size} not positive.')
self._size = siz... | **Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically employ weak references for s... | CacheLruStrong | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CacheLruStrong:
"""**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementati... | stack_v2_sparse_classes_36k_train_020329 | 8,726 | permissive | [
{
"docstring": "Initialize this cache to an empty cache with a capacity of this size. Parameters ---------- size : int **Cache capacity** (i.e., maximum number of key-value pairs held in this cache). Raises ------ _BeartypeUtilCacheLruException: If the capacity is *not* an integer or its a **non-positive intege... | 4 | null | Implement the Python class `CacheLruStrong` described below.
Class description:
**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-sa... | Implement the Python class `CacheLruStrong` described below.
Class description:
**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-sa... | 0cfd53391eb4de2f8297a4632aa5895b8d82a5b7 | <|skeleton|>
class CacheLruStrong:
"""**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CacheLruStrong:
"""**Thread-safe strong Least Recently Used (LRU) cache** (i.e., mapping limited to some maximum capacity of strongly referenced arbitrary keys mapped onto strongly referenced arbitrary values, whose methods are guaranteed to behave thread-safely). Design ------ Cache implementations typically... | the_stack_v2_python_sparse | beartype/_util/cache/map/utilmaplru.py | beartype/beartype | train | 1,992 |
103772284285c96881bda976526f0bc0e9c95785 | [
"pwm_str_key = []\nfor k in bit_string:\n x = ''\n if k == '0':\n x = '001'\n if k == '1':\n x = '011'\n pwm_str_key.append(x)\nreturn ''.join(pwm_str_key)",
"if len(symbols) < 6:\n return None\nbits = []\nfound_bits = re.findall('0+(1+)', symbols)\nfor one_bits in found_bits:\n on... | <|body_start_0|>
pwm_str_key = []
for k in bit_string:
x = ''
if k == '0':
x = '001'
if k == '1':
x = '011'
pwm_str_key.append(x)
return ''.join(pwm_str_key)
<|end_body_0|>
<|body_start_1|>
if len(symbols) <... | PWMThreeSymbolMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PWMThreeSymbolMixin:
def _encode_pwm_symbols(bit_string):
""">>> PWMThreeSymbolMixin._encode_pwm_symbols("00110011") '001001011011001001011011'"""
<|body_0|>
def _decode_pwm_symbols(symbols):
"""Turns a string of radio symbols into a PCM-decoded packet >>> PWMThreeSy... | stack_v2_sparse_classes_36k_train_020330 | 11,147 | no_license | [
{
"docstring": ">>> PWMThreeSymbolMixin._encode_pwm_symbols(\"00110011\") '001001011011001001011011'",
"name": "_encode_pwm_symbols",
"signature": "def _encode_pwm_symbols(bit_string)"
},
{
"docstring": "Turns a string of radio symbols into a PCM-decoded packet >>> PWMThreeSymbolMixin._decode_pw... | 2 | stack_v2_sparse_classes_30k_train_008090 | Implement the Python class `PWMThreeSymbolMixin` described below.
Class description:
Implement the PWMThreeSymbolMixin class.
Method signatures and docstrings:
- def _encode_pwm_symbols(bit_string): >>> PWMThreeSymbolMixin._encode_pwm_symbols("00110011") '001001011011001001011011'
- def _decode_pwm_symbols(symbols): ... | Implement the Python class `PWMThreeSymbolMixin` described below.
Class description:
Implement the PWMThreeSymbolMixin class.
Method signatures and docstrings:
- def _encode_pwm_symbols(bit_string): >>> PWMThreeSymbolMixin._encode_pwm_symbols("00110011") '001001011011001001011011'
- def _decode_pwm_symbols(symbols): ... | eaf1b9bedfeec47e420fc284fbd25b08371025a8 | <|skeleton|>
class PWMThreeSymbolMixin:
def _encode_pwm_symbols(bit_string):
""">>> PWMThreeSymbolMixin._encode_pwm_symbols("00110011") '001001011011001001011011'"""
<|body_0|>
def _decode_pwm_symbols(symbols):
"""Turns a string of radio symbols into a PCM-decoded packet >>> PWMThreeSy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PWMThreeSymbolMixin:
def _encode_pwm_symbols(bit_string):
""">>> PWMThreeSymbolMixin._encode_pwm_symbols("00110011") '001001011011001001011011'"""
pwm_str_key = []
for k in bit_string:
x = ''
if k == '0':
x = '001'
if k == '1':
... | the_stack_v2_python_sparse | restful_rfcat/drivers/_utils.py | cjsatuforc/restful_rfcat | train | 0 | |
309f707d68839a49ee448e3f956a85bb6deac1b9 | [
"self._device = dev\nself._size = int(size) if size != '' else 0\nself._info = info\nself._attr = attr\nself._primaries = primaries\nself._nonPrimaries = nonPrimaries\nself._class = pType\nself._primaries = 0\nself._nonPrimaries = 0\nself._class = ''",
"self._primaries = primaries\nself._nonPrimaries = nonPrimari... | <|body_start_0|>
self._device = dev
self._size = int(size) if size != '' else 0
self._info = info
self._attr = attr
self._primaries = primaries
self._nonPrimaries = nonPrimaries
self._class = pType
self._primaries = 0
self._nonPrimaries = 0
... | Stores the info about a container of partitions. This can be a physical disk or a logical volume. | VirtualDisk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VirtualDisk:
"""Stores the info about a container of partitions. This can be a physical disk or a logical volume."""
def __init__(self, dev, size, info=None, attr=None, primaries=0, nonPrimaries=0, pType=None):
"""Constructor. @param dev: the device name @param size: the size in MiBy... | stack_v2_sparse_classes_36k_train_020331 | 32,293 | no_license | [
{
"docstring": "Constructor. @param dev: the device name @param size: the size in MiByte @param info: additional info about filesys... @param attr: attributes like LVM_VG @param primaries: count of primary partitions @param nonPrimaries: count of non primary partitions @param pType: gpt or msdos",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_010540 | Implement the Python class `VirtualDisk` described below.
Class description:
Stores the info about a container of partitions. This can be a physical disk or a logical volume.
Method signatures and docstrings:
- def __init__(self, dev, size, info=None, attr=None, primaries=0, nonPrimaries=0, pType=None): Constructor. ... | Implement the Python class `VirtualDisk` described below.
Class description:
Stores the info about a container of partitions. This can be a physical disk or a logical volume.
Method signatures and docstrings:
- def __init__(self, dev, size, info=None, attr=None, primaries=0, nonPrimaries=0, pType=None): Constructor. ... | 32e3eb74409741307d52a04173f0e5f0d4186352 | <|skeleton|>
class VirtualDisk:
"""Stores the info about a container of partitions. This can be a physical disk or a logical volume."""
def __init__(self, dev, size, info=None, attr=None, primaries=0, nonPrimaries=0, pType=None):
"""Constructor. @param dev: the device name @param size: the size in MiBy... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VirtualDisk:
"""Stores the info about a container of partitions. This can be a physical disk or a logical volume."""
def __init__(self, dev, size, info=None, attr=None, primaries=0, nonPrimaries=0, pType=None):
"""Constructor. @param dev: the device name @param size: the size in MiByte @param inf... | the_stack_v2_python_sparse | isource/diskinfopage.py | siduction/sidu-installer | train | 0 |
b40757936daaf95350ba63092fe0ef219d03fd63 | [
"position_block = {}\nfor position in self.POSITION:\n sub_position_block = {}\n for data_type in subquery['forecast']:\n df_group = self.context_row_handler(df_block[(df_block['data_type__name'] == data_type) & (df_block[position] == 1)])\n sub_position_block[data_type] = df_group\n self.for... | <|body_start_0|>
position_block = {}
for position in self.POSITION:
sub_position_block = {}
for data_type in subquery['forecast']:
df_group = self.context_row_handler(df_block[(df_block['data_type__name'] == data_type) & (df_block[position] == 1)])
... | Manager create necessary table information for indicator. | PercentRowManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PercentRowManager:
"""Manager create necessary table information for indicator."""
def indicator_handler(self, df_block, kwargs, subquery):
"""Calculate indicator row values."""
<|body_0|>
def sub_indicator_handler(self, position_block):
"""Sub method for indicat... | stack_v2_sparse_classes_36k_train_020332 | 1,984 | no_license | [
{
"docstring": "Calculate indicator row values.",
"name": "indicator_handler",
"signature": "def indicator_handler(self, df_block, kwargs, subquery)"
},
{
"docstring": "Sub method for indicator values calculation.",
"name": "sub_indicator_handler",
"signature": "def sub_indicator_handler... | 2 | stack_v2_sparse_classes_30k_train_004407 | Implement the Python class `PercentRowManager` described below.
Class description:
Manager create necessary table information for indicator.
Method signatures and docstrings:
- def indicator_handler(self, df_block, kwargs, subquery): Calculate indicator row values.
- def sub_indicator_handler(self, position_block): S... | Implement the Python class `PercentRowManager` described below.
Class description:
Manager create necessary table information for indicator.
Method signatures and docstrings:
- def indicator_handler(self, df_block, kwargs, subquery): Calculate indicator row values.
- def sub_indicator_handler(self, position_block): S... | b8f2a377ca2f0f55ddf2b1ace05402d2dfacf4cd | <|skeleton|>
class PercentRowManager:
"""Manager create necessary table information for indicator."""
def indicator_handler(self, df_block, kwargs, subquery):
"""Calculate indicator row values."""
<|body_0|>
def sub_indicator_handler(self, position_block):
"""Sub method for indicat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PercentRowManager:
"""Manager create necessary table information for indicator."""
def indicator_handler(self, df_block, kwargs, subquery):
"""Calculate indicator row values."""
position_block = {}
for position in self.POSITION:
sub_position_block = {}
for ... | the_stack_v2_python_sparse | indicator/calc_percent_indicator.py | diagon555/KPI-presentation | train | 0 |
68e95eca89b6aadc4c04613e1128a108ba1357ae | [
"if not s:\n return ''\ntemp = ''.join(map(''.join, zip(['#'] * len(s), s)) + ['#'])\nlen_temp = len(temp)\np = [0] * len_temp\nrb = 0\nc = 0\nmax_idx = max_len = 0\nfor idx in xrange(1, len_temp):\n p[idx] = min(p[2 * c - idx], rb - idx) if rb > idx else 0\n while idx - p[idx] > 0 and idx + p[idx] + 1 < l... | <|body_start_0|>
if not s:
return ''
temp = ''.join(map(''.join, zip(['#'] * len(s), s)) + ['#'])
len_temp = len(temp)
p = [0] * len_temp
rb = 0
c = 0
max_idx = max_len = 0
for idx in xrange(1, len_temp):
p[idx] = min(p[2 * c - idx]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_020333 | 2,202 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome2",
"signature": "def longestPalindrome2(self, s)"
},
{
"docstring": ":type s: str :rtype:... | 3 | stack_v2_sparse_classes_30k_train_002524 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: str
- def longestPalindrome2(self, s): :type s: str :rtype: str
- def longestPalindrome3(self, s): :type s: str :rtype: str
... | dbdb227e12f329e4ca064b338f1fbdca42f3a848 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
def longestPalindrome3(self, s):
""":type s: str :rtype: str"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
if not s:
return ''
temp = ''.join(map(''.join, zip(['#'] * len(s), s)) + ['#'])
len_temp = len(temp)
p = [0] * len_temp
rb = 0
c = 0
max_idx = max_len = 0
... | the_stack_v2_python_sparse | LC5.py | Qiao-Liang/LeetCode | train | 0 | |
4491085849f4ebeac19cfc82a3692dc31df1fc83 | [
"l = len(nums)\nif k == 0 or k == l:\n return\nk = k % l\nnums.extend(nums[:l - k])\ndel nums[:l - k]",
"length = len(nums)\ni = k % length\nnums[:] = nums[-i:] + nums[:-i]",
"k = k % len(nums)\nif len(nums) == 1 or k == 0:\n nums = nums\nelif len(nums) == 2:\n if k % 2 == 1:\n nums.reverse()\ne... | <|body_start_0|>
l = len(nums)
if k == 0 or k == l:
return
k = k % l
nums.extend(nums[:l - k])
del nums[:l - k]
<|end_body_0|>
<|body_start_1|>
length = len(nums)
i = k % length
nums[:] = nums[-i:] + nums[:-i]
<|end_body_1|>
<|body_start_2|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify ... | stack_v2_sparse_classes_36k_train_020334 | 1,143 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate1",
"signature": "def rotate1(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place ins... | 3 | stack_v2_sparse_classes_30k_train_011700 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.
- def rotate2(self, nums, k): :type nums: List[i... | 132d3d901a1e9bb027fc32e2269bc6efc170eee9 | <|skeleton|>
class Solution:
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
l = len(nums)
if k == 0 or k == l:
return
k = k % l
nums.extend(nums[:l - k])
del nums[:l - k]
def ... | the_stack_v2_python_sparse | Leetcode/旋转数组.py | simple5510/Leetcode | train | 0 | |
95bb7fb4607744f7fa20249f0b4a46ab44bb17f0 | [
"self.agent_status = agent_status\nself.endpoint = endpoint\nself.guid = guid\nself.name = name\nself.protection_source_id = protection_source_id\nself.status = status",
"if dictionary is None:\n return None\nagent_status = dictionary.get('agentStatus')\nendpoint = dictionary.get('endpoint')\nguid = dictionary... | <|body_start_0|>
self.agent_status = agent_status
self.endpoint = endpoint
self.guid = guid
self.name = name
self.protection_source_id = protection_source_id
self.status = status
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'ExchangeHostInfo' model. Specifies the Information about the Exchange host. Attributes: agent_status (AgentStatusEnum): Specifies the status of the agent on the Exchange host. Specifies the status of agent on Exchange Application Server. 'kSupported' indicates the agent is supported for Exchange ... | ExchangeHostInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExchangeHostInfo:
"""Implementation of the 'ExchangeHostInfo' model. Specifies the Information about the Exchange host. Attributes: agent_status (AgentStatusEnum): Specifies the status of the agent on the Exchange host. Specifies the status of agent on Exchange Application Server. 'kSupported' in... | stack_v2_sparse_classes_36k_train_020335 | 3,820 | permissive | [
{
"docstring": "Constructor for the ExchangeHostInfo class",
"name": "__init__",
"signature": "def __init__(self, agent_status=None, endpoint=None, guid=None, name=None, protection_source_id=None, status=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictiona... | 2 | stack_v2_sparse_classes_30k_train_017706 | Implement the Python class `ExchangeHostInfo` described below.
Class description:
Implementation of the 'ExchangeHostInfo' model. Specifies the Information about the Exchange host. Attributes: agent_status (AgentStatusEnum): Specifies the status of the agent on the Exchange host. Specifies the status of agent on Excha... | Implement the Python class `ExchangeHostInfo` described below.
Class description:
Implementation of the 'ExchangeHostInfo' model. Specifies the Information about the Exchange host. Attributes: agent_status (AgentStatusEnum): Specifies the status of the agent on the Exchange host. Specifies the status of agent on Excha... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ExchangeHostInfo:
"""Implementation of the 'ExchangeHostInfo' model. Specifies the Information about the Exchange host. Attributes: agent_status (AgentStatusEnum): Specifies the status of the agent on the Exchange host. Specifies the status of agent on Exchange Application Server. 'kSupported' in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExchangeHostInfo:
"""Implementation of the 'ExchangeHostInfo' model. Specifies the Information about the Exchange host. Attributes: agent_status (AgentStatusEnum): Specifies the status of the agent on the Exchange host. Specifies the status of agent on Exchange Application Server. 'kSupported' indicates the a... | the_stack_v2_python_sparse | cohesity_management_sdk/models/exchange_host_info.py | cohesity/management-sdk-python | train | 24 |
4eefe3f2214ed67ab0f3433eaf009ee68aeafb9c | [
"sagemaker_session = sagemaker_session or Session()\nbucket, key_prefix = parse_s3_url(url=desired_s3_uri)\nif kms_key is not None:\n extra_args = {'SSEKMSKeyId': kms_key, 'ServerSideEncryption': 'aws:kms'}\nelse:\n extra_args = None\nreturn sagemaker_session.upload_data(path=local_path, bucket=bucket, key_pr... | <|body_start_0|>
sagemaker_session = sagemaker_session or Session()
bucket, key_prefix = parse_s3_url(url=desired_s3_uri)
if kms_key is not None:
extra_args = {'SSEKMSKeyId': kms_key, 'ServerSideEncryption': 'aws:kms'}
else:
extra_args = None
return sagema... | Contains static methods for uploading directories or files to S3. | S3Uploader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3Uploader:
"""Contains static methods for uploading directories or files to S3."""
def upload(local_path, desired_s3_uri, kms_key=None, sagemaker_session=None):
"""Static method that uploads a given file or directory to S3. Args: local_path (str): Path (absolute or relative) of loca... | stack_v2_sparse_classes_36k_train_020336 | 8,554 | permissive | [
{
"docstring": "Static method that uploads a given file or directory to S3. Args: local_path (str): Path (absolute or relative) of local file or directory to upload. desired_s3_uri (str): The desired S3 location to upload to. It is the prefix to which the local filename will be added. kms_key (str): The KMS key... | 3 | null | Implement the Python class `S3Uploader` described below.
Class description:
Contains static methods for uploading directories or files to S3.
Method signatures and docstrings:
- def upload(local_path, desired_s3_uri, kms_key=None, sagemaker_session=None): Static method that uploads a given file or directory to S3. Ar... | Implement the Python class `S3Uploader` described below.
Class description:
Contains static methods for uploading directories or files to S3.
Method signatures and docstrings:
- def upload(local_path, desired_s3_uri, kms_key=None, sagemaker_session=None): Static method that uploads a given file or directory to S3. Ar... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class S3Uploader:
"""Contains static methods for uploading directories or files to S3."""
def upload(local_path, desired_s3_uri, kms_key=None, sagemaker_session=None):
"""Static method that uploads a given file or directory to S3. Args: local_path (str): Path (absolute or relative) of loca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3Uploader:
"""Contains static methods for uploading directories or files to S3."""
def upload(local_path, desired_s3_uri, kms_key=None, sagemaker_session=None):
"""Static method that uploads a given file or directory to S3. Args: local_path (str): Path (absolute or relative) of local file or dir... | the_stack_v2_python_sparse | src/sagemaker/s3.py | aws/sagemaker-python-sdk | train | 2,050 |
876f3e1c3a60dcf83591ce5da6a55e04ec41b237 | [
"self.optimizer_type = optimizer_type\nself.base_lr = base_lr\nself.min_lr = min_lr\nself.exp_gamma = exp_gamma\nself.steps_per_epoch = steps_per_epoch\nself.warmup_epochs = warmup_epochs\nself.hold_epochs = hold_epochs\nself.current_lr = None\nself.max_weight_norm = max_weight_norm if max_weight_norm is not None e... | <|body_start_0|>
self.optimizer_type = optimizer_type
self.base_lr = base_lr
self.min_lr = min_lr
self.exp_gamma = exp_gamma
self.steps_per_epoch = steps_per_epoch
self.warmup_epochs = warmup_epochs
self.hold_epochs = hold_epochs
self.current_lr = None
... | TransducerOptimizerFactory | [
"MIT",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransducerOptimizerFactory:
def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_decay=None, opt_eps=None, loss_scaling=None, gradient_clipping_norm=None, max_weight_norm=None):
"""Class for creating an... | stack_v2_sparse_classes_36k_train_020337 | 4,334 | permissive | [
{
"docstring": "Class for creating and updating popart optimizers :param str optimizer_type: optimizer type - 'SGD' or 'LAMB' :param float base_lr: base learning rate :param float min_lr: minimum learning rate :param float exp_gamma: gamma factor for exponential lr scheduler :param int steps_per_epoch: training... | 3 | null | Implement the Python class `TransducerOptimizerFactory` described below.
Class description:
Implement the TransducerOptimizerFactory class.
Method signatures and docstrings:
- def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_dec... | Implement the Python class `TransducerOptimizerFactory` described below.
Class description:
Implement the TransducerOptimizerFactory class.
Method signatures and docstrings:
- def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_dec... | 46d2b7687b829778369fc6328170a7b14761e5c6 | <|skeleton|>
class TransducerOptimizerFactory:
def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_decay=None, opt_eps=None, loss_scaling=None, gradient_clipping_norm=None, max_weight_norm=None):
"""Class for creating an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransducerOptimizerFactory:
def __init__(self, optimizer_type, base_lr, min_lr, exp_gamma, steps_per_epoch, warmup_epochs, hold_epochs, beta1=None, beta2=None, weight_decay=None, opt_eps=None, loss_scaling=None, gradient_clipping_norm=None, max_weight_norm=None):
"""Class for creating and updating pop... | the_stack_v2_python_sparse | applications/popart/transformer_transducer/training/transducer_optimizer.py | payoto/graphcore_examples | train | 0 | |
78a5aefb40d3252f633d3b999059dc8dc9de9891 | [
"score = []\nfor x in A:\n if x[0] == 0:\n self.zeroToOne(x)\nA = [list(x) for x in zip(*A)]\nself.flipMatrix(A)\nA = [list(x) for x in zip(*A)]\nfor row in A:\n score.append(self.score(row))\nreturn sum(score)",
"for x in range(1, len(A)):\n ones = A[x].count(1)\n zeros = A[x].count(0)\n if... | <|body_start_0|>
score = []
for x in A:
if x[0] == 0:
self.zeroToOne(x)
A = [list(x) for x in zip(*A)]
self.flipMatrix(A)
A = [list(x) for x in zip(*A)]
for row in A:
score.append(self.score(row))
return sum(score)
<|end_bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def matrixScore(self, A):
""":type A: List[List[int]] :rtype: int"""
<|body_0|>
def flipMatrix(self, A):
""":type A: List[List[int]] :rtype: int flip the matrix by checking if there are more 0 in each row or column"""
<|body_1|>
def zeroToOne(s... | stack_v2_sparse_classes_36k_train_020338 | 1,816 | no_license | [
{
"docstring": ":type A: List[List[int]] :rtype: int",
"name": "matrixScore",
"signature": "def matrixScore(self, A)"
},
{
"docstring": ":type A: List[List[int]] :rtype: int flip the matrix by checking if there are more 0 in each row or column",
"name": "flipMatrix",
"signature": "def fl... | 4 | stack_v2_sparse_classes_30k_train_011944 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def matrixScore(self, A): :type A: List[List[int]] :rtype: int
- def flipMatrix(self, A): :type A: List[List[int]] :rtype: int flip the matrix by checking if there are more 0 in ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def matrixScore(self, A): :type A: List[List[int]] :rtype: int
- def flipMatrix(self, A): :type A: List[List[int]] :rtype: int flip the matrix by checking if there are more 0 in ... | a6d0e392134afe19d1aed2dfe7914b674e05ecc6 | <|skeleton|>
class Solution:
def matrixScore(self, A):
""":type A: List[List[int]] :rtype: int"""
<|body_0|>
def flipMatrix(self, A):
""":type A: List[List[int]] :rtype: int flip the matrix by checking if there are more 0 in each row or column"""
<|body_1|>
def zeroToOne(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def matrixScore(self, A):
""":type A: List[List[int]] :rtype: int"""
score = []
for x in A:
if x[0] == 0:
self.zeroToOne(x)
A = [list(x) for x in zip(*A)]
self.flipMatrix(A)
A = [list(x) for x in zip(*A)]
for row in ... | the_stack_v2_python_sparse | 861scoreFlipMatrix.py | Ting007/leetcodePractice | train | 0 | |
be5ec931135ab16a6c583c484734d52cba16bd5b | [
"logs = get_logging_container()\n_, parsed_data, logs = self.parse_stdout_from_retrieved(logs)\nbase_exit_code = self.check_base_errors(logs)\nif base_exit_code:\n return self.exit(base_exit_code, logs)\nself.out('output_parameters', Dict(dict=parsed_data))\nif 'ERROR_OUTPUT_STDOUT_INCOMPLETE' in logs.error:\n ... | <|body_start_0|>
logs = get_logging_container()
_, parsed_data, logs = self.parse_stdout_from_retrieved(logs)
base_exit_code = self.check_base_errors(logs)
if base_exit_code:
return self.exit(base_exit_code, logs)
self.out('output_parameters', Dict(dict=parsed_data))
... | ``Parser`` implementation for the ``Pw2gwCalculation`` calculation job class. | Pw2gwParser | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pw2gwParser:
"""``Parser`` implementation for the ``Pw2gwCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``Pw2gwCalculation`` into output nodes. Two nodes that are expected are the default 'retrieved' `FolderData` node wh... | stack_v2_sparse_classes_36k_train_020339 | 2,882 | permissive | [
{
"docstring": "Parse the retrieved files of a completed ``Pw2gwCalculation`` into output nodes. Two nodes that are expected are the default 'retrieved' `FolderData` node which will store the retrieved files permanently in the repository. The second required node is a filepath under the key ``retrieved_temporar... | 2 | stack_v2_sparse_classes_30k_train_012131 | Implement the Python class `Pw2gwParser` described below.
Class description:
``Parser`` implementation for the ``Pw2gwCalculation`` calculation job class.
Method signatures and docstrings:
- def parse(self, **kwargs): Parse the retrieved files of a completed ``Pw2gwCalculation`` into output nodes. Two nodes that are ... | Implement the Python class `Pw2gwParser` described below.
Class description:
``Parser`` implementation for the ``Pw2gwCalculation`` calculation job class.
Method signatures and docstrings:
- def parse(self, **kwargs): Parse the retrieved files of a completed ``Pw2gwCalculation`` into output nodes. Two nodes that are ... | 7263f92ccabcfc9f828b9da5473e1aefbc4b8eca | <|skeleton|>
class Pw2gwParser:
"""``Parser`` implementation for the ``Pw2gwCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``Pw2gwCalculation`` into output nodes. Two nodes that are expected are the default 'retrieved' `FolderData` node wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pw2gwParser:
"""``Parser`` implementation for the ``Pw2gwCalculation`` calculation job class."""
def parse(self, **kwargs):
"""Parse the retrieved files of a completed ``Pw2gwCalculation`` into output nodes. Two nodes that are expected are the default 'retrieved' `FolderData` node which will stor... | the_stack_v2_python_sparse | src/aiida_quantumespresso/parsers/pw2gw.py | aiidateam/aiida-quantumespresso | train | 56 |
8d545db6e8f2fdba0ebd05d49a4deb96ce13d0f3 | [
"self.r = radius\nself.x_ = x_center\nself.y_ = y_center",
"l = math.sqrt(random.uniform(0, 1)) * self.r\ndeg = random.uniform(0, 1) * 360\nx = self.x_ + l * math.cos(deg)\ny = self.y_ + l * math.sin(deg)\nreturn [x, y]"
] | <|body_start_0|>
self.r = radius
self.x_ = x_center
self.y_ = y_center
<|end_body_0|>
<|body_start_1|>
l = math.sqrt(random.uniform(0, 1)) * self.r
deg = random.uniform(0, 1) * 360
x = self.x_ + l * math.cos(deg)
y = self.y_ + l * math.sin(deg)
return [x,... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.r = radius
... | stack_v2_sparse_classes_36k_train_020340 | 1,100 | permissive | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
<|skeleton|>
class Sol... | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.r = radius
self.x_ = x_center
self.y_ = y_center
def randPoint(self):
""":rtype: List[float]"""
l = math.sqrt(random.uniform... | the_stack_v2_python_sparse | py/leetcode/RandomPointCircle.py | danyfang/SourceCode | train | 0 | |
d2878069fa2180777c162e70954e176bf5f25852 | [
"super(BasicBlock, self).__init__()\nself.conv1 = conv3x3(inplanes, planes, stride)\nself.bn1 = nn.BatchNorm2d(planes)\nself.relu = nn.ReLU(inplace=True)\nself.conv2 = conv3x3(planes, planes)\nself.bn2 = nn.BatchNorm2d(planes)\nself.downsample = downsample\nself.stride = stride",
"residual = x\nout = self.conv1(x... | <|body_start_0|>
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsamp... | BasicBlock ResNwr Block | BasicBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicBlock:
"""BasicBlock ResNwr Block"""
def __init__(self, inplanes, planes, stride=1, downsample=None):
""":param inplanes: :param planes: :param stride: :param downsample:"""
<|body_0|>
def forward(self, x):
""":param x: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_020341 | 3,300 | no_license | [
{
"docstring": ":param inplanes: :param planes: :param stride: :param downsample:",
"name": "__init__",
"signature": "def __init__(self, inplanes, planes, stride=1, downsample=None)"
},
{
"docstring": ":param x: :return:",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008636 | Implement the Python class `BasicBlock` described below.
Class description:
BasicBlock ResNwr Block
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, downsample=None): :param inplanes: :param planes: :param stride: :param downsample:
- def forward(self, x): :param x: :return: | Implement the Python class `BasicBlock` described below.
Class description:
BasicBlock ResNwr Block
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, downsample=None): :param inplanes: :param planes: :param stride: :param downsample:
- def forward(self, x): :param x: :return:
<|skele... | ab83a47ef2e107dd7160ea0ca1832fa0531926b7 | <|skeleton|>
class BasicBlock:
"""BasicBlock ResNwr Block"""
def __init__(self, inplanes, planes, stride=1, downsample=None):
""":param inplanes: :param planes: :param stride: :param downsample:"""
<|body_0|>
def forward(self, x):
""":param x: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicBlock:
"""BasicBlock ResNwr Block"""
def __init__(self, inplanes, planes, stride=1, downsample=None):
""":param inplanes: :param planes: :param stride: :param downsample:"""
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = n... | the_stack_v2_python_sparse | src/ResNet.py | MauritsBleeker/Bi-STET | train | 72 |
d6ed850c2215bd27f976d8f3ce2cda6bbe8d4a17 | [
"self.d = len(a)\nassert len(b) == self.d\nassert len(orders) == self.d\nself.a = np.array(a, dtype=float)\nself.b = np.array(b, dtype=float)\nself.orders = np.array(orders, dtype=int)\nself.dtype = self.a.dtype\nself.__coeffs__ = None\nif values is not None:\n self.set_values(values)",
"values = np.array(valu... | <|body_start_0|>
self.d = len(a)
assert len(b) == self.d
assert len(orders) == self.d
self.a = np.array(a, dtype=float)
self.b = np.array(b, dtype=float)
self.orders = np.array(orders, dtype=int)
self.dtype = self.a.dtype
self.__coeffs__ = None
if ... | Class representing a cubic spline interpolator on a regular cartesian grid.. | CubicSpline | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CubicSpline:
"""Class representing a cubic spline interpolator on a regular cartesian grid.."""
def __init__(self, a, b, orders, values=None):
"""Creates a cubic spline interpolator on a regular cartesian grid. Parameters: ----------- a : array of size d (float) Lower bounds of the c... | stack_v2_sparse_classes_36k_train_020342 | 7,068 | permissive | [
{
"docstring": "Creates a cubic spline interpolator on a regular cartesian grid. Parameters: ----------- a : array of size d (float) Lower bounds of the cartesian grid. b : array of size d (float) Upper bounds of the cartesian grid. orders : array of size d (int) Number of nodes along each dimension (=(n1,...,n... | 5 | stack_v2_sparse_classes_30k_train_011926 | Implement the Python class `CubicSpline` described below.
Class description:
Class representing a cubic spline interpolator on a regular cartesian grid..
Method signatures and docstrings:
- def __init__(self, a, b, orders, values=None): Creates a cubic spline interpolator on a regular cartesian grid. Parameters: ----... | Implement the Python class `CubicSpline` described below.
Class description:
Class representing a cubic spline interpolator on a regular cartesian grid..
Method signatures and docstrings:
- def __init__(self, a, b, orders, values=None): Creates a cubic spline interpolator on a regular cartesian grid. Parameters: ----... | 19b2cd3882003c19b7aeb7c35fca5cdad3fe1d5e | <|skeleton|>
class CubicSpline:
"""Class representing a cubic spline interpolator on a regular cartesian grid.."""
def __init__(self, a, b, orders, values=None):
"""Creates a cubic spline interpolator on a regular cartesian grid. Parameters: ----------- a : array of size d (float) Lower bounds of the c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CubicSpline:
"""Class representing a cubic spline interpolator on a regular cartesian grid.."""
def __init__(self, a, b, orders, values=None):
"""Creates a cubic spline interpolator on a regular cartesian grid. Parameters: ----------- a : array of size d (float) Lower bounds of the cartesian grid... | the_stack_v2_python_sparse | interpolation/splines/splines.py | EconForge/interpolation.py | train | 116 |
9b90606d3456f8603f6db3ae0aea5585b0173077 | [
"picking_obj = self.pool.get('stock.picking')\nseq_obj_name = self._name\nvals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)\nnew_id = picking_obj.create(cr, user, vals, context)\nreturn new_id",
"picking_obj = self.pool.get('stock.picking')\nwrite_boolean = picking_obj.write(cr, uid, ids, va... | <|body_start_0|>
picking_obj = self.pool.get('stock.picking')
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id = picking_obj.create(cr, user, vals, context)
return new_id
<|end_body_0|>
<|body_start_1|>
picking_obj ... | stock_picking_out | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking_out:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override write to call write of stock.picking"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_020343 | 17,898 | no_license | [
{
"docstring": "Override create to call create of stock.picking",
"name": "create",
"signature": "def create(self, cr, user, vals, context=None)"
},
{
"docstring": "Override write to call write of stock.picking",
"name": "write",
"signature": "def write(self, cr, uid, ids, vals, context=... | 2 | stack_v2_sparse_classes_30k_train_008568 | Implement the Python class `stock_picking_out` described below.
Class description:
Implement the stock_picking_out class.
Method signatures and docstrings:
- def create(self, cr, user, vals, context=None): Override create to call create of stock.picking
- def write(self, cr, uid, ids, vals, context=None): Override wr... | Implement the Python class `stock_picking_out` described below.
Class description:
Implement the stock_picking_out class.
Method signatures and docstrings:
- def create(self, cr, user, vals, context=None): Override create to call create of stock.picking
- def write(self, cr, uid, ids, vals, context=None): Override wr... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_picking_out:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
<|body_0|>
def write(self, cr, uid, ids, vals, context=None):
"""Override write to call write of stock.picking"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_picking_out:
def create(self, cr, user, vals, context=None):
"""Override create to call create of stock.picking"""
picking_obj = self.pool.get('stock.picking')
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/stock_oc/model/stock.py | musabahmed/baba | train | 0 | |
4f53eebf489d79c775025a3b2a251a5d34039a3a | [
"self.right_answers = set(right_answers)\nself.problem = problem\nself.task = task\nself.kind = kind\nself.choices = ctypes.py_object * len(choices)\nself.choices = self.choices()\nfor i in range(len(choices)):\n self.choices[i] = choices[i]",
"self.task = Receiver.mml2latex(self.task).strip('$')\nfor i in ran... | <|body_start_0|>
self.right_answers = set(right_answers)
self.problem = problem
self.task = task
self.kind = kind
self.choices = ctypes.py_object * len(choices)
self.choices = self.choices()
for i in range(len(choices)):
self.choices[i] = choices[i]
<|... | A class that represents a separate problem. | Problem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem:
"""A class that represents a separate problem."""
def __init__(self, problem='', task='', kind='', choices=(), right_answers=()):
"""(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kin... | stack_v2_sparse_classes_36k_train_020344 | 9,855 | no_license | [
{
"docstring": "(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kind of the problem :param choices: available choices :param right_answers: right_answers for the problem",
"name": "__init__",
"signature": "def __i... | 3 | stack_v2_sparse_classes_30k_train_012684 | Implement the Python class `Problem` described below.
Class description:
A class that represents a separate problem.
Method signatures and docstrings:
- def __init__(self, problem='', task='', kind='', choices=(), right_answers=()): (Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem ... | Implement the Python class `Problem` described below.
Class description:
A class that represents a separate problem.
Method signatures and docstrings:
- def __init__(self, problem='', task='', kind='', choices=(), right_answers=()): (Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem ... | 43ea67af67bd9ceb9a2dd0ce7cf4ee342c3e13a2 | <|skeleton|>
class Problem:
"""A class that represents a separate problem."""
def __init__(self, problem='', task='', kind='', choices=(), right_answers=()):
"""(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Problem:
"""A class that represents a separate problem."""
def __init__(self, problem='', task='', kind='', choices=(), right_answers=()):
"""(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kind of the prob... | the_stack_v2_python_sparse | flask-app/my_modules/classes.py | Centurion256/ProjectLogos | train | 1 |
5fc2d820a7df8346d47946045b3c4c2652bbed0a | [
"if payload.get('password') != payload.get('confirm_password'):\n abort(400, 'Password does not match')\ncount, records = base_obj.get(COLLECTIONS['USERS'], {'email': payload['email']})\nif count > 0:\n abort(400, 'Email ID Already Exists')\npayload = custom_marshal(payload, user, 'create')\npayload['password... | <|body_start_0|>
if payload.get('password') != payload.get('confirm_password'):
abort(400, 'Password does not match')
count, records = base_obj.get(COLLECTIONS['USERS'], {'email': payload['email']})
if count > 0:
abort(400, 'Email ID Already Exists')
payload = cus... | Service Class for User View | UserService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserService:
"""Service Class for User View"""
def signup(self, payload):
"""signup function :return:"""
<|body_0|>
def activate(self, id):
"""Activate the user :param id: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if payload.get('... | stack_v2_sparse_classes_36k_train_020345 | 1,668 | no_license | [
{
"docstring": "signup function :return:",
"name": "signup",
"signature": "def signup(self, payload)"
},
{
"docstring": "Activate the user :param id: :return:",
"name": "activate",
"signature": "def activate(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018856 | Implement the Python class `UserService` described below.
Class description:
Service Class for User View
Method signatures and docstrings:
- def signup(self, payload): signup function :return:
- def activate(self, id): Activate the user :param id: :return: | Implement the Python class `UserService` described below.
Class description:
Service Class for User View
Method signatures and docstrings:
- def signup(self, payload): signup function :return:
- def activate(self, id): Activate the user :param id: :return:
<|skeleton|>
class UserService:
"""Service Class for Use... | 075cd9a9faaa2d24f1c7ea8507c115e6936aed04 | <|skeleton|>
class UserService:
"""Service Class for User View"""
def signup(self, payload):
"""signup function :return:"""
<|body_0|>
def activate(self, id):
"""Activate the user :param id: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserService:
"""Service Class for User View"""
def signup(self, payload):
"""signup function :return:"""
if payload.get('password') != payload.get('confirm_password'):
abort(400, 'Password does not match')
count, records = base_obj.get(COLLECTIONS['USERS'], {'email': p... | the_stack_v2_python_sparse | app/users/service.py | nosqlly/Todo-App | train | 3 |
03fcfe715de835dae63ae8ccdbbf55186ed14a80 | [
"if needs_paid and (current_user.is_anonymous or not current_user.has_paid):\n return False\nreturn ModuleAPI.get_highest_permission_for_module(module_name) >= 1",
"if needs_paid and (current_user.is_anonymous or not current_user.has_paid):\n return False\nreturn ModuleAPI.get_highest_permission_for_module(... | <|body_start_0|>
if needs_paid and (current_user.is_anonymous or not current_user.has_paid):
return False
return ModuleAPI.get_highest_permission_for_module(module_name) >= 1
<|end_body_0|>
<|body_start_1|>
if needs_paid and (current_user.is_anonymous or not current_user.has_paid):
... | ModuleAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleAPI:
def can_read(module_name, needs_paid=False):
"""Check if the current user can view the module_name. Distinguishes between paid members and regular users"""
<|body_0|>
def can_write(module_name, needs_paid=False):
"""Check if the current user can edit the m... | stack_v2_sparse_classes_36k_train_020346 | 1,898 | permissive | [
{
"docstring": "Check if the current user can view the module_name. Distinguishes between paid members and regular users",
"name": "can_read",
"signature": "def can_read(module_name, needs_paid=False)"
},
{
"docstring": "Check if the current user can edit the module_name.",
"name": "can_writ... | 3 | null | Implement the Python class `ModuleAPI` described below.
Class description:
Implement the ModuleAPI class.
Method signatures and docstrings:
- def can_read(module_name, needs_paid=False): Check if the current user can view the module_name. Distinguishes between paid members and regular users
- def can_write(module_nam... | Implement the Python class `ModuleAPI` described below.
Class description:
Implement the ModuleAPI class.
Method signatures and docstrings:
- def can_read(module_name, needs_paid=False): Check if the current user can view the module_name. Distinguishes between paid members and regular users
- def can_write(module_nam... | 378aed005a47be76ad1d5577288368045d62f355 | <|skeleton|>
class ModuleAPI:
def can_read(module_name, needs_paid=False):
"""Check if the current user can view the module_name. Distinguishes between paid members and regular users"""
<|body_0|>
def can_write(module_name, needs_paid=False):
"""Check if the current user can edit the m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleAPI:
def can_read(module_name, needs_paid=False):
"""Check if the current user can view the module_name. Distinguishes between paid members and regular users"""
if needs_paid and (current_user.is_anonymous or not current_user.has_paid):
return False
return ModuleAPI.g... | the_stack_v2_python_sparse | app/utils/module.py | YSturkenboom/viaduct | train | 0 | |
bc08e3f845ef62ded5dc971e5cbf8b38d5e46f30 | [
"dummy = ListNode(0)\ndummy.next = head\nfast = dummy\nslow = dummy\nfor _ in range(n):\n fast = fast.next\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next\nslow.next = slow.next.next\nreturn dummy.next",
"if not head:\n return None\ndummy = ListNode(0)\ndummy.next = head\nfast = dummy... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
fast = dummy
slow = dummy
for _ in range(n):
fast = fast.next
while fast and fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.nex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
"""*将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。 *使用两个指针 时间复杂度 o(n) 空间复杂度 o(1)"""
<|body_0|>
def findnode(self, head, n):
"""找正着数的第三分之一的结点 四分之一 N分之一 fast比slow多走三倍 四倍 N倍 找倒着数的第三分之一的结点 fast走三倍 slow走2倍 *将添加... | stack_v2_sparse_classes_36k_train_020347 | 1,750 | no_license | [
{
"docstring": "*将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。 *使用两个指针 时间复杂度 o(n) 空间复杂度 o(1)",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": "找正着数的第三分之一的结点 四分之一 N分之一 fast比slow多走三倍 四倍 N倍 找倒着数的第三分之一的结点 fast走三倍 slow走2倍 *将添加一个哑结点作为辅助... | 2 | stack_v2_sparse_classes_30k_train_019034 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): *将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。 *使用两个指针 时间复杂度 o(n) 空间复杂度 o(1)
- def findnode(self, head, n): 找正着数的第三分之一的结点 四分之... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): *将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。 *使用两个指针 时间复杂度 o(n) 空间复杂度 o(1)
- def findnode(self, head, n): 找正着数的第三分之一的结点 四分之... | ebf9503d4bc6d4335c463aa2b4622dd7df55fb87 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
"""*将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。 *使用两个指针 时间复杂度 o(n) 空间复杂度 o(1)"""
<|body_0|>
def findnode(self, head, n):
"""找正着数的第三分之一的结点 四分之一 N分之一 fast比slow多走三倍 四倍 N倍 找倒着数的第三分之一的结点 fast走三倍 slow走2倍 *将添加... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head, n):
"""*将添加一个哑结点作为辅助,该结点位于列表头部。哑结点用来简化某些极端情况,例如列表中只含有一个结点,或需要删除列表的头部。 *使用两个指针 时间复杂度 o(n) 空间复杂度 o(1)"""
dummy = ListNode(0)
dummy.next = head
fast = dummy
slow = dummy
for _ in range(n):
fast = fast.next
... | the_stack_v2_python_sparse | linkedlist/19_remove_nth_node_from_end.py | huuu97/LeetCode | train | 0 | |
8f6a372869a9445f5b037d4a036eea48007fc3dd | [
"username = self.cleaned_data['username']\ntry:\n User.objects.get(username=username)\nexcept User.DoesNotExist:\n return username\nraise ValidationError(_('A user with that username already exists.'))",
"password1 = self.cleaned_data.get('password1', '')\npassword2 = self.cleaned_data['password2']\nif pass... | <|body_start_0|>
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise ValidationError(_('A user with that username already exists.'))
<|end_body_0|>
<|body_start_1|>
password1 = ... | Form for registering a new user account | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account"""
def clean_username(self):
"""Verify username not existed in database"""
<|body_0|>
def clean_password2(self):
"""Verify password2 is the same as password1"""
<|body_1|>
def save(self, co... | stack_v2_sparse_classes_36k_train_020348 | 3,293 | no_license | [
{
"docstring": "Verify username not existed in database",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Verify password2 is the same as password1",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save U... | 3 | stack_v2_sparse_classes_30k_train_016992 | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account
Method signatures and docstrings:
- def clean_username(self): Verify username not existed in database
- def clean_password2(self): Verify password2 is the same as password1
- def save(self, commit... | Implement the Python class `RegistrationForm` described below.
Class description:
Form for registering a new user account
Method signatures and docstrings:
- def clean_username(self): Verify username not existed in database
- def clean_password2(self): Verify password2 is the same as password1
- def save(self, commit... | 04541d41bb2fe3d7217b43202ff0d999c82d1e9e | <|skeleton|>
class RegistrationForm:
"""Form for registering a new user account"""
def clean_username(self):
"""Verify username not existed in database"""
<|body_0|>
def clean_password2(self):
"""Verify password2 is the same as password1"""
<|body_1|>
def save(self, co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Form for registering a new user account"""
def clean_username(self):
"""Verify username not existed in database"""
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
retur... | the_stack_v2_python_sparse | apps/account/forms.py | lifepy/myway | train | 2 |
6ded0a84bc30d76b3a5ff610be14cf20fc8f72cd | [
"self.lang = lang\nself.dictionary = corpora.Dictionary.load(model_dir_path + file_name[self.lang]['dict_file_name'])\nself.model = models.LdaMulticore.load(model_dir_path + file_name[self.lang]['model_file_name'])\nif self.lang == 'HINDI':\n self.lang_obj = Hindi()\nelif self.lang == 'ENGLISH':\n self.lang_o... | <|body_start_0|>
self.lang = lang
self.dictionary = corpora.Dictionary.load(model_dir_path + file_name[self.lang]['dict_file_name'])
self.model = models.LdaMulticore.load(model_dir_path + file_name[self.lang]['model_file_name'])
if self.lang == 'HINDI':
self.lang_obj = Hindi(... | EvaluateLDA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluateLDA:
def __init__(self, model_dir_path, lang):
"""model_dir_path is path where models are saved. init function loads dictionary and model which are previously trained. on the basis of language we assign lang_obj which contains utility functions like tokenizing and cleanup of code... | stack_v2_sparse_classes_36k_train_020349 | 5,215 | no_license | [
{
"docstring": "model_dir_path is path where models are saved. init function loads dictionary and model which are previously trained. on the basis of language we assign lang_obj which contains utility functions like tokenizing and cleanup of code for that particluar lang.",
"name": "__init__",
"signatur... | 5 | null | Implement the Python class `EvaluateLDA` described below.
Class description:
Implement the EvaluateLDA class.
Method signatures and docstrings:
- def __init__(self, model_dir_path, lang): model_dir_path is path where models are saved. init function loads dictionary and model which are previously trained. on the basis... | Implement the Python class `EvaluateLDA` described below.
Class description:
Implement the EvaluateLDA class.
Method signatures and docstrings:
- def __init__(self, model_dir_path, lang): model_dir_path is path where models are saved. init function loads dictionary and model which are previously trained. on the basis... | b1d8eb050182cd782bc6f3bb3ac1429fe22ab7b7 | <|skeleton|>
class EvaluateLDA:
def __init__(self, model_dir_path, lang):
"""model_dir_path is path where models are saved. init function loads dictionary and model which are previously trained. on the basis of language we assign lang_obj which contains utility functions like tokenizing and cleanup of code... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluateLDA:
def __init__(self, model_dir_path, lang):
"""model_dir_path is path where models are saved. init function loads dictionary and model which are previously trained. on the basis of language we assign lang_obj which contains utility functions like tokenizing and cleanup of code for that part... | the_stack_v2_python_sparse | ba_lda/topic_modeling/topic_modeling/evaluate/lda.py | ZouJoshua/ml_project | train | 0 | |
91249bd7bd754d360a5a3ae812732f3274a5d54c | [
"input_json = request.data\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))\njson_params = dict(zip(['profile_id'], [input_json['SessionDetails']['Payl... | <|body_start_0|>
input_json = request.data
output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))
json_params = dict(zip(['profile_id'], [... | This covers the API for fetching all support centre tickets raised by the user | PostLoginFetchMyTicketsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostLoginFetchMyTicketsAPI:
"""This covers the API for fetching all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to fetching common questions based on ticket type."""
<|body_0|>
def post_login_fetch_my_tickets_json(self, request)... | stack_v2_sparse_classes_36k_train_020350 | 2,735 | no_license | [
{
"docstring": "Post Function to fetching common questions based on ticket type.",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "This function fetches all the support centre tickets raised by logged in user :param request: { 'profile_id': 1, } :return:",
"name": "... | 2 | null | Implement the Python class `PostLoginFetchMyTicketsAPI` described below.
Class description:
This covers the API for fetching all support centre tickets raised by the user
Method signatures and docstrings:
- def post(self, request): Post Function to fetching common questions based on ticket type.
- def post_login_fetc... | Implement the Python class `PostLoginFetchMyTicketsAPI` described below.
Class description:
This covers the API for fetching all support centre tickets raised by the user
Method signatures and docstrings:
- def post(self, request): Post Function to fetching common questions based on ticket type.
- def post_login_fetc... | 36eb9931f330e64902354c6fc471be2adf4b7049 | <|skeleton|>
class PostLoginFetchMyTicketsAPI:
"""This covers the API for fetching all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to fetching common questions based on ticket type."""
<|body_0|>
def post_login_fetch_my_tickets_json(self, request)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostLoginFetchMyTicketsAPI:
"""This covers the API for fetching all support centre tickets raised by the user"""
def post(self, request):
"""Post Function to fetching common questions based on ticket type."""
input_json = request.data
output_json = dict(zip(['AvailabilityDetails',... | the_stack_v2_python_sparse | Generic/common/supportcentre/api/post_login_fetch_my_tickets/views_post_login_fetch_my_tickets.py | archiemb303/common_backend_django | train | 0 |
4523a33d4629d310aadbbae6b094b3084fef8380 | [
"self.filepath = audio_filename\ntry:\n audio = EasyID3(audio_filename)\nexcept:\n raise ValueError\nelse:\n self.tags = {}\n self.tags['artist'] = audio.get('artist', 'Unknown')\n self.tags['title'] = audio.get('title', 'Unknown')\n self.tags['album'] = audio.get('album', 'Unknown')\n self.tag... | <|body_start_0|>
self.filepath = audio_filename
try:
audio = EasyID3(audio_filename)
except:
raise ValueError
else:
self.tags = {}
self.tags['artist'] = audio.get('artist', 'Unknown')
self.tags['title'] = audio.get('title', 'Unk... | Class for work with ID3 tags of Mp3 files | Tag | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tag:
"""Class for work with ID3 tags of Mp3 files"""
def __init__(self, audio_filename):
"""@type audio_filename str Init function of Tag class"""
<|body_0|>
def set_tags(self, **kwargs):
"""@type **kwargs dict Set ID3 tags (artist, title, album, album_date, genr... | stack_v2_sparse_classes_36k_train_020351 | 2,305 | no_license | [
{
"docstring": "@type audio_filename str Init function of Tag class",
"name": "__init__",
"signature": "def __init__(self, audio_filename)"
},
{
"docstring": "@type **kwargs dict Set ID3 tags (artist, title, album, album_date, genre, tracknumber) in mp3 files",
"name": "set_tags",
"signa... | 3 | stack_v2_sparse_classes_30k_train_006299 | Implement the Python class `Tag` described below.
Class description:
Class for work with ID3 tags of Mp3 files
Method signatures and docstrings:
- def __init__(self, audio_filename): @type audio_filename str Init function of Tag class
- def set_tags(self, **kwargs): @type **kwargs dict Set ID3 tags (artist, title, al... | Implement the Python class `Tag` described below.
Class description:
Class for work with ID3 tags of Mp3 files
Method signatures and docstrings:
- def __init__(self, audio_filename): @type audio_filename str Init function of Tag class
- def set_tags(self, **kwargs): @type **kwargs dict Set ID3 tags (artist, title, al... | a53bed4b95f2848ec64156e642b6166a1ca6a1e4 | <|skeleton|>
class Tag:
"""Class for work with ID3 tags of Mp3 files"""
def __init__(self, audio_filename):
"""@type audio_filename str Init function of Tag class"""
<|body_0|>
def set_tags(self, **kwargs):
"""@type **kwargs dict Set ID3 tags (artist, title, album, album_date, genr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tag:
"""Class for work with ID3 tags of Mp3 files"""
def __init__(self, audio_filename):
"""@type audio_filename str Init function of Tag class"""
self.filepath = audio_filename
try:
audio = EasyID3(audio_filename)
except:
raise ValueError
e... | the_stack_v2_python_sparse | src/tools/tags.py | Xkeeper/LastVK | train | 0 |
b9888866f41fdf12510ca8e7a4c80074023b3009 | [
"super().__init__(model_type, task, **kwargs)\nself.nb_classes = None\nself.set_task(task)",
"if type(task) != thelper.tasks.Detection:\n raise AssertionError(\"task passed to ExternalClassifModule should be 'thelper.tasks.Detection'\")\nself.nb_classes = len(self.task.class_names)\nimport torchvision\nif hasa... | <|body_start_0|>
super().__init__(model_type, task, **kwargs)
self.nb_classes = None
self.set_task(task)
<|end_body_0|>
<|body_start_1|>
if type(task) != thelper.tasks.Detection:
raise AssertionError("task passed to ExternalClassifModule should be 'thelper.tasks.Detection'")... | External model interface specialization for object detection tasks. This interface will try to 'rewire' the last fully connected layer of the models it instantiates to match the number of classes to predict defined in the task object. .. seealso:: | :class:`thelper.nn.utils.Module` | :class:`thelper.nn.utils.ExternalMo... | ExternalDetectModule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalDetectModule:
"""External model interface specialization for object detection tasks. This interface will try to 'rewire' the last fully connected layer of the models it instantiates to match the number of classes to predict defined in the task object. .. seealso:: | :class:`thelper.nn.uti... | stack_v2_sparse_classes_36k_train_020352 | 22,198 | permissive | [
{
"docstring": "Receives a task object to hold internally for model specialization, and tries to rewire the last 'fc' layer.",
"name": "__init__",
"signature": "def __init__(self, model_type, task, **kwargs)"
},
{
"docstring": "Rewires the last fully connected layer of the wrapped network to fit... | 2 | null | Implement the Python class `ExternalDetectModule` described below.
Class description:
External model interface specialization for object detection tasks. This interface will try to 'rewire' the last fully connected layer of the models it instantiates to match the number of classes to predict defined in the task object... | Implement the Python class `ExternalDetectModule` described below.
Class description:
External model interface specialization for object detection tasks. This interface will try to 'rewire' the last fully connected layer of the models it instantiates to match the number of classes to predict defined in the task object... | d91c50d4e3755c4779ef882967519aaa9d863ff4 | <|skeleton|>
class ExternalDetectModule:
"""External model interface specialization for object detection tasks. This interface will try to 'rewire' the last fully connected layer of the models it instantiates to match the number of classes to predict defined in the task object. .. seealso:: | :class:`thelper.nn.uti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalDetectModule:
"""External model interface specialization for object detection tasks. This interface will try to 'rewire' the last fully connected layer of the models it instantiates to match the number of classes to predict defined in the task object. .. seealso:: | :class:`thelper.nn.utils.Module` | ... | the_stack_v2_python_sparse | thelper/nn/utils.py | plstcharles/thelper | train | 19 |
96a1a64ef9d8864a4b7bbb557df22bb22fff5521 | [
"example_1 = 'COM)B\\nB)C\\nC)D\\nD)E\\nE)F\\nB)G\\nG)H\\nD)I\\nE)J\\nJ)K\\nK)L'\nself.assertEqual(day_6.part1(example_1), 42)\nself.assertEqual(day_6.part1(), 270768)",
"example_1 = 'COM)B\\nB)C\\nC)D\\nD)E\\nE)F\\nB)G\\nG)H\\nD)I\\nE)J\\nJ)K\\nK)L\\nK)YOU\\nI)SAN'\nself.assertEqual(day_6.part2(example_1), 4)\ns... | <|body_start_0|>
example_1 = 'COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L'
self.assertEqual(day_6.part1(example_1), 42)
self.assertEqual(day_6.part1(), 270768)
<|end_body_0|>
<|body_start_1|>
example_1 = 'COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L\nK)YOU\nI)SAN'... | TestDay6 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDay6:
def test_part1(self):
"""Finds the total number of direct and indirect orbits in the orbit map"""
<|body_0|>
def test_part2(self):
"""Finds the minimum number of orbital transfers needed to move from you to santa"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_020353 | 942 | permissive | [
{
"docstring": "Finds the total number of direct and indirect orbits in the orbit map",
"name": "test_part1",
"signature": "def test_part1(self)"
},
{
"docstring": "Finds the minimum number of orbital transfers needed to move from you to santa",
"name": "test_part2",
"signature": "def te... | 2 | stack_v2_sparse_classes_30k_train_018062 | Implement the Python class `TestDay6` described below.
Class description:
Implement the TestDay6 class.
Method signatures and docstrings:
- def test_part1(self): Finds the total number of direct and indirect orbits in the orbit map
- def test_part2(self): Finds the minimum number of orbital transfers needed to move f... | Implement the Python class `TestDay6` described below.
Class description:
Implement the TestDay6 class.
Method signatures and docstrings:
- def test_part1(self): Finds the total number of direct and indirect orbits in the orbit map
- def test_part2(self): Finds the minimum number of orbital transfers needed to move f... | d9e0b55daefdc8439e70ce4c17e88e4efddf4b33 | <|skeleton|>
class TestDay6:
def test_part1(self):
"""Finds the total number of direct and indirect orbits in the orbit map"""
<|body_0|>
def test_part2(self):
"""Finds the minimum number of orbital transfers needed to move from you to santa"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDay6:
def test_part1(self):
"""Finds the total number of direct and indirect orbits in the orbit map"""
example_1 = 'COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L'
self.assertEqual(day_6.part1(example_1), 42)
self.assertEqual(day_6.part1(), 270768)
def test_p... | the_stack_v2_python_sparse | 2019/6/test.py | agarun/adventofcode | train | 1 | |
5e377a424203e3bbd9249627343b0dee22cc66c6 | [
"if not root:\n return ''\nres, Q, i = ('', Queue(), 0)\nQ.put((root, 'null', -1, 0))\nwhile not Q.empty():\n node, parent, parentIndex, isLeft = Q.get()\n res += str(node.val) + '|' + str(i) + '|' + parent + '|' + str(parentIndex) + '|' + str(isLeft) + '_'\n if node.left:\n Q.put((node.left, str... | <|body_start_0|>
if not root:
return ''
res, Q, i = ('', Queue(), 0)
Q.put((root, 'null', -1, 0))
while not Q.empty():
node, parent, parentIndex, isLeft = Q.get()
res += str(node.val) + '|' + str(i) + '|' + parent + '|' + str(parentIndex) + '|' + str(i... | 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_36k_train_020354 | 1,673 | 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 | null | 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:... | 25e5caf324e25edfdf0a7a3be1e572f5d4c88837 | <|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_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
res, Q, i = ('', Queue(), 0)
Q.put((root, 'null', -1, 0))
while not Q.empty():
node, parent, parentIndex, isLeft = ... | the_stack_v2_python_sparse | Trees/serialize_and_deserialize_binary_tree.py | msraju2009/CodingProblemsPractice | train | 0 | |
bf8684cf75da8be70745cd71dbcab027ced6eef9 | [
"super(GaussianSmoothing, self).__init__()\nself.shift = shift\nself.fft_centered = fft_centered\nself.fft_normalization = fft_normalization\nself.spatial_dims = spatial_dims\nif isinstance(kernel_size, int):\n kernel_size = [kernel_size] * dim\nif isinstance(sigma, float):\n sigma = [sigma] * dim\nkernel = 1... | <|body_start_0|>
super(GaussianSmoothing, self).__init__()
self.shift = shift
self.fft_centered = fft_centered
self.fft_normalization = fft_normalization
self.spatial_dims = spatial_dims
if isinstance(kernel_size, int):
kernel_size = [kernel_size] * dim
... | Apply gaussian smoothing on a 1d, 2d or 3d tensor. Filtering is performed separately for each channel in the input using a depthwise convolution. | GaussianSmoothing | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianSmoothing:
"""Apply gaussian smoothing on a 1d, 2d or 3d tensor. Filtering is performed separately for each channel in the input using a depthwise convolution."""
def __init__(self, channels: int, kernel_size: Union[Optional[List[int]], int], sigma: float, dim: int=2, shift: bool=Fal... | stack_v2_sparse_classes_36k_train_020355 | 48,550 | permissive | [
{
"docstring": "Initialize the module with the gaussian kernel size and standard deviation. Parameters ---------- channels : int Number of channels in the input tensor. kernel_size : Union[Optional[List[int]], int] Gaussian kernel size. sigma : float Gaussian kernel standard deviation. dim : int Number of dimen... | 2 | stack_v2_sparse_classes_30k_train_013583 | Implement the Python class `GaussianSmoothing` described below.
Class description:
Apply gaussian smoothing on a 1d, 2d or 3d tensor. Filtering is performed separately for each channel in the input using a depthwise convolution.
Method signatures and docstrings:
- def __init__(self, channels: int, kernel_size: Union[... | Implement the Python class `GaussianSmoothing` described below.
Class description:
Apply gaussian smoothing on a 1d, 2d or 3d tensor. Filtering is performed separately for each channel in the input using a depthwise convolution.
Method signatures and docstrings:
- def __init__(self, channels: int, kernel_size: Union[... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class GaussianSmoothing:
"""Apply gaussian smoothing on a 1d, 2d or 3d tensor. Filtering is performed separately for each channel in the input using a depthwise convolution."""
def __init__(self, channels: int, kernel_size: Union[Optional[List[int]], int], sigma: float, dim: int=2, shift: bool=Fal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianSmoothing:
"""Apply gaussian smoothing on a 1d, 2d or 3d tensor. Filtering is performed separately for each channel in the input using a depthwise convolution."""
def __init__(self, channels: int, kernel_size: Union[Optional[List[int]], int], sigma: float, dim: int=2, shift: bool=False, fft_cente... | the_stack_v2_python_sparse | mridc/collections/quantitative/parts/transforms.py | wdika/mridc | train | 40 |
da74cf3cadbf65e2f2fd85686b15c878e1975298 | [
"if n < 2:\n return 0\nprimes = [True] * n\nprimes[0] = primes[1] = False\nfor i in range(2, int(n ** 0.5) + 1):\n if primes[i]:\n primes[i * i:n:i] = [False] * len(primes[i * i:n:i])\nreturn sum(primes)",
"if n < 2:\n return 0\nprimes = [True] * n\nprimes[0] = primes[1] = False\nfor i in range(2,... | <|body_start_0|>
if n < 2:
return 0
primes = [True] * n
primes[0] = primes[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
primes[i * i:n:i] = [False] * len(primes[i * i:n:i])
return sum(primes)
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def rewrite(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 2:
return 0
primes = [True] * n
primes... | stack_v2_sparse_classes_36k_train_020356 | 1,467 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "countPrimes",
"signature": "def countPrimes(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "rewrite",
"signature": "def rewrite(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def rewrite(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes(self, n): :type n: int :rtype: int
- def rewrite(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def countPrimes(self, n):
""":type ... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def rewrite(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimes(self, n):
""":type n: int :rtype: int"""
if n < 2:
return 0
primes = [True] * n
primes[0] = primes[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
primes[i * i:n:i] = [False] * len(primes[i... | the_stack_v2_python_sparse | co_ms/204_Count_Primes.py | vsdrun/lc_public | train | 6 | |
45ec800708f9fe5343eaed46cf2e141c8d15cde7 | [
"super().__init__()\nself.acceptsDistribution = True\nself.metricType = None",
"self.distParams = {}\nfor child in paramInput.subparts:\n if child.getName() == 'metricType':\n self.metricType = list((elem.strip() for elem in child.value.split('|')))\n else:\n self.distParams[child.getName()] =... | <|body_start_0|>
super().__init__()
self.acceptsDistribution = True
self.metricType = None
<|end_body_0|>
<|body_start_1|>
self.distParams = {}
for child in paramInput.subparts:
if child.getName() == 'metricType':
self.metricType = list((elem.strip() ... | Metric to compare two datasets using statistical tests. | StatsTestMetric | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StatsTestMetric:
"""Metric to compare two datasets using statistical tests."""
def __init__(self):
"""Constructor @ In, None @ Out, None"""
<|body_0|>
def handleInput(self, paramInput):
"""Method that reads the portion of the xml input that belongs to this specia... | stack_v2_sparse_classes_36k_train_020357 | 4,118 | permissive | [
{
"docstring": "Constructor @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method that reads the portion of the xml input that belongs to this specialized class and initialize internal parameters @ In, paramInput, InputData.parameterInput, input... | 3 | null | Implement the Python class `StatsTestMetric` described below.
Class description:
Metric to compare two datasets using statistical tests.
Method signatures and docstrings:
- def __init__(self): Constructor @ In, None @ Out, None
- def handleInput(self, paramInput): Method that reads the portion of the xml input that b... | Implement the Python class `StatsTestMetric` described below.
Class description:
Metric to compare two datasets using statistical tests.
Method signatures and docstrings:
- def __init__(self): Constructor @ In, None @ Out, None
- def handleInput(self, paramInput): Method that reads the portion of the xml input that b... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class StatsTestMetric:
"""Metric to compare two datasets using statistical tests."""
def __init__(self):
"""Constructor @ In, None @ Out, None"""
<|body_0|>
def handleInput(self, paramInput):
"""Method that reads the portion of the xml input that belongs to this specia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StatsTestMetric:
"""Metric to compare two datasets using statistical tests."""
def __init__(self):
"""Constructor @ In, None @ Out, None"""
super().__init__()
self.acceptsDistribution = True
self.metricType = None
def handleInput(self, paramInput):
"""Method t... | the_stack_v2_python_sparse | ravenframework/Metrics/metrics/StatsTestMetric.py | idaholab/raven | train | 201 |
7586716a38a1b92cc6e31dedc52fa31959e02e58 | [
"import asdf\nwith asdf.open(self.filepath) as handle:\n header = self.to_simple_types(handle.tree)\n header['HISTORY'] = self.get_history(handle)\nreturn header",
"history = 'UNDEFINED'\nwith log.error_on_exception('Failed reading ASDF history, see ASDF docs on adding history'):\n histall = []\n hist... | <|body_start_0|>
import asdf
with asdf.open(self.filepath) as handle:
header = self.to_simple_types(handle.tree)
header['HISTORY'] = self.get_history(handle)
return header
<|end_body_0|>
<|body_start_1|>
history = 'UNDEFINED'
with log.error_on_exception('... | AsdfFile | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsdfFile:
def get_raw_header(self, needed_keys=(), **keys):
"""Return the flattened header associated with an ASDF file."""
<|body_0|>
def get_history(self, handle):
"""Given and ASDF file object `handle`, return the history collected into a single string."""
... | stack_v2_sparse_classes_36k_train_020358 | 2,054 | permissive | [
{
"docstring": "Return the flattened header associated with an ASDF file.",
"name": "get_raw_header",
"signature": "def get_raw_header(self, needed_keys=(), **keys)"
},
{
"docstring": "Given and ASDF file object `handle`, return the history collected into a single string.",
"name": "get_hist... | 3 | null | Implement the Python class `AsdfFile` described below.
Class description:
Implement the AsdfFile class.
Method signatures and docstrings:
- def get_raw_header(self, needed_keys=(), **keys): Return the flattened header associated with an ASDF file.
- def get_history(self, handle): Given and ASDF file object `handle`, ... | Implement the Python class `AsdfFile` described below.
Class description:
Implement the AsdfFile class.
Method signatures and docstrings:
- def get_raw_header(self, needed_keys=(), **keys): Return the flattened header associated with an ASDF file.
- def get_history(self, handle): Given and ASDF file object `handle`, ... | 08da10721c0e979877dc9579b4092c79f4ceee27 | <|skeleton|>
class AsdfFile:
def get_raw_header(self, needed_keys=(), **keys):
"""Return the flattened header associated with an ASDF file."""
<|body_0|>
def get_history(self, handle):
"""Given and ASDF file object `handle`, return the history collected into a single string."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsdfFile:
def get_raw_header(self, needed_keys=(), **keys):
"""Return the flattened header associated with an ASDF file."""
import asdf
with asdf.open(self.filepath) as handle:
header = self.to_simple_types(handle.tree)
header['HISTORY'] = self.get_history(handl... | the_stack_v2_python_sparse | crds/io/asdf.py | spacetelescope/crds | train | 9 | |
93c5fb079d87c95c1221032d38ee828c19516ebb | [
"super().__init__()\nself.total_duration = 0\nself.save_partial = True\nself.orb_tune_save_each_nrmeas = 10\nself.correct_orbit = True\nself.correct_orbit_nr_iters = 5\nself.get_tunes = True\nself.bpm_name = self.DEFAULT_BPMNAME\nself.bpm_attenuation = 14\nself.acquisition_timeout = 1\nself.acquisition_period = 3\n... | <|body_start_0|>
super().__init__()
self.total_duration = 0
self.save_partial = True
self.orb_tune_save_each_nrmeas = 10
self.correct_orbit = True
self.correct_orbit_nr_iters = 5
self.get_tunes = True
self.bpm_name = self.DEFAULT_BPMNAME
self.bpm_a... | . | MeasTouschekParams | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.total_duration = 0
self.save_partial = True
self.orb_tune_... | stack_v2_sparse_classes_36k_train_020359 | 34,435 | permissive | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000680 | Implement the Python class `MeasTouschekParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): . | Implement the Python class `MeasTouschekParams` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self): .
- def __str__(self): .
<|skeleton|>
class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""... | 39644161d98964a3a3d80d63269201f0a1712e82 | <|skeleton|>
class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
<|body_0|>
def __str__(self):
"""."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasTouschekParams:
"""."""
def __init__(self):
"""."""
super().__init__()
self.total_duration = 0
self.save_partial = True
self.orb_tune_save_each_nrmeas = 10
self.correct_orbit = True
self.correct_orbit_nr_iters = 5
self.get_tunes = True
... | the_stack_v2_python_sparse | apsuite/commisslib/meas_touschek_lifetime.py | lnls-fac/apsuite | train | 1 |
1d56f70baf8e9185b69afd77dcd7fac15b19595c | [
"doc = xml.dom.minidom.Document()\narticleData = MetaXml.createGoobiMetadata(doc, article_metadata)\nmodsExtTag = doc.createElement('mods:extension')\nmodsExtTag.appendChild(articleData)\nmodsTag = doc.createElement('mods:mods')\nmodsTag.setAttributeNS('mods', 'xmlns:mods', 'http://www.loc.gov/mods/v3')\nmodsTag.ap... | <|body_start_0|>
doc = xml.dom.minidom.Document()
articleData = MetaXml.createGoobiMetadata(doc, article_metadata)
modsExtTag = doc.createElement('mods:extension')
modsExtTag.appendChild(articleData)
modsTag = doc.createElement('mods:mods')
modsTag.setAttributeNS('mods', ... | This class contains functions used for working with Goobi's meta.xml file | MetaXml | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaXml:
"""This class contains functions used for working with Goobi's meta.xml file"""
def generateArticleXml(article_id, article_metadata):
"""Given an id and a dictionary of data, create an XML node in the article format Metadata should follow this format: [ {'name': 'Abstract', ... | stack_v2_sparse_classes_36k_train_020360 | 3,630 | no_license | [
{
"docstring": "Given an id and a dictionary of data, create an XML node in the article format Metadata should follow this format: [ {'name': 'Abstract', 'data' : 'From the Roman Empire...' }, {'name' : 'TitleDocMain', 'data' : 'Return of the oppressed'}, {'name' : 'Author', 'type' : 'person', 'fields' : [ {'ta... | 3 | stack_v2_sparse_classes_30k_train_007984 | Implement the Python class `MetaXml` described below.
Class description:
This class contains functions used for working with Goobi's meta.xml file
Method signatures and docstrings:
- def generateArticleXml(article_id, article_metadata): Given an id and a dictionary of data, create an XML node in the article format Me... | Implement the Python class `MetaXml` described below.
Class description:
This class contains functions used for working with Goobi's meta.xml file
Method signatures and docstrings:
- def generateArticleXml(article_id, article_metadata): Given an id and a dictionary of data, create an XML node in the article format Me... | 1891071f6c5445cb9470b3d6a896fd6077466a37 | <|skeleton|>
class MetaXml:
"""This class contains functions used for working with Goobi's meta.xml file"""
def generateArticleXml(article_id, article_metadata):
"""Given an id and a dictionary of data, create an XML node in the article format Metadata should follow this format: [ {'name': 'Abstract', ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaXml:
"""This class contains functions used for working with Goobi's meta.xml file"""
def generateArticleXml(article_id, article_metadata):
"""Given an id and a dictionary of data, create an XML node in the article format Metadata should follow this format: [ {'name': 'Abstract', 'data' : 'Fro... | the_stack_v2_python_sparse | kb/tools/goobi/meta_xml.py | kb-dk/goobi-scripts | train | 0 |
027b65a1279a658506f7bfb84d73d3d5821c9715 | [
"try:\n import dgl\nexcept:\n raise ImportError('This class requires dgl.')\ntry:\n import dgllife\nexcept:\n raise ImportError('This class requires dgllife.')\nif mode not in ['classification', 'regression']:\n raise ValueError(\"mode must be either 'classification' or 'regression'\")\nsuper(GCN, se... | <|body_start_0|>
try:
import dgl
except:
raise ImportError('This class requires dgl.')
try:
import dgllife
except:
raise ImportError('This class requires dgllife.')
if mode not in ['classification', 'regression']:
raise ... | Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where the weights are computed by apply... | GCN | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCN:
"""Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where th... | stack_v2_sparse_classes_36k_train_020361 | 14,944 | permissive | [
{
"docstring": "Parameters ---------- n_tasks: int Number of tasks. graph_conv_layers: list of int Width of channels for GCN layers. graph_conv_layers[i] gives the width of channel for the i-th GCN layer. If not specified, the default value will be [64, 64]. activation: callable The activation function to apply... | 2 | stack_v2_sparse_classes_30k_train_009725 | Implement the Python class `GCN` described below.
Class description:
Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node... | Implement the Python class `GCN` described below.
Class description:
Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class GCN:
"""Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GCN:
"""Model for Graph Property Prediction Based on Graph Convolution Networks (GCN). This model proceeds as follows: * Update node representations in graphs with a variant of GCN * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where the weights are... | the_stack_v2_python_sparse | deepchem/models/torch_models/gcn.py | deepchem/deepchem | train | 4,876 |
b7bfff15aca54c782a99c93dae68127b372c056c | [
"if section is None and option is not None:\n raise ValueError('--section not specified')\npath = self.CONFIG_BASEURL\nif section is not None and option is None:\n path += '/' + section\nelif section is not None and option is not None:\n path += '/'.join(['', section, option])\nurl = build_url(choice(self.... | <|body_start_0|>
if section is None and option is not None:
raise ValueError('--section not specified')
path = self.CONFIG_BASEURL
if section is not None and option is None:
path += '/' + section
elif section is not None and option is not None:
path +=... | Client class for working with the configuration | ConfigClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigClient:
"""Client class for working with the configuration"""
def get_config(self, section=None, option=None):
"""Sends the request to get the matching configuration. :param section: the optional name of the section. :param option: the optional option within the section. :retur... | stack_v2_sparse_classes_36k_train_020362 | 4,460 | permissive | [
{
"docstring": "Sends the request to get the matching configuration. :param section: the optional name of the section. :param option: the optional option within the section. :return: dictionary containing the configuration.",
"name": "get_config",
"signature": "def get_config(self, section=None, option=... | 3 | stack_v2_sparse_classes_30k_train_000406 | Implement the Python class `ConfigClient` described below.
Class description:
Client class for working with the configuration
Method signatures and docstrings:
- def get_config(self, section=None, option=None): Sends the request to get the matching configuration. :param section: the optional name of the section. :par... | Implement the Python class `ConfigClient` described below.
Class description:
Client class for working with the configuration
Method signatures and docstrings:
- def get_config(self, section=None, option=None): Sends the request to get the matching configuration. :param section: the optional name of the section. :par... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class ConfigClient:
"""Client class for working with the configuration"""
def get_config(self, section=None, option=None):
"""Sends the request to get the matching configuration. :param section: the optional name of the section. :param option: the optional option within the section. :retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigClient:
"""Client class for working with the configuration"""
def get_config(self, section=None, option=None):
"""Sends the request to get the matching configuration. :param section: the optional name of the section. :param option: the optional option within the section. :return: dictionary... | the_stack_v2_python_sparse | lib/rucio/client/configclient.py | rucio/rucio | train | 232 |
e62517e15a8699f881c950a043772a5d972a6d80 | [
"d = TreeNode('D')\ne = TreeNode('E')\nf = TreeNode('F')\ng = TreeNode('G')\nb = TreeNode('B', d, e, f)\nc = TreeNode('C', g)\na = TreeNode('A', b, c)\nself.assertEqual(str(a), 'A\\nB C\\nD E F G')",
"x = TreeNode('X')\ny = TreeNode('Y')\nz = TreeNode('Z')\nn1 = TreeNode('1')\nn2 = TreeNode('2')\nn3 = TreeNode('3... | <|body_start_0|>
d = TreeNode('D')
e = TreeNode('E')
f = TreeNode('F')
g = TreeNode('G')
b = TreeNode('B', d, e, f)
c = TreeNode('C', g)
a = TreeNode('A', b, c)
self.assertEqual(str(a), 'A\nB C\nD E F G')
<|end_body_0|>
<|body_start_1|>
x = TreeNo... | Test for: [#3] Tree printing. | TestTreePrinting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTreePrinting:
"""Test for: [#3] Tree printing."""
def test_3_layer_tree(self):
"""Given example 3-layer tree is used as input."""
<|body_0|>
def test_6_layer_tree(self):
"""Input tree: layer 1: A /|\\ layer 2: B C D / / \\ \\ /| | /\\ \\ layer 3: E F G H I J ... | stack_v2_sparse_classes_36k_train_020363 | 2,670 | no_license | [
{
"docstring": "Given example 3-layer tree is used as input.",
"name": "test_3_layer_tree",
"signature": "def test_3_layer_tree(self)"
},
{
"docstring": "Input tree: layer 1: A /|\\\\ layer 2: B C D / / \\\\ \\\\ /| | /\\\\ \\\\ layer 3: E F G H I J /| | | | |\\\\ \\\\ layer 4: K L M N O P Q R /... | 2 | null | Implement the Python class `TestTreePrinting` described below.
Class description:
Test for: [#3] Tree printing.
Method signatures and docstrings:
- def test_3_layer_tree(self): Given example 3-layer tree is used as input.
- def test_6_layer_tree(self): Input tree: layer 1: A /|\\ layer 2: B C D / / \\ \\ /| | /\\ \\ ... | Implement the Python class `TestTreePrinting` described below.
Class description:
Test for: [#3] Tree printing.
Method signatures and docstrings:
- def test_3_layer_tree(self): Given example 3-layer tree is used as input.
- def test_6_layer_tree(self): Input tree: layer 1: A /|\\ layer 2: B C D / / \\ \\ /| | /\\ \\ ... | 3678646116c8e43bef1f52f384eb4a236a269788 | <|skeleton|>
class TestTreePrinting:
"""Test for: [#3] Tree printing."""
def test_3_layer_tree(self):
"""Given example 3-layer tree is used as input."""
<|body_0|>
def test_6_layer_tree(self):
"""Input tree: layer 1: A /|\\ layer 2: B C D / / \\ \\ /| | /\\ \\ layer 3: E F G H I J ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestTreePrinting:
"""Test for: [#3] Tree printing."""
def test_3_layer_tree(self):
"""Given example 3-layer tree is used as input."""
d = TreeNode('D')
e = TreeNode('E')
f = TreeNode('F')
g = TreeNode('G')
b = TreeNode('B', d, e, f)
c = TreeNode('C'... | the_stack_v2_python_sparse | interview_test_tasks/browser_vendor/final/task_3/test.py | fifajan/py-stuff | train | 2 |
8d20f4a9c275b515ac04961662973dfb7330ef37 | [
"store = StoreModel.query.filter_by(id=store_id).first()\nif not store:\n store_api.abort(404, \"Store {} doesn't exist\".format(store_id))\nelse:\n return store",
"store = StoreModel.query.filter_by(id=store_id).first()\nif not store:\n store_api.abort(404, 'Store {} not found'.format(store_id))\nstore.... | <|body_start_0|>
store = StoreModel.query.filter_by(id=store_id).first()
if not store:
store_api.abort(404, "Store {} doesn't exist".format(store_id))
else:
return store
<|end_body_0|>
<|body_start_1|>
store = StoreModel.query.filter_by(id=store_id).first()
... | Store | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Store:
def get(self, store_id):
"""Get a store given its identifier"""
<|body_0|>
def delete(self, store_id):
"""Delete a store given its identifier"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
store = StoreModel.query.filter_by(id=store_id).firs... | stack_v2_sparse_classes_36k_train_020364 | 4,193 | no_license | [
{
"docstring": "Get a store given its identifier",
"name": "get",
"signature": "def get(self, store_id)"
},
{
"docstring": "Delete a store given its identifier",
"name": "delete",
"signature": "def delete(self, store_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007076 | Implement the Python class `Store` described below.
Class description:
Implement the Store class.
Method signatures and docstrings:
- def get(self, store_id): Get a store given its identifier
- def delete(self, store_id): Delete a store given its identifier | Implement the Python class `Store` described below.
Class description:
Implement the Store class.
Method signatures and docstrings:
- def get(self, store_id): Get a store given its identifier
- def delete(self, store_id): Delete a store given its identifier
<|skeleton|>
class Store:
def get(self, store_id):
... | f380164e92b70874042364ad4b5b20c5793d6921 | <|skeleton|>
class Store:
def get(self, store_id):
"""Get a store given its identifier"""
<|body_0|>
def delete(self, store_id):
"""Delete a store given its identifier"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Store:
def get(self, store_id):
"""Get a store given its identifier"""
store = StoreModel.query.filter_by(id=store_id).first()
if not store:
store_api.abort(404, "Store {} doesn't exist".format(store_id))
else:
return store
def delete(self, store_id... | the_stack_v2_python_sparse | project/app/main/controllers/store.py | ArielVilleda/docker-flask-postgres | train | 0 | |
e82f29738b5c6b2e7fe624254380a7b8c4695b98 | [
"super().__init__(properties=properties, data=data, source=source, copy=copy, _use_data=_use_data)\nself._initialise_netcdf(source)\nself._initialise_original_filenames(source)",
"if _create_title and _title is None:\n _title = 'List: ' + self.identity(default='')\nreturn super().dump(display=display, _key=_ke... | <|body_start_0|>
super().__init__(properties=properties, data=data, source=source, copy=copy, _use_data=_use_data)
self._initialise_netcdf(source)
self._initialise_original_filenames(source)
<|end_body_0|>
<|body_start_1|>
if _create_title and _title is None:
_title = 'List:... | A list variable required to uncompress a gathered array. Compression by gathering combines axes of a multidimensional array into a new, discrete axis whilst omitting the missing values and thus reducing the number of values that need to be stored. The information needed to uncompress the data is stored in a list variab... | List | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""A list variable required to uncompress a gathered array. Compression by gathering combines axes of a multidimensional array into a new, discrete axis whilst omitting the missing values and thus reducing the number of values that need to be stored. The information needed to uncompress the... | stack_v2_sparse_classes_36k_train_020365 | 2,560 | permissive | [
{
"docstring": "**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Parameter example:* ``properties={'long_name': 'uncompression indices'}`` {{init data: data_like, optional}} {{init source: optional}} {{init copy: `bool`, optional}}",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_train_014429 | Implement the Python class `List` described below.
Class description:
A list variable required to uncompress a gathered array. Compression by gathering combines axes of a multidimensional array into a new, discrete axis whilst omitting the missing values and thus reducing the number of values that need to be stored. T... | Implement the Python class `List` described below.
Class description:
A list variable required to uncompress a gathered array. Compression by gathering combines axes of a multidimensional array into a new, discrete axis whilst omitting the missing values and thus reducing the number of values that need to be stored. T... | 142accf27fbbc052473b4eee47daf0e81c88df3a | <|skeleton|>
class List:
"""A list variable required to uncompress a gathered array. Compression by gathering combines axes of a multidimensional array into a new, discrete axis whilst omitting the missing values and thus reducing the number of values that need to be stored. The information needed to uncompress the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class List:
"""A list variable required to uncompress a gathered array. Compression by gathering combines axes of a multidimensional array into a new, discrete axis whilst omitting the missing values and thus reducing the number of values that need to be stored. The information needed to uncompress the data is stor... | the_stack_v2_python_sparse | cfdm/list.py | NCAS-CMS/cfdm | train | 29 |
0942aa7b669d6c40ac4efc7e054fd9a3e825eedc | [
"super().__init__(*args, **kwargs)\nself.fields['name'].widget.attrs.update({'class': 'w3-input w3-border', 'style': 'width:20em; display:inline-block;'})\nself.fields['description'].widget.attrs.update({'class': 'w3-input w3-border', 'rows': 3})\nself.fields['program_type'].widget.attrs.update({'class': 'w3-select... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'w3-input w3-border', 'style': 'width:20em; display:inline-block;'})
self.fields['description'].widget.attrs.update({'class': 'w3-input w3-border', 'rows': 3})
self.fields['program_type']... | Default Model Form | ProgramModelForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramModelForm:
"""Default Model Form"""
def __init__(self, *args, **kwargs):
"""Update field definitions with custom attributes"""
<|body_0|>
def clean_time_start(self):
"""Raise error if field is required but empty"""
<|body_1|>
def clean_duratio... | stack_v2_sparse_classes_36k_train_020366 | 7,909 | no_license | [
{
"docstring": "Update field definitions with custom attributes",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Raise error if field is required but empty",
"name": "clean_time_start",
"signature": "def clean_time_start(self)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_test_000969 | Implement the Python class `ProgramModelForm` described below.
Class description:
Default Model Form
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Update field definitions with custom attributes
- def clean_time_start(self): Raise error if field is required but empty
- def clean_duration(se... | Implement the Python class `ProgramModelForm` described below.
Class description:
Default Model Form
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Update field definitions with custom attributes
- def clean_time_start(self): Raise error if field is required but empty
- def clean_duration(se... | 9efd022b6dda81e4088dd78036d652cd88d8214a | <|skeleton|>
class ProgramModelForm:
"""Default Model Form"""
def __init__(self, *args, **kwargs):
"""Update field definitions with custom attributes"""
<|body_0|>
def clean_time_start(self):
"""Raise error if field is required but empty"""
<|body_1|>
def clean_duratio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgramModelForm:
"""Default Model Form"""
def __init__(self, *args, **kwargs):
"""Update field definitions with custom attributes"""
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'w3-input w3-border', 'style': 'width:20em; display:inline-bloc... | the_stack_v2_python_sparse | programs/forms.py | leventerevesz/irrigation-server | train | 0 |
a0e604c1d2fc4bcce8e15cfde077884ba95a250e | [
"try:\n user = User.objects.get(username__iexact=self.cleaned_data['username'])\nexcept User.DoesNotExist:\n return self.cleaned_data['username']\nraise forms.ValidationError(_('A user with that username already exists.'))",
"if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:\n if ... | <|body_start_0|>
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_('A user with that username already exists.'))
<|end_body_0|>
<|body_start_1|>
... | Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user... | SignUpForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignUpForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method ... | stack_v2_sparse_classes_36k_train_020367 | 10,431 | permissive | [
{
"docstring": "Validate that the username is alphanumeric and is not already in use.",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_erro... | 3 | stack_v2_sparse_classes_30k_train_008039 | Implement the Python class `SignUpForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but sho... | Implement the Python class `SignUpForm` described below.
Class description:
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but sho... | 4f0e74a14f45b263a3d9fdab554bd21540fd4e22 | <|skeleton|>
class SignUpForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignUpForm:
"""Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual... | the_stack_v2_python_sparse | iseteam/trips/forms.py | R3SWebDevelopment/iseteam | train | 0 |
385ed474b5b4d52ee05209b2dd9b62718e81d358 | [
"self.label = label\nself.subsample_factor = 1 if subsample_factor is None else subsample_factor\nself.items = []\nself.i = 0",
"item = (self.i, x)\nif self.subsample_factor == 1 or self.i % self.subsample_factor == 1 or (not self.items):\n self.items.append(item)\nelse:\n self.items[-1] = item\nself.i += 1... | <|body_start_0|>
self.label = label
self.subsample_factor = 1 if subsample_factor is None else subsample_factor
self.items = []
self.i = 0
<|end_body_0|>
<|body_start_1|>
item = (self.i, x)
if self.subsample_factor == 1 or self.i % self.subsample_factor == 1 or (not self... | A section in the Logging structure. | _Section | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Section:
"""A section in the Logging structure."""
def __init__(self, label, subsample_factor=None):
"""Initialize a Section instance. Args: label: A short name for the section. subsample_factor: Rate at which to subsample logging in this section."""
<|body_0|>
def log(... | stack_v2_sparse_classes_36k_train_020368 | 3,542 | permissive | [
{
"docstring": "Initialize a Section instance. Args: label: A short name for the section. subsample_factor: Rate at which to subsample logging in this section.",
"name": "__init__",
"signature": "def __init__(self, label, subsample_factor=None)"
},
{
"docstring": "Add a record to the log.",
... | 2 | stack_v2_sparse_classes_30k_train_007175 | Implement the Python class `_Section` described below.
Class description:
A section in the Logging structure.
Method signatures and docstrings:
- def __init__(self, label, subsample_factor=None): Initialize a Section instance. Args: label: A short name for the section. subsample_factor: Rate at which to subsample log... | Implement the Python class `_Section` described below.
Class description:
A section in the Logging structure.
Method signatures and docstrings:
- def __init__(self, label, subsample_factor=None): Initialize a Section instance. Args: label: A short name for the section. subsample_factor: Rate at which to subsample log... | 548dc4e2e6a8e3ac65e1921bd94fe589d661d47b | <|skeleton|>
class _Section:
"""A section in the Logging structure."""
def __init__(self, label, subsample_factor=None):
"""Initialize a Section instance. Args: label: A short name for the section. subsample_factor: Rate at which to subsample logging in this section."""
<|body_0|>
def log(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Section:
"""A section in the Logging structure."""
def __init__(self, label, subsample_factor=None):
"""Initialize a Section instance. Args: label: A short name for the section. subsample_factor: Rate at which to subsample logging in this section."""
self.label = label
self.subsa... | the_stack_v2_python_sparse | magenta/models/coconet/lib_logging.py | magenta/magenta | train | 4,142 |
edfdf7c6c38847e7d85bd939238a517409a1fe7f | [
"FeaturewiseDatasetMeasure.__init__(self, **kwargs)\nself.threshold = threshold\nself.w_guess = w_guess\nself.w = None\nself.kernel_width = kernel_width",
"M = {}\nH = {}\nfor i in range(label.size):\n M[i] = N.where(label != label[i])[0]\n tmp = N.where(label == label[i])[0].tolist()\n tmp.remove(i)\n ... | <|body_start_0|>
FeaturewiseDatasetMeasure.__init__(self, **kwargs)
self.threshold = threshold
self.w_guess = w_guess
self.w = None
self.kernel_width = kernel_width
<|end_body_0|>
<|body_start_1|>
M = {}
H = {}
for i in range(label.size):
M[i]... | `FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the number of iterations, N the number of instances, I the number of features. See: Y.... | IterativeRelief | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterativeRelief:
"""`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the number of iterations, N the number of i... | stack_v2_sparse_classes_36k_train_020369 | 16,907 | permissive | [
{
"docstring": "Constructor of the IRELIEF class.",
"name": "__init__",
"signature": "def __init__(self, threshold=0.01, kernel_width=1.0, w_guess=None, **kwargs)"
},
{
"docstring": "Compute hit/miss dictionaries. For each instance compute the set of indices having the same class label and diffe... | 4 | null | Implement the Python class `IterativeRelief` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the ... | Implement the Python class `IterativeRelief` described below.
Class description:
`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the ... | 2a8fcaa57457c8994455144e9e69494d167204c4 | <|skeleton|>
class IterativeRelief:
"""`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the number of iterations, N the number of i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IterativeRelief:
"""`FeaturewiseDatasetMeasure` that performs multivariate I-RELIEF algorithm. Batch version. Batch I-RELIEF-2 feature weighting algorithm. Works for binary or multiclass class-labels. Batch version with complexity O(T*N^2*I), where T is the number of iterations, N the number of instances, I t... | the_stack_v2_python_sparse | mvpa/measures/irelief.py | gorlins/PyMVPA | train | 0 |
62a06265a899f1d422031d38480e05ed3b650020 | [
"query = Query(SkillLine.collection, service_id=self._client.service_id)\nquery.add_term(field=SkillCategory.id_field, value=self.id)\nquery.sort('skill_category_index')\nreturn SequenceProxy(SkillLine, query, client=self._client)",
"query = Query(SkillSet.collection, service_id=self._client.service_id)\nquery.ad... | <|body_start_0|>
query = Query(SkillLine.collection, service_id=self._client.service_id)
query.add_term(field=SkillCategory.id_field, value=self.id)
query.sort('skill_category_index')
return SequenceProxy(SkillLine, query, client=self._client)
<|end_body_0|>
<|body_start_1|>
que... | A skill category for a particular class or vehicle. Skill categories are groups like "Passive Systems", "Performance Slot", or weapon-specific groups like scopes or rail attachments. .. attribute:: id :type: int The unique ID of this skill category. In the API payload, this field is called ``skill_category_id``. .. att... | SkillCategory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkillCategory:
"""A skill category for a particular class or vehicle. Skill categories are groups like "Passive Systems", "Performance Slot", or weapon-specific groups like scopes or rail attachments. .. attribute:: id :type: int The unique ID of this skill category. In the API payload, this fiel... | stack_v2_sparse_classes_36k_train_020370 | 11,338 | permissive | [
{
"docstring": "Return the skill lines contained in this category. This returns a :class:`auraxium.SequenceProxy`.",
"name": "skill_lines",
"signature": "def skill_lines(self) -> SequenceProxy['SkillLine']"
},
{
"docstring": "Return the skill set for this category. This returns an :class:`auraxi... | 2 | null | Implement the Python class `SkillCategory` described below.
Class description:
A skill category for a particular class or vehicle. Skill categories are groups like "Passive Systems", "Performance Slot", or weapon-specific groups like scopes or rail attachments. .. attribute:: id :type: int The unique ID of this skill ... | Implement the Python class `SkillCategory` described below.
Class description:
A skill category for a particular class or vehicle. Skill categories are groups like "Passive Systems", "Performance Slot", or weapon-specific groups like scopes or rail attachments. .. attribute:: id :type: int The unique ID of this skill ... | 23dcf927a199c8d7c917d89fe96b470a34cf4bba | <|skeleton|>
class SkillCategory:
"""A skill category for a particular class or vehicle. Skill categories are groups like "Passive Systems", "Performance Slot", or weapon-specific groups like scopes or rail attachments. .. attribute:: id :type: int The unique ID of this skill category. In the API payload, this fiel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkillCategory:
"""A skill category for a particular class or vehicle. Skill categories are groups like "Passive Systems", "Performance Slot", or weapon-specific groups like scopes or rail attachments. .. attribute:: id :type: int The unique ID of this skill category. In the API payload, this field is called `... | the_stack_v2_python_sparse | auraxium/ps2/_skill.py | leonhard-s/auraxium | train | 29 |
528696d93a9963e1ca6d9c9eeb46f42190c6a0da | [
"self.positiveWords = set()\nself.negativeWords = set()\nfile = open(positives, 'r')\nlines = file.readlines()\nfor line in lines:\n if line[0] == ';' or line[0] == ' ':\n continue\n self.positiveWords.add(line.rstrip('\\n'))\nfile.close()\nfile = open(negatives, 'r')\nlines = file.readlines()\nfor lin... | <|body_start_0|>
self.positiveWords = set()
self.negativeWords = set()
file = open(positives, 'r')
lines = file.readlines()
for line in lines:
if line[0] == ';' or line[0] == ' ':
continue
self.positiveWords.add(line.rstrip('\n'))
f... | Implements sentiment analysis. | Analyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Analyzer:
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
<|body_0|>
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_020371 | 2,142 | no_license | [
{
"docstring": "Initialize Analyzer.",
"name": "__init__",
"signature": "def __init__(self, positives, negatives)"
},
{
"docstring": "Analyze text for sentiment, returning its score.",
"name": "analyze",
"signature": "def analyze(self, text)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000215 | Implement the Python class `Analyzer` described below.
Class description:
Implements sentiment analysis.
Method signatures and docstrings:
- def __init__(self, positives, negatives): Initialize Analyzer.
- def analyze(self, text): Analyze text for sentiment, returning its score. | Implement the Python class `Analyzer` described below.
Class description:
Implements sentiment analysis.
Method signatures and docstrings:
- def __init__(self, positives, negatives): Initialize Analyzer.
- def analyze(self, text): Analyze text for sentiment, returning its score.
<|skeleton|>
class Analyzer:
"""I... | 8809d6774996a51bd763e067584b894c400bffb9 | <|skeleton|>
class Analyzer:
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
<|body_0|>
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Analyzer:
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
self.positiveWords = set()
self.negativeWords = set()
file = open(positives, 'r')
lines = file.readlines()
for line in lines:
if ... | the_stack_v2_python_sparse | pset6/sentiments/analyzer.py | jpriggs/cs50 | train | 0 |
e28318a318280b0f4bbc8f0c574e4d5039d26b16 | [
"cur, pre = (head, None)\nwhile cur:\n next = cur.next\n cur.next = pre\n pre = cur\n cur = next\nreturn pre",
"fast = slow = head\nwhile fast.next and fast.next.next and slow.next:\n fast = fast.next.next\n slow = slow.next\n if slow == fast:\n return True\nreturn False",
"pre, pre.... | <|body_start_0|>
cur, pre = (head, None)
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
<|end_body_0|>
<|body_start_1|>
fast = slow = head
while fast.next and fast.next.next and slow.next:
fas... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def f(self, head):
"""链表中是否有环"""
<|body_1|>
def f1(self, head):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
<|body_2|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_020372 | 1,169 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": "链表中是否有环",
"name": "f",
"signature": "def f(self, head)"
},
{
"docstring": "给定 1->2->3->4, 你应该返回 2->1->4->3.",
"name": "f1",
"signat... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def f(self, head): 链表中是否有环
- def f1(self, head): 给定 1->2->3->4, 你应该返回 2->1->4->3. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def f(self, head): 链表中是否有环
- def f1(self, head): 给定 1->2->3->4, 你应该返回 2->1->4->3.
<|skeleton|>
class Solutio... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def f(self, head):
"""链表中是否有环"""
<|body_1|>
def f1(self, head):
"""给定 1->2->3->4, 你应该返回 2->1->4->3."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
cur, pre = (head, None)
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
def f(self, head):
"""链表中是否有环"""
... | the_stack_v2_python_sparse | 算法/练习算法.py | RichieSong/algorithm | train | 0 | |
7ba867e31377c9580051df1288119d8b2d31ebdd | [
"uglies = [1]\nmerged = heapq.merge(*map(lambda p: (u * p for u in uglies), primes))\nuniqed = (u for u, _ in itertools.groupby(merged))\nmap(uglies.append, itertools.islice(uniqed, n - 1))\nreturn uglies[-1]",
"uglies = [1]\n\ndef gen(prime):\n for ugly in uglies:\n yield (ugly * prime)\nmerged = heapq... | <|body_start_0|>
uglies = [1]
merged = heapq.merge(*map(lambda p: (u * p for u in uglies), primes))
uniqed = (u for u, _ in itertools.groupby(merged))
map(uglies.append, itertools.islice(uniqed, n - 1))
return uglies[-1]
<|end_body_0|>
<|body_start_1|>
uglies = [1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int beats 84.85%"""
<|body_0|>
def nthSuperUglyNumber1(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int beats 85.23%"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_020373 | 948 | no_license | [
{
"docstring": ":type n: int :type primes: List[int] :rtype: int beats 84.85%",
"name": "nthSuperUglyNumber",
"signature": "def nthSuperUglyNumber(self, n, primes)"
},
{
"docstring": ":type n: int :type primes: List[int] :rtype: int beats 85.23%",
"name": "nthSuperUglyNumber1",
"signatur... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int beats 84.85%
- def nthSuperUglyNumber1(self, n, primes): :type n: int :type primes: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nthSuperUglyNumber(self, n, primes): :type n: int :type primes: List[int] :rtype: int beats 84.85%
- def nthSuperUglyNumber1(self, n, primes): :type n: int :type primes: List... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int beats 84.85%"""
<|body_0|>
def nthSuperUglyNumber1(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int beats 85.23%"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def nthSuperUglyNumber(self, n, primes):
""":type n: int :type primes: List[int] :rtype: int beats 84.85%"""
uglies = [1]
merged = heapq.merge(*map(lambda p: (u * p for u in uglies), primes))
uniqed = (u for u, _ in itertools.groupby(merged))
map(uglies.append... | the_stack_v2_python_sparse | LeetCode/313_super_ugly_number.py | yao23/Machine_Learning_Playground | train | 12 | |
4d95b7f12dde84de2a60d1fabcae66ed0189e857 | [
"assert x_interpolated[-1] <= x_predicted[-1], 'x_predicted[-1]={} but x_interpolated[-1]={}'.format(x_predicted[-1], x_interpolated[-1])\nself.x_predicted = x_predicted\nself.x_interpolated = x_interpolated\nself.weights = tt.as_tensor_variable(interpolation_weights(x_predicted, x_interpolated))\nreturn super().__... | <|body_start_0|>
assert x_interpolated[-1] <= x_predicted[-1], 'x_predicted[-1]={} but x_interpolated[-1]={}'.format(x_predicted[-1], x_interpolated[-1])
self.x_predicted = x_predicted
self.x_interpolated = x_interpolated
self.weights = tt.as_tensor_variable(interpolation_weights(x_predi... | Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates. | InterpolationOps | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterpolationOps:
"""Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates."""
def __init__(self, x_predicted, x_interpolated):
"""Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predi... | stack_v2_sparse_classes_36k_train_020374 | 10,590 | no_license | [
{
"docstring": "Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predicted (T_pred,) x_interpolated (ndarray): x-coordinates for which Y is desired (T_data,)",
"name": "__init__",
"signature": "def __init__(self, x_predicted, x_interpolated)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_017956 | Implement the Python class `InterpolationOps` described below.
Class description:
Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates.
Method signatures and docstrings:
- def __init__(self, x_predicted, x_interpolated): Prepare an interpolation subgraph. Args: x_pre... | Implement the Python class `InterpolationOps` described below.
Class description:
Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates.
Method signatures and docstrings:
- def __init__(self, x_predicted, x_interpolated): Prepare an interpolation subgraph. Args: x_pre... | da2b583efc7083a4d6bdbfc4c5deb3e92f380118 | <|skeleton|>
class InterpolationOps:
"""Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates."""
def __init__(self, x_predicted, x_interpolated):
"""Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterpolationOps:
"""Linearly interpolates the entries in a tensor according to vectors of predicted and desired coordinates."""
def __init__(self, x_predicted, x_interpolated):
"""Prepare an interpolation subgraph. Args: x_predicted (ndarray): x-coordinates for which Y will be predicted (T_pred,... | the_stack_v2_python_sparse | Find_RCR/RCR2_identification.py | PredictiveIntelligenceLab/1DBloodFlowPINNs | train | 44 |
74744a0a4c26bda4051d9106bab13421f23cd244 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn GroupSetting()",
"from .entity import Entity\nfrom .setting_value import SettingValue\nfrom .entity import Entity\nfrom .setting_value import SettingValue\nfields: Dict[str, Callable[[Any], None]] = {'displayName': lambda n: setattr(se... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return GroupSetting()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .setting_value import SettingValue
from .entity import Entity
from .setting_value import Se... | GroupSetting | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupSetting:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupSetting:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k_train_020375 | 2,852 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: GroupSetting",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `GroupSetting` described below.
Class description:
Implement the GroupSetting class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupSetting: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `GroupSetting` described below.
Class description:
Implement the GroupSetting class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupSetting: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class GroupSetting:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupSetting:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupSetting:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> GroupSetting:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: GroupSetting""... | the_stack_v2_python_sparse | msgraph/generated/models/group_setting.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
37c17cd9e2b83bc36c80d33561252b737caa0612 | [
"mnist_model = _build_model(two_heads=False)\ntask, eval_task = _mnist_tasks()\ntraining_session = training.Loop(mnist_model, tasks=[task], eval_tasks=[eval_task], eval_at=lambda step_n: step_n % 20 == 0)\ntraining_session.run(n_steps=100)\nself.assertEqual(training_session.step, 100)\nself.assertGreater(_read_metr... | <|body_start_0|>
mnist_model = _build_model(two_heads=False)
task, eval_task = _mnist_tasks()
training_session = training.Loop(mnist_model, tasks=[task], eval_tasks=[eval_task], eval_at=lambda step_n: step_n % 20 == 0)
training_session.run(n_steps=100)
self.assertEqual(training_s... | MnistTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MnistTest:
def test_train_mnist_single_task(self, mock_stdout):
"""Train MNIST model a bit, to compare to other implementations."""
<|body_0|>
def test_train_mnist_multitask(self, mock_stdout):
"""Train two-head MNIST model a bit, to compare to other implementations.... | stack_v2_sparse_classes_36k_train_020376 | 5,307 | permissive | [
{
"docstring": "Train MNIST model a bit, to compare to other implementations.",
"name": "test_train_mnist_single_task",
"signature": "def test_train_mnist_single_task(self, mock_stdout)"
},
{
"docstring": "Train two-head MNIST model a bit, to compare to other implementations.",
"name": "test... | 2 | null | Implement the Python class `MnistTest` described below.
Class description:
Implement the MnistTest class.
Method signatures and docstrings:
- def test_train_mnist_single_task(self, mock_stdout): Train MNIST model a bit, to compare to other implementations.
- def test_train_mnist_multitask(self, mock_stdout): Train tw... | Implement the Python class `MnistTest` described below.
Class description:
Implement the MnistTest class.
Method signatures and docstrings:
- def test_train_mnist_single_task(self, mock_stdout): Train MNIST model a bit, to compare to other implementations.
- def test_train_mnist_multitask(self, mock_stdout): Train tw... | 1bb3b89427f669f2f0ec84633952e21b68964a23 | <|skeleton|>
class MnistTest:
def test_train_mnist_single_task(self, mock_stdout):
"""Train MNIST model a bit, to compare to other implementations."""
<|body_0|>
def test_train_mnist_multitask(self, mock_stdout):
"""Train two-head MNIST model a bit, to compare to other implementations.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MnistTest:
def test_train_mnist_single_task(self, mock_stdout):
"""Train MNIST model a bit, to compare to other implementations."""
mnist_model = _build_model(two_heads=False)
task, eval_task = _mnist_tasks()
training_session = training.Loop(mnist_model, tasks=[task], eval_task... | the_stack_v2_python_sparse | trax/supervised/mnist_test.py | google/trax | train | 8,180 | |
1f5dd48e3a1863222ab6ce02b6c97ed368020faa | [
"self.self_attn = ConditionalAttention(**self.self_attn_cfg)\nself.cross_attn = ConditionalAttention(**self.cross_attn_cfg)\nself.embed_dims = self.self_attn.embed_dims\nself.ffn = FFN(**self.ffn_cfg)\nnorms_list = [build_norm_layer(self.norm_cfg, self.embed_dims)[1] for _ in range(3)]\nself.norms = ModuleList(norm... | <|body_start_0|>
self.self_attn = ConditionalAttention(**self.self_attn_cfg)
self.cross_attn = ConditionalAttention(**self.cross_attn_cfg)
self.embed_dims = self.self_attn.embed_dims
self.ffn = FFN(**self.ffn_cfg)
norms_list = [build_norm_layer(self.norm_cfg, self.embed_dims)[1] ... | Implements decoder layer in DAB-DETR transformer. | DABDetrTransformerDecoderLayer | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DABDetrTransformerDecoderLayer:
"""Implements decoder layer in DAB-DETR transformer."""
def _init_layers(self):
"""Initialize self-attention, cross-attention, FFN, normalization and others."""
<|body_0|>
def forward(self, query: Tensor, key: Tensor, query_pos: Tensor, ke... | stack_v2_sparse_classes_36k_train_020377 | 11,683 | permissive | [
{
"docstring": "Initialize self-attention, cross-attention, FFN, normalization and others.",
"name": "_init_layers",
"signature": "def _init_layers(self)"
},
{
"docstring": "Args: query (Tensor): The input query with shape [bs, num_queries, dim]. key (Tensor): The key tensor with shape [bs, num_... | 2 | null | Implement the Python class `DABDetrTransformerDecoderLayer` described below.
Class description:
Implements decoder layer in DAB-DETR transformer.
Method signatures and docstrings:
- def _init_layers(self): Initialize self-attention, cross-attention, FFN, normalization and others.
- def forward(self, query: Tensor, ke... | Implement the Python class `DABDetrTransformerDecoderLayer` described below.
Class description:
Implements decoder layer in DAB-DETR transformer.
Method signatures and docstrings:
- def _init_layers(self): Initialize self-attention, cross-attention, FFN, normalization and others.
- def forward(self, query: Tensor, ke... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DABDetrTransformerDecoderLayer:
"""Implements decoder layer in DAB-DETR transformer."""
def _init_layers(self):
"""Initialize self-attention, cross-attention, FFN, normalization and others."""
<|body_0|>
def forward(self, query: Tensor, key: Tensor, query_pos: Tensor, ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DABDetrTransformerDecoderLayer:
"""Implements decoder layer in DAB-DETR transformer."""
def _init_layers(self):
"""Initialize self-attention, cross-attention, FFN, normalization and others."""
self.self_attn = ConditionalAttention(**self.self_attn_cfg)
self.cross_attn = Conditiona... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/layers/transformer/dab_detr_layers.py | alldatacenter/alldata | train | 774 |
0ff4a23cbefc050faf7bba571527f350caf3cfe2 | [
"if general_md is None:\n general_md = metadata_info.GeneralMd(name=_MODEL_NAME, description=MODEL_DESCRIPTION)\nif input_md is None:\n input_md = metadata_info.InputImageTensorMd(name=INPUT_NAME, description=INPUT_DESCRIPTION, color_space_type=_metadata_fb.ColorSpaceType.RGB)\nif output_md is None:\n outp... | <|body_start_0|>
if general_md is None:
general_md = metadata_info.GeneralMd(name=_MODEL_NAME, description=MODEL_DESCRIPTION)
if input_md is None:
input_md = metadata_info.InputImageTensorMd(name=INPUT_NAME, description=INPUT_DESCRIPTION, color_space_type=_metadata_fb.ColorSpaceT... | Writes metadata into an image classifier. | MetadataWriter | [
"GPL-1.0-or-later",
"MIT",
"LGPL-2.0-or-later",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataWriter:
"""Writes metadata into an image classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputImageTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]... | stack_v2_sparse_classes_36k_train_020378 | 5,768 | permissive | [
{
"docstring": "Creates MetadataWriter based on general/input/output information. Args: model_buffer: valid buffer of the model file. general_md: general information about the model. If not specified, default general metadata will be generated. input_md: input image tensor informaton, if not specified, default ... | 2 | null | Implement the Python class `MetadataWriter` described below.
Class description:
Writes metadata into an image classifier.
Method signatures and docstrings:
- def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputImageTenso... | Implement the Python class `MetadataWriter` described below.
Class description:
Writes metadata into an image classifier.
Method signatures and docstrings:
- def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputImageTenso... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class MetadataWriter:
"""Writes metadata into an image classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputImageTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetadataWriter:
"""Writes metadata into an image classifier."""
def create_from_metadata_info(cls, model_buffer: bytearray, general_md: Optional[metadata_info.GeneralMd]=None, input_md: Optional[metadata_info.InputImageTensorMd]=None, output_md: Optional[metadata_info.ClassificationTensorMd]=None):
... | the_stack_v2_python_sparse | third_party/tflite_support/src/tensorflow_lite_support/metadata/python/metadata_writers/image_classifier.py | chromium/chromium | train | 17,408 |
78eac0d7ab32ee63c9542b0a7e7ed12ea5fe9fcf | [
"super(HonourAutoCombat, self).start()\nfor char in self.characters.values():\n character = char['char']\n character.start_auto_combat_skill()",
"for char in self.characters.values():\n character = char['char']\n character.stop_auto_combat_skill()\nawait super(HonourAutoCombat, self).finish()"
] | <|body_start_0|>
super(HonourAutoCombat, self).start()
for char in self.characters.values():
character = char['char']
character.start_auto_combat_skill()
<|end_body_0|>
<|body_start_1|>
for char in self.characters.values():
character = char['char']
... | This implements the honour combat handler. | HonourAutoCombat | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HonourAutoCombat:
"""This implements the honour combat handler."""
def start(self):
"""Start a combat, make all NPCs to cast skills automatically."""
<|body_0|>
async def finish(self):
"""Finish a combat. Send results to players, and kill all failed characters.""... | stack_v2_sparse_classes_36k_train_020379 | 856 | permissive | [
{
"docstring": "Start a combat, make all NPCs to cast skills automatically.",
"name": "start",
"signature": "def start(self)"
},
{
"docstring": "Finish a combat. Send results to players, and kill all failed characters.",
"name": "finish",
"signature": "async def finish(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010611 | Implement the Python class `HonourAutoCombat` described below.
Class description:
This implements the honour combat handler.
Method signatures and docstrings:
- def start(self): Start a combat, make all NPCs to cast skills automatically.
- async def finish(self): Finish a combat. Send results to players, and kill all... | Implement the Python class `HonourAutoCombat` described below.
Class description:
This implements the honour combat handler.
Method signatures and docstrings:
- def start(self): Start a combat, make all NPCs to cast skills automatically.
- async def finish(self): Finish a combat. Send results to players, and kill all... | 5fa06b29bf800646dc4da5851fdf7a1f299f15a7 | <|skeleton|>
class HonourAutoCombat:
"""This implements the honour combat handler."""
def start(self):
"""Start a combat, make all NPCs to cast skills automatically."""
<|body_0|>
async def finish(self):
"""Finish a combat. Send results to players, and kill all failed characters.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HonourAutoCombat:
"""This implements the honour combat handler."""
def start(self):
"""Start a combat, make all NPCs to cast skills automatically."""
super(HonourAutoCombat, self).start()
for char in self.characters.values():
character = char['char']
charac... | the_stack_v2_python_sparse | muddery/server/combat/combat_runner/honour_auto_combat.py | muddery/muddery | train | 139 |
efe6adf707770e8c0724c69fc96c7c4b1ff96e4c | [
"from mpi4py import MPI\nself.OR = MPI.LOR\nsuper().__init__(controller, params, description)\nself.buffers = Pars({'restart': False, 'max_restart_reached': False, 'restart_earlier': False})",
"crash_now = False\nif S.status.first:\n self.buffers.max_restart_reached = S.status.restarts_in_a_row >= self.params.... | <|body_start_0|>
from mpi4py import MPI
self.OR = MPI.LOR
super().__init__(controller, params, description)
self.buffers = Pars({'restart': False, 'max_restart_reached': False, 'restart_earlier': False})
<|end_body_0|>
<|body_start_1|>
crash_now = False
if S.status.first... | MPI specific version of basic restarting | BasicRestartingMPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicRestartingMPI:
"""MPI specific version of basic restarting"""
def __init__(self, controller, params, description, **kwargs):
"""Initialization routine. Adds a buffer. Args: controller (pySDC.Controller): The controller params (dict): Parameters for the convergence controller des... | stack_v2_sparse_classes_36k_train_020380 | 12,854 | permissive | [
{
"docstring": "Initialization routine. Adds a buffer. Args: controller (pySDC.Controller): The controller params (dict): Parameters for the convergence controller description (dict): The description object used to instantiate the controller",
"name": "__init__",
"signature": "def __init__(self, control... | 3 | null | Implement the Python class `BasicRestartingMPI` described below.
Class description:
MPI specific version of basic restarting
Method signatures and docstrings:
- def __init__(self, controller, params, description, **kwargs): Initialization routine. Adds a buffer. Args: controller (pySDC.Controller): The controller par... | Implement the Python class `BasicRestartingMPI` described below.
Class description:
MPI specific version of basic restarting
Method signatures and docstrings:
- def __init__(self, controller, params, description, **kwargs): Initialization routine. Adds a buffer. Args: controller (pySDC.Controller): The controller par... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class BasicRestartingMPI:
"""MPI specific version of basic restarting"""
def __init__(self, controller, params, description, **kwargs):
"""Initialization routine. Adds a buffer. Args: controller (pySDC.Controller): The controller params (dict): Parameters for the convergence controller des... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicRestartingMPI:
"""MPI specific version of basic restarting"""
def __init__(self, controller, params, description, **kwargs):
"""Initialization routine. Adds a buffer. Args: controller (pySDC.Controller): The controller params (dict): Parameters for the convergence controller description (dic... | the_stack_v2_python_sparse | pySDC/implementations/convergence_controller_classes/basic_restarting.py | Parallel-in-Time/pySDC | train | 30 |
667e7285aed8a0d88d949e76445fa0845f990b5a | [
"try:\n file_cnt = save_upload_file(request, nnid, ver, node)\n return Response(json.dumps(['{0} file upload success'.format(file_cnt)]))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = ''\n return Res... | <|body_start_0|>
try:
file_cnt = save_upload_file(request, nnid, ver, node)
return Response(json.dumps(['{0} file upload success'.format(file_cnt)]))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return... | WorkFlowDataImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowDataImage:
def post(self, request, src, form, prg, nnid, ver, node):
"""This API is for set node parameters This node is for data extraction This node especially handles image type data You can set source server by set up parameters --- # Class Name : WorkFlowDataImage # Descript... | stack_v2_sparse_classes_36k_train_020381 | 3,962 | permissive | [
{
"docstring": "This API is for set node parameters This node is for data extraction This node especially handles image type data You can set source server by set up parameters --- # Class Name : WorkFlowDataImage # Description: Set params for data source, preprocess method and etc",
"name": "post",
"si... | 4 | null | Implement the Python class `WorkFlowDataImage` described below.
Class description:
Implement the WorkFlowDataImage class.
Method signatures and docstrings:
- def post(self, request, src, form, prg, nnid, ver, node): This API is for set node parameters This node is for data extraction This node especially handles imag... | Implement the Python class `WorkFlowDataImage` described below.
Class description:
Implement the WorkFlowDataImage class.
Method signatures and docstrings:
- def post(self, request, src, form, prg, nnid, ver, node): This API is for set node parameters This node is for data extraction This node especially handles imag... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowDataImage:
def post(self, request, src, form, prg, nnid, ver, node):
"""This API is for set node parameters This node is for data extraction This node especially handles image type data You can set source server by set up parameters --- # Class Name : WorkFlowDataImage # Descript... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkFlowDataImage:
def post(self, request, src, form, prg, nnid, ver, node):
"""This API is for set node parameters This node is for data extraction This node especially handles image type data You can set source server by set up parameters --- # Class Name : WorkFlowDataImage # Description: Set param... | the_stack_v2_python_sparse | api/views/workflow_data_image.py | yurimkoo/tensormsa | train | 1 | |
61a207b4fcc9ad4920cc3dce5e1517a9bfda113c | [
"self.avg_logical_transfer_rate_bps = avg_logical_transfer_rate_bps\nself.bytes_transferred = bytes_transferred\nself.end_time_usecs = end_time_usecs\nself.error = error\nself.logical_bytes_transferred = logical_bytes_transferred\nself.logical_size_bytes = logical_size_bytes\nself.progress_monitor_task_path = progr... | <|body_start_0|>
self.avg_logical_transfer_rate_bps = avg_logical_transfer_rate_bps
self.bytes_transferred = bytes_transferred
self.end_time_usecs = end_time_usecs
self.error = error
self.logical_bytes_transferred = logical_bytes_transferred
self.logical_size_bytes = logi... | Implementation of the 'RetrieveArchiveInfo' model. Proto to describe information about the retrieval of an archive task as provided by Icebox. Attributes: avg_logical_transfer_rate_bps (long|int): Average logical bytes transfer rate in bytes per second as seen by Icebox. bytes_transferred (long|int): Number of physical... | RetrieveArchiveInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrieveArchiveInfo:
"""Implementation of the 'RetrieveArchiveInfo' model. Proto to describe information about the retrieval of an archive task as provided by Icebox. Attributes: avg_logical_transfer_rate_bps (long|int): Average logical bytes transfer rate in bytes per second as seen by Icebox. b... | stack_v2_sparse_classes_36k_train_020382 | 7,377 | permissive | [
{
"docstring": "Constructor for the RetrieveArchiveInfo class",
"name": "__init__",
"signature": "def __init__(self, avg_logical_transfer_rate_bps=None, bytes_transferred=None, end_time_usecs=None, error=None, logical_bytes_transferred=None, logical_size_bytes=None, progress_monitor_task_path=None, retr... | 2 | null | Implement the Python class `RetrieveArchiveInfo` described below.
Class description:
Implementation of the 'RetrieveArchiveInfo' model. Proto to describe information about the retrieval of an archive task as provided by Icebox. Attributes: avg_logical_transfer_rate_bps (long|int): Average logical bytes transfer rate i... | Implement the Python class `RetrieveArchiveInfo` described below.
Class description:
Implementation of the 'RetrieveArchiveInfo' model. Proto to describe information about the retrieval of an archive task as provided by Icebox. Attributes: avg_logical_transfer_rate_bps (long|int): Average logical bytes transfer rate i... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RetrieveArchiveInfo:
"""Implementation of the 'RetrieveArchiveInfo' model. Proto to describe information about the retrieval of an archive task as provided by Icebox. Attributes: avg_logical_transfer_rate_bps (long|int): Average logical bytes transfer rate in bytes per second as seen by Icebox. b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RetrieveArchiveInfo:
"""Implementation of the 'RetrieveArchiveInfo' model. Proto to describe information about the retrieval of an archive task as provided by Icebox. Attributes: avg_logical_transfer_rate_bps (long|int): Average logical bytes transfer rate in bytes per second as seen by Icebox. bytes_transfer... | the_stack_v2_python_sparse | cohesity_management_sdk/models/retrieve_archive_info.py | cohesity/management-sdk-python | train | 24 |
7a63f333c783129ef9db683591e049f1cd48cdae | [
"assert super_voter, 'Cannot initialize without a super voter.'\nsuper().__init__(allow_all_abstain=allow_all_abstain, cascade_authorization=cascade_authorization)\nself.__super_voter = super_voter",
"if self.__super_voter.supports(expression, attribute) and self.__super_voter.vote(authentication, expression, att... | <|body_start_0|>
assert super_voter, 'Cannot initialize without a super voter.'
super().__init__(allow_all_abstain=allow_all_abstain, cascade_authorization=cascade_authorization)
self.__super_voter = super_voter
<|end_body_0|>
<|body_start_1|>
if self.__super_voter.supports(expression, ... | A decision manager that grants access to a super user. | SuperUserDecisionManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperUserDecisionManager:
"""A decision manager that grants access to a super user."""
def __init__(self, super_voter, voters, allow_all_abstain=False, cascade_authorization=True):
"""Creates a new decision manager. Args: super_voter: a voter that used to make decisions about a super... | stack_v2_sparse_classes_36k_train_020383 | 12,706 | permissive | [
{
"docstring": "Creates a new decision manager. Args: super_voter: a voter that used to make decisions about a super user voters: the voters used to make access decisions. Accepts either a single voter or an iterable collection of voters.",
"name": "__init__",
"signature": "def __init__(self, super_vote... | 2 | stack_v2_sparse_classes_30k_train_009630 | Implement the Python class `SuperUserDecisionManager` described below.
Class description:
A decision manager that grants access to a super user.
Method signatures and docstrings:
- def __init__(self, super_voter, voters, allow_all_abstain=False, cascade_authorization=True): Creates a new decision manager. Args: super... | Implement the Python class `SuperUserDecisionManager` described below.
Class description:
A decision manager that grants access to a super user.
Method signatures and docstrings:
- def __init__(self, super_voter, voters, allow_all_abstain=False, cascade_authorization=True): Creates a new decision manager. Args: super... | 08e012f39b1ae4c435830e817167037d10f5db32 | <|skeleton|>
class SuperUserDecisionManager:
"""A decision manager that grants access to a super user."""
def __init__(self, super_voter, voters, allow_all_abstain=False, cascade_authorization=True):
"""Creates a new decision manager. Args: super_voter: a voter that used to make decisions about a super... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperUserDecisionManager:
"""A decision manager that grants access to a super user."""
def __init__(self, super_voter, voters, allow_all_abstain=False, cascade_authorization=True):
"""Creates a new decision manager. Args: super_voter: a voter that used to make decisions about a super user voters:... | the_stack_v2_python_sparse | dorthy/security/access.py | kurtrwall/dorthy | train | 0 |
92ed1df6416367c9fbf4703aac6bb499b383b143 | [
"Algorithm.__init__(self)\nself.name = 'Bilateral Filter'\nself.parent = 'Preprocessing'\nself.diameter = IntegerSlider('diameter', 1, 20, 1, 1)\nself.sigma_color = FloatSlider('sigmaColor', 0.0, 255.0, 0.1, 30.0)\nself.sigma_space = FloatSlider('sigmaSpace', 0.0, 255.0, 0.1, 30.0)\nself.channel1 = CheckBox('channe... | <|body_start_0|>
Algorithm.__init__(self)
self.name = 'Bilateral Filter'
self.parent = 'Preprocessing'
self.diameter = IntegerSlider('diameter', 1, 20, 1, 1)
self.sigma_color = FloatSlider('sigmaColor', 0.0, 255.0, 0.1, 30.0)
self.sigma_space = FloatSlider('sigmaSpace', 0... | Bilateral Filter algorithm implementation | AlgBody | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgBody:
"""Bilateral Filter algorithm implementation"""
def __init__(self):
"""Bilateral Filter object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *diameter* : diameter of each pixel neighborhood that is used during fi... | stack_v2_sparse_classes_36k_train_020384 | 3,243 | no_license | [
{
"docstring": "Bilateral Filter object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *diameter* : diameter of each pixel neighborhood that is used during filtering. If it is non-positive, it is computed from sigmaSpace. | *sigma_color* : filter sig... | 2 | null | Implement the Python class `AlgBody` described below.
Class description:
Bilateral Filter algorithm implementation
Method signatures and docstrings:
- def __init__(self): Bilateral Filter object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *diameter* : d... | Implement the Python class `AlgBody` described below.
Class description:
Bilateral Filter algorithm implementation
Method signatures and docstrings:
- def __init__(self): Bilateral Filter object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *diameter* : d... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class AlgBody:
"""Bilateral Filter algorithm implementation"""
def __init__(self):
"""Bilateral Filter object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *diameter* : diameter of each pixel neighborhood that is used during fi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgBody:
"""Bilateral Filter algorithm implementation"""
def __init__(self):
"""Bilateral Filter object constructor Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriated category | *diameter* : diameter of each pixel neighborhood that is used during filtering. If i... | the_stack_v2_python_sparse | Sebastian_Algorithms_untested/bilateral.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 |
530578ca3743cd681ee34187fd88b505d0f3650e | [
"_table_1 = DataFrame({'a': [1.0, 2.0, 3.0], 'b': [2.0, 3.0, 4.0]})\n_cleanings = [{'operator': 'drop_if_equal', 'columns': ['a'], 'value': 'NaN'}, {'operator': 'drop_if_equal', 'columns': ['b'], 'value': 'NaN'}]\n_rf = RowFilter(_table_1)\n_rf.filter(_cleanings)\nassert_frame_equal(_table_1, _rf.frame)",
"_table... | <|body_start_0|>
_table_1 = DataFrame({'a': [1.0, 2.0, 3.0], 'b': [2.0, 3.0, 4.0]})
_cleanings = [{'operator': 'drop_if_equal', 'columns': ['a'], 'value': 'NaN'}, {'operator': 'drop_if_equal', 'columns': ['b'], 'value': 'NaN'}]
_rf = RowFilter(_table_1)
_rf.filter(_cleanings)
ass... | Tests for the ``preprocess._clean_variables`` module dropping rows based on ``== "NaN"`` | CleanDropIfNaNTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanDropIfNaNTests:
"""Tests for the ``preprocess._clean_variables`` module dropping rows based on ``== "NaN"``"""
def test_drop_if_equal_nan_1():
"""Test that nothing is dropped"""
<|body_0|>
def test_drop_if_equal_nan_2():
"""Test that a single row is dropped"... | stack_v2_sparse_classes_36k_train_020385 | 2,733 | permissive | [
{
"docstring": "Test that nothing is dropped",
"name": "test_drop_if_equal_nan_1",
"signature": "def test_drop_if_equal_nan_1()"
},
{
"docstring": "Test that a single row is dropped",
"name": "test_drop_if_equal_nan_2",
"signature": "def test_drop_if_equal_nan_2()"
},
{
"docstrin... | 5 | stack_v2_sparse_classes_30k_train_012623 | Implement the Python class `CleanDropIfNaNTests` described below.
Class description:
Tests for the ``preprocess._clean_variables`` module dropping rows based on ``== "NaN"``
Method signatures and docstrings:
- def test_drop_if_equal_nan_1(): Test that nothing is dropped
- def test_drop_if_equal_nan_2(): Test that a s... | Implement the Python class `CleanDropIfNaNTests` described below.
Class description:
Tests for the ``preprocess._clean_variables`` module dropping rows based on ``== "NaN"``
Method signatures and docstrings:
- def test_drop_if_equal_nan_1(): Test that nothing is dropped
- def test_drop_if_equal_nan_2(): Test that a s... | 2e89bc55a61ce2a4ce77646bb427f5b3040f672c | <|skeleton|>
class CleanDropIfNaNTests:
"""Tests for the ``preprocess._clean_variables`` module dropping rows based on ``== "NaN"``"""
def test_drop_if_equal_nan_1():
"""Test that nothing is dropped"""
<|body_0|>
def test_drop_if_equal_nan_2():
"""Test that a single row is dropped"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CleanDropIfNaNTests:
"""Tests for the ``preprocess._clean_variables`` module dropping rows based on ``== "NaN"``"""
def test_drop_if_equal_nan_1():
"""Test that nothing is dropped"""
_table_1 = DataFrame({'a': [1.0, 2.0, 3.0], 'b': [2.0, 3.0, 4.0]})
_cleanings = [{'operator': 'dro... | the_stack_v2_python_sparse | numom2b_preprocessing/unittests/row_filter_tests/test_drop_if_nan.py | hayesall/nuMoM2b_preprocessing | train | 2 |
bd5eccb0b090739872c67e0010e169396484f35d | [
"if not isinstance(results, (str, list, tuple)):\n raise ParameterError('result parameter must be is {}, but actually get {}'.format((str, list, tuple), type(results)))\nif isinstance(results, (list, tuple)):\n for result in results:\n if not isinstance(result, str):\n raise ParameterError('... | <|body_start_0|>
if not isinstance(results, (str, list, tuple)):
raise ParameterError('result parameter must be is {}, but actually get {}'.format((str, list, tuple), type(results)))
if isinstance(results, (list, tuple)):
for result in results:
if not isinstance(r... | Writer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Writer:
def writer_file(file, results, mode='a', encoding='utf-8'):
"""输入字符串、列表字符,写入文件 :param file: (str, mandatory) 文件名 或 路径 + 文件名 :param results: (str or list or tuple, mandatory) 需要写入文件的字符集或单个字符串。例如"hello word" 或['hello world'] :param mode: (str, optional, default='a') 模式。默认为 'a' ,追加模... | stack_v2_sparse_classes_36k_train_020386 | 3,286 | no_license | [
{
"docstring": "输入字符串、列表字符,写入文件 :param file: (str, mandatory) 文件名 或 路径 + 文件名 :param results: (str or list or tuple, mandatory) 需要写入文件的字符集或单个字符串。例如\"hello word\" 或['hello world'] :param mode: (str, optional, default='a') 模式。默认为 'a' ,追加模式 :param encoding: (str, optional, default='utf-8') 编码。默认为 UTF-8 编码 :return:"... | 3 | stack_v2_sparse_classes_30k_train_004359 | Implement the Python class `Writer` described below.
Class description:
Implement the Writer class.
Method signatures and docstrings:
- def writer_file(file, results, mode='a', encoding='utf-8'): 输入字符串、列表字符,写入文件 :param file: (str, mandatory) 文件名 或 路径 + 文件名 :param results: (str or list or tuple, mandatory) 需要写入文件的字符集或... | Implement the Python class `Writer` described below.
Class description:
Implement the Writer class.
Method signatures and docstrings:
- def writer_file(file, results, mode='a', encoding='utf-8'): 输入字符串、列表字符,写入文件 :param file: (str, mandatory) 文件名 或 路径 + 文件名 :param results: (str or list or tuple, mandatory) 需要写入文件的字符集或... | 8a4f4ac6ae32caa4098da067b7c4a7bd86f01973 | <|skeleton|>
class Writer:
def writer_file(file, results, mode='a', encoding='utf-8'):
"""输入字符串、列表字符,写入文件 :param file: (str, mandatory) 文件名 或 路径 + 文件名 :param results: (str or list or tuple, mandatory) 需要写入文件的字符集或单个字符串。例如"hello word" 或['hello world'] :param mode: (str, optional, default='a') 模式。默认为 'a' ,追加模... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Writer:
def writer_file(file, results, mode='a', encoding='utf-8'):
"""输入字符串、列表字符,写入文件 :param file: (str, mandatory) 文件名 或 路径 + 文件名 :param results: (str or list or tuple, mandatory) 需要写入文件的字符集或单个字符串。例如"hello word" 或['hello world'] :param mode: (str, optional, default='a') 模式。默认为 'a' ,追加模式 :param encod... | the_stack_v2_python_sparse | module/core/writer.py | boyshen/BLTP | train | 2 | |
ede13065510e4903d5f52abfd5b7ae28abab7134 | [
"identifier = self.data['id']\nstate_name = self.data['state_name']\nitem = self.core.item_manager.items.get(identifier)\nif not item:\n return self.error(ERROR_ITEM_NOT_FOUND, f'No item found with identifier {identifier}', 404)\nif state_name not in item.states.states.keys():\n return self.error(ERROR_INVALI... | <|body_start_0|>
identifier = self.data['id']
state_name = self.data['state_name']
item = self.core.item_manager.items.get(identifier)
if not item:
return self.error(ERROR_ITEM_NOT_FOUND, f'No item found with identifier {identifier}', 404)
if state_name not in item.st... | Endpoint for an item state | ItemStateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemStateView:
"""Endpoint for an item state"""
async def post(self) -> JSONResponse:
"""POST /item/{id}/states/{state_name}"""
<|body_0|>
async def get(self) -> JSONResponse:
"""GET /item/{id}/states/{state_name}"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_020387 | 10,547 | permissive | [
{
"docstring": "POST /item/{id}/states/{state_name}",
"name": "post",
"signature": "async def post(self) -> JSONResponse"
},
{
"docstring": "GET /item/{id}/states/{state_name}",
"name": "get",
"signature": "async def get(self) -> JSONResponse"
}
] | 2 | stack_v2_sparse_classes_30k_train_013000 | Implement the Python class `ItemStateView` described below.
Class description:
Endpoint for an item state
Method signatures and docstrings:
- async def post(self) -> JSONResponse: POST /item/{id}/states/{state_name}
- async def get(self) -> JSONResponse: GET /item/{id}/states/{state_name} | Implement the Python class `ItemStateView` described below.
Class description:
Endpoint for an item state
Method signatures and docstrings:
- async def post(self) -> JSONResponse: POST /item/{id}/states/{state_name}
- async def get(self) -> JSONResponse: GET /item/{id}/states/{state_name}
<|skeleton|>
class ItemStat... | ee630d3ebf96d5b1d2055487d49968bdbb93d5b9 | <|skeleton|>
class ItemStateView:
"""Endpoint for an item state"""
async def post(self) -> JSONResponse:
"""POST /item/{id}/states/{state_name}"""
<|body_0|>
async def get(self) -> JSONResponse:
"""GET /item/{id}/states/{state_name}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItemStateView:
"""Endpoint for an item state"""
async def post(self) -> JSONResponse:
"""POST /item/{id}/states/{state_name}"""
identifier = self.data['id']
state_name = self.data['state_name']
item = self.core.item_manager.items.get(identifier)
if not item:
... | the_stack_v2_python_sparse | homecontrol/modules/api/endpoints.py | lennart-k/HomeControl | train | 7 |
987ae6c835a0900db3aa68476a756d5ca97b8a74 | [
"menu_item.MenuItem.__init__(self, main_menu, frame)\nself.create_menu_item_button('User Management')\nself.menu_item_button['command'] = self.get_user_management_window",
"self.gui.active_window.hide()\nself.associated_window = user_management_window.UserManagementWindow(self.gui)\nself.gui.active_window = self.... | <|body_start_0|>
menu_item.MenuItem.__init__(self, main_menu, frame)
self.create_menu_item_button('User Management')
self.menu_item_button['command'] = self.get_user_management_window
<|end_body_0|>
<|body_start_1|>
self.gui.active_window.hide()
self.associated_window = user_man... | This class is used to create a button that will bring the user to the user management menu. | UserManagementMenuItem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserManagementMenuItem:
"""This class is used to create a button that will bring the user to the user management menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the G... | stack_v2_sparse_classes_36k_train_020388 | 1,091 | no_license | [
{
"docstring": "Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active window",
"name": "__init__",
"signature": "def __init__(self, main_menu, frame)"
},
{
"docstring": "This function will hide everything on the activ... | 2 | stack_v2_sparse_classes_30k_train_011593 | Implement the Python class `UserManagementMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the user management menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu b... | Implement the Python class `UserManagementMenuItem` described below.
Class description:
This class is used to create a button that will bring the user to the user management menu.
Method signatures and docstrings:
- def __init__(self, main_menu, frame): Args: main_menu ([]): this class must know about the main menu b... | e26d9450b98fa0f372bcdf6eaf251a2c9dcba44e | <|skeleton|>
class UserManagementMenuItem:
"""This class is used to create a button that will bring the user to the user management menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the G... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserManagementMenuItem:
"""This class is used to create a button that will bring the user to the user management menu."""
def __init__(self, main_menu, frame):
"""Args: main_menu ([]): this class must know about the main menu because it knows about the GUI, and we need to alter the GUI's active w... | the_stack_v2_python_sparse | user_interface/menu_items/user_management_menu_item.py | pucheng-tan/WordFlow | train | 0 |
c40b770164453b8f38fd95ee98349bd43e10582f | [
"is_cyclic = False\nnodes = dict()\nwhile head and head.next:\n if head in nodes:\n is_cyclic = True\n break\n nodes[head] = 1\n head = head.next\nreturn is_cyclic",
"is_cylic = False\nhare = head\ntortoise = head\nwhile hare and hare.next:\n hare = hare.next.next\n tortoise = tortois... | <|body_start_0|>
is_cyclic = False
nodes = dict()
while head and head.next:
if head in nodes:
is_cyclic = True
break
nodes[head] = 1
head = head.next
return is_cyclic
<|end_body_0|>
<|body_start_1|>
is_cylic = F... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
"""This solution uses a dict to keep track of all the nodes visited. Solution - Runtime 29.5% Memory 14.8%"""
<|body_0|>
def neetcode(self, head: Optional[ListNode]) -> bool:
"""This uses the rabbit and ... | stack_v2_sparse_classes_36k_train_020389 | 1,693 | no_license | [
{
"docstring": "This solution uses a dict to keep track of all the nodes visited. Solution - Runtime 29.5% Memory 14.8%",
"name": "hasCycle",
"signature": "def hasCycle(self, head: Optional[ListNode]) -> bool"
},
{
"docstring": "This uses the rabbit and tortoise method, the rabbit moves double t... | 2 | stack_v2_sparse_classes_30k_train_017459 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head: Optional[ListNode]) -> bool: This solution uses a dict to keep track of all the nodes visited. Solution - Runtime 29.5% Memory 14.8%
- def neetcode(self,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head: Optional[ListNode]) -> bool: This solution uses a dict to keep track of all the nodes visited. Solution - Runtime 29.5% Memory 14.8%
- def neetcode(self,... | 6428b8f71951ae7491b5c968eff217fefa82870a | <|skeleton|>
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
"""This solution uses a dict to keep track of all the nodes visited. Solution - Runtime 29.5% Memory 14.8%"""
<|body_0|>
def neetcode(self, head: Optional[ListNode]) -> bool:
"""This uses the rabbit and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
"""This solution uses a dict to keep track of all the nodes visited. Solution - Runtime 29.5% Memory 14.8%"""
is_cyclic = False
nodes = dict()
while head and head.next:
if head in nodes:
... | the_stack_v2_python_sparse | LeetCode/9_lc_141_linked_list_cycle.py | ishamibrahim/BasicProgramming | train | 0 | |
afc736b1b3a17b901a6b3de7a42b9171b45c2c12 | [
"self.X = x\nself.Y = y\nself.kernel = kernel\nself.noise_variance = noise_variance\nself.cov = None if self.X is None else kernel.compute(self.X, self.X)\nself.max_observed_value = -99999",
"k_2star = self.kernel.compute(x, x)\nif self.cov is None:\n mu = np.zeros(x.shape)\n cov_posterior = k_2star + self.... | <|body_start_0|>
self.X = x
self.Y = y
self.kernel = kernel
self.noise_variance = noise_variance
self.cov = None if self.X is None else kernel.compute(self.X, self.X)
self.max_observed_value = -99999
<|end_body_0|>
<|body_start_1|>
k_2star = self.kernel.compute(x... | Implements a GP with mean zero and a custom kernel | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Implements a GP with mean zero and a custom kernel"""
def __init__(self, kernel=Matern52Kernel(), noise_variance=5e-05, x=None, y=None):
"""Initialize the GP with the given kernel and a noise parameter for the variance Optionally initialize this GP with given X an... | stack_v2_sparse_classes_36k_train_020390 | 3,767 | no_license | [
{
"docstring": "Initialize the GP with the given kernel and a noise parameter for the variance Optionally initialize this GP with given X and Y :param kernel: kernel function, has to be an instance of Kernel :param noise_variance: :param x: given input data :param y: given input label :return:",
"name": "__... | 2 | stack_v2_sparse_classes_30k_train_011146 | Implement the Python class `GaussianProcess` described below.
Class description:
Implements a GP with mean zero and a custom kernel
Method signatures and docstrings:
- def __init__(self, kernel=Matern52Kernel(), noise_variance=5e-05, x=None, y=None): Initialize the GP with the given kernel and a noise parameter for t... | Implement the Python class `GaussianProcess` described below.
Class description:
Implements a GP with mean zero and a custom kernel
Method signatures and docstrings:
- def __init__(self, kernel=Matern52Kernel(), noise_variance=5e-05, x=None, y=None): Initialize the GP with the given kernel and a noise parameter for t... | e93e7fa1fecf1ab333672f70009fd1a145ef60e4 | <|skeleton|>
class GaussianProcess:
"""Implements a GP with mean zero and a custom kernel"""
def __init__(self, kernel=Matern52Kernel(), noise_variance=5e-05, x=None, y=None):
"""Initialize the GP with the given kernel and a noise parameter for the variance Optionally initialize this GP with given X an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcess:
"""Implements a GP with mean zero and a custom kernel"""
def __init__(self, kernel=Matern52Kernel(), noise_variance=5e-05, x=None, y=None):
"""Initialize the GP with the given kernel and a noise parameter for the variance Optionally initialize this GP with given X and Y :param ke... | the_stack_v2_python_sparse | bayesopt/gaussian_process.py | AlexLi-98/misc | train | 0 |
2d7e1075cbb72d1401073ab5749ccc271f88c9bc | [
"x_headers = 'x-ms-date:' + date\nstring_to_hash = method + '\\n' + str(content_length) + '\\n' + content_type + '\\n' + x_headers + '\\n' + resource\nbytes_to_hash = bytes(string_to_hash, encoding='utf-8')\ndecoded_key = base64.b64decode(shared_key)\nencoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_h... | <|body_start_0|>
x_headers = 'x-ms-date:' + date
string_to_hash = method + '\n' + str(content_length) + '\n' + content_type + '\n' + x_headers + '\n' + resource
bytes_to_hash = bytes(string_to_hash, encoding='utf-8')
decoded_key = base64.b64decode(shared_key)
encoded_hash = base6... | AzureSentinel is Used to post data to log analytics. | AzureSentinel | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureSentinel:
"""AzureSentinel is Used to post data to log analytics."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build the signature."""
<|body_0|>
def post_data(self, customer_id, body, log_type):
"""Build and send... | stack_v2_sparse_classes_36k_train_020391 | 8,516 | permissive | [
{
"docstring": "To build the signature.",
"name": "build_signature",
"signature": "def build_signature(self, date, content_length, method, content_type, resource)"
},
{
"docstring": "Build and send a request to the POST API.",
"name": "post_data",
"signature": "def post_data(self, custom... | 2 | null | Implement the Python class `AzureSentinel` described below.
Class description:
AzureSentinel is Used to post data to log analytics.
Method signatures and docstrings:
- def build_signature(self, date, content_length, method, content_type, resource): To build the signature.
- def post_data(self, customer_id, body, log_... | Implement the Python class `AzureSentinel` described below.
Class description:
AzureSentinel is Used to post data to log analytics.
Method signatures and docstrings:
- def build_signature(self, date, content_length, method, content_type, resource): To build the signature.
- def post_data(self, customer_id, body, log_... | 4536a3f6b9bdef902312b3d96f9c2e66b8bf52c1 | <|skeleton|>
class AzureSentinel:
"""AzureSentinel is Used to post data to log analytics."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build the signature."""
<|body_0|>
def post_data(self, customer_id, body, log_type):
"""Build and send... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AzureSentinel:
"""AzureSentinel is Used to post data to log analytics."""
def build_signature(self, date, content_length, method, content_type, resource):
"""To build the signature."""
x_headers = 'x-ms-date:' + date
string_to_hash = method + '\n' + str(content_length) + '\n' + co... | the_stack_v2_python_sparse | Solutions/SecurityScorecard Cybersecurity Ratings/Data Connectors/SecurityScorecardRatings/SecurityScorecardRatingsSentinelConnector/writers.py | Azure/Azure-Sentinel | train | 3,697 |
54c297c6191ca2d6d2486a0de5a54fd0d5f702be | [
"self.actions = [BotCreate(), BotDelete(), BotList(), ExchangeCreate(), ExchangeDelete(), ExchangeList(), UserCreate(), UserDelete(), UserList()]\nself.login = Login()\nself.parser = None\nself.subparser = None\nself.subparsers = []\nself.set_up()\nself.execute()",
"self.parser = argparse.ArgumentParser()\nself.s... | <|body_start_0|>
self.actions = [BotCreate(), BotDelete(), BotList(), ExchangeCreate(), ExchangeDelete(), ExchangeList(), UserCreate(), UserDelete(), UserList()]
self.login = Login()
self.parser = None
self.subparser = None
self.subparsers = []
self.set_up()
self.... | Actions | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Actions:
def __init__(self):
"""Add new actions here to have them included automatically Sets up class variables for the parsers, subparsers array has the filled parsers for each action Set up all the actions in the parsers and then execute the correct action"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_020392 | 2,563 | no_license | [
{
"docstring": "Add new actions here to have them included automatically Sets up class variables for the parsers, subparsers array has the filled parsers for each action Set up all the actions in the parsers and then execute the correct action",
"name": "__init__",
"signature": "def __init__(self)"
},... | 3 | stack_v2_sparse_classes_30k_val_001029 | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def __init__(self): Add new actions here to have them included automatically Sets up class variables for the parsers, subparsers array has the filled parsers for each action Set up... | Implement the Python class `Actions` described below.
Class description:
Implement the Actions class.
Method signatures and docstrings:
- def __init__(self): Add new actions here to have them included automatically Sets up class variables for the parsers, subparsers array has the filled parsers for each action Set up... | 5d2219059650e59118574c426b9ba607985fc88c | <|skeleton|>
class Actions:
def __init__(self):
"""Add new actions here to have them included automatically Sets up class variables for the parsers, subparsers array has the filled parsers for each action Set up all the actions in the parsers and then execute the correct action"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Actions:
def __init__(self):
"""Add new actions here to have them included automatically Sets up class variables for the parsers, subparsers array has the filled parsers for each action Set up all the actions in the parsers and then execute the correct action"""
self.actions = [BotCreate(), Bo... | the_stack_v2_python_sparse | console/actions.py | KarimBenslimane/bitconnect | train | 0 | |
854c58ee666ddc408f8ac5dd85ee0392c2156ab3 | [
"super().__init__(year_due, month_due, day_due)\nself._questions = questions\nself._answers = answers\nself._response = [True, False]",
"total: int = 0\ni: int\nfor i in range(len(self._answers)):\n if self._answers[i] == self._response[i]:\n total += 1\nreturn total / len(self._answers) * 100"
] | <|body_start_0|>
super().__init__(year_due, month_due, day_due)
self._questions = questions
self._answers = answers
self._response = [True, False]
<|end_body_0|>
<|body_start_1|>
total: int = 0
i: int
for i in range(len(self._answers)):
if self._answe... | A quiz type of assignment. Public methods: __init__, get_grade | Quiz | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quiz:
"""A quiz type of assignment. Public methods: __init__, get_grade"""
def __init__(self, year_due: int, month_due: int, day_due: int, questions: list, answers: list) -> None:
"""Initialize the essay from parameters."""
<|body_0|>
def get_grade(self) -> int:
... | stack_v2_sparse_classes_36k_train_020393 | 3,058 | no_license | [
{
"docstring": "Initialize the essay from parameters.",
"name": "__init__",
"signature": "def __init__(self, year_due: int, month_due: int, day_due: int, questions: list, answers: list) -> None"
},
{
"docstring": "Return the grade for this assignment.",
"name": "get_grade",
"signature": ... | 2 | null | Implement the Python class `Quiz` described below.
Class description:
A quiz type of assignment. Public methods: __init__, get_grade
Method signatures and docstrings:
- def __init__(self, year_due: int, month_due: int, day_due: int, questions: list, answers: list) -> None: Initialize the essay from parameters.
- def ... | Implement the Python class `Quiz` described below.
Class description:
A quiz type of assignment. Public methods: __init__, get_grade
Method signatures and docstrings:
- def __init__(self, year_due: int, month_due: int, day_due: int, questions: list, answers: list) -> None: Initialize the essay from parameters.
- def ... | 0fe17edf6ffcb35265032c6449d866b9434fda00 | <|skeleton|>
class Quiz:
"""A quiz type of assignment. Public methods: __init__, get_grade"""
def __init__(self, year_due: int, month_due: int, day_due: int, questions: list, answers: list) -> None:
"""Initialize the essay from parameters."""
<|body_0|>
def get_grade(self) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Quiz:
"""A quiz type of assignment. Public methods: __init__, get_grade"""
def __init__(self, year_due: int, month_due: int, day_due: int, questions: list, answers: list) -> None:
"""Initialize the essay from parameters."""
super().__init__(year_due, month_due, day_due)
self._ques... | the_stack_v2_python_sparse | Chapter5TextbookCode/Listing 5-2.py | ProfessorBurke/PythonObjectsGames | train | 3 |
50d5841ee894fff16f008ede12fe243370a5cb00 | [
"if self.Briefcase:\n from cs.workflow.processes import Process\n if self.Briefcase.Process and self.Briefcase.Process.status in [Process.COMPLETED.status, Process.FAILED.status]:\n raise ue.Exception('cdbwf_process_already_closed')",
"if self.Briefcase:\n if not self.Briefcase.CheckAccess('edit s... | <|body_start_0|>
if self.Briefcase:
from cs.workflow.processes import Process
if self.Briefcase.Process and self.Briefcase.Process.status in [Process.COMPLETED.status, Process.FAILED.status]:
raise ue.Exception('cdbwf_process_already_closed')
<|end_body_0|>
<|body_start_... | FolderContent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FolderContent:
def check_process_status(self, ctx):
"""Check that the briefcase process is not closed"""
<|body_0|>
def check_briefcase_rights(self, ctx):
"""Check that the current user has the necessary access rights"""
<|body_1|>
def check_briefcase_co... | stack_v2_sparse_classes_36k_train_020394 | 20,066 | no_license | [
{
"docstring": "Check that the briefcase process is not closed",
"name": "check_process_status",
"signature": "def check_process_status(self, ctx)"
},
{
"docstring": "Check that the current user has the necessary access rights",
"name": "check_briefcase_rights",
"signature": "def check_b... | 5 | stack_v2_sparse_classes_30k_train_019594 | Implement the Python class `FolderContent` described below.
Class description:
Implement the FolderContent class.
Method signatures and docstrings:
- def check_process_status(self, ctx): Check that the briefcase process is not closed
- def check_briefcase_rights(self, ctx): Check that the current user has the necessa... | Implement the Python class `FolderContent` described below.
Class description:
Implement the FolderContent class.
Method signatures and docstrings:
- def check_process_status(self, ctx): Check that the briefcase process is not closed
- def check_briefcase_rights(self, ctx): Check that the current user has the necessa... | 6bc932c67bc8d93b873838ae6d9fb8d33c72234d | <|skeleton|>
class FolderContent:
def check_process_status(self, ctx):
"""Check that the briefcase process is not closed"""
<|body_0|>
def check_briefcase_rights(self, ctx):
"""Check that the current user has the necessary access rights"""
<|body_1|>
def check_briefcase_co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FolderContent:
def check_process_status(self, ctx):
"""Check that the briefcase process is not closed"""
if self.Briefcase:
from cs.workflow.processes import Process
if self.Briefcase.Process and self.Briefcase.Process.status in [Process.COMPLETED.status, Process.FAILED... | the_stack_v2_python_sparse | site-packages/cs.workflow-15.4.1.3-py2.7.egg/cs/workflow/briefcases.py | prachipainuly-rbei/devops-poc | train | 0 | |
af3ea5d2263ed919cb46f73618327ba1b9e99624 | [
"if endWord not in wordList:\n return 0\nself.build_graph(wordList)\nqueue_begin = collections.deque([(beginWord, 1)])\nqueue_end = collections.deque([(endWord, 1)])\nvisited_begin = {beginWord: 1}\nvisited_end = {endWord: 1}\nres = None\nwhile queue_begin and queue_end:\n res = self.visit_word_node(queue_beg... | <|body_start_0|>
if endWord not in wordList:
return 0
self.build_graph(wordList)
queue_begin = collections.deque([(beginWord, 1)])
queue_end = collections.deque([(endWord, 1)])
visited_begin = {beginWord: 1}
visited_end = {endWord: 1}
res = None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""Args: beginWord: str endWord: str wordList: list[str] Return: int"""
<|body_0|>
def visit_word_node(self, queue, visited, other_visited):
"""Args: queue: collections.deque visited: dict other_visited:... | stack_v2_sparse_classes_36k_train_020395 | 3,553 | no_license | [
{
"docstring": "Args: beginWord: str endWord: str wordList: list[str] Return: int",
"name": "ladderLength",
"signature": "def ladderLength(self, beginWord, endWord, wordList)"
},
{
"docstring": "Args: queue: collections.deque visited: dict other_visited: dic Return: int",
"name": "visit_word... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLength(self, beginWord, endWord, wordList): Args: beginWord: str endWord: str wordList: list[str] Return: int
- def visit_word_node(self, queue, visited, other_visited)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ladderLength(self, beginWord, endWord, wordList): Args: beginWord: str endWord: str wordList: list[str] Return: int
- def visit_word_node(self, queue, visited, other_visited)... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""Args: beginWord: str endWord: str wordList: list[str] Return: int"""
<|body_0|>
def visit_word_node(self, queue, visited, other_visited):
"""Args: queue: collections.deque visited: dict other_visited:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""Args: beginWord: str endWord: str wordList: list[str] Return: int"""
if endWord not in wordList:
return 0
self.build_graph(wordList)
queue_begin = collections.deque([(beginWord, 1)])
queue_en... | the_stack_v2_python_sparse | code/127. 单词接龙.py | AiZhanghan/Leetcode | train | 0 | |
e3e2eedb732dae775f7cad12d1edb8c13146e0b7 | [
"ls_pre = np.geomspace(2, lb[0], int(nb_dex_extrap_lo * np.log10(lb[0] / 2.0)))\nls_mid = (lb[:-1, None] + np.arange(nrb)[None, :] * np.diff(lb)[:, None] / nrb).flatten()[1:]\nls_post = np.geomspace(lb[-1], 2 * lb[-1], 50)\nself.ls_eval = np.concatenate((ls_pre, ls_mid, ls_post))\nself.kind = kind",
"ind_good = n... | <|body_start_0|>
ls_pre = np.geomspace(2, lb[0], int(nb_dex_extrap_lo * np.log10(lb[0] / 2.0)))
ls_mid = (lb[:-1, None] + np.arange(nrb)[None, :] * np.diff(lb)[:, None] / nrb).flatten()[1:]
ls_post = np.geomspace(lb[-1], 2 * lb[-1], 50)
self.ls_eval = np.concatenate((ls_pre, ls_mid, ls_p... | ClInterpolator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClInterpolator:
def __init__(self, lb, nrb=3, nb_dex_extrap_lo=10, kind='cubic'):
"""Interpolator for angular power spectra lb : central bandpower ells nrb : re-binning factor for ells within the range of the bandpowers nb_dex_extrap_lo : number of ells per decade for ells below the rang... | stack_v2_sparse_classes_36k_train_020396 | 1,953 | no_license | [
{
"docstring": "Interpolator for angular power spectra lb : central bandpower ells nrb : re-binning factor for ells within the range of the bandpowers nb_dex_extrap_lo : number of ells per decade for ells below the range of the bandpowers kind : interpolation type Extrapolation at high ell will be done assuming... | 2 | stack_v2_sparse_classes_30k_train_003059 | Implement the Python class `ClInterpolator` described below.
Class description:
Implement the ClInterpolator class.
Method signatures and docstrings:
- def __init__(self, lb, nrb=3, nb_dex_extrap_lo=10, kind='cubic'): Interpolator for angular power spectra lb : central bandpower ells nrb : re-binning factor for ells ... | Implement the Python class `ClInterpolator` described below.
Class description:
Implement the ClInterpolator class.
Method signatures and docstrings:
- def __init__(self, lb, nrb=3, nb_dex_extrap_lo=10, kind='cubic'): Interpolator for angular power spectra lb : central bandpower ells nrb : re-binning factor for ells ... | ea8e14b6e0f9178aee75872a58100503796ce9e6 | <|skeleton|>
class ClInterpolator:
def __init__(self, lb, nrb=3, nb_dex_extrap_lo=10, kind='cubic'):
"""Interpolator for angular power spectra lb : central bandpower ells nrb : re-binning factor for ells within the range of the bandpowers nb_dex_extrap_lo : number of ells per decade for ells below the rang... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClInterpolator:
def __init__(self, lb, nrb=3, nb_dex_extrap_lo=10, kind='cubic'):
"""Interpolator for angular power spectra lb : central bandpower ells nrb : re-binning factor for ells within the range of the bandpowers nb_dex_extrap_lo : number of ells per decade for ells below the range of the bandp... | the_stack_v2_python_sparse | modules/cl_interpolator.py | damonge/WeePeeZee | train | 2 | |
8b883f3cb5a9a35bf60c92ea39e1afc33181e7c2 | [
"data = get_calendar_row_by_id(pk)\nif not data:\n abort(NotFound.code, message='没有记录', status=False)\nif data.status_delete == STATUS_DEL_OK:\n abort(NotFound.code, message='已经删除', status=False)\nresult = marshal(data, fields_item, envelope=structure_key_item)\nreturn jsonify(result)",
"request_args = requ... | <|body_start_0|>
data = get_calendar_row_by_id(pk)
if not data:
abort(NotFound.code, message='没有记录', status=False)
if data.status_delete == STATUS_DEL_OK:
abort(NotFound.code, message='已经删除', status=False)
result = marshal(data, fields_item, envelope=structure_key... | CalendarResource | CalendarResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarResource:
"""CalendarResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:8000/calendar/1 :param pk: :return:"""
<|body_0|>
def put(self, pk):
"""Example: curl http://0.0.0.0:8000/calendar/1 -H "Content-Type: application/json" -X PUT -d ' { "cal... | stack_v2_sparse_classes_36k_train_020397 | 8,144 | no_license | [
{
"docstring": "Example: curl http://0.0.0.0:8000/calendar/1 :param pk: :return:",
"name": "get",
"signature": "def get(self, pk)"
},
{
"docstring": "Example: curl http://0.0.0.0:8000/calendar/1 -H \"Content-Type: application/json\" -X PUT -d ' { \"calendar\": { \"name\": \"周六出去玩\", \"date\": \"... | 3 | stack_v2_sparse_classes_30k_test_000983 | Implement the Python class `CalendarResource` described below.
Class description:
CalendarResource
Method signatures and docstrings:
- def get(self, pk): Example: curl http://0.0.0.0:8000/calendar/1 :param pk: :return:
- def put(self, pk): Example: curl http://0.0.0.0:8000/calendar/1 -H "Content-Type: application/jso... | Implement the Python class `CalendarResource` described below.
Class description:
CalendarResource
Method signatures and docstrings:
- def get(self, pk): Example: curl http://0.0.0.0:8000/calendar/1 :param pk: :return:
- def put(self, pk): Example: curl http://0.0.0.0:8000/calendar/1 -H "Content-Type: application/jso... | 0b44d83b95079734ac9aa78bc7af40a0a7530bca | <|skeleton|>
class CalendarResource:
"""CalendarResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:8000/calendar/1 :param pk: :return:"""
<|body_0|>
def put(self, pk):
"""Example: curl http://0.0.0.0:8000/calendar/1 -H "Content-Type: application/json" -X PUT -d ' { "cal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarResource:
"""CalendarResource"""
def get(self, pk):
"""Example: curl http://0.0.0.0:8000/calendar/1 :param pk: :return:"""
data = get_calendar_row_by_id(pk)
if not data:
abort(NotFound.code, message='没有记录', status=False)
if data.status_delete == STATUS_... | the_stack_v2_python_sparse | apps/lims/calendar/resource.py | zhanghe06/lims_project | train | 1 |
e4cc33506d25199ec4ff9b06c754c21f23f5143b | [
"maxSumList = [0] * len(array)\nfor i in range(len(array)):\n maxSum = 0\n sum_ = 0\n for j in range(i, len(array)):\n sum_ += array[j]\n if maxSum < sum_:\n maxSum = sum_\n maxSumList[i] = maxSum\nreturn max(maxSumList)",
"tmp = nums[0]\nmax_ = tmp\nfor i in range(1, len(nums... | <|body_start_0|>
maxSumList = [0] * len(array)
for i in range(len(array)):
maxSum = 0
sum_ = 0
for j in range(i, len(array)):
sum_ += array[j]
if maxSum < sum_:
maxSum = sum_
maxSumList[i] = maxSum
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, array):
"""暴力求解法"""
<|body_0|>
def maxSubArray(self, nums) -> int:
"""动态规划法DP"""
<|body_1|>
def maxSubArray3(self, nums) -> int:
"""分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_020398 | 2,930 | no_license | [
{
"docstring": "暴力求解法",
"name": "maxSubArray",
"signature": "def maxSubArray(self, array)"
},
{
"docstring": "动态规划法DP",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums) -> int"
},
{
"docstring": "分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解",
"name": "maxSubArray3",
"s... | 3 | stack_v2_sparse_classes_30k_train_002488 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, array): 暴力求解法
- def maxSubArray(self, nums) -> int: 动态规划法DP
- def maxSubArray3(self, nums) -> int: 分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, array): 暴力求解法
- def maxSubArray(self, nums) -> int: 动态规划法DP
- def maxSubArray3(self, nums) -> int: 分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解
<|skeleton|>
class Solut... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def maxSubArray(self, array):
"""暴力求解法"""
<|body_0|>
def maxSubArray(self, nums) -> int:
"""动态规划法DP"""
<|body_1|>
def maxSubArray3(self, nums) -> int:
"""分治法:将数组分为左右两部分和中间部分,递归实现。没能完全理解"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray(self, array):
"""暴力求解法"""
maxSumList = [0] * len(array)
for i in range(len(array)):
maxSum = 0
sum_ = 0
for j in range(i, len(array)):
sum_ += array[j]
if maxSum < sum_:
ma... | the_stack_v2_python_sparse | leetcode/53.最大子序和(动态规划).py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
30e47e03e2a52a31911b7356ecbed74d613e2bec | [
"from sims4communitylib.utils.sims.common_gender_utils import CommonGenderUtils\nif CommonGenderUtils.is_male(sim_info):\n return CommonGender.MALE\nelif CommonGenderUtils.is_female(sim_info):\n return CommonGender.FEMALE\nreturn CommonGender.INVALID",
"if gender == CommonGender.INVALID:\n return None\ni... | <|body_start_0|>
from sims4communitylib.utils.sims.common_gender_utils import CommonGenderUtils
if CommonGenderUtils.is_male(sim_info):
return CommonGender.MALE
elif CommonGenderUtils.is_female(sim_info):
return CommonGender.FEMALE
return CommonGender.INVALID
<|en... | Custom Gender enum containing all genders. | CommonGender | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonGender:
"""Custom Gender enum containing all genders."""
def get_gender(sim_info: SimInfo) -> 'CommonGender':
"""get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents wha... | stack_v2_sparse_classes_36k_train_020399 | 3,081 | permissive | [
{
"docstring": "get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents what gender a Sim is or CommonGender.INVALID if their gender cannot be determined. :rtype: CommonGender",
"name": "get_gender",
... | 3 | stack_v2_sparse_classes_30k_test_000310 | Implement the Python class `CommonGender` described below.
Class description:
Custom Gender enum containing all genders.
Method signatures and docstrings:
- def get_gender(sim_info: SimInfo) -> 'CommonGender': get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_in... | Implement the Python class `CommonGender` described below.
Class description:
Custom Gender enum containing all genders.
Method signatures and docstrings:
- def get_gender(sim_info: SimInfo) -> 'CommonGender': get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_in... | b59ea7e5f4bd01d3b3bd7603843d525a9c179867 | <|skeleton|>
class CommonGender:
"""Custom Gender enum containing all genders."""
def get_gender(sim_info: SimInfo) -> 'CommonGender':
"""get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents wha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonGender:
"""Custom Gender enum containing all genders."""
def get_gender(sim_info: SimInfo) -> 'CommonGender':
"""get_gender(sim_info) Retrieve the CommonGender of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The CommonGender that represents what gender a Si... | the_stack_v2_python_sparse | src/sims4communitylib/enums/common_gender.py | velocist/TS4CheatsInfo | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.