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
13b461b75939360c65038d04f1f197e5d17dd91c
[ "context = self.env.context\ndispatch_user = self.env['funenc.wechat.user'].search([('user_id', '=', context['uid'])])\norders = self.env['metro_park_maintenance.maintaince_order'].search([('id', 'in', context['ids'])])\nfor order in orders:\n order.state = 'assigned'\n order.work_user = self.work_user\n o...
<|body_start_0|> context = self.env.context dispatch_user = self.env['funenc.wechat.user'].search([('user_id', '=', context['uid'])]) orders = self.env['metro_park_maintenance.maintaince_order'].search([('id', 'in', context['ids'])]) for order in orders: order.state = 'assign...
检修工单向导
MaintainceOrderWizard
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaintainceOrderWizard: """检修工单向导""" def send_job_on_click(self): """派工确认按钮 :return:""" <|body_0|> def start_job_on_click(self): """开工确认按钮 :return:""" <|body_1|> def finish_job_on_click(self): """完工确认按钮 :return:""" <|body_2|> def ...
stack_v2_sparse_classes_36k_train_013700
6,763
no_license
[ { "docstring": "派工确认按钮 :return:", "name": "send_job_on_click", "signature": "def send_job_on_click(self)" }, { "docstring": "开工确认按钮 :return:", "name": "start_job_on_click", "signature": "def start_job_on_click(self)" }, { "docstring": "完工确认按钮 :return:", "name": "finish_job_on...
6
null
Implement the Python class `MaintainceOrderWizard` described below. Class description: 检修工单向导 Method signatures and docstrings: - def send_job_on_click(self): 派工确认按钮 :return: - def start_job_on_click(self): 开工确认按钮 :return: - def finish_job_on_click(self): 完工确认按钮 :return: - def finish_job_confirm_on_click(self): 完工确认的...
Implement the Python class `MaintainceOrderWizard` described below. Class description: 检修工单向导 Method signatures and docstrings: - def send_job_on_click(self): 派工确认按钮 :return: - def start_job_on_click(self): 开工确认按钮 :return: - def finish_job_on_click(self): 完工确认按钮 :return: - def finish_job_confirm_on_click(self): 完工确认的...
13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9
<|skeleton|> class MaintainceOrderWizard: """检修工单向导""" def send_job_on_click(self): """派工确认按钮 :return:""" <|body_0|> def start_job_on_click(self): """开工确认按钮 :return:""" <|body_1|> def finish_job_on_click(self): """完工确认按钮 :return:""" <|body_2|> def ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaintainceOrderWizard: """检修工单向导""" def send_job_on_click(self): """派工确认按钮 :return:""" context = self.env.context dispatch_user = self.env['funenc.wechat.user'].search([('user_id', '=', context['uid'])]) orders = self.env['metro_park_maintenance.maintaince_order'].search([...
the_stack_v2_python_sparse
mdias_addons/metro_park_maintenance/models/wizard/maintaince_order_wizard.py
rezaghanimi/main_mdias
train
0
fe1b68be12c5b5606e3c516dd1543be259d091e3
[ "data_list = []\nresults = self.query.all()\nformatter = self.request.locale.dates.getFormatter('date', 'short')\nfor result in results:\n data = {}\n data['qid'] = 'b_' + str(result.bill_id)\n data['subject'] = result.short_name\n data['title'] = result.short_name\n data['result_item_class'] = 'work...
<|body_start_0|> data_list = [] results = self.query.all() formatter = self.request.locale.dates.getFormatter('date', 'short') for result in results: data = {} data['qid'] = 'b_' + str(result.bill_id) data['subject'] = result.short_name dat...
Display all bills that can be scheduled for a parliamentary sitting
BillItemsViewlet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BillItemsViewlet: """Display all bills that can be scheduled for a parliamentary sitting""" def getData(self): """return the data of the query""" <|body_0|> def update(self): """refresh the query""" <|body_1|> <|end_skeleton|> <|body_start_0|> d...
stack_v2_sparse_classes_36k_train_013701
35,739
no_license
[ { "docstring": "return the data of the query", "name": "getData", "signature": "def getData(self)" }, { "docstring": "refresh the query", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_002039
Implement the Python class `BillItemsViewlet` described below. Class description: Display all bills that can be scheduled for a parliamentary sitting Method signatures and docstrings: - def getData(self): return the data of the query - def update(self): refresh the query
Implement the Python class `BillItemsViewlet` described below. Class description: Display all bills that can be scheduled for a parliamentary sitting Method signatures and docstrings: - def getData(self): return the data of the query - def update(self): refresh the query <|skeleton|> class BillItemsViewlet: """D...
5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d
<|skeleton|> class BillItemsViewlet: """Display all bills that can be scheduled for a parliamentary sitting""" def getData(self): """return the data of the query""" <|body_0|> def update(self): """refresh the query""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BillItemsViewlet: """Display all bills that can be scheduled for a parliamentary sitting""" def getData(self): """return the data of the query""" data_list = [] results = self.query.all() formatter = self.request.locale.dates.getFormatter('date', 'short') for resul...
the_stack_v2_python_sparse
bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/viewlets/workspace.py
malangalanga/bungeni-portal
train
0
39a02ccff3ea0e735efdfd8c700349917171dddd
[ "self.__size = 10\nself.__board = []\nself.__submarines = submarine\nfor i in range(10):\n self.__board.append([' '] * 10)\nself.__coords = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9}", "x, y = (self.__coords[coord[0]], int(coord[1]))\nfor sub in self.__submarines:\n if ...
<|body_start_0|> self.__size = 10 self.__board = [] self.__submarines = submarine for i in range(10): self.__board.append([' '] * 10) self.__coords = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9} <|end_body_0|> <|body_start_1|> ...
Tämä luokka vastaa pelialueelta. Välittää iskut laivoille, määrittelee voittajan jne.
Playground
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Playground: """Tämä luokka vastaa pelialueelta. Välittää iskut laivoille, määrittelee voittajan jne.""" def __init__(self, submarine): """Lukan alustaminen. Sisäiset muuttujat: size - pelialueen koko board - sisältää listojen listan, jossa on kaikki tarvittavat merkit. submarines - s...
stack_v2_sparse_classes_36k_train_013702
9,090
no_license
[ { "docstring": "Lukan alustaminen. Sisäiset muuttujat: size - pelialueen koko board - sisältää listojen listan, jossa on kaikki tarvittavat merkit. submarines - sisätlää vektorin, jossa on kaikki pelissa osallistuvat laivat (submarine-luokan edustajat) coord - sisäiseen käyttöön tarkoitettu dicti, jossa jokaise...
4
stack_v2_sparse_classes_30k_train_019848
Implement the Python class `Playground` described below. Class description: Tämä luokka vastaa pelialueelta. Välittää iskut laivoille, määrittelee voittajan jne. Method signatures and docstrings: - def __init__(self, submarine): Lukan alustaminen. Sisäiset muuttujat: size - pelialueen koko board - sisältää listojen l...
Implement the Python class `Playground` described below. Class description: Tämä luokka vastaa pelialueelta. Välittää iskut laivoille, määrittelee voittajan jne. Method signatures and docstrings: - def __init__(self, submarine): Lukan alustaminen. Sisäiset muuttujat: size - pelialueen koko board - sisältää listojen l...
5e26264eefd4f4f74b5c91bacf2317dc22d120cb
<|skeleton|> class Playground: """Tämä luokka vastaa pelialueelta. Välittää iskut laivoille, määrittelee voittajan jne.""" def __init__(self, submarine): """Lukan alustaminen. Sisäiset muuttujat: size - pelialueen koko board - sisältää listojen listan, jossa on kaikki tarvittavat merkit. submarines - s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Playground: """Tämä luokka vastaa pelialueelta. Välittää iskut laivoille, määrittelee voittajan jne.""" def __init__(self, submarine): """Lukan alustaminen. Sisäiset muuttujat: size - pelialueen koko board - sisältää listojen listan, jossa on kaikki tarvittavat merkit. submarines - sisätlää vekto...
the_stack_v2_python_sparse
kierros12/laivapeli2.py
kettu-metsanen/python_course
train
0
ff71295e0c7367c6d568112c40cebb3a8a77c733
[ "super().__init__(board)\nself.extra_steps = extra_steps\nself.went_down = False", "if self.went_down:\n self.position += random.randint(1, 6) + self.extra_steps\nelse:\n self.position += random.randint(1, 6)\nif self.position > self.board.position_adjustment(self.position):\n self.went_down = True\nelse...
<|body_start_0|> super().__init__(board) self.extra_steps = extra_steps self.went_down = False <|end_body_0|> <|body_start_1|> if self.went_down: self.position += random.randint(1, 6) + self.extra_steps else: self.position += random.randint(1, 6) ...
Resilient Player class, this player takes one extra step the next round if he fell down in the previous round.
ResilientPlayer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResilientPlayer: """Resilient Player class, this player takes one extra step the next round if he fell down in the previous round.""" def __init__(self, board, extra_steps=1): """:param board: Takes in board as input :param extra_steps: Takes in amount of steps he should take as inpu...
stack_v2_sparse_classes_36k_train_013703
7,940
no_license
[ { "docstring": ":param board: Takes in board as input :param extra_steps: Takes in amount of steps he should take as input", "name": "__init__", "signature": "def __init__(self, board, extra_steps=1)" }, { "docstring": "Moves the ResilientPlayer, done with if tests. Updates the current position ...
2
stack_v2_sparse_classes_30k_train_008592
Implement the Python class `ResilientPlayer` described below. Class description: Resilient Player class, this player takes one extra step the next round if he fell down in the previous round. Method signatures and docstrings: - def __init__(self, board, extra_steps=1): :param board: Takes in board as input :param ext...
Implement the Python class `ResilientPlayer` described below. Class description: Resilient Player class, this player takes one extra step the next round if he fell down in the previous round. Method signatures and docstrings: - def __init__(self, board, extra_steps=1): :param board: Takes in board as input :param ext...
4d2f6cc594a4c5decd844fdfba7baced6b78aa72
<|skeleton|> class ResilientPlayer: """Resilient Player class, this player takes one extra step the next round if he fell down in the previous round.""" def __init__(self, board, extra_steps=1): """:param board: Takes in board as input :param extra_steps: Takes in amount of steps he should take as inpu...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResilientPlayer: """Resilient Player class, this player takes one extra step the next round if he fell down in the previous round.""" def __init__(self, board, extra_steps=1): """:param board: Takes in board as input :param extra_steps: Takes in amount of steps he should take as input""" ...
the_stack_v2_python_sparse
src/pa02/chutes_simulation.py
amirarfan/INF200-2019-Exercises
train
0
44462eb6d42cea46ad622054eac699a07e37c013
[ "from oaautils import i4d\nself._ic = InterferometerConverter()\nself._interf = i4d.I4D()\nself._logger = logging.getLogger('4D')", "if nframes == 1:\n masked_ima = self._getMeasurementOnTheFly(self._interf)\nelse:\n cube_images = None\n for i in range(nframes):\n ima = self._getMeasurementOnTheFl...
<|body_start_0|> from oaautils import i4d self._ic = InterferometerConverter() self._interf = i4d.I4D() self._logger = logging.getLogger('4D') <|end_body_0|> <|body_start_1|> if nframes == 1: masked_ima = self._getMeasurementOnTheFly(self._interf) else: ...
Class for i4d interferometer
I4dArcetri
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class I4dArcetri: """Class for i4d interferometer""" def __init__(self): """The constructor""" <|body_0|> def acquire_phasemap(self, nframes=1, show=0): """Parameters ---------- nframes: int number of frames show: int 0 to not show the image Returns ------- masked_ima:...
stack_v2_sparse_classes_36k_train_013704
4,915
no_license
[ { "docstring": "The constructor", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Parameters ---------- nframes: int number of frames show: int 0 to not show the image Returns ------- masked_ima: numpy masked array interferometer image", "name": "acquire_phasemap", ...
4
null
Implement the Python class `I4dArcetri` described below. Class description: Class for i4d interferometer Method signatures and docstrings: - def __init__(self): The constructor - def acquire_phasemap(self, nframes=1, show=0): Parameters ---------- nframes: int number of frames show: int 0 to not show the image Return...
Implement the Python class `I4dArcetri` described below. Class description: Class for i4d interferometer Method signatures and docstrings: - def __init__(self): The constructor - def acquire_phasemap(self, nframes=1, show=0): Parameters ---------- nframes: int number of frames show: int 0 to not show the image Return...
cfb3757cc491199248dba767ddf47dce9b191261
<|skeleton|> class I4dArcetri: """Class for i4d interferometer""" def __init__(self): """The constructor""" <|body_0|> def acquire_phasemap(self, nframes=1, show=0): """Parameters ---------- nframes: int number of frames show: int 0 to not show the image Returns ------- masked_ima:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class I4dArcetri: """Class for i4d interferometer""" def __init__(self): """The constructor""" from oaautils import i4d self._ic = InterferometerConverter() self._interf = i4d.I4D() self._logger = logging.getLogger('4D') def acquire_phasemap(self, nframes=1, show=0)...
the_stack_v2_python_sparse
m4/devices/interferometer.py
alfiopuglisi/M4
train
0
667bd72cb4993f82f60c819b5fb84fe6d7726c59
[ "if hasattr(self, 'request') and user_id == self.request.session['user_id']:\n username = self.request.session['username']\n token = self.request.session['token']\n user = AuthUser(user_id, username, token)\n return user\nelse:\n return None", "LOG.debug('Beginning user authentication for user \"%s...
<|body_start_0|> if hasattr(self, 'request') and user_id == self.request.session['user_id']: username = self.request.session['username'] token = self.request.session['token'] user = AuthUser(user_id, username, token) return user else: return No...
Django authentication backend class for use with ``django.contrib.auth``.
KeystoneBackend
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeystoneBackend: """Django authentication backend class for use with ``django.contrib.auth``.""" def get_user(self, user_id): """Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to m...
stack_v2_sparse_classes_36k_train_013705
2,763
permissive
[ { "docstring": "Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to make the ``request`` object available to the auth backend class.", "name": "get_user", "signature": "def get_user(self, user_id)" },...
4
null
Implement the Python class `KeystoneBackend` described below. Class description: Django authentication backend class for use with ``django.contrib.auth``. Method signatures and docstrings: - def get_user(self, user_id): Returns the current user (if authenticated) based on the user ID and session data. Note: this requ...
Implement the Python class `KeystoneBackend` described below. Class description: Django authentication backend class for use with ``django.contrib.auth``. Method signatures and docstrings: - def get_user(self, user_id): Returns the current user (if authenticated) based on the user ID and session data. Note: this requ...
74140b041ac25ed83898ff3998e8dcbed35572bb
<|skeleton|> class KeystoneBackend: """Django authentication backend class for use with ``django.contrib.auth``.""" def get_user(self, user_id): """Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to m...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KeystoneBackend: """Django authentication backend class for use with ``django.contrib.auth``.""" def get_user(self, user_id): """Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to make the ``req...
the_stack_v2_python_sparse
tools/dockerize/webportal/usr/share/openstack-dashboard/openstack_dashboard/backend.py
foruy/openflow-multiopenstack
train
1
0667d50b8d8dd113a3777ec8a21e8f2e065534e8
[ "self.location = location\nself.velocity = velocity\nself.front = front / front.magnitude()\nself.acceleration = Vector2(0)", "self.location += delta_time * self.velocity\nself.velocity += delta_time * self.acceleration\nself.acceleration = Vector2(0)" ]
<|body_start_0|> self.location = location self.velocity = velocity self.front = front / front.magnitude() self.acceleration = Vector2(0) <|end_body_0|> <|body_start_1|> self.location += delta_time * self.velocity self.velocity += delta_time * self.acceleration se...
A class for basic physical properties. Can be extended with PhysicsDecorator classes. Attributes: `location': A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`. Should be normalized to have length of 1 `acceleration`: A pygame.Vector2
BasePhysics
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasePhysics: """A class for basic physical properties. Can be extended with PhysicsDecorator classes. Attributes: `location': A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`. Should be normalized to have length of 1...
stack_v2_sparse_classes_36k_train_013706
7,411
no_license
[ { "docstring": "Initializes BasePhysics. Arguments: `location`: A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`.", "name": "__init__", "signature": "def __init__(self, location, velocity, front)" }, { "docstring": ...
2
stack_v2_sparse_classes_30k_train_002800
Implement the Python class `BasePhysics` described below. Class description: A class for basic physical properties. Can be extended with PhysicsDecorator classes. Attributes: `location': A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`. S...
Implement the Python class `BasePhysics` described below. Class description: A class for basic physical properties. Can be extended with PhysicsDecorator classes. Attributes: `location': A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`. S...
a210b6254c2a99c50cce591aeaf0a88bfc92993f
<|skeleton|> class BasePhysics: """A class for basic physical properties. Can be extended with PhysicsDecorator classes. Attributes: `location': A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`. Should be normalized to have length of 1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BasePhysics: """A class for basic physical properties. Can be extended with PhysicsDecorator classes. Attributes: `location': A pygame.Vector2 `velocity`: A pygame.Vector2 `front`: A pygame.Vector2 A vector pointing to the direction of the front of `self`. Should be normalized to have length of 1 `acceleratio...
the_stack_v2_python_sparse
src/game/physics.py
kluopaja/plane-game
train
0
ae74ec510096893c1629c9555f3503c75aaf1f05
[ "if isinstance(instance, RegisteredShutdown):\n container = GracefulShutdown.ServiceContainer(instance, nice)\n GracefulShutdown._register.append(container)\nelse:\n raise TypeError('Registered objects for graceful shutdown MUST be of type `RegisteredShutdown`.')", "logging.info('Shutting down services:'...
<|body_start_0|> if isinstance(instance, RegisteredShutdown): container = GracefulShutdown.ServiceContainer(instance, nice) GracefulShutdown._register.append(container) else: raise TypeError('Registered objects for graceful shutdown MUST be of type `RegisteredShutdown...
GracefulShutdown
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GracefulShutdown: def register(instance, nice=0): """Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Po...
stack_v2_sparse_classes_36k_train_013707
2,914
permissive
[ { "docstring": "Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Popen() object containers, should - extend RegisteredShutdown a...
2
stack_v2_sparse_classes_30k_train_010817
Implement the Python class `GracefulShutdown` described below. Class description: Implement the GracefulShutdown class. Method signatures and docstrings: - def register(instance, nice=0): Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending prio...
Implement the Python class `GracefulShutdown` described below. Class description: Implement the GracefulShutdown class. Method signatures and docstrings: - def register(instance, nice=0): Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending prio...
92f21b1b8a9f701cac3976a8db7034ecfefc58c7
<|skeleton|> class GracefulShutdown: def register(instance, nice=0): """Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Po...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GracefulShutdown: def register(instance, nice=0): """Arguments: `instance` argument should be an Object of type `RegisteredShutdown`. `nice` parameter permits a natural ascending priority-basis for shutdown execution order. Default is 0 (int), no range limitations. Usage: - subprocess.Popen() object c...
the_stack_v2_python_sparse
src/service/registered_shutdown.py
yeauxji/LightStage-Repo
train
0
ff6a8054b1f8438a02fdde2f2a2fbb97630276db
[ "idx = list()\nfor i, value in enumerate(nums):\n for j in range(i + 1, len(nums)):\n if value + nums[j] == target:\n idx.append(i)\n idx.append(j)\nreturn idx", "idx = list()\norder = sorted(range(len(nums)), key=lambda k: nums[k])\nnums = [nums[i] for i in order]\nfor i, value in...
<|body_start_0|> idx = list() for i, value in enumerate(nums): for j in range(i + 1, len(nums)): if value + nums[j] == target: idx.append(i) idx.append(j) return idx <|end_body_0|> <|body_start_1|> idx = list() ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def twoSum1(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSum2(self, nums, target): """sort nums and retain order in original list start with a[0], check a[0]+a[1], then a[0]+a[n-1] then move to middl...
stack_v2_sparse_classes_36k_train_013708
5,563
no_license
[ { "docstring": ":type nums: List[int] :type target: int :rtype: List[int]", "name": "twoSum1", "signature": "def twoSum1(self, nums, target)" }, { "docstring": "sort nums and retain order in original list start with a[0], check a[0]+a[1], then a[0]+a[n-1] then move to middle SHOULD consider chec...
5
stack_v2_sparse_classes_30k_train_011887
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def twoSum2(self, nums, target): sort nums and retain order in original list start wi...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def twoSum1(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int] - def twoSum2(self, nums, target): sort nums and retain order in original list start wi...
4af44f7364c6fb4d95309056f7a7853de779b3bb
<|skeleton|> class Solution: def twoSum1(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" <|body_0|> def twoSum2(self, nums, target): """sort nums and retain order in original list start with a[0], check a[0]+a[1], then a[0]+a[n-1] then move to middl...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def twoSum1(self, nums, target): """:type nums: List[int] :type target: int :rtype: List[int]""" idx = list() for i, value in enumerate(nums): for j in range(i + 1, len(nums)): if value + nums[j] == target: idx.append(i) ...
the_stack_v2_python_sparse
codes_python/0001_Two_Sum.py
mondler/leetcode
train
0
79205759e44904843ef5999daeaeaf4fb8e02563
[ "s = sum(nums)\nif s % k != 0:\n return False\ntarget = s // k\nvisited = [False for _ in nums]\nreturn self.dfs(nums, 0, None, target, visited, k)", "if k == 1:\n return True\nif cur_sum and cur_sum == target_sum:\n return self.dfs(nums, 0, None, target_sum, visited, k - 1)\nfor i in range(start_idx, le...
<|body_start_0|> s = sum(nums) if s % k != 0: return False target = s // k visited = [False for _ in nums] return self.dfs(nums, 0, None, target, visited, k) <|end_body_0|> <|body_start_1|> if k == 1: return True if cur_sum and cur_sum == ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: """resurive search""" <|body_0|> def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k): """some corner cases: 1. target_sum default at 0: sum or empty array is 0? 2. nxt_sum = (cur_s...
stack_v2_sparse_classes_36k_train_013709
3,307
no_license
[ { "docstring": "resurive search", "name": "canPartitionKSubsets", "signature": "def canPartitionKSubsets(self, nums: List[int], k: int) -> bool" }, { "docstring": "some corner cases: 1. target_sum default at 0: sum or empty array is 0? 2. nxt_sum = (cur_sum or 0) + nums[i] rather than cur_sum or...
2
stack_v2_sparse_classes_30k_train_017131
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: resurive search - def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k): some corner cases: 1. target_s...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: resurive search - def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k): some corner cases: 1. target_s...
929dde1723fb2f54870c8a9badc80fc23e8400d3
<|skeleton|> class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: """resurive search""" <|body_0|> def dfs(self, nums, start_idx, cur_sum, target_sum, visited, k): """some corner cases: 1. target_sum default at 0: sum or empty array is 0? 2. nxt_sum = (cur_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canPartitionKSubsets(self, nums: List[int], k: int) -> bool: """resurive search""" s = sum(nums) if s % k != 0: return False target = s // k visited = [False for _ in nums] return self.dfs(nums, 0, None, target, visited, k) def dfs...
the_stack_v2_python_sparse
_algorithms_challenges/leetcode/LeetCode/698 Partition to K Equal Sum Subsets.py
syurskyi/Algorithms_and_Data_Structure
train
4
5f9afe4853c0b364ae0d35e509857f28cc8659fc
[ "msg = 'Specify a valid before date (-b) or an age (-a).'\nwith self.assertRaisesMessage(CommandError, msg):\n call_command('clean_entries')", "msg = 'Specify a valid before date (-b) or an age (-a).'\nwith self.assertRaisesMessage(CommandError, msg):\n call_command('clean_entries', '-a=-3')", "today, now...
<|body_start_0|> msg = 'Specify a valid before date (-b) or an age (-a).' with self.assertRaisesMessage(CommandError, msg): call_command('clean_entries') <|end_body_0|> <|body_start_1|> msg = 'Specify a valid before date (-b) or an age (-a).' with self.assertRaisesMessage(Co...
Tests of the management command to clear out old entries.
Clean_Entry_Tests
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Clean_Entry_Tests: """Tests of the management command to clear out old entries.""" def test_no_args_gives_error(self): """Make sure providing no arguments raises an error.""" <|body_0|> def test_negative_age_gives_error(self): """Make sure negative age raises an ...
stack_v2_sparse_classes_36k_train_013710
29,880
permissive
[ { "docstring": "Make sure providing no arguments raises an error.", "name": "test_no_args_gives_error", "signature": "def test_no_args_gives_error(self)" }, { "docstring": "Make sure negative age raises an error.", "name": "test_negative_age_gives_error", "signature": "def test_negative_...
6
stack_v2_sparse_classes_30k_train_013029
Implement the Python class `Clean_Entry_Tests` described below. Class description: Tests of the management command to clear out old entries. Method signatures and docstrings: - def test_no_args_gives_error(self): Make sure providing no arguments raises an error. - def test_negative_age_gives_error(self): Make sure ne...
Implement the Python class `Clean_Entry_Tests` described below. Class description: Tests of the management command to clear out old entries. Method signatures and docstrings: - def test_no_args_gives_error(self): Make sure providing no arguments raises an error. - def test_negative_age_gives_error(self): Make sure ne...
12e1f2d3f6e7da5fbbbeb2af1322117589e218fa
<|skeleton|> class Clean_Entry_Tests: """Tests of the management command to clear out old entries.""" def test_no_args_gives_error(self): """Make sure providing no arguments raises an error.""" <|body_0|> def test_negative_age_gives_error(self): """Make sure negative age raises an ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Clean_Entry_Tests: """Tests of the management command to clear out old entries.""" def test_no_args_gives_error(self): """Make sure providing no arguments raises an error.""" msg = 'Specify a valid before date (-b) or an age (-a).' with self.assertRaisesMessage(CommandError, msg):...
the_stack_v2_python_sparse
diary/tests.py
BobBowles/django-diary
train
23
ff0eb24014181d10dac403ffc269d5e581b658a9
[ "html_class = super(BaseBookmarkPlugin, self).html_class\nif self.data.image:\n html_class += ' iconic-url'\nreturn html_class", "try:\n bookmark = Bookmark._default_manager.get(pk=self.data.bookmark)\nexcept ObjectDoesNotExist:\n return\nif bookmark:\n data = {'bookmark': bookmark.pk, 'title': bookma...
<|body_start_0|> html_class = super(BaseBookmarkPlugin, self).html_class if self.data.image: html_class += ' iconic-url' return html_class <|end_body_0|> <|body_start_1|> try: bookmark = Bookmark._default_manager.get(pk=self.data.bookmark) except ObjectDo...
Base URL plugin.
BaseBookmarkPlugin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseBookmarkPlugin: """Base URL plugin.""" def html_class(self): """HTML class. If plugin has an image, we add a class `iconic` to it.""" <|body_0|> def update_plugin_data(self, dashboard_entry): """Update plugin data. Should return a dictionary with the plugin d...
stack_v2_sparse_classes_36k_train_013711
3,111
no_license
[ { "docstring": "HTML class. If plugin has an image, we add a class `iconic` to it.", "name": "html_class", "signature": "def html_class(self)" }, { "docstring": "Update plugin data. Should return a dictionary with the plugin data which is supposed to be updated.", "name": "update_plugin_data...
2
null
Implement the Python class `BaseBookmarkPlugin` described below. Class description: Base URL plugin. Method signatures and docstrings: - def html_class(self): HTML class. If plugin has an image, we add a class `iconic` to it. - def update_plugin_data(self, dashboard_entry): Update plugin data. Should return a diction...
Implement the Python class `BaseBookmarkPlugin` described below. Class description: Base URL plugin. Method signatures and docstrings: - def html_class(self): HTML class. If plugin has an image, we add a class `iconic` to it. - def update_plugin_data(self, dashboard_entry): Update plugin data. Should return a diction...
bef95536e96417e18972a3118e19a8074bfc8684
<|skeleton|> class BaseBookmarkPlugin: """Base URL plugin.""" def html_class(self): """HTML class. If plugin has an image, we add a class `iconic` to it.""" <|body_0|> def update_plugin_data(self, dashboard_entry): """Update plugin data. Should return a dictionary with the plugin d...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseBookmarkPlugin: """Base URL plugin.""" def html_class(self): """HTML class. If plugin has an image, we add a class `iconic` to it.""" html_class = super(BaseBookmarkPlugin, self).html_class if self.data.image: html_class += ' iconic-url' return html_class ...
the_stack_v2_python_sparse
ENV/Lib/site-packages/dash/contrib/plugins/url/dash_plugins.py
JulianYangJingJun/OSVRCMS
train
3
d17c80544fcdf8b0e2b46de91c4396d462210da9
[ "pre, curr = (None, root)\nin_order = []\nwhile curr:\n if not curr.left:\n in_order.append(curr.val)\n curr = curr.right\n else:\n pre = curr.left\n while pre.right:\n pre = pre.right\n pre.right = curr\n temp = curr\n curr = curr.left\n temp...
<|body_start_0|> pre, curr = (None, root) in_order = [] while curr: if not curr.left: in_order.append(curr.val) curr = curr.right else: pre = curr.left while pre.right: pre = pre.right ...
BinaryTree
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryTree: def in_order_traversal_(self, root: 'TreeNode'): """Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return:""" <|body_0|> def in_order_traversal(self, root: 'TreeNode'): """Approach: Using stack Time Complexity: O(N) ...
stack_v2_sparse_classes_36k_train_013712
1,689
no_license
[ { "docstring": "Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return:", "name": "in_order_traversal_", "signature": "def in_order_traversal_(self, root: 'TreeNode')" }, { "docstring": "Approach: Using stack Time Complexity: O(N) Space Complexity: O(N) :par...
2
stack_v2_sparse_classes_30k_train_001621
Implement the Python class `BinaryTree` described below. Class description: Implement the BinaryTree class. Method signatures and docstrings: - def in_order_traversal_(self, root: 'TreeNode'): Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return: - def in_order_traversal(self, ...
Implement the Python class `BinaryTree` described below. Class description: Implement the BinaryTree class. Method signatures and docstrings: - def in_order_traversal_(self, root: 'TreeNode'): Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return: - def in_order_traversal(self, ...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class BinaryTree: def in_order_traversal_(self, root: 'TreeNode'): """Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return:""" <|body_0|> def in_order_traversal(self, root: 'TreeNode'): """Approach: Using stack Time Complexity: O(N) ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryTree: def in_order_traversal_(self, root: 'TreeNode'): """Approach: Morris Traversal Time Complexity: O(N) Space Complexity: O(N) :param root: :return:""" pre, curr = (None, root) in_order = [] while curr: if not curr.left: in_order.append(curr...
the_stack_v2_python_sparse
revisited/trees/inorder_traversal.py
Shiv2157k/leet_code
train
1
fc5e63542998adba97a67f2a5990f3fa429a44f8
[ "self.cmd = cmd\nself.rsp = rsp\nself.dev = dev\nself.timeout = timeout\nself.re = re\nself.rpc_error = None\nself.xml = rsp\nif isinstance(errs, RPCError) and hasattr(errs, 'errors'):\n self.errs = [JXML.rpc_error(error.xml) for error in errs.errors]\n for error in errs.errors:\n if error.severity == ...
<|body_start_0|> self.cmd = cmd self.rsp = rsp self.dev = dev self.timeout = timeout self.re = re self.rpc_error = None self.xml = rsp if isinstance(errs, RPCError) and hasattr(errs, 'errors'): self.errs = [JXML.rpc_error(error.xml) for error i...
Parent class for all junos-pyez RPC Exceptions
RpcError
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RpcError: """Parent class for all junos-pyez RPC Exceptions""" def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None): """:cmd: is the rpc command :rsp: is the rpc response (after <rpc-reply>) :errs: is a list of dictionaries of extracted <rpc-error> eleme...
stack_v2_sparse_classes_36k_train_013713
9,037
permissive
[ { "docstring": ":cmd: is the rpc command :rsp: is the rpc response (after <rpc-reply>) :errs: is a list of dictionaries of extracted <rpc-error> elements. :dev: is the device rpc was executed on :timeout: is the timeout value of the device :re: is the RE or member exception occured on", "name": "__init__", ...
2
null
Implement the Python class `RpcError` described below. Class description: Parent class for all junos-pyez RPC Exceptions Method signatures and docstrings: - def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None): :cmd: is the rpc command :rsp: is the rpc response (after <rpc-reply>) :errs:...
Implement the Python class `RpcError` described below. Class description: Parent class for all junos-pyez RPC Exceptions Method signatures and docstrings: - def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None): :cmd: is the rpc command :rsp: is the rpc response (after <rpc-reply>) :errs:...
e19a7683be1da67140798987ac42e8c82041c393
<|skeleton|> class RpcError: """Parent class for all junos-pyez RPC Exceptions""" def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None): """:cmd: is the rpc command :rsp: is the rpc response (after <rpc-reply>) :errs: is a list of dictionaries of extracted <rpc-error> eleme...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RpcError: """Parent class for all junos-pyez RPC Exceptions""" def __init__(self, cmd=None, rsp=None, errs=None, dev=None, timeout=None, re=None): """:cmd: is the rpc command :rsp: is the rpc response (after <rpc-reply>) :errs: is a list of dictionaries of extracted <rpc-error> elements. :dev: is...
the_stack_v2_python_sparse
lib/jnpr/junos/exception.py
Juniper/py-junos-eznc
train
628
4b176da8904e0219f28e62297148af9c6176c649
[ "start_p = {'Healthy': 0.6, 'Fever': 0.4}\nhidden_state_p = {'Healthy': {'Healthy': 0.7, 'Fever': 0.3}, 'Fever': {'Healthy': 0.4, 'Fever': 0.6}}\nevent_p = {'Healthy': {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1}, 'Fever': {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6}}\nhmm = Hmm(start_p, hidden_state_p, event_p)\npath ...
<|body_start_0|> start_p = {'Healthy': 0.6, 'Fever': 0.4} hidden_state_p = {'Healthy': {'Healthy': 0.7, 'Fever': 0.3}, 'Fever': {'Healthy': 0.4, 'Fever': 0.6}} event_p = {'Healthy': {'normal': 0.5, 'cold': 0.4, 'dizzy': 0.1}, 'Fever': {'normal': 0.1, 'cold': 0.3, 'dizzy': 0.6}} hmm = Hmm...
HmmTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HmmTest: def test_sick_patient(self): """https://youtu.be/uAT3iJpQwJ0 https://en.wikipedia.org/wiki/Viterbi_algorithm""" <|body_0|> def test_weather(self): """https://en.wikipedia.org/wiki/Hidden_Markov_model""" <|body_1|> def test_gataca(self): ...
stack_v2_sparse_classes_36k_train_013714
13,944
no_license
[ { "docstring": "https://youtu.be/uAT3iJpQwJ0 https://en.wikipedia.org/wiki/Viterbi_algorithm", "name": "test_sick_patient", "signature": "def test_sick_patient(self)" }, { "docstring": "https://en.wikipedia.org/wiki/Hidden_Markov_model", "name": "test_weather", "signature": "def test_wea...
3
stack_v2_sparse_classes_30k_test_001186
Implement the Python class `HmmTest` described below. Class description: Implement the HmmTest class. Method signatures and docstrings: - def test_sick_patient(self): https://youtu.be/uAT3iJpQwJ0 https://en.wikipedia.org/wiki/Viterbi_algorithm - def test_weather(self): https://en.wikipedia.org/wiki/Hidden_Markov_mode...
Implement the Python class `HmmTest` described below. Class description: Implement the HmmTest class. Method signatures and docstrings: - def test_sick_patient(self): https://youtu.be/uAT3iJpQwJ0 https://en.wikipedia.org/wiki/Viterbi_algorithm - def test_weather(self): https://en.wikipedia.org/wiki/Hidden_Markov_mode...
2c92927322db17dd0c8cc8a8200877e0a5519b2c
<|skeleton|> class HmmTest: def test_sick_patient(self): """https://youtu.be/uAT3iJpQwJ0 https://en.wikipedia.org/wiki/Viterbi_algorithm""" <|body_0|> def test_weather(self): """https://en.wikipedia.org/wiki/Hidden_Markov_model""" <|body_1|> def test_gataca(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class HmmTest: def test_sick_patient(self): """https://youtu.be/uAT3iJpQwJ0 https://en.wikipedia.org/wiki/Viterbi_algorithm""" start_p = {'Healthy': 0.6, 'Fever': 0.4} hidden_state_p = {'Healthy': {'Healthy': 0.7, 'Fever': 0.3}, 'Fever': {'Healthy': 0.4, 'Fever': 0.6}} event_p = {'He...
the_stack_v2_python_sparse
hmm.py
rodolf0/snippets
train
0
272a843592f160ad7cdbb2c798a266e0a7c50293
[ "if not prices:\n return 0\nn = len(prices)\ndp, money, profit = ([], prices[0], 0)\nfor i in range(n):\n profit = max(profit, prices[i] - money)\n money = min(money, prices[i])\n dp.append(profit)\ni, ans, money, profit = (n - 1, dp[n - 1], prices[n - 1], 0)\nwhile i >= 0:\n profit = max(profit, mon...
<|body_start_0|> if not prices: return 0 n = len(prices) dp, money, profit = ([], prices[0], 0) for i in range(n): profit = max(profit, prices[i] - money) money = min(money, prices[i]) dp.append(profit) i, ans, money, profit = (n - ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k_train_013715
3,922
no_license
[ { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" }, { "docstring": ":type prices: List[int] :rtype: int", "name": "maxProfit", "signature": "def maxProfit(self, prices)" }, { "docstring": ":type prices: List[int...
4
stack_v2_sparse_classes_30k_train_016196
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: L...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: List[int] :rtype: int - def maxProfit(self, prices): :type prices: L...
a2cd0dc5e098080df87c4fb57d16877d21ca47a3
<|skeleton|> class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_0|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" <|body_1|> def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit(self, prices): """:type prices: List[int] :rtype: int""" if not prices: return 0 n = len(prices) dp, money, profit = ([], prices[0], 0) for i in range(n): profit = max(profit, prices[i] - money) money = min(mon...
the_stack_v2_python_sparse
0123_Best_Time_to_Buy_and_Sell_Stock_III/solution.py
benjaminhuanghuang/ben-leetcode
train
1
fd7c2e83d33918e5bdeaaee4ef08f5e2f1eb359c
[ "self._repeat_interval = repeat\nself._wait_ticks = initial_delay\nif time_based:\n self._tick_generator = pygame.time.Clock().tick\nelse:\n self._tick_generator = lambda: 1", "self._wait_ticks -= self._tick_generator()\nif self._wait_ticks <= 0:\n self._wait_ticks = self._repeat_interval\n return Tru...
<|body_start_0|> self._repeat_interval = repeat self._wait_ticks = initial_delay if time_based: self._tick_generator = pygame.time.Clock().tick else: self._tick_generator = lambda: 1 <|end_body_0|> <|body_start_1|> self._wait_ticks -= self._tick_generator...
A simple class to manage periodic events based on either the number of cycles/ticks passed or time passed. Typical Code Usage: ticker = TickRepeater(20) while <condition>: if ticker.tick(): <do periodic work>
TickRepeater
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TickRepeater: """A simple class to manage periodic events based on either the number of cycles/ticks passed or time passed. Typical Code Usage: ticker = TickRepeater(20) while <condition>: if ticker.tick(): <do periodic work>""" def __init__(self, repeat: int, initial_delay: int=0, time_base...
stack_v2_sparse_classes_36k_train_013716
7,343
permissive
[ { "docstring": "Sets up a tick counter with a specific periodicity and initial delay. :param repeat: number of ticks to wait between executions :param initial_delay: initial number of ticks to wait before the first execution", "name": "__init__", "signature": "def __init__(self, repeat: int, initial_del...
2
stack_v2_sparse_classes_30k_train_016884
Implement the Python class `TickRepeater` described below. Class description: A simple class to manage periodic events based on either the number of cycles/ticks passed or time passed. Typical Code Usage: ticker = TickRepeater(20) while <condition>: if ticker.tick(): <do periodic work> Method signatures and docstring...
Implement the Python class `TickRepeater` described below. Class description: A simple class to manage periodic events based on either the number of cycles/ticks passed or time passed. Typical Code Usage: ticker = TickRepeater(20) while <condition>: if ticker.tick(): <do periodic work> Method signatures and docstring...
652eb52f2ac7f65f9b3bec93702caec866775e98
<|skeleton|> class TickRepeater: """A simple class to manage periodic events based on either the number of cycles/ticks passed or time passed. Typical Code Usage: ticker = TickRepeater(20) while <condition>: if ticker.tick(): <do periodic work>""" def __init__(self, repeat: int, initial_delay: int=0, time_base...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TickRepeater: """A simple class to manage periodic events based on either the number of cycles/ticks passed or time passed. Typical Code Usage: ticker = TickRepeater(20) while <condition>: if ticker.tick(): <do periodic work>""" def __init__(self, repeat: int, initial_delay: int=0, time_based=False): ...
the_stack_v2_python_sparse
minesweeper/utils.py
tmthyln/deepminesweeper
train
2
edb81e19985485f259300ec0c86f0f83ca151307
[ "def callback(*_):\n root = self.master.winfo_toplevel()\n root.event_generate(sequence)\nreturn callback", "super().__init__(parent, **kwargs)\nself.settings = settings\nhelp_menu = tk.Menu(self, tearoff=False)\nhelp_menu.add_command(label='About…', command=self.show_about)\nfile_menu = tk.Menu(self, tearo...
<|body_start_0|> def callback(*_): root = self.master.winfo_toplevel() root.event_generate(sequence) return callback <|end_body_0|> <|body_start_1|> super().__init__(parent, **kwargs) self.settings = settings help_menu = tk.Menu(self, tearoff=False) ...
The Application's main menu
MainMenu
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MainMenu: """The Application's main menu""" def _event(self, sequence): """Return a callback function that generates the sequence""" <|body_0|> def __init__(self, parent, settings, **kwargs): """Constructor for MainMenu arguments: parent - The parent widget setti...
stack_v2_sparse_classes_36k_train_013717
2,215
permissive
[ { "docstring": "Return a callback function that generates the sequence", "name": "_event", "signature": "def _event(self, sequence)" }, { "docstring": "Constructor for MainMenu arguments: parent - The parent widget settings - a dict containing Tkinter variables", "name": "__init__", "sig...
3
stack_v2_sparse_classes_30k_train_002964
Implement the Python class `MainMenu` described below. Class description: The Application's main menu Method signatures and docstrings: - def _event(self, sequence): Return a callback function that generates the sequence - def __init__(self, parent, settings, **kwargs): Constructor for MainMenu arguments: parent - Th...
Implement the Python class `MainMenu` described below. Class description: The Application's main menu Method signatures and docstrings: - def _event(self, sequence): Return a callback function that generates the sequence - def __init__(self, parent, settings, **kwargs): Constructor for MainMenu arguments: parent - Th...
9e9c7468982992d87358be09c11c2cfaaaecd615
<|skeleton|> class MainMenu: """The Application's main menu""" def _event(self, sequence): """Return a callback function that generates the sequence""" <|body_0|> def __init__(self, parent, settings, **kwargs): """Constructor for MainMenu arguments: parent - The parent widget setti...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MainMenu: """The Application's main menu""" def _event(self, sequence): """Return a callback function that generates the sequence""" def callback(*_): root = self.master.winfo_toplevel() root.event_generate(sequence) return callback def __init__(self, ...
the_stack_v2_python_sparse
Chapter08/ABQ_Data_Entry/abq_data_entry/mainmenu.py
LihengGong/Python-GUI-Programming-with-Tkinter-2E
train
0
de6849597c5d723fe2cc65243a26ebd859d292d6
[ "file = './FilteredData/filteredData.csv'\nmapData = MapDataSelector(file)\nt = mapData.getYearData(2000, ['Hail'])\nself.assertEqual(len(t), 2)\nself.assertEqual(len(t[0]), len(t[1]))\nself.assertTrue(len(t[0]) > 0)", "file = './FilteredData/filteredData.csv'\nmapData = MapDataSelector(file)\nt = mapData.getYear...
<|body_start_0|> file = './FilteredData/filteredData.csv' mapData = MapDataSelector(file) t = mapData.getYearData(2000, ['Hail']) self.assertEqual(len(t), 2) self.assertEqual(len(t[0]), len(t[1])) self.assertTrue(len(t[0]) > 0) <|end_body_0|> <|body_start_1|> fil...
MapDataTests
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MapDataTests: def test_lengthHail(self): """Tests lengths match""" <|body_0|> def test_lengthMulti(self): """Tests lengths match with multiselect""" <|body_1|> def test_lonMulti(self): """Tests lons valid""" <|body_2|> <|end_skeleton|> ...
stack_v2_sparse_classes_36k_train_013718
1,114
no_license
[ { "docstring": "Tests lengths match", "name": "test_lengthHail", "signature": "def test_lengthHail(self)" }, { "docstring": "Tests lengths match with multiselect", "name": "test_lengthMulti", "signature": "def test_lengthMulti(self)" }, { "docstring": "Tests lons valid", "nam...
3
null
Implement the Python class `MapDataTests` described below. Class description: Implement the MapDataTests class. Method signatures and docstrings: - def test_lengthHail(self): Tests lengths match - def test_lengthMulti(self): Tests lengths match with multiselect - def test_lonMulti(self): Tests lons valid
Implement the Python class `MapDataTests` described below. Class description: Implement the MapDataTests class. Method signatures and docstrings: - def test_lengthHail(self): Tests lengths match - def test_lengthMulti(self): Tests lengths match with multiselect - def test_lonMulti(self): Tests lons valid <|skeleton|...
dc9185cbc5e65650d985ebecf877a157c8c19a13
<|skeleton|> class MapDataTests: def test_lengthHail(self): """Tests lengths match""" <|body_0|> def test_lengthMulti(self): """Tests lengths match with multiselect""" <|body_1|> def test_lonMulti(self): """Tests lons valid""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MapDataTests: def test_lengthHail(self): """Tests lengths match""" file = './FilteredData/filteredData.csv' mapData = MapDataSelector(file) t = mapData.getYearData(2000, ['Hail']) self.assertEqual(len(t), 2) self.assertEqual(len(t[0]), len(t[1])) self.as...
the_stack_v2_python_sparse
rb2540/MapDataTests.py
ds-ga-1007/final_project
train
0
8e09b3c90ae813ea92a0fea935d9497c4608d498
[ "super(LayerNorm, self).__init__()\nself.a_2 = nn.Parameter(torch.ones(features))\nself.b_2 = nn.Parameter(torch.zeros(features))\nself.eps = eps", "mean = x.mean(-1, keepdim=True)\nstd = x.std(-1, keepdim=True)\nreturn self.a_2 * (x - mean) / (std + self.eps) + self.b_2" ]
<|body_start_0|> super(LayerNorm, self).__init__() self.a_2 = nn.Parameter(torch.ones(features)) self.b_2 = nn.Parameter(torch.zeros(features)) self.eps = eps <|end_body_0|> <|body_start_1|> mean = x.mean(-1, keepdim=True) std = x.std(-1, keepdim=True) return sel...
LayerNorm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LayerNorm: def __init__(self, features, eps=1e-06): """param features: number of features in input to normalzie param eps: epsilon to ensure stabiltiy in normalizing""" <|body_0|> def forward(self, x): """Normalizes the input params x: tensor to normalize return: nor...
stack_v2_sparse_classes_36k_train_013719
11,359
no_license
[ { "docstring": "param features: number of features in input to normalzie param eps: epsilon to ensure stabiltiy in normalizing", "name": "__init__", "signature": "def __init__(self, features, eps=1e-06)" }, { "docstring": "Normalizes the input params x: tensor to normalize return: normalizes the...
2
stack_v2_sparse_classes_30k_train_018013
Implement the Python class `LayerNorm` described below. Class description: Implement the LayerNorm class. Method signatures and docstrings: - def __init__(self, features, eps=1e-06): param features: number of features in input to normalzie param eps: epsilon to ensure stabiltiy in normalizing - def forward(self, x): ...
Implement the Python class `LayerNorm` described below. Class description: Implement the LayerNorm class. Method signatures and docstrings: - def __init__(self, features, eps=1e-06): param features: number of features in input to normalzie param eps: epsilon to ensure stabiltiy in normalizing - def forward(self, x): ...
c0b2f83a7d4c0d5fa5effb7584e0e0acc6f877a0
<|skeleton|> class LayerNorm: def __init__(self, features, eps=1e-06): """param features: number of features in input to normalzie param eps: epsilon to ensure stabiltiy in normalizing""" <|body_0|> def forward(self, x): """Normalizes the input params x: tensor to normalize return: nor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LayerNorm: def __init__(self, features, eps=1e-06): """param features: number of features in input to normalzie param eps: epsilon to ensure stabiltiy in normalizing""" super(LayerNorm, self).__init__() self.a_2 = nn.Parameter(torch.ones(features)) self.b_2 = nn.Parameter(torch...
the_stack_v2_python_sparse
src/main/base_models/architectures/Transformer.py
iesl/institution_hierarchies
train
3
548b005eb3e0043b0393c3a2559eac1add0e6a5f
[ "i, j = (len(S) - 1, 0)\nres = []\nwhile i >= 0:\n if S[i] == '-':\n i -= 1\n continue\n if j == K:\n res.append('-')\n j = 0\n continue\n else:\n res.append(S[i].upper())\n j += 1\n i -= 1\nreturn ''.join(res[::-1])", "S_ = S.replace('-', '')\nn = len(S_) ...
<|body_start_0|> i, j = (len(S) - 1, 0) res = [] while i >= 0: if S[i] == '-': i -= 1 continue if j == K: res.append('-') j = 0 continue else: res.append(S[i].upper...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def licenseKeyFormatting(self, S, K): """:type S: str :type K: int :rtype: str""" <|body_0|> def licenseKeyFormatting2(self, S, K): """:type S: str :type K: int :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> i, j = (len(S) - 1...
stack_v2_sparse_classes_36k_train_013720
1,763
no_license
[ { "docstring": ":type S: str :type K: int :rtype: str", "name": "licenseKeyFormatting", "signature": "def licenseKeyFormatting(self, S, K)" }, { "docstring": ":type S: str :type K: int :rtype: str", "name": "licenseKeyFormatting2", "signature": "def licenseKeyFormatting2(self, S, K)" }...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def licenseKeyFormatting(self, S, K): :type S: str :type K: int :rtype: str - def licenseKeyFormatting2(self, S, K): :type S: str :type K: int :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def licenseKeyFormatting(self, S, K): :type S: str :type K: int :rtype: str - def licenseKeyFormatting2(self, S, K): :type S: str :type K: int :rtype: str <|skeleton|> class Sol...
546cbce06fcd4bc34e16d42b5d5eb68fb25e16a9
<|skeleton|> class Solution: def licenseKeyFormatting(self, S, K): """:type S: str :type K: int :rtype: str""" <|body_0|> def licenseKeyFormatting2(self, S, K): """:type S: str :type K: int :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def licenseKeyFormatting(self, S, K): """:type S: str :type K: int :rtype: str""" i, j = (len(S) - 1, 0) res = [] while i >= 0: if S[i] == '-': i -= 1 continue if j == K: res.append('-') ...
the_stack_v2_python_sparse
leetcode/solution_482.py
eselyavka/python
train
0
8386cc3e6407247fb98fe8bd5e810d6c31436eb9
[ "self.name = name\nself.age = age\nPerson.Count += 1", "print('name is ', self.name)\nprint('age is ', self.age)\nprint('there are ' + str(Person.Count) + ' person in the class')" ]
<|body_start_0|> self.name = name self.age = age Person.Count += 1 <|end_body_0|> <|body_start_1|> print('name is ', self.name) print('age is ', self.age) print('there are ' + str(Person.Count) + ' person in the class') <|end_body_1|>
classdocs
Person
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Person: """classdocs""" def __init__(self, name, age): """Constructor @param: name the name of this person @param: age the age of this person""" <|body_0|> def detail(self): """the detail infomation of this person""" <|body_1|> <|end_skeleton|> <|body_s...
stack_v2_sparse_classes_36k_train_013721
889
no_license
[ { "docstring": "Constructor @param: name the name of this person @param: age the age of this person", "name": "__init__", "signature": "def __init__(self, name, age)" }, { "docstring": "the detail infomation of this person", "name": "detail", "signature": "def detail(self)" } ]
2
stack_v2_sparse_classes_30k_train_011693
Implement the Python class `Person` described below. Class description: classdocs Method signatures and docstrings: - def __init__(self, name, age): Constructor @param: name the name of this person @param: age the age of this person - def detail(self): the detail infomation of this person
Implement the Python class `Person` described below. Class description: classdocs Method signatures and docstrings: - def __init__(self, name, age): Constructor @param: name the name of this person @param: age the age of this person - def detail(self): the detail infomation of this person <|skeleton|> class Person: ...
c7dd6def7ec081b483c3a4cfe334d17c049224c2
<|skeleton|> class Person: """classdocs""" def __init__(self, name, age): """Constructor @param: name the name of this person @param: age the age of this person""" <|body_0|> def detail(self): """the detail infomation of this person""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Person: """classdocs""" def __init__(self, name, age): """Constructor @param: name the name of this person @param: age the age of this person""" self.name = name self.age = age Person.Count += 1 def detail(self): """the detail infomation of this person""" ...
the_stack_v2_python_sparse
offline-only/tkinter/jicheng.py
liucz25/FSGL
train
1
13a7a0d8e083f8a893d1d53d05a7aaf4630aa5d9
[ "self.object = form.save()\nif hasattr(self, 'on_success'):\n self.on_success(form)\nurl = '' if self.reload_on_success else self.get_success_url()\nreturn HttpResponse(url)", "resp = super(AjaxFormView, self).form_invalid(form)\nresp.status_code = 403\nreturn resp" ]
<|body_start_0|> self.object = form.save() if hasattr(self, 'on_success'): self.on_success(form) url = '' if self.reload_on_success else self.get_success_url() return HttpResponse(url) <|end_body_0|> <|body_start_1|> resp = super(AjaxFormView, self).form_invalid(form...
a mixin used for ajax based forms. see `forms.js`.
AjaxFormView
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AjaxFormView: """a mixin used for ajax based forms. see `forms.js`.""" def form_valid(self, form): """returns link to redirect or empty string to reload as text/html""" <|body_0|> def form_invalid(self, form): """returns an 403 http response with form, including ...
stack_v2_sparse_classes_36k_train_013722
6,925
permissive
[ { "docstring": "returns link to redirect or empty string to reload as text/html", "name": "form_valid", "signature": "def form_valid(self, form)" }, { "docstring": "returns an 403 http response with form, including errors, as text/html", "name": "form_invalid", "signature": "def form_inv...
2
null
Implement the Python class `AjaxFormView` described below. Class description: a mixin used for ajax based forms. see `forms.js`. Method signatures and docstrings: - def form_valid(self, form): returns link to redirect or empty string to reload as text/html - def form_invalid(self, form): returns an 403 http response ...
Implement the Python class `AjaxFormView` described below. Class description: a mixin used for ajax based forms. see `forms.js`. Method signatures and docstrings: - def form_valid(self, form): returns link to redirect or empty string to reload as text/html - def form_invalid(self, form): returns an 403 http response ...
549438b126797a252dbd554179b03764566b946a
<|skeleton|> class AjaxFormView: """a mixin used for ajax based forms. see `forms.js`.""" def form_valid(self, form): """returns link to redirect or empty string to reload as text/html""" <|body_0|> def form_invalid(self, form): """returns an 403 http response with form, including ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AjaxFormView: """a mixin used for ajax based forms. see `forms.js`.""" def form_valid(self, form): """returns link to redirect or empty string to reload as text/html""" self.object = form.save() if hasattr(self, 'on_success'): self.on_success(form) url = '' if ...
the_stack_v2_python_sparse
src/ocd/base_views.py
yaniv14/OpenCommunity
train
0
476dbafcf90978aa393edcd047dadd0419ca1b63
[ "ref = 'tttt'\nquery = 'ttAtt'\nmatch = 4\nmismatch = 2\ngap_extend_penalty = 2\ngap_open_penalty = 4\naligner = ssw.Aligner.construct(match_score=match, mismatch_penalty=mismatch, gap_opening_penalty=gap_open_penalty, gap_extending_penalty=gap_extend_penalty)\nfilter_ = ssw.Filter()\nlength = aligner.set_reference...
<|body_start_0|> ref = 'tttt' query = 'ttAtt' match = 4 mismatch = 2 gap_extend_penalty = 2 gap_open_penalty = 4 aligner = ssw.Aligner.construct(match_score=match, mismatch_penalty=mismatch, gap_opening_penalty=gap_open_penalty, gap_extending_penalty=gap_extend_pe...
Tests for the wrapped SSW aligner in a way that fails with gcc5.4.
SswGccTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SswGccTest: """Tests for the wrapped SSW aligner in a way that fails with gcc5.4.""" def test_short(self): """Test very short strings.""" <|body_0|> def test_longer(self): """Test longer strings, so the second-best alignment is considered.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_013723
3,151
permissive
[ { "docstring": "Test very short strings.", "name": "test_short", "signature": "def test_short(self)" }, { "docstring": "Test longer strings, so the second-best alignment is considered.", "name": "test_longer", "signature": "def test_longer(self)" } ]
2
stack_v2_sparse_classes_30k_train_002655
Implement the Python class `SswGccTest` described below. Class description: Tests for the wrapped SSW aligner in a way that fails with gcc5.4. Method signatures and docstrings: - def test_short(self): Test very short strings. - def test_longer(self): Test longer strings, so the second-best alignment is considered.
Implement the Python class `SswGccTest` described below. Class description: Tests for the wrapped SSW aligner in a way that fails with gcc5.4. Method signatures and docstrings: - def test_short(self): Test very short strings. - def test_longer(self): Test longer strings, so the second-best alignment is considered. <...
ab068c4588a02e2167051bd9e74c0c9579462b51
<|skeleton|> class SswGccTest: """Tests for the wrapped SSW aligner in a way that fails with gcc5.4.""" def test_short(self): """Test very short strings.""" <|body_0|> def test_longer(self): """Test longer strings, so the second-best alignment is considered.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SswGccTest: """Tests for the wrapped SSW aligner in a way that fails with gcc5.4.""" def test_short(self): """Test very short strings.""" ref = 'tttt' query = 'ttAtt' match = 4 mismatch = 2 gap_extend_penalty = 2 gap_open_penalty = 4 aligner...
the_stack_v2_python_sparse
deepvariant/realigner/python/ssw_misc_test.py
google/deepvariant
train
3,002
cc4f29a161eab13f9418823efcdea37e9c449c29
[ "email_token = data\ntime = timezone.now() - timezone.timedelta(days=7)\ntry:\n token = Token.objects.get(key=email_token)\nexcept Token.DoesNotExist:\n raise serializers.ValidationError('Invalid token.')\nif token.created < time:\n raise serializers.ValidationError('Expired token.')\nself.context['token']...
<|body_start_0|> email_token = data time = timezone.now() - timezone.timedelta(days=7) try: token = Token.objects.get(key=email_token) except Token.DoesNotExist: raise serializers.ValidationError('Invalid token.') if token.created < time: raise...
Verify user's account and change status 'is_active' to true
VerifyAccountSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VerifyAccountSerializer: """Verify user's account and change status 'is_active' to true""" def validate_token(self, data): """Validate the token.""" <|body_0|> def save(self, **kwargs): """Update user's active status and token.""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k_train_013724
10,085
no_license
[ { "docstring": "Validate the token.", "name": "validate_token", "signature": "def validate_token(self, data)" }, { "docstring": "Update user's active status and token.", "name": "save", "signature": "def save(self, **kwargs)" } ]
2
null
Implement the Python class `VerifyAccountSerializer` described below. Class description: Verify user's account and change status 'is_active' to true Method signatures and docstrings: - def validate_token(self, data): Validate the token. - def save(self, **kwargs): Update user's active status and token.
Implement the Python class `VerifyAccountSerializer` described below. Class description: Verify user's account and change status 'is_active' to true Method signatures and docstrings: - def validate_token(self, data): Validate the token. - def save(self, **kwargs): Update user's active status and token. <|skeleton|> ...
e2f4557e2a85405838c6c9f65f1cb8a5f60a35ba
<|skeleton|> class VerifyAccountSerializer: """Verify user's account and change status 'is_active' to true""" def validate_token(self, data): """Validate the token.""" <|body_0|> def save(self, **kwargs): """Update user's active status and token.""" <|body_1|> <|end_skelet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VerifyAccountSerializer: """Verify user's account and change status 'is_active' to true""" def validate_token(self, data): """Validate the token.""" email_token = data time = timezone.now() - timezone.timedelta(days=7) try: token = Token.objects.get(key=email_t...
the_stack_v2_python_sparse
apps/users/serializers/users.py
HebertFerrer/WebMaster-back-end
train
0
3ac54465dc818aa85a46d13be5f3255540181706
[ "num = len(gas)\nfor i in range(num):\n remain = gas[i] - cost[i]\n if remain < 0:\n continue\n else:\n j = i\n while remain >= 0:\n j = (j + 1) % num\n remain += gas[j] - cost[j]\n if remain < 0:\n break\n if j == i and remain...
<|body_start_0|> num = len(gas) for i in range(num): remain = gas[i] - cost[i] if remain < 0: continue else: j = i while remain >= 0: j = (j + 1) % num remain += gas[j] - cost[j] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def canCompleteCircuit(self, gas, cost): """:type gas: List[int] :type cost: List[int] :rtype: int""" <|body_0|> def canCompleteCircuit2(self, gas, cost): """:type gas: List[int] :type cost: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|b...
stack_v2_sparse_classes_36k_train_013725
1,428
no_license
[ { "docstring": ":type gas: List[int] :type cost: List[int] :rtype: int", "name": "canCompleteCircuit", "signature": "def canCompleteCircuit(self, gas, cost)" }, { "docstring": ":type gas: List[int] :type cost: List[int] :rtype: int", "name": "canCompleteCircuit2", "signature": "def canCo...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int - def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def canCompleteCircuit(self, gas, cost): :type gas: List[int] :type cost: List[int] :rtype: int - def canCompleteCircuit2(self, gas, cost): :type gas: List[int] :type cost: List[...
0fc4c7af59246e3064db41989a45d9db413a624b
<|skeleton|> class Solution: def canCompleteCircuit(self, gas, cost): """:type gas: List[int] :type cost: List[int] :rtype: int""" <|body_0|> def canCompleteCircuit2(self, gas, cost): """:type gas: List[int] :type cost: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def canCompleteCircuit(self, gas, cost): """:type gas: List[int] :type cost: List[int] :rtype: int""" num = len(gas) for i in range(num): remain = gas[i] - cost[i] if remain < 0: continue else: j = i ...
the_stack_v2_python_sparse
134. Gas Station/gas.py
Macielyoung/LeetCode
train
1
4b5368c8c9b7ecbf6a968475da7d330f481e5731
[ "editor_class: Optional[Type[MP3Editor]] = None\nif editor is None:\n editor_class = EDITORS[0]\nelse:\n editor = editor.lower()\n for ecls in EDITORS:\n if ecls.__name__.lower() == editor:\n editor_class = ecls\n break\nif editor_class is None:\n raise NotImplementedError(f...
<|body_start_0|> editor_class: Optional[Type[MP3Editor]] = None if editor is None: editor_class = EDITORS[0] else: editor = editor.lower() for ecls in EDITORS: if ecls.__name__.lower() == editor: editor_class = ecls ...
Class for creating MP3Editor and MP3Parser instances
MP3Factory
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MP3Factory: """Class for creating MP3Editor and MP3Parser instances""" def create_editor(cls, editor: Optional[str]=None) -> MP3Editor: """Create an MP3Editor. If editor==None, the factory will pick the first one that is supported.""" <|body_0|> def create_parser(cls, pa...
stack_v2_sparse_classes_36k_train_013726
1,969
no_license
[ { "docstring": "Create an MP3Editor. If editor==None, the factory will pick the first one that is supported.", "name": "create_editor", "signature": "def create_editor(cls, editor: Optional[str]=None) -> MP3Editor" }, { "docstring": "Create an MP3Parser. If parser==None, the factory will pick th...
2
stack_v2_sparse_classes_30k_train_001488
Implement the Python class `MP3Factory` described below. Class description: Class for creating MP3Editor and MP3Parser instances Method signatures and docstrings: - def create_editor(cls, editor: Optional[str]=None) -> MP3Editor: Create an MP3Editor. If editor==None, the factory will pick the first one that is suppor...
Implement the Python class `MP3Factory` described below. Class description: Class for creating MP3Editor and MP3Parser instances Method signatures and docstrings: - def create_editor(cls, editor: Optional[str]=None) -> MP3Editor: Create an MP3Editor. If editor==None, the factory will pick the first one that is suppor...
ede4d295d90e81bf2cfcd52ab894273e139c3730
<|skeleton|> class MP3Factory: """Class for creating MP3Editor and MP3Parser instances""" def create_editor(cls, editor: Optional[str]=None) -> MP3Editor: """Create an MP3Editor. If editor==None, the factory will pick the first one that is supported.""" <|body_0|> def create_parser(cls, pa...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MP3Factory: """Class for creating MP3Editor and MP3Parser instances""" def create_editor(cls, editor: Optional[str]=None) -> MP3Editor: """Create an MP3Editor. If editor==None, the factory will pick the first one that is supported.""" editor_class: Optional[Type[MP3Editor]] = None ...
the_stack_v2_python_sparse
musicbingo/mp3/factory.py
jdizzle1988/music-bingo
train
0
7c05fb6bdc88876cce6ca8e3aac44c7a98c1003a
[ "if MUTED:\n return MutedSound()\nelse:\n return pygame.mixer.Sound(os.path.join('data', 'sounds', name))", "if not MUTED and False:\n pygame.mixer.music.load(os.path.join('data', 'music', name))\n pygame.mixer.music.play(-1)" ]
<|body_start_0|> if MUTED: return MutedSound() else: return pygame.mixer.Sound(os.path.join('data', 'sounds', name)) <|end_body_0|> <|body_start_1|> if not MUTED and False: pygame.mixer.music.load(os.path.join('data', 'music', name)) pygame.mixer....
Handle sounds
_Sounds
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _Sounds: """Handle sounds""" def getSound(self, name): """Return a new sound""" <|body_0|> def playMusic(self, name): """Return a new sound""" <|body_1|> <|end_skeleton|> <|body_start_0|> if MUTED: return MutedSound() else: ...
stack_v2_sparse_classes_36k_train_013727
638
permissive
[ { "docstring": "Return a new sound", "name": "getSound", "signature": "def getSound(self, name)" }, { "docstring": "Return a new sound", "name": "playMusic", "signature": "def playMusic(self, name)" } ]
2
null
Implement the Python class `_Sounds` described below. Class description: Handle sounds Method signatures and docstrings: - def getSound(self, name): Return a new sound - def playMusic(self, name): Return a new sound
Implement the Python class `_Sounds` described below. Class description: Handle sounds Method signatures and docstrings: - def getSound(self, name): Return a new sound - def playMusic(self, name): Return a new sound <|skeleton|> class _Sounds: """Handle sounds""" def getSound(self, name): """Return ...
cee7e4b5dc28c57a6c912852827652b5f51005ae
<|skeleton|> class _Sounds: """Handle sounds""" def getSound(self, name): """Return a new sound""" <|body_0|> def playMusic(self, name): """Return a new sound""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _Sounds: """Handle sounds""" def getSound(self, name): """Return a new sound""" if MUTED: return MutedSound() else: return pygame.mixer.Sound(os.path.join('data', 'sounds', name)) def playMusic(self, name): """Return a new sound""" if n...
the_stack_v2_python_sparse
IE_games_8/unvisible-0.4.0/unvisible/sound.py
IndexErrorCoders/PygamesCompilation
train
2
992801d21d037431328b9c8631a8fd2d3f5b167d
[ "if move_nr == 0:\n return hand\ncolor_played = color_of_card[current_trick[0]]\nhave_color_played = np.sum(hand * color_masks[color_played, :]) > 0\nif have_color_played:\n return hand * color_masks[color_played, :]\nelse:\n return hand", "hearts = color_masks[HEARTS, :]\npoints = -hearts[trick].sum()\n...
<|body_start_0|> if move_nr == 0: return hand color_played = color_of_card[current_trick[0]] have_color_played = np.sum(hand * color_masks[color_played, :]) > 0 if have_color_played: return hand * color_masks[color_played, :] else: return hand ...
Class for implementing rules of the jass game for hearts. The rules are as follows: - The winner of a trick is determined by the basic jass rules without trump, i.e. like "obe" - Each heart card gives a penalty of 1 point. - The SQ card gives a penalty of 9 points. - The valid cards are determined like in 'obe', i.e. y...
RuleHearts
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RuleHearts: """Class for implementing rules of the jass game for hearts. The rules are as follows: - The winner of a trick is determined by the basic jass rules without trump, i.e. like "obe" - Each heart card gives a penalty of 1 point. - The SQ card gives a penalty of 9 points. - The valid card...
stack_v2_sparse_classes_36k_train_013728
3,399
no_license
[ { "docstring": "Get the valid cards that can be played by the current player. Args: hand: one-hot encoded array of hands owned by the player current_trick: array with the indices of the cards for the previous moves in the current trick move_nr: which move the player has to make in the current trick, 0 for first...
3
null
Implement the Python class `RuleHearts` described below. Class description: Class for implementing rules of the jass game for hearts. The rules are as follows: - The winner of a trick is determined by the basic jass rules without trump, i.e. like "obe" - Each heart card gives a penalty of 1 point. - The SQ card gives ...
Implement the Python class `RuleHearts` described below. Class description: Class for implementing rules of the jass game for hearts. The rules are as follows: - The winner of a trick is determined by the basic jass rules without trump, i.e. like "obe" - Each heart card gives a penalty of 1 point. - The SQ card gives ...
73b59f773f138e390951849f982de865d4f667b5
<|skeleton|> class RuleHearts: """Class for implementing rules of the jass game for hearts. The rules are as follows: - The winner of a trick is determined by the basic jass rules without trump, i.e. like "obe" - Each heart card gives a penalty of 1 point. - The SQ card gives a penalty of 9 points. - The valid card...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RuleHearts: """Class for implementing rules of the jass game for hearts. The rules are as follows: - The winner of a trick is determined by the basic jass rules without trump, i.e. like "obe" - Each heart card gives a penalty of 1 point. - The SQ card gives a penalty of 9 points. - The valid cards are determi...
the_stack_v2_python_sparse
source/jass/base/rule_hearts.py
FAIKUE/DL4G
train
0
e841e63d18c81995bc5e365156c9cfaa1a026573
[ "if not triangle:\n return 0\nn = len(triangle)\ndp = [[0] * (i + 1) for i in range(n)]\ndp[0][0] = triangle[0][0]\nfor i in range(1, n):\n dp[i][0] = dp[i - 1][0] + triangle[i][0]\n dp[i][-1] = dp[i - 1][-1] + triangle[i][-1]\nfor i in range(2, n):\n for j in range(1, i):\n dp[i][j] = min(dp[i -...
<|body_start_0|> if not triangle: return 0 n = len(triangle) dp = [[0] * (i + 1) for i in range(n)] dp[0][0] = triangle[0][0] for i in range(1, n): dp[i][0] = dp[i - 1][0] + triangle[i][0] dp[i][-1] = dp[i - 1][-1] + triangle[i][-1] for...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minimumTotal(self, triangle): """自上向下dp 空间复杂度0(n^2) :type triangle: List[List[int]] :rtype: int""" <|body_0|> def minimumTotal2(self, triangle): """自顶乡下dp 空间复杂度O(n^2) 代码复杂度优化 加一行不用初始化dp :param triangle: :return:""" <|body_1|> def minimumTot...
stack_v2_sparse_classes_36k_train_013729
2,512
no_license
[ { "docstring": "自上向下dp 空间复杂度0(n^2) :type triangle: List[List[int]] :rtype: int", "name": "minimumTotal", "signature": "def minimumTotal(self, triangle)" }, { "docstring": "自顶乡下dp 空间复杂度O(n^2) 代码复杂度优化 加一行不用初始化dp :param triangle: :return:", "name": "minimumTotal2", "signature": "def minimum...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle): 自上向下dp 空间复杂度0(n^2) :type triangle: List[List[int]] :rtype: int - def minimumTotal2(self, triangle): 自顶乡下dp 空间复杂度O(n^2) 代码复杂度优化 加一行不用初始化dp :param...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minimumTotal(self, triangle): 自上向下dp 空间复杂度0(n^2) :type triangle: List[List[int]] :rtype: int - def minimumTotal2(self, triangle): 自顶乡下dp 空间复杂度O(n^2) 代码复杂度优化 加一行不用初始化dp :param...
5d3574ccd282d0146c83c286ae28d8baaabd4910
<|skeleton|> class Solution: def minimumTotal(self, triangle): """自上向下dp 空间复杂度0(n^2) :type triangle: List[List[int]] :rtype: int""" <|body_0|> def minimumTotal2(self, triangle): """自顶乡下dp 空间复杂度O(n^2) 代码复杂度优化 加一行不用初始化dp :param triangle: :return:""" <|body_1|> def minimumTot...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def minimumTotal(self, triangle): """自上向下dp 空间复杂度0(n^2) :type triangle: List[List[int]] :rtype: int""" if not triangle: return 0 n = len(triangle) dp = [[0] * (i + 1) for i in range(n)] dp[0][0] = triangle[0][0] for i in range(1, n): ...
the_stack_v2_python_sparse
120_三角形最小路径和.py
lovehhf/LeetCode
train
0
d9561d872188c1486a844288ad13e1b71d27b1ae
[ "errors = {}\nif 'delivery_date' in bundle.data:\n try:\n dateutil.parser.parse(bundle.data['delivery_date'])\n except Exception:\n logger.error('Missing delivery date.')\n errors['delivery_date'] = 'Not a valid date format.'\nif 'vat' in bundle.data:\n try:\n int(bundle.data['v...
<|body_start_0|> errors = {} if 'delivery_date' in bundle.data: try: dateutil.parser.parse(bundle.data['delivery_date']) except Exception: logger.error('Missing delivery date.') errors['delivery_date'] = 'Not a valid date format.' ...
AcknowledgementValidation
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AcknowledgementValidation: def is_valid(self, bundle, request=None): """Validates that the data to be inputted into the model is valid""" <|body_0|> def _validate_item(self, item): """Validates that a data for an item is complete so that an order can be built""" ...
stack_v2_sparse_classes_36k_train_013730
4,295
no_license
[ { "docstring": "Validates that the data to be inputted into the model is valid", "name": "is_valid", "signature": "def is_valid(self, bundle, request=None)" }, { "docstring": "Validates that a data for an item is complete so that an order can be built", "name": "_validate_item", "signatu...
3
stack_v2_sparse_classes_30k_train_013940
Implement the Python class `AcknowledgementValidation` described below. Class description: Implement the AcknowledgementValidation class. Method signatures and docstrings: - def is_valid(self, bundle, request=None): Validates that the data to be inputted into the model is valid - def _validate_item(self, item): Valid...
Implement the Python class `AcknowledgementValidation` described below. Class description: Implement the AcknowledgementValidation class. Method signatures and docstrings: - def is_valid(self, bundle, request=None): Validates that the data to be inputted into the model is valid - def _validate_item(self, item): Valid...
bef520659a7316c861933f9609b6b9ca7d9f47ac
<|skeleton|> class AcknowledgementValidation: def is_valid(self, bundle, request=None): """Validates that the data to be inputted into the model is valid""" <|body_0|> def _validate_item(self, item): """Validates that a data for an item is complete so that an order can be built""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AcknowledgementValidation: def is_valid(self, bundle, request=None): """Validates that the data to be inputted into the model is valid""" errors = {} if 'delivery_date' in bundle.data: try: dateutil.parser.parse(bundle.data['delivery_date']) exce...
the_stack_v2_python_sparse
invoices/validation.py
charliephairoj/backend
train
0
230f5f17b1dc1a7d637581d25d54f89adaa38d6f
[ "msg = msg.view(size, -1, *msg.shape[1:])\nout = msg.mean(1)\nreturn out", "col, row = es\nx_i, x_o = (x[row], x[col])\nmsg = ops.Concat(-1)((x_i, x_o))\nreturn (msg, col, len(x))" ]
<|body_start_0|> msg = msg.view(size, -1, *msg.shape[1:]) out = msg.mean(1) return out <|end_body_0|> <|body_start_1|> col, row = es x_i, x_o = (x[row], x[col]) msg = ops.Concat(-1)((x_i, x_o)) return (msg, col, len(x)) <|end_body_1|>
Reimplementation of the Message-Passing class to allow more flexibility.
GNN
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GNN: """Reimplementation of the Message-Passing class to allow more flexibility.""" def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: """Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, o...
stack_v2_sparse_classes_36k_train_013731
9,199
permissive
[ { "docstring": "Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, optional only 3 types of aggregation are supported: 'add', 'mean' or 'max'. The default is \"mean\". Returns ------- Tensor aggregated node embeddings.", "name": "aggregate", "s...
2
stack_v2_sparse_classes_30k_train_009762
Implement the Python class `GNN` described below. Class description: Reimplementation of the Message-Passing class to allow more flexibility. Method signatures and docstrings: - def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: Parameters ---------- msg : Tensor [E, ..., dim * 2]. i...
Implement the Python class `GNN` described below. Class description: Reimplementation of the Message-Passing class to allow more flexibility. Method signatures and docstrings: - def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: Parameters ---------- msg : Tensor [E, ..., dim * 2]. i...
eab643f51336dbf7d711f02d27e6516e5affee59
<|skeleton|> class GNN: """Reimplementation of the Message-Passing class to allow more flexibility.""" def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: """Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, o...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GNN: """Reimplementation of the Message-Passing class to allow more flexibility.""" def aggregate(self, msg: Tensor, idx: Tensor, size: int, agg: str='mean') -> Tensor: """Parameters ---------- msg : Tensor [E, ..., dim * 2]. idx : Tensor [E]. size : int number of nodes. agg : str, optional only ...
the_stack_v2_python_sparse
research/gnn/nri-mpm/models/base.py
mindspore-ai/models
train
301
6410d873e885b8c6df3a6876b17a9187d3d2fa19
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')" ]
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
MarkerTrackerServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarkerTrackerServicer: """Missing associated documentation comment in .proto file.""" def TrackMarkers(self, request, context): """Streams MarkerData protobufs.""" <|body_0|> def GetLatestMarkerData(self, request, context): """Retrieves the latest singular instan...
stack_v2_sparse_classes_36k_train_013732
4,316
permissive
[ { "docstring": "Streams MarkerData protobufs.", "name": "TrackMarkers", "signature": "def TrackMarkers(self, request, context)" }, { "docstring": "Retrieves the latest singular instance of MarkerData.", "name": "GetLatestMarkerData", "signature": "def GetLatestMarkerData(self, request, c...
2
null
Implement the Python class `MarkerTrackerServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def TrackMarkers(self, request, context): Streams MarkerData protobufs. - def GetLatestMarkerData(self, request, context): Retrieves the l...
Implement the Python class `MarkerTrackerServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def TrackMarkers(self, request, context): Streams MarkerData protobufs. - def GetLatestMarkerData(self, request, context): Retrieves the l...
583f1de43e91cdd24d632d783872528eb1337480
<|skeleton|> class MarkerTrackerServicer: """Missing associated documentation comment in .proto file.""" def TrackMarkers(self, request, context): """Streams MarkerData protobufs.""" <|body_0|> def GetLatestMarkerData(self, request, context): """Retrieves the latest singular instan...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MarkerTrackerServicer: """Missing associated documentation comment in .proto file.""" def TrackMarkers(self, request, context): """Streams MarkerData protobufs.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImple...
the_stack_v2_python_sparse
phasespace/marker_data_pb2_grpc.py
lauramsmith/fine-tuning-locomotion
train
90
887cf0464b44e4287a33716e02adb5ba5c625a08
[ "BaseDiscretizer.__init__(self, feature_names=feature_names, fill_na=fill_na, return_numeric=return_numeric, return_array=return_array, decimal=decimal)\nself.max_depth = max_depth\nself.kwds = kwds", "if y is None:\n raise Exception('y未提供!')\ndt = sklearn.tree.DecisionTreeClassifier(criterion='entropy', max_d...
<|body_start_0|> BaseDiscretizer.__init__(self, feature_names=feature_names, fill_na=fill_na, return_numeric=return_numeric, return_array=return_array, decimal=decimal) self.max_depth = max_depth self.kwds = kwds <|end_body_0|> <|body_start_1|> if y is None: raise Exception(...
EntropyDiscretizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EntropyDiscretizer: def __init__(self, feature_names=None, max_depth=3, fill_na=-1, return_numeric=True, return_array=False, decimal=2, **kwds): """根据单变量决策树离散化。 feature_names: 需要离散化的变量列表,非负整数或者字符串。 max_depth: 决策树最大深度,用于限制离散化的区间数。 kwds: 其他决策树参数,参考sklearn.tree.DecisionTreeClassifier。""" ...
stack_v2_sparse_classes_36k_train_013733
13,441
no_license
[ { "docstring": "根据单变量决策树离散化。 feature_names: 需要离散化的变量列表,非负整数或者字符串。 max_depth: 决策树最大深度,用于限制离散化的区间数。 kwds: 其他决策树参数,参考sklearn.tree.DecisionTreeClassifier。", "name": "__init__", "signature": "def __init__(self, feature_names=None, max_depth=3, fill_na=-1, return_numeric=True, return_array=False, decimal=2, *...
2
stack_v2_sparse_classes_30k_test_000025
Implement the Python class `EntropyDiscretizer` described below. Class description: Implement the EntropyDiscretizer class. Method signatures and docstrings: - def __init__(self, feature_names=None, max_depth=3, fill_na=-1, return_numeric=True, return_array=False, decimal=2, **kwds): 根据单变量决策树离散化。 feature_names: 需要离散化...
Implement the Python class `EntropyDiscretizer` described below. Class description: Implement the EntropyDiscretizer class. Method signatures and docstrings: - def __init__(self, feature_names=None, max_depth=3, fill_na=-1, return_numeric=True, return_array=False, decimal=2, **kwds): 根据单变量决策树离散化。 feature_names: 需要离散化...
2e5304fe3152509b60003ac41a60c0ed7f5cf6c7
<|skeleton|> class EntropyDiscretizer: def __init__(self, feature_names=None, max_depth=3, fill_na=-1, return_numeric=True, return_array=False, decimal=2, **kwds): """根据单变量决策树离散化。 feature_names: 需要离散化的变量列表,非负整数或者字符串。 max_depth: 决策树最大深度,用于限制离散化的区间数。 kwds: 其他决策树参数,参考sklearn.tree.DecisionTreeClassifier。""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EntropyDiscretizer: def __init__(self, feature_names=None, max_depth=3, fill_na=-1, return_numeric=True, return_array=False, decimal=2, **kwds): """根据单变量决策树离散化。 feature_names: 需要离散化的变量列表,非负整数或者字符串。 max_depth: 决策树最大深度,用于限制离散化的区间数。 kwds: 其他决策树参数,参考sklearn.tree.DecisionTreeClassifier。""" BaseDisc...
the_stack_v2_python_sparse
installment_consume_model/discretize.py
tesla2349/Kaiyuan-Financial-Consumption-Risk-Control-Model
train
0
c0a26c4ee40c5e7a1bc91eb030c4c311b14be04b
[ "if mock_dispatcher is None:\n dispatcher = CheckerDispatcher()\nelse:\n dispatcher = mock_dispatcher\nif mock_increment_error_count is None:\n\n def increment_error_count():\n \"\"\"Increment the total count of reported errors.\"\"\"\n self.error_count += 1\nelse:\n increment_error_count ...
<|body_start_0|> if mock_dispatcher is None: dispatcher = CheckerDispatcher() else: dispatcher = mock_dispatcher if mock_increment_error_count is None: def increment_error_count(): """Increment the total count of reported errors.""" ...
A ProcessorBase for checking style. Attributes: error_count: An integer that is the total number of reported errors for the lifetime of this instance.
StyleProcessor
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StyleProcessor: """A ProcessorBase for checking style. Attributes: error_count: An integer that is the total number of reported errors for the lifetime of this instance.""" def __init__(self, configuration, mock_dispatcher=None, mock_increment_error_count=None, mock_carriage_checker_class=No...
stack_v2_sparse_classes_36k_train_013734
23,775
permissive
[ { "docstring": "Create an instance. Args: configuration: A StyleProcessorConfiguration instance. mock_dispatcher: A mock CheckerDispatcher instance. This parameter is for unit testing. Defaults to a CheckerDispatcher instance. mock_increment_error_count: A mock error-count incrementer. mock_carriage_checker_cla...
3
null
Implement the Python class `StyleProcessor` described below. Class description: A ProcessorBase for checking style. Attributes: error_count: An integer that is the total number of reported errors for the lifetime of this instance. Method signatures and docstrings: - def __init__(self, configuration, mock_dispatcher=N...
Implement the Python class `StyleProcessor` described below. Class description: A ProcessorBase for checking style. Attributes: error_count: An integer that is the total number of reported errors for the lifetime of this instance. Method signatures and docstrings: - def __init__(self, configuration, mock_dispatcher=N...
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
<|skeleton|> class StyleProcessor: """A ProcessorBase for checking style. Attributes: error_count: An integer that is the total number of reported errors for the lifetime of this instance.""" def __init__(self, configuration, mock_dispatcher=None, mock_increment_error_count=None, mock_carriage_checker_class=No...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StyleProcessor: """A ProcessorBase for checking style. Attributes: error_count: An integer that is the total number of reported errors for the lifetime of this instance.""" def __init__(self, configuration, mock_dispatcher=None, mock_increment_error_count=None, mock_carriage_checker_class=None): ...
the_stack_v2_python_sparse
third_party/blink/tools/blinkpy/style/checker.py
chromium/chromium
train
17,408
9db278f0dc7a46f514c0d43a669b72f69524f7a0
[ "self.directions = self._listify_input(input_string.lower())\nself.steps = [0, 0, 0, 0]\nself.facing = 0", "stripped_string = re.sub('\\\\s+', '', input_string.strip())\nsplit_list = stripped_string.split(',')\nreturn [(x[0], int(x[1:])) for x in split_list]", "for direction in self.directions:\n rotate = di...
<|body_start_0|> self.directions = self._listify_input(input_string.lower()) self.steps = [0, 0, 0, 0] self.facing = 0 <|end_body_0|> <|body_start_1|> stripped_string = re.sub('\\s+', '', input_string.strip()) split_list = stripped_string.split(',') return [(x[0], int(x[...
Class for turning walking directions into distance from start.
Walker
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Walker: """Class for turning walking directions into distance from start.""" def __init__(self, input_string): """Initialize.""" <|body_0|> def _listify_input(self, input_string): """Turn a string of inputs into a list.""" <|body_1|> def run(self): ...
stack_v2_sparse_classes_36k_train_013735
1,396
permissive
[ { "docstring": "Initialize.", "name": "__init__", "signature": "def __init__(self, input_string)" }, { "docstring": "Turn a string of inputs into a list.", "name": "_listify_input", "signature": "def _listify_input(self, input_string)" }, { "docstring": "Step through the directio...
3
stack_v2_sparse_classes_30k_train_015916
Implement the Python class `Walker` described below. Class description: Class for turning walking directions into distance from start. Method signatures and docstrings: - def __init__(self, input_string): Initialize. - def _listify_input(self, input_string): Turn a string of inputs into a list. - def run(self): Step ...
Implement the Python class `Walker` described below. Class description: Class for turning walking directions into distance from start. Method signatures and docstrings: - def __init__(self, input_string): Initialize. - def _listify_input(self, input_string): Turn a string of inputs into a list. - def run(self): Step ...
17c729af2af5f1d95ba6ff68771a82ca6d00b05d
<|skeleton|> class Walker: """Class for turning walking directions into distance from start.""" def __init__(self, input_string): """Initialize.""" <|body_0|> def _listify_input(self, input_string): """Turn a string of inputs into a list.""" <|body_1|> def run(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Walker: """Class for turning walking directions into distance from start.""" def __init__(self, input_string): """Initialize.""" self.directions = self._listify_input(input_string.lower()) self.steps = [0, 0, 0, 0] self.facing = 0 def _listify_input(self, input_string...
the_stack_v2_python_sparse
2016/day01_no_time_for_a_taxicab/python/src/part1.py
tlake/advent-of-code
train
0
225b674eb13af0437835abd3138050035b839bd7
[ "item_list = response.xpath('//div[@class=\"sg-col-inner\"]//a[@class=\"a-link-normal a-text-normal\"]/@href').getall()\nfor item in item_list:\n yield response.follow(item, callback=self.parse_item)\nnext_page = response.xpath('//div[@class=\"a-section a-spacing-none a-padding-base\"]//li[@class=\"a-last\"]/a/@...
<|body_start_0|> item_list = response.xpath('//div[@class="sg-col-inner"]//a[@class="a-link-normal a-text-normal"]/@href').getall() for item in item_list: yield response.follow(item, callback=self.parse_item) next_page = response.xpath('//div[@class="a-section a-spacing-none a-paddin...
AmazonSpiderSpider
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AmazonSpiderSpider: def parse(self, response): """Funcion principal para obtener los elemntos de cada página de Amazon""" <|body_0|> def parse_item(self, response): """Funcion que obtiene el nombre y el precio de los productos dentro de cada página""" <|body_...
stack_v2_sparse_classes_36k_train_013736
2,170
permissive
[ { "docstring": "Funcion principal para obtener los elemntos de cada página de Amazon", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "Funcion que obtiene el nombre y el precio de los productos dentro de cada página", "name": "parse_item", "signature": "def p...
2
stack_v2_sparse_classes_30k_train_017240
Implement the Python class `AmazonSpiderSpider` described below. Class description: Implement the AmazonSpiderSpider class. Method signatures and docstrings: - def parse(self, response): Funcion principal para obtener los elemntos de cada página de Amazon - def parse_item(self, response): Funcion que obtiene el nombr...
Implement the Python class `AmazonSpiderSpider` described below. Class description: Implement the AmazonSpiderSpider class. Method signatures and docstrings: - def parse(self, response): Funcion principal para obtener los elemntos de cada página de Amazon - def parse_item(self, response): Funcion que obtiene el nombr...
24e71616dae692e931e95cd3815ca88fa9b8a46a
<|skeleton|> class AmazonSpiderSpider: def parse(self, response): """Funcion principal para obtener los elemntos de cada página de Amazon""" <|body_0|> def parse_item(self, response): """Funcion que obtiene el nombre y el precio de los productos dentro de cada página""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AmazonSpiderSpider: def parse(self, response): """Funcion principal para obtener los elemntos de cada página de Amazon""" item_list = response.xpath('//div[@class="sg-col-inner"]//a[@class="a-link-normal a-text-normal"]/@href').getall() for item in item_list: yield response...
the_stack_v2_python_sparse
Retos/ScraperAmazon/amazon/amazon/spiders/amazon_spider.py
juanpanu-zz/PM_DataScience
train
0
8252e8aa6ad09e841a111211bd7c279ee45a199e
[ "if isinstance(grouped_by_field, str):\n self.grouped_by_field = [grouped_by_field]\nelse:\n self.grouped_by_field = grouped_by_field\nself.grouped_by_field_key = ' + '.join([g + '_' for g in self.grouped_by_field])\nself.date_field = date_field if date_field is None else date_field + '_'\nself.vectors = vect...
<|body_start_0|> if isinstance(grouped_by_field, str): self.grouped_by_field = [grouped_by_field] else: self.grouped_by_field = grouped_by_field self.grouped_by_field_key = ' + '.join([g + '_' for g in self.grouped_by_field]) self.date_field = date_field if date_f...
_Vector Space Model_ is an algebraic model for representing text documents as vectors of index terms. A VSM object allow you to easily explore the multi dimensional Vector Space. It is required that you have already performed the Vectorization.
VSM
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VSM: """_Vector Space Model_ is an algebraic model for representing text documents as vectors of index terms. A VSM object allow you to easily explore the multi dimensional Vector Space. It is required that you have already performed the Vectorization.""" def __init__(self, vectors: Iterable...
stack_v2_sparse_classes_36k_train_013737
5,909
no_license
[ { "docstring": "**\\\\_\\\\_init\\\\_\\\\_**: Creates a new VSM object. Args: vectors (Iterable[dict]): Vector records produced by vectorization. <br/> Each record must have a \"bow\" (Bag of Words) field in which is stored a Dict[str, int]. It has tokens as key and frequencies as values. grouped_by_field (Unio...
4
stack_v2_sparse_classes_30k_train_001273
Implement the Python class `VSM` described below. Class description: _Vector Space Model_ is an algebraic model for representing text documents as vectors of index terms. A VSM object allow you to easily explore the multi dimensional Vector Space. It is required that you have already performed the Vectorization. Meth...
Implement the Python class `VSM` described below. Class description: _Vector Space Model_ is an algebraic model for representing text documents as vectors of index terms. A VSM object allow you to easily explore the multi dimensional Vector Space. It is required that you have already performed the Vectorization. Meth...
adddd0b5cb67a50301ef5ae323c61bde57210cb8
<|skeleton|> class VSM: """_Vector Space Model_ is an algebraic model for representing text documents as vectors of index terms. A VSM object allow you to easily explore the multi dimensional Vector Space. It is required that you have already performed the Vectorization.""" def __init__(self, vectors: Iterable...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VSM: """_Vector Space Model_ is an algebraic model for representing text documents as vectors of index terms. A VSM object allow you to easily explore the multi dimensional Vector Space. It is required that you have already performed the Vectorization.""" def __init__(self, vectors: Iterable[dict], group...
the_stack_v2_python_sparse
venv/lib/python3.9/site-packages/compling/lexicalAnalysis/vectorization/impl/vsm.py
TheKing-coder68/Verselet
train
1
2e561cd0a00a555cb425bf3af86598d3b1d59830
[ "item_dict = {}\nfor attribute_obj in attributes(cls.meta_.entity_cls).values():\n if isinstance(attribute_obj, Reference):\n item_dict[attribute_obj.relation.attribute_name] = attribute_obj.relation.value\n else:\n item_dict[attribute_obj.attribute_name] = getattr(entity, attribute_obj.attribut...
<|body_start_0|> item_dict = {} for attribute_obj in attributes(cls.meta_.entity_cls).values(): if isinstance(attribute_obj, Reference): item_dict[attribute_obj.relation.attribute_name] = attribute_obj.relation.value else: item_dict[attribute_obj.a...
A model for the Elasticsearch index
ElasticsearchModel
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElasticsearchModel: """A model for the Elasticsearch index""" def from_entity(cls, entity) -> 'ElasticsearchModel': """Convert the entity to a Elasticsearch record""" <|body_0|> def to_entity(cls, item: 'ElasticsearchModel'): """Convert the elasticsearch document...
stack_v2_sparse_classes_36k_train_013738
21,821
permissive
[ { "docstring": "Convert the entity to a Elasticsearch record", "name": "from_entity", "signature": "def from_entity(cls, entity) -> 'ElasticsearchModel'" }, { "docstring": "Convert the elasticsearch document to an entity", "name": "to_entity", "signature": "def to_entity(cls, item: 'Elas...
2
stack_v2_sparse_classes_30k_train_015361
Implement the Python class `ElasticsearchModel` described below. Class description: A model for the Elasticsearch index Method signatures and docstrings: - def from_entity(cls, entity) -> 'ElasticsearchModel': Convert the entity to a Elasticsearch record - def to_entity(cls, item: 'ElasticsearchModel'): Convert the e...
Implement the Python class `ElasticsearchModel` described below. Class description: A model for the Elasticsearch index Method signatures and docstrings: - def from_entity(cls, entity) -> 'ElasticsearchModel': Convert the entity to a Elasticsearch record - def to_entity(cls, item: 'ElasticsearchModel'): Convert the e...
60544e7a24757b7968c229343213807b0fcf6bc4
<|skeleton|> class ElasticsearchModel: """A model for the Elasticsearch index""" def from_entity(cls, entity) -> 'ElasticsearchModel': """Convert the entity to a Elasticsearch record""" <|body_0|> def to_entity(cls, item: 'ElasticsearchModel'): """Convert the elasticsearch document...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ElasticsearchModel: """A model for the Elasticsearch index""" def from_entity(cls, entity) -> 'ElasticsearchModel': """Convert the entity to a Elasticsearch record""" item_dict = {} for attribute_obj in attributes(cls.meta_.entity_cls).values(): if isinstance(attribute...
the_stack_v2_python_sparse
src/protean/adapters/repository/elasticsearch.py
proteanhq/protean
train
9
3ce2495efc5d5b97ba92d2eca3e1b8c5eee3f9db
[ "super(DpkgLocal, self).__init__()\nself._release = release\nself._arch = arch\nself._executor = executor", "root = self._executor.root_filesystem_directory()\ndirectory.safe_makedirs(os.path.join(root, 'var', 'cache', 'apt', 'archives', 'partial'))\ndirectory.safe_makedirs(os.path.join(root, 'var', 'lib', 'apt',...
<|body_start_0|> super(DpkgLocal, self).__init__() self._release = release self._arch = arch self._executor = executor <|end_body_0|> <|body_start_1|> root = self._executor.root_filesystem_directory() directory.safe_makedirs(os.path.join(root, 'var', 'cache', 'apt', 'arc...
Debian packaging system, installing packages to local directory.
DpkgLocal
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DpkgLocal: """Debian packaging system, installing packages to local directory.""" def __init__(self, release, arch, executor): """Initialize this PackageSystem.""" <|body_0|> def _initialize_directories(self): """Ensure that all APT and Dpkg directories are initi...
stack_v2_sparse_classes_36k_train_013739
19,882
permissive
[ { "docstring": "Initialize this PackageSystem.", "name": "__init__", "signature": "def __init__(self, release, arch, executor)" }, { "docstring": "Ensure that all APT and Dpkg directories are initialized.", "name": "_initialize_directories", "signature": "def _initialize_directories(self...
4
stack_v2_sparse_classes_30k_train_016481
Implement the Python class `DpkgLocal` described below. Class description: Debian packaging system, installing packages to local directory. Method signatures and docstrings: - def __init__(self, release, arch, executor): Initialize this PackageSystem. - def _initialize_directories(self): Ensure that all APT and Dpkg ...
Implement the Python class `DpkgLocal` described below. Class description: Debian packaging system, installing packages to local directory. Method signatures and docstrings: - def __init__(self, release, arch, executor): Initialize this PackageSystem. - def _initialize_directories(self): Ensure that all APT and Dpkg ...
bb31302cfc48f55da56c12ab27b88644380209b9
<|skeleton|> class DpkgLocal: """Debian packaging system, installing packages to local directory.""" def __init__(self, release, arch, executor): """Initialize this PackageSystem.""" <|body_0|> def _initialize_directories(self): """Ensure that all APT and Dpkg directories are initi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DpkgLocal: """Debian packaging system, installing packages to local directory.""" def __init__(self, release, arch, executor): """Initialize this PackageSystem.""" super(DpkgLocal, self).__init__() self._release = release self._arch = arch self._executor = executor...
the_stack_v2_python_sparse
psqtraviscontainer/package_system.py
violethaze74/polysquare-travis-container
train
0
688b3f42d97abd4aa6bce3ae787562f5ba51589a
[ "self._feature_store_id = feature_store_id\nself._feature_group_id = feature_group_id\nself._variable_api = VariableApi()", "_client = client.get_instance()\npath_params = ['project', _client._project_id, 'featurestores', self._feature_store_id, 'featuregroups', self._feature_group_id, 'expectationsuite']\nmajor,...
<|body_start_0|> self._feature_store_id = feature_store_id self._feature_group_id = feature_group_id self._variable_api = VariableApi() <|end_body_0|> <|body_start_1|> _client = client.get_instance() path_params = ['project', _client._project_id, 'featurestores', self._feature_s...
ExpectationSuiteApi
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExpectationSuiteApi: def __init__(self, feature_store_id: int, feature_group_id: int): """Expectation Suite endpoints for the Feature Group resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id of the respective Feat...
stack_v2_sparse_classes_36k_train_013740
6,356
permissive
[ { "docstring": "Expectation Suite endpoints for the Feature Group resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id of the respective Feature Group :type feature_group_id: int", "name": "__init__", "signature": "def __init__(sel...
6
stack_v2_sparse_classes_30k_train_021397
Implement the Python class `ExpectationSuiteApi` described below. Class description: Implement the ExpectationSuiteApi class. Method signatures and docstrings: - def __init__(self, feature_store_id: int, feature_group_id: int): Expectation Suite endpoints for the Feature Group resource. :param feature_store_id: id of...
Implement the Python class `ExpectationSuiteApi` described below. Class description: Implement the ExpectationSuiteApi class. Method signatures and docstrings: - def __init__(self, feature_store_id: int, feature_group_id: int): Expectation Suite endpoints for the Feature Group resource. :param feature_store_id: id of...
3e67b26271e43b1ce38bd1e872bfb4c9212bb372
<|skeleton|> class ExpectationSuiteApi: def __init__(self, feature_store_id: int, feature_group_id: int): """Expectation Suite endpoints for the Feature Group resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id of the respective Feat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExpectationSuiteApi: def __init__(self, feature_store_id: int, feature_group_id: int): """Expectation Suite endpoints for the Feature Group resource. :param feature_store_id: id of the respective Feature Store :type feature_store_id: int :param feature_group_id: id of the respective Feature Group :typ...
the_stack_v2_python_sparse
python/hsfs/core/expectation_suite_api.py
logicalclocks/feature-store-api
train
59
44cbef43a60810286d2b96efeb3d660c13200f68
[ "count = 0\nfor x in data:\n if count == 0:\n if x >> 5 == 6:\n count = 1\n elif x >> 4 == 14:\n count = 2\n elif x >> 3 == 30:\n count = 3\n elif x >> 7 == 1:\n return False\n else:\n if x >> 6 != 2:\n return False\n ...
<|body_start_0|> count = 0 for x in data: if count == 0: if x >> 5 == 6: count = 1 elif x >> 4 == 14: count = 2 elif x >> 3 == 30: count = 3 elif x >> 7 == 1: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def validUtf8(self, data): """:type data: List[int] :rtype: bool""" <|body_0|> def validUtf8_2(self, data): """:type data: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|> <|body_start_0|> count = 0 for x in data: ...
stack_v2_sparse_classes_36k_train_013741
4,568
no_license
[ { "docstring": ":type data: List[int] :rtype: bool", "name": "validUtf8", "signature": "def validUtf8(self, data)" }, { "docstring": ":type data: List[int] :rtype: bool", "name": "validUtf8_2", "signature": "def validUtf8_2(self, data)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validUtf8(self, data): :type data: List[int] :rtype: bool - def validUtf8_2(self, data): :type data: List[int] :rtype: bool
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validUtf8(self, data): :type data: List[int] :rtype: bool - def validUtf8_2(self, data): :type data: List[int] :rtype: bool <|skeleton|> class Solution: def validUtf8(s...
635af6e22aa8eef8e7920a585d43a45a891a8157
<|skeleton|> class Solution: def validUtf8(self, data): """:type data: List[int] :rtype: bool""" <|body_0|> def validUtf8_2(self, data): """:type data: List[int] :rtype: bool""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def validUtf8(self, data): """:type data: List[int] :rtype: bool""" count = 0 for x in data: if count == 0: if x >> 5 == 6: count = 1 elif x >> 4 == 14: count = 2 elif x >> 3 =...
the_stack_v2_python_sparse
code393UTF-8Validation.py
cybelewang/leetcode-python
train
0
fcc40d881c57e9b3641e318243dfd2a8ec7ca38a
[ "k = 0\nfor n in range(L, R + 1):\n result = bin(n).count('1')\n if is_prime(result):\n k = k + 1\nreturn k", "primes = {2, 3, 5, 7, 11, 13, 17, 19}\nres = 0\nfor num in range(L, R + 1):\n if bin(num).count('1') in primes:\n res += 1\nreturn res" ]
<|body_start_0|> k = 0 for n in range(L, R + 1): result = bin(n).count('1') if is_prime(result): k = k + 1 return k <|end_body_0|> <|body_start_1|> primes = {2, 3, 5, 7, 11, 13, 17, 19} res = 0 for num in range(L, R + 1): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int""" <|body_0|> def static_countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> k = 0 for ...
stack_v2_sparse_classes_36k_train_013742
1,993
no_license
[ { "docstring": ":type L: int :type R: int :rtype: int", "name": "countPrimeSetBits", "signature": "def countPrimeSetBits(self, L, R)" }, { "docstring": ":type L: int :type R: int :rtype: int", "name": "static_countPrimeSetBits", "signature": "def static_countPrimeSetBits(self, L, R)" }...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int - def static_countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int - def static_countPrimeSetBits(self, L, R): :type L: int :type R: int :rtype: int <|skeleton|> class Sol...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int""" <|body_0|> def static_countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def countPrimeSetBits(self, L, R): """:type L: int :type R: int :rtype: int""" k = 0 for n in range(L, R + 1): result = bin(n).count('1') if is_prime(result): k = k + 1 return k def static_countPrimeSetBits(self, L, R): ...
the_stack_v2_python_sparse
bit-manipulation/762_Prime_Number_of_Set_Bits_in_Binary_Representation.py
vsdrun/lc_public
train
6
a637db1286729a45de9111224e0b60c68b5205ae
[ "super().__init__(self.PROBLEM_NAME)\nself.root_node = root_node\nself.max_sum = -sys.maxsize - 1", "print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nself.find_max(self.root_node)\nreturn self.max_sum", "if node is None:\n return 0\nleft_max = self.find_max(node.left)\nright_max = self.find_max(nod...
<|body_start_0|> super().__init__(self.PROBLEM_NAME) self.root_node = root_node self.max_sum = -sys.maxsize - 1 <|end_body_0|> <|body_start_1|> print('Solving {} problem ...'.format(self.PROBLEM_NAME)) self.find_max(self.root_node) return self.max_sum <|end_body_1|> <|b...
Binary Tree Max Sum Path
BinaryTreeMaxSumPath
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BinaryTreeMaxSumPath: """Binary Tree Max Sum Path""" def __init__(self, root_node): """Binary Tree Max Sum Path Args: root_node: node of the tree Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the problem Note: For the bottom up approach. At e...
stack_v2_sparse_classes_36k_train_013743
2,462
no_license
[ { "docstring": "Binary Tree Max Sum Path Args: root_node: node of the tree Returns: None Raises: None", "name": "__init__", "signature": "def __init__(self, root_node)" }, { "docstring": "Solve the problem Note: For the bottom up approach. At each node, the potential maximum path could be one of...
3
null
Implement the Python class `BinaryTreeMaxSumPath` described below. Class description: Binary Tree Max Sum Path Method signatures and docstrings: - def __init__(self, root_node): Binary Tree Max Sum Path Args: root_node: node of the tree Returns: None Raises: None - def solve(self): Solve the problem Note: For the bot...
Implement the Python class `BinaryTreeMaxSumPath` described below. Class description: Binary Tree Max Sum Path Method signatures and docstrings: - def __init__(self, root_node): Binary Tree Max Sum Path Args: root_node: node of the tree Returns: None Raises: None - def solve(self): Solve the problem Note: For the bot...
11f4d25cb211740514c119a60962d075a0817abd
<|skeleton|> class BinaryTreeMaxSumPath: """Binary Tree Max Sum Path""" def __init__(self, root_node): """Binary Tree Max Sum Path Args: root_node: node of the tree Returns: None Raises: None""" <|body_0|> def solve(self): """Solve the problem Note: For the bottom up approach. At e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BinaryTreeMaxSumPath: """Binary Tree Max Sum Path""" def __init__(self, root_node): """Binary Tree Max Sum Path Args: root_node: node of the tree Returns: None Raises: None""" super().__init__(self.PROBLEM_NAME) self.root_node = root_node self.max_sum = -sys.maxsize - 1 ...
the_stack_v2_python_sparse
python/problems/binary_tree/binary_tree_max_sum_path.py
santhosh-kumar/AlgorithmsAndDataStructures
train
2
a5428b1a799611dac61e81dbc7ee2f8a16a80f57
[ "if str2bool(value):\n return queryset.filter(allocated__gte=F('quantity'))\nelse:\n return queryset.filter(allocated__lt=F('quantity'))", "flt = Q(quantity__lte=F('total_available_stock') + F('allocated'))\nif str2bool(value):\n return queryset.filter(flt)\nelse:\n return queryset.exclude(flt)" ]
<|body_start_0|> if str2bool(value): return queryset.filter(allocated__gte=F('quantity')) else: return queryset.filter(allocated__lt=F('quantity')) <|end_body_0|> <|body_start_1|> flt = Q(quantity__lte=F('total_available_stock') + F('allocated')) if str2bool(valu...
Custom filterset for the BuildLine API endpoint.
BuildLineFilter
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuildLineFilter: """Custom filterset for the BuildLine API endpoint.""" def filter_allocated(self, queryset, name, value): """Filter by whether each BuildLine is fully allocated""" <|body_0|> def filter_available(self, queryset, name, value): """Filter by whether...
stack_v2_sparse_classes_36k_train_013744
20,912
permissive
[ { "docstring": "Filter by whether each BuildLine is fully allocated", "name": "filter_allocated", "signature": "def filter_allocated(self, queryset, name, value)" }, { "docstring": "Filter by whether there is sufficient stock available for each BuildLine: To determine this, we need to know: - Th...
2
stack_v2_sparse_classes_30k_train_011374
Implement the Python class `BuildLineFilter` described below. Class description: Custom filterset for the BuildLine API endpoint. Method signatures and docstrings: - def filter_allocated(self, queryset, name, value): Filter by whether each BuildLine is fully allocated - def filter_available(self, queryset, name, valu...
Implement the Python class `BuildLineFilter` described below. Class description: Custom filterset for the BuildLine API endpoint. Method signatures and docstrings: - def filter_allocated(self, queryset, name, value): Filter by whether each BuildLine is fully allocated - def filter_available(self, queryset, name, valu...
e88a8e99a5f0b201c67a95cba097c729f090d5e2
<|skeleton|> class BuildLineFilter: """Custom filterset for the BuildLine API endpoint.""" def filter_allocated(self, queryset, name, value): """Filter by whether each BuildLine is fully allocated""" <|body_0|> def filter_available(self, queryset, name, value): """Filter by whether...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BuildLineFilter: """Custom filterset for the BuildLine API endpoint.""" def filter_allocated(self, queryset, name, value): """Filter by whether each BuildLine is fully allocated""" if str2bool(value): return queryset.filter(allocated__gte=F('quantity')) else: ...
the_stack_v2_python_sparse
InvenTree/build/api.py
inventree/InvenTree
train
3,077
3bc759d84927e1675421058f327f7f1437a1a626
[ "self.prot_attr = prot_attr\nself.estimator = estimator\nself.constraints = constraints\nself.eps = eps\nself.max_iter = max_iter\nself.nu = nu\nself.eta0 = eta0\nself.run_linprog_step = run_linprog_step\nself.drop_prot_attr = drop_prot_attr", "self.estimator_ = clone(self.estimator)\nmoments = {'DemographicParit...
<|body_start_0|> self.prot_attr = prot_attr self.estimator = estimator self.constraints = constraints self.eps = eps self.max_iter = max_iter self.nu = nu self.eta0 = eta0 self.run_linprog_step = run_linprog_step self.drop_prot_attr = drop_prot_att...
Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest empirical error subject to fair classification constraints ...
ExponentiatedGradientReduction
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExponentiatedGradientReduction: """Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest e...
stack_v2_sparse_classes_36k_train_013745
6,304
permissive
[ { "docstring": "Args: prot_attr: String or array-like column indices or column names of protected attributes. estimator: An estimator implementing methods ``fit(X, y, sample_weight)`` and ``predict(X)``, where ``X`` is the matrix of features, ``y`` is the vector of labels, and ``sample_weight`` is a vector of w...
4
stack_v2_sparse_classes_30k_train_000138
Implement the Python class `ExponentiatedGradientReduction` described below. Class description: Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a ...
Implement the Python class `ExponentiatedGradientReduction` described below. Class description: Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a ...
6f9972e4a7dbca2402f29b86ea67889143dbeb3e
<|skeleton|> class ExponentiatedGradientReduction: """Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest e...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExponentiatedGradientReduction: """Exponentiated gradient reduction for fair classification. Exponentiated gradient reduction is an in-processing technique that reduces fair classification to a sequence of cost-sensitive classification problems, returning a randomized classifier with the lowest empirical erro...
the_stack_v2_python_sparse
aif360/sklearn/inprocessing/exponentiated_gradient_reduction.py
Trusted-AI/AIF360
train
1,157
706e065d5a7f1fe0b5b92beff9432613340340a9
[ "scheduler_name = 'api_auto_create_schedulers_once' + str(random.randint(0, 99999))\nflow_table = load_workbook(abs_dir('flow_dataset_info.xlsx'))\ninfo_sheet = flow_table.get_sheet_by_name('flow_info')\nflow_id = info_sheet.cell(row=2, column=2).value\nflow_name = info_sheet.cell(row=2, column=3).value\ndata = {'n...
<|body_start_0|> scheduler_name = 'api_auto_create_schedulers_once' + str(random.randint(0, 99999)) flow_table = load_workbook(abs_dir('flow_dataset_info.xlsx')) info_sheet = flow_table.get_sheet_by_name('flow_info') flow_id = info_sheet.cell(row=2, column=2).value flow_name = in...
用来测试创建schedulers
CreateSchedulers
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateSchedulers: """用来测试创建schedulers""" def test_case01(self): """创建schedulers,单次执行""" <|body_0|> def test_case02(self): """创建schedulers,周期执行""" <|body_1|> <|end_skeleton|> <|body_start_0|> scheduler_name = 'api_auto_create_schedulers_once' + s...
stack_v2_sparse_classes_36k_train_013746
15,511
no_license
[ { "docstring": "创建schedulers,单次执行", "name": "test_case01", "signature": "def test_case01(self)" }, { "docstring": "创建schedulers,周期执行", "name": "test_case02", "signature": "def test_case02(self)" } ]
2
stack_v2_sparse_classes_30k_train_017015
Implement the Python class `CreateSchedulers` described below. Class description: 用来测试创建schedulers Method signatures and docstrings: - def test_case01(self): 创建schedulers,单次执行 - def test_case02(self): 创建schedulers,周期执行
Implement the Python class `CreateSchedulers` described below. Class description: 用来测试创建schedulers Method signatures and docstrings: - def test_case01(self): 创建schedulers,单次执行 - def test_case02(self): 创建schedulers,周期执行 <|skeleton|> class CreateSchedulers: """用来测试创建schedulers""" def test_case01(self): ...
fc41513af3063169ff1b17d6f01f7074057ceb1f
<|skeleton|> class CreateSchedulers: """用来测试创建schedulers""" def test_case01(self): """创建schedulers,单次执行""" <|body_0|> def test_case02(self): """创建schedulers,周期执行""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateSchedulers: """用来测试创建schedulers""" def test_case01(self): """创建schedulers,单次执行""" scheduler_name = 'api_auto_create_schedulers_once' + str(random.randint(0, 99999)) flow_table = load_workbook(abs_dir('flow_dataset_info.xlsx')) info_sheet = flow_table.get_sheet_by_nam...
the_stack_v2_python_sparse
singl_api/api_test_cases/cases_for_schedulers_api.py
bingjiegu/For_API
train
0
69c878a4bf08bf15956479bb5b81a26be2055037
[ "self.symbol = symbol\nself.unit = unit\nself.count = count\nself.period = period\nif json is None:\n self.json = self.get_json()\nelse:\n self.json = json", "today = dt.now()\nDIRECTION = 'last'\nepochs = date.get_end_start_epochs(today.year, today.month, today.day, DIRECTION, self.unit, self.count)\nretur...
<|body_start_0|> self.symbol = symbol self.unit = unit self.count = count self.period = period if json is None: self.json = self.get_json() else: self.json = json <|end_body_0|> <|body_start_1|> today = dt.now() DIRECTION = 'last' ...
Evaluates TA indicators of a market Gets data from a market and then calculates technical analysis features. It also prepares this data to be fed into machine learning interfaces by creating a pandas DataFrame, and generating training/test sets for features (x-axis) and the target market trend (y-axis). Attributes: sym...
Market
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Market: """Evaluates TA indicators of a market Gets data from a market and then calculates technical analysis features. It also prepares this data to be fed into machine learning interfaces by creating a pandas DataFrame, and generating training/test sets for features (x-axis) and the target mark...
stack_v2_sparse_classes_36k_train_013747
8,178
permissive
[ { "docstring": "Inits market class of symbol with data going back count units", "name": "__init__", "signature": "def __init__(self, json=None, symbol='USDT_BTC', unit='month', count=6, period=86400)" }, { "docstring": "Gets market chart data from today to a previous date", "name": "get_json...
4
null
Implement the Python class `Market` described below. Class description: Evaluates TA indicators of a market Gets data from a market and then calculates technical analysis features. It also prepares this data to be fed into machine learning interfaces by creating a pandas DataFrame, and generating training/test sets fo...
Implement the Python class `Market` described below. Class description: Evaluates TA indicators of a market Gets data from a market and then calculates technical analysis features. It also prepares this data to be fed into machine learning interfaces by creating a pandas DataFrame, and generating training/test sets fo...
945f0a83d6b94282c547bb6f4805f3381ad9c16a
<|skeleton|> class Market: """Evaluates TA indicators of a market Gets data from a market and then calculates technical analysis features. It also prepares this data to be fed into machine learning interfaces by creating a pandas DataFrame, and generating training/test sets for features (x-axis) and the target mark...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Market: """Evaluates TA indicators of a market Gets data from a market and then calculates technical analysis features. It also prepares this data to be fed into machine learning interfaces by creating a pandas DataFrame, and generating training/test sets for features (x-axis) and the target market trend (y-a...
the_stack_v2_python_sparse
Speculator/speculator/market.py
webclinic017/ml_monorepo
train
0
68fec3872a935295cfeb49238214f115919b0688
[ "sc.logger.info('video详情页初始状态检查开始')\nfun_name = 'test_video_origin'\nsc.logger.info('点击个人中心主按钮')\nsc.first_step(self.p_btn)\nsc.logger.info('点击第一个视频标题')\nel_video_til = 'com.quvideo.xiaoying:id/xiaoying_com_video_card_title'\nWebDriverWait(sc.driver, 10, 1).until(lambda el: el.find_element_by_id(el_video_til)).clic...
<|body_start_0|> sc.logger.info('video详情页初始状态检查开始') fun_name = 'test_video_origin' sc.logger.info('点击个人中心主按钮') sc.first_step(self.p_btn) sc.logger.info('点击第一个视频标题') el_video_til = 'com.quvideo.xiaoying:id/xiaoying_com_video_card_title' WebDriverWait(sc.driver, 10,...
个人视频详情页的测试类,分步截图.
TestUserVideos
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestUserVideos: """个人视频详情页的测试类,分步截图.""" def test_video_origin(self): """video详情页面的初始状态.""" <|body_0|> def test_video_play(self): """测试视频的播放.""" <|body_1|> def test_video_like(self): """测试视频的点赞功能.""" <|body_2|> def test_video_down...
stack_v2_sparse_classes_36k_train_013748
4,511
no_license
[ { "docstring": "video详情页面的初始状态.", "name": "test_video_origin", "signature": "def test_video_origin(self)" }, { "docstring": "测试视频的播放.", "name": "test_video_play", "signature": "def test_video_play(self)" }, { "docstring": "测试视频的点赞功能.", "name": "test_video_like", "signatur...
5
null
Implement the Python class `TestUserVideos` described below. Class description: 个人视频详情页的测试类,分步截图. Method signatures and docstrings: - def test_video_origin(self): video详情页面的初始状态. - def test_video_play(self): 测试视频的播放. - def test_video_like(self): 测试视频的点赞功能. - def test_video_download(self): 测试视频的下载功能. - def test_video_...
Implement the Python class `TestUserVideos` described below. Class description: 个人视频详情页的测试类,分步截图. Method signatures and docstrings: - def test_video_origin(self): video详情页面的初始状态. - def test_video_play(self): 测试视频的播放. - def test_video_like(self): 测试视频的点赞功能. - def test_video_download(self): 测试视频的下载功能. - def test_video_...
0003b68fc8e26a96ee1661c1eb1f26f96810e909
<|skeleton|> class TestUserVideos: """个人视频详情页的测试类,分步截图.""" def test_video_origin(self): """video详情页面的初始状态.""" <|body_0|> def test_video_play(self): """测试视频的播放.""" <|body_1|> def test_video_like(self): """测试视频的点赞功能.""" <|body_2|> def test_video_down...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestUserVideos: """个人视频详情页的测试类,分步截图.""" def test_video_origin(self): """video详情页面的初始状态.""" sc.logger.info('video详情页初始状态检查开始') fun_name = 'test_video_origin' sc.logger.info('点击个人中心主按钮') sc.first_step(self.p_btn) sc.logger.info('点击第一个视频标题') el_video_t...
the_stack_v2_python_sparse
iOS/VivaVideo/test_community/test_planet/test_videos.py
Lemonzhulixin/UItest
train
5
8e6a0b28979fb257c95520192126fd5b03d53b6c
[ "if self.filters:\n category_filter = self.filters.get(str(field.category.id), None)\n if category_filter:\n field_filter = category_filter.pop(field.key, None)\n if field_filter:\n self.save()", "self.where_clause = None\nif self.filters is not None:\n queries = []\n for key ...
<|body_start_0|> if self.filters: category_filter = self.filters.get(str(field.category.id), None) if category_filter: field_filter = category_filter.pop(field.key, None) if field_filter: self.save() <|end_body_0|> <|body_start_1|> ...
A mixin for filter.
FilterMixin
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FilterMixin: """A mixin for filter.""" def remove_filter_field(self, field): """Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.""" <|body_0|> def save(self, *args, **kwargs): """Over...
stack_v2_sparse_classes_36k_train_013749
1,197
permissive
[ { "docstring": "Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.", "name": "remove_filter_field", "signature": "def remove_filter_field(self, field)" }, { "docstring": "Overwrite `save` to implement integrity ensuran...
2
stack_v2_sparse_classes_30k_train_016655
Implement the Python class `FilterMixin` described below. Class description: A mixin for filter. Method signatures and docstrings: - def remove_filter_field(self, field): Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category. - def save(self, *...
Implement the Python class `FilterMixin` described below. Class description: A mixin for filter. Method signatures and docstrings: - def remove_filter_field(self, field): Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category. - def save(self, *...
16d31b5207de9f699fc01054baad1fe65ad1c3ca
<|skeleton|> class FilterMixin: """A mixin for filter.""" def remove_filter_field(self, field): """Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.""" <|body_0|> def save(self, *args, **kwargs): """Over...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FilterMixin: """A mixin for filter.""" def remove_filter_field(self, field): """Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.""" if self.filters: category_filter = self.filters.get(str(field.cat...
the_stack_v2_python_sparse
geokey/core/mixins.py
NeolithEra/geokey
train
0
dee1dddc7a9e65d8b49a2d1e7f8eea3946aae35b
[ "mime_message = _parse_mime_message(mime_message)\nsuper(InboundEmailMessage, self).update_from_mime_message(mime_message)\nfor property_, header in six.iteritems(InboundEmailMessage.__HEADER_PROPERTIES):\n value = mime_message[header]\n if value:\n setattr(self, property_, value)", "if content_type ...
<|body_start_0|> mime_message = _parse_mime_message(mime_message) super(InboundEmailMessage, self).update_from_mime_message(mime_message) for property_, header in six.iteritems(InboundEmailMessage.__HEADER_PROPERTIES): value = mime_message[header] if value: ...
Receives a parsed email as it is recevied from an external source. This class makes use of a `date` field and can store any number of additional bodies. These additional attributes make the email more flexible as required for incoming mail, where the developer has less control over the content. Example: # Read mail mes...
InboundEmailMessage
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InboundEmailMessage: """Receives a parsed email as it is recevied from an external source. This class makes use of a `date` field and can store any number of additional bodies. These additional attributes make the email more flexible as required for incoming mail, where the developer has less con...
stack_v2_sparse_classes_36k_train_013750
48,523
permissive
[ { "docstring": "Updates the values of a MIME message. This function copies over date values. Args: mime_message: The `email.Message` instance from which you want to copy information.", "name": "update_from_mime_message", "signature": "def update_from_mime_message(self, mime_message)" }, { "docst...
4
stack_v2_sparse_classes_30k_train_006866
Implement the Python class `InboundEmailMessage` described below. Class description: Receives a parsed email as it is recevied from an external source. This class makes use of a `date` field and can store any number of additional bodies. These additional attributes make the email more flexible as required for incoming...
Implement the Python class `InboundEmailMessage` described below. Class description: Receives a parsed email as it is recevied from an external source. This class makes use of a `date` field and can store any number of additional bodies. These additional attributes make the email more flexible as required for incoming...
8a5abedfe99b27a4dcb31fd47d3ba7b62fd0e47c
<|skeleton|> class InboundEmailMessage: """Receives a parsed email as it is recevied from an external source. This class makes use of a `date` field and can store any number of additional bodies. These additional attributes make the email more flexible as required for incoming mail, where the developer has less con...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InboundEmailMessage: """Receives a parsed email as it is recevied from an external source. This class makes use of a `date` field and can store any number of additional bodies. These additional attributes make the email more flexible as required for incoming mail, where the developer has less control over the...
the_stack_v2_python_sparse
src/google/appengine/api/mail.py
asriniva/appengine-python-standard
train
0
4c8debeb45a3d43a277237dca93b03181be081aa
[ "self.label_names = self.unpickle('cifar-10-batches-py/batches.meta', encoding='utf-8')['label_names']\nself.training_data = self.unpickle('cifar-10-batches-py/data_batch_1')\nself.training_images = self.training_data[b'data']\nself.training_labels = self.training_data[b'labels']\nself.shape_images()\nself.training...
<|body_start_0|> self.label_names = self.unpickle('cifar-10-batches-py/batches.meta', encoding='utf-8')['label_names'] self.training_data = self.unpickle('cifar-10-batches-py/data_batch_1') self.training_images = self.training_data[b'data'] self.training_labels = self.training_data[b'lab...
A convolutional neural network to be used to classify images from the CIFAR-10 dataset.
ConvolutionalNetwork
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConvolutionalNetwork: """A convolutional neural network to be used to classify images from the CIFAR-10 dataset.""" def __init__(self): """self.training_images -- a 10000x3072 numpy array of uint8s. Each a row of the array stores a 32x32 colour image. The first 1024 entries contain t...
stack_v2_sparse_classes_36k_train_013751
4,064
no_license
[ { "docstring": "self.training_images -- a 10000x3072 numpy array of uint8s. Each a row of the array stores a 32x32 colour image. The first 1024 entries contain the red channel values, the next 1024 the green, and the final 1024 the blue. The image is stored in row-major order, so that the first 32 entries of th...
5
null
Implement the Python class `ConvolutionalNetwork` described below. Class description: A convolutional neural network to be used to classify images from the CIFAR-10 dataset. Method signatures and docstrings: - def __init__(self): self.training_images -- a 10000x3072 numpy array of uint8s. Each a row of the array stor...
Implement the Python class `ConvolutionalNetwork` described below. Class description: A convolutional neural network to be used to classify images from the CIFAR-10 dataset. Method signatures and docstrings: - def __init__(self): self.training_images -- a 10000x3072 numpy array of uint8s. Each a row of the array stor...
415dcfaec589b0b14c5b9864872c912f3851b383
<|skeleton|> class ConvolutionalNetwork: """A convolutional neural network to be used to classify images from the CIFAR-10 dataset.""" def __init__(self): """self.training_images -- a 10000x3072 numpy array of uint8s. Each a row of the array stores a 32x32 colour image. The first 1024 entries contain t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConvolutionalNetwork: """A convolutional neural network to be used to classify images from the CIFAR-10 dataset.""" def __init__(self): """self.training_images -- a 10000x3072 numpy array of uint8s. Each a row of the array stores a 32x32 colour image. The first 1024 entries contain the red channe...
the_stack_v2_python_sparse
SFData/StackOverflow/s56912176_original.py
tensfa/tensfa
train
2
07f6a1f5dbd7c7a812d035b7595b0c6cce15aa0c
[ "self.transfer_enabled = transfer_enabled\nself.transfer_interval = transfer_interval\nself.transfer_day = transfer_day", "if dictionary is None:\n return None\ntransfer_enabled = dictionary.get('transfer_enabled')\ntransfer_interval = dictionary.get('transfer_interval')\ntransfer_day = dictionary.get('transfe...
<|body_start_0|> self.transfer_enabled = transfer_enabled self.transfer_interval = transfer_interval self.transfer_day = transfer_day <|end_body_0|> <|body_start_1|> if dictionary is None: return None transfer_enabled = dictionary.get('transfer_enabled') tran...
Implementation of the 'CreateTransferSettingsRequest' model. Informações de transferência do recebedor Attributes: transfer_enabled (bool): TODO: type description here. transfer_interval (string): TODO: type description here. transfer_day (int): TODO: type description here.
CreateTransferSettingsRequest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateTransferSettingsRequest: """Implementation of the 'CreateTransferSettingsRequest' model. Informações de transferência do recebedor Attributes: transfer_enabled (bool): TODO: type description here. transfer_interval (string): TODO: type description here. transfer_day (int): TODO: type descri...
stack_v2_sparse_classes_36k_train_013752
2,111
permissive
[ { "docstring": "Constructor for the CreateTransferSettingsRequest class", "name": "__init__", "signature": "def __init__(self, transfer_enabled=None, transfer_interval=None, transfer_day=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): ...
2
null
Implement the Python class `CreateTransferSettingsRequest` described below. Class description: Implementation of the 'CreateTransferSettingsRequest' model. Informações de transferência do recebedor Attributes: transfer_enabled (bool): TODO: type description here. transfer_interval (string): TODO: type description here...
Implement the Python class `CreateTransferSettingsRequest` described below. Class description: Implementation of the 'CreateTransferSettingsRequest' model. Informações de transferência do recebedor Attributes: transfer_enabled (bool): TODO: type description here. transfer_interval (string): TODO: type description here...
95c80c35dd57bb2a238faeaf30d1e3b4544d2298
<|skeleton|> class CreateTransferSettingsRequest: """Implementation of the 'CreateTransferSettingsRequest' model. Informações de transferência do recebedor Attributes: transfer_enabled (bool): TODO: type description here. transfer_interval (string): TODO: type description here. transfer_day (int): TODO: type descri...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CreateTransferSettingsRequest: """Implementation of the 'CreateTransferSettingsRequest' model. Informações de transferência do recebedor Attributes: transfer_enabled (bool): TODO: type description here. transfer_interval (string): TODO: type description here. transfer_day (int): TODO: type description here.""...
the_stack_v2_python_sparse
mundiapi/models/create_transfer_settings_request.py
mundipagg/MundiAPI-PYTHON
train
10
136cce504e223384d6dfd11490540c14e7fb909a
[ "texts = [u'Superscript: <sup>italics</sup>', u'Subscript: <sub>italics</sub>', u'Links: <a href=\"http://www.uanwe.org/\" target=\"_blank\">UNAWE</a>', u'Italics: <em>italics</em>', u'Paragraph: <p>italics</p>']\nfor text in texts:\n self.assertEqual(text, bleach_clean(text))", "text = u'Table: <table><tr><th...
<|body_start_0|> texts = [u'Superscript: <sup>italics</sup>', u'Subscript: <sub>italics</sub>', u'Links: <a href="http://www.uanwe.org/" target="_blank">UNAWE</a>', u'Italics: <em>italics</em>', u'Paragraph: <p>italics</p>'] for text in texts: self.assertEqual(text, bleach_clean(text)) <|end...
BleachTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BleachTest: def test_white_listed(self): """Tests that white listed html tags are not removed by bleach""" <|body_0|> def test_table(self): """Tests that tables are correctly bleached""" <|body_1|> def test_line_breaks(self): """Tests that tables...
stack_v2_sparse_classes_36k_train_013753
1,556
permissive
[ { "docstring": "Tests that white listed html tags are not removed by bleach", "name": "test_white_listed", "signature": "def test_white_listed(self)" }, { "docstring": "Tests that tables are correctly bleached", "name": "test_table", "signature": "def test_table(self)" }, { "docs...
4
stack_v2_sparse_classes_30k_train_013801
Implement the Python class `BleachTest` described below. Class description: Implement the BleachTest class. Method signatures and docstrings: - def test_white_listed(self): Tests that white listed html tags are not removed by bleach - def test_table(self): Tests that tables are correctly bleached - def test_line_brea...
Implement the Python class `BleachTest` described below. Class description: Implement the BleachTest class. Method signatures and docstrings: - def test_white_listed(self): Tests that white listed html tags are not removed by bleach - def test_table(self): Tests that tables are correctly bleached - def test_line_brea...
b19bb7fb0de502dd6f5a48332f7054f93f1522d0
<|skeleton|> class BleachTest: def test_white_listed(self): """Tests that white listed html tags are not removed by bleach""" <|body_0|> def test_table(self): """Tests that tables are correctly bleached""" <|body_1|> def test_line_breaks(self): """Tests that tables...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BleachTest: def test_white_listed(self): """Tests that white listed html tags are not removed by bleach""" texts = [u'Superscript: <sup>italics</sup>', u'Subscript: <sub>italics</sub>', u'Links: <a href="http://www.uanwe.org/" target="_blank">UNAWE</a>', u'Italics: <em>italics</em>', u'Paragra...
the_stack_v2_python_sparse
activities/tests.py
unawe/django-apps
train
1
c6d5278b72b661cdcd4e1d5b0c8413faaaadb86d
[ "def hashURL():\n code = ''\n tmp = ''\n for i in range(6):\n tmp = letters[random.randint(0, 10000) % 62]\n code = code + tmp\n return code\nprefix = 'http://tinyurl.com/'\nif longUrl in long_short:\n return prefix + long_short[longUrl]\nelse:\n suffix = hashURL()\n long_short[lo...
<|body_start_0|> def hashURL(): code = '' tmp = '' for i in range(6): tmp = letters[random.randint(0, 10000) % 62] code = code + tmp return code prefix = 'http://tinyurl.com/' if longUrl in long_short: re...
如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: """如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。""" def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" <|body_0|> def decode(self, shortUrl): """Decodes a shortened URL ...
stack_v2_sparse_classes_36k_train_013754
1,624
no_license
[ { "docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str", "name": "encode", "signature": "def encode(self, longUrl)" }, { "docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str", "name": "decode", "signature": "def decode(self,...
2
stack_v2_sparse_classes_30k_train_021686
Implement the Python class `Codec` described below. Class description: 如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。 Method signatures and docstrings: - def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str - def decode(self, shortUrl): Dec...
Implement the Python class `Codec` described below. Class description: 如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。 Method signatures and docstrings: - def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str - def decode(self, shortUrl): Dec...
034efcefe9940267abcf4c9cab655b2344e3e901
<|skeleton|> class Codec: """如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。""" def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" <|body_0|> def decode(self, shortUrl): """Decodes a shortened URL ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: """如何设计短URL? 如何设计一个hash function? 可以用26个字母大小写52个加上数字10个一共62个字符, 在从中随机选取6个字符 作为网站的后缀,棒棒哒。""" def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" def hashURL(): code = '' tmp = '' for i in range(6): ...
the_stack_v2_python_sparse
535_encode_and_decode_tinyURL.py
HongsenHe/algo2018
train
0
97bd263e9f45a68063c5314d25accb87c8f65687
[ "self.environment = environment\nself.leaves_count = leaves_count\nself.total_logical_size = total_logical_size", "if dictionary is None:\n return None\nenvironment = dictionary.get('environment')\nleaves_count = dictionary.get('leavesCount')\ntotal_logical_size = dictionary.get('totalLogicalSize')\nreturn cls...
<|body_start_0|> self.environment = environment self.leaves_count = leaves_count self.total_logical_size = total_logical_size <|end_body_0|> <|body_start_1|> if dictionary is None: return None environment = dictionary.get('environment') leaves_count = diction...
Implementation of the 'AggregatedSubtreeInfo' model. Aggregated information about a node subtree. Attributes: environment (EnvironmentAggregatedSubtreeInfoEnum): Specifies the environment such as 'kSQL' or 'kVMware', where the Protection Source exists. Supported environment types such as 'kView', 'kSQL', 'kVMware', etc...
AggregatedSubtreeInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AggregatedSubtreeInfo: """Implementation of the 'AggregatedSubtreeInfo' model. Aggregated information about a node subtree. Attributes: environment (EnvironmentAggregatedSubtreeInfoEnum): Specifies the environment such as 'kSQL' or 'kVMware', where the Protection Source exists. Supported environm...
stack_v2_sparse_classes_36k_train_013755
5,989
permissive
[ { "docstring": "Constructor for the AggregatedSubtreeInfo class", "name": "__init__", "signature": "def __init__(self, environment=None, leaves_count=None, total_logical_size=None)" }, { "docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary...
2
stack_v2_sparse_classes_30k_train_002744
Implement the Python class `AggregatedSubtreeInfo` described below. Class description: Implementation of the 'AggregatedSubtreeInfo' model. Aggregated information about a node subtree. Attributes: environment (EnvironmentAggregatedSubtreeInfoEnum): Specifies the environment such as 'kSQL' or 'kVMware', where the Prote...
Implement the Python class `AggregatedSubtreeInfo` described below. Class description: Implementation of the 'AggregatedSubtreeInfo' model. Aggregated information about a node subtree. Attributes: environment (EnvironmentAggregatedSubtreeInfoEnum): Specifies the environment such as 'kSQL' or 'kVMware', where the Prote...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class AggregatedSubtreeInfo: """Implementation of the 'AggregatedSubtreeInfo' model. Aggregated information about a node subtree. Attributes: environment (EnvironmentAggregatedSubtreeInfoEnum): Specifies the environment such as 'kSQL' or 'kVMware', where the Protection Source exists. Supported environm...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AggregatedSubtreeInfo: """Implementation of the 'AggregatedSubtreeInfo' model. Aggregated information about a node subtree. Attributes: environment (EnvironmentAggregatedSubtreeInfoEnum): Specifies the environment such as 'kSQL' or 'kVMware', where the Protection Source exists. Supported environment types suc...
the_stack_v2_python_sparse
cohesity_management_sdk/models/aggregated_subtree_info.py
cohesity/management-sdk-python
train
24
5ae04bda02458420cb66cc6f39b1d87d992a4fd9
[ "self.kp = kp\nself.ki = ki\nself.kd = kd\nself.maxCartOrder = maxCartOrder\nself.maxThetaOrder = maxThetaOrder", "errX = target[0] - pos[0] + feedForward[0]\nerrY = target[1] - pos[1] + feedForward[1]\nerrTheta = math.atan2(math.sin(target[2] - pos[2] + feedForward[2]), math.cos(target[2] - pos[2] + feedForward[...
<|body_start_0|> self.kp = kp self.ki = ki self.kd = kd self.maxCartOrder = maxCartOrder self.maxThetaOrder = maxThetaOrder <|end_body_0|> <|body_start_1|> errX = target[0] - pos[0] + feedForward[0] errY = target[1] - pos[1] + feedForward[1] errTheta = ma...
PIDController
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PIDController: def __init__(self, kp, ki, kd, maxCartOrder, maxThetaOrder): """Parameters ---------- kp : float ki : float kd : float maxCartOrder : float The maximal cartesian speed maxThetaOrder : float The maximal angular speed""" <|body_0|> def step(self, t, pos, target,...
stack_v2_sparse_classes_36k_train_013756
18,897
no_license
[ { "docstring": "Parameters ---------- kp : float ki : float kd : float maxCartOrder : float The maximal cartesian speed maxThetaOrder : float The maximal angular speed", "name": "__init__", "signature": "def __init__(self, kp, ki, kd, maxCartOrder, maxThetaOrder)" }, { "docstring": "Parameters -...
2
stack_v2_sparse_classes_30k_train_005106
Implement the Python class `PIDController` described below. Class description: Implement the PIDController class. Method signatures and docstrings: - def __init__(self, kp, ki, kd, maxCartOrder, maxThetaOrder): Parameters ---------- kp : float ki : float kd : float maxCartOrder : float The maximal cartesian speed max...
Implement the Python class `PIDController` described below. Class description: Implement the PIDController class. Method signatures and docstrings: - def __init__(self, kp, ki, kd, maxCartOrder, maxThetaOrder): Parameters ---------- kp : float ki : float kd : float maxCartOrder : float The maximal cartesian speed max...
86555afa37ff2f959e49779f148b89574295b972
<|skeleton|> class PIDController: def __init__(self, kp, ki, kd, maxCartOrder, maxThetaOrder): """Parameters ---------- kp : float ki : float kd : float maxCartOrder : float The maximal cartesian speed maxThetaOrder : float The maximal angular speed""" <|body_0|> def step(self, t, pos, target,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PIDController: def __init__(self, kp, ki, kd, maxCartOrder, maxThetaOrder): """Parameters ---------- kp : float ki : float kd : float maxCartOrder : float The maximal cartesian speed maxThetaOrder : float The maximal angular speed""" self.kp = kp self.ki = ki self.kd = kd ...
the_stack_v2_python_sparse
td5_bis/montero_eliott/control.py
EliottMontero/robotique_fac
train
1
ed52191d60476f3660a9b64073296eb82a51dd4e
[ "xs = []\nqueue = deque([root])\nwhile queue:\n node = queue.popleft()\n if node:\n xs.append(node.val)\n queue.append(node.left)\n queue.append(node.right)\n else:\n xs.append(None)\nwhile xs and xs[-1] is None:\n xs.pop()\nreturn str(xs).replace('None', 'null')", "data = ...
<|body_start_0|> xs = [] queue = deque([root]) while queue: node = queue.popleft() if node: xs.append(node.val) queue.append(node.left) queue.append(node.right) else: xs.append(None) while...
CodecFirst
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CodecFirst: 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_train_013757
1,980
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 `CodecFirst` described below. Class description: Implement the CodecFirst 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: s...
Implement the Python class `CodecFirst` described below. Class description: Implement the CodecFirst 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: s...
700ebd442ee224b8b369d0c4b0e986ba8edbff90
<|skeleton|> class CodecFirst: 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 CodecFirst: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" xs = [] queue = deque([root]) while queue: node = queue.popleft() if node: xs.append(node.val) queue.append(n...
the_stack_v2_python_sparse
leetcode/pai/chapter14/q47_p297_serialize.py
jms7446/hackerrank
train
3
da587a408516bd31b360de12c1f79c03b6ba6dd5
[ "if file:\n extension = splitext(file.name)[1]\n if extension not in ('.pdf', '.doc', '.docx'):\n raise serializers.ValidationError('Only pdf, doc, docx files')\nreturn file", "self.fields['skills'] = SkillSerializer(many=True)\nself.fields['owner'] = UserSerializer()\nself.fields['position'] = Posit...
<|body_start_0|> if file: extension = splitext(file.name)[1] if extension not in ('.pdf', '.doc', '.docx'): raise serializers.ValidationError('Only pdf, doc, docx files') return file <|end_body_0|> <|body_start_1|> self.fields['skills'] = SkillSerializer(...
Resume serializer.
ResumeSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResumeSerializer: """Resume serializer.""" def validate_file(file): """Validate file extension. :param file: :return:""" <|body_0|> def to_representation(self, instance: Resume) -> dict: """Transform object. :param instance: Resume :return: OrderedDict""" ...
stack_v2_sparse_classes_36k_train_013758
1,819
no_license
[ { "docstring": "Validate file extension. :param file: :return:", "name": "validate_file", "signature": "def validate_file(file)" }, { "docstring": "Transform object. :param instance: Resume :return: OrderedDict", "name": "to_representation", "signature": "def to_representation(self, inst...
2
null
Implement the Python class `ResumeSerializer` described below. Class description: Resume serializer. Method signatures and docstrings: - def validate_file(file): Validate file extension. :param file: :return: - def to_representation(self, instance: Resume) -> dict: Transform object. :param instance: Resume :return: O...
Implement the Python class `ResumeSerializer` described below. Class description: Resume serializer. Method signatures and docstrings: - def validate_file(file): Validate file extension. :param file: :return: - def to_representation(self, instance: Resume) -> dict: Transform object. :param instance: Resume :return: O...
713b9d84ac70d964d46f189ab1f9c7b944b9684b
<|skeleton|> class ResumeSerializer: """Resume serializer.""" def validate_file(file): """Validate file extension. :param file: :return:""" <|body_0|> def to_representation(self, instance: Resume) -> dict: """Transform object. :param instance: Resume :return: OrderedDict""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ResumeSerializer: """Resume serializer.""" def validate_file(file): """Validate file extension. :param file: :return:""" if file: extension = splitext(file.name)[1] if extension not in ('.pdf', '.doc', '.docx'): raise serializers.ValidationError('On...
the_stack_v2_python_sparse
jobadvisor/users/serializers/resume.py
ewgen19892/jobadvisor
train
0
39d5cbde1df13348c577ea715dc9665445e8b593
[ "category = unicodedata.category(c)[0]\nif category == 'C':\n return u' '\nif category == 'Z':\n return u' '\nreturn c", "assert isinstance(s, unicode)\ns = unicodedata.normalize('NFC', s)\nsanitized_lines = []\nfor line in s.split(u'\\n'):\n sanitized_lines.append(u''.join(map(TextSanitizer._sanitize, l...
<|body_start_0|> category = unicodedata.category(c)[0] if category == 'C': return u' ' if category == 'Z': return u' ' return c <|end_body_0|> <|body_start_1|> assert isinstance(s, unicode) s = unicodedata.normalize('NFC', s) sanitized_lin...
TextSanitizer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextSanitizer: def _sanitize(c): """Returns space if character is not printable""" <|body_0|> def clean_utf8(s): """Removes most funny characters from Unicode""" <|body_1|> <|end_skeleton|> <|body_start_0|> category = unicodedata.category(c)[0] ...
stack_v2_sparse_classes_36k_train_013759
4,023
permissive
[ { "docstring": "Returns space if character is not printable", "name": "_sanitize", "signature": "def _sanitize(c)" }, { "docstring": "Removes most funny characters from Unicode", "name": "clean_utf8", "signature": "def clean_utf8(s)" } ]
2
null
Implement the Python class `TextSanitizer` described below. Class description: Implement the TextSanitizer class. Method signatures and docstrings: - def _sanitize(c): Returns space if character is not printable - def clean_utf8(s): Removes most funny characters from Unicode
Implement the Python class `TextSanitizer` described below. Class description: Implement the TextSanitizer class. Method signatures and docstrings: - def _sanitize(c): Returns space if character is not printable - def clean_utf8(s): Removes most funny characters from Unicode <|skeleton|> class TextSanitizer: de...
f9248c3528a415a1e5af2c5a54a60c16cd79ff1d
<|skeleton|> class TextSanitizer: def _sanitize(c): """Returns space if character is not printable""" <|body_0|> def clean_utf8(s): """Removes most funny characters from Unicode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TextSanitizer: def _sanitize(c): """Returns space if character is not printable""" category = unicodedata.category(c)[0] if category == 'C': return u' ' if category == 'Z': return u' ' return c def clean_utf8(s): """Removes most funn...
the_stack_v2_python_sparse
baseline/util/encoding.py
christianbuck/CorpusMining
train
2
218b5ab3a2cbdb4f1c36aee62630c2320a7ca86c
[ "try:\n book = BookInfo.objects.get(pk=pk)\nexcept BookInfo.DoesNotExist:\n return HttpResponse(status=404)\nreturn JsonResponse({'id': book.id, 'name': book.name, 'pub_date': book.pub_date, 'read_count': book.read_count, 'comment_count': book.comment_count})", "try:\n book = BookInfo.objects.get(pk=pk)\...
<|body_start_0|> try: book = BookInfo.objects.get(pk=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) return JsonResponse({'id': book.id, 'name': book.name, 'pub_date': book.pub_date, 'read_count': book.read_count, 'comment_count': book.comment_count}) <|...
BookAPIView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BookAPIView: def get(self, request, pk): """获取单个图书信息 路由: GET /books/<pk>/ url中则需要设置books/(?P<pk>d+)/""" <|body_0|> def put(self, request, pk): """修改图书信息 路由: PUT /books/<pk>""" <|body_1|> def delete(self, request, pk): """删除图书 路由: DELETE /books/<p...
stack_v2_sparse_classes_36k_train_013760
4,279
permissive
[ { "docstring": "获取单个图书信息 路由: GET /books/<pk>/ url中则需要设置books/(?P<pk>d+)/", "name": "get", "signature": "def get(self, request, pk)" }, { "docstring": "修改图书信息 路由: PUT /books/<pk>", "name": "put", "signature": "def put(self, request, pk)" }, { "docstring": "删除图书 路由: DELETE /books/<...
3
null
Implement the Python class `BookAPIView` described below. Class description: Implement the BookAPIView class. Method signatures and docstrings: - def get(self, request, pk): 获取单个图书信息 路由: GET /books/<pk>/ url中则需要设置books/(?P<pk>d+)/ - def put(self, request, pk): 修改图书信息 路由: PUT /books/<pk> - def delete(self, request, pk...
Implement the Python class `BookAPIView` described below. Class description: Implement the BookAPIView class. Method signatures and docstrings: - def get(self, request, pk): 获取单个图书信息 路由: GET /books/<pk>/ url中则需要设置books/(?P<pk>d+)/ - def put(self, request, pk): 修改图书信息 路由: PUT /books/<pk> - def delete(self, request, pk...
771a3f44c5d0e9a7be1118b84ca89cd34c3d7293
<|skeleton|> class BookAPIView: def get(self, request, pk): """获取单个图书信息 路由: GET /books/<pk>/ url中则需要设置books/(?P<pk>d+)/""" <|body_0|> def put(self, request, pk): """修改图书信息 路由: PUT /books/<pk>""" <|body_1|> def delete(self, request, pk): """删除图书 路由: DELETE /books/<p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BookAPIView: def get(self, request, pk): """获取单个图书信息 路由: GET /books/<pk>/ url中则需要设置books/(?P<pk>d+)/""" try: book = BookInfo.objects.get(pk=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) return JsonResponse({'id': book.id, 'name': book...
the_stack_v2_python_sparse
19Django_Advanced/day01to06/demo/DRF/views.py
mumudexiaomuwu/Python24
train
1
455de4b4599b8b0efba4df13a000c61c33d4dc0b
[ "self.data = data\nself.instruments = configuration.instruments\nself.events = events\nself.strategy_name = 'multi_random'\nself.exchanges = configuration.exchange_names\nself.exchange = self.exchanges[0]\nself.instruments = self.instruments[self.exchange]\nself.datetime = datetime.utcnow()\nself.state = dict(((k, ...
<|body_start_0|> self.data = data self.instruments = configuration.instruments self.events = events self.strategy_name = 'multi_random' self.exchanges = configuration.exchange_names self.exchange = self.exchanges[0] self.instruments = self.instruments[self.exchang...
This strategy simply decides to enter or exit the market randomly
MultiRandomStrategy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiRandomStrategy: """This strategy simply decides to enter or exit the market randomly""" def __init__(self, data, events, configuration): """Parameters: data - The DataHandler object that provides bar information events - The Event Queue object.""" <|body_0|> def cal...
stack_v2_sparse_classes_36k_train_013761
2,671
no_license
[ { "docstring": "Parameters: data - The DataHandler object that provides bar information events - The Event Queue object.", "name": "__init__", "signature": "def __init__(self, data, events, configuration)" }, { "docstring": "Calculate the SignalEvents randomly", "name": "calculate_signals", ...
2
stack_v2_sparse_classes_30k_test_000236
Implement the Python class `MultiRandomStrategy` described below. Class description: This strategy simply decides to enter or exit the market randomly Method signatures and docstrings: - def __init__(self, data, events, configuration): Parameters: data - The DataHandler object that provides bar information events - T...
Implement the Python class `MultiRandomStrategy` described below. Class description: This strategy simply decides to enter or exit the market randomly Method signatures and docstrings: - def __init__(self, data, events, configuration): Parameters: data - The DataHandler object that provides bar information events - T...
39ad067fa9ea27002d06c98a9d06725ad886917b
<|skeleton|> class MultiRandomStrategy: """This strategy simply decides to enter or exit the market randomly""" def __init__(self, data, events, configuration): """Parameters: data - The DataHandler object that provides bar information events - The Event Queue object.""" <|body_0|> def cal...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MultiRandomStrategy: """This strategy simply decides to enter or exit the market randomly""" def __init__(self, data, events, configuration): """Parameters: data - The DataHandler object that provides bar information events - The Event Queue object.""" self.data = data self.instru...
the_stack_v2_python_sparse
strategies/crypto/multi_random.py
Dvisacker/backtrader
train
2
14040caed5f25502048e9b8854e460d2e07464ec
[ "self.device_id = device_id\nself.title = title\nself.alt_title = alt_title\nself.identity = identity\nself.site = site\nself.device_type = device_type\nself.device_type_id = device_type_id\nself.parent_id = parent_id\nself.child_ids = child_ids\nself.device_model = device_model\nself.turbine_type = turbine_type\ns...
<|body_start_0|> self.device_id = device_id self.title = title self.alt_title = alt_title self.identity = identity self.site = site self.device_type = device_type self.device_type_id = device_type_id self.parent_id = parent_id self.child_ids = chil...
Implementation of the 'Device' model. TODO: type model description here. Attributes: device_id (int): The id of a device. title (string): TODO: type description here. alt_title (string): An alternative title. identity (string): Device identification number. site (Site): The site where the device is located. device_type...
Device
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Device: """Implementation of the 'Device' model. TODO: type model description here. Attributes: device_id (int): The id of a device. title (string): TODO: type description here. alt_title (string): An alternative title. identity (string): Device identification number. site (Site): The site where ...
stack_v2_sparse_classes_36k_train_013762
6,998
permissive
[ { "docstring": "Constructor for the Device class", "name": "__init__", "signature": "def __init__(self, device_id=None, title=None, alt_title=None, identity=None, site=None, device_type=None, device_type_id=None, parent_id=None, child_ids=None, device_model=None, turbine_type=None, max_power=None, biddi...
2
stack_v2_sparse_classes_30k_train_002801
Implement the Python class `Device` described below. Class description: Implementation of the 'Device' model. TODO: type model description here. Attributes: device_id (int): The id of a device. title (string): TODO: type description here. alt_title (string): An alternative title. identity (string): Device identificati...
Implement the Python class `Device` described below. Class description: Implementation of the 'Device' model. TODO: type model description here. Attributes: device_id (int): The id of a device. title (string): TODO: type description here. alt_title (string): An alternative title. identity (string): Device identificati...
6835ee1f6a667b5c7827c5248391081f06b75513
<|skeleton|> class Device: """Implementation of the 'Device' model. TODO: type model description here. Attributes: device_id (int): The id of a device. title (string): TODO: type description here. alt_title (string): An alternative title. identity (string): Device identification number. site (Site): The site where ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Device: """Implementation of the 'Device' model. TODO: type model description here. Attributes: device_id (int): The id of a device. title (string): TODO: type description here. alt_title (string): An alternative title. identity (string): Device identification number. site (Site): The site where the device is...
the_stack_v2_python_sparse
greenbyteapi/models/device.py
charlie9578/greenbyte-api-sdk
train
0
a2d1244e76b19fd87ff7cb7d1636a56fd77e5b2b
[ "self.infolder, self.outfolder = (infolder, outfolder)\nself.collection_name = collection_name\nself.files = glob.glob('%s/*.%s' % (infolder, imagetype))\nn = len(self.files)\nself.type = imagetype\nself.files.sort()\nif n == 0:\n raise InvalidParameter('no %s files found in folder \"%s\"' % (imagetype, infolder...
<|body_start_0|> self.infolder, self.outfolder = (infolder, outfolder) self.collection_name = collection_name self.files = glob.glob('%s/*.%s' % (infolder, imagetype)) n = len(self.files) self.type = imagetype self.files.sort() if n == 0: raise Invalid...
Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an optional IPython.parallel.Client object
MakeCollection
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MakeCollection: """Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an op...
stack_v2_sparse_classes_36k_train_013763
5,986
permissive
[ { "docstring": "infolder : path to a folder containing a bunch of images (jpg by default) to convert outfolder : where to set up the collection keyword parameters collection_name: ['dzc'] name to apply to the deep zoom collection: will be the name of a xml file and the folder name containing the DZ images image...
4
null
Implement the Python class `MakeCollection` described below. Class description: Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images)...
Implement the Python class `MakeCollection` described below. Class description: Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images)...
edcdc696c3300e2f26ff3efa92a1bd9790074247
<|skeleton|> class MakeCollection: """Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an op...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MakeCollection: """Create a DeepZoom collection, converting a set of images. Usage: mc = dz_collection.MakeCollection('uw93/combined', '/phys/users/tburnett/pivot/24M_uw93') mc.convert() mc.collect() Note that the convert step time is order(number of images) and can be parallized by passing an optional IPytho...
the_stack_v2_python_sparse
python/uw/like2/pub/dz_collection.py
fermi-lat/pointlike
train
1
cd2d54970da531e6bb5eaf99d1cbaed325663bf1
[ "self.SetStartDate(2004, 1, 1)\nself.SetEndDate(2015, 1, 1)\nself.SetCash(100000)\nself.AddEquity('SPY', Resolution.Daily)\nself.__macd = self.MACD('SPY', 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)\nself.__previous = datetime.min\nself.PlotIndicator('MACD', True, self.__macd, self.__macd.Signal)\ns...
<|body_start_0|> self.SetStartDate(2004, 1, 1) self.SetEndDate(2015, 1, 1) self.SetCash(100000) self.AddEquity('SPY', Resolution.Daily) self.__macd = self.MACD('SPY', 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily) self.__previous = datetime.min self.P...
MACDTrendAlgorithm
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MACDTrendAlgorithm: def Initialize(self): """Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.""" <|body_0|> def OnData(self, data): """OnData event is the primary entry point for...
stack_v2_sparse_classes_36k_train_013764
2,822
permissive
[ { "docstring": "Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.", "name": "Initialize", "signature": "def Initialize(self)" }, { "docstring": "OnData event is the primary entry point for your algorithm. Eac...
2
stack_v2_sparse_classes_30k_train_003048
Implement the Python class `MACDTrendAlgorithm` described below. Class description: Implement the MACDTrendAlgorithm class. Method signatures and docstrings: - def Initialize(self): Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized...
Implement the Python class `MACDTrendAlgorithm` described below. Class description: Implement the MACDTrendAlgorithm class. Method signatures and docstrings: - def Initialize(self): Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized...
b33dd3bc140e14b883f39ecf848a793cf7292277
<|skeleton|> class MACDTrendAlgorithm: def Initialize(self): """Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.""" <|body_0|> def OnData(self, data): """OnData event is the primary entry point for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MACDTrendAlgorithm: def Initialize(self): """Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.""" self.SetStartDate(2004, 1, 1) self.SetEndDate(2015, 1, 1) self.SetCash(100000) self....
the_stack_v2_python_sparse
Algorithm.Python/MACDTrendAlgorithm.py
Capnode/Algoloop
train
87
cc7b6657339179d5ed279a33d28a42cfb59f298f
[ "assert isinstance(block_string, str)\nops = block_string.split('_')\noptions = {}\nfor op in ops:\n splits = re.split('(\\\\d.*)', op)\n if len(splits) >= 2:\n key, value = splits[:2]\n options[key] = value\nif 's' not in options or len(options['s']) != 2:\n raise ValueError('Strides options...
<|body_start_0|> assert isinstance(block_string, str) ops = block_string.split('_') options = {} for op in ops: splits = re.split('(\\d.*)', op) if len(splits) >= 2: key, value = splits[:2] options[key] = value if 's' not in...
Block Decoder for readability.
BlockDecoder
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BlockDecoder: """Block Decoder for readability.""" def _decode_block_string(self, block_string): """Gets a block through a string notation of arguments.""" <|body_0|> def _encode_block_string(self, block): """Encodes a block to a string.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_013765
30,373
permissive
[ { "docstring": "Gets a block through a string notation of arguments.", "name": "_decode_block_string", "signature": "def _decode_block_string(self, block_string)" }, { "docstring": "Encodes a block to a string.", "name": "_encode_block_string", "signature": "def _encode_block_string(self...
4
stack_v2_sparse_classes_30k_train_009266
Implement the Python class `BlockDecoder` described below. Class description: Block Decoder for readability. Method signatures and docstrings: - def _decode_block_string(self, block_string): Gets a block through a string notation of arguments. - def _encode_block_string(self, block): Encodes a block to a string. - de...
Implement the Python class `BlockDecoder` described below. Class description: Block Decoder for readability. Method signatures and docstrings: - def _decode_block_string(self, block_string): Gets a block through a string notation of arguments. - def _encode_block_string(self, block): Encodes a block to a string. - de...
1a8cc1467258c7245db3b5fe653d51d8638c7a25
<|skeleton|> class BlockDecoder: """Block Decoder for readability.""" def _decode_block_string(self, block_string): """Gets a block through a string notation of arguments.""" <|body_0|> def _encode_block_string(self, block): """Encodes a block to a string.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BlockDecoder: """Block Decoder for readability.""" def _decode_block_string(self, block_string): """Gets a block through a string notation of arguments.""" assert isinstance(block_string, str) ops = block_string.split('_') options = {} for op in ops: sp...
the_stack_v2_python_sparse
yolo3/efficientnet.py
panyongfeng/yolo3_tangrm
train
1
60351c5539a2c0347c18b9f37b9002f77e5524b1
[ "self.selector = selector\nself.delta_gamma = delta_gamma\nself.mean_e = ParallelMean(size=10)\nself.counts = np.zeros(5, dtype=int)", "prefixes = ['00/', '1p/', '1m/', '2p/', '2m/']\nfor i, p in enumerate(prefixes):\n data_p = _DataWrapper(data, prefix=p)\n sel = self.selector(data_p, *args, **kwargs)\n ...
<|body_start_0|> self.selector = selector self.delta_gamma = delta_gamma self.mean_e = ParallelMean(size=10) self.counts = np.zeros(5, dtype=int) <|end_body_0|> <|body_start_1|> prefixes = ['00/', '1p/', '1m/', '2p/', '2m/'] for i, p in enumerate(prefixes): d...
MetaDetectCalculator
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetaDetectCalculator: def __init__(self, selector, delta_gamma): """Parameters ---------- selector: function Function that selects objects delta_gamma: float The difference in applied g between 1p and 1m metacal variants""" <|body_0|> def add_data(self, data, *args, **kwargs...
stack_v2_sparse_classes_36k_train_013766
27,539
permissive
[ { "docstring": "Parameters ---------- selector: function Function that selects objects delta_gamma: float The difference in applied g between 1p and 1m metacal variants", "name": "__init__", "signature": "def __init__(self, selector, delta_gamma)" }, { "docstring": "Select objects from a new chu...
3
null
Implement the Python class `MetaDetectCalculator` described below. Class description: Implement the MetaDetectCalculator class. Method signatures and docstrings: - def __init__(self, selector, delta_gamma): Parameters ---------- selector: function Function that selects objects delta_gamma: float The difference in app...
Implement the Python class `MetaDetectCalculator` described below. Class description: Implement the MetaDetectCalculator class. Method signatures and docstrings: - def __init__(self, selector, delta_gamma): Parameters ---------- selector: function Function that selects objects delta_gamma: float The difference in app...
addbfbe6c4dc0df208ce4f7ba4cb0a7588a932e3
<|skeleton|> class MetaDetectCalculator: def __init__(self, selector, delta_gamma): """Parameters ---------- selector: function Function that selects objects delta_gamma: float The difference in applied g between 1p and 1m metacal variants""" <|body_0|> def add_data(self, data, *args, **kwargs...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetaDetectCalculator: def __init__(self, selector, delta_gamma): """Parameters ---------- selector: function Function that selects objects delta_gamma: float The difference in applied g between 1p and 1m metacal variants""" self.selector = selector self.delta_gamma = delta_gamma ...
the_stack_v2_python_sparse
txpipe/utils/calibration_tools.py
LSSTDESC/TXPipe
train
17
9ae03d6c1800f3b5835b01aa2accb6049c90a47f
[ "self.id_nodes = mapping\nfor child in self.children:\n child.update_id_nodes(mapping)", "node = type(self)()\nnode.scope_key = self.scope_key\nnode.children = [child.copy() for child in self.children]\nreturn node" ]
<|body_start_0|> self.id_nodes = mapping for child in self.children: child.update_id_nodes(mapping) <|end_body_0|> <|body_start_1|> node = type(self)() node.scope_key = self.scope_key node.children = [child.copy() for child in self.children] return node <|end...
A base class for defining compiler nodes.
CompilerNode
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompilerNode: """A base class for defining compiler nodes.""" def update_id_nodes(self, mapping): """Recursively update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifier information.""" <|body_0|> def copy(self)...
stack_v2_sparse_classes_36k_train_013767
11,984
permissive
[ { "docstring": "Recursively update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifier information.", "name": "update_id_nodes", "signature": "def update_id_nodes(self, mapping)" }, { "docstring": "Create a copy of the compiler node.", ...
2
null
Implement the Python class `CompilerNode` described below. Class description: A base class for defining compiler nodes. Method signatures and docstrings: - def update_id_nodes(self, mapping): Recursively update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifi...
Implement the Python class `CompilerNode` described below. Class description: A base class for defining compiler nodes. Method signatures and docstrings: - def update_id_nodes(self, mapping): Recursively update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifi...
1544e7fb371b8f941cfa2fde682795e479380284
<|skeleton|> class CompilerNode: """A base class for defining compiler nodes.""" def update_id_nodes(self, mapping): """Recursively update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifier information.""" <|body_0|> def copy(self)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CompilerNode: """A base class for defining compiler nodes.""" def update_id_nodes(self, mapping): """Recursively update the id nodes for this node. Parameters ---------- mapping : sortedmap The mapping to fill with the identifier information.""" self.id_nodes = mapping for child i...
the_stack_v2_python_sparse
enaml/core/compiler_nodes.py
MatthieuDartiailh/enaml
train
26
46a16608ba0b27fdfb43094cbc951d34fe3758bc
[ "nn.Module.__init__(self)\nif conv_kwargs is None:\n conv_kwargs = {'kernel_size': 3, 'stride': 1, 'padding': 1, 'bias': True}\nif norm_kwargs is None:\n norm_kwargs = {'eps': 1e-05, 'affine': True, 'momentum': 0.1, 'track_running_stats': True}\nif act_kwargs is None:\n act_kwargs = {'negative_slope': 0.01...
<|body_start_0|> nn.Module.__init__(self) if conv_kwargs is None: conv_kwargs = {'kernel_size': 3, 'stride': 1, 'padding': 1, 'bias': True} if norm_kwargs is None: norm_kwargs = {'eps': 1e-05, 'affine': True, 'momentum': 0.1, 'track_running_stats': True} if act_kw...
InitialConv
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InitialConv: def __init__(self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, norm=nn.BatchNorm2d, norm_kwargs=None, act=nn.LeakyReLU, act_kwargs=None, dropout=nn.Dropout2d, dropout_kwargs=None, network_kwargs=None): """The initial convolutional layer for a UNet-like...
stack_v2_sparse_classes_36k_train_013768
3,247
permissive
[ { "docstring": "The initial convolutional layer for a UNet-like network. Args: input_channels (int): The number of channels in the input tensor. output_channels (int): The number of channels in the output tensor. conv (nn.Module): The convolutional layer to use. conv_kwargs (dict): The arguments to pass to the ...
2
stack_v2_sparse_classes_30k_train_008897
Implement the Python class `InitialConv` described below. Class description: Implement the InitialConv class. Method signatures and docstrings: - def __init__(self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, norm=nn.BatchNorm2d, norm_kwargs=None, act=nn.LeakyReLU, act_kwargs=None, dropout=nn.D...
Implement the Python class `InitialConv` described below. Class description: Implement the InitialConv class. Method signatures and docstrings: - def __init__(self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, norm=nn.BatchNorm2d, norm_kwargs=None, act=nn.LeakyReLU, act_kwargs=None, dropout=nn.D...
72eb99f68205afd5f8d49a3bb6cfc08cfd467582
<|skeleton|> class InitialConv: def __init__(self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, norm=nn.BatchNorm2d, norm_kwargs=None, act=nn.LeakyReLU, act_kwargs=None, dropout=nn.Dropout2d, dropout_kwargs=None, network_kwargs=None): """The initial convolutional layer for a UNet-like...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class InitialConv: def __init__(self, input_channels, output_channels, conv=nn.Conv2d, conv_kwargs=None, norm=nn.BatchNorm2d, norm_kwargs=None, act=nn.LeakyReLU, act_kwargs=None, dropout=nn.Dropout2d, dropout_kwargs=None, network_kwargs=None): """The initial convolutional layer for a UNet-like network. Args...
the_stack_v2_python_sparse
GANDLF/models/seg_modules/InitialConv.py
mlcommons/GaNDLF
train
45
5ea39dda1400833d7ab14640a7ec1cc996ba5494
[ "self.app_server_id = app_server_id\nself.backup_supported = backup_supported\nself.backup_unsupported_reasons = backup_unsupported_reasons\nself.created_time_msecs = created_time_msecs\nself.database_state = database_state\nself.db_size_bytes = db_size_bytes\nself.dbguid = dbguid\nself.name = name\nself.owner_id =...
<|body_start_0|> self.app_server_id = app_server_id self.backup_supported = backup_supported self.backup_unsupported_reasons = backup_unsupported_reasons self.created_time_msecs = created_time_msecs self.database_state = database_state self.db_size_bytes = db_size_bytes ...
Implementation of the 'ExchangeDatabaseInfo' model. Specifies the information about the Exchange Database. Attributes: app_server_id (long|int): Specifies the entity id of the Exchange Application Server which has this database copy. backup_supported (bool): Specifies if backup is supported for the Exchange database co...
ExchangeDatabaseInfo
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExchangeDatabaseInfo: """Implementation of the 'ExchangeDatabaseInfo' model. Specifies the information about the Exchange Database. Attributes: app_server_id (long|int): Specifies the entity id of the Exchange Application Server which has this database copy. backup_supported (bool): Specifies if ...
stack_v2_sparse_classes_36k_train_013769
4,567
permissive
[ { "docstring": "Constructor for the ExchangeDatabaseInfo class", "name": "__init__", "signature": "def __init__(self, app_server_id=None, backup_supported=None, backup_unsupported_reasons=None, created_time_msecs=None, database_state=None, db_size_bytes=None, dbguid=None, name=None, owner_id=None, utc_o...
2
stack_v2_sparse_classes_30k_train_019056
Implement the Python class `ExchangeDatabaseInfo` described below. Class description: Implementation of the 'ExchangeDatabaseInfo' model. Specifies the information about the Exchange Database. Attributes: app_server_id (long|int): Specifies the entity id of the Exchange Application Server which has this database copy....
Implement the Python class `ExchangeDatabaseInfo` described below. Class description: Implementation of the 'ExchangeDatabaseInfo' model. Specifies the information about the Exchange Database. Attributes: app_server_id (long|int): Specifies the entity id of the Exchange Application Server which has this database copy....
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class ExchangeDatabaseInfo: """Implementation of the 'ExchangeDatabaseInfo' model. Specifies the information about the Exchange Database. Attributes: app_server_id (long|int): Specifies the entity id of the Exchange Application Server which has this database copy. backup_supported (bool): Specifies if ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ExchangeDatabaseInfo: """Implementation of the 'ExchangeDatabaseInfo' model. Specifies the information about the Exchange Database. Attributes: app_server_id (long|int): Specifies the entity id of the Exchange Application Server which has this database copy. backup_supported (bool): Specifies if backup is sup...
the_stack_v2_python_sparse
cohesity_management_sdk/models/exchange_database_info.py
cohesity/management-sdk-python
train
24
695cee99cf12c7c750bdd02cbb215e58afb2e2f2
[ "super(SELayer, self).__init__()\nself.pool = PoolingNdTorch('AdaptiveAvg', n_dim, 1)\nself.fc = nn.Sequential(ConvNdTorch(n_dim, channel, channel // reduction, kernel_size=1, bias=False), nn.ReLU(inplace=True), ConvNdTorch(n_dim, channel // reduction, channel, kernel_size=1, bias=False), nn.Sigmoid())", "y = sel...
<|body_start_0|> super(SELayer, self).__init__() self.pool = PoolingNdTorch('AdaptiveAvg', n_dim, 1) self.fc = nn.Sequential(ConvNdTorch(n_dim, channel, channel // reduction, kernel_size=1, bias=False), nn.ReLU(inplace=True), ConvNdTorch(n_dim, channel // reduction, channel, kernel_size=1, bias=...
SELayer
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SELayer: def __init__(self, n_dim, channel, reduction=16): """Squeeze and Excitation Layer https://arxiv.org/abs/1709.01507 Parameters ---------- n_dim : int dimensionality of convolution channel : int number of input channel reduction : int channel reduction factor""" <|body_0|>...
stack_v2_sparse_classes_36k_train_013770
8,979
permissive
[ { "docstring": "Squeeze and Excitation Layer https://arxiv.org/abs/1709.01507 Parameters ---------- n_dim : int dimensionality of convolution channel : int number of input channel reduction : int channel reduction factor", "name": "__init__", "signature": "def __init__(self, n_dim, channel, reduction=16...
2
stack_v2_sparse_classes_30k_val_000948
Implement the Python class `SELayer` described below. Class description: Implement the SELayer class. Method signatures and docstrings: - def __init__(self, n_dim, channel, reduction=16): Squeeze and Excitation Layer https://arxiv.org/abs/1709.01507 Parameters ---------- n_dim : int dimensionality of convolution chan...
Implement the Python class `SELayer` described below. Class description: Implement the SELayer class. Method signatures and docstrings: - def __init__(self, n_dim, channel, reduction=16): Squeeze and Excitation Layer https://arxiv.org/abs/1709.01507 Parameters ---------- n_dim : int dimensionality of convolution chan...
d944aa67d319bd63a2add5cb89e8308413943de6
<|skeleton|> class SELayer: def __init__(self, n_dim, channel, reduction=16): """Squeeze and Excitation Layer https://arxiv.org/abs/1709.01507 Parameters ---------- n_dim : int dimensionality of convolution channel : int number of input channel reduction : int channel reduction factor""" <|body_0|>...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SELayer: def __init__(self, n_dim, channel, reduction=16): """Squeeze and Excitation Layer https://arxiv.org/abs/1709.01507 Parameters ---------- n_dim : int dimensionality of convolution channel : int number of input channel reduction : int channel reduction factor""" super(SELayer, self).__i...
the_stack_v2_python_sparse
deliravision/torch/models/backbones/seblocks.py
delira-dev/vision_torch
train
5
3f44194eb88dcbba7503fff0b3aacd8dc850ace8
[ "goal = getattr(goal, 'raw_expr', goal)\nself.interp = interp\nself.rts = interp.backend.create_evaluation_rts(interp, goal)", "interval = self.interp.flags['telemetry_interval']\nvalue_generator = self.rts.generate_values()\nif interval is not None and interval > 0:\n return telemetry.report_telemetry(self.rt...
<|body_start_0|> goal = getattr(goal, 'raw_expr', goal) self.interp = interp self.rts = interp.backend.create_evaluation_rts(interp, goal) <|end_body_0|> <|body_start_1|> interval = self.interp.flags['telemetry_interval'] value_generator = self.rts.generate_values() if i...
Manages the evaluation of a Curry expression.
Evaluator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Evaluator: """Manages the evaluation of a Curry expression.""" def __init__(self, interp, goal): """Initialize evaluation of ``goal`` under interpreter ``interp``.""" <|body_0|> def evaluate(self): """Evaluate the goal.""" <|body_1|> def set_global_s...
stack_v2_sparse_classes_36k_train_013771
1,594
no_license
[ { "docstring": "Initialize evaluation of ``goal`` under interpreter ``interp``.", "name": "__init__", "signature": "def __init__(self, interp, goal)" }, { "docstring": "Evaluate the goal.", "name": "evaluate", "signature": "def evaluate(self)" }, { "docstring": "Sets the step lim...
3
null
Implement the Python class `Evaluator` described below. Class description: Manages the evaluation of a Curry expression. Method signatures and docstrings: - def __init__(self, interp, goal): Initialize evaluation of ``goal`` under interpreter ``interp``. - def evaluate(self): Evaluate the goal. - def set_global_step_...
Implement the Python class `Evaluator` described below. Class description: Manages the evaluation of a Curry expression. Method signatures and docstrings: - def __init__(self, interp, goal): Initialize evaluation of ``goal`` under interpreter ``interp``. - def evaluate(self): Evaluate the goal. - def set_global_step_...
c28c09ca100ac102fcaa8559ad2e12eb0d12d7d5
<|skeleton|> class Evaluator: """Manages the evaluation of a Curry expression.""" def __init__(self, interp, goal): """Initialize evaluation of ``goal`` under interpreter ``interp``.""" <|body_0|> def evaluate(self): """Evaluate the goal.""" <|body_1|> def set_global_s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Evaluator: """Manages the evaluation of a Curry expression.""" def __init__(self, interp, goal): """Initialize evaluation of ``goal`` under interpreter ``interp``.""" goal = getattr(goal, 'raw_expr', goal) self.interp = interp self.rts = interp.backend.create_evaluation_rt...
the_stack_v2_python_sparse
src/python/backends/generic/eval/evaluator.py
andyjost/Sprite
train
5
33a50c181c472fb1b0a0f8d2c852e4bbf1ca4e5b
[ "input_json, output_json, payload = (request.data['APIParams'], {}, {'Payload': None})\noutput_json['AuthenticationDetails'] = request.data['AuthenticationDetails']\nexisting_user_check_var = CheckEmailForRegistration.check_email_for_registration_function(input_json['email_id'])\nmatch = re.findall(\"'Status': 'Fai...
<|body_start_0|> input_json, output_json, payload = (request.data['APIParams'], {}, {'Payload': None}) output_json['AuthenticationDetails'] = request.data['AuthenticationDetails'] existing_user_check_var = CheckEmailForRegistration.check_email_for_registration_function(input_json['email_id']) ...
This covers the API for verification of link sent on user's email for unverified user.
SignUpVerificationAPI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SignUpVerificationAPI: """This covers the API for verification of link sent on user's email for unverified user.""" def post(self, request): """Post Function to verify the link sent on user's email for unverified user.""" <|body_0|> def check_for_activation_key(self, req...
stack_v2_sparse_classes_36k_train_013772
5,154
no_license
[ { "docstring": "Post Function to verify the link sent on user's email for unverified user.", "name": "post", "signature": "def post(self, request)" }, { "docstring": "Function to check for activation key status.", "name": "check_for_activation_key", "signature": "def check_for_activation...
2
null
Implement the Python class `SignUpVerificationAPI` described below. Class description: This covers the API for verification of link sent on user's email for unverified user. Method signatures and docstrings: - def post(self, request): Post Function to verify the link sent on user's email for unverified user. - def ch...
Implement the Python class `SignUpVerificationAPI` described below. Class description: This covers the API for verification of link sent on user's email for unverified user. Method signatures and docstrings: - def post(self, request): Post Function to verify the link sent on user's email for unverified user. - def ch...
36eb9931f330e64902354c6fc471be2adf4b7049
<|skeleton|> class SignUpVerificationAPI: """This covers the API for verification of link sent on user's email for unverified user.""" def post(self, request): """Post Function to verify the link sent on user's email for unverified user.""" <|body_0|> def check_for_activation_key(self, req...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SignUpVerificationAPI: """This covers the API for verification of link sent on user's email for unverified user.""" def post(self, request): """Post Function to verify the link sent on user's email for unverified user.""" input_json, output_json, payload = (request.data['APIParams'], {}, ...
the_stack_v2_python_sparse
Generic/common/registration/api/signup_verification/views_signup_verification.py
archiemb303/common_backend_django
train
0
e7cf8eb9189aaba3a0bcd92ba39c3af2b0c95e7b
[ "ret = [0]\nfor i in range(1, len(pattern)):\n print('剛入range後i', i)\n j = ret[i - 1]\n print('j', j)\n while j > 0 and pattern[j] != pattern[i]:\n print('j', j)\n j = ret[j - 1]\n print('while j > 0 and pattern[j] != pattern[i]:時j ', j)\n print('i', 'j', i, j)\n ret.append(j ...
<|body_start_0|> ret = [0] for i in range(1, len(pattern)): print('剛入range後i', i) j = ret[i - 1] print('j', j) while j > 0 and pattern[j] != pattern[i]: print('j', j) j = ret[j - 1] print('while j > 0 and pat...
KMP
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KMP: def partial(self, pattern): """Calculate partial match table: String -> [Int]""" <|body_0|> def search(self, T, P): """KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_36k_train_013773
1,672
no_license
[ { "docstring": "Calculate partial match table: String -> [Int]", "name": "partial", "signature": "def partial(self, pattern)" }, { "docstring": "KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T", "name": "search", "signature":...
2
stack_v2_sparse_classes_30k_train_017617
Implement the Python class `KMP` described below. Class description: Implement the KMP class. Method signatures and docstrings: - def partial(self, pattern): Calculate partial match table: String -> [Int] - def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o...
Implement the Python class `KMP` described below. Class description: Implement the KMP class. Method signatures and docstrings: - def partial(self, pattern): Calculate partial match table: String -> [Int] - def search(self, T, P): KMP search main algorithm: String -> String -> [Int] Return all the matching position o...
a54bd09f4b28f106196a6cd8a0f9c056bcd237e6
<|skeleton|> class KMP: def partial(self, pattern): """Calculate partial match table: String -> [Int]""" <|body_0|> def search(self, T, P): """KMP search main algorithm: String -> String -> [Int] Return all the matching position of pattern string P in T""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KMP: def partial(self, pattern): """Calculate partial match table: String -> [Int]""" ret = [0] for i in range(1, len(pattern)): print('剛入range後i', i) j = ret[i - 1] print('j', j) while j > 0 and pattern[j] != pattern[i]: ...
the_stack_v2_python_sparse
algorithm/KMP/KMP_github.py
luyihsien/leetcodepy
train
0
77e962aba1379118a851595e611258fb5586b7d8
[ "if not board or not board[0]:\n return\nprevious = [0] * len(board[0])\nsurround = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\nfor i in range(len(board)):\n left, tmp_previous = (0, board[i].copy())\n for j in range(len(board[0])):\n sum_, tmp = (0, board[i][j])\n ...
<|body_start_0|> if not board or not board[0]: return previous = [0] * len(board[0]) surround = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for i in range(len(board)): left, tmp_previous = (0, board[i].copy()) for j in range(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def gameOfLife1(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_...
stack_v2_sparse_classes_36k_train_013774
2,741
no_license
[ { "docstring": "Do not return anything, modify board in-place instead.", "name": "gameOfLife", "signature": "def gameOfLife(self, board: List[List[int]]) -> None" }, { "docstring": "Do not return anything, modify board in-place instead.", "name": "gameOfLife1", "signature": "def gameOfLi...
2
stack_v2_sparse_classes_30k_train_014762
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gameOfLife(self, board: List[List[int]]) -> None: Do not return anything, modify board in-place instead. - def gameOfLife1(self, board: List[List[int]]) -> None: Do not retur...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def gameOfLife(self, board: List[List[int]]) -> None: Do not return anything, modify board in-place instead. - def gameOfLife1(self, board: List[List[int]]) -> None: Do not retur...
e2fecd266bfced6208694b19a2d81182b13dacd6
<|skeleton|> class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_0|> def gameOfLife1(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" <|body_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """Do not return anything, modify board in-place instead.""" if not board or not board[0]: return previous = [0] * len(board[0]) surround = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0),...
the_stack_v2_python_sparse
gameOfLife.py
HuipengXu/leetcode
train
0
2388cf20016bd1fda379a8318a9292536d36ca5c
[ "digits = [str(i) for i in range(1, n + 1)]\nk -= 1\nresult = ''\nx = n\nwhile x > 0:\n perm_per_group = factorial(x - 1)\n group, index = divmod(k, perm_per_group)\n result += digits[group]\n k = index\n x -= 1\n digits.pop(group)\nreturn result", "digits = [i for i in range(1, n + 1)]\nm, n = ...
<|body_start_0|> digits = [str(i) for i in range(1, n + 1)] k -= 1 result = '' x = n while x > 0: perm_per_group = factorial(x - 1) group, index = divmod(k, perm_per_group) result += digits[group] k = index x -= 1 ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getPermutation(self, n, k): """:type n: int :type k: int :rtype: str""" <|body_0|> def getPermutation_(self, n, k): """:type n: int :type k: int :rtype: str""" <|body_1|> <|end_skeleton|> <|body_start_0|> digits = [str(i) for i in rang...
stack_v2_sparse_classes_36k_train_013775
1,336
no_license
[ { "docstring": ":type n: int :type k: int :rtype: str", "name": "getPermutation", "signature": "def getPermutation(self, n, k)" }, { "docstring": ":type n: int :type k: int :rtype: str", "name": "getPermutation_", "signature": "def getPermutation_(self, n, k)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getPermutation(self, n, k): :type n: int :type k: int :rtype: str - def getPermutation_(self, n, k): :type n: int :type k: int :rtype: str
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getPermutation(self, n, k): :type n: int :type k: int :rtype: str - def getPermutation_(self, n, k): :type n: int :type k: int :rtype: str <|skeleton|> class Solution: ...
ef052efcbcceb38e44fdd7cbcb6a7e6bd7ff8aa2
<|skeleton|> class Solution: def getPermutation(self, n, k): """:type n: int :type k: int :rtype: str""" <|body_0|> def getPermutation_(self, n, k): """:type n: int :type k: int :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def getPermutation(self, n, k): """:type n: int :type k: int :rtype: str""" digits = [str(i) for i in range(1, n + 1)] k -= 1 result = '' x = n while x > 0: perm_per_group = factorial(x - 1) group, index = divmod(k, perm_per_gro...
the_stack_v2_python_sparse
pure_math/permutation_sequence.py
moyuanhuang/leetcode
train
2
3b712ab8074120d6a1c6f48660e9c86e5c337f51
[ "study_id = filter_params.pop('study_id', None)\nq = TaskGenomicFile.query.filter_by(**filter_params)\nfrom dataservice.api.participant.models import Participant\nfrom dataservice.api.biospecimen.models import Biospecimen\nfrom dataservice.api.genomic_file.models import GenomicFile\nfrom dataservice.api.biospecimen...
<|body_start_0|> study_id = filter_params.pop('study_id', None) q = TaskGenomicFile.query.filter_by(**filter_params) from dataservice.api.participant.models import Participant from dataservice.api.biospecimen.models import Biospecimen from dataservice.api.genomic_file.models impo...
TaskGenomicFile List API
TaskGenomicFileListAPI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskGenomicFileListAPI: """TaskGenomicFile List API""" def get(self, filter_params, after, limit): """Get a paginated task_genomic_files --- template: path: get_list.yml properties: resource: TaskGenomicFile""" <|body_0|> def post(self): """Create a new task_geno...
stack_v2_sparse_classes_36k_train_013776
5,124
permissive
[ { "docstring": "Get a paginated task_genomic_files --- template: path: get_list.yml properties: resource: TaskGenomicFile", "name": "get", "signature": "def get(self, filter_params, after, limit)" }, { "docstring": "Create a new task_genomic_file --- template: path: new_resource.yml properties: ...
2
null
Implement the Python class `TaskGenomicFileListAPI` described below. Class description: TaskGenomicFile List API Method signatures and docstrings: - def get(self, filter_params, after, limit): Get a paginated task_genomic_files --- template: path: get_list.yml properties: resource: TaskGenomicFile - def post(self): C...
Implement the Python class `TaskGenomicFileListAPI` described below. Class description: TaskGenomicFile List API Method signatures and docstrings: - def get(self, filter_params, after, limit): Get a paginated task_genomic_files --- template: path: get_list.yml properties: resource: TaskGenomicFile - def post(self): C...
36ee3fc3d1ba9d1a177274d051fb175c56dd898e
<|skeleton|> class TaskGenomicFileListAPI: """TaskGenomicFile List API""" def get(self, filter_params, after, limit): """Get a paginated task_genomic_files --- template: path: get_list.yml properties: resource: TaskGenomicFile""" <|body_0|> def post(self): """Create a new task_geno...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskGenomicFileListAPI: """TaskGenomicFile List API""" def get(self, filter_params, after, limit): """Get a paginated task_genomic_files --- template: path: get_list.yml properties: resource: TaskGenomicFile""" study_id = filter_params.pop('study_id', None) q = TaskGenomicFile.que...
the_stack_v2_python_sparse
dataservice/api/task_genomic_file/resources.py
kids-first/kf-api-dataservice
train
9
e1ce1ea2e863a738d84528aa8c22db949d1ae3e3
[ "root1 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7))\nroot2 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7))\nself.assertTrue(contains(root1, root2))", "root1 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7))\nself.assertTrue(contains(root1, root1.left))\nself.assertTrue(contains(root1, root1....
<|body_start_0|> root1 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7)) root2 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7)) self.assertTrue(contains(root1, root2)) <|end_body_0|> <|body_start_1|> root1 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7)) self.as...
unittest for tree1 contains tree2
T1ContainsT2TestCase
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class T1ContainsT2TestCase: """unittest for tree1 contains tree2""" def test_same_tree(self): """test case: test tree1 contains tree2 of same tree""" <|body_0|> def test_sub_tree(self): """test case: tree2 is subtree of tree1""" <|body_1|> def test_contain...
stack_v2_sparse_classes_36k_train_013777
2,087
no_license
[ { "docstring": "test case: test tree1 contains tree2 of same tree", "name": "test_same_tree", "signature": "def test_same_tree(self)" }, { "docstring": "test case: tree2 is subtree of tree1", "name": "test_sub_tree", "signature": "def test_sub_tree(self)" }, { "docstring": "test ...
4
stack_v2_sparse_classes_30k_train_004613
Implement the Python class `T1ContainsT2TestCase` described below. Class description: unittest for tree1 contains tree2 Method signatures and docstrings: - def test_same_tree(self): test case: test tree1 contains tree2 of same tree - def test_sub_tree(self): test case: tree2 is subtree of tree1 - def test_contain(sel...
Implement the Python class `T1ContainsT2TestCase` described below. Class description: unittest for tree1 contains tree2 Method signatures and docstrings: - def test_same_tree(self): test case: test tree1 contains tree2 of same tree - def test_sub_tree(self): test case: tree2 is subtree of tree1 - def test_contain(sel...
d08108a14042a2d8833245a8fad559cf02747edc
<|skeleton|> class T1ContainsT2TestCase: """unittest for tree1 contains tree2""" def test_same_tree(self): """test case: test tree1 contains tree2 of same tree""" <|body_0|> def test_sub_tree(self): """test case: tree2 is subtree of tree1""" <|body_1|> def test_contain...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class T1ContainsT2TestCase: """unittest for tree1 contains tree2""" def test_same_tree(self): """test case: test tree1 contains tree2 of same tree""" root1 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7)) root2 = TreeNode(val=5, left=TreeNode(3), right=TreeNode(7)) self.as...
the_stack_v2_python_sparse
coding_interview_guide/3_binary_tree/11_t1_contain_t2/test_t1_contains_t2.py
guzhoudiaoke/data_structure_and_algorithms
train
0
5a3019d7b527a261a3998ab321a087802fab86f7
[ "mcpfpp_rcs = self.env['multi.company.partner.fiscal.position.purchase'].search([('partner_id', '=', self.id), ('company_id', '=', self.env.user.company_id.id)], limit=1)\nif mcpfpp_rcs:\n self.supplier_account_position_id = mcpfpp_rcs.account_position_id.id\nelse:\n self.supplier_account_position_id = False"...
<|body_start_0|> mcpfpp_rcs = self.env['multi.company.partner.fiscal.position.purchase'].search([('partner_id', '=', self.id), ('company_id', '=', self.env.user.company_id.id)], limit=1) if mcpfpp_rcs: self.supplier_account_position_id = mcpfpp_rcs.account_position_id.id else: ...
res_partner
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class res_partner: def _get_supplier_account_position_id(self): """Fonction qui retourne la position fiscale selon la société""" <|body_0|> def write(self, vals=None): """Interdiction de changer de catégorie""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_013778
7,933
no_license
[ { "docstring": "Fonction qui retourne la position fiscale selon la société", "name": "_get_supplier_account_position_id", "signature": "def _get_supplier_account_position_id(self)" }, { "docstring": "Interdiction de changer de catégorie", "name": "write", "signature": "def write(self, va...
2
stack_v2_sparse_classes_30k_train_000106
Implement the Python class `res_partner` described below. Class description: Implement the res_partner class. Method signatures and docstrings: - def _get_supplier_account_position_id(self): Fonction qui retourne la position fiscale selon la société - def write(self, vals=None): Interdiction de changer de catégorie
Implement the Python class `res_partner` described below. Class description: Implement the res_partner class. Method signatures and docstrings: - def _get_supplier_account_position_id(self): Fonction qui retourne la position fiscale selon la société - def write(self, vals=None): Interdiction de changer de catégorie ...
eb394e1f79ba1995da2dcd81adfdd511c22caff9
<|skeleton|> class res_partner: def _get_supplier_account_position_id(self): """Fonction qui retourne la position fiscale selon la société""" <|body_0|> def write(self, vals=None): """Interdiction de changer de catégorie""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class res_partner: def _get_supplier_account_position_id(self): """Fonction qui retourne la position fiscale selon la société""" mcpfpp_rcs = self.env['multi.company.partner.fiscal.position.purchase'].search([('partner_id', '=', self.id), ('company_id', '=', self.env.user.company_id.id)], limit=1) ...
the_stack_v2_python_sparse
OpenPROD/openprod-addons/multi_company/res_partner.py
kazacube-mziouadi/ceci
train
0
5acccd5684160effd45fcb697761f550939633a9
[ "length = 0\nfor index in range(len(nums)):\n if nums[index] != val:\n nums[length] = nums[index]\n length += 1\nreturn length", "if not nums:\n return 0\nleft, right = (0, len(nums))\nwhile left < right:\n if nums[left] == val:\n nums[left] = nums[right - 1]\n right -= 1\n ...
<|body_start_0|> length = 0 for index in range(len(nums)): if nums[index] != val: nums[length] = nums[index] length += 1 return length <|end_body_0|> <|body_start_1|> if not nums: return 0 left, right = (0, len(nums)) ...
Elements
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Elements: def remove(self, nums: List[int], val: int) -> int: """Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:""" <|body_0|> def remove_(self, nums: List[int], val: int) -> int: """Approach: Two Pointers when el...
stack_v2_sparse_classes_36k_train_013779
1,179
no_license
[ { "docstring": "Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:", "name": "remove", "signature": "def remove(self, nums: List[int], val: int) -> int" }, { "docstring": "Approach: Two Pointers when elements to be removed are rare. :param nums:...
2
stack_v2_sparse_classes_30k_train_010096
Implement the Python class `Elements` described below. Class description: Implement the Elements class. Method signatures and docstrings: - def remove(self, nums: List[int], val: int) -> int: Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return: - def remove_(self, nums...
Implement the Python class `Elements` described below. Class description: Implement the Elements class. Method signatures and docstrings: - def remove(self, nums: List[int], val: int) -> int: Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return: - def remove_(self, nums...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Elements: def remove(self, nums: List[int], val: int) -> int: """Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:""" <|body_0|> def remove_(self, nums: List[int], val: int) -> int: """Approach: Two Pointers when el...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Elements: def remove(self, nums: List[int], val: int) -> int: """Approach: Two Pointers Time Complexity: O(N) Space Complexity: O(1) :param nums: :param val: :return:""" length = 0 for index in range(len(nums)): if nums[index] != val: nums[length] = nums[ind...
the_stack_v2_python_sparse
revisited/arrays/remove_elements.py
Shiv2157k/leet_code
train
1
114a946be963339ce6fb775790365727f836c884
[ "super().__init__()\nself.length = len(inputs[0])\nif not all((len(inp) == self.length for inp in inputs)):\n raise ValueError('Lengths of inputs, i.e. number of fields or embedding size, must be equal.')\nself.inputs = inputs\ninputs = []\nfor idx, inp in enumerate(self.inputs):\n self.add_module(f'Input_{id...
<|body_start_0|> super().__init__() self.length = len(inputs[0]) if not all((len(inp) == self.length for inp in inputs)): raise ValueError('Lengths of inputs, i.e. number of fields or embedding size, must be equal.') self.inputs = inputs inputs = [] for idx, i...
Base Input class for stacking of list of Base Input class in column-wise. The shape of output is :math:`(B, N_{1} + ... + N_{k}, E)`, where :math:`N_{i}` is number of fields of inputs class i.
StackedInput
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StackedInput: """Base Input class for stacking of list of Base Input class in column-wise. The shape of output is :math:`(B, N_{1} + ... + N_{k}, E)`, where :math:`N_{i}` is number of fields of inputs class i.""" def __init__(self, inputs: List[BaseInput]): """Initialize StackedInput...
stack_v2_sparse_classes_36k_train_013780
4,892
permissive
[ { "docstring": "Initialize StackedInputs Args: inputs (List[BaseInput]): list of input's layers (trs.inputs.Inputs). e.g. .. code-block:: python import torecsys as trs # initialize embedding layers used in StackedInputs single_index_emb_0 = trs.inputs.base.SingleIndexEmbedding(2, 8) single_index_emb_1 = trs.inp...
3
stack_v2_sparse_classes_30k_train_002229
Implement the Python class `StackedInput` described below. Class description: Base Input class for stacking of list of Base Input class in column-wise. The shape of output is :math:`(B, N_{1} + ... + N_{k}, E)`, where :math:`N_{i}` is number of fields of inputs class i. Method signatures and docstrings: - def __init_...
Implement the Python class `StackedInput` described below. Class description: Base Input class for stacking of list of Base Input class in column-wise. The shape of output is :math:`(B, N_{1} + ... + N_{k}, E)`, where :math:`N_{i}` is number of fields of inputs class i. Method signatures and docstrings: - def __init_...
751a43b9cd35e951d81c0d9cf46507b1777bb7ff
<|skeleton|> class StackedInput: """Base Input class for stacking of list of Base Input class in column-wise. The shape of output is :math:`(B, N_{1} + ... + N_{k}, E)`, where :math:`N_{i}` is number of fields of inputs class i.""" def __init__(self, inputs: List[BaseInput]): """Initialize StackedInput...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StackedInput: """Base Input class for stacking of list of Base Input class in column-wise. The shape of output is :math:`(B, N_{1} + ... + N_{k}, E)`, where :math:`N_{i}` is number of fields of inputs class i.""" def __init__(self, inputs: List[BaseInput]): """Initialize StackedInputs Args: input...
the_stack_v2_python_sparse
torecsys/inputs/base/stacked_inp.py
p768lwy3/torecsys
train
98
338ae2b6520b3b428bff0b53cfca80050f7c6a38
[ "with tempfile.TemporaryDirectory() as tmp_dir:\n test_repo_manager = repo_manager.RepoManager(self.curl_repo, tmp_dir)\n git_path = os.path.join(test_repo_manager.base_dir, test_repo_manager.repo_name, '.git')\n self.assertTrue(os.path.isdir(git_path))\n test_repo_manager.remove_repo()\n with self.a...
<|body_start_0|> with tempfile.TemporaryDirectory() as tmp_dir: test_repo_manager = repo_manager.RepoManager(self.curl_repo, tmp_dir) git_path = os.path.join(test_repo_manager.base_dir, test_repo_manager.repo_name, '.git') self.assertTrue(os.path.isdir(git_path)) ...
Class to test the functionality of the RepoManager class.
TestRepoManager
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestRepoManager: """Class to test the functionality of the RepoManager class.""" def test_clone_correctly(self): """Tests the correct location of the git repo.""" <|body_0|> def test_checkout_commit(self): """Tests that the git checkout command works.""" ...
stack_v2_sparse_classes_36k_train_013781
3,505
permissive
[ { "docstring": "Tests the correct location of the git repo.", "name": "test_clone_correctly", "signature": "def test_clone_correctly(self)" }, { "docstring": "Tests that the git checkout command works.", "name": "test_checkout_commit", "signature": "def test_checkout_commit(self)" }, ...
3
stack_v2_sparse_classes_30k_train_018364
Implement the Python class `TestRepoManager` described below. Class description: Class to test the functionality of the RepoManager class. Method signatures and docstrings: - def test_clone_correctly(self): Tests the correct location of the git repo. - def test_checkout_commit(self): Tests that the git checkout comma...
Implement the Python class `TestRepoManager` described below. Class description: Class to test the functionality of the RepoManager class. Method signatures and docstrings: - def test_clone_correctly(self): Tests the correct location of the git repo. - def test_checkout_commit(self): Tests that the git checkout comma...
8e2d57684bd49355b80572592c3af5cefc19a69c
<|skeleton|> class TestRepoManager: """Class to test the functionality of the RepoManager class.""" def test_clone_correctly(self): """Tests the correct location of the git repo.""" <|body_0|> def test_checkout_commit(self): """Tests that the git checkout command works.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestRepoManager: """Class to test the functionality of the RepoManager class.""" def test_clone_correctly(self): """Tests the correct location of the git repo.""" with tempfile.TemporaryDirectory() as tmp_dir: test_repo_manager = repo_manager.RepoManager(self.curl_repo, tmp_di...
the_stack_v2_python_sparse
infra/repo_manager_test.py
DeepInThought/oss-fuzz
train
2
5e52d56c3763f619a06de8225185562aa1dc113d
[ "super().__init__(weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries)\nself.unit_descriptions = unit_descriptions\nif self.entity_description.is_forecast_item:\n self.forecast_data = getattr(self.forecast_coordinator.data, 'forecast')\n self.day_data: ForecastDetailDescriptio...
<|body_start_0|> super().__init__(weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries) self.unit_descriptions = unit_descriptions if self.entity_description.is_forecast_item: self.forecast_data = getattr(self.forecast_coordinator.data, 'forecast') ...
Implementation of Weatherbit sensor.
WeatherbitSensor
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeatherbitSensor: """Implementation of Weatherbit sensor.""" def __init__(self, weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries: ConfigEntry, unit_descriptions): """Initialize an WeatherFlow sensor.""" <|body_0|> def native_value(self...
stack_v2_sparse_classes_36k_train_013782
17,617
permissive
[ { "docstring": "Initialize an WeatherFlow sensor.", "name": "__init__", "signature": "def __init__(self, weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries: ConfigEntry, unit_descriptions)" }, { "docstring": "Return the state of the sensor.", "name": "native...
4
stack_v2_sparse_classes_30k_train_003603
Implement the Python class `WeatherbitSensor` described below. Class description: Implementation of Weatherbit sensor. Method signatures and docstrings: - def __init__(self, weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries: ConfigEntry, unit_descriptions): Initialize an WeatherFlow...
Implement the Python class `WeatherbitSensor` described below. Class description: Implementation of Weatherbit sensor. Method signatures and docstrings: - def __init__(self, weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries: ConfigEntry, unit_descriptions): Initialize an WeatherFlow...
8548d9999ddd54f13d6a307e013abcb8c897a74e
<|skeleton|> class WeatherbitSensor: """Implementation of Weatherbit sensor.""" def __init__(self, weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries: ConfigEntry, unit_descriptions): """Initialize an WeatherFlow sensor.""" <|body_0|> def native_value(self...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WeatherbitSensor: """Implementation of Weatherbit sensor.""" def __init__(self, weatherbitapi, coordinator, forecast_coordinator, station_data, description, entries: ConfigEntry, unit_descriptions): """Initialize an WeatherFlow sensor.""" super().__init__(weatherbitapi, coordinator, forec...
the_stack_v2_python_sparse
custom_components/weatherbit/sensor.py
bacco007/HomeAssistantConfig
train
98
e485d15ba9140bb22e30b9c72e18bd6fd5a8b19a
[ "self.quant_bit = quant_bit\nOperatorSerializable.__init__(self)\nModule.__init__(self)\nQuantConv2d.__init__(self, in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)", "input = input....
<|body_start_0|> self.quant_bit = quant_bit OperatorSerializable.__init__(self) Module.__init__(self) QuantConv2d.__init__(self, in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias, paddi...
QuantizeConv2d Module inherit nn.Module.
QuantizeConv2d
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QuantizeConv2d: """QuantizeConv2d Module inherit nn.Module.""" def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', quant_bit=None): """Construct Identity class.""" <|body_0|> def forward(s...
stack_v2_sparse_classes_36k_train_013783
25,894
permissive
[ { "docstring": "Construct Identity class.", "name": "__init__", "signature": "def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', quant_bit=None)" }, { "docstring": "Do an inference on Identity.", "name": "for...
2
stack_v2_sparse_classes_30k_train_015005
Implement the Python class `QuantizeConv2d` described below. Class description: QuantizeConv2d Module inherit nn.Module. Method signatures and docstrings: - def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', quant_bit=None): Construct...
Implement the Python class `QuantizeConv2d` described below. Class description: QuantizeConv2d Module inherit nn.Module. Method signatures and docstrings: - def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', quant_bit=None): Construct...
e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04
<|skeleton|> class QuantizeConv2d: """QuantizeConv2d Module inherit nn.Module.""" def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', quant_bit=None): """Construct Identity class.""" <|body_0|> def forward(s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class QuantizeConv2d: """QuantizeConv2d Module inherit nn.Module.""" def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', quant_bit=None): """Construct Identity class.""" self.quant_bit = quant_bit Operato...
the_stack_v2_python_sparse
zeus/modules/operators/functions/pytorch_fn.py
huawei-noah/xingtian
train
308
e273e77b604f23b055b2fa7d8c25d16df4986e8c
[ "for patient in patientDao.fetchAllPatients():\n if patient['id'] == id:\n return patient\napi.abort(404, \"Patient {} doesn't exist\".format(id))", "patient = self.get(id)\npatientDao.deletePatient(id)\nreturn ('patient {} deleted successfully'.format(id), 200)", "currPatient = self.get(id)\nupdatedP...
<|body_start_0|> for patient in patientDao.fetchAllPatients(): if patient['id'] == id: return patient api.abort(404, "Patient {} doesn't exist".format(id)) <|end_body_0|> <|body_start_1|> patient = self.get(id) patientDao.deletePatient(id) return ('pa...
Patient
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Patient: def get(self, id): """get patient by input id""" <|body_0|> def delete(self, id): """delete a specific patient""" <|body_1|> def put(self, id): """Update a patient record""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_013784
2,957
no_license
[ { "docstring": "get patient by input id", "name": "get", "signature": "def get(self, id)" }, { "docstring": "delete a specific patient", "name": "delete", "signature": "def delete(self, id)" }, { "docstring": "Update a patient record", "name": "put", "signature": "def put...
3
stack_v2_sparse_classes_30k_train_013857
Implement the Python class `Patient` described below. Class description: Implement the Patient class. Method signatures and docstrings: - def get(self, id): get patient by input id - def delete(self, id): delete a specific patient - def put(self, id): Update a patient record
Implement the Python class `Patient` described below. Class description: Implement the Patient class. Method signatures and docstrings: - def get(self, id): get patient by input id - def delete(self, id): delete a specific patient - def put(self, id): Update a patient record <|skeleton|> class Patient: def get(...
d5aa7d822fa6b729a699cccad5a3f83f2d2a3bdb
<|skeleton|> class Patient: def get(self, id): """get patient by input id""" <|body_0|> def delete(self, id): """delete a specific patient""" <|body_1|> def put(self, id): """Update a patient record""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Patient: def get(self, id): """get patient by input id""" for patient in patientDao.fetchAllPatients(): if patient['id'] == id: return patient api.abort(404, "Patient {} doesn't exist".format(id)) def delete(self, id): """delete a specific patie...
the_stack_v2_python_sparse
apis/patient.py
Manik-Jain/EMR_API
train
0
f02e92cd35b59e74fdf3fbc59cff5fa2e379240d
[ "self.show = show\nlog.info('Looking up show: %s' % self.show)\nself.season = str(int(season))\nself.episode = str(int(episode))\nself.show_id, self.show = self.__get_show_id()\nlog.debug('Retrieved show id: %s' % self.show_id)\nlog.debug('Retrieved canonical show name: %s' % self.show)\nself.title = self.__get_epi...
<|body_start_0|> self.show = show log.info('Looking up show: %s' % self.show) self.season = str(int(season)) self.episode = str(int(episode)) self.show_id, self.show = self.__get_show_id() log.debug('Retrieved show id: %s' % self.show_id) log.debug('Retrieved cano...
TvRage
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TvRage: def __init__(self, show, season, episode): """:param show_name: The show name of the episode title to be retrieved.""" <|body_0|> def __get_show_id(self): """Retrieves the show ID of the show name passed in when the class is instantiated. :raises URLError: Ra...
stack_v2_sparse_classes_36k_train_013785
4,759
permissive
[ { "docstring": ":param show_name: The show name of the episode title to be retrieved.", "name": "__init__", "signature": "def __init__(self, show, season, episode)" }, { "docstring": "Retrieves the show ID of the show name passed in when the class is instantiated. :raises URLError: Raised when a...
3
stack_v2_sparse_classes_30k_train_006291
Implement the Python class `TvRage` described below. Class description: Implement the TvRage class. Method signatures and docstrings: - def __init__(self, show, season, episode): :param show_name: The show name of the episode title to be retrieved. - def __get_show_id(self): Retrieves the show ID of the show name pas...
Implement the Python class `TvRage` described below. Class description: Implement the TvRage class. Method signatures and docstrings: - def __init__(self, show, season, episode): :param show_name: The show name of the episode title to be retrieved. - def __get_show_id(self): Retrieves the show ID of the show name pas...
aa44757ae4e61b32acfe7260e56868d1477dc96e
<|skeleton|> class TvRage: def __init__(self, show, season, episode): """:param show_name: The show name of the episode title to be retrieved.""" <|body_0|> def __get_show_id(self): """Retrieves the show ID of the show name passed in when the class is instantiated. :raises URLError: Ra...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TvRage: def __init__(self, show, season, episode): """:param show_name: The show name of the episode title to be retrieved.""" self.show = show log.info('Looking up show: %s' % self.show) self.season = str(int(season)) self.episode = str(int(episode)) self.show_...
the_stack_v2_python_sparse
tvrenamr/lib/tvrage.py
msabramo/tvrenamr
train
0
8b723db43a5ab241fb6a084d0eeb1fd2143eed7f
[ "if isinstance(klass, ContentType):\n ct = klass\nelse:\n ct = ContentType.objects.get_for_model(klass)\nids = self.filter_for_permission_name(permission, target_obj_or_class, can_delegate=can_delegate).filter(object_type=ct).values_list('object_id', flat=True)\nreturn ct.model_class().objects.filter(id__in=i...
<|body_start_0|> if isinstance(klass, ContentType): ct = klass else: ct = ContentType.objects.get_for_model(klass) ids = self.filter_for_permission_name(permission, target_obj_or_class, can_delegate=can_delegate).filter(object_type=ct).values_list('object_id', flat=True) ...
Extends L{GenericObjectManager} to add useful functions for getting L{Permittee}s.
PermitteeManager
[ "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PermitteeManager: """Extends L{GenericObjectManager} to add useful functions for getting L{Permittee}s.""" def filter_for_class_and_permission_name(self, klass, permission, target_obj_or_class, can_delegate=False): """Return a queryset filtered for only those who own a permission for...
stack_v2_sparse_classes_36k_train_013786
21,795
permissive
[ { "docstring": "Return a queryset filtered for only those who own a permission for a particular object. Further, the returned queryset is of class given by C{klass}. @param klass: The class of the objects in the returned queryset. @type klass: C{class} or C{ContentType}. @param permission: name of the permissio...
4
null
Implement the Python class `PermitteeManager` described below. Class description: Extends L{GenericObjectManager} to add useful functions for getting L{Permittee}s. Method signatures and docstrings: - def filter_for_class_and_permission_name(self, klass, permission, target_obj_or_class, can_delegate=False): Return a ...
Implement the Python class `PermitteeManager` described below. Class description: Extends L{GenericObjectManager} to add useful functions for getting L{Permittee}s. Method signatures and docstrings: - def filter_for_class_and_permission_name(self, klass, permission, target_obj_or_class, can_delegate=False): Return a ...
059ed2b3308bda2af5e1942dc9967e6573dd6a53
<|skeleton|> class PermitteeManager: """Extends L{GenericObjectManager} to add useful functions for getting L{Permittee}s.""" def filter_for_class_and_permission_name(self, klass, permission, target_obj_or_class, can_delegate=False): """Return a queryset filtered for only those who own a permission for...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PermitteeManager: """Extends L{GenericObjectManager} to add useful functions for getting L{Permittee}s.""" def filter_for_class_and_permission_name(self, klass, permission, target_obj_or_class, can_delegate=False): """Return a queryset filtered for only those who own a permission for a particular...
the_stack_v2_python_sparse
expedient/src/python/expedient/common/permissions/managers.py
dana-i2cat/felix
train
4
5aba69e32bace2512f6077f56d4679e82f7c1586
[ "self.mailbox_vec = mailbox_vec\nself.pst_params = pst_params\nself.skip_mbx_permit_for_pst = skip_mbx_permit_for_pst\nself.target_folder_path = target_folder_path\nself.target_mailbox = target_mailbox", "if dictionary is None:\n return None\nmailbox_vec = None\nif dictionary.get('mailboxVec') != None:\n ma...
<|body_start_0|> self.mailbox_vec = mailbox_vec self.pst_params = pst_params self.skip_mbx_permit_for_pst = skip_mbx_permit_for_pst self.target_folder_path = target_folder_path self.target_mailbox = target_mailbox <|end_body_0|> <|body_start_1|> if dictionary is None: ...
Implementation of the 'RestoreOutlookParams' model. TODO: type description here. Attributes: mailbox_vec (list of RestoreOutlookParams_Mailbox): In a RestoreJob , user will provide the list of mailboxes to be restored. Provision is there for restoring full AND partial mailbox recovery. pst_params (EwsToPstConversionPar...
RestoreOutlookParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestoreOutlookParams: """Implementation of the 'RestoreOutlookParams' model. TODO: type description here. Attributes: mailbox_vec (list of RestoreOutlookParams_Mailbox): In a RestoreJob , user will provide the list of mailboxes to be restored. Provision is there for restoring full AND partial mai...
stack_v2_sparse_classes_36k_train_013787
4,261
permissive
[ { "docstring": "Constructor for the RestoreOutlookParams class", "name": "__init__", "signature": "def __init__(self, mailbox_vec=None, pst_params=None, skip_mbx_permit_for_pst=None, target_folder_path=None, target_mailbox=None)" }, { "docstring": "Creates an instance of this model from a dictio...
2
stack_v2_sparse_classes_30k_train_001911
Implement the Python class `RestoreOutlookParams` described below. Class description: Implementation of the 'RestoreOutlookParams' model. TODO: type description here. Attributes: mailbox_vec (list of RestoreOutlookParams_Mailbox): In a RestoreJob , user will provide the list of mailboxes to be restored. Provision is t...
Implement the Python class `RestoreOutlookParams` described below. Class description: Implementation of the 'RestoreOutlookParams' model. TODO: type description here. Attributes: mailbox_vec (list of RestoreOutlookParams_Mailbox): In a RestoreJob , user will provide the list of mailboxes to be restored. Provision is t...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RestoreOutlookParams: """Implementation of the 'RestoreOutlookParams' model. TODO: type description here. Attributes: mailbox_vec (list of RestoreOutlookParams_Mailbox): In a RestoreJob , user will provide the list of mailboxes to be restored. Provision is there for restoring full AND partial mai...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RestoreOutlookParams: """Implementation of the 'RestoreOutlookParams' model. TODO: type description here. Attributes: mailbox_vec (list of RestoreOutlookParams_Mailbox): In a RestoreJob , user will provide the list of mailboxes to be restored. Provision is there for restoring full AND partial mailbox recovery...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_outlook_params.py
cohesity/management-sdk-python
train
24
b4b9b3a017c348d205600bf4bdb8023fff9cd5a9
[ "data = json.dumps(kwargs)\nresp, body = self.post('tasks', data)\nself.expected_success(201, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)", "url = 'tasks'\nif kwargs:\n url += '?%s' % urllib.urlencode(kwargs)\nresp, body = self.get(url)\nself.expected_success(200, resp.st...
<|body_start_0|> data = json.dumps(kwargs) resp, body = self.post('tasks', data) self.expected_success(201, resp.status) body = json.loads(body) return rest_client.ResponseBody(resp, body) <|end_body_0|> <|body_start_1|> url = 'tasks' if kwargs: url +...
TaskClient
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskClient: def create_task(self, **kwargs): """Create a task. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/image/v2/#create-task""" <|body_0|> def list_tasks(self, **kwargs): """List tas...
stack_v2_sparse_classes_36k_train_013788
2,275
permissive
[ { "docstring": "Create a task. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/image/v2/#create-task", "name": "create_task", "signature": "def create_task(self, **kwargs)" }, { "docstring": "List tasks. For a full list...
3
null
Implement the Python class `TaskClient` described below. Class description: Implement the TaskClient class. Method signatures and docstrings: - def create_task(self, **kwargs): Create a task. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/i...
Implement the Python class `TaskClient` described below. Class description: Implement the TaskClient class. Method signatures and docstrings: - def create_task(self, **kwargs): Create a task. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/i...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class TaskClient: def create_task(self, **kwargs): """Create a task. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/image/v2/#create-task""" <|body_0|> def list_tasks(self, **kwargs): """List tas...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TaskClient: def create_task(self, **kwargs): """Create a task. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/image/v2/#create-task""" data = json.dumps(kwargs) resp, body = self.post('tasks', data) s...
the_stack_v2_python_sparse
tempest/lib/services/image/v2/tasks_client.py
openstack/tempest
train
270
2b4c0d6ccb17c055b6bdd11288f1fe69827794cd
[ "@lru_cache(maxsize=len(prices))\ndef maximize(i: int) -> int:\n if i >= len(prices):\n return 0\n max_profit = 0\n min_val = prices[i]\n max_val = prices[i]\n for j in range(i + 1, len(prices)):\n if prices[j] < min_val:\n min_val = prices[j]\n max_val = prices[j]...
<|body_start_0|> @lru_cache(maxsize=len(prices)) def maximize(i: int) -> int: if i >= len(prices): return 0 max_profit = 0 min_val = prices[i] max_val = prices[i] for j in range(i + 1, len(prices)): if prices[j] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit_dp(self, prices: List[int]) -> int: """Divide the problem: - If you select to buy and sell in [i,j] => sub-problem for [j+2, n] - Find the maximum you can do by trying systematically all possibilities => Complexity is in the O(N**2) maximum""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_013789
2,553
no_license
[ { "docstring": "Divide the problem: - If you select to buy and sell in [i,j] => sub-problem for [j+2, n] - Find the maximum you can do by trying systematically all possibilities => Complexity is in the O(N**2) maximum", "name": "maxProfit_dp", "signature": "def maxProfit_dp(self, prices: List[int]) -> i...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit_dp(self, prices: List[int]) -> int: Divide the problem: - If you select to buy and sell in [i,j] => sub-problem for [j+2, n] - Find the maximum you can do by trying...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit_dp(self, prices: List[int]) -> int: Divide the problem: - If you select to buy and sell in [i,j] => sub-problem for [j+2, n] - Find the maximum you can do by trying...
3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8
<|skeleton|> class Solution: def maxProfit_dp(self, prices: List[int]) -> int: """Divide the problem: - If you select to buy and sell in [i,j] => sub-problem for [j+2, n] - Find the maximum you can do by trying systematically all possibilities => Complexity is in the O(N**2) maximum""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def maxProfit_dp(self, prices: List[int]) -> int: """Divide the problem: - If you select to buy and sell in [i,j] => sub-problem for [j+2, n] - Find the maximum you can do by trying systematically all possibilities => Complexity is in the O(N**2) maximum""" @lru_cache(maxsize=len(pri...
the_stack_v2_python_sparse
stocks/WithCoolDown.py
QuentinDuval/PythonExperiments
train
3
0ff636fc4dda7402f0c82b3949ea44233b392e99
[ "self.nFichier = nomFichier\nself.strOut = f'Analyse du fichier {self.nFichier} :\\n'\nself.trames = lectureOctets(nomFichier)", "strOuts = list()\nfor numTrame, trame in enumerate(self.trames):\n trame, strOut, estIPV4 = trameEthernet(trame)\n strOut.replace('\\n', '\\n\\t')\n if not estIPV4:\n s...
<|body_start_0|> self.nFichier = nomFichier self.strOut = f'Analyse du fichier {self.nFichier} :\n' self.trames = lectureOctets(nomFichier) <|end_body_0|> <|body_start_1|> strOuts = list() for numTrame, trame in enumerate(self.trames): trame, strOut, estIPV4 = trameE...
ProtocolAnalyser va récupérer et analyser la trame En utilisant les différents fonctions d'analyse
ProtocolAnalyser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProtocolAnalyser: """ProtocolAnalyser va récupérer et analyser la trame En utilisant les différents fonctions d'analyse""" def __init__(self, nomFichier: str): """ProtocolAnalyser(nomFichier : str) -> ProtocolAnalyser Object nomFichier""" <|body_0|> def analyse(self): ...
stack_v2_sparse_classes_36k_train_013790
2,446
no_license
[ { "docstring": "ProtocolAnalyser(nomFichier : str) -> ProtocolAnalyser Object nomFichier", "name": "__init__", "signature": "def __init__(self, nomFichier: str)" }, { "docstring": "ProtocolAnalyser.analyse() -> list[str] Retourne une liste de str repésentant l'analyse", "name": "analyse", ...
2
stack_v2_sparse_classes_30k_val_000573
Implement the Python class `ProtocolAnalyser` described below. Class description: ProtocolAnalyser va récupérer et analyser la trame En utilisant les différents fonctions d'analyse Method signatures and docstrings: - def __init__(self, nomFichier: str): ProtocolAnalyser(nomFichier : str) -> ProtocolAnalyser Object no...
Implement the Python class `ProtocolAnalyser` described below. Class description: ProtocolAnalyser va récupérer et analyser la trame En utilisant les différents fonctions d'analyse Method signatures and docstrings: - def __init__(self, nomFichier: str): ProtocolAnalyser(nomFichier : str) -> ProtocolAnalyser Object no...
ef71a890c1510ddf614b41a75aeeb1667954a99f
<|skeleton|> class ProtocolAnalyser: """ProtocolAnalyser va récupérer et analyser la trame En utilisant les différents fonctions d'analyse""" def __init__(self, nomFichier: str): """ProtocolAnalyser(nomFichier : str) -> ProtocolAnalyser Object nomFichier""" <|body_0|> def analyse(self): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProtocolAnalyser: """ProtocolAnalyser va récupérer et analyser la trame En utilisant les différents fonctions d'analyse""" def __init__(self, nomFichier: str): """ProtocolAnalyser(nomFichier : str) -> ProtocolAnalyser Object nomFichier""" self.nFichier = nomFichier self.strOut = f...
the_stack_v2_python_sparse
core.py
T-Shai/lite-wireshark-clone
train
0
6f91d47659a9ec242d4cb42f02a6de6f1b296116
[ "table_object = Tag.query.get_or_404(int_id)\nform = TagForm(obj=table_object)\ntemplate_return = flask.render_template('edit.html', form=form)\nreturn template_return", "table_object = Tag.query.get_or_404(int_id)\nform = TagForm(obj=table_object)\nif form.validate_on_submit():\n form.populate_obj(table_objec...
<|body_start_0|> table_object = Tag.query.get_or_404(int_id) form = TagForm(obj=table_object) template_return = flask.render_template('edit.html', form=form) return template_return <|end_body_0|> <|body_start_1|> table_object = Tag.query.get_or_404(int_id) form = TagForm...
EditTagResource
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EditTagResource: def get(self, int_id): """Args: int_id: Returns:""" <|body_0|> def post(self, int_id): """Args: int_id: Returns:""" <|body_1|> <|end_skeleton|> <|body_start_0|> table_object = Tag.query.get_or_404(int_id) form = TagForm(obj=...
stack_v2_sparse_classes_36k_train_013791
3,873
no_license
[ { "docstring": "Args: int_id: Returns:", "name": "get", "signature": "def get(self, int_id)" }, { "docstring": "Args: int_id: Returns:", "name": "post", "signature": "def post(self, int_id)" } ]
2
stack_v2_sparse_classes_30k_train_004149
Implement the Python class `EditTagResource` described below. Class description: Implement the EditTagResource class. Method signatures and docstrings: - def get(self, int_id): Args: int_id: Returns: - def post(self, int_id): Args: int_id: Returns:
Implement the Python class `EditTagResource` described below. Class description: Implement the EditTagResource class. Method signatures and docstrings: - def get(self, int_id): Args: int_id: Returns: - def post(self, int_id): Args: int_id: Returns: <|skeleton|> class EditTagResource: def get(self, int_id): ...
865403e3b1717226b25c9d64aeb4c35c7220e7e3
<|skeleton|> class EditTagResource: def get(self, int_id): """Args: int_id: Returns:""" <|body_0|> def post(self, int_id): """Args: int_id: Returns:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class EditTagResource: def get(self, int_id): """Args: int_id: Returns:""" table_object = Tag.query.get_or_404(int_id) form = TagForm(obj=table_object) template_return = flask.render_template('edit.html', form=form) return template_return def post(self, int_id): ...
the_stack_v2_python_sparse
things_organizer/web_app/tags/resources.py
yeyeto2788/Things-Organizer
train
11
d5efa6ff0d0bc190951eab8e986435d63f523567
[ "super(ErrorCalculator, self).__init__()\nself.report_cer = report_cer\nself.report_wer = report_wer\nself.char_list = char_list\nself.space = sym_space\nself.blank = sym_blank\nif self.blank in self.char_list:\n self.idx_blank = self.char_list.index(self.blank)\nelse:\n self.idx_blank = None\nif self.space i...
<|body_start_0|> super(ErrorCalculator, self).__init__() self.report_cer = report_cer self.report_wer = report_wer self.char_list = char_list self.space = sym_space self.blank = sym_blank if self.blank in self.char_list: self.idx_blank = self.char_list...
Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: :param sym_space: :param sym_blank: :return:
ErrorCalculator
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ErrorCalculator: """Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: :param sym_space: :param sym_blank: :return:""" def __init__(self, char_list, sym_space, s...
stack_v2_sparse_classes_36k_train_013792
8,773
permissive
[ { "docstring": "Construct an ErrorCalculator object.", "name": "__init__", "signature": "def __init__(self, char_list, sym_space, sym_blank, report_cer=False, report_wer=False)" }, { "docstring": "Calculate sentence-level WER/CER score. :param torch.Tensor ys_hat: prediction (batch, seqlen) :par...
6
stack_v2_sparse_classes_30k_train_008362
Implement the Python class `ErrorCalculator` described below. Class description: Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: :param sym_space: :param sym_blank: :return: Method sig...
Implement the Python class `ErrorCalculator` described below. Class description: Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: :param sym_space: :param sym_blank: :return: Method sig...
bcd20948db7846ee523443ef9fd78c7a1248c95e
<|skeleton|> class ErrorCalculator: """Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: :param sym_space: :param sym_blank: :return:""" def __init__(self, char_list, sym_space, s...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ErrorCalculator: """Calculate CER and WER for E2E_ASR and CTC models during training. :param y_hats: numpy array with predicted text :param y_pads: numpy array with true (target) text :param char_list: :param sym_space: :param sym_blank: :return:""" def __init__(self, char_list, sym_space, sym_blank, rep...
the_stack_v2_python_sparse
espnet/nets/e2e_asr_common.py
espnet/espnet
train
7,242
d0e7af811b4f439da0ead90bd784ac32d479f46a
[ "mapping_dict = mapping.get_field_mapping_dict()\napproved_dict = {input: (output, approved) for input, (output, approved) in mapping_dict.items() if approved == APPROVED}\nreturn FieldMapping.from_dict(approved_dict)", "if remove_unapproved_source_mappings:\n source_mapping = FieldMappingResolver._remove_unap...
<|body_start_0|> mapping_dict = mapping.get_field_mapping_dict() approved_dict = {input: (output, approved) for input, (output, approved) in mapping_dict.items() if approved == APPROVED} return FieldMapping.from_dict(approved_dict) <|end_body_0|> <|body_start_1|> if remove_unapproved_so...
FieldMappingResolver
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FieldMappingResolver: def _remove_unapproved_mappings(mapping: FieldMapping): """Removes unnaproved mappings from a FieldMapping.""" <|body_0|> def _resolve_mapping(new_mapping: FieldMapping, source_mapping: FieldMapping, overwrite: bool=False, remove_unapproved_source_mappi...
stack_v2_sparse_classes_36k_train_013793
2,895
permissive
[ { "docstring": "Removes unnaproved mappings from a FieldMapping.", "name": "_remove_unapproved_mappings", "signature": "def _remove_unapproved_mappings(mapping: FieldMapping)" }, { "docstring": "Combines source and new field mappings. May overwrite source mappings or remove unapproved source map...
3
stack_v2_sparse_classes_30k_test_000261
Implement the Python class `FieldMappingResolver` described below. Class description: Implement the FieldMappingResolver class. Method signatures and docstrings: - def _remove_unapproved_mappings(mapping: FieldMapping): Removes unnaproved mappings from a FieldMapping. - def _resolve_mapping(new_mapping: FieldMapping,...
Implement the Python class `FieldMappingResolver` described below. Class description: Implement the FieldMappingResolver class. Method signatures and docstrings: - def _remove_unapproved_mappings(mapping: FieldMapping): Removes unnaproved mappings from a FieldMapping. - def _resolve_mapping(new_mapping: FieldMapping,...
2c6eef098c902ed5e074e98b0419affacfa4d6ca
<|skeleton|> class FieldMappingResolver: def _remove_unapproved_mappings(mapping: FieldMapping): """Removes unnaproved mappings from a FieldMapping.""" <|body_0|> def _resolve_mapping(new_mapping: FieldMapping, source_mapping: FieldMapping, overwrite: bool=False, remove_unapproved_source_mappi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FieldMappingResolver: def _remove_unapproved_mappings(mapping: FieldMapping): """Removes unnaproved mappings from a FieldMapping.""" mapping_dict = mapping.get_field_mapping_dict() approved_dict = {input: (output, approved) for input, (output, approved) in mapping_dict.items() if appro...
the_stack_v2_python_sparse
etl/helpers/field_mapping/resolver.py
GIIMSC/goodwilldatainitiative-etl
train
0
bdeeae3d262cf069d26a89adb49b3094b82d7944
[ "api_token_model = self.api_token_model\nassert api_token_model is not None\nif not token:\n return None\nqueryset = api_token_model.objects.filter(token=token).select_related('user')\ntry:\n webapi_token = queryset.get()\nexcept api_token_model.DoesNotExist:\n return None\nuser = webapi_token.user\nif not...
<|body_start_0|> api_token_model = self.api_token_model assert api_token_model is not None if not token: return None queryset = api_token_model.objects.filter(token=token).select_related('user') try: webapi_token = queryset.get() except api_token_m...
Mixin for a standard auth backend for API token authentication. This will handle authenticating users and their API tokens for API requests. It's only used for API requests that specify a username and a token. This class is meant to be subclassed and mixed in to another Django auth backend (note: not a :py:class:`~djbl...
TokenAuthBackendMixin
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TokenAuthBackendMixin: """Mixin for a standard auth backend for API token authentication. This will handle authenticating users and their API tokens for API requests. It's only used for API requests that specify a username and a token. This class is meant to be subclassed and mixed in to another ...
stack_v2_sparse_classes_36k_train_013794
12,956
no_license
[ { "docstring": "Authenticate a user, given a token ID. Args: request (django.http.HttpRequest, unused): The request object. token (unicode, optional): The API token ID to authenticate with. **kwargs (dict, unused): Keyword arguments for future expansion. Returns: django.contrib.auth.models.User: The resulting u...
2
stack_v2_sparse_classes_30k_train_009105
Implement the Python class `TokenAuthBackendMixin` described below. Class description: Mixin for a standard auth backend for API token authentication. This will handle authenticating users and their API tokens for API requests. It's only used for API requests that specify a username and a token. This class is meant to...
Implement the Python class `TokenAuthBackendMixin` described below. Class description: Mixin for a standard auth backend for API token authentication. This will handle authenticating users and their API tokens for API requests. It's only used for API requests that specify a username and a token. This class is meant to...
99ea69d80a3a393b0da4da3152ef26e808dd8487
<|skeleton|> class TokenAuthBackendMixin: """Mixin for a standard auth backend for API token authentication. This will handle authenticating users and their API tokens for API requests. It's only used for API requests that specify a username and a token. This class is meant to be subclassed and mixed in to another ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TokenAuthBackendMixin: """Mixin for a standard auth backend for API token authentication. This will handle authenticating users and their API tokens for API requests. It's only used for API requests that specify a username and a token. This class is meant to be subclassed and mixed in to another Django auth b...
the_stack_v2_python_sparse
djblets/webapi/auth/backends/api_tokens.py
chipx86/djblets
train
2
baf53e7da6ecad69cd56647b7e9a54103e28fb5d
[ "num_issues = ProcessingIssue.objects.filter(project=project).count()\nlast_seen = ProcessingIssue.objects.filter(project=project).order_by('-datetime').first()\nresolveable_issues, has_more = ProcessingIssue.objects.find_resolved(project_id=project.id)\nreprocessing_issues = ReprocessingReport.objects.filter(proje...
<|body_start_0|> num_issues = ProcessingIssue.objects.filter(project=project).count() last_seen = ProcessingIssue.objects.filter(project=project).order_by('-datetime').first() resolveable_issues, has_more = ProcessingIssue.objects.find_resolved(project_id=project.id) reprocessing_issues ...
ProjectProcessingIssuesEndpoint
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProjectProcessingIssuesEndpoint: def get(self, request, project): """List a project's processing issues.""" <|body_0|> def delete(self, request, project): """This deletes all open processing issues and triggers reprocessing if the user disabled the checkbox""" ...
stack_v2_sparse_classes_36k_train_013795
4,504
permissive
[ { "docstring": "List a project's processing issues.", "name": "get", "signature": "def get(self, request, project)" }, { "docstring": "This deletes all open processing issues and triggers reprocessing if the user disabled the checkbox", "name": "delete", "signature": "def delete(self, re...
2
stack_v2_sparse_classes_30k_train_008863
Implement the Python class `ProjectProcessingIssuesEndpoint` described below. Class description: Implement the ProjectProcessingIssuesEndpoint class. Method signatures and docstrings: - def get(self, request, project): List a project's processing issues. - def delete(self, request, project): This deletes all open pro...
Implement the Python class `ProjectProcessingIssuesEndpoint` described below. Class description: Implement the ProjectProcessingIssuesEndpoint class. Method signatures and docstrings: - def get(self, request, project): List a project's processing issues. - def delete(self, request, project): This deletes all open pro...
b937615079d7b24dc225a83b99b1b65da932fc66
<|skeleton|> class ProjectProcessingIssuesEndpoint: def get(self, request, project): """List a project's processing issues.""" <|body_0|> def delete(self, request, project): """This deletes all open processing issues and triggers reprocessing if the user disabled the checkbox""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProjectProcessingIssuesEndpoint: def get(self, request, project): """List a project's processing issues.""" num_issues = ProcessingIssue.objects.filter(project=project).count() last_seen = ProcessingIssue.objects.filter(project=project).order_by('-datetime').first() resolveable...
the_stack_v2_python_sparse
src/sentry/api/endpoints/project_processingissues.py
atlassian/sentry
train
1
76dc655443d97b04ba4b0f17cc54bfc5137d1885
[ "if constraints == None:\n constraints = []\nChain.__init__(self, constraints)", "for const in self._constraints:\n if const.is_valid(value):\n return True\nreturn False" ]
<|body_start_0|> if constraints == None: constraints = [] Chain.__init__(self, constraints) <|end_body_0|> <|body_start_1|> for const in self._constraints: if const.is_valid(value): return True return False <|end_body_1|>
Rappresenta una And Chain di condizioni sugli attributi
OrChain
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OrChain: """Rappresenta una And Chain di condizioni sugli attributi""" def __init__(self, constraints=None): """Constructor""" <|body_0|> def is_valid(self, value): """La chain e' vera non appena la prima condizione vera e' trovata nella lista""" <|body_1...
stack_v2_sparse_classes_36k_train_013796
684
no_license
[ { "docstring": "Constructor", "name": "__init__", "signature": "def __init__(self, constraints=None)" }, { "docstring": "La chain e' vera non appena la prima condizione vera e' trovata nella lista", "name": "is_valid", "signature": "def is_valid(self, value)" } ]
2
stack_v2_sparse_classes_30k_train_019674
Implement the Python class `OrChain` described below. Class description: Rappresenta una And Chain di condizioni sugli attributi Method signatures and docstrings: - def __init__(self, constraints=None): Constructor - def is_valid(self, value): La chain e' vera non appena la prima condizione vera e' trovata nella list...
Implement the Python class `OrChain` described below. Class description: Rappresenta una And Chain di condizioni sugli attributi Method signatures and docstrings: - def __init__(self, constraints=None): Constructor - def is_valid(self, value): La chain e' vera non appena la prima condizione vera e' trovata nella list...
468a9ba295ab658670472a0156772f428d7f3fe4
<|skeleton|> class OrChain: """Rappresenta una And Chain di condizioni sugli attributi""" def __init__(self, constraints=None): """Constructor""" <|body_0|> def is_valid(self, value): """La chain e' vera non appena la prima condizione vera e' trovata nella lista""" <|body_1...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OrChain: """Rappresenta una And Chain di condizioni sugli attributi""" def __init__(self, constraints=None): """Constructor""" if constraints == None: constraints = [] Chain.__init__(self, constraints) def is_valid(self, value): """La chain e' vera non app...
the_stack_v2_python_sparse
src/icse/ps/constraints/OrChain.py
ximarx/icse-ps
train
0
2059ff505cc63f7bbe28b28affec0d65d9281b96
[ "self.fetch_snapshot_metadata_disabled = fetch_snapshot_metadata_disabled\nself.notify_backup_complete_disabled = notify_backup_complete_disabled\nself.vss_copy_only_backup = vss_copy_only_backup\nself.vss_excluded_writers = vss_excluded_writers", "if dictionary is None:\n return None\nfetch_snapshot_metadata_...
<|body_start_0|> self.fetch_snapshot_metadata_disabled = fetch_snapshot_metadata_disabled self.notify_backup_complete_disabled = notify_backup_complete_disabled self.vss_copy_only_backup = vss_copy_only_backup self.vss_excluded_writers = vss_excluded_writers <|end_body_0|> <|body_start_...
Implementation of the 'PhysicalSnapshotParams' model. This message contains params that controls the snapshot process for a physical host. Attributes: fetch_snapshot_metadata_disabled (bool): Whether fetching and storing of snapshot metadata was disabled. notify_backup_complete_disabled (bool): Whether notify backup co...
PhysicalSnapshotParams
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PhysicalSnapshotParams: """Implementation of the 'PhysicalSnapshotParams' model. This message contains params that controls the snapshot process for a physical host. Attributes: fetch_snapshot_metadata_disabled (bool): Whether fetching and storing of snapshot metadata was disabled. notify_backup_...
stack_v2_sparse_classes_36k_train_013797
2,812
permissive
[ { "docstring": "Constructor for the PhysicalSnapshotParams class", "name": "__init__", "signature": "def __init__(self, fetch_snapshot_metadata_disabled=None, notify_backup_complete_disabled=None, vss_copy_only_backup=None, vss_excluded_writers=None)" }, { "docstring": "Creates an instance of th...
2
null
Implement the Python class `PhysicalSnapshotParams` described below. Class description: Implementation of the 'PhysicalSnapshotParams' model. This message contains params that controls the snapshot process for a physical host. Attributes: fetch_snapshot_metadata_disabled (bool): Whether fetching and storing of snapsho...
Implement the Python class `PhysicalSnapshotParams` described below. Class description: Implementation of the 'PhysicalSnapshotParams' model. This message contains params that controls the snapshot process for a physical host. Attributes: fetch_snapshot_metadata_disabled (bool): Whether fetching and storing of snapsho...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class PhysicalSnapshotParams: """Implementation of the 'PhysicalSnapshotParams' model. This message contains params that controls the snapshot process for a physical host. Attributes: fetch_snapshot_metadata_disabled (bool): Whether fetching and storing of snapshot metadata was disabled. notify_backup_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PhysicalSnapshotParams: """Implementation of the 'PhysicalSnapshotParams' model. This message contains params that controls the snapshot process for a physical host. Attributes: fetch_snapshot_metadata_disabled (bool): Whether fetching and storing of snapshot metadata was disabled. notify_backup_complete_disa...
the_stack_v2_python_sparse
cohesity_management_sdk/models/physical_snapshot_params.py
cohesity/management-sdk-python
train
24
d7bd582f19fca523ea8fb6c125588eea41f29403
[ "self._request_msg = request_msg\nself._response_msg = response_msg\nhttp.HttpMessageWriter.__init__(self, sock, response_msg, write_timeout)", "if self._request_msg.start_line:\n request_method = self._request_msg.start_line.method\nelse:\n request_method = None\nresponse_code = self._response_msg.start_li...
<|body_start_0|> self._request_msg = request_msg self._response_msg = response_msg http.HttpMessageWriter.__init__(self, sock, response_msg, write_timeout) <|end_body_0|> <|body_start_1|> if self._request_msg.start_line: request_method = self._request_msg.start_line.method ...
Writes an HTTP response to client.
_HttpServerToClientMessageWriter
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class _HttpServerToClientMessageWriter: """Writes an HTTP response to client.""" def __init__(self, sock, request_msg, response_msg, write_timeout): """Writes the response to the client. @type sock: socket @param sock: Target socket @type request_msg: http.HttpMessage @param request_msg: R...
stack_v2_sparse_classes_36k_train_013798
20,673
permissive
[ { "docstring": "Writes the response to the client. @type sock: socket @param sock: Target socket @type request_msg: http.HttpMessage @param request_msg: Request message, required to determine whether response may have a message body @type response_msg: http.HttpMessage @param response_msg: Response message @typ...
2
null
Implement the Python class `_HttpServerToClientMessageWriter` described below. Class description: Writes an HTTP response to client. Method signatures and docstrings: - def __init__(self, sock, request_msg, response_msg, write_timeout): Writes the response to the client. @type sock: socket @param sock: Target socket ...
Implement the Python class `_HttpServerToClientMessageWriter` described below. Class description: Writes an HTTP response to client. Method signatures and docstrings: - def __init__(self, sock, request_msg, response_msg, write_timeout): Writes the response to the client. @type sock: socket @param sock: Target socket ...
456ea285a7583183c2c8e5bcffe9006ec8a9d658
<|skeleton|> class _HttpServerToClientMessageWriter: """Writes an HTTP response to client.""" def __init__(self, sock, request_msg, response_msg, write_timeout): """Writes the response to the client. @type sock: socket @param sock: Target socket @type request_msg: http.HttpMessage @param request_msg: R...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class _HttpServerToClientMessageWriter: """Writes an HTTP response to client.""" def __init__(self, sock, request_msg, response_msg, write_timeout): """Writes the response to the client. @type sock: socket @param sock: Target socket @type request_msg: http.HttpMessage @param request_msg: Request messag...
the_stack_v2_python_sparse
lib/http/server.py
ganeti/ganeti
train
465
caa0f6e81d8b6908bfa1eba5fbecc64271a56bd6
[ "hash_map = {}\nfor i, n in enumerate(nums):\n for d in range(t + 1):\n if n - d in hash_map and i - hash_map[abs(n - d)] <= k:\n return True\n elif n + d in hash_map and i - hash_map[n + d] <= k:\n return True\n hash_map[n] = i\nreturn False", "if k == 0:\n return Fal...
<|body_start_0|> hash_map = {} for i, n in enumerate(nums): for d in range(t + 1): if n - d in hash_map and i - hash_map[abs(n - d)] <= k: return True elif n + d in hash_map and i - hash_map[n + d] <= k: return True ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def containsNearbyAlmostDuplicate_TLE(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" <|body_0|> def containsNearbyAlmostDuplicate(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" ...
stack_v2_sparse_classes_36k_train_013799
3,134
no_license
[ { "docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool", "name": "containsNearbyAlmostDuplicate_TLE", "signature": "def containsNearbyAlmostDuplicate_TLE(self, nums, k, t)" }, { "docstring": ":type nums: List[int] :type k: int :type t: int :rtype: bool", "name": "contai...
2
stack_v2_sparse_classes_30k_train_016427
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyAlmostDuplicate_TLE(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool - def containsNearbyAlmostDuplicate(self, nums, k, t): :type...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def containsNearbyAlmostDuplicate_TLE(self, nums, k, t): :type nums: List[int] :type k: int :type t: int :rtype: bool - def containsNearbyAlmostDuplicate(self, nums, k, t): :type...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def containsNearbyAlmostDuplicate_TLE(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" <|body_0|> def containsNearbyAlmostDuplicate(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def containsNearbyAlmostDuplicate_TLE(self, nums, k, t): """:type nums: List[int] :type k: int :type t: int :rtype: bool""" hash_map = {} for i, n in enumerate(nums): for d in range(t + 1): if n - d in hash_map and i - hash_map[abs(n - d)] <= k: ...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00220.Contains Duplicate III.py
roger6blog/LeetCode
train
0