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
c7e12d9df2dee2eade1f090e6e027940570e26b9
[ "self._true_mean = Config.get_param(config, 'true_mean')\nif Config.has_key(config, 'std_deviation'):\n self._std_deviation = Config.get_param(config, 'std_deviation')\nelse:\n self._std_deviation = None\nself._significance_level = Config.get_param(config, 'significance_level')", "if len(deviation) is not 1...
<|body_start_0|> self._true_mean = Config.get_param(config, 'true_mean') if Config.has_key(config, 'std_deviation'): self._std_deviation = Config.get_param(config, 'std_deviation') else: self._std_deviation = None self._significance_level = Config.get_param(config...
Base class for student t test.
StudentTTest
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StudentTTest: """Base class for student t test.""" def __init__(self, config): """Constructor for a new hypothesis by using the student t test. It includes the value, the deviation and the number of samples. :param config: Configuration from yaml file""" <|body_0|> def c...
stack_v2_sparse_classes_36k_train_024700
2,054
permissive
[ { "docstring": "Constructor for a new hypothesis by using the student t test. It includes the value, the deviation and the number of samples. :param config: Configuration from yaml file", "name": "__init__", "signature": "def __init__(self, config)" }, { "docstring": "Check if the given informat...
2
null
Implement the Python class `StudentTTest` described below. Class description: Base class for student t test. Method signatures and docstrings: - def __init__(self, config): Constructor for a new hypothesis by using the student t test. It includes the value, the deviation and the number of samples. :param config: Conf...
Implement the Python class `StudentTTest` described below. Class description: Base class for student t test. Method signatures and docstrings: - def __init__(self, config): Constructor for a new hypothesis by using the student t test. It includes the value, the deviation and the number of samples. :param config: Conf...
2f66e226fc335ae357001d07fbc74d30ab469509
<|skeleton|> class StudentTTest: """Base class for student t test.""" def __init__(self, config): """Constructor for a new hypothesis by using the student t test. It includes the value, the deviation and the number of samples. :param config: Configuration from yaml file""" <|body_0|> def c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StudentTTest: """Base class for student t test.""" def __init__(self, config): """Constructor for a new hypothesis by using the student t test. It includes the value, the deviation and the number of samples. :param config: Configuration from yaml file""" self._true_mean = Config.get_param...
the_stack_v2_python_sparse
tug_observers/tug_observer_plugins/tug_observer_plugin_utils/scripts/hypothesis_check/single_value_hypothesis_check/student_t_test.py
annarosejohny/Model_based_diagnosis
train
0
e094adcc06d95287efec38b54ea8121981a9f329
[ "return_data = []\nfor minion_id in minions:\n try:\n history = salt_returns.objects.filter(id=minion_id)\n for job in history:\n full_ret = job.full_ret\n return_data.append({'id': job.id, 'full_ret': full_ret, 'fun': job.fun, 'jid': job.jid, 'comment': job.return_value, 'suc...
<|body_start_0|> return_data = [] for minion_id in minions: try: history = salt_returns.objects.filter(id=minion_id) for job in history: full_ret = job.full_ret return_data.append({'id': job.id, 'full_ret': full_ret, 'fu...
API to retrieve data from salt_returns for a group of minions
JobHistoryListView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JobHistoryListView: """API to retrieve data from salt_returns for a group of minions""" def get_minion_job_history(self, minions, page_number): """Loop through minions and get their job history. Then parse it a bit.""" <|body_0|> def list(self, request, *args, **kwargs):...
stack_v2_sparse_classes_36k_train_024701
47,872
no_license
[ { "docstring": "Loop through minions and get their job history. Then parse it a bit.", "name": "get_minion_job_history", "signature": "def get_minion_job_history(self, minions, page_number)" }, { "docstring": "Since we have two different front ends sending data, we need some awkward logic to see...
2
stack_v2_sparse_classes_30k_test_000350
Implement the Python class `JobHistoryListView` described below. Class description: API to retrieve data from salt_returns for a group of minions Method signatures and docstrings: - def get_minion_job_history(self, minions, page_number): Loop through minions and get their job history. Then parse it a bit. - def list(...
Implement the Python class `JobHistoryListView` described below. Class description: API to retrieve data from salt_returns for a group of minions Method signatures and docstrings: - def get_minion_job_history(self, minions, page_number): Loop through minions and get their job history. Then parse it a bit. - def list(...
122a172caea82ef660e81a9dfc6377afd731f9cb
<|skeleton|> class JobHistoryListView: """API to retrieve data from salt_returns for a group of minions""" def get_minion_job_history(self, minions, page_number): """Loop through minions and get their job history. Then parse it a bit.""" <|body_0|> def list(self, request, *args, **kwargs):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JobHistoryListView: """API to retrieve data from salt_returns for a group of minions""" def get_minion_job_history(self, minions, page_number): """Loop through minions and get their job history. Then parse it a bit.""" return_data = [] for minion_id in minions: try: ...
the_stack_v2_python_sparse
sso/files/gui/sse/job/views.py
nofxrok/headless
train
1
747feffffdba33029a438093fb583d517282eed6
[ "super().__init__(name=name)\nif 'name' in parameters:\n raise ValueError('Cannot have parameter named str(name)')\nself._parameters = dict()\nif parameters:\n self._create_attributes(parameters)", "for param_name in parameters:\n param_value = parameters[param_name]\n setattr(self, param_name, param_...
<|body_start_0|> super().__init__(name=name) if 'name' in parameters: raise ValueError('Cannot have parameter named str(name)') self._parameters = dict() if parameters: self._create_attributes(parameters) <|end_body_0|> <|body_start_1|> for param_name in ...
Abstract class that encapsulates a meta instrument. A meta instrument can take many forms. It may be composed of many physical instruments. It may be an element of an experiment that is controlled by multiple physical instruments. It might even correspond to a model of a physical or simulated system. Typically, all met...
MetaInstrument
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetaInstrument: """Abstract class that encapsulates a meta instrument. A meta instrument can take many forms. It may be composed of many physical instruments. It may be an element of an experiment that is controlled by multiple physical instruments. It might even correspond to a model of a physic...
stack_v2_sparse_classes_36k_train_024702
5,014
no_license
[ { "docstring": "Args: name (str): the name of this meta instrument.", "name": "__init__", "signature": "def __init__(self, name: str, **parameters)" }, { "docstring": "Set every parameter as an attribute. Meant to be called once within the __init__() method. Very useful when initialising objects...
2
null
Implement the Python class `MetaInstrument` described below. Class description: Abstract class that encapsulates a meta instrument. A meta instrument can take many forms. It may be composed of many physical instruments. It may be an element of an experiment that is controlled by multiple physical instruments. It might...
Implement the Python class `MetaInstrument` described below. Class description: Abstract class that encapsulates a meta instrument. A meta instrument can take many forms. It may be composed of many physical instruments. It may be an element of an experiment that is controlled by multiple physical instruments. It might...
b1f8e742df003f1d4ed7962353f8646740592f7d
<|skeleton|> class MetaInstrument: """Abstract class that encapsulates a meta instrument. A meta instrument can take many forms. It may be composed of many physical instruments. It may be an element of an experiment that is controlled by multiple physical instruments. It might even correspond to a model of a physic...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MetaInstrument: """Abstract class that encapsulates a meta instrument. A meta instrument can take many forms. It may be composed of many physical instruments. It may be an element of an experiment that is controlled by multiple physical instruments. It might even correspond to a model of a physical or simulat...
the_stack_v2_python_sparse
codebase/instruments/instrument.py
qcrew-lab/qcore
train
1
b080de6d27ec1cefd589f4f3af5342efa604fffe
[ "session = create_session()\nif field.data in [phone[0] for phone in session.query(User.phone_number).all()]:\n raise ValidationError('Пользователь с таким номером телефона уже существует')", "session = create_session()\nif field.data in [email[0] for email in session.query(User.email).all()]:\n raise Valid...
<|body_start_0|> session = create_session() if field.data in [phone[0] for phone in session.query(User.phone_number).all()]: raise ValidationError('Пользователь с таким номером телефона уже существует') <|end_body_0|> <|body_start_1|> session = create_session() if field.data...
Класс формы регистрации.
RegistrationForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistrationForm: """Класс формы регистрации.""" def validate_phone_number_field(self, field: StringField): """Метод, проверяющий уникальность введенных данных в поле для телефона :param field: поле, которое необходимо проверить""" <|body_0|> def validate_email_field(sel...
stack_v2_sparse_classes_36k_train_024703
8,216
no_license
[ { "docstring": "Метод, проверяющий уникальность введенных данных в поле для телефона :param field: поле, которое необходимо проверить", "name": "validate_phone_number_field", "signature": "def validate_phone_number_field(self, field: StringField)" }, { "docstring": "Метод, проверяющий уникальнос...
2
stack_v2_sparse_classes_30k_train_016445
Implement the Python class `RegistrationForm` described below. Class description: Класс формы регистрации. Method signatures and docstrings: - def validate_phone_number_field(self, field: StringField): Метод, проверяющий уникальность введенных данных в поле для телефона :param field: поле, которое необходимо проверит...
Implement the Python class `RegistrationForm` described below. Class description: Класс формы регистрации. Method signatures and docstrings: - def validate_phone_number_field(self, field: StringField): Метод, проверяющий уникальность введенных данных в поле для телефона :param field: поле, которое необходимо проверит...
7227e0fab616086ed895b2d09d1dc247c0048183
<|skeleton|> class RegistrationForm: """Класс формы регистрации.""" def validate_phone_number_field(self, field: StringField): """Метод, проверяющий уникальность введенных данных в поле для телефона :param field: поле, которое необходимо проверить""" <|body_0|> def validate_email_field(sel...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RegistrationForm: """Класс формы регистрации.""" def validate_phone_number_field(self, field: StringField): """Метод, проверяющий уникальность введенных данных в поле для телефона :param field: поле, которое необходимо проверить""" session = create_session() if field.data in [phon...
the_stack_v2_python_sparse
data/forms.py
Nekson228/Webby
train
0
256003bfdf8b1245f83124aa9352628489fa5bd1
[ "username = kwargs.get('username', None)\nself.pagination_class.page_size_query_param = 'length'\nself.pagination_class.max_page_size = 100\nqueryset = self.filter_queryset(self.get_queryset())\nusername = bleach.clean(username)\nif request.user.is_staff:\n user = get_or_none(User, username=username)\n if use...
<|body_start_0|> username = kwargs.get('username', None) self.pagination_class.page_size_query_param = 'length' self.pagination_class.max_page_size = 100 queryset = self.filter_queryset(self.get_queryset()) username = bleach.clean(username) if request.user.is_staff: ...
API endpoint that allows users to view their history
UserHistoryViewSet
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserHistoryViewSet: """API endpoint that allows users to view their history""" def list(self, request, *args, **kwargs): """Return a list of a users command history""" <|body_0|> def retrieve(self, request, *args, **kwargs): """Return a specific user's command"""...
stack_v2_sparse_classes_36k_train_024704
4,294
permissive
[ { "docstring": "Return a list of a users command history", "name": "list", "signature": "def list(self, request, *args, **kwargs)" }, { "docstring": "Return a specific user's command", "name": "retrieve", "signature": "def retrieve(self, request, *args, **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_018745
Implement the Python class `UserHistoryViewSet` described below. Class description: API endpoint that allows users to view their history Method signatures and docstrings: - def list(self, request, *args, **kwargs): Return a list of a users command history - def retrieve(self, request, *args, **kwargs): Return a speci...
Implement the Python class `UserHistoryViewSet` described below. Class description: API endpoint that allows users to view their history Method signatures and docstrings: - def list(self, request, *args, **kwargs): Return a list of a users command history - def retrieve(self, request, *args, **kwargs): Return a speci...
85102bb41aa0d558a3fa088e4fd6f51613599ad0
<|skeleton|> class UserHistoryViewSet: """API endpoint that allows users to view their history""" def list(self, request, *args, **kwargs): """Return a list of a users command history""" <|body_0|> def retrieve(self, request, *args, **kwargs): """Return a specific user's command"""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserHistoryViewSet: """API endpoint that allows users to view their history""" def list(self, request, *args, **kwargs): """Return a list of a users command history""" username = kwargs.get('username', None) self.pagination_class.page_size_query_param = 'length' self.pagin...
the_stack_v2_python_sparse
orchestrator/core/orc_server/account/views/viewsets.py
g2-inc/openc2-oif-orchestrator
train
1
bc7867a3e997939292ac0777ed17ead2a75c2a7c
[ "data = self.get_json()\nif 'obj_id' not in data:\n return self.error('Missing required parameter: obj_id')\nwith self.Session() as session:\n try:\n obj_id = post_thumbnail(data, self.associated_user_object.id, session)\n except Exception as e:\n return self.error(f'Thumbnail failed to post:...
<|body_start_0|> data = self.get_json() if 'obj_id' not in data: return self.error('Missing required parameter: obj_id') with self.Session() as session: try: obj_id = post_thumbnail(data, self.associated_user_object.id, session) except Exceptio...
ThumbnailHandler
[ "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ThumbnailHandler: def post(self): """--- description: Upload thumbnails tags: - thumbnails requestBody: content: application/json: schema: type: object properties: obj_id: type: string description: ID of object associated with thumbnails. data: type: string format: byte description: base...
stack_v2_sparse_classes_36k_train_024705
22,926
permissive
[ { "docstring": "--- description: Upload thumbnails tags: - thumbnails requestBody: content: application/json: schema: type: object properties: obj_id: type: string description: ID of object associated with thumbnails. data: type: string format: byte description: base64-encoded PNG image file contents. Image siz...
4
null
Implement the Python class `ThumbnailHandler` described below. Class description: Implement the ThumbnailHandler class. Method signatures and docstrings: - def post(self): --- description: Upload thumbnails tags: - thumbnails requestBody: content: application/json: schema: type: object properties: obj_id: type: strin...
Implement the Python class `ThumbnailHandler` described below. Class description: Implement the ThumbnailHandler class. Method signatures and docstrings: - def post(self): --- description: Upload thumbnails tags: - thumbnails requestBody: content: application/json: schema: type: object properties: obj_id: type: strin...
161d3532ba3ba059446addcdac58ca96f39e9636
<|skeleton|> class ThumbnailHandler: def post(self): """--- description: Upload thumbnails tags: - thumbnails requestBody: content: application/json: schema: type: object properties: obj_id: type: string description: ID of object associated with thumbnails. data: type: string format: byte description: base...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ThumbnailHandler: def post(self): """--- description: Upload thumbnails tags: - thumbnails requestBody: content: application/json: schema: type: object properties: obj_id: type: string description: ID of object associated with thumbnails. data: type: string format: byte description: base64-encoded PNG...
the_stack_v2_python_sparse
skyportal/handlers/api/thumbnail.py
skyportal/skyportal
train
80
6db837e1bcaea8cf9b304017d511826394e1a2f3
[ "userdb = CombaUser()\nif userdb.hasPassword(username, password):\n return userdb.getUser(username)\nelse:\n return False", "valid_user = self.check_auth(username, password)\nif valid_user:\n group = None\n groupcreated = None\n try:\n user = User.objects.get(username=username)\n except U...
<|body_start_0|> userdb = CombaUser() if userdb.hasPassword(username, password): return userdb.getUser(username) else: return False <|end_body_0|> <|body_start_1|> valid_user = self.check_auth(username, password) if valid_user: group = None ...
Provides authentication via comba_lib
RedisBackend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedisBackend: """Provides authentication via comba_lib""" def check_auth(self, username, password): """check user and password in redis db :param username: :param password: :return:""" <|body_0|> def authenticate(self, username=None, password=None): """Overwrite ...
stack_v2_sparse_classes_36k_train_024706
3,013
no_license
[ { "docstring": "check user and password in redis db :param username: :param password: :return:", "name": "check_auth", "signature": "def check_auth(self, username, password)" }, { "docstring": "Overwrite the parent authenticate method :param username: :param password: :return:", "name": "aut...
3
stack_v2_sparse_classes_30k_test_000417
Implement the Python class `RedisBackend` described below. Class description: Provides authentication via comba_lib Method signatures and docstrings: - def check_auth(self, username, password): check user and password in redis db :param username: :param password: :return: - def authenticate(self, username=None, passw...
Implement the Python class `RedisBackend` described below. Class description: Provides authentication via comba_lib Method signatures and docstrings: - def check_auth(self, username, password): check user and password in redis db :param username: :param password: :return: - def authenticate(self, username=None, passw...
eb6b8bca4f782f7aa8fbabd4fddbfddaae769252
<|skeleton|> class RedisBackend: """Provides authentication via comba_lib""" def check_auth(self, username, password): """check user and password in redis db :param username: :param password: :return:""" <|body_0|> def authenticate(self, username=None, password=None): """Overwrite ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedisBackend: """Provides authentication via comba_lib""" def check_auth(self, username, password): """check user and password in redis db :param username: :param password: :return:""" userdb = CombaUser() if userdb.hasPassword(username, password): return userdb.getUse...
the_stack_v2_python_sparse
comba_web/redisbackend.py
combaos/comba_web
train
0
8c1348706b58cbc67772329a1d68007a4ec04dfe
[ "self.s = []\nself.m = []\nself.sset = set()\nself.mset = set()\nself.id = 0", "self.s.append((x, self.id))\nhq.heappush(self.m, (-x, -self.id))\nself.id += 1", "if self.top() is not None:\n d = self.s.pop()\n id = d[1]\n val = d[0]\n self.sset.add(id)\n return val", "if self.s:\n while self...
<|body_start_0|> self.s = [] self.m = [] self.sset = set() self.mset = set() self.id = 0 <|end_body_0|> <|body_start_1|> self.s.append((x, self.id)) hq.heappush(self.m, (-x, -self.id)) self.id += 1 <|end_body_1|> <|body_start_2|> if self.top() is...
MaxStack
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaxStack: def __init__(self): """initialize your data structure here. 設計: stack 與 heap 的modification 為獨立事件 各自mark各自的tag 並且在modify時check對方的狀態""" <|body_0|> def push(self, x): """:type x: int :rtype: None""" <|body_1|> def pop(self): """:rtype: int...
stack_v2_sparse_classes_36k_train_024707
3,412
no_license
[ { "docstring": "initialize your data structure here. 設計: stack 與 heap 的modification 為獨立事件 各自mark各自的tag 並且在modify時check對方的狀態", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": ":type x: int :rtype: None", "name": "push", "signature": "def push(self, x)" }, { ...
6
null
Implement the Python class `MaxStack` described below. Class description: Implement the MaxStack class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. 設計: stack 與 heap 的modification 為獨立事件 各自mark各自的tag 並且在modify時check對方的狀態 - def push(self, x): :type x: int :rtype: None - d...
Implement the Python class `MaxStack` described below. Class description: Implement the MaxStack class. Method signatures and docstrings: - def __init__(self): initialize your data structure here. 設計: stack 與 heap 的modification 為獨立事件 各自mark各自的tag 並且在modify時check對方的狀態 - def push(self, x): :type x: int :rtype: None - d...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class MaxStack: def __init__(self): """initialize your data structure here. 設計: stack 與 heap 的modification 為獨立事件 各自mark各自的tag 並且在modify時check對方的狀態""" <|body_0|> def push(self, x): """:type x: int :rtype: None""" <|body_1|> def pop(self): """:rtype: int...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MaxStack: def __init__(self): """initialize your data structure here. 設計: stack 與 heap 的modification 為獨立事件 各自mark各自的tag 並且在modify時check對方的狀態""" self.s = [] self.m = [] self.sset = set() self.mset = set() self.id = 0 def push(self, x): """:type x: in...
the_stack_v2_python_sparse
stack/716_Max_Stack.py
vsdrun/lc_public
train
6
5d7080cfb443ae4a3770e890963b839edf77fb45
[ "tg_instance = BuiltIn().get_library_instance('resources.libraries.python.TrafficGenerator')\ntg_instance.set_rate_provider_defaults(frame_size, traffic_profile)\nalgorithm = MultipleLossRatioSearch(measurer=tg_instance, final_trial_duration=final_trial_duration, final_relative_width=final_relative_width, number_of...
<|body_start_0|> tg_instance = BuiltIn().get_library_instance('resources.libraries.python.TrafficGenerator') tg_instance.set_rate_provider_defaults(frame_size, traffic_profile) algorithm = MultipleLossRatioSearch(measurer=tg_instance, final_trial_duration=final_trial_duration, final_relative_wid...
Class to be imported as Robot Library, containing a single keyword.
OptimizedSearch
[ "CC-BY-4.0", "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OptimizedSearch: """Class to be imported as Robot Library, containing a single keyword.""" def perform_optimized_ndrpdr_search(frame_size, traffic_profile, minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio=0.005, final_relative_width=0.005, final_trial_duration=30.0, initial_tr...
stack_v2_sparse_classes_36k_train_024708
32,463
permissive
[ { "docstring": "Setup initialized TG, perform optimized search, return intervals. :param frame_size: Frame size identifier or value [B]. :param traffic_profile: Module name as a traffic profile identifier. See resources/traffic_profiles/trex for implemented modules. :param minimum_transmit_rate: Minimal bidirec...
2
null
Implement the Python class `OptimizedSearch` described below. Class description: Class to be imported as Robot Library, containing a single keyword. Method signatures and docstrings: - def perform_optimized_ndrpdr_search(frame_size, traffic_profile, minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio=0.00...
Implement the Python class `OptimizedSearch` described below. Class description: Class to be imported as Robot Library, containing a single keyword. Method signatures and docstrings: - def perform_optimized_ndrpdr_search(frame_size, traffic_profile, minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio=0.00...
3151c98618c78e3782e48bbe4d9c8f906c126f69
<|skeleton|> class OptimizedSearch: """Class to be imported as Robot Library, containing a single keyword.""" def perform_optimized_ndrpdr_search(frame_size, traffic_profile, minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio=0.005, final_relative_width=0.005, final_trial_duration=30.0, initial_tr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OptimizedSearch: """Class to be imported as Robot Library, containing a single keyword.""" def perform_optimized_ndrpdr_search(frame_size, traffic_profile, minimum_transmit_rate, maximum_transmit_rate, packet_loss_ratio=0.005, final_relative_width=0.005, final_trial_duration=30.0, initial_trial_duration=...
the_stack_v2_python_sparse
resources/libraries/python/TrafficGenerator.py
preym17/csit
train
0
9996591799edd24e8b51773c0c8d8345e7891da7
[ "agent = request.user.userinfo.agent\ncompany = request.user.userinfo.company\ndata = models.SSARuleManage.tree(agent, company)\nreturn Response({'data': data, 'status': 200, 'msg': '获取成功'})", "obj_serializer = serializers.RuleManageSerializers(data=request.data, context={'request': request})\nif obj_serializer.i...
<|body_start_0|> agent = request.user.userinfo.agent company = request.user.userinfo.company data = models.SSARuleManage.tree(agent, company) return Response({'data': data, 'status': 200, 'msg': '获取成功'}) <|end_body_0|> <|body_start_1|> obj_serializer = serializers.RuleManageSeri...
专家分析系统
RuleManageList
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RuleManageList: """专家分析系统""" def get(self, request): """获取规则目录树""" <|body_0|> def post(self, request): """添加规则""" <|body_1|> <|end_skeleton|> <|body_start_0|> agent = request.user.userinfo.agent company = request.user.userinfo.company ...
stack_v2_sparse_classes_36k_train_024709
4,124
no_license
[ { "docstring": "获取规则目录树", "name": "get", "signature": "def get(self, request)" }, { "docstring": "添加规则", "name": "post", "signature": "def post(self, request)" } ]
2
stack_v2_sparse_classes_30k_val_000590
Implement the Python class `RuleManageList` described below. Class description: 专家分析系统 Method signatures and docstrings: - def get(self, request): 获取规则目录树 - def post(self, request): 添加规则
Implement the Python class `RuleManageList` described below. Class description: 专家分析系统 Method signatures and docstrings: - def get(self, request): 获取规则目录树 - def post(self, request): 添加规则 <|skeleton|> class RuleManageList: """专家分析系统""" def get(self, request): """获取规则目录树""" <|body_0|> def...
d6e025d7e9d9e3aecfd399c77f376130edd8a2df
<|skeleton|> class RuleManageList: """专家分析系统""" def get(self, request): """获取规则目录树""" <|body_0|> def post(self, request): """添加规则""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RuleManageList: """专家分析系统""" def get(self, request): """获取规则目录树""" agent = request.user.userinfo.agent company = request.user.userinfo.company data = models.SSARuleManage.tree(agent, company) return Response({'data': data, 'status': 200, 'msg': '获取成功'}) def po...
the_stack_v2_python_sparse
soc_ssa/views/experts_analysis.py
sundw2015/841
train
4
68fb771b41c6984b96e7a2e7418e1ab59169707b
[ "assert type(knots) is tuple\nassert type(order) is tuple\nassert type(boundary_knots) is tuple\nassert len(knots) == len(order)\nassert len(order) == len(boundary_knots)\nspl = []\nfor knts_i, k, knts_b, c in zip(knots, order, boundary_knots, coords):\n spl.append(bSpline(knts_i, k, knts_b))\nself.coords = coor...
<|body_start_0|> assert type(knots) is tuple assert type(order) is tuple assert type(boundary_knots) is tuple assert len(knots) == len(order) assert len(order) == len(boundary_knots) spl = [] for knts_i, k, knts_b, c in zip(knots, order, boundary_knots, coords): ...
TensorProductSpline, a class for working with tensor splines Contains basic routines for evaluating tensor product splines, computing the Vandermonde-like matrix for a spline, and computing derivatives. Based on Paul Diercx's treatment in "Curve and Surface Fittnig with Splines". The algorithms aren't strictly the most...
TensorProductSpline
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TensorProductSpline: """TensorProductSpline, a class for working with tensor splines Contains basic routines for evaluating tensor product splines, computing the Vandermonde-like matrix for a spline, and computing derivatives. Based on Paul Diercx's treatment in "Curve and Surface Fittnig with Sp...
stack_v2_sparse_classes_36k_train_024710
12,005
permissive
[ { "docstring": "Constructor for the tensor product spline Construct the tensor product spline from spline definitions along each axis we're interested in. The tensor product spline is the cartesian product of splines in each dimension. Args: knots: tuple, with one array for each dimension, defined as for bSplin...
4
null
Implement the Python class `TensorProductSpline` described below. Class description: TensorProductSpline, a class for working with tensor splines Contains basic routines for evaluating tensor product splines, computing the Vandermonde-like matrix for a spline, and computing derivatives. Based on Paul Diercx's treatmen...
Implement the Python class `TensorProductSpline` described below. Class description: TensorProductSpline, a class for working with tensor splines Contains basic routines for evaluating tensor product splines, computing the Vandermonde-like matrix for a spline, and computing derivatives. Based on Paul Diercx's treatmen...
6827886916e36432ce1d806f0a78edef6c9270d9
<|skeleton|> class TensorProductSpline: """TensorProductSpline, a class for working with tensor splines Contains basic routines for evaluating tensor product splines, computing the Vandermonde-like matrix for a spline, and computing derivatives. Based on Paul Diercx's treatment in "Curve and Surface Fittnig with Sp...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TensorProductSpline: """TensorProductSpline, a class for working with tensor splines Contains basic routines for evaluating tensor product splines, computing the Vandermonde-like matrix for a spline, and computing derivatives. Based on Paul Diercx's treatment in "Curve and Surface Fittnig with Splines". The a...
the_stack_v2_python_sparse
pybots/src/geometry/basis_spline.py
aivian/robots
train
0
1c7d9b90b4a32c2de1c0f4311716b3cd49e72abc
[ "if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0:\n return\nn = len(matrix)\nfor i in range(n // 2):\n for j in range(i, n - i - 1):\n tmp = matrix[i][j]\n matrix[i][j] = matrix[n - j - 1][i]\n matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]\n matrix[n - i - 1][n -...
<|body_start_0|> if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0: return n = len(matrix) for i in range(n // 2): for j in range(i, n - i - 1): tmp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate2(self, matrix): """:type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-p...
stack_v2_sparse_classes_36k_train_024711
1,556
no_license
[ { "docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.", "name": "rotate", "signature": "def rotate(self, matrix)" }, { "docstring": ":type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead.", ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. - def rotate2(self, matrix): :type matrix: List[List[...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. - def rotate2(self, matrix): :type matrix: List[List[...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" <|body_0|> def rotate2(self, matrix): """:type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def rotate(self, matrix): """:type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.""" if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0: return n = len(matrix) for i in range(n // 2): for ...
the_stack_v2_python_sparse
R/RotateImage.py
bssrdf/pyleet
train
2
88d39b3fae08bf6d8e2d2f7e663d69078a6ce975
[ "self._log.debug('init')\nname = os.path.basename(p).split('.')[0]\nself._log.debug('Get logger name = %s', name)\nself.logger = logging.getLogger(name)", "self._log.debug('get_tag')\nif not tag:\n self._log.debug('not tag')\n return\nelif type(tag) is str:\n self._log.debug('is str')\n return tag\nel...
<|body_start_0|> self._log.debug('init') name = os.path.basename(p).split('.')[0] self._log.debug('Get logger name = %s', name) self.logger = logging.getLogger(name) <|end_body_0|> <|body_start_1|> self._log.debug('get_tag') if not tag: self._log.debug('not t...
Custom logger wrapper. Typical use includes the module (file) and class name in the log output. By creating a module logger with the file name and adding a 'tag' to the message. Usage: # module.py: LOG = Logger(__file__) class ExampleClass(object): def __init__(self): LOG.debug(self, 'init') @classmethod def class_meth...
Logger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Logger: """Custom logger wrapper. Typical use includes the module (file) and class name in the log output. By creating a module logger with the file name and adding a 'tag' to the message. Usage: # module.py: LOG = Logger(__file__) class ExampleClass(object): def __init__(self): LOG.debug(self, '...
stack_v2_sparse_classes_36k_train_024712
15,106
permissive
[ { "docstring": "Init logger given a path string like __file__ (or a custom name).", "name": "__init__", "signature": "def __init__(self, p)" }, { "docstring": "Given a tag (e.g. None, 'tag', cls, self) return None or a string. The returned tag string is determined from the class name or string p...
3
stack_v2_sparse_classes_30k_train_000356
Implement the Python class `Logger` described below. Class description: Custom logger wrapper. Typical use includes the module (file) and class name in the log output. By creating a module logger with the file name and adding a 'tag' to the message. Usage: # module.py: LOG = Logger(__file__) class ExampleClass(object)...
Implement the Python class `Logger` described below. Class description: Custom logger wrapper. Typical use includes the module (file) and class name in the log output. By creating a module logger with the file name and adding a 'tag' to the message. Usage: # module.py: LOG = Logger(__file__) class ExampleClass(object)...
1b876810cc1a61d70f061fa554b03c5ad54c813c
<|skeleton|> class Logger: """Custom logger wrapper. Typical use includes the module (file) and class name in the log output. By creating a module logger with the file name and adding a 'tag' to the message. Usage: # module.py: LOG = Logger(__file__) class ExampleClass(object): def __init__(self): LOG.debug(self, '...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Logger: """Custom logger wrapper. Typical use includes the module (file) and class name in the log output. By creating a module logger with the file name and adding a 'tag' to the message. Usage: # module.py: LOG = Logger(__file__) class ExampleClass(object): def __init__(self): LOG.debug(self, 'init') @class...
the_stack_v2_python_sparse
common.py
gavingc/TuckerSync
train
0
2d581072b8629f9a56c20d08d7b4bc6f2ac77cd9
[ "user_pref = user_models.UserPref.get_signed_in_user_pref()\nif not user_pref:\n self.abort(403, msg='User must be signed in')\nnew_notify = self.get_bool_param('notify')\nuser_pref.notify_as_starrer = new_notify\nuser_pref.put()\nreturn {'message': 'Done'}", "user_pref = user_models.UserPref.get_signed_in_use...
<|body_start_0|> user_pref = user_models.UserPref.get_signed_in_user_pref() if not user_pref: self.abort(403, msg='User must be signed in') new_notify = self.get_bool_param('notify') user_pref.notify_as_starrer = new_notify user_pref.put() return {'message': '...
Users can store their settings preferences such as whether to get notification from the features they starred.
SettingsAPI
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SettingsAPI: """Users can store their settings preferences such as whether to get notification from the features they starred.""" def do_post(self, **kwargs): """Set the user settings (currently only the notify_as_starrer)""" <|body_0|> def do_get(self, **kwargs): ...
stack_v2_sparse_classes_36k_train_024713
1,588
permissive
[ { "docstring": "Set the user settings (currently only the notify_as_starrer)", "name": "do_post", "signature": "def do_post(self, **kwargs)" }, { "docstring": "Return the user settings (currently only the notify_as_starrer)", "name": "do_get", "signature": "def do_get(self, **kwargs)" ...
2
null
Implement the Python class `SettingsAPI` described below. Class description: Users can store their settings preferences such as whether to get notification from the features they starred. Method signatures and docstrings: - def do_post(self, **kwargs): Set the user settings (currently only the notify_as_starrer) - de...
Implement the Python class `SettingsAPI` described below. Class description: Users can store their settings preferences such as whether to get notification from the features they starred. Method signatures and docstrings: - def do_post(self, **kwargs): Set the user settings (currently only the notify_as_starrer) - de...
17f9886d064da5bda84006d5866077727646fff2
<|skeleton|> class SettingsAPI: """Users can store their settings preferences such as whether to get notification from the features they starred.""" def do_post(self, **kwargs): """Set the user settings (currently only the notify_as_starrer)""" <|body_0|> def do_get(self, **kwargs): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SettingsAPI: """Users can store their settings preferences such as whether to get notification from the features they starred.""" def do_post(self, **kwargs): """Set the user settings (currently only the notify_as_starrer)""" user_pref = user_models.UserPref.get_signed_in_user_pref() ...
the_stack_v2_python_sparse
api/settings_api.py
GoogleChrome/chromium-dashboard
train
574
e14770f6fb324f8a37e997f57eb98353c5081c99
[ "super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor...
<|body_start_0|> super(DecoderBlock, self).__init__() self.mha1 = MultiHeadAttention(dm, h) self.mha2 = MultiHeadAttention(dm, h) self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu') self.dense_output = tf.keras.layers.Dense(dm) self.layernorm1 = tf.keras....
the Transformer decoder block class
DecoderBlock
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DecoderBlock: """the Transformer decoder block class""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate""" <|body_0|> def c...
stack_v2_sparse_classes_36k_train_024714
2,383
no_license
[ { "docstring": "Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate", "name": "__init__", "signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)" }, { "docstring": "the call method for the transfor...
2
null
Implement the Python class `DecoderBlock` described below. Class description: the Transformer decoder block class Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer...
Implement the Python class `DecoderBlock` described below. Class description: the Transformer decoder block class Method signatures and docstrings: - def __init__(self, dm, h, hidden, drop_rate=0.1): Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer...
d86b0e0cae2dd07c761f84a493abc895007873ee
<|skeleton|> class DecoderBlock: """the Transformer decoder block class""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate""" <|body_0|> def c...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DecoderBlock: """the Transformer decoder block class""" def __init__(self, dm, h, hidden, drop_rate=0.1): """Decoder block initializer dm: in dimensionality of model h: number of heads hidden: number of hidden units in FC layer drop_rate: dropout rate""" super(DecoderBlock, self).__init__...
the_stack_v2_python_sparse
supervised_learning/0x12-transformer_apps/8-transformer_decoder_block.py
mag389/holbertonschool-machine_learning
train
2
ee79346eb9b225e02af30451ec164fb470090525
[ "self.d = dict()\nfor i in range(len(words)):\n w = words[i]\n if w in self.d:\n self.d[w].append(i)\n else:\n self.d[w] = [i]", "l1 = self.d[word1]\nl2 = self.d[word2]\nres = float('inf')\nfor i in range(len(l1)):\n nl = list(map(lambda x: abs(x - l1[i]), l2))\n res = min(res, min(nl...
<|body_start_0|> self.d = dict() for i in range(len(words)): w = words[i] if w in self.d: self.d[w].append(i) else: self.d[w] = [i] <|end_body_0|> <|body_start_1|> l1 = self.d[word1] l2 = self.d[word2] res = flo...
WordDistance
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.d = dict() for i in rang...
stack_v2_sparse_classes_36k_train_024715
1,448
no_license
[ { "docstring": ":type words: List[str]", "name": "__init__", "signature": "def __init__(self, words)" }, { "docstring": ":type word1: str :type word2: str :rtype: int", "name": "shortest", "signature": "def shortest(self, word1, word2)" } ]
2
stack_v2_sparse_classes_30k_train_005687
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
Implement the Python class `WordDistance` described below. Class description: Implement the WordDistance class. Method signatures and docstrings: - def __init__(self, words): :type words: List[str] - def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int <|skeleton|> class WordDistance: ...
29543f8da4881b9b8a08a39e510a77c1036c8386
<|skeleton|> class WordDistance: def __init__(self, words): """:type words: List[str]""" <|body_0|> def shortest(self, word1, word2): """:type word1: str :type word2: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WordDistance: def __init__(self, words): """:type words: List[str]""" self.d = dict() for i in range(len(words)): w = words[i] if w in self.d: self.d[w].append(i) else: self.d[w] = [i] def shortest(self, word1, wo...
the_stack_v2_python_sparse
244-shortest-word-distance-ii/shortest-word-distance-ii.py
Cccmm002/my_leetcode
train
0
bab16ada7b2c468c25cdc4e6494e17449401c03f
[ "q = db().query(cls.model)\nif lock_for_update:\n q = q.with_lockmode('update')\nres = q.first()\nif not res and fail_if_not_found:\n raise errors.ObjectNotFound(\"Object '{0}' is not found in DB\".format(cls.__name__))\nreturn res", "data.pop('master_node_uid', None)\nsuper(MasterNodeSettings, cls).update(...
<|body_start_0|> q = db().query(cls.model) if lock_for_update: q = q.with_lockmode('update') res = q.first() if not res and fail_if_not_found: raise errors.ObjectNotFound("Object '{0}' is not found in DB".format(cls.__name__)) return res <|end_body_0|> <|...
MasterNodeSettings
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MasterNodeSettings: def get_one(cls, fail_if_not_found=False, lock_for_update=False): """Get one instance from table. :param fail_if_not_found: raise an exception if object is not found :param lock_for_update: lock returned object for update (DB mutex) :return: instance of an object (mod...
stack_v2_sparse_classes_36k_train_024716
3,310
permissive
[ { "docstring": "Get one instance from table. :param fail_if_not_found: raise an exception if object is not found :param lock_for_update: lock returned object for update (DB mutex) :return: instance of an object (model)", "name": "get_one", "signature": "def get_one(cls, fail_if_not_found=False, lock_for...
3
null
Implement the Python class `MasterNodeSettings` described below. Class description: Implement the MasterNodeSettings class. Method signatures and docstrings: - def get_one(cls, fail_if_not_found=False, lock_for_update=False): Get one instance from table. :param fail_if_not_found: raise an exception if object is not f...
Implement the Python class `MasterNodeSettings` described below. Class description: Implement the MasterNodeSettings class. Method signatures and docstrings: - def get_one(cls, fail_if_not_found=False, lock_for_update=False): Get one instance from table. :param fail_if_not_found: raise an exception if object is not f...
0e09dce510927f2cc490b898e5fe3f813bd791be
<|skeleton|> class MasterNodeSettings: def get_one(cls, fail_if_not_found=False, lock_for_update=False): """Get one instance from table. :param fail_if_not_found: raise an exception if object is not found :param lock_for_update: lock returned object for update (DB mutex) :return: instance of an object (mod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MasterNodeSettings: def get_one(cls, fail_if_not_found=False, lock_for_update=False): """Get one instance from table. :param fail_if_not_found: raise an exception if object is not found :param lock_for_update: lock returned object for update (DB mutex) :return: instance of an object (model)""" ...
the_stack_v2_python_sparse
nailgun/nailgun/objects/master_node_settings.py
mba811/fuel-web
train
1
aa046820e8fc249515cce130237f2fc992825129
[ "super(MyImageNet22K, self).__init__(root, *args, **kwargs)\nself.exclude_imagenet1k = exclude_imagenet1k\nself.shuffle_idxs = False\nself.size = size\nif exclude_imagenet1k:\n self.samples = [s for s in self.samples if not any([idx in s[0] for idx in self.imagenet1k_idxs])]", "path, target = self.samples[inde...
<|body_start_0|> super(MyImageNet22K, self).__init__(root, *args, **kwargs) self.exclude_imagenet1k = exclude_imagenet1k self.shuffle_idxs = False self.size = size if exclude_imagenet1k: self.samples = [s for s in self.samples if not any([idx in s[0] for idx in self.i...
MyImageNet22K
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyImageNet22K: def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): """Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens tha...
stack_v2_sparse_classes_36k_train_024717
13,359
permissive
[ { "docstring": "Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens that some of the image files are broken. In this case, a warning is logged during training and a black image is returned...
2
stack_v2_sparse_classes_30k_train_019797
Implement the Python class `MyImageNet22K` described below. Class description: Implement the MyImageNet22K class. Method signatures and docstrings: - def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): Implements a torchvision style ImageNet22k dataset. The dataset needs to be d...
Implement the Python class `MyImageNet22K` described below. Class description: Implement the MyImageNet22K class. Method signatures and docstrings: - def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): Implements a torchvision style ImageNet22k dataset. The dataset needs to be d...
7af3d8eadabee81ab8f7db5dea7f8389ef090213
<|skeleton|> class MyImageNet22K: def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): """Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens tha...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MyImageNet22K: def __init__(self, root: str, size: torch.Size, exclude_imagenet1k=True, *args, **kwargs): """Implements a torchvision style ImageNet22k dataset. The dataset needs to be downloaded manually and put in the according directory. Since the dataset is very large, it happens that some of the ...
the_stack_v2_python_sparse
python/fcdd/datasets/outlier_exposure/imagenet.py
hkhaledmohamed/fcdd
train
0
22a60725b00e3dcdf96c58fae81969a0508687f2
[ "self.cmd = cmd\nself.environment = os.environ\nprocess = subprocess.Popen(['which', self.cmd[0]], env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nself.stdout, self.stderr = process.communicate()\nself.exitcode = process.returncode\nif self.exitcode != 0:\n raise ConnectomistConfigurationE...
<|body_start_0|> self.cmd = cmd self.environment = os.environ process = subprocess.Popen(['which', self.cmd[0]], env=self.environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.stdout, self.stderr = process.communicate() self.exitcode = process.returncode if se...
Parent class for the wrapping of Connectomist Ptk functions.
PtkWrapper
[ "LicenseRef-scancode-cecill-b-en" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PtkWrapper: """Parent class for the wrapping of Connectomist Ptk functions.""" def __init__(self, cmd): """Initialize the PtkWrapper class Parameters ---------- cmd: list of str (mandatory) the Morphologist command to execute.""" <|body_0|> def __call__(self, files_to_ch...
stack_v2_sparse_classes_36k_train_024718
8,020
permissive
[ { "docstring": "Initialize the PtkWrapper class Parameters ---------- cmd: list of str (mandatory) the Morphologist command to execute.", "name": "__init__", "signature": "def __init__(self, cmd)" }, { "docstring": "Run the Connectomist Ptk command. Parameters ---------- files_to_check: list of ...
2
stack_v2_sparse_classes_30k_train_001052
Implement the Python class `PtkWrapper` described below. Class description: Parent class for the wrapping of Connectomist Ptk functions. Method signatures and docstrings: - def __init__(self, cmd): Initialize the PtkWrapper class Parameters ---------- cmd: list of str (mandatory) the Morphologist command to execute. ...
Implement the Python class `PtkWrapper` described below. Class description: Parent class for the wrapping of Connectomist Ptk functions. Method signatures and docstrings: - def __init__(self, cmd): Initialize the PtkWrapper class Parameters ---------- cmd: list of str (mandatory) the Morphologist command to execute. ...
3105d2b1e4458c3be398391436be54bf59949a34
<|skeleton|> class PtkWrapper: """Parent class for the wrapping of Connectomist Ptk functions.""" def __init__(self, cmd): """Initialize the PtkWrapper class Parameters ---------- cmd: list of str (mandatory) the Morphologist command to execute.""" <|body_0|> def __call__(self, files_to_ch...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PtkWrapper: """Parent class for the wrapping of Connectomist Ptk functions.""" def __init__(self, cmd): """Initialize the PtkWrapper class Parameters ---------- cmd: list of str (mandatory) the Morphologist command to execute.""" self.cmd = cmd self.environment = os.environ ...
the_stack_v2_python_sparse
clindmri/extensions/connectomist/wrappers.py
neurospin/caps-clindmri
train
0
0a463924803fd0fd6693929e892b0529410abac5
[ "self.regex = regex\nm = len(regex)\nself.m = m\nops = Stack()\ngraph = Digraph(m + 1)\nfor i in range(0, m):\n lp = i\n if regex[i] == '(' or regex[i] == '|':\n ops.push(i)\n elif regex[i] == ')':\n or_ = ops.pop()\n if regex[or_] == '|':\n lp = ops.pop()\n graph...
<|body_start_0|> self.regex = regex m = len(regex) self.m = m ops = Stack() graph = Digraph(m + 1) for i in range(0, m): lp = i if regex[i] == '(' or regex[i] == '|': ops.push(i) elif regex[i] == ')': or_...
The NFA class provides a data type for creating a nondeterministic finite state automaton (NFA) from a regular expression and testing whether a given string is matched by that regular expression. It supports the following operations: concatenation, closure, binary or, and parentheses, metacharacters (either in the text...
NFA
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NFA: """The NFA class provides a data type for creating a nondeterministic finite state automaton (NFA) from a regular expression and testing whether a given string is matched by that regular expression. It supports the following operations: concatenation, closure, binary or, and parentheses, met...
stack_v2_sparse_classes_36k_train_024719
3,293
no_license
[ { "docstring": "Initializes the NFA from the specified regular expression. :param regex: the regular expression", "name": "__init__", "signature": "def __init__(self, regex)" }, { "docstring": "Returns True if the text is matched by the regular expression. :param txt: the text :returns: True if ...
2
stack_v2_sparse_classes_30k_train_021051
Implement the Python class `NFA` described below. Class description: The NFA class provides a data type for creating a nondeterministic finite state automaton (NFA) from a regular expression and testing whether a given string is matched by that regular expression. It supports the following operations: concatenation, c...
Implement the Python class `NFA` described below. Class description: The NFA class provides a data type for creating a nondeterministic finite state automaton (NFA) from a regular expression and testing whether a given string is matched by that regular expression. It supports the following operations: concatenation, c...
658e3a42b712fb79a4afc8c3acf24161bd5d6737
<|skeleton|> class NFA: """The NFA class provides a data type for creating a nondeterministic finite state automaton (NFA) from a regular expression and testing whether a given string is matched by that regular expression. It supports the following operations: concatenation, closure, binary or, and parentheses, met...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class NFA: """The NFA class provides a data type for creating a nondeterministic finite state automaton (NFA) from a regular expression and testing whether a given string is matched by that regular expression. It supports the following operations: concatenation, closure, binary or, and parentheses, metacharacters (...
the_stack_v2_python_sparse
algs4/strings/nfa.py
bhavyaagg/python-test
train
0
88260242b8609eb63a87062ea9931c3290e37d3e
[ "if not 0 <= maxBirthProb <= 1:\n raise ValueError\nif not 0 <= clearProb <= 1:\n raise ValueError\nelse:\n self.maxBirthProb = maxBirthProb\n self.clearProb = clearProb", "potential = random.random()\nif potential <= self.clearProb:\n return True\nreturn False", "self.popDensity = popDensity\nPo...
<|body_start_0|> if not 0 <= maxBirthProb <= 1: raise ValueError if not 0 <= clearProb <= 1: raise ValueError else: self.maxBirthProb = maxBirthProb self.clearProb = clearProb <|end_body_0|> <|body_start_1|> potential = random.random() ...
Representation of a simple virus (does not model drug effects/resistance).
SimpleVirus
[ "Giftware" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleVirus: """Representation of a simple virus (does not model drug effects/resistance).""" def __init__(self, maxBirthProb, clearProb): """Initialize a SimpleVirus instance, saves all parameters as attributes of the instance. maxBirthProb: Maximum reproduction probability (a float...
stack_v2_sparse_classes_36k_train_024720
28,689
permissive
[ { "docstring": "Initialize a SimpleVirus instance, saves all parameters as attributes of the instance. maxBirthProb: Maximum reproduction probability (a float between 0-1) clearProb: Maximum clearance probability (a float between 0-1).", "name": "__init__", "signature": "def __init__(self, maxBirthProb,...
3
stack_v2_sparse_classes_30k_train_001966
Implement the Python class `SimpleVirus` described below. Class description: Representation of a simple virus (does not model drug effects/resistance). Method signatures and docstrings: - def __init__(self, maxBirthProb, clearProb): Initialize a SimpleVirus instance, saves all parameters as attributes of the instance...
Implement the Python class `SimpleVirus` described below. Class description: Representation of a simple virus (does not model drug effects/resistance). Method signatures and docstrings: - def __init__(self, maxBirthProb, clearProb): Initialize a SimpleVirus instance, saves all parameters as attributes of the instance...
6f7dab3b1ef188b1ace0dba72eed78843879e9e7
<|skeleton|> class SimpleVirus: """Representation of a simple virus (does not model drug effects/resistance).""" def __init__(self, maxBirthProb, clearProb): """Initialize a SimpleVirus instance, saves all parameters as attributes of the instance. maxBirthProb: Maximum reproduction probability (a float...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SimpleVirus: """Representation of a simple virus (does not model drug effects/resistance).""" def __init__(self, maxBirthProb, clearProb): """Initialize a SimpleVirus instance, saves all parameters as attributes of the instance. maxBirthProb: Maximum reproduction probability (a float between 0-1)...
the_stack_v2_python_sparse
MIT/Problem sets/ps12.py
CStage/MIT-Git
train
0
07b6c0c2357ca2ab7198d756806b861fc705b913
[ "super(DenseLayers, self).__init__(name=name, **kwargs)\nif any((size < 1 for size in hidden_sizes)):\n raise ValueError('All sizes in `hidden_sizes` must be positive.')\nself.hidden_sizes = hidden_sizes\nself.activation = tf.keras.activations.get(activation)\nself.use_bias = use_bias\nself.kernel_initializer = ...
<|body_start_0|> super(DenseLayers, self).__init__(name=name, **kwargs) if any((size < 1 for size in hidden_sizes)): raise ValueError('All sizes in `hidden_sizes` must be positive.') self.hidden_sizes = hidden_sizes self.activation = tf.keras.activations.get(activation) ...
Convenience class for stacking Dense layers. The result is a simple fully-connected network with `len(hidden_sizes)` layers, the last of which is the output. The given activation function will be applied to every layer except for the last one, which will not have any activation.
DenseLayers
[ "Apache-2.0", "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DenseLayers: """Convenience class for stacking Dense layers. The result is a simple fully-connected network with `len(hidden_sizes)` layers, the last of which is the output. The given activation function will be applied to every layer except for the last one, which will not have any activation.""...
stack_v2_sparse_classes_36k_train_024721
4,381
permissive
[ { "docstring": "Init. Args: hidden_sizes: List of hidden layer sizes, one for each layer in order. The last integer will be the layer size of the output. activation: Activation function to use. If you don't specify anything, no activation is applied (i.e. \"linear\" activation: a(x) = x). Note that the last lay...
2
stack_v2_sparse_classes_30k_train_005108
Implement the Python class `DenseLayers` described below. Class description: Convenience class for stacking Dense layers. The result is a simple fully-connected network with `len(hidden_sizes)` layers, the last of which is the output. The given activation function will be applied to every layer except for the last one...
Implement the Python class `DenseLayers` described below. Class description: Convenience class for stacking Dense layers. The result is a simple fully-connected network with `len(hidden_sizes)` layers, the last of which is the output. The given activation function will be applied to every layer except for the last one...
5573d9c5822f4e866b6692769963ae819cb3f10d
<|skeleton|> class DenseLayers: """Convenience class for stacking Dense layers. The result is a simple fully-connected network with `len(hidden_sizes)` layers, the last of which is the output. The given activation function will be applied to every layer except for the last one, which will not have any activation.""...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DenseLayers: """Convenience class for stacking Dense layers. The result is a simple fully-connected network with `len(hidden_sizes)` layers, the last of which is the output. The given activation function will be applied to every layer except for the last one, which will not have any activation.""" def __...
the_stack_v2_python_sparse
readtwice/layers/helpers.py
Jimmy-INL/google-research
train
1
b91e44f770a2a4dc2566ef805425b59d8b80881d
[ "filters = {}\nfor field in self.lookup_field:\n if self.request.GET.get(field, None):\n if field in self.varchar_fields:\n filters[field] = ast.literal_eval(self.request.GET.get(field, None))\n elif field in self.int_fields:\n filters[field] = int(self.request.GET.get(field, ...
<|body_start_0|> filters = {} for field in self.lookup_field: if self.request.GET.get(field, None): if field in self.varchar_fields: filters[field] = ast.literal_eval(self.request.GET.get(field, None)) elif field in self.int_fields: ...
A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data.
ListFilterAPIView
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListFilterAPIView: """A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data.""" def get_filters(self): """Method which creates the filters dict. Matches the given Parameters from the request with the allowed looku...
stack_v2_sparse_classes_36k_train_024722
13,273
permissive
[ { "docstring": "Method which creates the filters dict. Matches the given Parameters from the request with the allowed lookup_fields, and only maps non-empty fields.", "name": "get_filters", "signature": "def get_filters(self)" }, { "docstring": "Method which returns the filtered Queryset.", ...
2
stack_v2_sparse_classes_30k_train_003645
Implement the Python class `ListFilterAPIView` described below. Class description: A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data. Method signatures and docstrings: - def get_filters(self): Method which creates the filters dict. Matches the...
Implement the Python class `ListFilterAPIView` described below. Class description: A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data. Method signatures and docstrings: - def get_filters(self): Method which creates the filters dict. Matches the...
8c5bc4c9ba9759b58b52ddf339ccaec40ec5f6ea
<|skeleton|> class ListFilterAPIView: """A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data.""" def get_filters(self): """Method which creates the filters dict. Matches the given Parameters from the request with the allowed looku...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ListFilterAPIView: """A View which creates a filters dict and returns a List of objects matching alle given Filters. View only for Retrieving Data.""" def get_filters(self): """Method which creates the filters dict. Matches the given Parameters from the request with the allowed lookup_fields, and...
the_stack_v2_python_sparse
geomat/stein/views.py
GeoMatDigital/django-geomat
train
3
d22b509c66f8f33f775b72f89dc11d123ee56747
[ "while i < j:\n array[i], array[j] = (array[j], array[i])\n i += 1\n j -= 1", "for i in range(len(array) - 1, 0, -1):\n if array[i] > array[i - 1]:\n break\nelse:\n array.reverse()\n return\nfor j in range(len(array) - 1, i - 1, -1):\n if array[j] > array[i - 1]:\n array[j], arr...
<|body_start_0|> while i < j: array[i], array[j] = (array[j], array[i]) i += 1 j -= 1 <|end_body_0|> <|body_start_1|> for i in range(len(array) - 1, 0, -1): if array[i] > array[i - 1]: break else: array.reverse() ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def reverse_array(self, array, i, j): """Reverses array in-place from index i to j.""" <|body_0|> def next_permutation(self, array): """Generates next lexicographical permutation of an array. Modifies array in-place, doesn't return anything.""" <|bo...
stack_v2_sparse_classes_36k_train_024723
3,435
no_license
[ { "docstring": "Reverses array in-place from index i to j.", "name": "reverse_array", "signature": "def reverse_array(self, array, i, j)" }, { "docstring": "Generates next lexicographical permutation of an array. Modifies array in-place, doesn't return anything.", "name": "next_permutation",...
5
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse_array(self, array, i, j): Reverses array in-place from index i to j. - def next_permutation(self, array): Generates next lexicographical permutation of an array. Modi...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def reverse_array(self, array, i, j): Reverses array in-place from index i to j. - def next_permutation(self, array): Generates next lexicographical permutation of an array. Modi...
71b722ddfe8da04572e527b055cf8723d5c87bbf
<|skeleton|> class Solution: def reverse_array(self, array, i, j): """Reverses array in-place from index i to j.""" <|body_0|> def next_permutation(self, array): """Generates next lexicographical permutation of an array. Modifies array in-place, doesn't return anything.""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def reverse_array(self, array, i, j): """Reverses array in-place from index i to j.""" while i < j: array[i], array[j] = (array[j], array[i]) i += 1 j -= 1 def next_permutation(self, array): """Generates next lexicographical permutatio...
the_stack_v2_python_sparse
Backtracking/permutation_sequence.py
vladn90/Algorithms
train
0
6912719ddd454307106777e35f3e6f03ce3ee769
[ "self.reuse = False\nself.batch_size = batch_size\nself.num_channels = num_channels\nself.layer_stage_sizes = layer_stage_sizes\nself.name = name\nself.num_classes = num_classes\nself.batch_norm_use = batch_norm_use\nself.inner_layer_depth = inner_layer_depth\nself.strided_dim_reduction = strided_dim_reduction\nsel...
<|body_start_0|> self.reuse = False self.batch_size = batch_size self.num_channels = num_channels self.layer_stage_sizes = layer_stage_sizes self.name = name self.num_classes = num_classes self.batch_norm_use = batch_norm_use self.inner_layer_depth = inner...
VGGClassifier
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VGGClassifier: def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): """Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_sizes:...
stack_v2_sparse_classes_36k_train_024724
9,392
permissive
[ { "docstring": "Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_sizes: A list containing the filters for each layer stage, where layer stage is a series of convolutional layers with stride=1 and no max pooling followed by a dimensionality reducing stage...
2
null
Implement the Python class `VGGClassifier` described below. Class description: Implement the VGGClassifier class. Method signatures and docstrings: - def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): Initializes...
Implement the Python class `VGGClassifier` described below. Class description: Implement the VGGClassifier class. Method signatures and docstrings: - def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): Initializes...
2831df3ef210cb3e259bbc43dd39159533f4a33e
<|skeleton|> class VGGClassifier: def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): """Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_sizes:...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VGGClassifier: def __init__(self, batch_size, layer_stage_sizes, name, num_classes, num_channels=1, batch_norm_use=False, inner_layer_depth=2, strided_dim_reduction=True): """Initializes a VGG Classifier architecture :param batch_size: The size of the data batch :param layer_stage_sizes: A list contai...
the_stack_v2_python_sparse
network_architectures.py
comRamona/ACL-2018-Multimodal-Sentiment-Analysis-Multicomp
train
0
bacde2ae00408dda8f5d833ececa4d3dbc1fd5bc
[ "session_id = super().create_session(user_id)\nif session_id is None:\n return None\nuser_session = UserSession(user_id=user_id, session_id=session_id)\nif user_session is None:\n return None\nuser_session.save()\nUserSession.save_to_file()\nreturn session_id", "if session_id is None:\n return None\nUser...
<|body_start_0|> session_id = super().create_session(user_id) if session_id is None: return None user_session = UserSession(user_id=user_id, session_id=session_id) if user_session is None: return None user_session.save() UserSession.save_to_file() ...
Session in database Class
SessionDBAuth
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionDBAuth: """Session in database Class""" def create_session(self, user_id=None): """Make a new Session to Database Args: user_id: Identificator of the user_id Return: Session ID""" <|body_0|> def user_id_for_session_id(self, session_id=None): """Make user i...
stack_v2_sparse_classes_36k_train_024725
2,328
no_license
[ { "docstring": "Make a new Session to Database Args: user_id: Identificator of the user_id Return: Session ID", "name": "create_session", "signature": "def create_session(self, user_id=None)" }, { "docstring": "Make user id to session Args: session_id: String of the session Return: User ID if no...
3
stack_v2_sparse_classes_30k_val_001092
Implement the Python class `SessionDBAuth` described below. Class description: Session in database Class Method signatures and docstrings: - def create_session(self, user_id=None): Make a new Session to Database Args: user_id: Identificator of the user_id Return: Session ID - def user_id_for_session_id(self, session_...
Implement the Python class `SessionDBAuth` described below. Class description: Session in database Class Method signatures and docstrings: - def create_session(self, user_id=None): Make a new Session to Database Args: user_id: Identificator of the user_id Return: Session ID - def user_id_for_session_id(self, session_...
fa0b08c37ece2510d450a8ad01d43ce48d18357b
<|skeleton|> class SessionDBAuth: """Session in database Class""" def create_session(self, user_id=None): """Make a new Session to Database Args: user_id: Identificator of the user_id Return: Session ID""" <|body_0|> def user_id_for_session_id(self, session_id=None): """Make user i...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SessionDBAuth: """Session in database Class""" def create_session(self, user_id=None): """Make a new Session to Database Args: user_id: Identificator of the user_id Return: Session ID""" session_id = super().create_session(user_id) if session_id is None: return None ...
the_stack_v2_python_sparse
0x07-Session_authentication/api/v1/auth/session_db_auth.py
Zaccheaus90/holbertonschool-web_back_end-1
train
0
e6526b64c01934a79e23ff7e09453e45b7bf96b2
[ "self.input = 'AlgoExpert is the best!'\nself.output = 'best! the is AlgoExpert'\nreturn (self.input, self.output)", "input_str, output_arr = self.setUp()\noutput = reverseWordsInString(input_str)\nself.assertEqual(output, output_arr)" ]
<|body_start_0|> self.input = 'AlgoExpert is the best!' self.output = 'best! the is AlgoExpert' return (self.input, self.output) <|end_body_0|> <|body_start_1|> input_str, output_arr = self.setUp() output = reverseWordsInString(input_str) self.assertEqual(output, output_...
Class with unittests for ReverseWordsInString.py
test_ReverseWordsInString
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class test_ReverseWordsInString: """Class with unittests for ReverseWordsInString.py""" def setUp(self): """Sets up input.""" <|body_0|> def test_ExpectedOutput(self): """Checks if returned output is as expected.""" <|body_1|> <|end_skeleton|> <|body_start_0|...
stack_v2_sparse_classes_36k_train_024726
898
no_license
[ { "docstring": "Sets up input.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Checks if returned output is as expected.", "name": "test_ExpectedOutput", "signature": "def test_ExpectedOutput(self)" } ]
2
null
Implement the Python class `test_ReverseWordsInString` described below. Class description: Class with unittests for ReverseWordsInString.py Method signatures and docstrings: - def setUp(self): Sets up input. - def test_ExpectedOutput(self): Checks if returned output is as expected.
Implement the Python class `test_ReverseWordsInString` described below. Class description: Class with unittests for ReverseWordsInString.py Method signatures and docstrings: - def setUp(self): Sets up input. - def test_ExpectedOutput(self): Checks if returned output is as expected. <|skeleton|> class test_ReverseWor...
3aa62ad36c3b06b2a3b05f1f8e2a9e21d68b371f
<|skeleton|> class test_ReverseWordsInString: """Class with unittests for ReverseWordsInString.py""" def setUp(self): """Sets up input.""" <|body_0|> def test_ExpectedOutput(self): """Checks if returned output is as expected.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class test_ReverseWordsInString: """Class with unittests for ReverseWordsInString.py""" def setUp(self): """Sets up input.""" self.input = 'AlgoExpert is the best!' self.output = 'best! the is AlgoExpert' return (self.input, self.output) def test_ExpectedOutput(self): ...
the_stack_v2_python_sparse
AlgoExpert_algorithms/Medium/ReverseWordsInString/test_ReverseWordsInString.py
JakubKazimierski/PythonPortfolio
train
9
68773e40edbd3d6b138ede3d676decacb28d558a
[ "hunt_urn = rdfvalue.RDFURN(request.REQ.get('hunt_id'))\nwith aff4.FACTORY.Open(hunt_urn, aff4_type='GRRHunt', token=request.token) as hunt:\n runner = hunt.GetRunner()\n hunt_args = rdfvalue.ModifyHuntFlowArgs(client_limit=runner.args.client_limit, expiry_time=runner.context.expires)\n self.hunt_params_fo...
<|body_start_0|> hunt_urn = rdfvalue.RDFURN(request.REQ.get('hunt_id')) with aff4.FACTORY.Open(hunt_urn, aff4_type='GRRHunt', token=request.token) as hunt: runner = hunt.GetRunner() hunt_args = rdfvalue.ModifyHuntFlowArgs(client_limit=runner.args.client_limit, expiry_time=runner....
Dialog that allows user to modify certain hunt parameters.
ModifyHuntDialog
[ "Apache-2.0", "DOC" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ModifyHuntDialog: """Dialog that allows user to modify certain hunt parameters.""" def Layout(self, request, response): """Layout handler.""" <|body_0|> def RenderAjax(self, request, response): """Starts ModifyHuntFlow that actually modifies a hunt.""" <|...
stack_v2_sparse_classes_36k_train_024727
47,444
permissive
[ { "docstring": "Layout handler.", "name": "Layout", "signature": "def Layout(self, request, response)" }, { "docstring": "Starts ModifyHuntFlow that actually modifies a hunt.", "name": "RenderAjax", "signature": "def RenderAjax(self, request, response)" } ]
2
null
Implement the Python class `ModifyHuntDialog` described below. Class description: Dialog that allows user to modify certain hunt parameters. Method signatures and docstrings: - def Layout(self, request, response): Layout handler. - def RenderAjax(self, request, response): Starts ModifyHuntFlow that actually modifies ...
Implement the Python class `ModifyHuntDialog` described below. Class description: Dialog that allows user to modify certain hunt parameters. Method signatures and docstrings: - def Layout(self, request, response): Layout handler. - def RenderAjax(self, request, response): Starts ModifyHuntFlow that actually modifies ...
ba1648b97a76f844ffb8e1891cc9e2680f9b1c6e
<|skeleton|> class ModifyHuntDialog: """Dialog that allows user to modify certain hunt parameters.""" def Layout(self, request, response): """Layout handler.""" <|body_0|> def RenderAjax(self, request, response): """Starts ModifyHuntFlow that actually modifies a hunt.""" <|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ModifyHuntDialog: """Dialog that allows user to modify certain hunt parameters.""" def Layout(self, request, response): """Layout handler.""" hunt_urn = rdfvalue.RDFURN(request.REQ.get('hunt_id')) with aff4.FACTORY.Open(hunt_urn, aff4_type='GRRHunt', token=request.token) as hunt: ...
the_stack_v2_python_sparse
gui/plugins/hunt_view.py
defaultnamehere/grr
train
3
a96ffdcbcb7a08673b65f6039442c24c0868e93e
[ "self.cf = cf\nwf = ListReader(cf, 'whitelist', need_compiled_ix=False)\nwhitelist = wf.srcdict.keys()\nself.whitedict = {'ip': [], 'ip6': []}\nself.havenets = {'ip': False, 'ip6': False}\nself.normalise_addr = NormaliseAddress(cf, error_name='Whitelist')\nfor ipstr in whitelist:\n proto = 'ip'\n if ':' in ip...
<|body_start_0|> self.cf = cf wf = ListReader(cf, 'whitelist', need_compiled_ix=False) whitelist = wf.srcdict.keys() self.whitedict = {'ip': [], 'ip6': []} self.havenets = {'ip': False, 'ip6': False} self.normalise_addr = NormaliseAddress(cf, error_name='Whitelist') ...
Check for IPs in whitelist
WhiteListCheck
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WhiteListCheck: """Check for IPs in whitelist""" def __init__(self, cf): """Read whitelist contents from whitelist.d Create whitedict - dict indexed by ip|ip6 values are ipaddress classes""" <|body_0|> def is_white(self, proto, ipaddr): """Lookup ipaddr in white ...
stack_v2_sparse_classes_36k_train_024728
2,713
permissive
[ { "docstring": "Read whitelist contents from whitelist.d Create whitedict - dict indexed by ip|ip6 values are ipaddress classes", "name": "__init__", "signature": "def __init__(self, cf)" }, { "docstring": "Lookup ipaddr in white list dict Parameters ---------- proto : {'ip', 'ip6'} ipadddr : st...
2
stack_v2_sparse_classes_30k_train_011053
Implement the Python class `WhiteListCheck` described below. Class description: Check for IPs in whitelist Method signatures and docstrings: - def __init__(self, cf): Read whitelist contents from whitelist.d Create whitedict - dict indexed by ip|ip6 values are ipaddress classes - def is_white(self, proto, ipaddr): Lo...
Implement the Python class `WhiteListCheck` described below. Class description: Check for IPs in whitelist Method signatures and docstrings: - def __init__(self, cf): Read whitelist contents from whitelist.d Create whitedict - dict indexed by ip|ip6 values are ipaddress classes - def is_white(self, proto, ipaddr): Lo...
43e48d46089113e09c3a267c255d3102f3dddac7
<|skeleton|> class WhiteListCheck: """Check for IPs in whitelist""" def __init__(self, cf): """Read whitelist contents from whitelist.d Create whitedict - dict indexed by ip|ip6 values are ipaddress classes""" <|body_0|> def is_white(self, proto, ipaddr): """Lookup ipaddr in white ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class WhiteListCheck: """Check for IPs in whitelist""" def __init__(self, cf): """Read whitelist contents from whitelist.d Create whitedict - dict indexed by ip|ip6 values are ipaddress classes""" self.cf = cf wf = ListReader(cf, 'whitelist', need_compiled_ix=False) whitelist = ...
the_stack_v2_python_sparse
nftfw/whitelistcheck.py
pcollinson/nftfw
train
31
7cafc0356301b96505e5f57c2cfab529384dbe38
[ "ans = 0\ntotalLength = 0\nstack = [(-1, 0)]\nfor p in input.split('\\n'):\n currDepth = p.count('\\t')\n currLength = len(p.replace('\\t', ''))\n depth, length = stack[-1]\n while depth >= currDepth:\n totalLength -= length\n stack.pop()\n depth, length = stack[-1]\n if currDept...
<|body_start_0|> ans = 0 totalLength = 0 stack = [(-1, 0)] for p in input.split('\n'): currDepth = p.count('\t') currLength = len(p.replace('\t', '')) depth, length = stack[-1] while depth >= currDepth: totalLength -= length...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def lengthLongestPath(self, input): """:type input: str :rtype: int""" <|body_0|> def lengthLongestPath2(self, input): """:type input: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ans = 0 totalLength = 0 ...
stack_v2_sparse_classes_36k_train_024729
6,317
no_license
[ { "docstring": ":type input: str :rtype: int", "name": "lengthLongestPath", "signature": "def lengthLongestPath(self, input)" }, { "docstring": ":type input: str :rtype: int", "name": "lengthLongestPath2", "signature": "def lengthLongestPath2(self, input)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthLongestPath(self, input): :type input: str :rtype: int - def lengthLongestPath2(self, input): :type input: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def lengthLongestPath(self, input): :type input: str :rtype: int - def lengthLongestPath2(self, input): :type input: str :rtype: int <|skeleton|> class Solution: def length...
2d5fa4cd696d5035ea8859befeadc5cc436959c9
<|skeleton|> class Solution: def lengthLongestPath(self, input): """:type input: str :rtype: int""" <|body_0|> def lengthLongestPath2(self, input): """:type input: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def lengthLongestPath(self, input): """:type input: str :rtype: int""" ans = 0 totalLength = 0 stack = [(-1, 0)] for p in input.split('\n'): currDepth = p.count('\t') currLength = len(p.replace('\t', '')) depth, length = sta...
the_stack_v2_python_sparse
SourceCode/Python/Problem/00388.Longest_Absolute_File_Path.py
roger6blog/LeetCode
train
0
0505504dbb08a78ebc45dc0936873653dadc00db
[ "aspect = Aspect.query.get(aspect_id)\nif aspect is None:\n return abort(HTTPStatus.NOT_FOUND, message='Aspect is not found')\nif aspect.image_path is None:\n return abort(HTTPStatus.NOT_FOUND, 'Aspect image is not found')\nreturn file_storage.download(file_storage.FileCategory.AspectImage, aspect.image_path)...
<|body_start_0|> aspect = Aspect.query.get(aspect_id) if aspect is None: return abort(HTTPStatus.NOT_FOUND, message='Aspect is not found') if aspect.image_path is None: return abort(HTTPStatus.NOT_FOUND, 'Aspect image is not found') return file_storage.download(fi...
AspectImageResource
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AspectImageResource: def get(self, aspect_id): """Get aspect image""" <|body_0|> def put(self, aspect_id): """Replace aspect image * User can set the aspect image **if it does not exists**. This is done to set the image after creating the aspect * User with permissio...
stack_v2_sparse_classes_36k_train_024730
2,266
permissive
[ { "docstring": "Get aspect image", "name": "get", "signature": "def get(self, aspect_id)" }, { "docstring": "Replace aspect image * User can set the aspect image **if it does not exists**. This is done to set the image after creating the aspect * User with permission to **\"edit aspects\"** can ...
2
stack_v2_sparse_classes_30k_train_013484
Implement the Python class `AspectImageResource` described below. Class description: Implement the AspectImageResource class. Method signatures and docstrings: - def get(self, aspect_id): Get aspect image - def put(self, aspect_id): Replace aspect image * User can set the aspect image **if it does not exists**. This ...
Implement the Python class `AspectImageResource` described below. Class description: Implement the AspectImageResource class. Method signatures and docstrings: - def get(self, aspect_id): Get aspect image - def put(self, aspect_id): Replace aspect image * User can set the aspect image **if it does not exists**. This ...
dce87ffe395ae4bd08b47f28e07594e1889da819
<|skeleton|> class AspectImageResource: def get(self, aspect_id): """Get aspect image""" <|body_0|> def put(self, aspect_id): """Replace aspect image * User can set the aspect image **if it does not exists**. This is done to set the image after creating the aspect * User with permissio...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class AspectImageResource: def get(self, aspect_id): """Get aspect image""" aspect = Aspect.query.get(aspect_id) if aspect is None: return abort(HTTPStatus.NOT_FOUND, message='Aspect is not found') if aspect.image_path is None: return abort(HTTPStatus.NOT_FOUN...
the_stack_v2_python_sparse
src/backend/app/api/public/aspects/aspect/aspect_image.py
aimanow/sft
train
0
bb963d8389eb4eceea6361d54b661170b3997774
[ "self._seed = seed\nself.server = server\nself.height = height\nself.width = width\nself.density = density\nself.infected_chance = infected_chance\nself.carrier = 0\nself.infected = 0\nself.susceptible = 0\nself.recovered = 0\nself.total = 0\nself.patient_zero = patient_zero\nself.human_kill_zombie_chance = human_k...
<|body_start_0|> self._seed = seed self.server = server self.height = height self.width = width self.density = density self.infected_chance = infected_chance self.carrier = 0 self.infected = 0 self.susceptible = 0 self.recovered = 0 ...
Apocalypse model. Model holds all the data and functions for the simulation to work. It is a subclass of the mesa framework.
Apocalypse
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Apocalypse: """Apocalypse model. Model holds all the data and functions for the simulation to work. It is a subclass of the mesa framework.""" def __init__(self, height=50, width=50, density=0.1, infected_chance=0.05, map_id=5, city_id=0, province='', human_kill_agent_chance=0.6, patient_zer...
stack_v2_sparse_classes_36k_train_024731
4,644
no_license
[ { "docstring": "Initializes the apocalypse object, makes the grid and puts agents on that grid. Args: height (int): Grid height. width (int): Grid width. density (float): Percentage of the amount of agents in an area. infected_chance (float): Percentage of agents in an area to be infected. map_id (int): Index t...
3
stack_v2_sparse_classes_30k_train_015407
Implement the Python class `Apocalypse` described below. Class description: Apocalypse model. Model holds all the data and functions for the simulation to work. It is a subclass of the mesa framework. Method signatures and docstrings: - def __init__(self, height=50, width=50, density=0.1, infected_chance=0.05, map_id...
Implement the Python class `Apocalypse` described below. Class description: Apocalypse model. Model holds all the data and functions for the simulation to work. It is a subclass of the mesa framework. Method signatures and docstrings: - def __init__(self, height=50, width=50, density=0.1, infected_chance=0.05, map_id...
59d645537f3644a451243ae83d6a0288ba6e4123
<|skeleton|> class Apocalypse: """Apocalypse model. Model holds all the data and functions for the simulation to work. It is a subclass of the mesa framework.""" def __init__(self, height=50, width=50, density=0.1, infected_chance=0.05, map_id=5, city_id=0, province='', human_kill_agent_chance=0.6, patient_zer...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Apocalypse: """Apocalypse model. Model holds all the data and functions for the simulation to work. It is a subclass of the mesa framework.""" def __init__(self, height=50, width=50, density=0.1, infected_chance=0.05, map_id=5, city_id=0, province='', human_kill_agent_chance=0.6, patient_zero=False, door...
the_stack_v2_python_sparse
apocalypse_sim/model.py
PimPaardekooper/zombie_apocalypse
train
0
fc9d79cd611cd91ed01072956b6add2533666f04
[ "errors: dict = {}\nif user_input is not None:\n region_identifier = user_input[CONF_REGION_IDENTIFIER]\n if not await self.hass.async_add_executor_job(DwdWeatherWarningsAPI, region_identifier):\n errors['base'] = 'invalid_identifier'\n if not errors:\n await self.async_set_unique_id(region_i...
<|body_start_0|> errors: dict = {} if user_input is not None: region_identifier = user_input[CONF_REGION_IDENTIFIER] if not await self.hass.async_add_executor_job(DwdWeatherWarningsAPI, region_identifier): errors['base'] = 'invalid_identifier' if not e...
Handle the config flow for the dwd_weather_warnings integration.
DwdWeatherWarningsConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DwdWeatherWarningsConfigFlow: """Handle the config flow for the dwd_weather_warnings integration.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" <|body_0|> async def async_step_import(self, import_...
stack_v2_sparse_classes_36k_train_024732
2,654
permissive
[ { "docstring": "Handle the initial step.", "name": "async_step_user", "signature": "async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult" }, { "docstring": "Import a config entry from configuration.yaml.", "name": "async_step_import", "signature": "async ...
2
null
Implement the Python class `DwdWeatherWarningsConfigFlow` described below. Class description: Handle the config flow for the dwd_weather_warnings integration. Method signatures and docstrings: - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step. - async def...
Implement the Python class `DwdWeatherWarningsConfigFlow` described below. Class description: Handle the config flow for the dwd_weather_warnings integration. Method signatures and docstrings: - async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the initial step. - async def...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class DwdWeatherWarningsConfigFlow: """Handle the config flow for the dwd_weather_warnings integration.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" <|body_0|> async def async_step_import(self, import_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DwdWeatherWarningsConfigFlow: """Handle the config flow for the dwd_weather_warnings integration.""" async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: """Handle the initial step.""" errors: dict = {} if user_input is not None: regio...
the_stack_v2_python_sparse
homeassistant/components/dwd_weather_warnings/config_flow.py
home-assistant/core
train
35,501
90884b41eaf5730f0e863cc4192d527fb2a08603
[ "if re.search('([^a-zA-Z/._\\\\d+])', username) is None:\n return username\nraise serializers.ValidationError('Username can only contain alphanumeric characters and . or _.')", "if re.search('(^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)(?=.*[@$!%*?&])[A-Za-z\\\\d@$_!%*?&]{8,}$)', password) is not None:\n return pass...
<|body_start_0|> if re.search('([^a-zA-Z/._\\d+])', username) is None: return username raise serializers.ValidationError('Username can only contain alphanumeric characters and . or _.') <|end_body_0|> <|body_start_1|> if re.search('(^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-...
serializes and validates user's data
UserSerializer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserSerializer: """serializes and validates user's data""" def validate_username(self, username): """Validate username""" <|body_0|> def validate_password(self, password): """Validate password""" <|body_1|> def create(self, validated_data): "...
stack_v2_sparse_classes_36k_train_024733
3,565
permissive
[ { "docstring": "Validate username", "name": "validate_username", "signature": "def validate_username(self, username)" }, { "docstring": "Validate password", "name": "validate_password", "signature": "def validate_password(self, password)" }, { "docstring": "creates a user", "...
3
stack_v2_sparse_classes_30k_val_001201
Implement the Python class `UserSerializer` described below. Class description: serializes and validates user's data Method signatures and docstrings: - def validate_username(self, username): Validate username - def validate_password(self, password): Validate password - def create(self, validated_data): creates a use...
Implement the Python class `UserSerializer` described below. Class description: serializes and validates user's data Method signatures and docstrings: - def validate_username(self, username): Validate username - def validate_password(self, password): Validate password - def create(self, validated_data): creates a use...
009def5bbaf3066df19ce3f48eacd6c8c055acdf
<|skeleton|> class UserSerializer: """serializes and validates user's data""" def validate_username(self, username): """Validate username""" <|body_0|> def validate_password(self, password): """Validate password""" <|body_1|> def create(self, validated_data): "...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserSerializer: """serializes and validates user's data""" def validate_username(self, username): """Validate username""" if re.search('([^a-zA-Z/._\\d+])', username) is None: return username raise serializers.ValidationError('Username can only contain alphanumeric cha...
the_stack_v2_python_sparse
apps/account/serializers.py
sasili-adetunji/flightify
train
0
36544a5bae567d5261aa30dde41cb54d018d9d67
[ "env.switch[1].ui.create_lag(lag=3800, key=0, lag_type='Static', hash_mode='None')\nlag = {'lagId': 3800, 'name': 'lag3800', 'actorAdminLagKey': 0, 'lagControlType': 'Static', 'hashMode': 'None'}\nlag_table = env.switch[1].ui.get_table_lags()\nassert lag in lag_table, 'LAG has not been added'\nenv.switch[1].ui.dele...
<|body_start_0|> env.switch[1].ui.create_lag(lag=3800, key=0, lag_type='Static', hash_mode='None') lag = {'lagId': 3800, 'name': 'lag3800', 'actorAdminLagKey': 0, 'lagControlType': 'Static', 'hashMode': 'None'} lag_table = env.switch[1].ui.get_table_lags() assert lag in lag_table, 'LAG h...
@description Suite for LAG testing
TestLagSamples
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestLagSamples: """@description Suite for LAG testing""" def test_configure_static_lag(self, env): """@brief Verify that static LAG can be created and deleted @steps -# Create static LAG. -# Verify static LAG has been created. -# Delete static LAG. -# Verify static LAG has been delet...
stack_v2_sparse_classes_36k_train_024734
6,708
permissive
[ { "docstring": "@brief Verify that static LAG can be created and deleted @steps -# Create static LAG. -# Verify static LAG has been created. -# Delete static LAG. -# Verify static LAG has been deleted. @endsteps", "name": "test_configure_static_lag", "signature": "def test_configure_static_lag(self, env...
3
stack_v2_sparse_classes_30k_train_017283
Implement the Python class `TestLagSamples` described below. Class description: @description Suite for LAG testing Method signatures and docstrings: - def test_configure_static_lag(self, env): @brief Verify that static LAG can be created and deleted @steps -# Create static LAG. -# Verify static LAG has been created. ...
Implement the Python class `TestLagSamples` described below. Class description: @description Suite for LAG testing Method signatures and docstrings: - def test_configure_static_lag(self, env): @brief Verify that static LAG can be created and deleted @steps -# Create static LAG. -# Verify static LAG has been created. ...
18c532fcea7b98cbeadd68e82bdad78ebaaecf4e
<|skeleton|> class TestLagSamples: """@description Suite for LAG testing""" def test_configure_static_lag(self, env): """@brief Verify that static LAG can be created and deleted @steps -# Create static LAG. -# Verify static LAG has been created. -# Delete static LAG. -# Verify static LAG has been delet...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestLagSamples: """@description Suite for LAG testing""" def test_configure_static_lag(self, env): """@brief Verify that static LAG can be created and deleted @steps -# Create static LAG. -# Verify static LAG has been created. -# Delete static LAG. -# Verify static LAG has been deleted. @endsteps...
the_stack_v2_python_sparse
l2/lag/test_lag_samples.py
ravigupta1989/testcases
train
0
9cba50c729d3f384102b9dc431c55bbf36b7cc8f
[ "self.sc = sc\nself._skl2spark_classes = {SKL_LogisticRegression: ClassNames('org.apache.spark.ml.classification.LogisticRegressionModel', LogisticRegressionModel), SKL_LinearRegression: ClassNames('org.apache.spark.ml.regression.LinearRegressionModel', LinearRegressionModel)}\nself._supported_skl_types = self._skl...
<|body_start_0|> self.sc = sc self._skl2spark_classes = {SKL_LogisticRegression: ClassNames('org.apache.spark.ml.classification.LogisticRegressionModel', LogisticRegressionModel), SKL_LinearRegression: ClassNames('org.apache.spark.ml.regression.LinearRegressionModel', LinearRegressionModel)} sel...
Class for converting between scikit-learn and Spark ML models
Converter
[ "Python-2.0", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Converter: """Class for converting between scikit-learn and Spark ML models""" def __init__(self, sc): """:param sc: SparkContext""" <|body_0|> def toSpark(self, model): """Convert a scikit-learn model to a Spark ML model from the Pipelines API (spark.ml). Curren...
stack_v2_sparse_classes_36k_train_024735
6,928
permissive
[ { "docstring": ":param sc: SparkContext", "name": "__init__", "signature": "def __init__(self, sc)" }, { "docstring": "Convert a scikit-learn model to a Spark ML model from the Pipelines API (spark.ml). Currently supported models: - sklearn.linear_model.LogisticRegression (binary classification ...
6
null
Implement the Python class `Converter` described below. Class description: Class for converting between scikit-learn and Spark ML models Method signatures and docstrings: - def __init__(self, sc): :param sc: SparkContext - def toSpark(self, model): Convert a scikit-learn model to a Spark ML model from the Pipelines A...
Implement the Python class `Converter` described below. Class description: Class for converting between scikit-learn and Spark ML models Method signatures and docstrings: - def __init__(self, sc): :param sc: SparkContext - def toSpark(self, model): Convert a scikit-learn model to a Spark ML model from the Pipelines A...
2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6
<|skeleton|> class Converter: """Class for converting between scikit-learn and Spark ML models""" def __init__(self, sc): """:param sc: SparkContext""" <|body_0|> def toSpark(self, model): """Convert a scikit-learn model to a Spark ML model from the Pipelines API (spark.ml). Curren...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Converter: """Class for converting between scikit-learn and Spark ML models""" def __init__(self, sc): """:param sc: SparkContext""" self.sc = sc self._skl2spark_classes = {SKL_LogisticRegression: ClassNames('org.apache.spark.ml.classification.LogisticRegressionModel', LogisticReg...
the_stack_v2_python_sparse
lib/python2.7/site-packages/spark_sklearn/converter.py
wangyum/Anaconda
train
11
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae
[ "q = quantity.Volume(1.0, 'm^3')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'm^3')", "q = quantity.Volume(1.0, 'L')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 0.001, delta=1e-09)\nself.assertEqual(q.un...
<|body_start_0|> q = quantity.Volume(1.0, 'm^3') self.assertAlmostEqual(q.value, 1.0, 6) self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06) self.assertEqual(q.units, 'm^3') <|end_body_0|> <|body_start_1|> q = quantity.Volume(1.0, 'L') self.assertAlmostEqual(q.value, 1....
Contains unit tests of the Volume unit type object.
TestVolume
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestVolume: """Contains unit tests of the Volume unit type object.""" def test_m3(self): """Test the creation of an volume quantity with units of m^3.""" <|body_0|> def test_L(self): """Test the creation of an volume quantity with units of L.""" <|body_1|...
stack_v2_sparse_classes_36k_train_024736
33,010
permissive
[ { "docstring": "Test the creation of an volume quantity with units of m^3.", "name": "test_m3", "signature": "def test_m3(self)" }, { "docstring": "Test the creation of an volume quantity with units of L.", "name": "test_L", "signature": "def test_L(self)" } ]
2
stack_v2_sparse_classes_30k_train_004591
Implement the Python class `TestVolume` described below. Class description: Contains unit tests of the Volume unit type object. Method signatures and docstrings: - def test_m3(self): Test the creation of an volume quantity with units of m^3. - def test_L(self): Test the creation of an volume quantity with units of L.
Implement the Python class `TestVolume` described below. Class description: Contains unit tests of the Volume unit type object. Method signatures and docstrings: - def test_m3(self): Test the creation of an volume quantity with units of m^3. - def test_L(self): Test the creation of an volume quantity with units of L....
0937b2e0a955dcf21b79674a4e89f43941c0dd85
<|skeleton|> class TestVolume: """Contains unit tests of the Volume unit type object.""" def test_m3(self): """Test the creation of an volume quantity with units of m^3.""" <|body_0|> def test_L(self): """Test the creation of an volume quantity with units of L.""" <|body_1|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestVolume: """Contains unit tests of the Volume unit type object.""" def test_m3(self): """Test the creation of an volume quantity with units of m^3.""" q = quantity.Volume(1.0, 'm^3') self.assertAlmostEqual(q.value, 1.0, 6) self.assertAlmostEqual(q.value_si, 1.0, delta=1...
the_stack_v2_python_sparse
rmgpy/quantityTest.py
vrlambert/RMG-Py
train
1
2ed8f673cb00541414cc276099fbf36196ddae00
[ "self._feature_columns = tuple(feature_columns or [])\nassert self._feature_columns\nchief_hook = None\nif isinstance(optimizer, sdca_optimizer.SDCAOptimizer) and enable_centered_bias:\n enable_centered_bias = False\n logging.warning('centered_bias is not supported with SDCA, please disable it explicitly.')\n...
<|body_start_0|> self._feature_columns = tuple(feature_columns or []) assert self._feature_columns chief_hook = None if isinstance(optimizer, sdca_optimizer.SDCAOptimizer) and enable_centered_bias: enable_centered_bias = False logging.warning('centered_bias is not...
Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_b = crossed_column(...) estimator = LinearR...
LinearRegressor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LinearRegressor: """Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_...
stack_v2_sparse_classes_36k_train_024737
38,403
permissive
[ { "docstring": "Construct a `LinearRegressor` estimator object. Args: feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph, etc. This can also be u...
4
null
Implement the Python class `LinearRegressor` described below. Class description: Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...
Implement the Python class `LinearRegressor` described below. Class description: Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class LinearRegressor: """Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LinearRegressor: """Linear regressor model. Train a linear regression model to predict label value given observation of feature values. Example: ```python sparse_column_a = sparse_column_with_hash_bucket(...) sparse_column_b = sparse_column_with_hash_bucket(...) sparse_feature_a_x_sparse_feature_b = crossed_c...
the_stack_v2_python_sparse
Tensorflow_OpenCV_Nightly/source/tensorflow/contrib/learn/python/learn/estimators/linear.py
ryfeus/lambda-packs
train
1,283
700c185d9f867c5bf7db8c45c4dc913a7ab04271
[ "assert isinstance(cone, ConvexConeInPositiveQuadrant), 'incorrect cone type'\nconstraints = []\nname = name or str(id(cone))\nleft_extreme_ray = cone.left_extreme_ray()\nx_coeff = math.tan(math.radians(left_extreme_ray.angle_in_degrees())) if left_extreme_ray.angle_in_degrees() < 90 else 1.0\ny_coeff = 1 if left_e...
<|body_start_0|> assert isinstance(cone, ConvexConeInPositiveQuadrant), 'incorrect cone type' constraints = [] name = name or str(id(cone)) left_extreme_ray = cone.left_extreme_ray() x_coeff = math.tan(math.radians(left_extreme_ray.angle_in_degrees())) if left_extreme_ray.angle_i...
Implements constraint generator utility
ConstraintGenerationUtilities
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConstraintGenerationUtilities: """Implements constraint generator utility""" def create_constraints_for_cone_in_positive_quadrant(momilp_model, cone, x_var, y_var, name=None): """Creates and adds the constraints to the model for the given cone, returns the constraints""" <|bo...
stack_v2_sparse_classes_36k_train_024738
41,178
permissive
[ { "docstring": "Creates and adds the constraints to the model for the given cone, returns the constraints", "name": "create_constraints_for_cone_in_positive_quadrant", "signature": "def create_constraints_for_cone_in_positive_quadrant(momilp_model, cone, x_var, y_var, name=None)" }, { "docstring...
4
stack_v2_sparse_classes_30k_train_015393
Implement the Python class `ConstraintGenerationUtilities` described below. Class description: Implements constraint generator utility Method signatures and docstrings: - def create_constraints_for_cone_in_positive_quadrant(momilp_model, cone, x_var, y_var, name=None): Creates and adds the constraints to the model fo...
Implement the Python class `ConstraintGenerationUtilities` described below. Class description: Implements constraint generator utility Method signatures and docstrings: - def create_constraints_for_cone_in_positive_quadrant(momilp_model, cone, x_var, y_var, name=None): Creates and adds the constraints to the model fo...
465ea7aaa62157411f9f181b994f4d7e6b8a2e33
<|skeleton|> class ConstraintGenerationUtilities: """Implements constraint generator utility""" def create_constraints_for_cone_in_positive_quadrant(momilp_model, cone, x_var, y_var, name=None): """Creates and adds the constraints to the model for the given cone, returns the constraints""" <|bo...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ConstraintGenerationUtilities: """Implements constraint generator utility""" def create_constraints_for_cone_in_positive_quadrant(momilp_model, cone, x_var, y_var, name=None): """Creates and adds the constraints to the model for the given cone, returns the constraints""" assert isinstance...
the_stack_v2_python_sparse
src/momilp/utilities.py
gokhanceyhan/momilp
train
2
e9f4277fd38de1862c6a642f24e2111ba1afefc2
[ "self.InitAttr(node, bool, c4d.PYLOOKATCAMERA_PITCH)\nnode[c4d.PYLOOKATCAMERA_PITCH] = True\npd = c4d.PriorityData()\nif pd is None:\n raise MemoryError('Failed to create a priority data.')\npd.SetPriorityValue(c4d.PRIORITYVALUE_CAMERADEPENDENT, True)\nnode[c4d.EXPRESSION_PRIORITY] = pd\nreturn True", "bd = do...
<|body_start_0|> self.InitAttr(node, bool, c4d.PYLOOKATCAMERA_PITCH) node[c4d.PYLOOKATCAMERA_PITCH] = True pd = c4d.PriorityData() if pd is None: raise MemoryError('Failed to create a priority data.') pd.SetPriorityValue(c4d.PRIORITYVALUE_CAMERADEPENDENT, True) ...
Look at Camera
LookAtCamera
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LookAtCamera: """Look at Camera""" def Init(self, node): """Called when Cinema 4D Initialize the TagData (used to define, default values). Args: node (c4d.GeListNode): The instance of the TagData. Returns: True on success, otherwise False.""" <|body_0|> def Execute(self,...
stack_v2_sparse_classes_36k_train_024739
3,361
permissive
[ { "docstring": "Called when Cinema 4D Initialize the TagData (used to define, default values). Args: node (c4d.GeListNode): The instance of the TagData. Returns: True on success, otherwise False.", "name": "Init", "signature": "def Init(self, node)" }, { "docstring": "Called by Cinema 4D at each...
2
null
Implement the Python class `LookAtCamera` described below. Class description: Look at Camera Method signatures and docstrings: - def Init(self, node): Called when Cinema 4D Initialize the TagData (used to define, default values). Args: node (c4d.GeListNode): The instance of the TagData. Returns: True on success, othe...
Implement the Python class `LookAtCamera` described below. Class description: Look at Camera Method signatures and docstrings: - def Init(self, node): Called when Cinema 4D Initialize the TagData (used to define, default values). Args: node (c4d.GeListNode): The instance of the TagData. Returns: True on success, othe...
b1ea3fce533df34094bc3d0bd6460dfb84306e53
<|skeleton|> class LookAtCamera: """Look at Camera""" def Init(self, node): """Called when Cinema 4D Initialize the TagData (used to define, default values). Args: node (c4d.GeListNode): The instance of the TagData. Returns: True on success, otherwise False.""" <|body_0|> def Execute(self,...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LookAtCamera: """Look at Camera""" def Init(self, node): """Called when Cinema 4D Initialize the TagData (used to define, default values). Args: node (c4d.GeListNode): The instance of the TagData. Returns: True on success, otherwise False.""" self.InitAttr(node, bool, c4d.PYLOOKATCAMERA_P...
the_stack_v2_python_sparse
plugins/py-look_at_camera_r13/py-look_at_camera_r13.pyp
PluginCafe/cinema4d_py_sdk_extended
train
112
1852adbb56a7c08dc4a4e555c62da35036eddb7c
[ "self.wind = wind\nself.water = water\nsuper(Langmuir, self).__init__(**kwargs)\nself.array_types.update({'fay_area': gat('fay_area'), 'area': gat('area'), 'bulk_init_volume': gat('bulk_init_volume'), 'age': gat('age'), 'positions': gat('positions'), 'spill_num': gat('spill_num'), 'frac_coverage': gat('frac_coverag...
<|body_start_0|> self.wind = wind self.water = water super(Langmuir, self).__init__(**kwargs) self.array_types.update({'fay_area': gat('fay_area'), 'area': gat('area'), 'bulk_init_volume': gat('bulk_init_volume'), 'age': gat('age'), 'positions': gat('positions'), 'spill_num': gat('spill_...
Easiest to define this as a weathering process that updates 'area' array
Langmuir
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Langmuir: """Easiest to define this as a weathering process that updates 'area' array""" def __init__(self, water=None, wind=None, **kwargs): """initialize wind to (0, 0) if it is None""" <|body_0|> def _get_frac_coverage(self, points, model_time, rel_buoy, thickness): ...
stack_v2_sparse_classes_36k_train_024740
38,088
permissive
[ { "docstring": "initialize wind to (0, 0) if it is None", "name": "__init__", "signature": "def __init__(self, water=None, wind=None, **kwargs)" }, { "docstring": "return fractional coverage for a blob of oil with inputs; relative_buoyancy, and thickness Assumes the thickness is the minimum oil ...
4
stack_v2_sparse_classes_30k_train_004905
Implement the Python class `Langmuir` described below. Class description: Easiest to define this as a weathering process that updates 'area' array Method signatures and docstrings: - def __init__(self, water=None, wind=None, **kwargs): initialize wind to (0, 0) if it is None - def _get_frac_coverage(self, points, mod...
Implement the Python class `Langmuir` described below. Class description: Easiest to define this as a weathering process that updates 'area' array Method signatures and docstrings: - def __init__(self, water=None, wind=None, **kwargs): initialize wind to (0, 0) if it is None - def _get_frac_coverage(self, points, mod...
97bb561fb8c953c4ee766a3f9d84a41aef93fb28
<|skeleton|> class Langmuir: """Easiest to define this as a weathering process that updates 'area' array""" def __init__(self, water=None, wind=None, **kwargs): """initialize wind to (0, 0) if it is None""" <|body_0|> def _get_frac_coverage(self, points, model_time, rel_buoy, thickness): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Langmuir: """Easiest to define this as a weathering process that updates 'area' array""" def __init__(self, water=None, wind=None, **kwargs): """initialize wind to (0, 0) if it is None""" self.wind = wind self.water = water super(Langmuir, self).__init__(**kwargs) ...
the_stack_v2_python_sparse
py_gnome/gnome/weatherers/spreading.py
NOAA-ORR-ERD/PyGnome
train
45
5bdcace672df14724c42ef88461bdc91041be62e
[ "self.lexicon = lexicon\nL_inv = self.lexicon.L_inv.to(device)\nif L_inv.properties & k2.fsa_properties.ARC_SORTED != 0:\n L_inv = k2.arc_sort(L_inv)\nassert L_inv.requires_grad is False\nassert oov in self.lexicon.words\nself.L_inv = L_inv\nself.oov_id = self.lexicon.words[oov]\nself.oov = oov\nself.device = de...
<|body_start_0|> self.lexicon = lexicon L_inv = self.lexicon.L_inv.to(device) if L_inv.properties & k2.fsa_properties.ARC_SORTED != 0: L_inv = k2.arc_sort(L_inv) assert L_inv.requires_grad is False assert oov in self.lexicon.words self.L_inv = L_inv se...
MmiTrainingGraphCompiler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MmiTrainingGraphCompiler: def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): """Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word.""" <|body_0|> ...
stack_v2_sparse_classes_36k_train_024741
6,137
permissive
[ { "docstring": "Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word.", "name": "__init__", "signature": "def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>')" }, { "d...
3
stack_v2_sparse_classes_30k_train_013647
Implement the Python class `MmiTrainingGraphCompiler` described below. Class description: Implement the MmiTrainingGraphCompiler class. Method signatures and docstrings: - def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): Args: L_inv: Its labels are words, while its aux_labels are phones. ...
Implement the Python class `MmiTrainingGraphCompiler` described below. Class description: Implement the MmiTrainingGraphCompiler class. Method signatures and docstrings: - def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): Args: L_inv: Its labels are words, while its aux_labels are phones. ...
2dda31e14039a79b77c89bcd3bb96d52cbf60c8a
<|skeleton|> class MmiTrainingGraphCompiler: def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): """Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word.""" <|body_0|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MmiTrainingGraphCompiler: def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'): """Args: L_inv: Its labels are words, while its aux_labels are phones. phones: The phone symbol table. words: The word symbol table. oov: Out of vocabulary word.""" self.lexicon = lexicon ...
the_stack_v2_python_sparse
snowfall/training/mmi_graph.py
csukuangfj/snowfall
train
0
61013f5d18ffd68ac791127bbbc4978d735ced4a
[ "ins_col = 0\nfor point in self.points:\n time.sleep(2)\n ins_col = ins_col + 1\n self.cut(point)\n trans_img = img_to_str(self.cut_img_name)\n row_content, col_content = trans_img.basicAccurate()\n excel_obj = excel_class(row_content, col_content, ins_col, self.start_row, excel_name=self.excel_na...
<|body_start_0|> ins_col = 0 for point in self.points: time.sleep(2) ins_col = ins_col + 1 self.cut(point) trans_img = img_to_str(self.cut_img_name) row_content, col_content = trans_img.basicAccurate() excel_obj = excel_class(row_co...
handler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class handler: def pre_cut(self): """根据point来将图片截取为多张图片,并识别生成excel""" <|body_0|> def handler_img(self): """读取文件夹里面的图片,并交给pre_cut()处理""" <|body_1|> <|end_skeleton|> <|body_start_0|> ins_col = 0 for point in self.points: time.sleep(2) ...
stack_v2_sparse_classes_36k_train_024742
8,802
no_license
[ { "docstring": "根据point来将图片截取为多张图片,并识别生成excel", "name": "pre_cut", "signature": "def pre_cut(self)" }, { "docstring": "读取文件夹里面的图片,并交给pre_cut()处理", "name": "handler_img", "signature": "def handler_img(self)" } ]
2
null
Implement the Python class `handler` described below. Class description: Implement the handler class. Method signatures and docstrings: - def pre_cut(self): 根据point来将图片截取为多张图片,并识别生成excel - def handler_img(self): 读取文件夹里面的图片,并交给pre_cut()处理
Implement the Python class `handler` described below. Class description: Implement the handler class. Method signatures and docstrings: - def pre_cut(self): 根据point来将图片截取为多张图片,并识别生成excel - def handler_img(self): 读取文件夹里面的图片,并交给pre_cut()处理 <|skeleton|> class handler: def pre_cut(self): """根据point来将图片截取为多张...
3c02098163611eaa4a21994cded89912794b9338
<|skeleton|> class handler: def pre_cut(self): """根据point来将图片截取为多张图片,并识别生成excel""" <|body_0|> def handler_img(self): """读取文件夹里面的图片,并交给pre_cut()处理""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class handler: def pre_cut(self): """根据point来将图片截取为多张图片,并识别生成excel""" ins_col = 0 for point in self.points: time.sleep(2) ins_col = ins_col + 1 self.cut(point) trans_img = img_to_str(self.cut_img_name) row_content, col_content = tra...
the_stack_v2_python_sparse
other/ocr.py
sunjiebin/s12
train
0
eae781e58493abcefc29f5b15efb3bc5bd34b850
[ "super().__init__(form=form, bTxt=self.START_TEXT, bCmd=lambda: self.__toggleMic())\nself.__start = True\nself.__configure()", "self.__mic = Microphone()\nself._button.configure(foreground=self.FOREGROUND)\nself._button.configure(background=self.START_COLOR)", "if self.__start:\n self._button['text'] = self....
<|body_start_0|> super().__init__(form=form, bTxt=self.START_TEXT, bCmd=lambda: self.__toggleMic()) self.__start = True self.__configure() <|end_body_0|> <|body_start_1|> self.__mic = Microphone() self._button.configure(foreground=self.FOREGROUND) self._button.configure(...
Class for selecting sound file.
MicButton
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MicButton: """Class for selecting sound file.""" def __init__(self, form): """Construct object.""" <|body_0|> def __configure(self): """Initialize the look/location of the Button.""" <|body_1|> def __toggleMic(self): """Toggle the microphone ...
stack_v2_sparse_classes_36k_train_024743
1,853
no_license
[ { "docstring": "Construct object.", "name": "__init__", "signature": "def __init__(self, form)" }, { "docstring": "Initialize the look/location of the Button.", "name": "__configure", "signature": "def __configure(self)" }, { "docstring": "Toggle the microphone button to start/st...
3
stack_v2_sparse_classes_30k_train_000408
Implement the Python class `MicButton` described below. Class description: Class for selecting sound file. Method signatures and docstrings: - def __init__(self, form): Construct object. - def __configure(self): Initialize the look/location of the Button. - def __toggleMic(self): Toggle the microphone button to start...
Implement the Python class `MicButton` described below. Class description: Class for selecting sound file. Method signatures and docstrings: - def __init__(self, form): Construct object. - def __configure(self): Initialize the look/location of the Button. - def __toggleMic(self): Toggle the microphone button to start...
6d29e1e0b2335c90452a832373dcf3058cec33e9
<|skeleton|> class MicButton: """Class for selecting sound file.""" def __init__(self, form): """Construct object.""" <|body_0|> def __configure(self): """Initialize the look/location of the Button.""" <|body_1|> def __toggleMic(self): """Toggle the microphone ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class MicButton: """Class for selecting sound file.""" def __init__(self, form): """Construct object.""" super().__init__(form=form, bTxt=self.START_TEXT, bCmd=lambda: self.__toggleMic()) self.__start = True self.__configure() def __configure(self): """Initialize th...
the_stack_v2_python_sparse
emotionAnalyzer/gui/micButton.py
vkepuska/LivePitchTracking
train
0
231b9c86fcad9a224466518886a8356e98813ff4
[ "for arg in self.non_number_values:\n self.assertRaises(TypeError, prev1.proper_dividers_list, arg)\nfor arg, val in self.proper_dividers_values:\n self.assertEqual(prev1.proper_dividers_list(arg), val)", "for arg in self.non_number_values:\n self.assertRaises(TypeError, prev1.proper_dividers_fun, arg)\n...
<|body_start_0|> for arg in self.non_number_values: self.assertRaises(TypeError, prev1.proper_dividers_list, arg) for arg, val in self.proper_dividers_values: self.assertEqual(prev1.proper_dividers_list(arg), val) <|end_body_0|> <|body_start_1|> for arg in self.non_numbe...
TestProperDividers
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestProperDividers: def test_proper_dividers_list(self): """Testing proper_dividers_list function""" <|body_0|> def test_proper_dividers_fun(self): """Testing proper_dividers_fun function""" <|body_1|> def test_proper_dividers_map(self): """Testi...
stack_v2_sparse_classes_36k_train_024744
8,451
no_license
[ { "docstring": "Testing proper_dividers_list function", "name": "test_proper_dividers_list", "signature": "def test_proper_dividers_list(self)" }, { "docstring": "Testing proper_dividers_fun function", "name": "test_proper_dividers_fun", "signature": "def test_proper_dividers_fun(self)" ...
4
stack_v2_sparse_classes_30k_train_002525
Implement the Python class `TestProperDividers` described below. Class description: Implement the TestProperDividers class. Method signatures and docstrings: - def test_proper_dividers_list(self): Testing proper_dividers_list function - def test_proper_dividers_fun(self): Testing proper_dividers_fun function - def te...
Implement the Python class `TestProperDividers` described below. Class description: Implement the TestProperDividers class. Method signatures and docstrings: - def test_proper_dividers_list(self): Testing proper_dividers_list function - def test_proper_dividers_fun(self): Testing proper_dividers_fun function - def te...
0cd4bbe3feb63b248d643303433f9fb2fc2def79
<|skeleton|> class TestProperDividers: def test_proper_dividers_list(self): """Testing proper_dividers_list function""" <|body_0|> def test_proper_dividers_fun(self): """Testing proper_dividers_fun function""" <|body_1|> def test_proper_dividers_map(self): """Testi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestProperDividers: def test_proper_dividers_list(self): """Testing proper_dividers_list function""" for arg in self.non_number_values: self.assertRaises(TypeError, prev1.proper_dividers_list, arg) for arg, val in self.proper_dividers_values: self.assertEqual(pr...
the_stack_v2_python_sparse
Python - advanced course/Solutions/9/9.1.py
maxymilianz/CS-at-University-of-Wroclaw
train
0
ad44f625d79e3d60f639d5cbd137c2b7fed42049
[ "int_n = int(n)\nfor k in range(2, int_n):\n tmp = 0\n i = 0\n while tmp < int_n:\n tmp += k ** i\n i += 1\n if tmp == int_n:\n return str(k)", "n = int(n)\n\ndef check(k, len):\n tmp = 0\n for i in range(len):\n tmp += k ** i\n return tmp\nfor N in range(len(bin(n...
<|body_start_0|> int_n = int(n) for k in range(2, int_n): tmp = 0 i = 0 while tmp < int_n: tmp += k ** i i += 1 if tmp == int_n: return str(k) <|end_body_0|> <|body_start_1|> n = int(n) def ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def smallestGoodBase(self, n: str) -> str: """k^0+k^1+k^2... n > k >= 2 input = "1000000000000000000" 超时 :param n: :return:""" <|body_0|> def smallestGoodBase(self, n: str) -> str: """二分查找 bin()求出n的二进制(-2减去符号), 其他进制都小于二进制的长度 if tmp > n: r = mid - 1 if tmp <...
stack_v2_sparse_classes_36k_train_024745
2,087
no_license
[ { "docstring": "k^0+k^1+k^2... n > k >= 2 input = \"1000000000000000000\" 超时 :param n: :return:", "name": "smallestGoodBase", "signature": "def smallestGoodBase(self, n: str) -> str" }, { "docstring": "二分查找 bin()求出n的二进制(-2减去符号), 其他进制都小于二进制的长度 if tmp > n: r = mid - 1 if tmp < n: l = mid + 1 [l,r]...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestGoodBase(self, n: str) -> str: k^0+k^1+k^2... n > k >= 2 input = "1000000000000000000" 超时 :param n: :return: - def smallestGoodBase(self, n: str) -> str: 二分查找 bin()求出...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def smallestGoodBase(self, n: str) -> str: k^0+k^1+k^2... n > k >= 2 input = "1000000000000000000" 超时 :param n: :return: - def smallestGoodBase(self, n: str) -> str: 二分查找 bin()求出...
b1680014ce3f55ba952a1e64241c0cbb783cc436
<|skeleton|> class Solution: def smallestGoodBase(self, n: str) -> str: """k^0+k^1+k^2... n > k >= 2 input = "1000000000000000000" 超时 :param n: :return:""" <|body_0|> def smallestGoodBase(self, n: str) -> str: """二分查找 bin()求出n的二进制(-2减去符号), 其他进制都小于二进制的长度 if tmp > n: r = mid - 1 if tmp <...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def smallestGoodBase(self, n: str) -> str: """k^0+k^1+k^2... n > k >= 2 input = "1000000000000000000" 超时 :param n: :return:""" int_n = int(n) for k in range(2, int_n): tmp = 0 i = 0 while tmp < int_n: tmp += k ** i ...
the_stack_v2_python_sparse
a_483.py
sun510001/leetcode_jianzhi_offer_2
train
0
5adf9955f31264db3543ee2bfb31382d184bbb69
[ "try:\n ilp.solve(pulp.GLPK())\n assert round(pulp.value(ilp.objective), 0) == 5\nexcept pulp.solvers.PulpSolverError:\n pytest.fail(f'Solver not installed')", "try:\n ilp.solve(pulp.COIN())\n assert round(pulp.value(ilp.objective), 0) == 5\nexcept pulp.solvers.PulpSolverError:\n pytest.fail(f'S...
<|body_start_0|> try: ilp.solve(pulp.GLPK()) assert round(pulp.value(ilp.objective), 0) == 5 except pulp.solvers.PulpSolverError: pytest.fail(f'Solver not installed') <|end_body_0|> <|body_start_1|> try: ilp.solve(pulp.COIN()) assert r...
Test Installed Solvers.
TestSolver
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestSolver: """Test Installed Solvers.""" def test_glpk(self, ilp): """Test method for GLPK.""" <|body_0|> def test_cbc(self, ilp): """Test method for CBC.""" <|body_1|> def test_cplex(self, ilp): """Test method for CPLEX.""" <|body_2...
stack_v2_sparse_classes_36k_train_024746
1,770
permissive
[ { "docstring": "Test method for GLPK.", "name": "test_glpk", "signature": "def test_glpk(self, ilp)" }, { "docstring": "Test method for CBC.", "name": "test_cbc", "signature": "def test_cbc(self, ilp)" }, { "docstring": "Test method for CPLEX.", "name": "test_cplex", "sig...
5
stack_v2_sparse_classes_30k_train_002588
Implement the Python class `TestSolver` described below. Class description: Test Installed Solvers. Method signatures and docstrings: - def test_glpk(self, ilp): Test method for GLPK. - def test_cbc(self, ilp): Test method for CBC. - def test_cplex(self, ilp): Test method for CPLEX. - def test_gurobi(self, ilp): Test...
Implement the Python class `TestSolver` described below. Class description: Test Installed Solvers. Method signatures and docstrings: - def test_glpk(self, ilp): Test method for GLPK. - def test_cbc(self, ilp): Test method for CBC. - def test_cplex(self, ilp): Test method for CPLEX. - def test_gurobi(self, ilp): Test...
12f696633743825b34556180eed171649a26f05d
<|skeleton|> class TestSolver: """Test Installed Solvers.""" def test_glpk(self, ilp): """Test method for GLPK.""" <|body_0|> def test_cbc(self, ilp): """Test method for CBC.""" <|body_1|> def test_cplex(self, ilp): """Test method for CPLEX.""" <|body_2...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TestSolver: """Test Installed Solvers.""" def test_glpk(self, ilp): """Test method for GLPK.""" try: ilp.solve(pulp.GLPK()) assert round(pulp.value(ilp.objective), 0) == 5 except pulp.solvers.PulpSolverError: pytest.fail(f'Solver not installed')...
the_stack_v2_python_sparse
check_installed_solvers.py
atomassi/mapping_distrinet
train
2
6deea93b94d6b74e2c53f73415426eff47e37a84
[ "hash1 = generate_password_hash('default')\nhash2 = generate_password_hash(u'default', method='sha1')\nassert hash1 != hash2\nassert check_password_hash(hash1, 'default')\nassert check_password_hash(hash2, 'default')\nassert hash1.startswith('sha1$')\nassert hash2.startswith('sha1$')\nfakehash = generate_password_h...
<|body_start_0|> hash1 = generate_password_hash('default') hash2 = generate_password_hash(u'default', method='sha1') assert hash1 != hash2 assert check_password_hash(hash1, 'default') assert check_password_hash(hash2, 'default') assert hash1.startswith('sha1$') as...
SecurityTestCase
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecurityTestCase: def test_password_hashing(self): """Test the password hashing and password hash checking""" <|body_0|> def test_safe_join(self): """Test the safe joining helper""" <|body_1|> <|end_skeleton|> <|body_start_0|> hash1 = generate_passw...
stack_v2_sparse_classes_36k_train_024747
1,838
permissive
[ { "docstring": "Test the password hashing and password hash checking", "name": "test_password_hashing", "signature": "def test_password_hashing(self)" }, { "docstring": "Test the safe joining helper", "name": "test_safe_join", "signature": "def test_safe_join(self)" } ]
2
stack_v2_sparse_classes_30k_train_004629
Implement the Python class `SecurityTestCase` described below. Class description: Implement the SecurityTestCase class. Method signatures and docstrings: - def test_password_hashing(self): Test the password hashing and password hash checking - def test_safe_join(self): Test the safe joining helper
Implement the Python class `SecurityTestCase` described below. Class description: Implement the SecurityTestCase class. Method signatures and docstrings: - def test_password_hashing(self): Test the password hashing and password hash checking - def test_safe_join(self): Test the safe joining helper <|skeleton|> class...
6641120dfac24800a25214daaf594b5d534fc9bd
<|skeleton|> class SecurityTestCase: def test_password_hashing(self): """Test the password hashing and password hash checking""" <|body_0|> def test_safe_join(self): """Test the safe joining helper""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SecurityTestCase: def test_password_hashing(self): """Test the password hashing and password hash checking""" hash1 = generate_password_hash('default') hash2 = generate_password_hash(u'default', method='sha1') assert hash1 != hash2 assert check_password_hash(hash1, 'def...
the_stack_v2_python_sparse
gcm_flask/werkzeug/testsuite/security.py
BCB-PWA-Team/Barcamp-Bangalore-Android-App
train
0
5b08bd32f6843c2a5eb398330af3ad1ff11a44e9
[ "super(PreprocessorSelfSupervised, self).__init__(root_dir=root_dir, patch_size=patch_size, pad_type=pad_type, look_for_labels=look_for_labels, crop=crop, spacing=spacing)\nself.transforms = [{'name': 'Mirroring', 'execution_probability': 0.5}]\nself.type = 'self-supervised'", "image, _ = super(PreprocessorSelfSu...
<|body_start_0|> super(PreprocessorSelfSupervised, self).__init__(root_dir=root_dir, patch_size=patch_size, pad_type=pad_type, look_for_labels=look_for_labels, crop=crop, spacing=spacing) self.transforms = [{'name': 'Mirroring', 'execution_probability': 0.5}] self.type = 'self-supervised' <|end_...
PreprocessorSelfSupervised class. Extends the original class by not processing the labels and saving the processed data.
PreprocessorSelfSupervised
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreprocessorSelfSupervised: """PreprocessorSelfSupervised class. Extends the original class by not processing the labels and saving the processed data.""" def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=False, spacing=(0.8, 0.8, 0.8...
stack_v2_sparse_classes_36k_train_024748
19,145
no_license
[ { "docstring": "PreprocessorSelfSupervised constructor, extending the Preprocessor constructor by defining augumentations and level of supervision. Args: root_dir (string): path to folder containing raw data. Defaults to '../raw'. patch_size (tuple of ints): patch size for padding and croping calculation. Defau...
2
stack_v2_sparse_classes_30k_train_011968
Implement the Python class `PreprocessorSelfSupervised` described below. Class description: PreprocessorSelfSupervised class. Extends the original class by not processing the labels and saving the processed data. Method signatures and docstrings: - def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2...
Implement the Python class `PreprocessorSelfSupervised` described below. Class description: PreprocessorSelfSupervised class. Extends the original class by not processing the labels and saving the processed data. Method signatures and docstrings: - def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2...
d89f696a1404f5793b71ca46261055a7f4575497
<|skeleton|> class PreprocessorSelfSupervised: """PreprocessorSelfSupervised class. Extends the original class by not processing the labels and saving the processed data.""" def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=False, spacing=(0.8, 0.8, 0.8...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PreprocessorSelfSupervised: """PreprocessorSelfSupervised class. Extends the original class by not processing the labels and saving the processed data.""" def __init__(self, root_dir='../raw', patch_size=(64, 64, 32), crop=2, pad_type='zero_pad', look_for_labels=False, spacing=(0.8, 0.8, 0.8), **kwargs):...
the_stack_v2_python_sparse
source/dataset/preprocessor.py
BereznyMatej/IBT
train
0
e249a07fb698ae1884ce89db87ee0c0445f581cd
[ "Email = self.cleaned_data.get('Email')\ndominio = Email.split('@')[-1].split('.')\nif dominio[0] in ['gmail', 'hotmail', 'outlook', 'yahoo', 'live'] and dominio[1] in ['com', 'mx', 'live']:\n return Email\nelse:\n raise forms.ValidationError(\"¡Ingresa un correo electrónico valido, ya sea de 'google', 'hotma...
<|body_start_0|> Email = self.cleaned_data.get('Email') dominio = Email.split('@')[-1].split('.') if dominio[0] in ['gmail', 'hotmail', 'outlook', 'yahoo', 'live'] and dominio[1] in ['com', 'mx', 'live']: return Email else: raise forms.ValidationError("¡Ingresa un...
ReservacionForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReservacionForm: def clean_Email(self): """Si el Email brindado ya existe en la base de datos, regresamos None para evitar la multiplicidad del mismo correo. Teniendo así, un correo por cliente sin importar el número de reservaciones que esté realice.""" <|body_0|> def clean...
stack_v2_sparse_classes_36k_train_024749
4,491
no_license
[ { "docstring": "Si el Email brindado ya existe en la base de datos, regresamos None para evitar la multiplicidad del mismo correo. Teniendo así, un correo por cliente sin importar el número de reservaciones que esté realice.", "name": "clean_Email", "signature": "def clean_Email(self)" }, { "doc...
2
stack_v2_sparse_classes_30k_train_004813
Implement the Python class `ReservacionForm` described below. Class description: Implement the ReservacionForm class. Method signatures and docstrings: - def clean_Email(self): Si el Email brindado ya existe en la base de datos, regresamos None para evitar la multiplicidad del mismo correo. Teniendo así, un correo po...
Implement the Python class `ReservacionForm` described below. Class description: Implement the ReservacionForm class. Method signatures and docstrings: - def clean_Email(self): Si el Email brindado ya existe en la base de datos, regresamos None para evitar la multiplicidad del mismo correo. Teniendo así, un correo po...
d5041229d2ddd223a818020efa2ea4efb4339429
<|skeleton|> class ReservacionForm: def clean_Email(self): """Si el Email brindado ya existe en la base de datos, regresamos None para evitar la multiplicidad del mismo correo. Teniendo así, un correo por cliente sin importar el número de reservaciones que esté realice.""" <|body_0|> def clean...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ReservacionForm: def clean_Email(self): """Si el Email brindado ya existe en la base de datos, regresamos None para evitar la multiplicidad del mismo correo. Teniendo así, un correo por cliente sin importar el número de reservaciones que esté realice.""" Email = self.cleaned_data.get('Email') ...
the_stack_v2_python_sparse
sitioweb_sasor/reservacion/forms.py
DanielRosasPerez/SitioWeb_Restaurante
train
0
a072e9bd8e46081428855d315bb777f223028f5f
[ "work_on = self.clean_urls(provider.get('url', []))\nfor url in work_on:\n if self.supports_url(url):\n return True\nreturn False", "for bu in self.base_urls:\n if self.clean_url(url).startswith(bu):\n return True\nreturn False", "lic_statements = [{'under the Creative Commons Attribution 3....
<|body_start_0|> work_on = self.clean_urls(provider.get('url', [])) for url in work_on: if self.supports_url(url): return True return False <|end_body_0|> <|body_start_1|> for bu in self.base_urls: if self.clean_url(url).startswith(bu): ...
COPERNICUSPlugin
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class COPERNICUSPlugin: def supports(self, provider): """Does this plugin support this provider""" <|body_0|> def supports_url(self, url): """Same as the supports() function but answers the question for a single URL.""" <|body_1|> def license_detect(self, reco...
stack_v2_sparse_classes_36k_train_024750
2,267
permissive
[ { "docstring": "Does this plugin support this provider", "name": "supports", "signature": "def supports(self, provider)" }, { "docstring": "Same as the supports() function but answers the question for a single URL.", "name": "supports_url", "signature": "def supports_url(self, url)" },...
3
stack_v2_sparse_classes_30k_train_000989
Implement the Python class `COPERNICUSPlugin` described below. Class description: Implement the COPERNICUSPlugin class. Method signatures and docstrings: - def supports(self, provider): Does this plugin support this provider - def supports_url(self, url): Same as the supports() function but answers the question for a...
Implement the Python class `COPERNICUSPlugin` described below. Class description: Implement the COPERNICUSPlugin class. Method signatures and docstrings: - def supports(self, provider): Does this plugin support this provider - def supports_url(self, url): Same as the supports() function but answers the question for a...
280ba5dcbc508ec01093b8bc2a76aee5a9793723
<|skeleton|> class COPERNICUSPlugin: def supports(self, provider): """Does this plugin support this provider""" <|body_0|> def supports_url(self, url): """Same as the supports() function but answers the question for a single URL.""" <|body_1|> def license_detect(self, reco...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class COPERNICUSPlugin: def supports(self, provider): """Does this plugin support this provider""" work_on = self.clean_urls(provider.get('url', [])) for url in work_on: if self.supports_url(url): return True return False def supports_url(self, url): ...
the_stack_v2_python_sparse
openarticlegauge/plugins/copernicus.py
cameronneylon/OpenArticleGauge
train
0
4d6e6102e133611e90b6ea6322d6b12d7d0dd91b
[ "if type(N) is not int:\n raise TypeError('N must be int representing number of blocks in the encoder')\nif type(dm) is not int:\n raise TypeError('dm must be int representing dimensionality of model')\nif type(h) is not int:\n raise TypeError('h must be int representing number of heads')\nif type(hidden) ...
<|body_start_0|> if type(N) is not int: raise TypeError('N must be int representing number of blocks in the encoder') if type(dm) is not int: raise TypeError('dm must be int representing dimensionality of model') if type(h) is not int: raise TypeError('h must ...
Class to create the transformer network class constructor: def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1) public instance attributes: encoder: the encoder layer decoder: the decoder layer linear: the Dense layer with target_vocab units public instance metho...
Transformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Transformer: """Class to create the transformer network class constructor: def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1) public instance attributes: encoder: the encoder layer decoder: the decoder layer linear: the Dense layer with t...
stack_v2_sparse_classes_36k_train_024751
4,876
no_license
[ { "docstring": "Class constructor parameters: N [int]: represents the number of blocks in the encoder and decoder dm [int]: represents the dimensionality of the model h [int]: represents the number of heads hidden [int]: represents the number of hidden units in fully connected layer input_vocab [int]: represent...
2
null
Implement the Python class `Transformer` described below. Class description: Class to create the transformer network class constructor: def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1) public instance attributes: encoder: the encoder layer decoder: the decod...
Implement the Python class `Transformer` described below. Class description: Class to create the transformer network class constructor: def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1) public instance attributes: encoder: the encoder layer decoder: the decod...
8834b201ca84937365e4dcc0fac978656cdf5293
<|skeleton|> class Transformer: """Class to create the transformer network class constructor: def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1) public instance attributes: encoder: the encoder layer decoder: the decoder layer linear: the Dense layer with t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Transformer: """Class to create the transformer network class constructor: def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1) public instance attributes: encoder: the encoder layer decoder: the decoder layer linear: the Dense layer with target_vocab u...
the_stack_v2_python_sparse
supervised_learning/0x11-attention/11-transformer.py
ejonakodra/holbertonschool-machine_learning-1
train
0
a55dc6594227a004dd2dff0d2226e071150cc0fe
[ "data = csv.reader(open(path), delimiter='\\t', quoting=csv.QUOTE_NONE)\nrows = []\nfor x, row in enumerate(data):\n score = float(row[4]) / 5.0\n rows.append((x + 1, score, row[5], row[6]))\nreturn rows", "print('Building model')\nembeddings = Embeddings({'path': Models.vectorPath(vector), 'scoring': score...
<|body_start_0|> data = csv.reader(open(path), delimiter='\t', quoting=csv.QUOTE_NONE) rows = [] for x, row in enumerate(data): score = float(row[4]) / 5.0 rows.append((x + 1, score, row[5], row[6])) return rows <|end_body_0|> <|body_start_1|> print('Buil...
STS Benchmark Dataset General text similarity http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark
STS
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class STS: """STS Benchmark Dataset General text similarity http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark""" def read(path): """Reads a STS data file. Args: path: full path to file Returns: rows""" <|body_0|> def train(vector, score): """Trains an Embeddings mod...
stack_v2_sparse_classes_36k_train_024752
6,859
permissive
[ { "docstring": "Reads a STS data file. Args: path: full path to file Returns: rows", "name": "read", "signature": "def read(path)" }, { "docstring": "Trains an Embeddings model on STS dev + train data. Args: vector: word vector model path score: scoring method (bm25, sif, tfidf or None for avera...
4
stack_v2_sparse_classes_30k_train_019461
Implement the Python class `STS` described below. Class description: STS Benchmark Dataset General text similarity http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark Method signatures and docstrings: - def read(path): Reads a STS data file. Args: path: full path to file Returns: rows - def train(vector, score): Tra...
Implement the Python class `STS` described below. Class description: STS Benchmark Dataset General text similarity http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark Method signatures and docstrings: - def read(path): Reads a STS data file. Args: path: full path to file Returns: rows - def train(vector, score): Tra...
c1fde2fcb3cf830247131385ec5340e6a148e70a
<|skeleton|> class STS: """STS Benchmark Dataset General text similarity http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark""" def read(path): """Reads a STS data file. Args: path: full path to file Returns: rows""" <|body_0|> def train(vector, score): """Trains an Embeddings mod...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class STS: """STS Benchmark Dataset General text similarity http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark""" def read(path): """Reads a STS data file. Args: path: full path to file Returns: rows""" data = csv.reader(open(path), delimiter='\t', quoting=csv.QUOTE_NONE) rows = [] ...
the_stack_v2_python_sparse
src/python/codequestion/evaluate.py
spreck/codequestion
train
0
12f9b4d30774393712a613afe07d1ec9ebf67e1c
[ "super(RedactingPIIFilter, self).__init__()\nself.scrubber = self._get_scrubber()\nself._patterns = patterns", "scrubber = scrubadub.Scrubber()\nscrubber.remove_detector('email')\nscrubber.remove_detector('name')\nscrubber.remove_detector('phone')\nscrubber.add_detector(TINDetector)\nreturn scrubber", "record.m...
<|body_start_0|> super(RedactingPIIFilter, self).__init__() self.scrubber = self._get_scrubber() self._patterns = patterns <|end_body_0|> <|body_start_1|> scrubber = scrubadub.Scrubber() scrubber.remove_detector('email') scrubber.remove_detector('name') scrubber....
Redacting filter to remove PII information.
RedactingPIIFilter
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RedactingPIIFilter: """Redacting filter to remove PII information.""" def __init__(self, patterns=[]): """Initialize PII filter. New patterns can be given as input.""" <|body_0|> def _get_scrubber(): """Initialize a scrubber with phone, skype, ssn, tin and url de...
stack_v2_sparse_classes_36k_train_024753
1,926
permissive
[ { "docstring": "Initialize PII filter. New patterns can be given as input.", "name": "__init__", "signature": "def __init__(self, patterns=[])" }, { "docstring": "Initialize a scrubber with phone, skype, ssn, tin and url detector.", "name": "_get_scrubber", "signature": "def _get_scrubbe...
4
stack_v2_sparse_classes_30k_train_015624
Implement the Python class `RedactingPIIFilter` described below. Class description: Redacting filter to remove PII information. Method signatures and docstrings: - def __init__(self, patterns=[]): Initialize PII filter. New patterns can be given as input. - def _get_scrubber(): Initialize a scrubber with phone, skype...
Implement the Python class `RedactingPIIFilter` described below. Class description: Redacting filter to remove PII information. Method signatures and docstrings: - def __init__(self, patterns=[]): Initialize PII filter. New patterns can be given as input. - def _get_scrubber(): Initialize a scrubber with phone, skype...
1e2da9494faf9e316a17cbe899284db9e61d0902
<|skeleton|> class RedactingPIIFilter: """Redacting filter to remove PII information.""" def __init__(self, patterns=[]): """Initialize PII filter. New patterns can be given as input.""" <|body_0|> def _get_scrubber(): """Initialize a scrubber with phone, skype, ssn, tin and url de...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class RedactingPIIFilter: """Redacting filter to remove PII information.""" def __init__(self, patterns=[]): """Initialize PII filter. New patterns can be given as input.""" super(RedactingPIIFilter, self).__init__() self.scrubber = self._get_scrubber() self._patterns = patterns...
the_stack_v2_python_sparse
claims_to_quality/lib/qpp_logging/pii_scrubber.py
gaybro8777/qpp-claims-to-quality-public
train
0
e382713dbf6209d3d754f3a0e1e13855f155fb67
[ "request = data_set.get('request')\nuser = data_set.get('user')\nif user:\n username = cls.analyze(user, uuid)\n driver = cls.analyze_class.get_user(username)\n CompatAPPDriver.driver = driver\nelse:\n user = data_set.get('session')\n driver = cls.session_class.get_session(user)\nfor step in request:...
<|body_start_0|> request = data_set.get('request') user = data_set.get('user') if user: username = cls.analyze(user, uuid) driver = cls.analyze_class.get_user(username) CompatAPPDriver.driver = driver else: user = data_set.get('session') ...
APPDriver
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class APPDriver: def run(cls, data_set, uuid, host, **kwargs): """Webdriver驱动执行浏览器元素定位与元素动作操作 :param data_set: 测试用例节点信息 { "path": "/login", "user": "user1", "version": 2, "request": [ {"eventName": "元素点击", "event": "click", "locations": ["css selector", "#kw"], "input": "输入内容"}, {"eventName": ...
stack_v2_sparse_classes_36k_train_024754
6,213
permissive
[ { "docstring": "Webdriver驱动执行浏览器元素定位与元素动作操作 :param data_set: 测试用例节点信息 { \"path\": \"/login\", \"user\": \"user1\", \"version\": 2, \"request\": [ {\"eventName\": \"元素点击\", \"event\": \"click\", \"locations\": [\"css selector\", \"#kw\"], \"input\": \"输入内容\"}, {\"eventName\": \"元素名称\", \"event\": \"click\", \"lo...
2
stack_v2_sparse_classes_30k_train_002417
Implement the Python class `APPDriver` described below. Class description: Implement the APPDriver class. Method signatures and docstrings: - def run(cls, data_set, uuid, host, **kwargs): Webdriver驱动执行浏览器元素定位与元素动作操作 :param data_set: 测试用例节点信息 { "path": "/login", "user": "user1", "version": 2, "request": [ {"eventName"...
Implement the Python class `APPDriver` described below. Class description: Implement the APPDriver class. Method signatures and docstrings: - def run(cls, data_set, uuid, host, **kwargs): Webdriver驱动执行浏览器元素定位与元素动作操作 :param data_set: 测试用例节点信息 { "path": "/login", "user": "user1", "version": 2, "request": [ {"eventName"...
5ecae8652c9f71aaa78cc0fd181d431cb130cab1
<|skeleton|> class APPDriver: def run(cls, data_set, uuid, host, **kwargs): """Webdriver驱动执行浏览器元素定位与元素动作操作 :param data_set: 测试用例节点信息 { "path": "/login", "user": "user1", "version": 2, "request": [ {"eventName": "元素点击", "event": "click", "locations": ["css selector", "#kw"], "input": "输入内容"}, {"eventName": ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class APPDriver: def run(cls, data_set, uuid, host, **kwargs): """Webdriver驱动执行浏览器元素定位与元素动作操作 :param data_set: 测试用例节点信息 { "path": "/login", "user": "user1", "version": 2, "request": [ {"eventName": "元素点击", "event": "click", "locations": ["css selector", "#kw"], "input": "输入内容"}, {"eventName": "元素名称", "event...
the_stack_v2_python_sparse
giantstar/drivers/appDriver.py
DaoSen-v/giantstar
train
0
709b7a281bac1f3d1f7541e5bddaa9a7e7cf4786
[ "super(VeryDeepNieFineCoattention, self).__init__()\nself.n_lt_layers = 2\nwith self.init_scope():\n self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1)\n self.attention_layer_1 = GraphLinear(head, 1, nobias=True)\n self.attention_layer_2 = GraphLinear(head, 1, nobias=True)\n self.prev_lt_laye...
<|body_start_0|> super(VeryDeepNieFineCoattention, self).__init__() self.n_lt_layers = 2 with self.init_scope(): self.energy_layer = links.Bilinear(hidden_dim, hidden_dim, 1) self.attention_layer_1 = GraphLinear(head, 1, nobias=True) self.attention_layer_2 = G...
TODO
VeryDeepNieFineCoattention
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VeryDeepNieFineCoattention: """TODO""" def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): """:param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism""" ...
stack_v2_sparse_classes_36k_train_024755
25,561
permissive
[ { "docstring": ":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism", "name": "__init__", "signature": "def __init__(self, hidden_dim, out_dim, head, activation=functions.identity)" }, { "do...
3
stack_v2_sparse_classes_30k_train_019058
Implement the Python class `VeryDeepNieFineCoattention` described below. Class description: TODO Method signatures and docstrings: - def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :...
Implement the Python class `VeryDeepNieFineCoattention` described below. Class description: TODO Method signatures and docstrings: - def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): :param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :...
21b64a3c8cc9bc33718ae09c65aa917e575132eb
<|skeleton|> class VeryDeepNieFineCoattention: """TODO""" def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): """:param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VeryDeepNieFineCoattention: """TODO""" def __init__(self, hidden_dim, out_dim, head, activation=functions.identity): """:param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation :param head: number of heads in attention mechanism""" super(Ve...
the_stack_v2_python_sparse
models/coattention/nie_coattention.py
Minys233/GCN-BMP
train
1
b81c9bc57bb9ec7b07cf341d71c0afce53294774
[ "self.args, self.setup = (args, setup)\nself.batch_size = batch_size\nself.augmentations = augmentations\nself.mixing_method = mixing_method\nwith open(args.file.name, 'rb') as handle:\n data_package = pickle.load(handle)\nif 'xtrain' in data_package.keys():\n self.trainset, self.validset, self.poisonset, sel...
<|body_start_0|> self.args, self.setup = (args, setup) self.batch_size = batch_size self.augmentations = augmentations self.mixing_method = mixing_method with open(args.file.name, 'rb') as handle: data_package = pickle.load(handle) if 'xtrain' in data_package....
Generate a dataset definition completely from file
KettleExternal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KettleExternal: """Generate a dataset definition completely from file""" def __init__(self, args, batch_size, augmentations, mixing_method=dict(type=None, strength=0.0), setup=dict(device=torch.device('cpu'), dtype=torch.float)): """Initialize with given specs...""" <|body_0|...
stack_v2_sparse_classes_36k_train_024756
5,772
no_license
[ { "docstring": "Initialize with given specs...", "name": "__init__", "signature": "def __init__(self, args, batch_size, augmentations, mixing_method=dict(type=None, strength=0.0), setup=dict(device=torch.device('cpu'), dtype=torch.float))" }, { "docstring": "Load a metapoison package. xtrain: CI...
2
stack_v2_sparse_classes_30k_val_000027
Implement the Python class `KettleExternal` described below. Class description: Generate a dataset definition completely from file Method signatures and docstrings: - def __init__(self, args, batch_size, augmentations, mixing_method=dict(type=None, strength=0.0), setup=dict(device=torch.device('cpu'), dtype=torch.flo...
Implement the Python class `KettleExternal` described below. Class description: Generate a dataset definition completely from file Method signatures and docstrings: - def __init__(self, args, batch_size, augmentations, mixing_method=dict(type=None, strength=0.0), setup=dict(device=torch.device('cpu'), dtype=torch.flo...
cedfa1dab4c7bbd0a2fe350664b4c0a885583c08
<|skeleton|> class KettleExternal: """Generate a dataset definition completely from file""" def __init__(self, args, batch_size, augmentations, mixing_method=dict(type=None, strength=0.0), setup=dict(device=torch.device('cpu'), dtype=torch.float)): """Initialize with given specs...""" <|body_0|...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class KettleExternal: """Generate a dataset definition completely from file""" def __init__(self, args, batch_size, augmentations, mixing_method=dict(type=None, strength=0.0), setup=dict(device=torch.device('cpu'), dtype=torch.float)): """Initialize with given specs...""" self.args, self.setup ...
the_stack_v2_python_sparse
forest/data/kettle_external.py
hsouri/Sleeper-Agent
train
51
240095c0488be53dfe26b4c0c5b361b176b79cf8
[ "self.login()\nclient = Clients.objects.first()\nng = NotificationGroups.objects.first()\nresponse = self.client.get(reverse('linkednotifcationgroups'), {'client_id': client.id}, format='json')\nexpected = NotificationGroups.objects.filter(contacts__client_id=client.id)\nserializer = DropDownSerializer(expected, ma...
<|body_start_0|> self.login() client = Clients.objects.first() ng = NotificationGroups.objects.first() response = self.client.get(reverse('linkednotifcationgroups'), {'client_id': client.id}, format='json') expected = NotificationGroups.objects.filter(contacts__client_id=client.i...
GetSamplesTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GetSamplesTest: def test_get_linked_notify_groups(self): """This test ensures that notification groups attached to the client id are returned""" <|body_0|> def test_get_all_samples(self): """This test ensures that all samples added in the setUp method exist when loop...
stack_v2_sparse_classes_36k_train_024757
19,832
no_license
[ { "docstring": "This test ensures that notification groups attached to the client id are returned", "name": "test_get_linked_notify_groups", "signature": "def test_get_linked_notify_groups(self)" }, { "docstring": "This test ensures that all samples added in the setUp method exist when loop thro...
3
stack_v2_sparse_classes_30k_train_003473
Implement the Python class `GetSamplesTest` described below. Class description: Implement the GetSamplesTest class. Method signatures and docstrings: - def test_get_linked_notify_groups(self): This test ensures that notification groups attached to the client id are returned - def test_get_all_samples(self): This test...
Implement the Python class `GetSamplesTest` described below. Class description: Implement the GetSamplesTest class. Method signatures and docstrings: - def test_get_linked_notify_groups(self): This test ensures that notification groups attached to the client id are returned - def test_get_all_samples(self): This test...
1c6e2cf3b0d347e68d4b105e4d2b12824a2ae0fb
<|skeleton|> class GetSamplesTest: def test_get_linked_notify_groups(self): """This test ensures that notification groups attached to the client id are returned""" <|body_0|> def test_get_all_samples(self): """This test ensures that all samples added in the setUp method exist when loop...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class GetSamplesTest: def test_get_linked_notify_groups(self): """This test ensures that notification groups attached to the client id are returned""" self.login() client = Clients.objects.first() ng = NotificationGroups.objects.first() response = self.client.get(reverse('lin...
the_stack_v2_python_sparse
eldashboard/tests.py
ahmedsaatci/lims
train
0
1cfce9e0c5e5f69a1e1a659548de04ba80ba7bcd
[ "super().__init__()\nself.data = data\nself.noise_map = noise_map", "xvalues = np.arange(self.data.shape[0])\nmodel_data = instance.model_data_1d_via_xvalues_from(xvalues=xvalues)\nresidual_map = self.data - model_data\nchi_squared_map = (residual_map / self.noise_map) ** 2.0\nchi_squared = sum(chi_squared_map)\n...
<|body_start_0|> super().__init__() self.data = data self.noise_map = noise_map <|end_body_0|> <|body_start_1|> xvalues = np.arange(self.data.shape[0]) model_data = instance.model_data_1d_via_xvalues_from(xvalues=xvalues) residual_map = self.data - model_data chi...
Analysis
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Analysis: def __init__(self, data: np.ndarray, noise_map: np.ndarray): """Standard Analysis class example used throughout PyAutoFit examples.""" <|body_0|> def log_likelihood_function(self, instance) -> float: """Standard log likelihood function used throughout PyAut...
stack_v2_sparse_classes_36k_train_024758
20,890
no_license
[ { "docstring": "Standard Analysis class example used throughout PyAutoFit examples.", "name": "__init__", "signature": "def __init__(self, data: np.ndarray, noise_map: np.ndarray)" }, { "docstring": "Standard log likelihood function used throughout PyAutoFit examples.", "name": "log_likeliho...
4
stack_v2_sparse_classes_30k_test_000089
Implement the Python class `Analysis` described below. Class description: Implement the Analysis class. Method signatures and docstrings: - def __init__(self, data: np.ndarray, noise_map: np.ndarray): Standard Analysis class example used throughout PyAutoFit examples. - def log_likelihood_function(self, instance) -> ...
Implement the Python class `Analysis` described below. Class description: Implement the Analysis class. Method signatures and docstrings: - def __init__(self, data: np.ndarray, noise_map: np.ndarray): Standard Analysis class example used throughout PyAutoFit examples. - def log_likelihood_function(self, instance) -> ...
ac76dfef4643189a130ce18d23070bb81272a93c
<|skeleton|> class Analysis: def __init__(self, data: np.ndarray, noise_map: np.ndarray): """Standard Analysis class example used throughout PyAutoFit examples.""" <|body_0|> def log_likelihood_function(self, instance) -> float: """Standard log likelihood function used throughout PyAut...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Analysis: def __init__(self, data: np.ndarray, noise_map: np.ndarray): """Standard Analysis class example used throughout PyAutoFit examples.""" super().__init__() self.data = data self.noise_map = noise_map def log_likelihood_function(self, instance) -> float: """...
the_stack_v2_python_sparse
scripts/cookbooks/database.py
Jammy2211/autofit_workspace
train
6
60171a16cd96548f1768ae642e4e5494d52933c3
[ "ret = 0\nif len(A) < 3:\n return ret\nstart, end = (0, 1)\nwhile end < len(A):\n if A[end] <= A[start]:\n start = end\n end += 1\n else:\n peak = end + 1\n while peak < len(A) and A[peak] > A[peak - 1]:\n peak += 1\n peak -= 1\n end = peak + 1\n ...
<|body_start_0|> ret = 0 if len(A) < 3: return ret start, end = (0, 1) while end < len(A): if A[end] <= A[start]: start = end end += 1 else: peak = end + 1 while peak < len(A) and A[peak] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestMountain(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def longestMountain2(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ret = 0 if len(A) < 3: retur...
stack_v2_sparse_classes_36k_train_024759
2,431
no_license
[ { "docstring": ":type A: List[int] :rtype: int", "name": "longestMountain", "signature": "def longestMountain(self, A)" }, { "docstring": ":type A: List[int] :rtype: int", "name": "longestMountain2", "signature": "def longestMountain2(self, A)" } ]
2
stack_v2_sparse_classes_30k_train_001772
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestMountain(self, A): :type A: List[int] :rtype: int - def longestMountain2(self, A): :type A: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestMountain(self, A): :type A: List[int] :rtype: int - def longestMountain2(self, A): :type A: List[int] :rtype: int <|skeleton|> class Solution: def longestMountai...
9190d3d178f1733aa226973757ee7e045b7bab00
<|skeleton|> class Solution: def longestMountain(self, A): """:type A: List[int] :rtype: int""" <|body_0|> def longestMountain2(self, A): """:type A: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def longestMountain(self, A): """:type A: List[int] :rtype: int""" ret = 0 if len(A) < 3: return ret start, end = (0, 1) while end < len(A): if A[end] <= A[start]: start = end end += 1 else: ...
the_stack_v2_python_sparse
LongestMountainInArray.py
ellinx/LC-python
train
1
e26a9c412592d46c702218a52e8c251518d952a0
[ "def dfs(x):\n if x == n:\n res.append(self.removeFirstZero(''.join(num)))\n return\n else:\n for i in range(10):\n num[x] = str(i)\n dfs(x + 1)\nres = []\nnum = ['0'] * n\ndfs(0)\nreturn res", "if int(num_str) == 0:\n return '0'\ni = 0\ndone = False\nwhile i < ...
<|body_start_0|> def dfs(x): if x == n: res.append(self.removeFirstZero(''.join(num))) return else: for i in range(10): num[x] = str(i) dfs(x + 1) res = [] num = ['0'] * n dfs(...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def printNumbers(self, n: int) -> [int]: """打印 “从 1至最大的 n 位数的列表” 常规思路就是用list(range(1, n))直接打印 但是当n比较大时,它会超出int32整型的取值范围,超出取值范围的字无法正常存储。因此需要考虑大数越界问题。 注意:我们可以观察到该列表是一个n位0-9的全排列,该列全排列的问题都可以使用这个代码来写 :param n: :return:""" <|body_0|> def removeFirstZero(self, num_str): ...
stack_v2_sparse_classes_36k_train_024760
1,653
no_license
[ { "docstring": "打印 “从 1至最大的 n 位数的列表” 常规思路就是用list(range(1, n))直接打印 但是当n比较大时,它会超出int32整型的取值范围,超出取值范围的字无法正常存储。因此需要考虑大数越界问题。 注意:我们可以观察到该列表是一个n位0-9的全排列,该列全排列的问题都可以使用这个代码来写 :param n: :return:", "name": "printNumbers", "signature": "def printNumbers(self, n: int) -> [int]" }, { "docstring": "移除数字字符串前面的...
2
stack_v2_sparse_classes_30k_train_012179
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def printNumbers(self, n: int) -> [int]: 打印 “从 1至最大的 n 位数的列表” 常规思路就是用list(range(1, n))直接打印 但是当n比较大时,它会超出int32整型的取值范围,超出取值范围的字无法正常存储。因此需要考虑大数越界问题。 注意:我们可以观察到该列表是一个n位0-9的全排列,该列全排列的...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def printNumbers(self, n: int) -> [int]: 打印 “从 1至最大的 n 位数的列表” 常规思路就是用list(range(1, n))直接打印 但是当n比较大时,它会超出int32整型的取值范围,超出取值范围的字无法正常存储。因此需要考虑大数越界问题。 注意:我们可以观察到该列表是一个n位0-9的全排列,该列全排列的...
97cc61fefe0bedf5161687aab92fb09b0df990e2
<|skeleton|> class Solution: def printNumbers(self, n: int) -> [int]: """打印 “从 1至最大的 n 位数的列表” 常规思路就是用list(range(1, n))直接打印 但是当n比较大时,它会超出int32整型的取值范围,超出取值范围的字无法正常存储。因此需要考虑大数越界问题。 注意:我们可以观察到该列表是一个n位0-9的全排列,该列全排列的问题都可以使用这个代码来写 :param n: :return:""" <|body_0|> def removeFirstZero(self, num_str): ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def printNumbers(self, n: int) -> [int]: """打印 “从 1至最大的 n 位数的列表” 常规思路就是用list(range(1, n))直接打印 但是当n比较大时,它会超出int32整型的取值范围,超出取值范围的字无法正常存储。因此需要考虑大数越界问题。 注意:我们可以观察到该列表是一个n位0-9的全排列,该列全排列的问题都可以使用这个代码来写 :param n: :return:""" def dfs(x): if x == n: res.append(self....
the_stack_v2_python_sparse
code/other/print_number.py
JiaXingBinggan/For_work
train
0
c2b2a257f8e6c2ffdd120273ec3a76700f60cdcc
[ "self.assertRaises(ValueError, json_lib.AssertIsInstance, tuple(), list, 'a bad value')\nself.assertRaises(ValueError, json_lib.AssertIsInstance, 1, float, 'a bad value')\nself.assertRaises(ValueError, json_lib.AssertIsInstance, 1, bool, 'a bad value')\njson_lib.AssertIsInstance([1], list, 'good value')\njson_lib.A...
<|body_start_0|> self.assertRaises(ValueError, json_lib.AssertIsInstance, tuple(), list, 'a bad value') self.assertRaises(ValueError, json_lib.AssertIsInstance, 1, float, 'a bad value') self.assertRaises(ValueError, json_lib.AssertIsInstance, 1, bool, 'a bad value') json_lib.AssertIsInst...
Tests for chromite.lib.json_lib.
JsonHelpersTest
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsonHelpersTest: """Tests for chromite.lib.json_lib.""" def testAssertIsInstance(self): """Test that AssertIsInstance is correct.""" <|body_0|> def testGetValueOfType(self): """Test that GetValueOfType is correct.""" <|body_1|> def testPopValueOfType...
stack_v2_sparse_classes_36k_train_024761
2,477
permissive
[ { "docstring": "Test that AssertIsInstance is correct.", "name": "testAssertIsInstance", "signature": "def testAssertIsInstance(self)" }, { "docstring": "Test that GetValueOfType is correct.", "name": "testGetValueOfType", "signature": "def testGetValueOfType(self)" }, { "docstri...
4
null
Implement the Python class `JsonHelpersTest` described below. Class description: Tests for chromite.lib.json_lib. Method signatures and docstrings: - def testAssertIsInstance(self): Test that AssertIsInstance is correct. - def testGetValueOfType(self): Test that GetValueOfType is correct. - def testPopValueOfType(sel...
Implement the Python class `JsonHelpersTest` described below. Class description: Tests for chromite.lib.json_lib. Method signatures and docstrings: - def testAssertIsInstance(self): Test that AssertIsInstance is correct. - def testGetValueOfType(self): Test that GetValueOfType is correct. - def testPopValueOfType(sel...
72a05af97787001756bae2511b7985e61498c965
<|skeleton|> class JsonHelpersTest: """Tests for chromite.lib.json_lib.""" def testAssertIsInstance(self): """Test that AssertIsInstance is correct.""" <|body_0|> def testGetValueOfType(self): """Test that GetValueOfType is correct.""" <|body_1|> def testPopValueOfType...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class JsonHelpersTest: """Tests for chromite.lib.json_lib.""" def testAssertIsInstance(self): """Test that AssertIsInstance is correct.""" self.assertRaises(ValueError, json_lib.AssertIsInstance, tuple(), list, 'a bad value') self.assertRaises(ValueError, json_lib.AssertIsInstance, 1, f...
the_stack_v2_python_sparse
third_party/chromite/lib/json_lib_unittest.py
metux/chromium-suckless
train
5
3be6d75737ef3f383f1f94b37a1e59fa01d47fa7
[ "if n <= 0:\n return\ndp = [0 for i in range(n + 1)]\ndp[0] = 1\ndp[1] = 1\nfor i in range(2, n + 1):\n dp[i] = dp[i - 1] + dp[i - 2]\nreturn dp[n]", "if n <= 2:\n return n\ndp = [1, 1]\nfor i in range(n - 2):\n dp.append(dp[-1] + dp[-2])\nreturn dp[-1]", "if n <= 0:\n return\ndp = [0 for i in ra...
<|body_start_0|> if n <= 0: return dp = [0 for i in range(n + 1)] dp[0] = 1 dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] <|end_body_0|> <|body_start_1|> if n <= 2: return n dp = [1, 1] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def climbStairs(self, n): """:type n: int :rtype: int""" <|body_0|> def climbStairs(self, n): """:type n: int :rtype: int""" <|body_1|> def climbStairs(self, n): """:type n: int :rtype: int""" <|body_2|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_36k_train_024762
1,248
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "climbStairs", "signature": "def climbStairs(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "climbStairs", "signature": "def climbStairs(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "climbS...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def climbStairs(self, n): :type n: int :rtype: int - def climbStairs(self, n): :type n: int :rtype: int - def climbStairs(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def climbStairs(self, n): :type n: int :rtype: int - def climbStairs(self, n): :type n: int :rtype: int - def climbStairs(self, n): :type n: int :rtype: int <|skeleton|> class S...
e718fcb6b83664d3d6413cf9b2bb4a875e62de9c
<|skeleton|> class Solution: def climbStairs(self, n): """:type n: int :rtype: int""" <|body_0|> def climbStairs(self, n): """:type n: int :rtype: int""" <|body_1|> def climbStairs(self, n): """:type n: int :rtype: int""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def climbStairs(self, n): """:type n: int :rtype: int""" if n <= 0: return dp = [0 for i in range(n + 1)] dp[0] = 1 dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] def climbStairs(self...
the_stack_v2_python_sparse
climbStair.py
bch6179/Pyn
train
1
f18fc0fbfc739ef67c3daa42b6e9a54af8169401
[ "self._facility = facility\nself._option = option\nself._priority = priority", "title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)\nsyslog.openlog(title, self._option, self._facility)\nsyslog.syslog(self._priority, message)\nsyslog.closelog()" ]
<|body_start_0|> self._facility = facility self._option = option self._priority = priority <|end_body_0|> <|body_start_1|> title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT) syslog.openlog(title, self._option, self._facility) syslog.syslog(self._priority, message) ...
Implement the syslog notification service.
SyslogNotificationService
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SyslogNotificationService: """Implement the syslog notification service.""" def __init__(self, facility, option, priority): """Initialize the service.""" <|body_0|> def send_message(self, message='', **kwargs): """Send a message to syslog.""" <|body_1|> ...
stack_v2_sparse_classes_36k_train_024763
2,640
permissive
[ { "docstring": "Initialize the service.", "name": "__init__", "signature": "def __init__(self, facility, option, priority)" }, { "docstring": "Send a message to syslog.", "name": "send_message", "signature": "def send_message(self, message='', **kwargs)" } ]
2
stack_v2_sparse_classes_30k_train_000863
Implement the Python class `SyslogNotificationService` described below. Class description: Implement the syslog notification service. Method signatures and docstrings: - def __init__(self, facility, option, priority): Initialize the service. - def send_message(self, message='', **kwargs): Send a message to syslog.
Implement the Python class `SyslogNotificationService` described below. Class description: Implement the syslog notification service. Method signatures and docstrings: - def __init__(self, facility, option, priority): Initialize the service. - def send_message(self, message='', **kwargs): Send a message to syslog. <...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class SyslogNotificationService: """Implement the syslog notification service.""" def __init__(self, facility, option, priority): """Initialize the service.""" <|body_0|> def send_message(self, message='', **kwargs): """Send a message to syslog.""" <|body_1|> ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SyslogNotificationService: """Implement the syslog notification service.""" def __init__(self, facility, option, priority): """Initialize the service.""" self._facility = facility self._option = option self._priority = priority def send_message(self, message='', **kwa...
the_stack_v2_python_sparse
homeassistant/components/syslog/notify.py
home-assistant/core
train
35,501
dcad37a8101e1054ceb0404e5dcec42041a1f2a3
[ "BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise)\nself.veh_id = veh_id\nself.k_1 = k_1\nself.k_2 = k_2\nself.h = h\nself.tau = tau\nself.a = a", "lead_id = env.k.vehicle.get_leader(self.veh_id)\nlead_vel = env.k.vehicle.get_speed(lead_id)\nthis_vel =...
<|body_start_0|> BaseController.__init__(self, veh_id, car_following_params, delay=time_delay, fail_safe=fail_safe, noise=noise) self.veh_id = veh_id self.k_1 = k_1 self.k_2 = k_2 self.h = h self.tau = tau self.a = a <|end_body_0|> <|body_start_1|> lead_i...
Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float desired time gap (default: 1.0) tau : fl...
LACController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LACController: """Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float...
stack_v2_sparse_classes_36k_train_024764
17,548
permissive
[ { "docstring": "Instantiate a Linear Adaptive Cruise controller.", "name": "__init__", "signature": "def __init__(self, veh_id, car_following_params, k_1=0.3, k_2=0.4, h=1, tau=0.1, a=0, time_delay=0.0, noise=0, fail_safe=None)" }, { "docstring": "See parent class.", "name": "get_accel", ...
2
stack_v2_sparse_classes_30k_test_001127
Implement the Python class `LACController` described below. Class description: Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float de...
Implement the Python class `LACController` described below. Class description: Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float de...
badac3da17f04d8d8ae5691ee8ba2af9d56fac35
<|skeleton|> class LACController: """Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LACController: """Linear Adaptive Cruise Control. Attributes ---------- veh_id : str Vehicle ID for SUMO identification car_following_params : flow.core.params.SumoCarFollowingParams see parent class k_1 : float design parameter (default: 0.8) k_2 : float design parameter (default: 0.9) h : float desired time...
the_stack_v2_python_sparse
flow/controllers/car_following_models.py
parthjaggi/flow
train
6
c65980d356c8ef391f94747bf265eba2c0d6a81c
[ "Action.__init__(self, game_state, player)\nassert isinstance(is_right_goal, bool)\nassert isinstance(minimum_distance, (int, float))\nassert isinstance(maximum_distance, (int, float)) or maximum_distance is None\nif maximum_distance is not None:\n assert maximum_distance >= minimum_distance\nif maximum_distance...
<|body_start_0|> Action.__init__(self, game_state, player) assert isinstance(is_right_goal, bool) assert isinstance(minimum_distance, (int, float)) assert isinstance(maximum_distance, (int, float)) or maximum_distance is None if maximum_distance is not None: assert ma...
Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action): player_id : L'identifiant du gardien...
ProtectGoal
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ProtectGoal: """Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action...
stack_v2_sparse_classes_36k_train_024765
4,322
permissive
[ { "docstring": ":param game_state: L'état courant du jeu. :param player: L'instance du joueur qui est le gardien de but. :param is_right_goal: Un booléen indiquant si le but à protéger est celui de droite. :param minimum_distance: La distance minimale qu'il doit y avoir entre le gardien et le centre du but. :pa...
2
stack_v2_sparse_classes_30k_train_012368
Implement the Python class `ProtectGoal` described below. Class description: Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendr...
Implement the Python class `ProtectGoal` described below. Class description: Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendr...
ea997cad26e9eaec75e32f7490e2819151937d93
<|skeleton|> class ProtectGoal: """Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ProtectGoal: """Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action): player_id ...
the_stack_v2_python_sparse
ai/STA/Action/ProtectGoal.py
EtienneLavallee/StrategyAI
train
0
4412086452ba95c15086a7747db1b13c767c4cc8
[ "result = ['']\ncounts = []\ni = 0\nwhile i < len(s):\n if s[i] in ascii_letters:\n result[-1] += s[i]\n elif s[i] in digits:\n j = s[i:].find('[')\n counts.append(int(s[i:i + j]))\n result.append('')\n i += j\n elif s[i] == ']':\n count = counts.pop()\n sub...
<|body_start_0|> result = [''] counts = [] i = 0 while i < len(s): if s[i] in ascii_letters: result[-1] += s[i] elif s[i] in digits: j = s[i:].find('[') counts.append(int(s[i:i + j])) result.append(''...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def decodeString(self, s: str) -> str: """20190928 执行用时 :32 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.26%的用户 思路借鉴了第 154 场周赛, 一位小哥的解法. 维护了一个栈, 最终结果保存在栈底元素中 1. 每当遇到括号需要进行操作时, 都向栈中压入一个空串, 2. 在操作完成之后, 将处理后的字符串 pop 出来, 拼接到栈顶的字符串中 3. 重复 1, 2 步, 最终栈中只有一个元素, 即...
stack_v2_sparse_classes_36k_train_024766
2,765
no_license
[ { "docstring": "20190928 执行用时 :32 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.26%的用户 思路借鉴了第 154 场周赛, 一位小哥的解法. 维护了一个栈, 最终结果保存在栈底元素中 1. 每当遇到括号需要进行操作时, 都向栈中压入一个空串, 2. 在操作完成之后, 将处理后的字符串 pop 出来, 拼接到栈顶的字符串中 3. 重复 1, 2 步, 最终栈中只有一个元素, 即处理完的字符串", "name": "decodeString", "signature": "def ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def decodeString(self, s: str) -> str: 20190928 执行用时 :32 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.26%的用户 思路借鉴了第 154 场周赛, 一位小哥的解法. 维护了一个栈, 最终结果保存在栈底元素中 ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def decodeString(self, s: str) -> str: 20190928 执行用时 :32 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.26%的用户 思路借鉴了第 154 场周赛, 一位小哥的解法. 维护了一个栈, 最终结果保存在栈底元素中 ...
99a3abf1774933af73a8405f9b59e5e64906bca4
<|skeleton|> class Solution: def decodeString(self, s: str) -> str: """20190928 执行用时 :32 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.26%的用户 思路借鉴了第 154 场周赛, 一位小哥的解法. 维护了一个栈, 最终结果保存在栈底元素中 1. 每当遇到括号需要进行操作时, 都向栈中压入一个空串, 2. 在操作完成之后, 将处理后的字符串 pop 出来, 拼接到栈顶的字符串中 3. 重复 1, 2 步, 最终栈中只有一个元素, 即...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def decodeString(self, s: str) -> str: """20190928 执行用时 :32 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.26%的用户 思路借鉴了第 154 场周赛, 一位小哥的解法. 维护了一个栈, 最终结果保存在栈底元素中 1. 每当遇到括号需要进行操作时, 都向栈中压入一个空串, 2. 在操作完成之后, 将处理后的字符串 pop 出来, 拼接到栈顶的字符串中 3. 重复 1, 2 步, 最终栈中只有一个元素, 即处理完的字符串""" ...
the_stack_v2_python_sparse
leetcode/394.decode-string.py
iamkissg/leetcode
train
0
37e4d973fb36d678eba97b6f2562a25650270e1c
[ "if remote_directory == '/':\n res = self._exec_command('chdir /')\n return res\nif remote_directory == '':\n return\nremote_dirname, basename = osp.split(remote_directory)\nself.mkdir_RECURSIVE(remote_dirname)\ntry:\n cmdargs = self.prepare_sftp_command('chdir ' + remote_directory)\n res = self.mylo...
<|body_start_0|> if remote_directory == '/': res = self._exec_command('chdir /') return res if remote_directory == '': return remote_dirname, basename = osp.split(remote_directory) self.mkdir_RECURSIVE(remote_dirname) try: cmdargs =...
This class defines a SFTP server for copying files. It is usually used with a SSH server for shell commands. In server configuration, enter: protocol_exec : asrun.plugins.server.SSHServer protocol_copyto : asrun.plugins.sftp_server.SFTPFilesystemServer protocol_copyfrom : asrun.plugins.sftp_server.SFTPFilesystemServer
SFTPFilesystemServer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SFTPFilesystemServer: """This class defines a SFTP server for copying files. It is usually used with a SSH server for shell commands. In server configuration, enter: protocol_exec : asrun.plugins.server.SSHServer protocol_copyto : asrun.plugins.sftp_server.SFTPFilesystemServer protocol_copyfrom :...
stack_v2_sparse_classes_36k_train_024767
7,459
no_license
[ { "docstring": "Simulating a \"mkdir -p\" command in sftp", "name": "mkdir_RECURSIVE", "signature": "def mkdir_RECURSIVE(self, remote_directory, rights=None)" }, { "docstring": "Simulating a rm -R command in sftp", "name": "rmdir_RECURSIVE", "signature": "def rmdir_RECURSIVE(self, path)"...
6
null
Implement the Python class `SFTPFilesystemServer` described below. Class description: This class defines a SFTP server for copying files. It is usually used with a SSH server for shell commands. In server configuration, enter: protocol_exec : asrun.plugins.server.SSHServer protocol_copyto : asrun.plugins.sftp_server.S...
Implement the Python class `SFTPFilesystemServer` described below. Class description: This class defines a SFTP server for copying files. It is usually used with a SSH server for shell commands. In server configuration, enter: protocol_exec : asrun.plugins.server.SSHServer protocol_copyto : asrun.plugins.sftp_server.S...
62592c0f17be823caad8ea71cd52841acbab6185
<|skeleton|> class SFTPFilesystemServer: """This class defines a SFTP server for copying files. It is usually used with a SSH server for shell commands. In server configuration, enter: protocol_exec : asrun.plugins.server.SSHServer protocol_copyto : asrun.plugins.sftp_server.SFTPFilesystemServer protocol_copyfrom :...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SFTPFilesystemServer: """This class defines a SFTP server for copying files. It is usually used with a SSH server for shell commands. In server configuration, enter: protocol_exec : asrun.plugins.server.SSHServer protocol_copyto : asrun.plugins.sftp_server.SFTPFilesystemServer protocol_copyfrom : asrun.plugin...
the_stack_v2_python_sparse
asrun/plugins/sftp_server.py
zhanxiangqian/salome
train
1
e2d789f7cf28b747e67913c7712ceaa4a8ef8274
[ "self.radius = radius\nself.radius2 = radius ** 2\nself.xc = x_center\nself.xmin = x_center - radius\nself.xmax = x_center + radius\nself.yc = y_center\nself.ymin = y_center - radius\nself.ymax = y_center + radius", "while True:\n x = random.uniform(self.xmin, self.xmax)\n y = random.uniform(self.ymin, self...
<|body_start_0|> self.radius = radius self.radius2 = radius ** 2 self.xc = x_center self.xmin = x_center - radius self.xmax = x_center + radius self.yc = y_center self.ymin = y_center - radius self.ymax = y_center + radius <|end_body_0|> <|body_start_1|> ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def __init__(self, radius, x_center, y_center): """:type radius: float :type x_center: float :type y_center: float""" <|body_0|> def randPoint(self): """:rtype: List[float]""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.radius = radi...
stack_v2_sparse_classes_36k_train_024768
914
permissive
[ { "docstring": ":type radius: float :type x_center: float :type y_center: float", "name": "__init__", "signature": "def __init__(self, radius, x_center, y_center)" }, { "docstring": ":rtype: List[float]", "name": "randPoint", "signature": "def randPoint(self)" } ]
2
stack_v2_sparse_classes_30k_val_001110
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float - def randPoint(self): :rtype: List[float]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float - def randPoint(self): :rtype: List[float] <|skeleton|> class Sol...
3719f5cb059eefd66b83eb8ae990652f4b7fd124
<|skeleton|> class Solution: def __init__(self, radius, x_center, y_center): """:type radius: float :type x_center: float :type y_center: float""" <|body_0|> def randPoint(self): """:rtype: List[float]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def __init__(self, radius, x_center, y_center): """:type radius: float :type x_center: float :type y_center: float""" self.radius = radius self.radius2 = radius ** 2 self.xc = x_center self.xmin = x_center - radius self.xmax = x_center + radius ...
the_stack_v2_python_sparse
Python3/0478-Generate-Random-Point-in-a-Circle/soln.py
wyaadarsh/LeetCode-Solutions
train
0
e23c611eef6184227698000f33da0114c9df3191
[ "try:\n\n def generate(vo):\n for subscription in list_subscriptions(name=name, account=account, vo=vo):\n yield (render_json(**subscription) + '\\n')\n return try_stream(generate(vo=request.environ.get('vo')))\nexcept SubscriptionNotFound as error:\n return generate_http_error_flask(404,...
<|body_start_0|> try: def generate(vo): for subscription in list_subscriptions(name=name, account=account, vo=vo): yield (render_json(**subscription) + '\n') return try_stream(generate(vo=request.environ.get('vo'))) except SubscriptionNotFound...
REST APIs for subscriptions.
Subscription
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Subscription: """REST APIs for subscriptions.""" def get(self, account=None, name=None): """--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - na...
stack_v2_sparse_classes_36k_train_024769
24,180
permissive
[ { "docstring": "--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - name: name in: path description: The subscription name. schema: type: string style: simple responses: 200:...
3
stack_v2_sparse_classes_30k_train_003841
Implement the Python class `Subscription` described below. Class description: REST APIs for subscriptions. Method signatures and docstrings: - def get(self, account=None, name=None): --- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: ...
Implement the Python class `Subscription` described below. Class description: REST APIs for subscriptions. Method signatures and docstrings: - def get(self, account=None, name=None): --- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: ...
7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b
<|skeleton|> class Subscription: """REST APIs for subscriptions.""" def get(self, account=None, name=None): """--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - na...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Subscription: """REST APIs for subscriptions.""" def get(self, account=None, name=None): """--- summary: Get Subscription description: Retrieve a subscription. tags: - Replicas parameters: - name: account in: path description: The account name. schema: type: string style: simple - name: name in: ...
the_stack_v2_python_sparse
lib/rucio/web/rest/flaskapi/v1/subscriptions.py
rucio/rucio
train
232
b6a1f38bd7c658ef43db5712faa03243d894dc71
[ "super(Button, self).__init__(image=Button.image, x=x, y=y, dx=0, dy=0)\nself.game = game\nself.parent = parent\nself.counter = 0", "if self.counter != 0:\n self.counter -= 1\nfor sprite in self.overlapping_sprites:\n if sprite == self.game.player and games.keyboard.is_pressed(games.K_s) and (self.counter =...
<|body_start_0|> super(Button, self).__init__(image=Button.image, x=x, y=y, dx=0, dy=0) self.game = game self.parent = parent self.counter = 0 <|end_body_0|> <|body_start_1|> if self.counter != 0: self.counter -= 1 for sprite in self.overlapping_sprites: ...
Button object that can be pressed to dispense companion cubes
Button
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Button: """Button object that can be pressed to dispense companion cubes""" def __init__(self, game, parent, x, y): """Initialize the sprite.""" <|body_0|> def update(self): """If player is over the button they can press it""" <|body_1|> <|end_skeleton|>...
stack_v2_sparse_classes_36k_train_024770
943
no_license
[ { "docstring": "Initialize the sprite.", "name": "__init__", "signature": "def __init__(self, game, parent, x, y)" }, { "docstring": "If player is over the button they can press it", "name": "update", "signature": "def update(self)" } ]
2
stack_v2_sparse_classes_30k_train_004515
Implement the Python class `Button` described below. Class description: Button object that can be pressed to dispense companion cubes Method signatures and docstrings: - def __init__(self, game, parent, x, y): Initialize the sprite. - def update(self): If player is over the button they can press it
Implement the Python class `Button` described below. Class description: Button object that can be pressed to dispense companion cubes Method signatures and docstrings: - def __init__(self, game, parent, x, y): Initialize the sprite. - def update(self): If player is over the button they can press it <|skeleton|> clas...
aab3e28ef659b9a62060940e752b22679b344fdf
<|skeleton|> class Button: """Button object that can be pressed to dispense companion cubes""" def __init__(self, game, parent, x, y): """Initialize the sprite.""" <|body_0|> def update(self): """If player is over the button they can press it""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Button: """Button object that can be pressed to dispense companion cubes""" def __init__(self, game, parent, x, y): """Initialize the sprite.""" super(Button, self).__init__(image=Button.image, x=x, y=y, dx=0, dy=0) self.game = game self.parent = parent self.counte...
the_stack_v2_python_sparse
bin/button.py
noelano/Portal
train
0
1bebf5d0ceac2ebb9379f272ee52d5b9dac018d6
[ "serializer = ContentLibraryFilterSerializer(data=request.query_params)\nserializer.is_valid(raise_exception=True)\norg = serializer.validated_data['org']\nlibrary_type = serializer.validated_data['type']\ntext_search = serializer.validated_data['text_search']\npaginator = LibraryApiPagination()\nqueryset = api.get...
<|body_start_0|> serializer = ContentLibraryFilterSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) org = serializer.validated_data['org'] library_type = serializer.validated_data['type'] text_search = serializer.validated_data['text_search'] ...
Views to list, search for, and create content libraries.
LibraryRootView
[ "AGPL-3.0-only", "AGPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LibraryRootView: """Views to list, search for, and create content libraries.""" def get(self, request): """Return a list of all content libraries that the user has permission to view.""" <|body_0|> def post(self, request): """Create a new content library.""" ...
stack_v2_sparse_classes_36k_train_024771
42,120
permissive
[ { "docstring": "Return a list of all content libraries that the user has permission to view.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a new content library.", "name": "post", "signature": "def post(self, request)" } ]
2
null
Implement the Python class `LibraryRootView` described below. Class description: Views to list, search for, and create content libraries. Method signatures and docstrings: - def get(self, request): Return a list of all content libraries that the user has permission to view. - def post(self, request): Create a new con...
Implement the Python class `LibraryRootView` described below. Class description: Views to list, search for, and create content libraries. Method signatures and docstrings: - def get(self, request): Return a list of all content libraries that the user has permission to view. - def post(self, request): Create a new con...
5809eaca7079a15ee56b0b7fcfea425337046c97
<|skeleton|> class LibraryRootView: """Views to list, search for, and create content libraries.""" def get(self, request): """Return a list of all content libraries that the user has permission to view.""" <|body_0|> def post(self, request): """Create a new content library.""" ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LibraryRootView: """Views to list, search for, and create content libraries.""" def get(self, request): """Return a list of all content libraries that the user has permission to view.""" serializer = ContentLibraryFilterSerializer(data=request.query_params) serializer.is_valid(rai...
the_stack_v2_python_sparse
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/content_libraries/views.py
luque/better-ways-of-thinking-about-software
train
3
78221a7ec98e7165723377cc52039e01b80ae10e
[ "self.resource_service = resource_service\nself.client = resource_service.client\nself.messages = self.client.MESSAGES_MODULE\nself.status_enum = self.messages.Operation.StatusValueValuesEnum\nself.target_ref = target_ref", "if operation.error:\n raise OperationErrors(operation.error.errors)\nreturn operation....
<|body_start_0|> self.resource_service = resource_service self.client = resource_service.client self.messages = self.client.MESSAGES_MODULE self.status_enum = self.messages.Operation.StatusValueValuesEnum self.target_ref = target_ref <|end_body_0|> <|body_start_1|> if op...
Compute operations poller.
Poller
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Poller: """Compute operations poller.""" def __init__(self, resource_service, target_ref=None): """Initializes poller for compute operations. Args: resource_service: apitools.base.py.base_api.BaseApiService, service representing the target of operation. target_ref: Resource, optional...
stack_v2_sparse_classes_36k_train_024772
6,267
permissive
[ { "docstring": "Initializes poller for compute operations. Args: resource_service: apitools.base.py.base_api.BaseApiService, service representing the target of operation. target_ref: Resource, optional reference to the expected target of the operation. If not provided operation.targetLink will be used instead."...
4
null
Implement the Python class `Poller` described below. Class description: Compute operations poller. Method signatures and docstrings: - def __init__(self, resource_service, target_ref=None): Initializes poller for compute operations. Args: resource_service: apitools.base.py.base_api.BaseApiService, service representin...
Implement the Python class `Poller` described below. Class description: Compute operations poller. Method signatures and docstrings: - def __init__(self, resource_service, target_ref=None): Initializes poller for compute operations. Args: resource_service: apitools.base.py.base_api.BaseApiService, service representin...
c98b58aeb0994e011df960163541e9379ae7ea06
<|skeleton|> class Poller: """Compute operations poller.""" def __init__(self, resource_service, target_ref=None): """Initializes poller for compute operations. Args: resource_service: apitools.base.py.base_api.BaseApiService, service representing the target of operation. target_ref: Resource, optional...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Poller: """Compute operations poller.""" def __init__(self, resource_service, target_ref=None): """Initializes poller for compute operations. Args: resource_service: apitools.base.py.base_api.BaseApiService, service representing the target of operation. target_ref: Resource, optional reference to...
the_stack_v2_python_sparse
google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/compute/operations/poller.py
KaranToor/MA450
train
1
3f4761df442b7c0bd44aab5a80ea353cf9457377
[ "collection_critic = await FakeUserDocument().objects.find_all()\nrandom.shuffle(collection_critic)\nfake_user_list = {}\nfor document_critic in collection_critic[:10]:\n fake_user_list[str(document_critic._id)] = document_critic.info.name\nraise utils.exceptions.Result(content={'fakeUserList': fake_user_list})"...
<|body_start_0|> collection_critic = await FakeUserDocument().objects.find_all() random.shuffle(collection_critic) fake_user_list = {} for document_critic in collection_critic[:10]: fake_user_list[str(document_critic._id)] = document_critic.info.name raise utils.excep...
FakeStatisticHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FakeStatisticHandler: async def get(self): """Запрос данных по пользователям (случайные 10).""" <|body_0|> async def post(self): """Расчет статистики. В качестве параметров передавать список необходимых данных: двоих пользователей или фильм. Возвращать данные рассчит...
stack_v2_sparse_classes_36k_train_024773
6,265
no_license
[ { "docstring": "Запрос данных по пользователям (случайные 10).", "name": "get", "signature": "async def get(self)" }, { "docstring": "Расчет статистики. В качестве параметров передавать список необходимых данных: двоих пользователей или фильм. Возвращать данные рассчитанные данные.", "name":...
2
stack_v2_sparse_classes_30k_train_007359
Implement the Python class `FakeStatisticHandler` described below. Class description: Implement the FakeStatisticHandler class. Method signatures and docstrings: - async def get(self): Запрос данных по пользователям (случайные 10). - async def post(self): Расчет статистики. В качестве параметров передавать список нео...
Implement the Python class `FakeStatisticHandler` described below. Class description: Implement the FakeStatisticHandler class. Method signatures and docstrings: - async def get(self): Запрос данных по пользователям (случайные 10). - async def post(self): Расчет статистики. В качестве параметров передавать список нео...
c22b3bc4c533b2e1508dfbd211ce98e26517d079
<|skeleton|> class FakeStatisticHandler: async def get(self): """Запрос данных по пользователям (случайные 10).""" <|body_0|> async def post(self): """Расчет статистики. В качестве параметров передавать список необходимых данных: двоих пользователей или фильм. Возвращать данные рассчит...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FakeStatisticHandler: async def get(self): """Запрос данных по пользователям (случайные 10).""" collection_critic = await FakeUserDocument().objects.find_all() random.shuffle(collection_critic) fake_user_list = {} for document_critic in collection_critic[:10]: ...
the_stack_v2_python_sparse
server/modules/recommendation/handlers/fake/statistic.py
Rey8d01/chimera
train
10
b7fb5916f850092f066f97069ca3f8650d7dae24
[ "self.locale = locale\nself.participant = participant\nself.utterancetierTypes = utterancetierTypes\nself.wordtierTypes = wordtierTypes\nself.postierTypes = postierTypes\nself.morphemetierTypes = None\nself.glosstierTypes = None\nself.translationtierTypes = translationtierTypes\nself.interlineartype = POS\nself.ann...
<|body_start_0|> self.locale = locale self.participant = participant self.utterancetierTypes = utterancetierTypes self.wordtierTypes = wordtierTypes self.postierTypes = postierTypes self.morphemetierTypes = None self.glosstierTypes = None self.translationt...
The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through several functions. The data contains "tags", w...
PosCorpusReader
[ "CC-BY-3.0", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PosCorpusReader: """The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through sev...
stack_v2_sparse_classes_36k_train_024774
20,569
permissive
[ { "docstring": "root: is the directory where your .eaf files are stored. Only the files in the given directory are read, there is no recursive reading right now. This parameter is obligatory. files: a regular expression for the filenames to read. The default value is \"*.eaf\" locale: restricts the corpus data ...
4
stack_v2_sparse_classes_30k_train_006905
Implement the Python class `PosCorpusReader` described below. Class description: The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and...
Implement the Python class `PosCorpusReader` described below. Class description: The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and...
ac2bed9b6e759033d17b6ed9e8fa1e79dad68ae6
<|skeleton|> class PosCorpusReader: """The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through sev...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class PosCorpusReader: """The class EafPosCorpusReader implements a part of the corpus reader API described in the Natual Language Toolkit (NLTK). The class reads in all the .eaf files (from the linguistics annotation software called Elan) in a given directory and makes this data accessible through several function...
the_stack_v2_python_sparse
src/poioapi/corpusreader.py
IgorBMSTU/poio-api
train
0
f0e60f64684acbdeaa07e12e52d8d27ceb140fb1
[ "super(OpenDetails, self).__init__(*args, **kwargs)\nself.endpoint = 'reports'\nself.campaign_id = None", "self.campaign_id = campaign_id\nif get_all:\n return self._iterate(url=self._build_path(campaign_id, 'open-details'), **queryparams)\nelse:\n return self._mc_client._get(url=self._build_path(campaign_i...
<|body_start_0|> super(OpenDetails, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign_id = None <|end_body_0|> <|body_start_1|> self.campaign_id = campaign_id if get_all: return self._iterate(url=self._build_path(campaign_id, 'open-details'), **...
Get a detailed report about any emails in a specific campaign that were opened by the recipient.
OpenDetails
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OpenDetails: """Get a detailed report about any emails in a specific campaign that were opened by the recipient.""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" <|body_0|> def all(self, campaign_id, get_all=False, **queryparams): """Get deta...
stack_v2_sparse_classes_36k_train_024775
1,734
permissive
[ { "docstring": "Initialize the endpoint", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Get detailed information about any campaign emails that were opened by a list member. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:cla...
2
stack_v2_sparse_classes_30k_train_007946
Implement the Python class `OpenDetails` described below. Class description: Get a detailed report about any emails in a specific campaign that were opened by the recipient. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the endpoint - def all(self, campaign_id, get_all=False, **q...
Implement the Python class `OpenDetails` described below. Class description: Get a detailed report about any emails in a specific campaign that were opened by the recipient. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Initialize the endpoint - def all(self, campaign_id, get_all=False, **q...
bf61cd602dc44cbff32fbf6f6dcdd33cf6f782e8
<|skeleton|> class OpenDetails: """Get a detailed report about any emails in a specific campaign that were opened by the recipient.""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" <|body_0|> def all(self, campaign_id, get_all=False, **queryparams): """Get deta...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class OpenDetails: """Get a detailed report about any emails in a specific campaign that were opened by the recipient.""" def __init__(self, *args, **kwargs): """Initialize the endpoint""" super(OpenDetails, self).__init__(*args, **kwargs) self.endpoint = 'reports' self.campaign...
the_stack_v2_python_sparse
mailchimp3/entities/reportopendetails.py
VingtCinq/python-mailchimp
train
190
cbad5f2dcc9b7c4552470abe8d0ea8925579f1eb
[ "if not buf or not skt:\n raise ValueError('<send_bytes> invalid socket descriptor or buf')\nif timeout:\n skt.settimeout(timeout)\nelse:\n skt.settimeout(None)\nlength = len(buf)\nsent_total = 0\nwhile sent_total < length:\n sent = skt.send(buf)\n if not sent:\n raise IOError('<send_bytes> co...
<|body_start_0|> if not buf or not skt: raise ValueError('<send_bytes> invalid socket descriptor or buf') if timeout: skt.settimeout(timeout) else: skt.settimeout(None) length = len(buf) sent_total = 0 while sent_total < length: ...
SocketHelper
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SocketHelper: def send_bytes(skt, buf, timeout=0): """Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception""" <|body_0|> def recv_bytes(skt, length, timeout=0): """Receive bytes from the socket @raise ValueError, IOError, socket.timeout, Exc...
stack_v2_sparse_classes_36k_train_024776
2,505
permissive
[ { "docstring": "Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception", "name": "send_bytes", "signature": "def send_bytes(skt, buf, timeout=0)" }, { "docstring": "Receive bytes from the socket @raise ValueError, IOError, socket.timeout, Exception", "name": "recv_byt...
4
null
Implement the Python class `SocketHelper` described below. Class description: Implement the SocketHelper class. Method signatures and docstrings: - def send_bytes(skt, buf, timeout=0): Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception - def recv_bytes(skt, length, timeout=0): Receive byte...
Implement the Python class `SocketHelper` described below. Class description: Implement the SocketHelper class. Method signatures and docstrings: - def send_bytes(skt, buf, timeout=0): Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception - def recv_bytes(skt, length, timeout=0): Receive byte...
9d8220a0925327bddf0e10887e22b57c5d6adb37
<|skeleton|> class SocketHelper: def send_bytes(skt, buf, timeout=0): """Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception""" <|body_0|> def recv_bytes(skt, length, timeout=0): """Receive bytes from the socket @raise ValueError, IOError, socket.timeout, Exc...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SocketHelper: def send_bytes(skt, buf, timeout=0): """Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception""" if not buf or not skt: raise ValueError('<send_bytes> invalid socket descriptor or buf') if timeout: skt.settimeout(timeout) ...
the_stack_v2_python_sparse
lib/perf_engines/sys_helper.py
couchbase/testrunner
train
18
dd2e26be4e72fcb5d389e063df358567e9682624
[ "super().default_login()\nleaguer_level_page = Leaguer_Level_Page(self.base, test_data)\nleaguer_level_page.switch_in_leaguer_level_menu()\nleaguer_level_page.click_add_btn()\nleaguer_level_page.input_add_info()\nleaguer_level_page.click_save_btn()\nleaguer_level_page.assert_add_result()", "super().default_login(...
<|body_start_0|> super().default_login() leaguer_level_page = Leaguer_Level_Page(self.base, test_data) leaguer_level_page.switch_in_leaguer_level_menu() leaguer_level_page.click_add_btn() leaguer_level_page.input_add_info() leaguer_level_page.click_save_btn() leag...
Leaguer_Level_Case
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Leaguer_Level_Case: def test_001_leaguer_level_add(self): """新增会员""" <|body_0|> def test_002_leaguer_level_query(self): """查询会员""" <|body_1|> def test_003_leaguer_level_del(self): """删除会员""" <|body_2|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_36k_train_024777
1,873
no_license
[ { "docstring": "新增会员", "name": "test_001_leaguer_level_add", "signature": "def test_001_leaguer_level_add(self)" }, { "docstring": "查询会员", "name": "test_002_leaguer_level_query", "signature": "def test_002_leaguer_level_query(self)" }, { "docstring": "删除会员", "name": "test_003...
3
stack_v2_sparse_classes_30k_train_018071
Implement the Python class `Leaguer_Level_Case` described below. Class description: Implement the Leaguer_Level_Case class. Method signatures and docstrings: - def test_001_leaguer_level_add(self): 新增会员 - def test_002_leaguer_level_query(self): 查询会员 - def test_003_leaguer_level_del(self): 删除会员
Implement the Python class `Leaguer_Level_Case` described below. Class description: Implement the Leaguer_Level_Case class. Method signatures and docstrings: - def test_001_leaguer_level_add(self): 新增会员 - def test_002_leaguer_level_query(self): 查询会员 - def test_003_leaguer_level_del(self): 删除会员 <|skeleton|> class Lea...
94875917afb222cadcf6b4fde391e44cfbc9d199
<|skeleton|> class Leaguer_Level_Case: def test_001_leaguer_level_add(self): """新增会员""" <|body_0|> def test_002_leaguer_level_query(self): """查询会员""" <|body_1|> def test_003_leaguer_level_del(self): """删除会员""" <|body_2|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Leaguer_Level_Case: def test_001_leaguer_level_add(self): """新增会员""" super().default_login() leaguer_level_page = Leaguer_Level_Page(self.base, test_data) leaguer_level_page.switch_in_leaguer_level_menu() leaguer_level_page.click_add_btn() leaguer_level_page.inp...
the_stack_v2_python_sparse
test_case/leaguer_case/test_leaguer_level_case.py
goodboyxzmkk/youlebao
train
5
1bb69a91efb77ee151f70f2ba35860b4a4cbaaea
[ "dirpath_start = os.path.join(dirpath_testdata, 'simple_directory_tree', 'branch_01', 'leaf_01')\ndirpath_expected = os.path.join(dirpath_testdata, 'simple_directory_tree')\ndirpath_actual = da.lwc.search.find_ancestor_dir_containing(dirpath_start, 'marker_file')\nassert dirpath_expected == dirpath_actual", "dirp...
<|body_start_0|> dirpath_start = os.path.join(dirpath_testdata, 'simple_directory_tree', 'branch_01', 'leaf_01') dirpath_expected = os.path.join(dirpath_testdata, 'simple_directory_tree') dirpath_actual = da.lwc.search.find_ancestor_dir_containing(dirpath_start, 'marker_file') assert dir...
Specify the find_ancestor_dir_containing() function.
SpecifyFindAncestorDirContaining
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpecifyFindAncestorDirContaining: """Specify the find_ancestor_dir_containing() function.""" def it_finds_an_ancestor_dir(self, dirpath_testdata): """Smoke test for find_ancestor_dir_containing function.""" <|body_0|> def it_finds_the_starting_dir(self, dirpath_testdata)...
stack_v2_sparse_classes_36k_train_024778
29,518
permissive
[ { "docstring": "Smoke test for find_ancestor_dir_containing function.", "name": "it_finds_an_ancestor_dir", "signature": "def it_finds_an_ancestor_dir(self, dirpath_testdata)" }, { "docstring": "Smoke test for find_ancestor_dir_containing function.", "name": "it_finds_the_starting_dir", ...
3
null
Implement the Python class `SpecifyFindAncestorDirContaining` described below. Class description: Specify the find_ancestor_dir_containing() function. Method signatures and docstrings: - def it_finds_an_ancestor_dir(self, dirpath_testdata): Smoke test for find_ancestor_dir_containing function. - def it_finds_the_star...
Implement the Python class `SpecifyFindAncestorDirContaining` described below. Class description: Specify the find_ancestor_dir_containing() function. Method signatures and docstrings: - def it_finds_an_ancestor_dir(self, dirpath_testdata): Smoke test for find_ancestor_dir_containing function. - def it_finds_the_star...
04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d
<|skeleton|> class SpecifyFindAncestorDirContaining: """Specify the find_ancestor_dir_containing() function.""" def it_finds_an_ancestor_dir(self, dirpath_testdata): """Smoke test for find_ancestor_dir_containing function.""" <|body_0|> def it_finds_the_starting_dir(self, dirpath_testdata)...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class SpecifyFindAncestorDirContaining: """Specify the find_ancestor_dir_containing() function.""" def it_finds_an_ancestor_dir(self, dirpath_testdata): """Smoke test for find_ancestor_dir_containing function.""" dirpath_start = os.path.join(dirpath_testdata, 'simple_directory_tree', 'branch_01...
the_stack_v2_python_sparse
a3_src/h70_internal/da/lwc/spec/spec_search.py
wtpayne/hiai
train
5
e661e1b6676516bd4732d842f6b1c93295cf2fac
[ "if LooseVersion(self.from_version) < LooseVersion(FROM_VERSION_LAYOUTS_CONTAINER):\n error_message, error_code = Errors.invalid_version_in_layoutscontainer('fromVersion')\n if self.handle_error(error_message, error_code, file_path=self.file_path):\n return False\nreturn True", "if self.to_version an...
<|body_start_0|> if LooseVersion(self.from_version) < LooseVersion(FROM_VERSION_LAYOUTS_CONTAINER): error_message, error_code = Errors.invalid_version_in_layoutscontainer('fromVersion') if self.handle_error(error_message, error_code, file_path=self.file_path): return Fals...
LayoutsContainerValidator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LayoutsContainerValidator: def is_valid_from_version(self) -> bool: """Checks if from version field is valid. Returns: bool. True if from version field is valid, else False.""" <|body_0|> def is_valid_to_version(self) -> bool: """Checks if to version field is valid. ...
stack_v2_sparse_classes_36k_train_024779
4,349
permissive
[ { "docstring": "Checks if from version field is valid. Returns: bool. True if from version field is valid, else False.", "name": "is_valid_from_version", "signature": "def is_valid_from_version(self) -> bool" }, { "docstring": "Checks if to version field is valid. Returns: bool. True if to versi...
2
stack_v2_sparse_classes_30k_train_015086
Implement the Python class `LayoutsContainerValidator` described below. Class description: Implement the LayoutsContainerValidator class. Method signatures and docstrings: - def is_valid_from_version(self) -> bool: Checks if from version field is valid. Returns: bool. True if from version field is valid, else False. ...
Implement the Python class `LayoutsContainerValidator` described below. Class description: Implement the LayoutsContainerValidator class. Method signatures and docstrings: - def is_valid_from_version(self) -> bool: Checks if from version field is valid. Returns: bool. True if from version field is valid, else False. ...
a17e868e6fc5153f09e7a329801de85aa60cc752
<|skeleton|> class LayoutsContainerValidator: def is_valid_from_version(self) -> bool: """Checks if from version field is valid. Returns: bool. True if from version field is valid, else False.""" <|body_0|> def is_valid_to_version(self) -> bool: """Checks if to version field is valid. ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LayoutsContainerValidator: def is_valid_from_version(self) -> bool: """Checks if from version field is valid. Returns: bool. True if from version field is valid, else False.""" if LooseVersion(self.from_version) < LooseVersion(FROM_VERSION_LAYOUTS_CONTAINER): error_message, error_c...
the_stack_v2_python_sparse
demisto_sdk/commands/common/hook_validations/layout.py
SukhnandanMalhotra/demisto-sdk
train
0
4520848a6bf14de2dec126de4f9f116330db3ba1
[ "super().__init__()\nself.mixture_size = mixture_size\ninitial_scalar_parameters = [0.0] * mixture_size\nself.scalar_parameters = ParameterList([Parameter(torch.tensor([initial_scalar_parameters[i]], dtype=torch.float, device=flair.device), requires_grad=trainable) for i in range(mixture_size)])\nself.gamma = Param...
<|body_start_0|> super().__init__() self.mixture_size = mixture_size initial_scalar_parameters = [0.0] * mixture_size self.scalar_parameters = ParameterList([Parameter(torch.tensor([initial_scalar_parameters[i]], dtype=torch.float, device=flair.device), requires_grad=trainable) for i in ...
Mixes several tensors by a learned weighting. Computes a parameterised scalar mixture of N tensors. This method was proposed by Liu et al. (2019) in the paper: "Linguistic Knowledge and Transferability of Contextual Representations" (https://arxiv.org/abs/1903.08855) The implementation is copied and slightly modified f...
ScalarMix
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScalarMix: """Mixes several tensors by a learned weighting. Computes a parameterised scalar mixture of N tensors. This method was proposed by Liu et al. (2019) in the paper: "Linguistic Knowledge and Transferability of Contextual Representations" (https://arxiv.org/abs/1903.08855) The implementat...
stack_v2_sparse_classes_36k_train_024780
7,952
permissive
[ { "docstring": "Inits scalar mix implementation. ``mixture = gamma * sum(s_k * tensor_k)`` where ``s = softmax(w)``, with ``w`` and ``gamma`` scalar parameters. :param mixture_size: size of mixtures (usually the number of layers)", "name": "__init__", "signature": "def __init__(self, mixture_size: int, ...
2
null
Implement the Python class `ScalarMix` described below. Class description: Mixes several tensors by a learned weighting. Computes a parameterised scalar mixture of N tensors. This method was proposed by Liu et al. (2019) in the paper: "Linguistic Knowledge and Transferability of Contextual Representations" (https://ar...
Implement the Python class `ScalarMix` described below. Class description: Mixes several tensors by a learned weighting. Computes a parameterised scalar mixture of N tensors. This method was proposed by Liu et al. (2019) in the paper: "Linguistic Knowledge and Transferability of Contextual Representations" (https://ar...
1795ac80da18efadcd56b46374a40190abca07e4
<|skeleton|> class ScalarMix: """Mixes several tensors by a learned weighting. Computes a parameterised scalar mixture of N tensors. This method was proposed by Liu et al. (2019) in the paper: "Linguistic Knowledge and Transferability of Contextual Representations" (https://arxiv.org/abs/1903.08855) The implementat...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScalarMix: """Mixes several tensors by a learned weighting. Computes a parameterised scalar mixture of N tensors. This method was proposed by Liu et al. (2019) in the paper: "Linguistic Knowledge and Transferability of Contextual Representations" (https://arxiv.org/abs/1903.08855) The implementation is copied...
the_stack_v2_python_sparse
flair/embeddings/base.py
flairNLP/flair
train
5,684
8d3767b711a7d7b15486529f21f8ad54453d622a
[ "self.distance = distance\nself.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7)\nself.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 100, -100)\nself.pid_angle = PID(0.0, 0.01, 0.0, 0.01, 500, -500, 0.3, -0.3)\nself.pid_height = PID(0.0, 0.002, 0.0002, 0.002, 500, -500, 0.3, -0.2)\ncflib.crtp.ini...
<|body_start_0|> self.distance = distance self.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7) self.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 100, -100) self.pid_angle = PID(0.0, 0.01, 0.0, 0.01, 500, -500, 0.3, -0.3) self.pid_height = PID(0.0, 0.002, 0.00...
Aruco_tracker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Aruco_tracker: def __init__(self, distance): """Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.""" <|body_0|> def search_marker(self): """Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, ini...
stack_v2_sparse_classes_36k_train_024781
3,942
no_license
[ { "docstring": "Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.", "name": "__init__", "signature": "def __init__(self, distance)" }, { "docstring": "Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, inicia movimento de r...
4
stack_v2_sparse_classes_30k_train_004566
Implement the Python class `Aruco_tracker` described below. Class description: Implement the Aruco_tracker class. Method signatures and docstrings: - def __init__(self, distance): Inicialização dos drivers, parâmetros do controle PID e decolagem do drone. - def search_marker(self): Interrompe o movimento se nao encon...
Implement the Python class `Aruco_tracker` described below. Class description: Implement the Aruco_tracker class. Method signatures and docstrings: - def __init__(self, distance): Inicialização dos drivers, parâmetros do controle PID e decolagem do drone. - def search_marker(self): Interrompe o movimento se nao encon...
8af0ca6930b326ae7bc0cd7bb9aa2d6aa62bceeb
<|skeleton|> class Aruco_tracker: def __init__(self, distance): """Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.""" <|body_0|> def search_marker(self): """Interrompe o movimento se nao encontrar o marcador por tres frames consecutivos. Após 4 segundos, ini...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Aruco_tracker: def __init__(self, distance): """Inicialização dos drivers, parâmetros do controle PID e decolagem do drone.""" self.distance = distance self.pid_foward = PID(distance, 0.01, 0.0001, 0.01, 500, -500, 0.7, -0.7) self.pid_yaw = PID(0, 0.33, 0.0, 0.33, 500, -500, 10...
the_stack_v2_python_sparse
Código-fonte/Esquadrilha/aruco_tracker_pid.py
EvoSystems-com-br/IniciacaoCientifica2018_ProjetoDrones
train
0
d416e44660facb07879f2d214c0706e9b0ff04d0
[ "self.number = number\nself.title = title\nself.paragraphs = []\nfor paragraph_lines in paragraphs:\n new_pragraph = Paragraph.Paragraph(paragraph_lines)\n self.paragraphs.append(new_pragraph)", "if paragraph_idx:\n self.paragraphs[paragraph_idx].read()\nelse:\n for paragraph in self.paragraphs:\n ...
<|body_start_0|> self.number = number self.title = title self.paragraphs = [] for paragraph_lines in paragraphs: new_pragraph = Paragraph.Paragraph(paragraph_lines) self.paragraphs.append(new_pragraph) <|end_body_0|> <|body_start_1|> if paragraph_idx: ...
Chapter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Chapter: def __init__(self, number, title, paragraphs): """A chapter consists of multiple paragraphs.""" <|body_0|> def read(self, paragraph_idx=None): """A paragraph can be read.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.number = number ...
stack_v2_sparse_classes_36k_train_024782
676
no_license
[ { "docstring": "A chapter consists of multiple paragraphs.", "name": "__init__", "signature": "def __init__(self, number, title, paragraphs)" }, { "docstring": "A paragraph can be read.", "name": "read", "signature": "def read(self, paragraph_idx=None)" } ]
2
stack_v2_sparse_classes_30k_train_011824
Implement the Python class `Chapter` described below. Class description: Implement the Chapter class. Method signatures and docstrings: - def __init__(self, number, title, paragraphs): A chapter consists of multiple paragraphs. - def read(self, paragraph_idx=None): A paragraph can be read.
Implement the Python class `Chapter` described below. Class description: Implement the Chapter class. Method signatures and docstrings: - def __init__(self, number, title, paragraphs): A chapter consists of multiple paragraphs. - def read(self, paragraph_idx=None): A paragraph can be read. <|skeleton|> class Chapter...
70dac5017980c8f30294f2cbd98e5bfd905bfaa7
<|skeleton|> class Chapter: def __init__(self, number, title, paragraphs): """A chapter consists of multiple paragraphs.""" <|body_0|> def read(self, paragraph_idx=None): """A paragraph can be read.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Chapter: def __init__(self, number, title, paragraphs): """A chapter consists of multiple paragraphs.""" self.number = number self.title = title self.paragraphs = [] for paragraph_lines in paragraphs: new_pragraph = Paragraph.Paragraph(paragraph_lines) ...
the_stack_v2_python_sparse
week2/objectOriented/Chapter.py
MalteMagnussen/PythonProjects
train
0
409220a3cf8b7ab8209f12d7ac382a7634617d34
[ "super(TinyTransformer, self).__init__()\nif N_v is None:\n dim_out = dim_ff[-1] * N_head\nelse:\n dim_out = N_v * N_head\ndim_in = dim_ff[0]\nself.linear_link = linear_link\nself.num_layer = num_layer\nself.h = N_head\nself.dim_ff = dim_ff\nself.mlps = []\nself.attn = []\nself.lins = []\nfor l in range(num_l...
<|body_start_0|> super(TinyTransformer, self).__init__() if N_v is None: dim_out = dim_ff[-1] * N_head else: dim_out = N_v * N_head dim_in = dim_ff[0] self.linear_link = linear_link self.num_layer = num_layer self.h = N_head self.di...
TinyTransformer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TinyTransformer: def __init__(self, dim_ff, num_layer, N_head, N_qk=None, N_v=None, queries=False, linear_link=False, resnorm=True, **mlp_args): """Separate linear maps for the keys, queries, and values are optional""" <|body_0|> def forward(self, x, mask=None): """t...
stack_v2_sparse_classes_36k_train_024783
45,005
no_license
[ { "docstring": "Separate linear maps for the keys, queries, and values are optional", "name": "__init__", "signature": "def __init__(self, dim_ff, num_layer, N_head, N_qk=None, N_v=None, queries=False, linear_link=False, resnorm=True, **mlp_args)" }, { "docstring": "the mask tells you which inpu...
2
stack_v2_sparse_classes_30k_train_011447
Implement the Python class `TinyTransformer` described below. Class description: Implement the TinyTransformer class. Method signatures and docstrings: - def __init__(self, dim_ff, num_layer, N_head, N_qk=None, N_v=None, queries=False, linear_link=False, resnorm=True, **mlp_args): Separate linear maps for the keys, q...
Implement the Python class `TinyTransformer` described below. Class description: Implement the TinyTransformer class. Method signatures and docstrings: - def __init__(self, dim_ff, num_layer, N_head, N_qk=None, N_v=None, queries=False, linear_link=False, resnorm=True, **mlp_args): Separate linear maps for the keys, q...
1d4c76920d50729680305a4e877c30e2b782d9d7
<|skeleton|> class TinyTransformer: def __init__(self, dim_ff, num_layer, N_head, N_qk=None, N_v=None, queries=False, linear_link=False, resnorm=True, **mlp_args): """Separate linear maps for the keys, queries, and values are optional""" <|body_0|> def forward(self, x, mask=None): """t...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TinyTransformer: def __init__(self, dim_ff, num_layer, N_head, N_qk=None, N_v=None, queries=False, linear_link=False, resnorm=True, **mlp_args): """Separate linear maps for the keys, queries, and values are optional""" super(TinyTransformer, self).__init__() if N_v is None: ...
the_stack_v2_python_sparse
src/students.py
Kelarion/repler
train
0
0585300ad5394565d03bdcffc6a41484d181e432
[ "if type(self).batch_insert == BaseSDS.batch_insert:\n raise NotImplementedError('insert or batch_insert need to be overridden')\nself.batch_insert(document[None], [index], *args, **kwargs)\nreturn self", "if type(self).insert == BaseSDS.insert:\n raise NotImplementedError('insert or batch_insert need to be...
<|body_start_0|> if type(self).batch_insert == BaseSDS.batch_insert: raise NotImplementedError('insert or batch_insert need to be overridden') self.batch_insert(document[None], [index], *args, **kwargs) return self <|end_body_0|> <|body_start_1|> if type(self).insert == Base...
Base Search Data Structure, need to be instantiate. Maintains an index for documents to be retrieved with query. When queried the appropriate index(es) will be returned (not the document(s))
BaseSDS
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BaseSDS: """Base Search Data Structure, need to be instantiate. Maintains an index for documents to be retrieved with query. When queried the appropriate index(es) will be returned (not the document(s))""" def insert(self, document, index, *args, **kwargs): """Insert a single documen...
stack_v2_sparse_classes_36k_train_024784
6,136
permissive
[ { "docstring": "Insert a single document in the data structure by saving the index. The document is not saved for scalability. This is the default implementation that uses batch_insert. See batch_insert documentation. Parameters ---------- document : numpy.ndarray or torch.Tensor The document to by inserted (wi...
6
null
Implement the Python class `BaseSDS` described below. Class description: Base Search Data Structure, need to be instantiate. Maintains an index for documents to be retrieved with query. When queried the appropriate index(es) will be returned (not the document(s)) Method signatures and docstrings: - def insert(self, d...
Implement the Python class `BaseSDS` described below. Class description: Base Search Data Structure, need to be instantiate. Maintains an index for documents to be retrieved with query. When queried the appropriate index(es) will be returned (not the document(s)) Method signatures and docstrings: - def insert(self, d...
3d9dbad51e1bfc0bbb1a60d0aa03c99340f6930c
<|skeleton|> class BaseSDS: """Base Search Data Structure, need to be instantiate. Maintains an index for documents to be retrieved with query. When queried the appropriate index(es) will be returned (not the document(s))""" def insert(self, document, index, *args, **kwargs): """Insert a single documen...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class BaseSDS: """Base Search Data Structure, need to be instantiate. Maintains an index for documents to be retrieved with query. When queried the appropriate index(es) will be returned (not the document(s))""" def insert(self, document, index, *args, **kwargs): """Insert a single document in the data...
the_stack_v2_python_sparse
radbm/search/base.py
duchesneaumathieu/radbm
train
0
464c96498b8f3d51b88ac52b5a0545d6dd9aae84
[ "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')", "conte...
<|body_start_0|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') <|end_body_0|> <|body_start_1|> context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not im...
Missing associated documentation comment in .proto file.
CollectorServicer
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CollectorServicer: """Missing associated documentation comment in .proto file.""" def SendEvent(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def SendMetric(self, request, context): """Missing associated docume...
stack_v2_sparse_classes_36k_train_024785
5,307
permissive
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "SendEvent", "signature": "def SendEvent(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "SendMetric", "signature": "def SendMetric(self, requ...
3
stack_v2_sparse_classes_30k_train_003609
Implement the Python class `CollectorServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def SendEvent(self, request, context): Missing associated documentation comment in .proto file. - def SendMetric(self, request, context): Miss...
Implement the Python class `CollectorServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def SendEvent(self, request, context): Missing associated documentation comment in .proto file. - def SendMetric(self, request, context): Miss...
135b3ac8947c123571bec80c6e2ff579b772f16d
<|skeleton|> class CollectorServicer: """Missing associated documentation comment in .proto file.""" def SendEvent(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def SendMetric(self, request, context): """Missing associated docume...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CollectorServicer: """Missing associated documentation comment in .proto file.""" def SendEvent(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') ...
the_stack_v2_python_sparse
python/grpc/service2/service/service_pb2_grpc.py
JoseIbanez/testing
train
3
625bce635506d481adbb5c09ab311a120b7c0634
[ "metadata_bytes = f.read(16)\ndimension, self.chunk_size, scaler_vector_length = _struct_unpack(endianness + 'LQL', metadata_bytes)\nif dimension != 1:\n raise ValueError('Data dimension is not 1')\nscaler_class = _scaler_classes[scaler_type]\nself.scalers = [scaler_class(f, endianness) for _ in range(scaler_vec...
<|body_start_0|> metadata_bytes = f.read(16) dimension, self.chunk_size, scaler_vector_length = _struct_unpack(endianness + 'LQL', metadata_bytes) if dimension != 1: raise ValueError('Data dimension is not 1') scaler_class = _scaler_classes[scaler_type] self.scalers =...
Describes DAQmx data for a single channel
DaqMxMetadata
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DaqMxMetadata: """Describes DAQmx data for a single channel""" def __init__(self, f, endianness, scaler_type, channel_data_type): """Read the metadata for a DAQmx raw segment. This is the raw DAQmx-specific portion of the raw data index.""" <|body_0|> def __repr__(self):...
stack_v2_sparse_classes_36k_train_024786
12,402
permissive
[ { "docstring": "Read the metadata for a DAQmx raw segment. This is the raw DAQmx-specific portion of the raw data index.", "name": "__init__", "signature": "def __init__(self, f, endianness, scaler_type, channel_data_type)" }, { "docstring": "Return string representation of DAQmx metadata", ...
2
stack_v2_sparse_classes_30k_train_004377
Implement the Python class `DaqMxMetadata` described below. Class description: Describes DAQmx data for a single channel Method signatures and docstrings: - def __init__(self, f, endianness, scaler_type, channel_data_type): Read the metadata for a DAQmx raw segment. This is the raw DAQmx-specific portion of the raw d...
Implement the Python class `DaqMxMetadata` described below. Class description: Describes DAQmx data for a single channel Method signatures and docstrings: - def __init__(self, f, endianness, scaler_type, channel_data_type): Read the metadata for a DAQmx raw segment. This is the raw DAQmx-specific portion of the raw d...
66827d3bf32a715ba4b3521d091c43a3f50a1f1f
<|skeleton|> class DaqMxMetadata: """Describes DAQmx data for a single channel""" def __init__(self, f, endianness, scaler_type, channel_data_type): """Read the metadata for a DAQmx raw segment. This is the raw DAQmx-specific portion of the raw data index.""" <|body_0|> def __repr__(self):...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class DaqMxMetadata: """Describes DAQmx data for a single channel""" def __init__(self, f, endianness, scaler_type, channel_data_type): """Read the metadata for a DAQmx raw segment. This is the raw DAQmx-specific portion of the raw data index.""" metadata_bytes = f.read(16) dimension, s...
the_stack_v2_python_sparse
nptdms_mod/daqmx.py
fusion-flap/flap_w7x_abes
train
0
a522a9a365b5dc0ed140d6f6d4adb2bf73347791
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthOSVersionPerformance()", "from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'activeDeviceCount': lambda n: setattr(self, 'active_device_count', n.get_int...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return UserExperienceAnalyticsAppHealthOSVersionPerformance() <|end_body_0|> <|body_start_1|> from .entity import Entity from .entity import Entity fields: Dict[str, Callable[[Any], Non...
The user experience analytics device OS version performance entity contains OS version performance details.
UserExperienceAnalyticsAppHealthOSVersionPerformance
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UserExperienceAnalyticsAppHealthOSVersionPerformance: """The user experience analytics device OS version performance entity contains OS version performance details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthOSVersionPerfor...
stack_v2_sparse_classes_36k_train_024787
3,897
permissive
[ { "docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsAppHealthOSVersionPerformance", "name": "create_from_discriminator_value", "signature...
3
null
Implement the Python class `UserExperienceAnalyticsAppHealthOSVersionPerformance` described below. Class description: The user experience analytics device OS version performance entity contains OS version performance details. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional...
Implement the Python class `UserExperienceAnalyticsAppHealthOSVersionPerformance` described below. Class description: The user experience analytics device OS version performance entity contains OS version performance details. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class UserExperienceAnalyticsAppHealthOSVersionPerformance: """The user experience analytics device OS version performance entity contains OS version performance details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthOSVersionPerfor...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class UserExperienceAnalyticsAppHealthOSVersionPerformance: """The user experience analytics device OS version performance entity contains OS version performance details.""" def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsAppHealthOSVersionPerformance: ...
the_stack_v2_python_sparse
msgraph/generated/models/user_experience_analytics_app_health_o_s_version_performance.py
microsoftgraph/msgraph-sdk-python
train
135
ece6df2ca704c466fa44676ffc47ee7d5c67d417
[ "if n == 0:\n return [0]\n\ndef gray(code, counter, target):\n if counter == target:\n return code\n rcode = code[::-1]\n for i in range(len(code)):\n code[i] = '0' + code[i]\n for i in range(len(rcode)):\n rcode[i] = '1' + rcode[i]\n return gray(code + rcode, counter + 1, tar...
<|body_start_0|> if n == 0: return [0] def gray(code, counter, target): if counter == target: return code rcode = code[::-1] for i in range(len(code)): code[i] = '0' + code[i] for i in range(len(rcode)): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def grayCode(self, n): """:type n: int :rtype: List[int]""" <|body_0|> def grayCode2(self, n): """An amazing more efficient solution by a fellow coder""" <|body_1|> <|end_skeleton|> <|body_start_0|> if n == 0: return [0] ...
stack_v2_sparse_classes_36k_train_024788
1,488
no_license
[ { "docstring": ":type n: int :rtype: List[int]", "name": "grayCode", "signature": "def grayCode(self, n)" }, { "docstring": "An amazing more efficient solution by a fellow coder", "name": "grayCode2", "signature": "def grayCode2(self, n)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def grayCode(self, n): :type n: int :rtype: List[int] - def grayCode2(self, n): An amazing more efficient solution by a fellow coder
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def grayCode(self, n): :type n: int :rtype: List[int] - def grayCode2(self, n): An amazing more efficient solution by a fellow coder <|skeleton|> class Solution: def grayCo...
b7e92f9a7c4d6652d4901b189f51063ce5520653
<|skeleton|> class Solution: def grayCode(self, n): """:type n: int :rtype: List[int]""" <|body_0|> def grayCode2(self, n): """An amazing more efficient solution by a fellow coder""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def grayCode(self, n): """:type n: int :rtype: List[int]""" if n == 0: return [0] def gray(code, counter, target): if counter == target: return code rcode = code[::-1] for i in range(len(code)): ...
the_stack_v2_python_sparse
leetcode/medium/gray_code.py
abkunal/Data-Structures-and-Algorithms
train
2
a89198cd71be35f99f3929834a08f1c869535cce
[ "input_json = request.data\noutput_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None]))\ntry:\n json_params = input_json['APIParams']\n json_params['profile_...
<|body_start_0|> input_json = request.data output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [input_json['AvailabilityDetails'], input_json['AuthenticationDetails'], input_json['SessionDetails'], None])) try: json_params = input_jso...
This API will fetch all notifications for a user
FetchMyNotificationsAPI
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FetchMyNotificationsAPI: """This API will fetch all notifications for a user""" def post(self, request): """Post function to crete a notification""" <|body_0|> def fetch_my_notifications_json(self, request): """This API will fetch all notifications for a user. :p...
stack_v2_sparse_classes_36k_train_024789
3,361
no_license
[ { "docstring": "Post function to crete a notification", "name": "post", "signature": "def post(self, request)" }, { "docstring": "This API will fetch all notifications for a user. :param request: { 'profile_id':277 } :return", "name": "fetch_my_notifications_json", "signature": "def fetc...
2
stack_v2_sparse_classes_30k_train_011875
Implement the Python class `FetchMyNotificationsAPI` described below. Class description: This API will fetch all notifications for a user Method signatures and docstrings: - def post(self, request): Post function to crete a notification - def fetch_my_notifications_json(self, request): This API will fetch all notific...
Implement the Python class `FetchMyNotificationsAPI` described below. Class description: This API will fetch all notifications for a user Method signatures and docstrings: - def post(self, request): Post function to crete a notification - def fetch_my_notifications_json(self, request): This API will fetch all notific...
36eb9931f330e64902354c6fc471be2adf4b7049
<|skeleton|> class FetchMyNotificationsAPI: """This API will fetch all notifications for a user""" def post(self, request): """Post function to crete a notification""" <|body_0|> def fetch_my_notifications_json(self, request): """This API will fetch all notifications for a user. :p...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class FetchMyNotificationsAPI: """This API will fetch all notifications for a user""" def post(self, request): """Post function to crete a notification""" input_json = request.data output_json = dict(zip(['AvailabilityDetails', 'AuthenticationDetails', 'SessionDetails', 'Payload'], [inp...
the_stack_v2_python_sparse
Generic/common/notifications_new/api/fetch_my_notifications/views_fetch_my_notifications.py
archiemb303/common_backend_django
train
0
e013bb92a9e26aa4e07c4bf60dbae05284a1b481
[ "if storage_type == 'sql':\n loader = cls._get_sql_loader(provider, **kwargs)\nelif storage_type == 's3':\n loader = cls._get_s3_loader(provider)\nelse:\n raise ValueError('Storage type %s is not supported' % storage_type)\nreturn loader", "loader: icdlab.AbstractS3DataLoader\nif provider == 'kibot':\n ...
<|body_start_0|> if storage_type == 'sql': loader = cls._get_sql_loader(provider, **kwargs) elif storage_type == 's3': loader = cls._get_s3_loader(provider) else: raise ValueError('Storage type %s is not supported' % storage_type) return loader <|end_b...
Builds AbstractDataLoader objects based on different criteria (e.g., provider and storage type).
LoaderFactory
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LoaderFactory: """Builds AbstractDataLoader objects based on different criteria (e.g., provider and storage type).""" def get_loader(cls, storage_type: str, provider: str, **kwargs: Any) -> icdlab.AbstractDataLoader: """Return a data loader for the requested `storage_type` and `provi...
stack_v2_sparse_classes_36k_train_024790
3,109
permissive
[ { "docstring": "Return a data loader for the requested `storage_type` and `provider`. :param storage_type: load from where (e.g., s3, sql) :param provider: provider (e.g., kibot, ib) :param kwargs: additional parameters for loader instantiation :raises ValueError: `storage_type` loader is not implemented for pr...
3
stack_v2_sparse_classes_30k_train_000562
Implement the Python class `LoaderFactory` described below. Class description: Builds AbstractDataLoader objects based on different criteria (e.g., provider and storage type). Method signatures and docstrings: - def get_loader(cls, storage_type: str, provider: str, **kwargs: Any) -> icdlab.AbstractDataLoader: Return ...
Implement the Python class `LoaderFactory` described below. Class description: Builds AbstractDataLoader objects based on different criteria (e.g., provider and storage type). Method signatures and docstrings: - def get_loader(cls, storage_type: str, provider: str, **kwargs: Any) -> icdlab.AbstractDataLoader: Return ...
363c59fa29df2ba2719cbad2f8a19ae12cc54a92
<|skeleton|> class LoaderFactory: """Builds AbstractDataLoader objects based on different criteria (e.g., provider and storage type).""" def get_loader(cls, storage_type: str, provider: str, **kwargs: Any) -> icdlab.AbstractDataLoader: """Return a data loader for the requested `storage_type` and `provi...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class LoaderFactory: """Builds AbstractDataLoader objects based on different criteria (e.g., provider and storage type).""" def get_loader(cls, storage_type: str, provider: str, **kwargs: Any) -> icdlab.AbstractDataLoader: """Return a data loader for the requested `storage_type` and `provider`. :param ...
the_stack_v2_python_sparse
im/app/services/loader_factory.py
srlindemann/amp
train
0
e56498107c650b8f0078a4c2b42b3c63f5253d9b
[ "if not isinstance(tpl, tuple):\n return False\nif not len(tpl) == 2:\n return False\nif not isinstance(tpl[0], int) or not isinstance(tpl[1], int):\n return False\nif tpl[0] < 0 or tpl[1] < 0:\n return False\nreturn True", "if not isinstance(array, np.ndarray) or not self.shape(dimensions) or (not se...
<|body_start_0|> if not isinstance(tpl, tuple): return False if not len(tpl) == 2: return False if not isinstance(tpl[0], int) or not isinstance(tpl[1], int): return False if tpl[0] < 0 or tpl[1] < 0: return False return True <|end_...
Scrapbooker class
ScrapBooker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ScrapBooker: """Scrapbooker class""" def shape(self, tpl): """Utility to check if object is a valid 'shape' of format (x, y)""" <|body_0|> def crop(self, array, dimensions, position=(0, 0)): """Crops the image as a rectangle via dim arguments (being the new heigh...
stack_v2_sparse_classes_36k_train_024791
3,859
no_license
[ { "docstring": "Utility to check if object is a valid 'shape' of format (x, y)", "name": "shape", "signature": "def shape(self, tpl)" }, { "docstring": "Crops the image as a rectangle via dim arguments (being the new height and width oof the image) from the coordinates given by position argument...
5
stack_v2_sparse_classes_30k_train_006661
Implement the Python class `ScrapBooker` described below. Class description: Scrapbooker class Method signatures and docstrings: - def shape(self, tpl): Utility to check if object is a valid 'shape' of format (x, y) - def crop(self, array, dimensions, position=(0, 0)): Crops the image as a rectangle via dim arguments...
Implement the Python class `ScrapBooker` described below. Class description: Scrapbooker class Method signatures and docstrings: - def shape(self, tpl): Utility to check if object is a valid 'shape' of format (x, y) - def crop(self, array, dimensions, position=(0, 0)): Crops the image as a rectangle via dim arguments...
d47cab16cbad806a14b1323014dbab8da5a000aa
<|skeleton|> class ScrapBooker: """Scrapbooker class""" def shape(self, tpl): """Utility to check if object is a valid 'shape' of format (x, y)""" <|body_0|> def crop(self, array, dimensions, position=(0, 0)): """Crops the image as a rectangle via dim arguments (being the new heigh...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ScrapBooker: """Scrapbooker class""" def shape(self, tpl): """Utility to check if object is a valid 'shape' of format (x, y)""" if not isinstance(tpl, tuple): return False if not len(tpl) == 2: return False if not isinstance(tpl[0], int) or not isin...
the_stack_v2_python_sparse
day03/ex02/ScrapBooker.py
cclaude42/python_bootcamp
train
7
c080cdf86e43b13bc5852d13a061e33a6e7b2e73
[ "_check_data_dim(data, dim=2)\nx = data[:, 0]\ny = data[:, 1]\nA = np.zeros((3, data.shape[0]), dtype=np.double)\nA[2, :] = -1\n\ndef dist(xc, yc):\n return np.sqrt((x - xc) ** 2 + (y - yc) ** 2)\n\ndef fun(params):\n xc, yc, r = params\n return dist(xc, yc) - r\n\ndef Dfun(params):\n xc, yc, r = params...
<|body_start_0|> _check_data_dim(data, dim=2) x = data[:, 0] y = data[:, 1] A = np.zeros((3, data.shape[0]), dtype=np.double) A[2, :] = -1 def dist(xc, yc): return np.sqrt((x - xc) ** 2 + (y - yc) ** 2) def fun(params): xc, yc, r = params...
Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } A minimum number of 3 points is required to solve for the paramet...
CircleModel
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CircleModel: """Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } A minimum number of 3 poin...
stack_v2_sparse_classes_36k_train_024792
28,119
permissive
[ { "docstring": "Estimate circle model from data using total least squares. Parameters ---------- data : (N, 2) array N points with ``(x, y)`` coordinates, respectively. Returns ------- success : bool True, if model estimation succeeds.", "name": "estimate", "signature": "def estimate(self, data)" }, ...
3
stack_v2_sparse_classes_30k_train_000093
Implement the Python class `CircleModel` described below. Class description: Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc...
Implement the Python class `CircleModel` described below. Class description: Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class CircleModel: """Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } A minimum number of 3 poin...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class CircleModel: """Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } A minimum number of 3 points is require...
the_stack_v2_python_sparse
Skimage_numpy/source/skimage/measure/fit.py
ryfeus/lambda-packs
train
1,283
4bc1c7956d246798c6432acedc08f32fae3b718b
[ "if self._disk_subformat is None:\n with open(self.path, 'rb') as fileobj:\n header = fileobj.read(1000).decode('ascii', 'ignore')\n match = re.search('createType=\"(.*)\"', header)\n if not match:\n raise RuntimeError(\"Could not find VMDK 'createType' in the file header:\\n{0}\".format(head...
<|body_start_0|> if self._disk_subformat is None: with open(self.path, 'rb') as fileobj: header = fileobj.read(1000).decode('ascii', 'ignore') match = re.search('createType="(.*)"', header) if not match: raise RuntimeError("Could not find VMDK ...
VMDK disk image file representation.
VMDK
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VMDK: """VMDK disk image file representation.""" def disk_subformat(self): """Disk subformat, such as 'streamOptimized'.""" <|body_0|> def from_other_image(cls, input_image, output_dir, output_subformat='streamOptimized'): """Convert the other disk image into an ...
stack_v2_sparse_classes_36k_train_024793
7,641
permissive
[ { "docstring": "Disk subformat, such as 'streamOptimized'.", "name": "disk_subformat", "signature": "def disk_subformat(self)" }, { "docstring": "Convert the other disk image into an image of this type. Args: input_image (DiskRepresentation): Existing image representation. output_dir (str): Outp...
3
stack_v2_sparse_classes_30k_train_011852
Implement the Python class `VMDK` described below. Class description: VMDK disk image file representation. Method signatures and docstrings: - def disk_subformat(self): Disk subformat, such as 'streamOptimized'. - def from_other_image(cls, input_image, output_dir, output_subformat='streamOptimized'): Convert the othe...
Implement the Python class `VMDK` described below. Class description: VMDK disk image file representation. Method signatures and docstrings: - def disk_subformat(self): Disk subformat, such as 'streamOptimized'. - def from_other_image(cls, input_image, output_dir, output_subformat='streamOptimized'): Convert the othe...
0811b96311881a8293f28f2e300f6bed1b77ee31
<|skeleton|> class VMDK: """VMDK disk image file representation.""" def disk_subformat(self): """Disk subformat, such as 'streamOptimized'.""" <|body_0|> def from_other_image(cls, input_image, output_dir, output_subformat='streamOptimized'): """Convert the other disk image into an ...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class VMDK: """VMDK disk image file representation.""" def disk_subformat(self): """Disk subformat, such as 'streamOptimized'.""" if self._disk_subformat is None: with open(self.path, 'rb') as fileobj: header = fileobj.read(1000).decode('ascii', 'ignore') ...
the_stack_v2_python_sparse
COT/disks/vmdk.py
glennmatthews/cot
train
88
1bb39d0527726bbab2b79a96b63c677b6f88e5e1
[ "data = {'token': self.token, 'project_id': project_id}\ndata.update(kwargs)\nfiles = {'file': open(filename, 'r')}\nreturn self.api._post('templates/import_into_project', data=data, files=files)", "data = {'token': self.token, 'project_id': project_id}\ndata.update(kwargs)\nreturn self.api._post('templates/expor...
<|body_start_0|> data = {'token': self.token, 'project_id': project_id} data.update(kwargs) files = {'file': open(filename, 'r')} return self.api._post('templates/import_into_project', data=data, files=files) <|end_body_0|> <|body_start_1|> data = {'token': self.token, 'project_...
TemplatesManager
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplatesManager: def import_into_project(self, project_id, filename, **kwargs): """Imports a template into a project.""" <|body_0|> def export_as_file(self, project_id, **kwargs): """Exports a template as a file.""" <|body_1|> def export_as_url(self, pr...
stack_v2_sparse_classes_36k_train_024794
993
permissive
[ { "docstring": "Imports a template into a project.", "name": "import_into_project", "signature": "def import_into_project(self, project_id, filename, **kwargs)" }, { "docstring": "Exports a template as a file.", "name": "export_as_file", "signature": "def export_as_file(self, project_id,...
3
stack_v2_sparse_classes_30k_train_007706
Implement the Python class `TemplatesManager` described below. Class description: Implement the TemplatesManager class. Method signatures and docstrings: - def import_into_project(self, project_id, filename, **kwargs): Imports a template into a project. - def export_as_file(self, project_id, **kwargs): Exports a temp...
Implement the Python class `TemplatesManager` described below. Class description: Implement the TemplatesManager class. Method signatures and docstrings: - def import_into_project(self, project_id, filename, **kwargs): Imports a template into a project. - def export_as_file(self, project_id, **kwargs): Exports a temp...
7b85de81619146d3d54fececda068010ae73775b
<|skeleton|> class TemplatesManager: def import_into_project(self, project_id, filename, **kwargs): """Imports a template into a project.""" <|body_0|> def export_as_file(self, project_id, **kwargs): """Exports a template as a file.""" <|body_1|> def export_as_url(self, pr...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class TemplatesManager: def import_into_project(self, project_id, filename, **kwargs): """Imports a template into a project.""" data = {'token': self.token, 'project_id': project_id} data.update(kwargs) files = {'file': open(filename, 'r')} return self.api._post('templates/im...
the_stack_v2_python_sparse
todoist/managers/templates.py
Doist/todoist-python
train
627
635f22143c3d162117e618e790d84e4b1921ae3d
[ "self.color = color\nself.color_code = '0xFFFFFF'\nif self.color == 'blue':\n self.color_code = '#1E90FF'\nelif self.color == 'red':\n self.color_code = '#DC143C'\nelif self.color == 'green':\n self.color_code = '#32CD32'\nself.stations = {}", "logger.info(f'In Line({self.color}), creating station:{json....
<|body_start_0|> self.color = color self.color_code = '0xFFFFFF' if self.color == 'blue': self.color_code = '#1E90FF' elif self.color == 'red': self.color_code = '#DC143C' elif self.color == 'green': self.color_code = '#32CD32' self.sta...
Defines the Line Model
Line
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Line: """Defines the Line Model""" def __init__(self, color): """Creates a line""" <|body_0|> def _handle_station(self, value): """Adds the station to this Line's data model""" <|body_1|> def _handle_arrival(self, message): """Updates train l...
stack_v2_sparse_classes_36k_train_024795
4,009
no_license
[ { "docstring": "Creates a line", "name": "__init__", "signature": "def __init__(self, color)" }, { "docstring": "Adds the station to this Line's data model", "name": "_handle_station", "signature": "def _handle_station(self, value)" }, { "docstring": "Updates train locations", ...
4
stack_v2_sparse_classes_30k_train_002859
Implement the Python class `Line` described below. Class description: Defines the Line Model Method signatures and docstrings: - def __init__(self, color): Creates a line - def _handle_station(self, value): Adds the station to this Line's data model - def _handle_arrival(self, message): Updates train locations - def ...
Implement the Python class `Line` described below. Class description: Defines the Line Model Method signatures and docstrings: - def __init__(self, color): Creates a line - def _handle_station(self, value): Adds the station to this Line's data model - def _handle_arrival(self, message): Updates train locations - def ...
6688dfbaac143730e8eec0e0b1540f502a8c00bd
<|skeleton|> class Line: """Defines the Line Model""" def __init__(self, color): """Creates a line""" <|body_0|> def _handle_station(self, value): """Adds the station to this Line's data model""" <|body_1|> def _handle_arrival(self, message): """Updates train l...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Line: """Defines the Line Model""" def __init__(self, color): """Creates a line""" self.color = color self.color_code = '0xFFFFFF' if self.color == 'blue': self.color_code = '#1E90FF' elif self.color == 'red': self.color_code = '#DC143C' ...
the_stack_v2_python_sparse
Optimizing Public Transportation/consumers/models/line.py
gmpatil/DataStreamingND
train
0
854fdb81330fd1292d122a477393c5810e1fff61
[ "self.name = name\nif isinstance(appNamespace, ModuleType):\n self.appNamespace = appNamespace\nelse:\n raise TypeError('Second argument of ViewRouter constructor must be a python module.')\nif label is not None:\n self.label = label\nelse:\n self.label = self.name\nself.registry[name] = self\nself.page...
<|body_start_0|> self.name = name if isinstance(appNamespace, ModuleType): self.appNamespace = appNamespace else: raise TypeError('Second argument of ViewRouter constructor must be a python module.') if label is not None: self.label = label els...
This class creates a global registry of pages. Web pages register with an instance (router) using the @registerView decorator, and can be served when requested (from router.pages)
ViewRouter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ViewRouter: """This class creates a global registry of pages. Web pages register with an instance (router) using the @registerView decorator, and can be served when requested (from router.pages)""" def __init__(self, name, appNamespace, label=None): """:param str name: the name of th...
stack_v2_sparse_classes_36k_train_024796
1,575
no_license
[ { "docstring": ":param str name: the name of the router, used as part of the name for the page URL: http::/hostname/routerName/pageName", "name": "__init__", "signature": "def __init__(self, name, appNamespace, label=None)" }, { "docstring": "Calls a page view function with name *name* passing t...
2
null
Implement the Python class `ViewRouter` described below. Class description: This class creates a global registry of pages. Web pages register with an instance (router) using the @registerView decorator, and can be served when requested (from router.pages) Method signatures and docstrings: - def __init__(self, name, a...
Implement the Python class `ViewRouter` described below. Class description: This class creates a global registry of pages. Web pages register with an instance (router) using the @registerView decorator, and can be served when requested (from router.pages) Method signatures and docstrings: - def __init__(self, name, a...
91d2eca1e443c5bca0757c5576e86a227c45288c
<|skeleton|> class ViewRouter: """This class creates a global registry of pages. Web pages register with an instance (router) using the @registerView decorator, and can be served when requested (from router.pages)""" def __init__(self, name, appNamespace, label=None): """:param str name: the name of th...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class ViewRouter: """This class creates a global registry of pages. Web pages register with an instance (router) using the @registerView decorator, and can be served when requested (from router.pages)""" def __init__(self, name, appNamespace, label=None): """:param str name: the name of the router, use...
the_stack_v2_python_sparse
smo/web/router.py
wzzhhh1/SmoWeb
train
0
fc7e7f164d6ac62856bc4f9717c4d73d7301922f
[ "queue = [root] if root else []\nres = ''\nwhile queue:\n node = queue.pop(0)\n if node:\n res += '%d,' % node.val\n queue.append(node.left)\n queue.append(node.right)\n else:\n res += 'N,'\nreturn res[:-1]", "data_list = data.split(',')\nval = data_list.pop(0)\nif not val:\n ...
<|body_start_0|> queue = [root] if root else [] res = '' while queue: node = queue.pop(0) if node: res += '%d,' % node.val queue.append(node.left) queue.append(node.right) else: res += 'N,' ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_36k_train_024797
2,305
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_007187
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
95d5aa4158209ad9ab81017e3bc82ef0680ea6bd
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" queue = [root] if root else [] res = '' while queue: node = queue.pop(0) if node: res += '%d,' % node.val queue.ap...
the_stack_v2_python_sparse
Tree/BinaryTree/297_Serialize_and_Deserialize_Binary_Tree.py
OldFuzzier/Data-Structures-and-Algorithms-
train
0
6d3f111e512bc82eefbd0e8bec7dfb33148bac1b
[ "hub_status_count = HubStatus.objects.count()\nlamp_status_count = LampCtrlStatus.objects.count()\nthreads_count = 1\nmysql_memory = 0\nif platform.system() == 'Linux':\n process = subprocess.Popen('mysqladmin -uroot -psmartlamp status', shell=True, stdout=subprocess.PIPE)\n ret = process.stdout.readline()\n ...
<|body_start_0|> hub_status_count = HubStatus.objects.count() lamp_status_count = LampCtrlStatus.objects.count() threads_count = 1 mysql_memory = 0 if platform.system() == 'Linux': process = subprocess.Popen('mysqladmin -uroot -psmartlamp status', shell=True, stdout=s...
状态 get_database_status: 获取数据库状态
StatusViewSet
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StatusViewSet: """状态 get_database_status: 获取数据库状态""" def get_database_status(self, request, *args, **kwargs): """获取数据库状态 GET /status/database/ :return { "hub_status_count": hub_status_count, "lamp_status_count": lamp_status_count, "threads_count": threads_count, "database_memory": my...
stack_v2_sparse_classes_36k_train_024798
5,381
no_license
[ { "docstring": "获取数据库状态 GET /status/database/ :return { \"hub_status_count\": hub_status_count, \"lamp_status_count\": lamp_status_count, \"threads_count\": threads_count, \"database_memory\": mysql_memory }", "name": "get_database_status", "signature": "def get_database_status(self, request, *args, **k...
2
null
Implement the Python class `StatusViewSet` described below. Class description: 状态 get_database_status: 获取数据库状态 Method signatures and docstrings: - def get_database_status(self, request, *args, **kwargs): 获取数据库状态 GET /status/database/ :return { "hub_status_count": hub_status_count, "lamp_status_count": lamp_status_cou...
Implement the Python class `StatusViewSet` described below. Class description: 状态 get_database_status: 获取数据库状态 Method signatures and docstrings: - def get_database_status(self, request, *args, **kwargs): 获取数据库状态 GET /status/database/ :return { "hub_status_count": hub_status_count, "lamp_status_count": lamp_status_cou...
e153a5c02cce248bea8412f432c02d5e26f1fdc1
<|skeleton|> class StatusViewSet: """状态 get_database_status: 获取数据库状态""" def get_database_status(self, request, *args, **kwargs): """获取数据库状态 GET /status/database/ :return { "hub_status_count": hub_status_count, "lamp_status_count": lamp_status_count, "threads_count": threads_count, "database_memory": my...
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class StatusViewSet: """状态 get_database_status: 获取数据库状态""" def get_database_status(self, request, *args, **kwargs): """获取数据库状态 GET /status/database/ :return { "hub_status_count": hub_status_count, "lamp_status_count": lamp_status_count, "threads_count": threads_count, "database_memory": mysql_memory }"...
the_stack_v2_python_sparse
apps/status/views.py
CabbyWang/django-demo
train
0
bf9f1b5d0fe2f1f28c3041d3ed1af49bbf0090d4
[ "q = Queue.PriorityQueue()\nfor n in nums:\n if q.qsize() == k + 1:\n q.get()\n q.put(n)\nwhile q.qsize() != k:\n q.get()\nreturn q.get()", "import heapq\nary = []\nfor i in nums:\n heapq.heappush(ary, i)\n if len(ary) > k:\n heapq.heappop(ary)\nreturn heapq.heappop(ary)" ]
<|body_start_0|> q = Queue.PriorityQueue() for n in nums: if q.qsize() == k + 1: q.get() q.put(n) while q.qsize() != k: q.get() return q.get() <|end_body_0|> <|body_start_1|> import heapq ary = [] for i in nums:...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def findKthLargest(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def rewrite(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> q = Queue.Prio...
stack_v2_sparse_classes_36k_train_024799
1,497
no_license
[ { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "findKthLargest", "signature": "def findKthLargest(self, nums, k)" }, { "docstring": ":type nums: List[int] :type k: int :rtype: int", "name": "rewrite", "signature": "def rewrite(self, nums, k)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def rewrite(self, nums, k): :type nums: List[int] :type k: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def findKthLargest(self, nums, k): :type nums: List[int] :type k: int :rtype: int - def rewrite(self, nums, k): :type nums: List[int] :type k: int :rtype: int <|skeleton|> class...
6350568d16b0f8c49a020f055bb6d72e2705ea56
<|skeleton|> class Solution: def findKthLargest(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_0|> def rewrite(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_36k
data/stack_v2_sparse_classes_30k
class Solution: def findKthLargest(self, nums, k): """:type nums: List[int] :type k: int :rtype: int""" q = Queue.PriorityQueue() for n in nums: if q.qsize() == k + 1: q.get() q.put(n) while q.qsize() != k: q.get() return q....
the_stack_v2_python_sparse
co_ms/215_Kth_Largest_Element_in_an_Array.py
vsdrun/lc_public
train
6