blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
378
8.64k
id
stringlengths
44
44
length_bytes
int64
505
50k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
153
4.88k
prompted_full_text
stringlengths
565
12.5k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
5.05k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
snapshot_total_rows
int64
75.8k
75.8k
solution
stringlengths
242
8.3k
source
stringclasses
1 value
source_path
stringlengths
4
177
source_repo
stringlengths
6
110
split
stringclasses
1 value
star_events_count
int64
0
209k
023484b9614624f255c4cceb2cc9709a8df1ba39
[ "world = c4d.GetWorldContainerInstance()\nif world is None:\n raise RuntimeError('Failed to retrieve the world container instance.')\nbc = world.GetContainerInstance(WPREF_PYPREFERENCE)\nif bc is None:\n world.SetContainer(WPREF_PYPREFERENCE, c4d.BaseContainer())\n bc = world.GetContainerInstance(WPREF_PYP...
<|body_start_0|> world = c4d.GetWorldContainerInstance() if world is None: raise RuntimeError('Failed to retrieve the world container instance.') bc = world.GetContainerInstance(WPREF_PYPREFERENCE) if bc is None: world.SetContainer(WPREF_PYPREFERENCE, c4d.BaseCont...
PreferenceHelper
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PreferenceHelper: def GetPreferenceContainer(): """Helper method to retrieve or create the WPREF_PYPREFERENCE container instance stored in the world container. Returns: c4d.BaseContainer: The container instance stored in the world container. Raises: RuntimeError: The BaseContainer can't ...
stack_v2_sparse_classes_75kplus_train_006300
9,244
permissive
[ { "docstring": "Helper method to retrieve or create the WPREF_PYPREFERENCE container instance stored in the world container. Returns: c4d.BaseContainer: The container instance stored in the world container. Raises: RuntimeError: The BaseContainer can't be retrieved. MemoryError: The BaseContainer can't be creat...
2
stack_v2_sparse_classes_30k_train_019708
Implement the Python class `PreferenceHelper` described below. Class description: Implement the PreferenceHelper class. Method signatures and docstrings: - def GetPreferenceContainer(): Helper method to retrieve or create the WPREF_PYPREFERENCE container instance stored in the world container. Returns: c4d.BaseContai...
Implement the Python class `PreferenceHelper` described below. Class description: Implement the PreferenceHelper class. Method signatures and docstrings: - def GetPreferenceContainer(): Helper method to retrieve or create the WPREF_PYPREFERENCE container instance stored in the world container. Returns: c4d.BaseContai...
b1ea3fce533df34094bc3d0bd6460dfb84306e53
<|skeleton|> class PreferenceHelper: def GetPreferenceContainer(): """Helper method to retrieve or create the WPREF_PYPREFERENCE container instance stored in the world container. Returns: c4d.BaseContainer: The container instance stored in the world container. Raises: RuntimeError: The BaseContainer can't ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PreferenceHelper: def GetPreferenceContainer(): """Helper method to retrieve or create the WPREF_PYPREFERENCE container instance stored in the world container. Returns: c4d.BaseContainer: The container instance stored in the world container. Raises: RuntimeError: The BaseContainer can't be retrieved. ...
the_stack_v2_python_sparse
plugins/py-preference_r19/py-preference_r19.pyp
PluginCafe/cinema4d_py_sdk_extended
train
112
f9baafe5a1a83b9e04a5b3b64a78729a345e5ed8
[ "self.name = name\nself.space = space\nself.input_ = input_\nself.output_ = output_\nself.commands = commands", "print('-----------------------------------------------------------')\nprint(' Current Command List ')\nprint('------------------------------------------------------...
<|body_start_0|> self.name = name self.space = space self.input_ = input_ self.output_ = output_ self.commands = commands <|end_body_0|> <|body_start_1|> print('-----------------------------------------------------------') print(' Current Comma...
Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertices output_ (list): output vertices c...
Pattern
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Pattern: """Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertice...
stack_v2_sparse_classes_75kplus_train_006301
7,995
permissive
[ { "docstring": "Constructor for Pattern class. Args: name (str): pattern name space (list): space vertices input_ (list): input vertices output_ (list): output vertices commands (list): command list", "name": "__init__", "signature": "def __init__(self, name: str, space: list, input_: list, output_: lis...
2
stack_v2_sparse_classes_30k_train_001069
Implement the Python class `Pattern` described below. Class description: Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): spac...
Implement the Python class `Pattern` described below. Class description: Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): spac...
8bc3c7238b5b6825eb63ded8d65afb08b389941f
<|skeleton|> class Pattern: """Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertice...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Pattern: """Class for creating a measurement pattern. This class represents the measurement pattern in the MBQC model. Please refer to [The measurement calculus, arXiv: 0704.1263] for technical details. Attributes: name (str): pattern name space (list): space vertices input_ (list): input vertices output_ (li...
the_stack_v2_python_sparse
Extensions/QuantumNetwork/qcompute_qnet/quantum/pattern.py
baidu/QCompute
train
86
1b90bf16b9ec49b8766d9150db91b8706610a94f
[ "if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.ValidationError(_('The email address provided is already registered. Please use a different email address/login now.'))\nreturn self.cleaned_data['email']", "if User.objects.filter(email__iexact=self.cleaned_data['username']):\n ...
<|body_start_0|> if User.objects.filter(email__iexact=self.cleaned_data['email']): raise forms.ValidationError(_('The email address provided is already registered. Please use a different email address/login now.')) return self.cleaned_data['email'] <|end_body_0|> <|body_start_1|> if...
Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user...
RegistrationForm
[ "BSD-2-Clause-Views", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistrationForm: """Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m...
stack_v2_sparse_classes_75kplus_train_006302
11,099
permissive
[ { "docstring": "Validate that the supplied email address is unique for the site.", "name": "clean_email", "signature": "def clean_email(self)" }, { "docstring": "Validate that the supplied username is unique for the site.", "name": "clean_username", "signature": "def clean_username(self)...
3
stack_v2_sparse_classes_30k_val_002292
Implement the Python class `RegistrationForm` described below. Class description: Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b...
Implement the Python class `RegistrationForm` described below. Class description: Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, b...
75a09bc5d0a2ec0ae994ac900a93dc027b527860
<|skeleton|> class RegistrationForm: """Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` m...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegistrationForm: """Form for registering a new user account. Validates that the requested username is not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the ...
the_stack_v2_python_sparse
Web_Server/webapps/accounts/forms.py
bemoss/BEMOSS3.5
train
81
b00c86d18aa3b01cfe4e7cee7588f86503dda518
[ "self.max_depth = max_depth\nself.save_images = save_images\nself.clock = time.time()\nself.t_save_frame = t_save_frame\nself.output_dir = output_dir\nself.data_dir = path.join(self.output_dir, '{}'.format(time.strftime('%d_%b_%Y_%H:%M', time.localtime())))\nif self.save_images:\n ensureDir(self.data_dir)\npass"...
<|body_start_0|> self.max_depth = max_depth self.save_images = save_images self.clock = time.time() self.t_save_frame = t_save_frame self.output_dir = output_dir self.data_dir = path.join(self.output_dir, '{}'.format(time.strftime('%d_%b_%Y_%H:%M', time.localtime()))) ...
Object to get data from Realsense Camera
Camera
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Camera: """Object to get data from Realsense Camera""" def __init__(self, max_depth=4, save_images=False, t_save_frame=5, output_dir='./trials/'): """Intitalize Camera object""" <|body_0|> def connect(self): """Establish connection to R200 camera""" <|bod...
stack_v2_sparse_classes_75kplus_train_006303
3,758
permissive
[ { "docstring": "Intitalize Camera object", "name": "__init__", "signature": "def __init__(self, max_depth=4, save_images=False, t_save_frame=5, output_dir='./trials/')" }, { "docstring": "Establish connection to R200 camera", "name": "connect", "signature": "def connect(self)" }, { ...
5
null
Implement the Python class `Camera` described below. Class description: Object to get data from Realsense Camera Method signatures and docstrings: - def __init__(self, max_depth=4, save_images=False, t_save_frame=5, output_dir='./trials/'): Intitalize Camera object - def connect(self): Establish connection to R200 ca...
Implement the Python class `Camera` described below. Class description: Object to get data from Realsense Camera Method signatures and docstrings: - def __init__(self, max_depth=4, save_images=False, t_save_frame=5, output_dir='./trials/'): Intitalize Camera object - def connect(self): Establish connection to R200 ca...
cc436ee5e52e66947bd932f4670acc701a6bbda0
<|skeleton|> class Camera: """Object to get data from Realsense Camera""" def __init__(self, max_depth=4, save_images=False, t_save_frame=5, output_dir='./trials/'): """Intitalize Camera object""" <|body_0|> def connect(self): """Establish connection to R200 camera""" <|bod...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Camera: """Object to get data from Realsense Camera""" def __init__(self, max_depth=4, save_images=False, t_save_frame=5, output_dir='./trials/'): """Intitalize Camera object""" self.max_depth = max_depth self.save_images = save_images self.clock = time.time() self...
the_stack_v2_python_sparse
main/vision/cam.py
IntelligentQuadruped/Implementation
train
2
85bd67b0b56ba41c8b00f11196096949829e2219
[ "from collections import Counter\ncouter = Counter(s)\nprint(couter)\nres = 0\nflag = False\nfor each in couter.keys():\n if couter[each] % 2 == 1:\n flag = True\n res += couter[each] - 1\n else:\n res += couter[each]\nif flag:\n return res + 1\nelse:\n return res", "strs = set(s)...
<|body_start_0|> from collections import Counter couter = Counter(s) print(couter) res = 0 flag = False for each in couter.keys(): if couter[each] % 2 == 1: flag = True res += couter[each] - 1 else: r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def longestPalindrome(self, s): """:type s: str :rtype: int""" <|body_0|> def longestPalindrome2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> from collections import Counter couter = Counter...
stack_v2_sparse_classes_75kplus_train_006304
1,930
no_license
[ { "docstring": ":type s: str :rtype: int", "name": "longestPalindrome", "signature": "def longestPalindrome(self, s)" }, { "docstring": ":type s: str :rtype: int", "name": "longestPalindrome2", "signature": "def longestPalindrome2(self, s)" } ]
2
stack_v2_sparse_classes_30k_train_030049
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome(self, s): :type s: str :rtype: int - def longestPalindrome2(self, s): :type s: str :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def longestPalindrome(self, s): :type s: str :rtype: int - def longestPalindrome2(self, s): :type s: str :rtype: int <|skeleton|> class Solution: def longestPalindrome(self...
4105e18050b15fc0409c75353ad31be17187dd34
<|skeleton|> class Solution: def longestPalindrome(self, s): """:type s: str :rtype: int""" <|body_0|> def longestPalindrome2(self, s): """:type s: str :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def longestPalindrome(self, s): """:type s: str :rtype: int""" from collections import Counter couter = Counter(s) print(couter) res = 0 flag = False for each in couter.keys(): if couter[each] % 2 == 1: flag = True ...
the_stack_v2_python_sparse
longestPalindrome.py
NeilWangziyu/Leetcode_py
train
2
2ba56f4e374a3001d13a22b515c37fc001101409
[ "self._name = name\nself._topic_blacklist = topic_blacklist\nself._regexes = set([re.compile(regex) for regex in regexes])", "for regex in self._regexes:\n match = regex.search(source_line)\n if match is None:\n continue\n route_group, topic_group = match.groups()\n log.debug(' ####:{}...
<|body_start_0|> self._name = name self._topic_blacklist = topic_blacklist self._regexes = set([re.compile(regex) for regex in regexes]) <|end_body_0|> <|body_start_1|> for regex in self._regexes: match = regex.search(source_line) if match is None: ...
Collects either publication or subscription information for nodes (modules and topics) & edges
PubSub
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PubSub: """Collects either publication or subscription information for nodes (modules and topics) & edges""" def __init__(self, name, topic_blacklist, regexes): """:param is_publication: if True, publications, False for subscriptions :param topic_blacklist: list of topics to blacklis...
stack_v2_sparse_classes_75kplus_train_006305
32,023
permissive
[ { "docstring": ":param is_publication: if True, publications, False for subscriptions :param topic_blacklist: list of topics to blacklist :param orb_pub_sub_regexes: list of regexes to extract orb calls (e.g. orb_subscribe). They need to have 2 captures, the second one is the one capturing ORB_ID(<topic>", ...
3
stack_v2_sparse_classes_30k_test_002843
Implement the Python class `PubSub` described below. Class description: Collects either publication or subscription information for nodes (modules and topics) & edges Method signatures and docstrings: - def __init__(self, name, topic_blacklist, regexes): :param is_publication: if True, publications, False for subscri...
Implement the Python class `PubSub` described below. Class description: Collects either publication or subscription information for nodes (modules and topics) & edges Method signatures and docstrings: - def __init__(self, name, topic_blacklist, regexes): :param is_publication: if True, publications, False for subscri...
3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b
<|skeleton|> class PubSub: """Collects either publication or subscription information for nodes (modules and topics) & edges""" def __init__(self, name, topic_blacklist, regexes): """:param is_publication: if True, publications, False for subscriptions :param topic_blacklist: list of topics to blacklis...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PubSub: """Collects either publication or subscription information for nodes (modules and topics) & edges""" def __init__(self, name, topic_blacklist, regexes): """:param is_publication: if True, publications, False for subscriptions :param topic_blacklist: list of topics to blacklist :param orb_...
the_stack_v2_python_sparse
Tools/uorb_graph/create.py
PX4/PX4-Autopilot
train
3,146
29209b4589c204ccbb0a1972fd35ec7981d29065
[ "subject = loader.render_to_string(subject_template_name, context)\nsubject = ''.join(subject.splitlines())\nbody = loader.render_to_string(email_template_name, context)\nemail_message = EmailMultiAlternatives(subject, body, from_email, [to_email])\nif html_email_template_name is not None:\n html_email = loader....
<|body_start_0|> subject = loader.render_to_string(subject_template_name, context) subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_temp...
This is a just an update copy of django.contrib.auth.views PasswordResetForm
PasswordResetForm
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordResetForm: """This is a just an update copy of django.contrib.auth.views PasswordResetForm""" def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """Send a django.core.mail.EmailMultiAlternatives to `t...
stack_v2_sparse_classes_75kplus_train_006306
9,146
no_license
[ { "docstring": "Send a django.core.mail.EmailMultiAlternatives to `to_email`.", "name": "send_mail", "signature": "def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)" }, { "docstring": "Given an email, return matching use...
3
null
Implement the Python class `PasswordResetForm` described below. Class description: This is a just an update copy of django.contrib.auth.views PasswordResetForm Method signatures and docstrings: - def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=No...
Implement the Python class `PasswordResetForm` described below. Class description: This is a just an update copy of django.contrib.auth.views PasswordResetForm Method signatures and docstrings: - def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=No...
608c2bf94aad0dd68b0c026c0163ab37ed7bee47
<|skeleton|> class PasswordResetForm: """This is a just an update copy of django.contrib.auth.views PasswordResetForm""" def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """Send a django.core.mail.EmailMultiAlternatives to `t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class PasswordResetForm: """This is a just an update copy of django.contrib.auth.views PasswordResetForm""" def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """Send a django.core.mail.EmailMultiAlternatives to `to_email`.""" ...
the_stack_v2_python_sparse
anodyne/dashboard/forms.py
anodyneweb/aw_backend
train
0
f8aa5b3b0b72ba967e03b6132f872fdfeda5aeaa
[ "logger.info('BS-Seeker FilterReads wrapper')\nTool.__init__(self)\nif configuration is None:\n configuration = {}\nself.configuration.update(configuration)", "command_line = ('python ' + os.path.join(bss_path, 'FilterReads.py') + ' -i ' + infile + ' -o ' + outfile + '.tmp').format()\nlogger.info(command_line)...
<|body_start_0|> logger.info('BS-Seeker FilterReads wrapper') Tool.__init__(self) if configuration is None: configuration = {} self.configuration.update(configuration) <|end_body_0|> <|body_start_1|> command_line = ('python ' + os.path.join(bss_path, 'FilterReads.py'...
Script from BS-Seeker2 for filtering FASTQ files to remove repeats
filterReadsTool
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class filterReadsTool: """Script from BS-Seeker2 for filtering FASTQ files to remove repeats""" def __init__(self, configuration=None): """Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation...
stack_v2_sparse_classes_75kplus_train_006307
5,136
permissive
[ { "docstring": "Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be carried out, which are specific to each Tool.", "name": "__init__", "signature": "def __init__(self, configuration=None)" },...
3
stack_v2_sparse_classes_30k_val_002773
Implement the Python class `filterReadsTool` described below. Class description: Script from BS-Seeker2 for filtering FASTQ files to remove repeats Method signatures and docstrings: - def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dicti...
Implement the Python class `filterReadsTool` described below. Class description: Script from BS-Seeker2 for filtering FASTQ files to remove repeats Method signatures and docstrings: - def __init__(self, configuration=None): Initialise the tool with its configuration. Parameters ---------- configuration : dict a dicti...
50c7115c0c1a6af48dc34f275e469d1b9eb02999
<|skeleton|> class filterReadsTool: """Script from BS-Seeker2 for filtering FASTQ files to remove repeats""" def __init__(self, configuration=None): """Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class filterReadsTool: """Script from BS-Seeker2 for filtering FASTQ files to remove repeats""" def __init__(self, configuration=None): """Initialise the tool with its configuration. Parameters ---------- configuration : dict a dictionary containing parameters that define how the operation should be ca...
the_stack_v2_python_sparse
tool/bs_seeker_filter.py
Multiscale-Genomics/mg-process-fastq
train
2
e058a79bd0a7cadbac26d470acc2bc04c3af8bca
[ "super(SessionThread, self).__init__()\nself.created = datetime.utcnow()\nself.id = id\nself.connection = connection\nself.key = security.diffiehellman(self.connection)\ntry:\n self.info = self.client_info()\n self.info['id'] = self.id\nexcept Exception as e:\n util.log('Error creating session: {}'.format(...
<|body_start_0|> super(SessionThread, self).__init__() self.created = datetime.utcnow() self.id = id self.connection = connection self.key = security.diffiehellman(self.connection) try: self.info = self.client_info() self.info['id'] = self.id ...
A subclass of threading.Thread that is designed to handle an incoming connection by creating an new authenticated session for the encrypted connection of the reverse TCP shell
SessionThread
[ "GPL-1.0-or-later", "GPL-3.0-only", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionThread: """A subclass of threading.Thread that is designed to handle an incoming connection by creating an new authenticated session for the encrypted connection of the reverse TCP shell""" def __init__(self, connection=None, id=0): """Create a new Session `Requires` :param co...
stack_v2_sparse_classes_75kplus_train_006308
18,248
permissive
[ { "docstring": "Create a new Session `Requires` :param connection: socket.socket object `Optional` :param int id: session ID", "name": "__init__", "signature": "def __init__(self, connection=None, id=0)" }, { "docstring": "Kill the reverse TCP shell session", "name": "kill", "signature":...
5
null
Implement the Python class `SessionThread` described below. Class description: A subclass of threading.Thread that is designed to handle an incoming connection by creating an new authenticated session for the encrypted connection of the reverse TCP shell Method signatures and docstrings: - def __init__(self, connecti...
Implement the Python class `SessionThread` described below. Class description: A subclass of threading.Thread that is designed to handle an incoming connection by creating an new authenticated session for the encrypted connection of the reverse TCP shell Method signatures and docstrings: - def __init__(self, connecti...
bd5d6b089e54fdd1942189b43f43660a0499324f
<|skeleton|> class SessionThread: """A subclass of threading.Thread that is designed to handle an incoming connection by creating an new authenticated session for the encrypted connection of the reverse TCP shell""" def __init__(self, connection=None, id=0): """Create a new Session `Requires` :param co...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SessionThread: """A subclass of threading.Thread that is designed to handle an incoming connection by creating an new authenticated session for the encrypted connection of the reverse TCP shell""" def __init__(self, connection=None, id=0): """Create a new Session `Requires` :param connection: soc...
the_stack_v2_python_sparse
byob/web-gui/buildyourownbotnet/server.py
PandemicPiero/the-hacking-toolkit
train
0
8659451e6172ff2bf2a74292389e40a4ed166de5
[ "self.wall_list = pygame.sprite.Group()\nself.enemy_list = pygame.sprite.Group()\nself.sludge = pygame.sprite.Group()\nself.consumeable = pygame.sprite.Group()\nself.can_climb = pygame.sprite.Group()\nself.player = player\nself.spore_list = [Decompose_Spore, Ledge_Spore]\nself.active_spore = self.spore_list[0]\nsel...
<|body_start_0|> self.wall_list = pygame.sprite.Group() self.enemy_list = pygame.sprite.Group() self.sludge = pygame.sprite.Group() self.consumeable = pygame.sprite.Group() self.can_climb = pygame.sprite.Group() self.player = player self.spore_list = [Decompose_Sp...
This is a generic super-class used to define a level. Create a child class for each level with level-specific info.
Room
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Room: """This is a generic super-class used to define a level. Create a child class for each level with level-specific info.""" def __init__(self, player): """Constructor. Pass in a handle to player. Needed for when moving platforms collide with the player.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus_train_006309
4,353
permissive
[ { "docstring": "Constructor. Pass in a handle to player. Needed for when moving platforms collide with the player.", "name": "__init__", "signature": "def __init__(self, player)" }, { "docstring": "Update everything in this level.", "name": "update", "signature": "def update(self)" }, ...
4
stack_v2_sparse_classes_30k_train_010164
Implement the Python class `Room` described below. Class description: This is a generic super-class used to define a level. Create a child class for each level with level-specific info. Method signatures and docstrings: - def __init__(self, player): Constructor. Pass in a handle to player. Needed for when moving plat...
Implement the Python class `Room` described below. Class description: This is a generic super-class used to define a level. Create a child class for each level with level-specific info. Method signatures and docstrings: - def __init__(self, player): Constructor. Pass in a handle to player. Needed for when moving plat...
85b93c3ed756afec05a1c2ca58b68f856aa140cb
<|skeleton|> class Room: """This is a generic super-class used to define a level. Create a child class for each level with level-specific info.""" def __init__(self, player): """Constructor. Pass in a handle to player. Needed for when moving platforms collide with the player.""" <|body_0|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Room: """This is a generic super-class used to define a level. Create a child class for each level with level-specific info.""" def __init__(self, player): """Constructor. Pass in a handle to player. Needed for when moving platforms collide with the player.""" self.wall_list = pygame.spri...
the_stack_v2_python_sparse
Sean_Code_Review.py
KaitlynKeil/bug-free-spork
train
0
40d4c959dfab70ff3362e055e620a0eaa5c21411
[ "if do_generate:\n self.game_map = self.generate(size)\nelse:\n self.game_map = []", "trap_count = int(size ** 2 / RATIO_TRAPS)\ntreasure_count = int(size ** 2 / RATIO_TREASURE)\nif trap_count <= 0:\n raise MapInitError('Error initializing trap count. Try larger map size.')\nif treasure_count < config.PL...
<|body_start_0|> if do_generate: self.game_map = self.generate(size) else: self.game_map = [] <|end_body_0|> <|body_start_1|> trap_count = int(size ** 2 / RATIO_TRAPS) treasure_count = int(size ** 2 / RATIO_TREASURE) if trap_count <= 0: raise ...
DungeonMap
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DungeonMap: def __init__(self, size, do_generate=True): """Class constructor :param size: Generated map size :param do_generate: Whether to initiate map generation""" <|body_0|> def generate(self, size): """Generates map for Dungeon Game :param size: Map square size ...
stack_v2_sparse_classes_75kplus_train_006310
5,735
permissive
[ { "docstring": "Class constructor :param size: Generated map size :param do_generate: Whether to initiate map generation", "name": "__init__", "signature": "def __init__(self, size, do_generate=True)" }, { "docstring": "Generates map for Dungeon Game :param size: Map square size :return: None", ...
6
stack_v2_sparse_classes_30k_train_009444
Implement the Python class `DungeonMap` described below. Class description: Implement the DungeonMap class. Method signatures and docstrings: - def __init__(self, size, do_generate=True): Class constructor :param size: Generated map size :param do_generate: Whether to initiate map generation - def generate(self, size...
Implement the Python class `DungeonMap` described below. Class description: Implement the DungeonMap class. Method signatures and docstrings: - def __init__(self, size, do_generate=True): Class constructor :param size: Generated map size :param do_generate: Whether to initiate map generation - def generate(self, size...
291592e97b6d8fe9f9e6627dc0023875918d3463
<|skeleton|> class DungeonMap: def __init__(self, size, do_generate=True): """Class constructor :param size: Generated map size :param do_generate: Whether to initiate map generation""" <|body_0|> def generate(self, size): """Generates map for Dungeon Game :param size: Map square size ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DungeonMap: def __init__(self, size, do_generate=True): """Class constructor :param size: Generated map size :param do_generate: Whether to initiate map generation""" if do_generate: self.game_map = self.generate(size) else: self.game_map = [] def generate(...
the_stack_v2_python_sparse
Kyrylo_Yeremenko/10/dungeon_game/dungeon_map.py
SmischenkoB/campus_2018_python
train
0
ea7992888df0d561d234ce08e02ecc624e4cdc43
[ "if obj is None:\n return self.readonly_fields\nif not request.user.has_perm('dictionary.publish_gloss'):\n self.readonly_fields += ('publish',)\nreturn self.readonly_fields", "obj.created_by = request.user\nobj.updated_by = request.user\nobj.save()", "if formset.model == Gloss:\n instances = formset.s...
<|body_start_0|> if obj is None: return self.readonly_fields if not request.user.has_perm('dictionary.publish_gloss'): self.readonly_fields += ('publish',) return self.readonly_fields <|end_body_0|> <|body_start_1|> obj.created_by = request.user obj.updat...
GlossAdmin
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GlossAdmin: def get_readonly_fields(self, request, obj=None): """Adds 'published' to 'readonly_fields' if user does not have permission to publish glosses.""" <|body_0|> def save_model(self, request, obj, form, change): """Sets created_by and updated_by as the origin...
stack_v2_sparse_classes_75kplus_train_006311
9,524
permissive
[ { "docstring": "Adds 'published' to 'readonly_fields' if user does not have permission to publish glosses.", "name": "get_readonly_fields", "signature": "def get_readonly_fields(self, request, obj=None)" }, { "docstring": "Sets created_by and updated_by as the original requests user", "name"...
3
null
Implement the Python class `GlossAdmin` described below. Class description: Implement the GlossAdmin class. Method signatures and docstrings: - def get_readonly_fields(self, request, obj=None): Adds 'published' to 'readonly_fields' if user does not have permission to publish glosses. - def save_model(self, request, o...
Implement the Python class `GlossAdmin` described below. Class description: Implement the GlossAdmin class. Method signatures and docstrings: - def get_readonly_fields(self, request, obj=None): Adds 'published' to 'readonly_fields' if user does not have permission to publish glosses. - def save_model(self, request, o...
e92f79d2c6b82fb3d52192ce94b29e1194403fce
<|skeleton|> class GlossAdmin: def get_readonly_fields(self, request, obj=None): """Adds 'published' to 'readonly_fields' if user does not have permission to publish glosses.""" <|body_0|> def save_model(self, request, obj, form, change): """Sets created_by and updated_by as the origin...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class GlossAdmin: def get_readonly_fields(self, request, obj=None): """Adds 'published' to 'readonly_fields' if user does not have permission to publish glosses.""" if obj is None: return self.readonly_fields if not request.user.has_perm('dictionary.publish_gloss'): s...
the_stack_v2_python_sparse
signbank/dictionary/admin.py
Signbank/FinSL-signbank
train
7
13d7bd8999443df2cad1f97c4791fa11130025a7
[ "n = len(nums)\nif n <= 2:\n return n\nslow, fast = (2, 2)\nwhile fast < n:\n if nums[slow - 2] != nums[fast]:\n nums[slow] = nums[fast]\n slow += 1\n fast += 1\nreturn slow", "n = len(nums)\nif n <= 2:\n return n\npos = 1\nfor i in range(1, len(nums) - 1):\n if nums[i - 1] != nums[i ...
<|body_start_0|> n = len(nums) if n <= 2: return n slow, fast = (2, 2) while fast < n: if nums[slow - 2] != nums[fast]: nums[slow] = nums[fast] slow += 1 fast += 1 return slow <|end_body_0|> <|body_start_1|> ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def removeDuplicates1(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> n = len(nums) if n <= 2: ...
stack_v2_sparse_classes_75kplus_train_006312
1,274
no_license
[ { "docstring": ":type nums: List[int] :rtype: int", "name": "removeDuplicates", "signature": "def removeDuplicates(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: int", "name": "removeDuplicates1", "signature": "def removeDuplicates1(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_045772
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicates(self, nums): :type nums: List[int] :rtype: int - def removeDuplicates1(self, nums): :type nums: List[int] :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def removeDuplicates(self, nums): :type nums: List[int] :rtype: int - def removeDuplicates1(self, nums): :type nums: List[int] :rtype: int <|skeleton|> class Solution: def ...
6e18c5d257840489cc3fb1079ae3804c743982a4
<|skeleton|> class Solution: def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" <|body_0|> def removeDuplicates1(self, nums): """:type nums: List[int] :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def removeDuplicates(self, nums): """:type nums: List[int] :rtype: int""" n = len(nums) if n <= 2: return n slow, fast = (2, 2) while fast < n: if nums[slow - 2] != nums[fast]: nums[slow] = nums[fast] slo...
the_stack_v2_python_sparse
out/production/leetcode/80.删除排序数组中的重复项-ii.py
yangyuxiang1996/leetcode
train
0
c3d328f08ba97fc61d46742bd4867cd770a227a1
[ "for index, node in enumerate(self.sortedTree(root)):\n if index + 1 == k:\n return node.val", "if current_node.left:\n for i_node in self.sortedTree(current_node.left):\n yield i_node\nyield current_node\nif current_node.right:\n for i_node in self.sortedTree(current_node.right):\n ...
<|body_start_0|> for index, node in enumerate(self.sortedTree(root)): if index + 1 == k: return node.val <|end_body_0|> <|body_start_1|> if current_node.left: for i_node in self.sortedTree(current_node.left): yield i_node yield current_nod...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def kthSmallest(self, root, k): """:type root: TreeNode :type k: int :rtype: int""" <|body_0|> def sortedTree(self, current_node): """:type current_node: TreeNode :type current_k: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_75kplus_train_006313
1,016
no_license
[ { "docstring": ":type root: TreeNode :type k: int :rtype: int", "name": "kthSmallest", "signature": "def kthSmallest(self, root, k)" }, { "docstring": ":type current_node: TreeNode :type current_k: int :rtype: int", "name": "sortedTree", "signature": "def sortedTree(self, current_node)" ...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kthSmallest(self, root, k): :type root: TreeNode :type k: int :rtype: int - def sortedTree(self, current_node): :type current_node: TreeNode :type current_k: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def kthSmallest(self, root, k): :type root: TreeNode :type k: int :rtype: int - def sortedTree(self, current_node): :type current_node: TreeNode :type current_k: int :rtype: int ...
551d9493ab2183b026f3b9e1687c19edac4b1c70
<|skeleton|> class Solution: def kthSmallest(self, root, k): """:type root: TreeNode :type k: int :rtype: int""" <|body_0|> def sortedTree(self, current_node): """:type current_node: TreeNode :type current_k: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def kthSmallest(self, root, k): """:type root: TreeNode :type k: int :rtype: int""" for index, node in enumerate(self.sortedTree(root)): if index + 1 == k: return node.val def sortedTree(self, current_node): """:type current_node: TreeNode :ty...
the_stack_v2_python_sparse
algorithms/KthSmallestElementinaBST/KthSmallestElementinaBST.py
BartWaaang/leetcode
train
0
5441083d7cd94933695bd99b301dbda2d9ad3ba1
[ "if not a:\n return [-1, -1]\nn = len(a)\nfor i in range(n):\n t = x - a[i]\n j = self.find_target(t, i, n, a)\n if j != 0:\n return [i + 1, j + 1]\nreturn [-1, -1]", "if not a or not n:\n return 0\nl = i + 1\nr = n - 1\nwhile l <= r:\n m = l + (r - l) // 2\n if a[m] == t:\n ret...
<|body_start_0|> if not a: return [-1, -1] n = len(a) for i in range(n): t = x - a[i] j = self.find_target(t, i, n, a) if j != 0: return [i + 1, j + 1] return [-1, -1] <|end_body_0|> <|body_start_1|> if not a or not...
One-pointer with binary search of sorted array. Time complexity: O(n) - Amortized iterate over all elements in array Space complexity: O(1) - Constant pointer evaluation
Solution
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: """One-pointer with binary search of sorted array. Time complexity: O(n) - Amortized iterate over all elements in array Space complexity: O(1) - Constant pointer evaluation""" def two_sum(self, a, x): """Determines indicies of elements whose sum equals target "x". :param li...
stack_v2_sparse_classes_75kplus_train_006314
4,794
permissive
[ { "docstring": "Determines indicies of elements whose sum equals target \"x\". :param list[int] a: sorted array of integers :type int x: target integer sum :return: list of indicies (base index 1) of target values :rtype: list[int]", "name": "two_sum", "signature": "def two_sum(self, a, x)" }, { ...
2
null
Implement the Python class `Solution` described below. Class description: One-pointer with binary search of sorted array. Time complexity: O(n) - Amortized iterate over all elements in array Space complexity: O(1) - Constant pointer evaluation Method signatures and docstrings: - def two_sum(self, a, x): Determines in...
Implement the Python class `Solution` described below. Class description: One-pointer with binary search of sorted array. Time complexity: O(n) - Amortized iterate over all elements in array Space complexity: O(1) - Constant pointer evaluation Method signatures and docstrings: - def two_sum(self, a, x): Determines in...
69f90877c5466927e8b081c4268cbcda074813ec
<|skeleton|> class Solution: """One-pointer with binary search of sorted array. Time complexity: O(n) - Amortized iterate over all elements in array Space complexity: O(1) - Constant pointer evaluation""" def two_sum(self, a, x): """Determines indicies of elements whose sum equals target "x". :param li...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: """One-pointer with binary search of sorted array. Time complexity: O(n) - Amortized iterate over all elements in array Space complexity: O(1) - Constant pointer evaluation""" def two_sum(self, a, x): """Determines indicies of elements whose sum equals target "x". :param list[int] a: so...
the_stack_v2_python_sparse
0167_two_sum_2/python_source.py
arthurdysart/LeetCode
train
0
5aa692bc58b9cfa196cac4928291e2637d996e94
[ "if not nums:\n return 0\nn = len(nums)\npreSum = [0] * (n + 1)\nfor i in range(n):\n preSum[i + 1] = preSum[i] + nums[i]\ncount = 0\nfor i in range(n):\n for j in range(i, n):\n sums = preSum[j + 1] - preSum[i]\n if sums == k:\n count += 1\nreturn count", "if not nums:\n retu...
<|body_start_0|> if not nums: return 0 n = len(nums) preSum = [0] * (n + 1) for i in range(n): preSum[i + 1] = preSum[i] + nums[i] count = 0 for i in range(n): for j in range(i, n): sums = preSum[j + 1] - preSum[i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def subarraySum(self, nums: list, k: int) -> int: """前缀和,然后暴力循环 数据太多超时""" <|body_0|> def subarraySum_2(self, nums: list, k: int) -> int: """优化版 1. 上面的方法中第二个for循环可以不要,它就是在计算某个范围的和而已,可以改成减法来做 2. 前缀和可以不用开辟数组,仅计算当前的和 3. 可以用字典来保存前缀和-k的差值""" <|body_1|> <...
stack_v2_sparse_classes_75kplus_train_006315
1,785
no_license
[ { "docstring": "前缀和,然后暴力循环 数据太多超时", "name": "subarraySum", "signature": "def subarraySum(self, nums: list, k: int) -> int" }, { "docstring": "优化版 1. 上面的方法中第二个for循环可以不要,它就是在计算某个范围的和而已,可以改成减法来做 2. 前缀和可以不用开辟数组,仅计算当前的和 3. 可以用字典来保存前缀和-k的差值", "name": "subarraySum_2", "signature": "def subarray...
2
stack_v2_sparse_classes_30k_test_000524
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarraySum(self, nums: list, k: int) -> int: 前缀和,然后暴力循环 数据太多超时 - def subarraySum_2(self, nums: list, k: int) -> int: 优化版 1. 上面的方法中第二个for循环可以不要,它就是在计算某个范围的和而已,可以改成减法来做 2. 前缀和...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def subarraySum(self, nums: list, k: int) -> int: 前缀和,然后暴力循环 数据太多超时 - def subarraySum_2(self, nums: list, k: int) -> int: 优化版 1. 上面的方法中第二个for循环可以不要,它就是在计算某个范围的和而已,可以改成减法来做 2. 前缀和...
3508e1ce089131b19603c3206aab4cf43023bb19
<|skeleton|> class Solution: def subarraySum(self, nums: list, k: int) -> int: """前缀和,然后暴力循环 数据太多超时""" <|body_0|> def subarraySum_2(self, nums: list, k: int) -> int: """优化版 1. 上面的方法中第二个for循环可以不要,它就是在计算某个范围的和而已,可以改成减法来做 2. 前缀和可以不用开辟数组,仅计算当前的和 3. 可以用字典来保存前缀和-k的差值""" <|body_1|> <...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def subarraySum(self, nums: list, k: int) -> int: """前缀和,然后暴力循环 数据太多超时""" if not nums: return 0 n = len(nums) preSum = [0] * (n + 1) for i in range(n): preSum[i + 1] = preSum[i] + nums[i] count = 0 for i in range(n): ...
the_stack_v2_python_sparse
algorithm/leetcode/list/19-和为K的子数组.py
lxconfig/UbuntuCode_bak
train
0
a636599c27b4a5c39e2dd51a440ba92701cb59ac
[ "super().__init__(grid_points, bin_edges, binned_pdf, normalization)\nif self.grid_dim == 2:\n self.triangulation = Delaunay(self.grid_points)\nelif self.grid_dim > 2:\n raise NotImplementedError('Interpolation in more then two dimension not impemented.')", "target_bin = np.digitize(target_point.squeeze(), ...
<|body_start_0|> super().__init__(grid_points, bin_edges, binned_pdf, normalization) if self.grid_dim == 2: self.triangulation = Delaunay(self.grid_points) elif self.grid_dim > 2: raise NotImplementedError('Interpolation in more then two dimension not impemented.') <|end_...
MomentMorphInterpolator
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MomentMorphInterpolator: def __init__(self, grid_points, bin_edges, binned_pdf, normalization=PDFNormalization.AREA): """Interpolator class using moment morphing. Parameters ---------- grid_points: np.ndarray, shape=(N, ...) Grid points at which interpolation templates exist. May be one ...
stack_v2_sparse_classes_75kplus_train_006316
13,244
permissive
[ { "docstring": "Interpolator class using moment morphing. Parameters ---------- grid_points: np.ndarray, shape=(N, ...) Grid points at which interpolation templates exist. May be one ot two dimensional. bin_edges: np.ndarray, shape=(M+1) Edges of the data binning binned_pdf: np.ndarray, shape=(N, ..., M) Conten...
4
stack_v2_sparse_classes_30k_train_034930
Implement the Python class `MomentMorphInterpolator` described below. Class description: Implement the MomentMorphInterpolator class. Method signatures and docstrings: - def __init__(self, grid_points, bin_edges, binned_pdf, normalization=PDFNormalization.AREA): Interpolator class using moment morphing. Parameters --...
Implement the Python class `MomentMorphInterpolator` described below. Class description: Implement the MomentMorphInterpolator class. Method signatures and docstrings: - def __init__(self, grid_points, bin_edges, binned_pdf, normalization=PDFNormalization.AREA): Interpolator class using moment morphing. Parameters --...
12a609566230d01a68a822aad38f080b60c473ce
<|skeleton|> class MomentMorphInterpolator: def __init__(self, grid_points, bin_edges, binned_pdf, normalization=PDFNormalization.AREA): """Interpolator class using moment morphing. Parameters ---------- grid_points: np.ndarray, shape=(N, ...) Grid points at which interpolation templates exist. May be one ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MomentMorphInterpolator: def __init__(self, grid_points, bin_edges, binned_pdf, normalization=PDFNormalization.AREA): """Interpolator class using moment morphing. Parameters ---------- grid_points: np.ndarray, shape=(N, ...) Grid points at which interpolation templates exist. May be one ot two dimensi...
the_stack_v2_python_sparse
pyirf/interpolation/moment_morph_interpolator.py
cta-observatory/pyirf
train
13
9e5ce91a7e1caca5554100eea65c801108f2ee29
[ "self._root_dir = os.path.abspath(root_dir)\nself._all_components = {}\nself._required_compnames = []\nfor comp in model:\n src = _External(self._root_dir, comp, model[comp])\n self._all_components[comp] = src\n if model[comp][ExternalsDescription.REQUIRED]:\n self._required_compnames.append(comp)",...
<|body_start_0|> self._root_dir = os.path.abspath(root_dir) self._all_components = {} self._required_compnames = [] for comp in model: src = _External(self._root_dir, comp, model[comp]) self._all_components[comp] = src if model[comp][ExternalsDescripti...
SourceTree represents a group of managed externals
SourceTree
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourceTree: """SourceTree represents a group of managed externals""" def __init__(self, root_dir, model): """Build a SourceTree object from a model description""" <|body_0|> def status(self, relative_path_base=LOCAL_PATH_INDICATOR): """Report the status component...
stack_v2_sparse_classes_75kplus_train_006317
12,567
permissive
[ { "docstring": "Build a SourceTree object from a model description", "name": "__init__", "signature": "def __init__(self, root_dir, model)" }, { "docstring": "Report the status components FIXME(bja, 2017-10) what do we do about situations where the user checked out the optional components, but d...
3
stack_v2_sparse_classes_30k_train_041754
Implement the Python class `SourceTree` described below. Class description: SourceTree represents a group of managed externals Method signatures and docstrings: - def __init__(self, root_dir, model): Build a SourceTree object from a model description - def status(self, relative_path_base=LOCAL_PATH_INDICATOR): Report...
Implement the Python class `SourceTree` described below. Class description: SourceTree represents a group of managed externals Method signatures and docstrings: - def __init__(self, root_dir, model): Build a SourceTree object from a model description - def status(self, relative_path_base=LOCAL_PATH_INDICATOR): Report...
a666ac3b58d19f04249f76c9340f2e4a4a27939b
<|skeleton|> class SourceTree: """SourceTree represents a group of managed externals""" def __init__(self, root_dir, model): """Build a SourceTree object from a model description""" <|body_0|> def status(self, relative_path_base=LOCAL_PATH_INDICATOR): """Report the status component...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SourceTree: """SourceTree represents a group of managed externals""" def __init__(self, root_dir, model): """Build a SourceTree object from a model description""" self._root_dir = os.path.abspath(root_dir) self._all_components = {} self._required_compnames = [] for...
the_stack_v2_python_sparse
manage_externals/manic/sourcetree.py
dtcenter/METplus
train
41
2fb0e30ec0fc7a1e902b04d2446ef196685fe3f3
[ "super().__init__(style, cfg)\nif self.animate:\n self.feature_info_label: Optional[str] = None\n self.color_ramp = style.color_ramp\nelse:\n self.feature_info_label = cast(Optional[str], cfg.get('feature_info_label', None))\n self.color_ramp = ColorRamp(style, cfg)", "xformed_data = cast('ColorRampDe...
<|body_start_0|> super().__init__(style, cfg) if self.animate: self.feature_info_label: Optional[str] = None self.color_ramp = style.color_ramp else: self.feature_info_label = cast(Optional[str], cfg.get('feature_info_label', None)) self.color_ramp...
MultiDateHandler base class. Handles "aggregator"-based index-value multi-date requests (e.g. delta)
MultiDateHandler
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiDateHandler: """MultiDateHandler base class. Handles "aggregator"-based index-value multi-date requests (e.g. delta)""" def __init__(self, style: 'ColorRampDef', cfg: CFG_DICT) -> None: """First stage initialisation :param style: The parent style object :param cfg: The multidate...
stack_v2_sparse_classes_75kplus_train_006318
23,941
permissive
[ { "docstring": "First stage initialisation :param style: The parent style object :param cfg: The multidate handler configuration", "name": "__init__", "signature": "def __init__(self, style: 'ColorRampDef', cfg: CFG_DICT) -> None" }, { "docstring": "Apply image transformation :param data: Raw da...
3
stack_v2_sparse_classes_30k_train_022378
Implement the Python class `MultiDateHandler` described below. Class description: MultiDateHandler base class. Handles "aggregator"-based index-value multi-date requests (e.g. delta) Method signatures and docstrings: - def __init__(self, style: 'ColorRampDef', cfg: CFG_DICT) -> None: First stage initialisation :param...
Implement the Python class `MultiDateHandler` described below. Class description: MultiDateHandler base class. Handles "aggregator"-based index-value multi-date requests (e.g. delta) Method signatures and docstrings: - def __init__(self, style: 'ColorRampDef', cfg: CFG_DICT) -> None: First stage initialisation :param...
0ed9b0a39c443cdb1ba54c56eb1ad5caf153ea99
<|skeleton|> class MultiDateHandler: """MultiDateHandler base class. Handles "aggregator"-based index-value multi-date requests (e.g. delta)""" def __init__(self, style: 'ColorRampDef', cfg: CFG_DICT) -> None: """First stage initialisation :param style: The parent style object :param cfg: The multidate...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MultiDateHandler: """MultiDateHandler base class. Handles "aggregator"-based index-value multi-date requests (e.g. delta)""" def __init__(self, style: 'ColorRampDef', cfg: CFG_DICT) -> None: """First stage initialisation :param style: The parent style object :param cfg: The multidate handler conf...
the_stack_v2_python_sparse
datacube_ows/styles/ramp.py
ArpitKubadia/datacube-ows
train
0
f0aa4bfc69acc45a8b8e85f6d857849ca128b455
[ "i = 0\nj = 0\nwhile i < len(nums):\n if nums[i] != 0:\n nums[i], nums[j] = (nums[j], nums[i])\n j += 1\n i += 1", "count_zeroes = 0\nwhile 0 in nums:\n nums.remove(0)\n count_zeroes += 1\nfor i in range(count_zeroes):\n nums.append(0)", "n = len(nums)\nfor i in xrange(n):\n if n...
<|body_start_0|> i = 0 j = 0 while i < len(nums): if nums[i] != 0: nums[i], nums[j] = (nums[j], nums[i]) j += 1 i += 1 <|end_body_0|> <|body_start_1|> count_zeroes = 0 while 0 in nums: nums.remove(0) ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def moveZeroes(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" <|body_0|> def moveZeroes(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" ...
stack_v2_sparse_classes_75kplus_train_006319
1,452
no_license
[ { "docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.", "name": "moveZeroes", "signature": "def moveZeroes(self, nums)" }, { "docstring": ":type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.", "name": "mo...
3
stack_v2_sparse_classes_30k_train_009826
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. - def moveZeroes(self, nums): :type nums: List[int] :rtype: N...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def moveZeroes(self, nums): :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. - def moveZeroes(self, nums): :type nums: List[int] :rtype: N...
5ff31f31b8472373b54c9fd0e02e2be5e69a3dd3
<|skeleton|> class Solution: def moveZeroes(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" <|body_0|> def moveZeroes(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def moveZeroes(self, nums): """:type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.""" i = 0 j = 0 while i < len(nums): if nums[i] != 0: nums[i], nums[j] = (nums[j], nums[i]) j += 1 ...
the_stack_v2_python_sparse
Top-Interview-Questions/Array-Easy-Collection/283-move-zeroes.py
ssong86/leetcode-problem-solving
train
0
c0709c5c31e7f9d512437e0ac0fe066f69e96560
[ "rank = len(X.shape)\nassert rank > 2, 'SampleLayers require rank > 2 input Tensors, with the first axis being the random samples of the net.'\nNet, KL = self._build(X)\nreturn (Net, KL)", "n_samples = tf.to_int32(tf.shape(X)[0])\ninput_shape = X.shape[2:].as_list()\nreturn (n_samples, input_shape)" ]
<|body_start_0|> rank = len(X.shape) assert rank > 2, 'SampleLayers require rank > 2 input Tensors, with the first axis being the random samples of the net.' Net, KL = self._build(X) return (Net, KL) <|end_body_0|> <|body_start_1|> n_samples = tf.to_int32(tf.shape(X)[0]) ...
Sample Layer base class. This is the base class for layers that build upon stochastic (variational) nets. These expect *rank >= 3* input Tensors, where the first dimension indexes the random samples of the stochastic net.
SampleLayer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SampleLayer: """Sample Layer base class. This is the base class for layers that build upon stochastic (variational) nets. These expect *rank >= 3* input Tensors, where the first dimension indexes the random samples of the stochastic net.""" def __call__(self, X): """Construct the sub...
stack_v2_sparse_classes_75kplus_train_006320
43,510
permissive
[ { "docstring": "Construct the subgraph for this layer. Parameters ---------- X : Tensor the input to this layer Returns ------- Net : Tensor the output of this layer KL : float, Tensor the regularizer/Kullback Leibler 'cost' of the parameters in this layer.", "name": "__call__", "signature": "def __call...
2
null
Implement the Python class `SampleLayer` described below. Class description: Sample Layer base class. This is the base class for layers that build upon stochastic (variational) nets. These expect *rank >= 3* input Tensors, where the first dimension indexes the random samples of the stochastic net. Method signatures a...
Implement the Python class `SampleLayer` described below. Class description: Sample Layer base class. This is the base class for layers that build upon stochastic (variational) nets. These expect *rank >= 3* input Tensors, where the first dimension indexes the random samples of the stochastic net. Method signatures a...
53a3de23dce4d607ffec92be936e83d2dd7ebb3c
<|skeleton|> class SampleLayer: """Sample Layer base class. This is the base class for layers that build upon stochastic (variational) nets. These expect *rank >= 3* input Tensors, where the first dimension indexes the random samples of the stochastic net.""" def __call__(self, X): """Construct the sub...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SampleLayer: """Sample Layer base class. This is the base class for layers that build upon stochastic (variational) nets. These expect *rank >= 3* input Tensors, where the first dimension indexes the random samples of the stochastic net.""" def __call__(self, X): """Construct the subgraph for thi...
the_stack_v2_python_sparse
aboleth/layers.py
LaplaceKorea/aboleth
train
0
c328caa15112491d0a840bb65454bd4812540486
[ "super(BasePlusNameSubEnt, self).__init__(config, vocab)\nself.name_model = NameModel(config, vocab)\nself.dim = self.name_model.dim + self.dim\nself.init_e_model()", "fv = []\nfv.extend(self.name_model.emb(entity))\nfv.extend(super().emb(entity))\nreturn fv" ]
<|body_start_0|> super(BasePlusNameSubEnt, self).__init__(config, vocab) self.name_model = NameModel(config, vocab) self.dim = self.name_model.dim + self.dim self.init_e_model() <|end_body_0|> <|body_start_1|> fv = [] fv.extend(self.name_model.emb(entity)) fv.ext...
BasePlusNameSubEnt
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasePlusNameSubEnt: def __init__(self, config, vocab): """A Sub Entity model.""" <|body_0|> def emb(self, entity): """Get all features of entity.""" <|body_1|> <|end_skeleton|> <|body_start_0|> super(BasePlusNameSubEnt, self).__init__(config, vocab)...
stack_v2_sparse_classes_75kplus_train_006321
1,518
permissive
[ { "docstring": "A Sub Entity model.", "name": "__init__", "signature": "def __init__(self, config, vocab)" }, { "docstring": "Get all features of entity.", "name": "emb", "signature": "def emb(self, entity)" } ]
2
stack_v2_sparse_classes_30k_val_000016
Implement the Python class `BasePlusNameSubEnt` described below. Class description: Implement the BasePlusNameSubEnt class. Method signatures and docstrings: - def __init__(self, config, vocab): A Sub Entity model. - def emb(self, entity): Get all features of entity.
Implement the Python class `BasePlusNameSubEnt` described below. Class description: Implement the BasePlusNameSubEnt class. Method signatures and docstrings: - def __init__(self, config, vocab): A Sub Entity model. - def emb(self, entity): Get all features of entity. <|skeleton|> class BasePlusNameSubEnt: def _...
542659170897ad05f7612639cb918886859ae9d6
<|skeleton|> class BasePlusNameSubEnt: def __init__(self, config, vocab): """A Sub Entity model.""" <|body_0|> def emb(self, entity): """Get all features of entity.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class BasePlusNameSubEnt: def __init__(self, config, vocab): """A Sub Entity model.""" super(BasePlusNameSubEnt, self).__init__(config, vocab) self.name_model = NameModel(config, vocab) self.dim = self.name_model.dim + self.dim self.init_e_model() def emb(self, entity): ...
the_stack_v2_python_sparse
src/python/coref/models/entity/BasePlusNameSubEnt.py
nmonath/coref_tools
train
0
d90ae0e31dac304b1612d05a66502d153e4a33a3
[ "favorite_stops = FavoriteStop.objects.filter(owner=self.request.user)\nserializer = FavoriteStopSerializer(favorite_stops, many=True)\nreturn Response(serializer.data)", "try:\n return Stop.objects.get(pk=primary_key)\nexcept Stop.DoesNotExist as stop_not_exist:\n raise Http404(f'Cannot find Stop: {primary...
<|body_start_0|> favorite_stops = FavoriteStop.objects.filter(owner=self.request.user) serializer = FavoriteStopSerializer(favorite_stops, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> try: return Stop.objects.get(pk=primary_key) except ...
Get, Post or Delete a FavoriteStop instance(s) for the currently authenticated user.
FavoriteStopView
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FavoriteStopView: """Get, Post or Delete a FavoriteStop instance(s) for the currently authenticated user.""" def get(self, request): """Return a list of all the FavoriteStops for the currently authenticated user.""" <|body_0|> def get_stop_object(primary_key): ""...
stack_v2_sparse_classes_75kplus_train_006322
31,821
permissive
[ { "docstring": "Return a list of all the FavoriteStops for the currently authenticated user.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Return the Stop object for the currently authenticated user.", "name": "get_stop_object", "signature": "def get_stop_obje...
5
null
Implement the Python class `FavoriteStopView` described below. Class description: Get, Post or Delete a FavoriteStop instance(s) for the currently authenticated user. Method signatures and docstrings: - def get(self, request): Return a list of all the FavoriteStops for the currently authenticated user. - def get_stop...
Implement the Python class `FavoriteStopView` described below. Class description: Get, Post or Delete a FavoriteStop instance(s) for the currently authenticated user. Method signatures and docstrings: - def get(self, request): Return a list of all the FavoriteStops for the currently authenticated user. - def get_stop...
35955cd9166b086f59157d23ed05a8ffcf82b617
<|skeleton|> class FavoriteStopView: """Get, Post or Delete a FavoriteStop instance(s) for the currently authenticated user.""" def get(self, request): """Return a list of all the FavoriteStops for the currently authenticated user.""" <|body_0|> def get_stop_object(primary_key): ""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FavoriteStopView: """Get, Post or Delete a FavoriteStop instance(s) for the currently authenticated user.""" def get(self, request): """Return a list of all the FavoriteStops for the currently authenticated user.""" favorite_stops = FavoriteStop.objects.filter(owner=self.request.user) ...
the_stack_v2_python_sparse
backend/dublinbus/views.py
Botazio/UCD-DublinBus
train
5
c4c48e461c839fb3c5470bd9da3f6610d86c2d66
[ "if len(nums) == 1:\n return 0\nreturn self.jumphelpter(nums, 0)", "jump_range = nums[cur_idx]\nif cur_idx + jump_range >= len(nums) - 1:\n return count + 1\nelse:\n best_next_idx, best_reach = (cur_idx, 0)\n for jump_distance in range(1, jump_range + 1):\n can_reach = jump_distance + nums[cur_...
<|body_start_0|> if len(nums) == 1: return 0 return self.jumphelpter(nums, 0) <|end_body_0|> <|body_start_1|> jump_range = nums[cur_idx] if cur_idx + jump_range >= len(nums) - 1: return count + 1 else: best_next_idx, best_reach = (cur_idx, 0) ...
Solution_C
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution_C: def jump(self, nums: List[int]) -> int: """Recursion method, just to practice recursion Very similar idea to Solution B, but slower as it is Recursive.""" <|body_0|> def jumphelpter(self, nums: List[int], cur_idx: int, count: int=0) -> int: """Helper C2""...
stack_v2_sparse_classes_75kplus_train_006323
4,925
permissive
[ { "docstring": "Recursion method, just to practice recursion Very similar idea to Solution B, but slower as it is Recursive.", "name": "jump", "signature": "def jump(self, nums: List[int]) -> int" }, { "docstring": "Helper C2", "name": "jumphelpter", "signature": "def jumphelpter(self, n...
2
null
Implement the Python class `Solution_C` described below. Class description: Implement the Solution_C class. Method signatures and docstrings: - def jump(self, nums: List[int]) -> int: Recursion method, just to practice recursion Very similar idea to Solution B, but slower as it is Recursive. - def jumphelpter(self, n...
Implement the Python class `Solution_C` described below. Class description: Implement the Solution_C class. Method signatures and docstrings: - def jump(self, nums: List[int]) -> int: Recursion method, just to practice recursion Very similar idea to Solution B, but slower as it is Recursive. - def jumphelpter(self, n...
143422321cbc3715ca08f6c3af8f960a55887ced
<|skeleton|> class Solution_C: def jump(self, nums: List[int]) -> int: """Recursion method, just to practice recursion Very similar idea to Solution B, but slower as it is Recursive.""" <|body_0|> def jumphelpter(self, nums: List[int], cur_idx: int, count: int=0) -> int: """Helper C2""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution_C: def jump(self, nums: List[int]) -> int: """Recursion method, just to practice recursion Very similar idea to Solution B, but slower as it is Recursive.""" if len(nums) == 1: return 0 return self.jumphelpter(nums, 0) def jumphelpter(self, nums: List[int], cu...
the_stack_v2_python_sparse
LeetCode/LC045_jump_game_ii.py
jxie0755/Learning_Python
train
0
a6d89cbb204f433f96c21d0c2e5e697a0c6f4a69
[ "super(ImuSensor, self).__init__(carla_actor=carla_actor, parent=parent, node=node, synchronous_mode=synchronous_mode, prefix='imu/' + carla_actor.attributes.get('role_name'))\nself.imu_publisher = rospy.Publisher(self.get_topic_prefix(), Imu, queue_size=10)\nself.listen()", "imu_msg = Imu()\nimu_msg.header = sel...
<|body_start_0|> super(ImuSensor, self).__init__(carla_actor=carla_actor, parent=parent, node=node, synchronous_mode=synchronous_mode, prefix='imu/' + carla_actor.attributes.get('role_name')) self.imu_publisher = rospy.Publisher(self.get_topic_prefix(), Imu, queue_size=10) self.listen() <|end_bo...
Actor implementation details for imu sensor
ImuSensor
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImuSensor: """Actor implementation details for imu sensor""" def __init__(self, carla_actor, parent, node, synchronous_mode): """Constructor :param carla_actor : carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent ...
stack_v2_sparse_classes_75kplus_train_006324
2,690
permissive
[ { "docstring": "Constructor :param carla_actor : carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param node: node-handle :type node: carla_ros_bridge.CarlaRosBridge :param synchronous_mode: use in synchronous mode? :type synchronous_mode...
2
null
Implement the Python class `ImuSensor` described below. Class description: Actor implementation details for imu sensor Method signatures and docstrings: - def __init__(self, carla_actor, parent, node, synchronous_mode): Constructor :param carla_actor : carla actor object :type carla_actor: carla.Actor :param parent: ...
Implement the Python class `ImuSensor` described below. Class description: Actor implementation details for imu sensor Method signatures and docstrings: - def __init__(self, carla_actor, parent, node, synchronous_mode): Constructor :param carla_actor : carla actor object :type carla_actor: carla.Actor :param parent: ...
65ba2fdb2ca24907083bc277ec333294ab174fa6
<|skeleton|> class ImuSensor: """Actor implementation details for imu sensor""" def __init__(self, carla_actor, parent, node, synchronous_mode): """Constructor :param carla_actor : carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ImuSensor: """Actor implementation details for imu sensor""" def __init__(self, carla_actor, parent, node, synchronous_mode): """Constructor :param carla_actor : carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param node: ...
the_stack_v2_python_sparse
ros/ros-bridge/carla_ros_bridge/src/carla_ros_bridge/imu.py
Essentia-Laboratory/intelligent-embedded-systems
train
3
76f2bf759843f38b288c9fbff97f11b812306107
[ "policy.authorize(pecan.request.context, 'report:list_tenants', {})\nif not begin:\n begin = ck_utils.get_month_start()\nif not end:\n end = ck_utils.get_next_month()\nstorage = pecan.request.storage_backend\ntenants = storage.get_tenants(begin, end)\nreturn tenants", "LOG.warning('/v1/report/total is depre...
<|body_start_0|> policy.authorize(pecan.request.context, 'report:list_tenants', {}) if not begin: begin = ck_utils.get_month_start() if not end: end = ck_utils.get_next_month() storage = pecan.request.storage_backend tenants = storage.get_tenants(begin, en...
REST Controller managing the reporting.
ReportController
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ReportController: """REST Controller managing the reporting.""" def tenants(self, begin=None, end=None): """Return the list of rated tenants.""" <|body_0|> def total(self, begin=None, end=None, tenant_id=None, service=None, all_tenants=False): """Return the amoun...
stack_v2_sparse_classes_75kplus_train_006325
5,763
permissive
[ { "docstring": "Return the list of rated tenants.", "name": "tenants", "signature": "def tenants(self, begin=None, end=None)" }, { "docstring": "Return the amount to pay for a given period.", "name": "total", "signature": "def total(self, begin=None, end=None, tenant_id=None, service=Non...
3
null
Implement the Python class `ReportController` described below. Class description: REST Controller managing the reporting. Method signatures and docstrings: - def tenants(self, begin=None, end=None): Return the list of rated tenants. - def total(self, begin=None, end=None, tenant_id=None, service=None, all_tenants=Fal...
Implement the Python class `ReportController` described below. Class description: REST Controller managing the reporting. Method signatures and docstrings: - def tenants(self, begin=None, end=None): Return the list of rated tenants. - def total(self, begin=None, end=None, tenant_id=None, service=None, all_tenants=Fal...
94630b97cd1fb4bdd9a638070ffbbe3625de8aa2
<|skeleton|> class ReportController: """REST Controller managing the reporting.""" def tenants(self, begin=None, end=None): """Return the list of rated tenants.""" <|body_0|> def total(self, begin=None, end=None, tenant_id=None, service=None, all_tenants=False): """Return the amoun...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ReportController: """REST Controller managing the reporting.""" def tenants(self, begin=None, end=None): """Return the list of rated tenants.""" policy.authorize(pecan.request.context, 'report:list_tenants', {}) if not begin: begin = ck_utils.get_month_start() ...
the_stack_v2_python_sparse
cloudkitty/api/v1/controllers/report.py
openstack/cloudkitty
train
103
6eb0e3c82c02edc76a91e724b1389aff8f84f610
[ "title = request.data.get('title', '')\nplugin = request.data.get('plugin', '')\ncondition = unquote(request.data.get('condition', ''))\nplan = request.data.get('plan', 0)\nids = request.data.get('ids', '')\nisupdate = request.data.get('isupdate', '0')\nconn = mongo.MongoConn()\nif plugin:\n targets = []\n fo...
<|body_start_0|> title = request.data.get('title', '') plugin = request.data.get('plugin', '') condition = unquote(request.data.get('condition', '')) plan = request.data.get('plan', 0) ids = request.data.get('ids', '') isupdate = request.data.get('isupdate', '0') ...
任务
TaskView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TaskView: """任务""" def post(self, request): """添加任务""" <|body_0|> def delete(self, request, id=None): """删除任务""" <|body_1|> <|end_skeleton|> <|body_start_0|> title = request.data.get('title', '') plugin = request.data.get('plugin', '') ...
stack_v2_sparse_classes_75kplus_train_006326
9,175
no_license
[ { "docstring": "添加任务", "name": "post", "signature": "def post(self, request)" }, { "docstring": "删除任务", "name": "delete", "signature": "def delete(self, request, id=None)" } ]
2
stack_v2_sparse_classes_30k_test_001395
Implement the Python class `TaskView` described below. Class description: 任务 Method signatures and docstrings: - def post(self, request): 添加任务 - def delete(self, request, id=None): 删除任务
Implement the Python class `TaskView` described below. Class description: 任务 Method signatures and docstrings: - def post(self, request): 添加任务 - def delete(self, request, id=None): 删除任务 <|skeleton|> class TaskView: """任务""" def post(self, request): """添加任务""" <|body_0|> def delete(self,...
d6e025d7e9d9e3aecfd399c77f376130edd8a2df
<|skeleton|> class TaskView: """任务""" def post(self, request): """添加任务""" <|body_0|> def delete(self, request, id=None): """删除任务""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TaskView: """任务""" def post(self, request): """添加任务""" title = request.data.get('title', '') plugin = request.data.get('plugin', '') condition = unquote(request.data.get('condition', '')) plan = request.data.get('plan', 0) ids = request.data.get('ids', '') ...
the_stack_v2_python_sparse
soc_scan/views/task.py
sundw2015/841
train
4
2041332a0f1742277b66f1f4e68a27a8f25a24f1
[ "super(QActionButtons, self).__init__()\nself.layout = QtGui.QHBoxLayout(self)\nqthelpers.clean_layouts(self.layout)\nparent.addWidget(self)", "_button = QtGui.QPushButton(name)\n_button.clicked.connect(action)\nself.layout.addWidget(_button)" ]
<|body_start_0|> super(QActionButtons, self).__init__() self.layout = QtGui.QHBoxLayout(self) qthelpers.clean_layouts(self.layout) parent.addWidget(self) <|end_body_0|> <|body_start_1|> _button = QtGui.QPushButton(name) _button.clicked.connect(action) self.layout...
QWidget with a hbox layout for action buttons.
QActionButtons
[ "CC0-1.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QActionButtons: """QWidget with a hbox layout for action buttons.""" def __init__(self, parent=None): """Initialise the widget. Create the layout.""" <|body_0|> def add_button(self, name, action): """Add a QPushButton object to the layout. Args: name (str): Name/...
stack_v2_sparse_classes_75kplus_train_006327
874
permissive
[ { "docstring": "Initialise the widget. Create the layout.", "name": "__init__", "signature": "def __init__(self, parent=None)" }, { "docstring": "Add a QPushButton object to the layout. Args: name (str): Name/label to add to the button. action (object): function call to add to button.", "nam...
2
null
Implement the Python class `QActionButtons` described below. Class description: QWidget with a hbox layout for action buttons. Method signatures and docstrings: - def __init__(self, parent=None): Initialise the widget. Create the layout. - def add_button(self, name, action): Add a QPushButton object to the layout. Ar...
Implement the Python class `QActionButtons` described below. Class description: QWidget with a hbox layout for action buttons. Method signatures and docstrings: - def __init__(self, parent=None): Initialise the widget. Create the layout. - def add_button(self, name, action): Add a QPushButton object to the layout. Ar...
16ce73bd8e9da0a3ba2b6ce93aff660458edf789
<|skeleton|> class QActionButtons: """QWidget with a hbox layout for action buttons.""" def __init__(self, parent=None): """Initialise the widget. Create the layout.""" <|body_0|> def add_button(self, name, action): """Add a QPushButton object to the layout. Args: name (str): Name/...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QActionButtons: """QWidget with a hbox layout for action buttons.""" def __init__(self, parent=None): """Initialise the widget. Create the layout.""" super(QActionButtons, self).__init__() self.layout = QtGui.QHBoxLayout(self) qthelpers.clean_layouts(self.layout) p...
the_stack_v2_python_sparse
assetbox/ui/panels/action_buttons.py
mlvfx/vfxAssetBox
train
2
ba3fe3891cfaab36da0bf47caaf39ff4a5bf5e1f
[ "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.
SynchronizationServicer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SynchronizationServicer: """Missing associated documentation comment in .proto file.""" def BlockFrom(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def BlockTo(self, request, context): """Missing associated doc...
stack_v2_sparse_classes_75kplus_train_006328
24,581
no_license
[ { "docstring": "Missing associated documentation comment in .proto file.", "name": "BlockFrom", "signature": "def BlockFrom(self, request, context)" }, { "docstring": "Missing associated documentation comment in .proto file.", "name": "BlockTo", "signature": "def BlockTo(self, request, c...
5
stack_v2_sparse_classes_30k_train_051596
Implement the Python class `SynchronizationServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def BlockFrom(self, request, context): Missing associated documentation comment in .proto file. - def BlockTo(self, request, context): M...
Implement the Python class `SynchronizationServicer` described below. Class description: Missing associated documentation comment in .proto file. Method signatures and docstrings: - def BlockFrom(self, request, context): Missing associated documentation comment in .proto file. - def BlockTo(self, request, context): M...
345bf7df822c4ae5cd9988ffdedae2fa5c1ffd99
<|skeleton|> class SynchronizationServicer: """Missing associated documentation comment in .proto file.""" def BlockFrom(self, request, context): """Missing associated documentation comment in .proto file.""" <|body_0|> def BlockTo(self, request, context): """Missing associated doc...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SynchronizationServicer: """Missing associated documentation comment in .proto file.""" def BlockFrom(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
grpc_pb2_grpc.py
isSPDL/SPDL
train
3
6624fd84c6b1f5e0132a61e1bef7c09ccec13819
[ "def send_machine_event(*args, **kwargs):\n self.fail('send_machine_event called')\nself.mock(metadata.metrics, 'send_machine_event', send_machine_event)\nkey = ndb.Key(models.Instance, 'fake-key')\nmetadata.compress(key)\nself.failIf(key.get())", "def send_machine_event(*args, **kwargs):\n self.fail('send_...
<|body_start_0|> def send_machine_event(*args, **kwargs): self.fail('send_machine_event called') self.mock(metadata.metrics, 'send_machine_event', send_machine_event) key = ndb.Key(models.Instance, 'fake-key') metadata.compress(key) self.failIf(key.get()) <|end_body_0...
Tests for metadata.compress.
CompressTest
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompressTest: """Tests for metadata.compress.""" def test_not_found(self): """Ensures nothing happens when the entity doesn't exist.""" <|body_0|> def test_active_metadata_update(self): """Ensures nothing happens when a metadata update is already active.""" ...
stack_v2_sparse_classes_75kplus_train_006329
29,404
permissive
[ { "docstring": "Ensures nothing happens when the entity doesn't exist.", "name": "test_not_found", "signature": "def test_not_found(self)" }, { "docstring": "Ensures nothing happens when a metadata update is already active.", "name": "test_active_metadata_update", "signature": "def test_...
4
null
Implement the Python class `CompressTest` described below. Class description: Tests for metadata.compress. Method signatures and docstrings: - def test_not_found(self): Ensures nothing happens when the entity doesn't exist. - def test_active_metadata_update(self): Ensures nothing happens when a metadata update is alr...
Implement the Python class `CompressTest` described below. Class description: Tests for metadata.compress. Method signatures and docstrings: - def test_not_found(self): Ensures nothing happens when the entity doesn't exist. - def test_active_metadata_update(self): Ensures nothing happens when a metadata update is alr...
3fa4c520dddd82ed190152709e0a54b35faa3bae
<|skeleton|> class CompressTest: """Tests for metadata.compress.""" def test_not_found(self): """Ensures nothing happens when the entity doesn't exist.""" <|body_0|> def test_active_metadata_update(self): """Ensures nothing happens when a metadata update is already active.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CompressTest: """Tests for metadata.compress.""" def test_not_found(self): """Ensures nothing happens when the entity doesn't exist.""" def send_machine_event(*args, **kwargs): self.fail('send_machine_event called') self.mock(metadata.metrics, 'send_machine_event', sen...
the_stack_v2_python_sparse
appengine/gce-backend/metadata_test.py
Slayo2008/New2
train
1
443bfe1ec50d3f2c05337cf14b0f3f0e87af057d
[ "super(MockBlog, self).__init__()\nself.name = blog_name\nself.title = blog_title\nself.is_nsfw = is_nsfw\nself.posts = []", "post = {}\npost['title'] = title\npost['body'] = body\nif timestamp is None:\n post['timestamp'] = (datetime.now() - datetime.fromtimestamp(0)).total_seconds()\nelse:\n post['timesta...
<|body_start_0|> super(MockBlog, self).__init__() self.name = blog_name self.title = blog_title self.is_nsfw = is_nsfw self.posts = [] <|end_body_0|> <|body_start_1|> post = {} post['title'] = title post['body'] = body if timestamp is None: ...
A fake Tumblr blog to be retrieved by the mock client.
MockBlog
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MockBlog: """A fake Tumblr blog to be retrieved by the mock client.""" def __init__(self, blog_name, blog_title, is_nsfw): """Create a new mock blog. Args: blog_name: The short name of the blog (string, no spaces). blog_title: The blog title (string, spaces OK). is_nsfw: Boolean.""" ...
stack_v2_sparse_classes_75kplus_train_006330
15,259
permissive
[ { "docstring": "Create a new mock blog. Args: blog_name: The short name of the blog (string, no spaces). blog_title: The blog title (string, spaces OK). is_nsfw: Boolean.", "name": "__init__", "signature": "def __init__(self, blog_name, blog_title, is_nsfw)" }, { "docstring": "Add a post to the ...
2
stack_v2_sparse_classes_30k_train_025616
Implement the Python class `MockBlog` described below. Class description: A fake Tumblr blog to be retrieved by the mock client. Method signatures and docstrings: - def __init__(self, blog_name, blog_title, is_nsfw): Create a new mock blog. Args: blog_name: The short name of the blog (string, no spaces). blog_title: ...
Implement the Python class `MockBlog` described below. Class description: A fake Tumblr blog to be retrieved by the mock client. Method signatures and docstrings: - def __init__(self, blog_name, blog_title, is_nsfw): Create a new mock blog. Args: blog_name: The short name of the blog (string, no spaces). blog_title: ...
5440b3a67b9f3bbaf61d019644286d152ba96d4f
<|skeleton|> class MockBlog: """A fake Tumblr blog to be retrieved by the mock client.""" def __init__(self, blog_name, blog_title, is_nsfw): """Create a new mock blog. Args: blog_name: The short name of the blog (string, no spaces). blog_title: The blog title (string, spaces OK). is_nsfw: Boolean.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MockBlog: """A fake Tumblr blog to be retrieved by the mock client.""" def __init__(self, blog_name, blog_title, is_nsfw): """Create a new mock blog. Args: blog_name: The short name of the blog (string, no spaces). blog_title: The blog title (string, spaces OK). is_nsfw: Boolean.""" super...
the_stack_v2_python_sparse
scrapers/tumblr/tests.py
NovelTorpedo/noveltorpedo
train
2
e1f7878ff1c5348c87c88182291ae1609077c028
[ "self.id = cnt\nself.addr = addr\nself.msg_cnt = 0", "self.msg_cnt += 1\nnonce = msg[:16]\nsalt = msg[16:32]\ntag = msg[32:48]\nciphertext = msg[48:]\nkey = passwd(salt)\ncipher = AES.new(key, AES.MODE_EAX, nonce=nonce)\nplaintext = cipher.decrypt(ciphertext)\ntry:\n cipher.verify(tag)\n print('%d : %r' % (...
<|body_start_0|> self.id = cnt self.addr = addr self.msg_cnt = 0 <|end_body_0|> <|body_start_1|> self.msg_cnt += 1 nonce = msg[:16] salt = msg[16:32] tag = msg[32:48] ciphertext = msg[48:] key = passwd(salt) cipher = AES.new(key, AES.MODE_...
Classe que implementa a funcionalidade do SERVIDOR.
ServerWorker
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ServerWorker: """Classe que implementa a funcionalidade do SERVIDOR.""" def __init__(self, cnt, addr=None): """Construtor da classe.""" <|body_0|> def process(self, msg): """Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a mensagem a transmiti...
stack_v2_sparse_classes_75kplus_train_006331
3,460
no_license
[ { "docstring": "Construtor da classe.", "name": "__init__", "signature": "def __init__(self, cnt, addr=None)" }, { "docstring": "Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação)", "name": "process", "...
2
null
Implement the Python class `ServerWorker` described below. Class description: Classe que implementa a funcionalidade do SERVIDOR. Method signatures and docstrings: - def __init__(self, cnt, addr=None): Construtor da classe. - def process(self, msg): Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a...
Implement the Python class `ServerWorker` described below. Class description: Classe que implementa a funcionalidade do SERVIDOR. Method signatures and docstrings: - def __init__(self, cnt, addr=None): Construtor da classe. - def process(self, msg): Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a...
218843525a9482e878bb435606314340b4fb3c75
<|skeleton|> class ServerWorker: """Classe que implementa a funcionalidade do SERVIDOR.""" def __init__(self, cnt, addr=None): """Construtor da classe.""" <|body_0|> def process(self, msg): """Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a mensagem a transmiti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ServerWorker: """Classe que implementa a funcionalidade do SERVIDOR.""" def __init__(self, cnt, addr=None): """Construtor da classe.""" self.id = cnt self.addr = addr self.msg_cnt = 0 def process(self, msg): """Processa uma mensagem (`bytestring`) enviada pelo...
the_stack_v2_python_sparse
Guioes/G5/EAX_mode/Server.py
CarlaCruz146/TC
train
0
90b61c67022ddea582804ac8952d825dac68f539
[ "need_params = ['device_id', 'device_owner', 'tenant_id', 'network_id']\nfilters, kwargs = rest_utils.parse_filters_kwargs(request, need_params)\nif not kwargs.get('tenant_id'):\n kwargs.update({'tenant_id': request.user.tenant_id})\nnetwork_list = api.neutron.network_list_for_tenant(request, kwargs.get('tenant_...
<|body_start_0|> need_params = ['device_id', 'device_owner', 'tenant_id', 'network_id'] filters, kwargs = rest_utils.parse_filters_kwargs(request, need_params) if not kwargs.get('tenant_id'): kwargs.update({'tenant_id': request.user.tenant_id}) network_list = api.neutron.netw...
API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports
Ports
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Ports: """API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports""" def get(self, request): """Get a list of unused free ports The listing result is an object with property "items". Each item is a port.""" <|body_0|> def post(self, request)...
stack_v2_sparse_classes_75kplus_train_006332
30,067
permissive
[ { "docstring": "Get a list of unused free ports The listing result is an object with property \"items\". Each item is a port.", "name": "get", "signature": "def get(self, request)" }, { "docstring": "Create a port on a specified network. :param network_id: network id a subnet is created on :para...
2
stack_v2_sparse_classes_30k_train_043364
Implement the Python class `Ports` described below. Class description: API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports Method signatures and docstrings: - def get(self, request): Get a list of unused free ports The listing result is an object with property "items". Each item is a...
Implement the Python class `Ports` described below. Class description: API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports Method signatures and docstrings: - def get(self, request): Get a list of unused free ports The listing result is an object with property "items". Each item is a...
9524f1952461c83db485d5d1702c350b158d7ce0
<|skeleton|> class Ports: """API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports""" def get(self, request): """Get a list of unused free ports The listing result is an object with property "items". Each item is a port.""" <|body_0|> def post(self, request)...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Ports: """API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports""" def get(self, request): """Get a list of unused free ports The listing result is an object with property "items". Each item is a port.""" need_params = ['device_id', 'device_owner', 'tenant_...
the_stack_v2_python_sparse
easystack_dashboard/api/rest/neutron.py
oksbsb/horizon-acc
train
0
6ab31a74b77a2701a335022fb9eeb21d7c1b64ec
[ "self.name = name\nself.private = private\nself.member = member", "member = self.member\nmember.instance = instance\ntry:\n if member.mapper is not None:\n value = member.premap(value)\n value = member.transform(value)\nfinally:\n member.instance = None\nself.private.values[self.name] = value", ...
<|body_start_0|> self.name = name self.private = private self.member = member <|end_body_0|> <|body_start_1|> member = self.member member.instance = instance try: if member.mapper is not None: value = member.premap(value) value = m...
Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`
Descriptor
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Descriptor: """Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`""" def __init__(self, name, private, member): """I...
stack_v2_sparse_classes_75kplus_train_006333
22,737
permissive
[ { "docstring": "Initialization :Parameters: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`", "name": "__init__", "signature": "def __init__(self, name, private, member)"...
4
stack_v2_sparse_classes_30k_train_047034
Implement the Python class `Descriptor` described below. Class description: Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member` Method signatures and d...
Implement the Python class `Descriptor` described below. Class description: Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member` Method signatures and d...
faecefdabd8fbf6d40738a24004772020c244f64
<|skeleton|> class Descriptor: """Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`""" def __init__(self, name, private, member): """I...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Descriptor: """Member descriptor class :IVariables: - `name`: The name of the member - `private`: The private data container - `member`: The actual member instance :Types: - `name`: ``str`` - `private`: `Private` - `member`: `Member`""" def __init__(self, name, private, member): """Initialization...
the_stack_v2_python_sparse
src/lib/svnmailer/settings/_typedstruct.py
m-tmatma/svnmailer
train
1
8dff1b8ab2c829c3c23887c2ff4dc64871dc52de
[ "super().__init__(players, game)\nself.index = 0\nself.groups = []\nself.split()\nfor i in range(1, len(self.groups)):\n self.groups[i].stopMoving()", "if self.groups[self.index].atGoal():\n self.groups[self.index].stopMoving()\n self.index += 1\n if self.index == len(self.groups):\n return Non...
<|body_start_0|> super().__init__(players, game) self.index = 0 self.groups = [] self.split() for i in range(1, len(self.groups)): self.groups[i].stopMoving() <|end_body_0|> <|body_start_1|> if self.groups[self.index].atGoal(): self.groups[self.in...
Class that represents Cooperative Basic Strategy
CoopBaseStrategy
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CoopBaseStrategy: """Class that represents Cooperative Basic Strategy""" def __init__(self, players, game): """:param players: :param game:""" <|body_0|> def nextIteration(self): """returns the next move of all players only one group can move at a time :return: l...
stack_v2_sparse_classes_75kplus_train_006334
2,093
no_license
[ { "docstring": ":param players: :param game:", "name": "__init__", "signature": "def __init__(self, players, game)" }, { "docstring": "returns the next move of all players only one group can move at a time :return: list of lists the next move of all players", "name": "nextIteration", "si...
3
stack_v2_sparse_classes_30k_train_007777
Implement the Python class `CoopBaseStrategy` described below. Class description: Class that represents Cooperative Basic Strategy Method signatures and docstrings: - def __init__(self, players, game): :param players: :param game: - def nextIteration(self): returns the next move of all players only one group can move...
Implement the Python class `CoopBaseStrategy` described below. Class description: Class that represents Cooperative Basic Strategy Method signatures and docstrings: - def __init__(self, players, game): :param players: :param game: - def nextIteration(self): returns the next move of all players only one group can move...
517507199d8be81b095eacb96ac1ec89de8a412e
<|skeleton|> class CoopBaseStrategy: """Class that represents Cooperative Basic Strategy""" def __init__(self, players, game): """:param players: :param game:""" <|body_0|> def nextIteration(self): """returns the next move of all players only one group can move at a time :return: l...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CoopBaseStrategy: """Class that represents Cooperative Basic Strategy""" def __init__(self, players, game): """:param players: :param game:""" super().__init__(players, game) self.index = 0 self.groups = [] self.split() for i in range(1, len(self.groups)): ...
the_stack_v2_python_sparse
projet/coopBaseStrategy.py
su-3i025-projet/coop-pathfinding-nassims
train
0
4f09ce28c4d0feab9fd25fa65715d381b7d6e7bd
[ "super().__init__(prefix)\ndefault_preprocessing_params = {'force_dimension_reduction': True}\ndefault_model_params = {'type_problem': 'regression', 'interface': 'autograd'}\ndefault_postprocessing_params = dict()\nif preprocessing_params:\n preprocessing_params = {**default_preprocessing_params, **preprocessing...
<|body_start_0|> super().__init__(prefix) default_preprocessing_params = {'force_dimension_reduction': True} default_model_params = {'type_problem': 'regression', 'interface': 'autograd'} default_postprocessing_params = dict() if preprocessing_params: preprocessing_pa...
Regression Application. Attributes: model: (QuantumNeuralNetwork):model to be trained to solve the application preprocessor (Preprocessor):preprocessor to be used to solve the application postprocessor (Postprocessor):postprocessor to be used to solve the application
RegressionApplication
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegressionApplication: """Regression Application. Attributes: model: (QuantumNeuralNetwork):model to be trained to solve the application preprocessor (Preprocessor):preprocessor to be used to solve the application postprocessor (Postprocessor):postprocessor to be used to solve the application""" ...
stack_v2_sparse_classes_75kplus_train_006335
4,146
permissive
[ { "docstring": "constructor", "name": "__init__", "signature": "def __init__(self, prefix='qnn', preprocessing_params=None, model_params=None, postprocessing_params=None)" }, { "docstring": "build the application according to dataset characteristics", "name": "build", "signature": "def b...
3
null
Implement the Python class `RegressionApplication` described below. Class description: Regression Application. Attributes: model: (QuantumNeuralNetwork):model to be trained to solve the application preprocessor (Preprocessor):preprocessor to be used to solve the application postprocessor (Postprocessor):postprocessor ...
Implement the Python class `RegressionApplication` described below. Class description: Regression Application. Attributes: model: (QuantumNeuralNetwork):model to be trained to solve the application preprocessor (Preprocessor):preprocessor to be used to solve the application postprocessor (Postprocessor):postprocessor ...
93287afa48486ccfaf175bf9449fd507d99759c0
<|skeleton|> class RegressionApplication: """Regression Application. Attributes: model: (QuantumNeuralNetwork):model to be trained to solve the application preprocessor (Preprocessor):preprocessor to be used to solve the application postprocessor (Postprocessor):postprocessor to be used to solve the application""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegressionApplication: """Regression Application. Attributes: model: (QuantumNeuralNetwork):model to be trained to solve the application preprocessor (Preprocessor):preprocessor to be used to solve the application postprocessor (Postprocessor):postprocessor to be used to solve the application""" def __in...
the_stack_v2_python_sparse
prevision_quantum_nn/applications/regression_application.py
tfqKR/prevision-quantum
train
0
3264e5d4965df0bc6b9f3c6912682c18039aac13
[ "super(WinRegistryParser, self).__init__()\nself._plugins = WinRegistryParser.GetPluginObjects()\nfor list_index, plugin_object in enumerate(self._plugins):\n if plugin_object.NAME == u'winreg_default':\n self._default_plugin = self._plugins.pop(list_index)\n break", "for filter_object in plugin_...
<|body_start_0|> super(WinRegistryParser, self).__init__() self._plugins = WinRegistryParser.GetPluginObjects() for list_index, plugin_object in enumerate(self._plugins): if plugin_object.NAME == u'winreg_default': self._default_plugin = self._plugins.pop(list_index) ...
Parses Windows NT Registry (REGF) files.
WinRegistryParser
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WinRegistryParser: """Parses Windows NT Registry (REGF) files.""" def __init__(self): """Initializes a parser object.""" <|body_0|> def _CanProcessKeyWithPlugin(self, registry_key, plugin_object): """Determines if a plugin can process a Windows Registry key or it...
stack_v2_sparse_classes_75kplus_train_006336
5,265
permissive
[ { "docstring": "Initializes a parser object.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Determines if a plugin can process a Windows Registry key or its values. Args: registry_key: a Windows Registry key (instance of dfwinreg.WinRegistryKey). plugin_object: a Wind...
6
stack_v2_sparse_classes_30k_train_009110
Implement the Python class `WinRegistryParser` described below. Class description: Parses Windows NT Registry (REGF) files. Method signatures and docstrings: - def __init__(self): Initializes a parser object. - def _CanProcessKeyWithPlugin(self, registry_key, plugin_object): Determines if a plugin can process a Windo...
Implement the Python class `WinRegistryParser` described below. Class description: Parses Windows NT Registry (REGF) files. Method signatures and docstrings: - def __init__(self): Initializes a parser object. - def _CanProcessKeyWithPlugin(self, registry_key, plugin_object): Determines if a plugin can process a Windo...
923797fc00664fa9e3277781b0334d6eed5664fd
<|skeleton|> class WinRegistryParser: """Parses Windows NT Registry (REGF) files.""" def __init__(self): """Initializes a parser object.""" <|body_0|> def _CanProcessKeyWithPlugin(self, registry_key, plugin_object): """Determines if a plugin can process a Windows Registry key or it...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WinRegistryParser: """Parses Windows NT Registry (REGF) files.""" def __init__(self): """Initializes a parser object.""" super(WinRegistryParser, self).__init__() self._plugins = WinRegistryParser.GetPluginObjects() for list_index, plugin_object in enumerate(self._plugins)...
the_stack_v2_python_sparse
plaso/parsers/winreg.py
CNR-ITTIG/plasodfaxp
train
1
77094baf032fa65b36d5f9f4242dd9957a7ae8b4
[ "super(ConceptExcerptEditForm, self).__init__(*args, **kwargs)\nfor tag in self.instance.topictag_set.all():\n label = 'Delete Tag: ' + tag.tag\n self.fields['tag_%d' % tag.id] = forms.BooleanField(label=_(label), required=False, initial=False)", "for tag in self.instance.topictag_set.all():\n if self.cl...
<|body_start_0|> super(ConceptExcerptEditForm, self).__init__(*args, **kwargs) for tag in self.instance.topictag_set.all(): label = 'Delete Tag: ' + tag.tag self.fields['tag_%d' % tag.id] = forms.BooleanField(label=_(label), required=False, initial=False) <|end_body_0|> <|body_s...
ConceptExcerptEditForm
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConceptExcerptEditForm: def __init__(self, *args, **kwargs): """This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data.""" <|body_0|> def save(self): """Saves an updat...
stack_v2_sparse_classes_75kplus_train_006337
11,505
permissive
[ { "docstring": "This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Saves an updated interview. Sinc...
2
stack_v2_sparse_classes_30k_train_041318
Implement the Python class `ConceptExcerptEditForm` described below. Class description: Implement the ConceptExcerptEditForm class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): This method creates text field for each concept returned by the imported function get_concept_list(). The intervi...
Implement the Python class `ConceptExcerptEditForm` described below. Class description: Implement the ConceptExcerptEditForm class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): This method creates text field for each concept returned by the imported function get_concept_list(). The intervi...
4f5fec75d1425de28a26eb3297ea5d4b0ed96c16
<|skeleton|> class ConceptExcerptEditForm: def __init__(self, *args, **kwargs): """This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data.""" <|body_0|> def save(self): """Saves an updat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConceptExcerptEditForm: def __init__(self, *args, **kwargs): """This method creates text field for each concept returned by the imported function get_concept_list(). The interview's old response is used as initial data.""" super(ConceptExcerptEditForm, self).__init__(*args, **kwargs) f...
the_stack_v2_python_sparse
conceptum/interviews/forms.py
kevincwebb/conceptum
train
0
42498c95b1dec89ab6f33ea3ae550e0851733877
[ "self.counter = 0\nself.frequency = spawning_frequency\nself.mix_and_match = mix_and_match\nself.prebuilts = prebuilt_vehicle_probs\nself.drivers = driver_template_probs\nself.vehicles = vehicle_template_probs", "self.counter += time_since_last_prompt\nif self.counter >= self.frequency:\n self.counter = 0\n ...
<|body_start_0|> self.counter = 0 self.frequency = spawning_frequency self.mix_and_match = mix_and_match self.prebuilts = prebuilt_vehicle_probs self.drivers = driver_template_probs self.vehicles = vehicle_template_probs <|end_body_0|> <|body_start_1|> self.count...
TemplatePairFactory
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TemplatePairFactory: def __init__(self, spawning_frequency, prebuilt_vehicle_probs, mix_and_match=False, driver_template_probs=None, vehicle_template_probs=None): """A TemplatePairFactory behaves in one of two ways. If the parameter mix_and_match is False, a VehicleTemplate-DriverTemplat...
stack_v2_sparse_classes_75kplus_train_006338
3,503
permissive
[ { "docstring": "A TemplatePairFactory behaves in one of two ways. If the parameter mix_and_match is False, a VehicleTemplate-DriverTemplate pair are returned according to the prebuilt probabilities. If mix_and_match is true, the VehicleTemplate-DriverTemplate pair are selected independantly from the driver_temp...
2
stack_v2_sparse_classes_30k_train_003690
Implement the Python class `TemplatePairFactory` described below. Class description: Implement the TemplatePairFactory class. Method signatures and docstrings: - def __init__(self, spawning_frequency, prebuilt_vehicle_probs, mix_and_match=False, driver_template_probs=None, vehicle_template_probs=None): A TemplatePair...
Implement the Python class `TemplatePairFactory` described below. Class description: Implement the TemplatePairFactory class. Method signatures and docstrings: - def __init__(self, spawning_frequency, prebuilt_vehicle_probs, mix_and_match=False, driver_template_probs=None, vehicle_template_probs=None): A TemplatePair...
69ba3bfddc8b8772b80a99fb7bb6b4367b417e5d
<|skeleton|> class TemplatePairFactory: def __init__(self, spawning_frequency, prebuilt_vehicle_probs, mix_and_match=False, driver_template_probs=None, vehicle_template_probs=None): """A TemplatePairFactory behaves in one of two ways. If the parameter mix_and_match is False, a VehicleTemplate-DriverTemplat...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TemplatePairFactory: def __init__(self, spawning_frequency, prebuilt_vehicle_probs, mix_and_match=False, driver_template_probs=None, vehicle_template_probs=None): """A TemplatePairFactory behaves in one of two ways. If the parameter mix_and_match is False, a VehicleTemplate-DriverTemplate pair are ret...
the_stack_v2_python_sparse
src/TemplatePairFactory.py
DLance96/TrafficSim-Simulator
train
0
13fd9260cd9381095efed53315fc93605ca0d227
[ "sleep_chain = NoOp() >> self.bundle_type((sleep(seconds=0.1) for _ in range(5)))\nstart_time = time.time()\nresult = sleep_chain.send(1)\nend_time = time.time()\nself.assertEqual(result, [1, 1, 1, 1, 1])\nself.assertLess(end_time - start_time, 0.5)", "if self.converter is None:\n raise unittest.SkipTest('no c...
<|body_start_0|> sleep_chain = NoOp() >> self.bundle_type((sleep(seconds=0.1) for _ in range(5))) start_time = time.time() result = sleep_chain.send(1) end_time = time.time() self.assertEqual(result, [1, 1, 1, 1, 1]) self.assertLess(end_time - start_time, 0.5) <|end_body_...
ConcurrentBundle
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ConcurrentBundle: def test_concurrent(self): """concurrent sleep""" <|body_0|> def test_convert_concurrent(self): """concurrent sleep from converter""" <|body_1|> def test_simple(self): """simple bundle as `a >> (b, c)`""" <|body_2|> ...
stack_v2_sparse_classes_75kplus_train_006339
4,703
permissive
[ { "docstring": "concurrent sleep", "name": "test_concurrent", "signature": "def test_concurrent(self)" }, { "docstring": "concurrent sleep from converter", "name": "test_convert_concurrent", "signature": "def test_convert_concurrent(self)" }, { "docstring": "simple bundle as `a >...
5
null
Implement the Python class `ConcurrentBundle` described below. Class description: Implement the ConcurrentBundle class. Method signatures and docstrings: - def test_concurrent(self): concurrent sleep - def test_convert_concurrent(self): concurrent sleep from converter - def test_simple(self): simple bundle as `a >> (...
Implement the Python class `ConcurrentBundle` described below. Class description: Implement the ConcurrentBundle class. Method signatures and docstrings: - def test_concurrent(self): concurrent sleep - def test_convert_concurrent(self): concurrent sleep from converter - def test_simple(self): simple bundle as `a >> (...
4e17f9992b4780bd0d9309202e2847df640bffe8
<|skeleton|> class ConcurrentBundle: def test_concurrent(self): """concurrent sleep""" <|body_0|> def test_convert_concurrent(self): """concurrent sleep from converter""" <|body_1|> def test_simple(self): """simple bundle as `a >> (b, c)`""" <|body_2|> ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ConcurrentBundle: def test_concurrent(self): """concurrent sleep""" sleep_chain = NoOp() >> self.bundle_type((sleep(seconds=0.1) for _ in range(5))) start_time = time.time() result = sleep_chain.send(1) end_time = time.time() self.assertEqual(result, [1, 1, 1, 1...
the_stack_v2_python_sparse
chainlet_unittests/test_chainlet/test_concurrency/testbase_primitives.py
maxfischer2781/chainlet
train
1
6ca09ae4d2a6f405599094fa85f954d6de1d4ce9
[ "list = self.lstItems.getMultiSelectedItems()\nfor item in list:\n for componentID in self.quad.components.keys():\n myComponent = self.quad.components[componentID]\n if myComponent.weaponID == item:\n del self.quad.components[myComponent.id]\n del self.quad.weapons[item]\nself.refres...
<|body_start_0|> list = self.lstItems.getMultiSelectedItems() for item in list: for componentID in self.quad.components.keys(): myComponent = self.quad.components[componentID] if myComponent.weaponID == item: del self.quad.components[myComp...
Panel displays List of Weapons in Quad
WeaponsInfoPanel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeaponsInfoPanel: """Panel displays List of Weapons in Quad""" def onRemove(self, item): """Remove selected items""" <|body_0|> def populate(self): """Populate panel with new data""" <|body_1|> <|end_skeleton|> <|body_start_0|> list = self.lstIt...
stack_v2_sparse_classes_75kplus_train_006340
6,973
no_license
[ { "docstring": "Remove selected items", "name": "onRemove", "signature": "def onRemove(self, item)" }, { "docstring": "Populate panel with new data", "name": "populate", "signature": "def populate(self)" } ]
2
null
Implement the Python class `WeaponsInfoPanel` described below. Class description: Panel displays List of Weapons in Quad Method signatures and docstrings: - def onRemove(self, item): Remove selected items - def populate(self): Populate panel with new data
Implement the Python class `WeaponsInfoPanel` described below. Class description: Panel displays List of Weapons in Quad Method signatures and docstrings: - def onRemove(self, item): Remove selected items - def populate(self): Populate panel with new data <|skeleton|> class WeaponsInfoPanel: """Panel displays Li...
46948d8d18a0639185dd4ffcffde126914991553
<|skeleton|> class WeaponsInfoPanel: """Panel displays List of Weapons in Quad""" def onRemove(self, item): """Remove selected items""" <|body_0|> def populate(self): """Populate panel with new data""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WeaponsInfoPanel: """Panel displays List of Weapons in Quad""" def onRemove(self, item): """Remove selected items""" list = self.lstItems.getMultiSelectedItems() for item in list: for componentID in self.quad.components.keys(): myComponent = self.quad.c...
the_stack_v2_python_sparse
anwmisc/anw-pyui/Packages/anwp/gui/quadinfo.py
colshag/ANW
train
2
ef3e3fd000289f682096727283cc159d976fe230
[ "self.data = data\nself.column_name = column_name\nself.author_names = self.data[column_name].unique()\nself.author_rating = {}\nfor name in self.author_names:\n self.author_rating[name] = random.randint(2, 20)\nself.author_rating['RichardDelwin'] = 12", "i = 0\nfor row_num in range(self.data.shape[0]):\n a...
<|body_start_0|> self.data = data self.column_name = column_name self.author_names = self.data[column_name].unique() self.author_rating = {} for name in self.author_names: self.author_rating[name] = random.randint(2, 20) self.author_rating['RichardDelwin'] = 1...
This class is concerned with extracting author names and mapping them to a numeric value ****************************************************************************************************** ** However this class isn't used, instead the author_details.py is used to just clean author names *** *************************...
Authors
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Authors: """This class is concerned with extracting author names and mapping them to a numeric value ****************************************************************************************************** ** However this class isn't used, instead the author_details.py is used to just clean author ...
stack_v2_sparse_classes_75kplus_train_006341
6,133
no_license
[ { "docstring": ":param data: The DataFrame consisting of authors :param column_name: author", "name": "__init__", "signature": "def __init__(self, data, column_name)" }, { "docstring": "This function was intended to clean author names and map them to integer values which could have been an indic...
2
stack_v2_sparse_classes_30k_train_037936
Implement the Python class `Authors` described below. Class description: This class is concerned with extracting author names and mapping them to a numeric value ****************************************************************************************************** ** However this class isn't used, instead the author_d...
Implement the Python class `Authors` described below. Class description: This class is concerned with extracting author names and mapping them to a numeric value ****************************************************************************************************** ** However this class isn't used, instead the author_d...
5c3e4df724207613f8c18681575b3e24cb54a14d
<|skeleton|> class Authors: """This class is concerned with extracting author names and mapping them to a numeric value ****************************************************************************************************** ** However this class isn't used, instead the author_details.py is used to just clean author ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Authors: """This class is concerned with extracting author names and mapping them to a numeric value ****************************************************************************************************** ** However this class isn't used, instead the author_details.py is used to just clean author names *** ***...
the_stack_v2_python_sparse
Features/feature_extraction.py
PavanRajkumar/Software-Risk
train
0
66c68f37af977b34b03765b3fd8e7a51f9c3243c
[ "try:\n self.object = User.objects.get(username=self.request.user)\n print(self.object)\n return self.object\nexcept:\n return None", "obj = self.get_object()\nprint(obj)\nif obj is not None:\n initial_data = model_to_dict(obj)\n print(initial_data)\n initial_data.update(model_to_dict(obj))\n...
<|body_start_0|> try: self.object = User.objects.get(username=self.request.user) print(self.object) return self.object except: return None <|end_body_0|> <|body_start_1|> obj = self.get_object() print(obj) if obj is not None: ...
UploadProfilePic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class UploadProfilePic: def get_object(self): """Check if data already exists""" <|body_0|> def get_initial(self): """Pre-fill the form if data exists""" <|body_1|> def form_valid(self, form): """Save to the database. If data exists, update else create...
stack_v2_sparse_classes_75kplus_train_006342
6,927
no_license
[ { "docstring": "Check if data already exists", "name": "get_object", "signature": "def get_object(self)" }, { "docstring": "Pre-fill the form if data exists", "name": "get_initial", "signature": "def get_initial(self)" }, { "docstring": "Save to the database. If data exists, upda...
3
stack_v2_sparse_classes_30k_train_023290
Implement the Python class `UploadProfilePic` described below. Class description: Implement the UploadProfilePic class. Method signatures and docstrings: - def get_object(self): Check if data already exists - def get_initial(self): Pre-fill the form if data exists - def form_valid(self, form): Save to the database. I...
Implement the Python class `UploadProfilePic` described below. Class description: Implement the UploadProfilePic class. Method signatures and docstrings: - def get_object(self): Check if data already exists - def get_initial(self): Pre-fill the form if data exists - def form_valid(self, form): Save to the database. I...
4e466eefaac29d9aebd162a320be32785f221d24
<|skeleton|> class UploadProfilePic: def get_object(self): """Check if data already exists""" <|body_0|> def get_initial(self): """Pre-fill the form if data exists""" <|body_1|> def form_valid(self, form): """Save to the database. If data exists, update else create...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class UploadProfilePic: def get_object(self): """Check if data already exists""" try: self.object = User.objects.get(username=self.request.user) print(self.object) return self.object except: return None def get_initial(self): """Pr...
the_stack_v2_python_sparse
SocialNetwork/dashboard/views.py
Nitu22499/SocialMediaClone
train
0
c6cfc99ccce79f02271345604ef996051b94d76f
[ "super().__init__(name=metric.name, metric=metric, model_selection_operator=model_selection_operator, logdir=logdir)\nif processing_predictions is None:\n processing_predictions = {'fn': tf.argmax, 'kwargs': {'axis': -1}}\nself._processing_predictions = processing_predictions", "for features, labels in context...
<|body_start_0|> super().__init__(name=metric.name, metric=metric, model_selection_operator=model_selection_operator, logdir=logdir) if processing_predictions is None: processing_predictions = {'fn': tf.argmax, 'kwargs': {'axis': -1}} self._processing_predictions = processing_predict...
Wrap a metric using `argmax` to extract predictions out of a classifier's output.
ClassifierMetric
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ClassifierMetric: """Wrap a metric using `argmax` to extract predictions out of a classifier's output.""" def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=Path().cwd() / 'log', processing_predictions=None) -> None: ...
stack_v2_sparse_classes_75kplus_train_006343
5,720
permissive
[ { "docstring": "Initialize the Metric. Args: metric (:py:class:`tf.keras.metrics.Metric`): The Keras Metric to use with the classifier (e.g.: Accuracy()). model_selection_operator (:py:obj:`typing.Callable`): The operation that will be used when `model_selection` is triggered to compare the metrics, used by the...
2
stack_v2_sparse_classes_30k_train_035301
Implement the Python class `ClassifierMetric` described below. Class description: Wrap a metric using `argmax` to extract predictions out of a classifier's output. Method signatures and docstrings: - def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=...
Implement the Python class `ClassifierMetric` described below. Class description: Wrap a metric using `argmax` to extract predictions out of a classifier's output. Method signatures and docstrings: - def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=...
92ac86fb0c962854e0d80c44165e0e7ff126b3c1
<|skeleton|> class ClassifierMetric: """Wrap a metric using `argmax` to extract predictions out of a classifier's output.""" def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=Path().cwd() / 'log', processing_predictions=None) -> None: ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ClassifierMetric: """Wrap a metric using `argmax` to extract predictions out of a classifier's output.""" def __init__(self, metric: tf.keras.metrics.Metric, model_selection_operator: Callable=None, logdir: Union[Path, str]=Path().cwd() / 'log', processing_predictions=None) -> None: """Initialize...
the_stack_v2_python_sparse
src/ashpy/metrics/classifier.py
zurutech/ashpy
train
89
5b4dd7d8f7eb47890c402f405b1eedcedefecc33
[ "if not head:\n return True\nslow = head\nfast = head.next\nwhile fast and fast.next:\n fast = fast.next.next\n slow = slow.next\ncur = slow.next\nslow.next = None\np = None\nwhile cur:\n q = cur.next\n cur.next = p\n p = cur\n cur = q\nwhile p and head:\n if p.val != head.val:\n retu...
<|body_start_0|> if not head: return True slow = head fast = head.next while fast and fast.next: fast = fast.next.next slow = slow.next cur = slow.next slow.next = None p = None while cur: q = cur.next ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isPalindrome(self, head: ListNode) -> bool: """1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:""" <|body_0|> def isPalindrome1(self, head: ListNode) -> bool: """使用数学方法""" <|body_1|> <|end_skeleton|> <|body_st...
stack_v2_sparse_classes_75kplus_train_006344
901
no_license
[ { "docstring": "1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:", "name": "isPalindrome", "signature": "def isPalindrome(self, head: ListNode) -> bool" }, { "docstring": "使用数学方法", "name": "isPalindrome1", "signature": "def isPalindrome1(self, head: List...
2
stack_v2_sparse_classes_30k_train_038016
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head: ListNode) -> bool: 1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return: - def isPalindrome1(self, head: ListNode) -> bo...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isPalindrome(self, head: ListNode) -> bool: 1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return: - def isPalindrome1(self, head: ListNode) -> bo...
4328382a65ac612aa4dc397f475c1d7db25c7723
<|skeleton|> class Solution: def isPalindrome(self, head: ListNode) -> bool: """1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:""" <|body_0|> def isPalindrome1(self, head: ListNode) -> bool: """使用数学方法""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isPalindrome(self, head: ListNode) -> bool: """1. 使用快慢指针,先找到链表的中间结点,参考ac_142 2. 反转链表的前半部分,可参考ac_206 3. 回文校验 :param head: :return:""" if not head: return True slow = head fast = head.next while fast and fast.next: fast = fast.next.ne...
the_stack_v2_python_sparse
thor/linklist/ac_234.py
duangduangda/Thor
train
0
5d720e079753c0e62a19608b9ee8a28d4d2c6f28
[ "super().__init__()\nself.vgg16partial = VGG16Partial(vgg_path=vgg_path).eval()\nself.loss_fn = torch.nn.L1Loss(size_average=True)\nself.l1_weight = l1_alpha\nself.vgg_weight = perceptual_alpha\nself.style_weight = style_alpha\nself.regularize_weight = smooth_alpha\nself.dividor = 1\nself.feat_num = feat_num", "y...
<|body_start_0|> super().__init__() self.vgg16partial = VGG16Partial(vgg_path=vgg_path).eval() self.loss_fn = torch.nn.L1Loss(size_average=True) self.l1_weight = l1_alpha self.vgg_weight = perceptual_alpha self.style_weight = style_alpha self.regularize_weight = s...
VGG16 perceptual loss
VGG16PartialLoss
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VGG16PartialLoss: """VGG16 perceptual loss""" def __init__(self, l1_alpha=5.0, perceptual_alpha=0.05, style_alpha=120, smooth_alpha=0, feat_num=3, vgg_path='/home/zack466/.torch/vgg16-397923af.pth'): """Init :param l1_alpha: weight of the l1 loss :param perceptual_alpha: weight of th...
stack_v2_sparse_classes_75kplus_train_006345
10,168
permissive
[ { "docstring": "Init :param l1_alpha: weight of the l1 loss :param perceptual_alpha: weight of the perceptual loss :param style_alpha: weight of the style loss :param smooth_alpha: weight of the regularizer :param feat_num: number of feature maps", "name": "__init__", "signature": "def __init__(self, l1...
2
stack_v2_sparse_classes_30k_val_002461
Implement the Python class `VGG16PartialLoss` described below. Class description: VGG16 perceptual loss Method signatures and docstrings: - def __init__(self, l1_alpha=5.0, perceptual_alpha=0.05, style_alpha=120, smooth_alpha=0, feat_num=3, vgg_path='/home/zack466/.torch/vgg16-397923af.pth'): Init :param l1_alpha: we...
Implement the Python class `VGG16PartialLoss` described below. Class description: VGG16 perceptual loss Method signatures and docstrings: - def __init__(self, l1_alpha=5.0, perceptual_alpha=0.05, style_alpha=120, smooth_alpha=0, feat_num=3, vgg_path='/home/zack466/.torch/vgg16-397923af.pth'): Init :param l1_alpha: we...
88146370c04bc299c0f4fa3a43d9dbc237bb102c
<|skeleton|> class VGG16PartialLoss: """VGG16 perceptual loss""" def __init__(self, l1_alpha=5.0, perceptual_alpha=0.05, style_alpha=120, smooth_alpha=0, feat_num=3, vgg_path='/home/zack466/.torch/vgg16-397923af.pth'): """Init :param l1_alpha: weight of the l1 loss :param perceptual_alpha: weight of th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VGG16PartialLoss: """VGG16 perceptual loss""" def __init__(self, l1_alpha=5.0, perceptual_alpha=0.05, style_alpha=120, smooth_alpha=0, feat_num=3, vgg_path='/home/zack466/.torch/vgg16-397923af.pth'): """Init :param l1_alpha: weight of the l1 loss :param perceptual_alpha: weight of the perceptual ...
the_stack_v2_python_sparse
losses/pconvloss.py
zack466/autoreg-sr
train
0
3394e5734184e5830a44b78a851afe5ade0d2fb8
[ "config = self.xmpp['xep_0004'].Form()\nconfig['type'] = 'submit'\nfor field, value in self.profile.items():\n config.add_field(var=field, value=value)\nreturn self.xmpp['xep_0060'].set_node_config(None, node, config, ifrom=ifrom, block=block, callback=callback, timeout=timeout)", "if not options:\n options...
<|body_start_0|> config = self.xmpp['xep_0004'].Form() config['type'] = 'submit' for field, value in self.profile.items(): config.add_field(var=field, value=value) return self.xmpp['xep_0060'].set_node_config(None, node, config, ifrom=ifrom, block=block, callback=callback, ti...
XEP-0222: Persistent Storage of Public Data via PubSub
XEP_0222
[ "MIT", "BSD-3-Clause", "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XEP_0222: """XEP-0222: Persistent Storage of Public Data via PubSub""" def configure(self, node, ifrom=None, block=None, callback=None, timeout=None): """Update a node's configuration to match the public storage profile.""" <|body_0|> def store(self, stanza, node=None, i...
stack_v2_sparse_classes_75kplus_train_006346
4,884
permissive
[ { "docstring": "Update a node's configuration to match the public storage profile.", "name": "configure", "signature": "def configure(self, node, ifrom=None, block=None, callback=None, timeout=None)" }, { "docstring": "Store public data via PEP. This is just a (very) thin wrapper around the XEP-...
3
stack_v2_sparse_classes_30k_val_001882
Implement the Python class `XEP_0222` described below. Class description: XEP-0222: Persistent Storage of Public Data via PubSub Method signatures and docstrings: - def configure(self, node, ifrom=None, block=None, callback=None, timeout=None): Update a node's configuration to match the public storage profile. - def ...
Implement the Python class `XEP_0222` described below. Class description: XEP-0222: Persistent Storage of Public Data via PubSub Method signatures and docstrings: - def configure(self, node, ifrom=None, block=None, callback=None, timeout=None): Update a node's configuration to match the public storage profile. - def ...
cc1d470397de768ffcc41d2ed5ac3118d19f09f5
<|skeleton|> class XEP_0222: """XEP-0222: Persistent Storage of Public Data via PubSub""" def configure(self, node, ifrom=None, block=None, callback=None, timeout=None): """Update a node's configuration to match the public storage profile.""" <|body_0|> def store(self, stanza, node=None, i...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class XEP_0222: """XEP-0222: Persistent Storage of Public Data via PubSub""" def configure(self, node, ifrom=None, block=None, callback=None, timeout=None): """Update a node's configuration to match the public storage profile.""" config = self.xmpp['xep_0004'].Form() config['type'] = 's...
the_stack_v2_python_sparse
sleekxmpp/plugins/xep_0222.py
fritzy/SleekXMPP
train
658
68ebf0311b14afad27cf1bb543dec38341bee8b5
[ "self.logger = logger\nself.log_level = log_level\nself.linebuf = ''", "sys.stdout.write(buf)\nfor line in buf.rstrip().splitlines():\n self.logger.log(self.log_level, line.rstrip())" ]
<|body_start_0|> self.logger = logger self.log_level = log_level self.linebuf = '' <|end_body_0|> <|body_start_1|> sys.stdout.write(buf) for line in buf.rstrip().splitlines(): self.logger.log(self.log_level, line.rstrip()) <|end_body_1|>
File-like stream object that redirects writes to a Logger instance.
StreamToLogger
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StreamToLogger: """File-like stream object that redirects writes to a Logger instance.""" def __init__(self, logger, log_level=logging.INFO): """@brief duck-typing for a file-stream object that redirects to a Logger instance @param Logger logger: instance of python standard Logger @p...
stack_v2_sparse_classes_75kplus_train_006347
11,245
permissive
[ { "docstring": "@brief duck-typing for a file-stream object that redirects to a Logger instance @param Logger logger: instance of python standard Logger @param int log_level: one of DEBUG, INFO, WARNING, ERROR, CRITICAL", "name": "__init__", "signature": "def __init__(self, logger, log_level=logging.INF...
2
stack_v2_sparse_classes_30k_train_050929
Implement the Python class `StreamToLogger` described below. Class description: File-like stream object that redirects writes to a Logger instance. Method signatures and docstrings: - def __init__(self, logger, log_level=logging.INFO): @brief duck-typing for a file-stream object that redirects to a Logger instance @p...
Implement the Python class `StreamToLogger` described below. Class description: File-like stream object that redirects writes to a Logger instance. Method signatures and docstrings: - def __init__(self, logger, log_level=logging.INFO): @brief duck-typing for a file-stream object that redirects to a Logger instance @p...
3314fbebdd547e8837c582a580dff33008edcfa9
<|skeleton|> class StreamToLogger: """File-like stream object that redirects writes to a Logger instance.""" def __init__(self, logger, log_level=logging.INFO): """@brief duck-typing for a file-stream object that redirects to a Logger instance @param Logger logger: instance of python standard Logger @p...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StreamToLogger: """File-like stream object that redirects writes to a Logger instance.""" def __init__(self, logger, log_level=logging.INFO): """@brief duck-typing for a file-stream object that redirects to a Logger instance @param Logger logger: instance of python standard Logger @param int log_...
the_stack_v2_python_sparse
postprocessing/Configuration.py
neutrons/post_processing_agent
train
0
2496f123b0ff1cae7a4473d613161b865ab51d26
[ "if not email or not password:\n raise ValueError\nself.setOpener()\nurl_login = 'http://mp.weixin.qq.com/cgi-bin/login?lang=en_US'\nm = hashlib.md5(password[0:16])\nm.digest()\npassword = m.hexdigest()\nbody = (('username', email), ('pwd', password), ('imgcode', ''), ('f', 'json'))\ntry:\n msg = json.loads(s...
<|body_start_0|> if not email or not password: raise ValueError self.setOpener() url_login = 'http://mp.weixin.qq.com/cgi-bin/login?lang=en_US' m = hashlib.md5(password[0:16]) m.digest() password = m.hexdigest() body = (('username', email), ('pwd', pas...
Client
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Client: def __init__(self, email=None, password=None): """登录公共平台服务器,如果失败将报客户端登录异常错误 :param email: :param password: :raise:""" <|body_0|> def sendTextMsg(self, sendTo, content): """给用户发送文字内容,成功返回True,使用时注意两次发送间隔,不能少于2s :param sendTo: :param content: :return:""" ...
stack_v2_sparse_classes_75kplus_train_006348
3,428
permissive
[ { "docstring": "登录公共平台服务器,如果失败将报客户端登录异常错误 :param email: :param password: :raise:", "name": "__init__", "signature": "def __init__(self, email=None, password=None)" }, { "docstring": "给用户发送文字内容,成功返回True,使用时注意两次发送间隔,不能少于2s :param sendTo: :param content: :return:", "name": "sendTextMsg", "s...
3
stack_v2_sparse_classes_30k_train_014553
Implement the Python class `Client` described below. Class description: Implement the Client class. Method signatures and docstrings: - def __init__(self, email=None, password=None): 登录公共平台服务器,如果失败将报客户端登录异常错误 :param email: :param password: :raise: - def sendTextMsg(self, sendTo, content): 给用户发送文字内容,成功返回True,使用时注意两次发送...
Implement the Python class `Client` described below. Class description: Implement the Client class. Method signatures and docstrings: - def __init__(self, email=None, password=None): 登录公共平台服务器,如果失败将报客户端登录异常错误 :param email: :param password: :raise: - def sendTextMsg(self, sendTo, content): 给用户发送文字内容,成功返回True,使用时注意两次发送...
665d39a2bd82543d5196555f0801ef8fd4a3ee48
<|skeleton|> class Client: def __init__(self, email=None, password=None): """登录公共平台服务器,如果失败将报客户端登录异常错误 :param email: :param password: :raise:""" <|body_0|> def sendTextMsg(self, sendTo, content): """给用户发送文字内容,成功返回True,使用时注意两次发送间隔,不能少于2s :param sendTo: :param content: :return:""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Client: def __init__(self, email=None, password=None): """登录公共平台服务器,如果失败将报客户端登录异常错误 :param email: :param password: :raise:""" if not email or not password: raise ValueError self.setOpener() url_login = 'http://mp.weixin.qq.com/cgi-bin/login?lang=en_US' m = h...
the_stack_v2_python_sparse
all-gists/5168051/snippet.py
gistable/gistable
train
76
a6bf7c2de8205404655cda35ce86cdf8c5f9659e
[ "def build_tree_skeleton(start: int, end: int) -> BSTNode:\n if start > end:\n return\n if start == end:\n return BSTNode(nodes[start])\n m = start + (end - start >> 1)\n currNode = BSTNode(nodes[m])\n currNode.left = build_tree_skeleton(start, m - 1)\n currNode.right = build_tree_sk...
<|body_start_0|> def build_tree_skeleton(start: int, end: int) -> BSTNode: if start > end: return if start == end: return BSTNode(nodes[start]) m = start + (end - start >> 1) currNode = BSTNode(nodes[m]) currNode.left = ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def createSortedArray(self, instructions: List[int]) -> int: """Use binary search tree.""" <|body_0|> def createSortedArray2(self, instructions: List[int]) -> int: """Use binary indexed tree. x & -x could get the least significant bit.""" <|body_1|>...
stack_v2_sparse_classes_75kplus_train_006349
2,961
no_license
[ { "docstring": "Use binary search tree.", "name": "createSortedArray", "signature": "def createSortedArray(self, instructions: List[int]) -> int" }, { "docstring": "Use binary indexed tree. x & -x could get the least significant bit.", "name": "createSortedArray2", "signature": "def crea...
2
stack_v2_sparse_classes_30k_train_040118
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def createSortedArray(self, instructions: List[int]) -> int: Use binary search tree. - def createSortedArray2(self, instructions: List[int]) -> int: Use binary indexed tree. x & ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def createSortedArray(self, instructions: List[int]) -> int: Use binary search tree. - def createSortedArray2(self, instructions: List[int]) -> int: Use binary indexed tree. x & ...
edb870f83f0c4568cce0cacec04ee70cf6b545bf
<|skeleton|> class Solution: def createSortedArray(self, instructions: List[int]) -> int: """Use binary search tree.""" <|body_0|> def createSortedArray2(self, instructions: List[int]) -> int: """Use binary indexed tree. x & -x could get the least significant bit.""" <|body_1|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def createSortedArray(self, instructions: List[int]) -> int: """Use binary search tree.""" def build_tree_skeleton(start: int, end: int) -> BSTNode: if start > end: return if start == end: return BSTNode(nodes[start]) ...
the_stack_v2_python_sparse
2021/create_sorted_array_through_instructions.py
eronekogin/leetcode
train
0
333bacc8de8caa6c083587714fbd077e9d6058d5
[ "neighbors = []\nfor i in range(data.shape[0]):\n dist = np.sqrt(np.sum(np.square(data[current_point] - data[i])))\n if dist <= eps:\n neighbors.append(i)\nreturn set(neighbors)", "cluster_label = -1\ncore_points_index = []\nneighbors_index_list = []\nunused_points_index = set([i for i in range(len(d...
<|body_start_0|> neighbors = [] for i in range(data.shape[0]): dist = np.sqrt(np.sum(np.square(data[current_point] - data[i]))) if dist <= eps: neighbors.append(i) return set(neighbors) <|end_body_0|> <|body_start_1|> cluster_label = -1 co...
DBSCAN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DBSCAN: def find_neighbor(current_point, data, eps): """找出一个指定数据的所有邻居。 :param current_point: 当前点 :param data: 数据集 :param eps: 最小邻居半径 :return: 邻居数据索引列表""" <|body_0|> def fit(epsilon, min_neighbor, data): """将数据集 data 中的所有数据点自适应聚类结果。 算法原理:https://blog.dominodatalab.com...
stack_v2_sparse_classes_75kplus_train_006350
4,720
no_license
[ { "docstring": "找出一个指定数据的所有邻居。 :param current_point: 当前点 :param data: 数据集 :param eps: 最小邻居半径 :return: 邻居数据索引列表", "name": "find_neighbor", "signature": "def find_neighbor(current_point, data, eps)" }, { "docstring": "将数据集 data 中的所有数据点自适应聚类结果。 算法原理:https://blog.dominodatalab.com/topology-and-densi...
2
stack_v2_sparse_classes_30k_train_054281
Implement the Python class `DBSCAN` described below. Class description: Implement the DBSCAN class. Method signatures and docstrings: - def find_neighbor(current_point, data, eps): 找出一个指定数据的所有邻居。 :param current_point: 当前点 :param data: 数据集 :param eps: 最小邻居半径 :return: 邻居数据索引列表 - def fit(epsilon, min_neighbor, data): 将数...
Implement the Python class `DBSCAN` described below. Class description: Implement the DBSCAN class. Method signatures and docstrings: - def find_neighbor(current_point, data, eps): 找出一个指定数据的所有邻居。 :param current_point: 当前点 :param data: 数据集 :param eps: 最小邻居半径 :return: 邻居数据索引列表 - def fit(epsilon, min_neighbor, data): 将数...
121d3c94b6fcd5533a878801aba4c326d791227d
<|skeleton|> class DBSCAN: def find_neighbor(current_point, data, eps): """找出一个指定数据的所有邻居。 :param current_point: 当前点 :param data: 数据集 :param eps: 最小邻居半径 :return: 邻居数据索引列表""" <|body_0|> def fit(epsilon, min_neighbor, data): """将数据集 data 中的所有数据点自适应聚类结果。 算法原理:https://blog.dominodatalab.com...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class DBSCAN: def find_neighbor(current_point, data, eps): """找出一个指定数据的所有邻居。 :param current_point: 当前点 :param data: 数据集 :param eps: 最小邻居半径 :return: 邻居数据索引列表""" neighbors = [] for i in range(data.shape[0]): dist = np.sqrt(np.sum(np.square(data[current_point] - data[i]))) ...
the_stack_v2_python_sparse
DataProcessingAlgorithm/DBSCAN.py
JackdawCF/autoPlanningAlgorithm
train
0
d8e7010bbe6d8e80e80cfc2e9c932ab339a73f27
[ "if file_:\n source = ImageFile(file_)\nelse:\n return None\nfor key, value in list(self.default_options.items()):\n options.setdefault(key, value)\nname = self._get_thumbnail_filename(source, geometry_string, options)\nthumbnail = ImageFile(name, default.storage)\nreturn thumbnail", "base_url = 'thumbs'...
<|body_start_0|> if file_: source = ImageFile(file_) else: return None for key, value in list(self.default_options.items()): options.setdefault(key, value) name = self._get_thumbnail_filename(source, geometry_string, options) thumbnail = ImageF...
S3Backend
[ "MIT", "CC-BY-SA-3.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class S3Backend: def get_thumbnail(self, file_, geometry_string, **options): """Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.""" ...
stack_v2_sparse_classes_75kplus_train_006351
1,764
permissive
[ { "docstring": "Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.", "name": "get_thumbnail", "signature": "def get_thumbnail(self, file_, geometry_st...
2
stack_v2_sparse_classes_30k_train_037445
Implement the Python class `S3Backend` described below. Class description: Implement the S3Backend class. Method signatures and docstrings: - def get_thumbnail(self, file_, geometry_string, **options): Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation...
Implement the Python class `S3Backend` described below. Class description: Implement the S3Backend class. Method signatures and docstrings: - def get_thumbnail(self, file_, geometry_string, **options): Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation...
db3f037c356a586b0eb6b9d5430ce12aa1ea7119
<|skeleton|> class S3Backend: def get_thumbnail(self, file_, geometry_string, **options): """Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class S3Backend: def get_thumbnail(self, file_, geometry_string, **options): """Returns thumbnail as an ImageFile instance for file with geometry and options given. All of the thumbnail generation logic is short-circuited as we know that CloudFront will generate the thumbnail for us.""" if file_: ...
the_stack_v2_python_sparse
electionleaflets/apps/core/s3_thumbnail_store.py
DemocracyClub/electionleaflets
train
9
d3a6ce2f3d97d3e76d4d5f12bdc327f5fcac3f6f
[ "metrics = set(metrics)\npersist_metrics = set()\nwith self.get_cursor() as cursor:\n cursor.execute(self.GET_STAGE_METRICS_SQL, (stage,))\n for id, metric in cursor.fetchall():\n persist_metrics.add(metric)\n creates = [(stage, m) for m in metrics.difference(persist_metrics)]\n cursor.executeman...
<|body_start_0|> metrics = set(metrics) persist_metrics = set() with self.get_cursor() as cursor: cursor.execute(self.GET_STAGE_METRICS_SQL, (stage,)) for id, metric in cursor.fetchall(): persist_metrics.add(metric) creates = [(stage, m) for m ...
MetricHandler
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MetricHandler: def declare(self, stage, metrics): """Get/Create metrics""" <|body_0|> def add_data(self, values): """Add a specified value for a specified metric id.""" <|body_1|> def get_data(self, metric_id, start, end): """Get the metric times...
stack_v2_sparse_classes_75kplus_train_006352
6,662
no_license
[ { "docstring": "Get/Create metrics", "name": "declare", "signature": "def declare(self, stage, metrics)" }, { "docstring": "Add a specified value for a specified metric id.", "name": "add_data", "signature": "def add_data(self, values)" }, { "docstring": "Get the metric timeserie...
5
stack_v2_sparse_classes_30k_train_041818
Implement the Python class `MetricHandler` described below. Class description: Implement the MetricHandler class. Method signatures and docstrings: - def declare(self, stage, metrics): Get/Create metrics - def add_data(self, values): Add a specified value for a specified metric id. - def get_data(self, metric_id, sta...
Implement the Python class `MetricHandler` described below. Class description: Implement the MetricHandler class. Method signatures and docstrings: - def declare(self, stage, metrics): Get/Create metrics - def add_data(self, values): Add a specified value for a specified metric id. - def get_data(self, metric_id, sta...
02e482e00b8d6c09bdbd6cb1f99ce8f2617e47cd
<|skeleton|> class MetricHandler: def declare(self, stage, metrics): """Get/Create metrics""" <|body_0|> def add_data(self, values): """Add a specified value for a specified metric id.""" <|body_1|> def get_data(self, metric_id, start, end): """Get the metric times...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MetricHandler: def declare(self, stage, metrics): """Get/Create metrics""" metrics = set(metrics) persist_metrics = set() with self.get_cursor() as cursor: cursor.execute(self.GET_STAGE_METRICS_SQL, (stage,)) for id, metric in cursor.fetchall(): ...
the_stack_v2_python_sparse
unshadow/server/metric.py
iakinsey/unshadow
train
1
35df0c5c5822582db60793288d1af0332795c447
[ "if definition is None:\n definition = RectDrawingBoxDefinition()\ndefinition = replace(definition, on_start=self.cache_selectable_boxes, on_change=self.handle_incomplete_selection_change, on_complete=self.handle_complete_selection)\nsuper(SelectionDrawingBox, self).__init__(definition, rect)\nself._cache: Set[S...
<|body_start_0|> if definition is None: definition = RectDrawingBoxDefinition() definition = replace(definition, on_start=self.cache_selectable_boxes, on_change=self.handle_incomplete_selection_change, on_complete=self.handle_complete_selection) super(SelectionDrawingBox, self).__ini...
A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system.
SelectionDrawingBox
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SelectionDrawingBox: """A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system.""" def __init__(self, definition: Optional[RectDrawingBoxDefiniti...
stack_v2_sparse_classes_75kplus_train_006353
11,725
permissive
[ { "docstring": "Create a new SelectionDrawingBox. :param definition: Definition of this drawing box. The callbacks will be overridden. :param rect: Definition of the rectangle that a drag selection can be made within. If None, defaults to the entire window.", "name": "__init__", "signature": "def __init...
4
stack_v2_sparse_classes_30k_train_051280
Implement the Python class `SelectionDrawingBox` described below. Class description: A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system. Method signatures and docstrin...
Implement the Python class `SelectionDrawingBox` described below. Class description: A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system. Method signatures and docstrin...
541247482748300bbebf9bdec5ecdc19339fe665
<|skeleton|> class SelectionDrawingBox: """A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system.""" def __init__(self, definition: Optional[RectDrawingBoxDefiniti...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SelectionDrawingBox: """A box that within its boundaries, any SelectableBox can be selected. This allows the user to drag to highlight or select many boxes at once. For example, this allows creation of a unit selection system.""" def __init__(self, definition: Optional[RectDrawingBoxDefinition]=None, rec...
the_stack_v2_python_sparse
shimmer/components/selection.py
MartinHowarth/shimmer
train
3
6ed8daf1e06972c1a306f11285184ed1489fd545
[ "self.biGramCount = {}\nself.uniGramCount = {}\nself.train(corpus)\nself.vocab = len(self.biGramCount.keys())", "self.bigram = LaplaceBigramLanguageModel(corpus)\nself.uniGramCount = self.bigram.uniGram.uniDict\nself.biGramCount = self.bigram.bigramCount", "result = 0.0\nfor i in range(1, len(sentence)):\n c...
<|body_start_0|> self.biGramCount = {} self.uniGramCount = {} self.train(corpus) self.vocab = len(self.biGramCount.keys()) <|end_body_0|> <|body_start_1|> self.bigram = LaplaceBigramLanguageModel(corpus) self.uniGramCount = self.bigram.uniGram.uniDict self.biGram...
StupidBackoffLanguageModel
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StupidBackoffLanguageModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" <|body_0|> def train(self, corpus): """Takes a corpus and trains your language model. Compute any counts or other corpus statistics in this function.""" ...
stack_v2_sparse_classes_75kplus_train_006354
1,334
no_license
[ { "docstring": "Initialize your data structures in the constructor.", "name": "__init__", "signature": "def __init__(self, corpus)" }, { "docstring": "Takes a corpus and trains your language model. Compute any counts or other corpus statistics in this function.", "name": "train", "signat...
3
stack_v2_sparse_classes_30k_train_044776
Implement the Python class `StupidBackoffLanguageModel` described below. Class description: Implement the StupidBackoffLanguageModel class. Method signatures and docstrings: - def __init__(self, corpus): Initialize your data structures in the constructor. - def train(self, corpus): Takes a corpus and trains your lang...
Implement the Python class `StupidBackoffLanguageModel` described below. Class description: Implement the StupidBackoffLanguageModel class. Method signatures and docstrings: - def __init__(self, corpus): Initialize your data structures in the constructor. - def train(self, corpus): Takes a corpus and trains your lang...
c85a5d0caf702efac27a50c17bf7a03c5768be9f
<|skeleton|> class StupidBackoffLanguageModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" <|body_0|> def train(self, corpus): """Takes a corpus and trains your language model. Compute any counts or other corpus statistics in this function.""" ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class StupidBackoffLanguageModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" self.biGramCount = {} self.uniGramCount = {} self.train(corpus) self.vocab = len(self.biGramCount.keys()) def train(self, corpus): """Takes a c...
the_stack_v2_python_sparse
LanguageModels/src/StupidBackoffLanguageModel.py
rahulr56/NLP
train
0
3e6a4093aff218c9857f4e3566832a26395a7f3a
[ "hash = {}\nfor p in products:\n for i in range(1, len(p) + 1):\n substr = p[:i]\n if substr not in hash:\n hash[substr] = PriorityQueue()\n hash[substr].push(p)\nres = []\nfor i in range(1, len(sw) + 1):\n substr = sw[:i]\n if substr in hash:\n res.append(hash[substr...
<|body_start_0|> hash = {} for p in products: for i in range(1, len(p) + 1): substr = p[:i] if substr not in hash: hash[substr] = PriorityQueue() hash[substr].push(p) res = [] for i in range(1, len(sw) + 1): ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def suggestedProducts_1(self, products, sw): """Method 1: Using Priority Queue to store all possible strings sharing same profix with sw[:i] for i in 1->len(sw)""" <|body_0|> def suggestedProducts_2(self, products, sw): """Method 2: sort and match prefix"""...
stack_v2_sparse_classes_75kplus_train_006355
4,850
no_license
[ { "docstring": "Method 1: Using Priority Queue to store all possible strings sharing same profix with sw[:i] for i in 1->len(sw)", "name": "suggestedProducts_1", "signature": "def suggestedProducts_1(self, products, sw)" }, { "docstring": "Method 2: sort and match prefix", "name": "suggested...
3
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def suggestedProducts_1(self, products, sw): Method 1: Using Priority Queue to store all possible strings sharing same profix with sw[:i] for i in 1->len(sw) - def suggestedProdu...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def suggestedProducts_1(self, products, sw): Method 1: Using Priority Queue to store all possible strings sharing same profix with sw[:i] for i in 1->len(sw) - def suggestedProdu...
9e4f6f1a2830bd9aab1bba374c98f0464825d435
<|skeleton|> class Solution: def suggestedProducts_1(self, products, sw): """Method 1: Using Priority Queue to store all possible strings sharing same profix with sw[:i] for i in 1->len(sw)""" <|body_0|> def suggestedProducts_2(self, products, sw): """Method 2: sort and match prefix"""...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def suggestedProducts_1(self, products, sw): """Method 1: Using Priority Queue to store all possible strings sharing same profix with sw[:i] for i in 1->len(sw)""" hash = {} for p in products: for i in range(1, len(p) + 1): substr = p[:i] ...
the_stack_v2_python_sparse
python_solutions/1268.search-suggestions-system.py
h4hany/leetcode
train
0
5e0f22634c0d707488207e07a55550f883f32383
[ "buffer_s_t = {}\nbuffer_t_s = {}\nreturn self._is_isomorphic_4(s, t)", "if len(s) == 0 and len(t) == 0:\n return True\nchar_s = s[0]\nchar_t = t[0]\nif char_s not in buffer_s_t and char_t not in buffer_t_s:\n buffer_s_t[char_s] = char_t\n buffer_t_s[char_t] = char_s\n return self._is_isomorphic(s[1:]...
<|body_start_0|> buffer_s_t = {} buffer_t_s = {} return self._is_isomorphic_4(s, t) <|end_body_0|> <|body_start_1|> if len(s) == 0 and len(t) == 0: return True char_s = s[0] char_t = t[0] if char_s not in buffer_s_t and char_t not in buffer_t_s: ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def _is_isomorphic(self, s, t, buffer_s_t, buffer_t_s): """backtracking version, two dict to buffer, memory limit exceeded. :param s: :param t: :param buffer_s_t: :param b...
stack_v2_sparse_classes_75kplus_train_006356
4,741
no_license
[ { "docstring": ":type s: str :type t: str :rtype: bool", "name": "isIsomorphic", "signature": "def isIsomorphic(self, s, t)" }, { "docstring": "backtracking version, two dict to buffer, memory limit exceeded. :param s: :param t: :param buffer_s_t: :param buffer_t_s: :return:", "name": "_is_i...
5
stack_v2_sparse_classes_30k_train_007246
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool - def _is_isomorphic(self, s, t, buffer_s_t, buffer_t_s): backtracking version, two dict to buffer, memory li...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool - def _is_isomorphic(self, s, t, buffer_s_t, buffer_t_s): backtracking version, two dict to buffer, memory li...
cf4235170db3629b65790fd0855a8a72ac5886f7
<|skeleton|> class Solution: def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" <|body_0|> def _is_isomorphic(self, s, t, buffer_s_t, buffer_t_s): """backtracking version, two dict to buffer, memory limit exceeded. :param s: :param t: :param buffer_s_t: :param b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def isIsomorphic(self, s, t): """:type s: str :type t: str :rtype: bool""" buffer_s_t = {} buffer_t_s = {} return self._is_isomorphic_4(s, t) def _is_isomorphic(self, s, t, buffer_s_t, buffer_t_s): """backtracking version, two dict to buffer, memory limit...
the_stack_v2_python_sparse
isomorphic_string.py
buxizhizhoum/leetcode
train
1
1c30e177e19b9845715f0ad9a2e0f01622919a2d
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RiskDetection()", "from .activity_type import ActivityType\nfrom .entity import Entity\nfrom .risk_detail import RiskDetail\nfrom .risk_detection_timing_type import RiskDetectionTimingType\nfrom .risk_level import RiskLevel\nfrom .risk...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return RiskDetection() <|end_body_0|> <|body_start_1|> from .activity_type import ActivityType from .entity import Entity from .risk_detail import RiskDetail from .risk_detectio...
RiskDetection
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RiskDetection: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns...
stack_v2_sparse_classes_75kplus_train_006357
10,613
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: RiskDetection", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_value...
3
stack_v2_sparse_classes_30k_train_029814
Implement the Python class `RiskDetection` described below. Class description: Implement the RiskDetection class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: Creates a new instance of the appropriate class based on discriminator value...
Implement the Python class `RiskDetection` described below. Class description: Implement the RiskDetection class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: Creates a new instance of the appropriate class based on discriminator value...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class RiskDetection: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: """Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RiskDetection: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskDetection: """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: RiskDetectio...
the_stack_v2_python_sparse
msgraph/generated/models/risk_detection.py
microsoftgraph/msgraph-sdk-python
train
135
7b122766f6d77ea757066cd2954bd63d2393f458
[ "content_types = Page.allowed_subpage_models()[1:]\nno_subpagetypes = set([])\nfor page_type in content_types:\n try:\n page_type.subpage_types\n except:\n no_subpagetypes.add(page_type.__name__)\nself.assertEqual(len(no_subpagetypes), 0, \"The following content types don't have a subpages_type ...
<|body_start_0|> content_types = Page.allowed_subpage_models()[1:] no_subpagetypes = set([]) for page_type in content_types: try: page_type.subpage_types except: no_subpagetypes.add(page_type.__name__) self.assertEqual(len(no_subpag...
Test the page model itself.
TestPageModels
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPageModels: """Test the page model itself.""" def test_page_models_have_subpage_types(self): """All page content types should have subpage_types explicitly set. This test won't tell us if they're set correctly but it will make sure we've at least done something.""" <|body...
stack_v2_sparse_classes_75kplus_train_006358
31,171
no_license
[ { "docstring": "All page content types should have subpage_types explicitly set. This test won't tell us if they're set correctly but it will make sure we've at least done something.", "name": "test_page_models_have_subpage_types", "signature": "def test_page_models_have_subpage_types(self)" }, { ...
2
null
Implement the Python class `TestPageModels` described below. Class description: Test the page model itself. Method signatures and docstrings: - def test_page_models_have_subpage_types(self): All page content types should have subpage_types explicitly set. This test won't tell us if they're set correctly but it will m...
Implement the Python class `TestPageModels` described below. Class description: Test the page model itself. Method signatures and docstrings: - def test_page_models_have_subpage_types(self): All page content types should have subpage_types explicitly set. This test won't tell us if they're set correctly but it will m...
e5912a17ed2de3a61ede2fbebda4a258664ff696
<|skeleton|> class TestPageModels: """Test the page model itself.""" def test_page_models_have_subpage_types(self): """All page content types should have subpage_types explicitly set. This test won't tell us if they're set correctly but it will make sure we've at least done something.""" <|body...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestPageModels: """Test the page model itself.""" def test_page_models_have_subpage_types(self): """All page content types should have subpage_types explicitly set. This test won't tell us if they're set correctly but it will make sure we've at least done something.""" content_types = Pag...
the_stack_v2_python_sparse
base/tests.py
uchicago-library/library_website
train
5
00f4af6a566bf7b4c4e450d8083843b69c38adae
[ "where_dom = [' %s %s %s ' % (x[0], x[1], isinstance(x[2], basestring) and \"'%s'\" % x[2] or x[2]) for x in domain]\nwhere_str = 'and'.join(where_dom)\nwhere_str = where_str.replace(',)', ')')\nreturn where_str", "self.ensure_one()\nResult = self.env['account.bank.receipt.view']\ndom = [('abr.state', '=', 'done'...
<|body_start_0|> where_dom = [' %s %s %s ' % (x[0], x[1], isinstance(x[2], basestring) and "'%s'" % x[2] or x[2]) for x in domain] where_str = 'and'.join(where_dom) where_str = where_str.replace(',)', ')') return where_str <|end_body_0|> <|body_start_1|> self.ensure_one() ...
XLSXReportSLAReceipt
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XLSXReportSLAReceipt: def _domain_to_where_str(self, domain): """Helper Function for better performance""" <|body_0|> def _compute_results(self): """Solution 1. Get from account bank receipt 2. Check state is done""" <|body_1|> <|end_skeleton|> <|body_start...
stack_v2_sparse_classes_75kplus_train_006359
3,668
no_license
[ { "docstring": "Helper Function for better performance", "name": "_domain_to_where_str", "signature": "def _domain_to_where_str(self, domain)" }, { "docstring": "Solution 1. Get from account bank receipt 2. Check state is done", "name": "_compute_results", "signature": "def _compute_resu...
2
stack_v2_sparse_classes_30k_train_044232
Implement the Python class `XLSXReportSLAReceipt` described below. Class description: Implement the XLSXReportSLAReceipt class. Method signatures and docstrings: - def _domain_to_where_str(self, domain): Helper Function for better performance - def _compute_results(self): Solution 1. Get from account bank receipt 2. ...
Implement the Python class `XLSXReportSLAReceipt` described below. Class description: Implement the XLSXReportSLAReceipt class. Method signatures and docstrings: - def _domain_to_where_str(self, domain): Helper Function for better performance - def _compute_results(self): Solution 1. Get from account bank receipt 2. ...
e8c21082c187f4639373b29a7a0905d069d770f2
<|skeleton|> class XLSXReportSLAReceipt: def _domain_to_where_str(self, domain): """Helper Function for better performance""" <|body_0|> def _compute_results(self): """Solution 1. Get from account bank receipt 2. Check state is done""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class XLSXReportSLAReceipt: def _domain_to_where_str(self, domain): """Helper Function for better performance""" where_dom = [' %s %s %s ' % (x[0], x[1], isinstance(x[2], basestring) and "'%s'" % x[2] or x[2]) for x in domain] where_str = 'and'.join(where_dom) where_str = where_str.r...
the_stack_v2_python_sparse
pabi_account_report/reports/xlsx_report_sla_receipt.py
pabi2/pb2_addons
train
6
75fbb48e7c9b38b134b638850f99e325040d95d8
[ "self.folder = folder\nself.dictionary = corpora.Dictionary.load(self.folder + '/dictionary')\nself.model = models.LdaModel.load(self.folder + '/model')\nself.vec_len = self.model.num_topics\nself.topic_vec = np.load(self.folder + '/topic_vec.npy')\nself.video_vec = np.load(self.folder + '/video_vec.npy')\nself.vid...
<|body_start_0|> self.folder = folder self.dictionary = corpora.Dictionary.load(self.folder + '/dictionary') self.model = models.LdaModel.load(self.folder + '/model') self.vec_len = self.model.num_topics self.topic_vec = np.load(self.folder + '/topic_vec.npy') self.video_...
The class for training topic model
SubjectVectorizer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SubjectVectorizer: """The class for training topic model""" def __init__(self, folder='./subject_models', cl_folder='../text_cleaner_models_with_subjects/', existing_video_index=None): """Initialize and load all models""" <|body_0|> def score_video_based_on_topic(self, t...
stack_v2_sparse_classes_75kplus_train_006360
9,029
no_license
[ { "docstring": "Initialize and load all models", "name": "__init__", "signature": "def __init__(self, folder='./subject_models', cl_folder='../text_cleaner_models_with_subjects/', existing_video_index=None)" }, { "docstring": "With the input topics, return a score for all the videos Removing vid...
2
null
Implement the Python class `SubjectVectorizer` described below. Class description: The class for training topic model Method signatures and docstrings: - def __init__(self, folder='./subject_models', cl_folder='../text_cleaner_models_with_subjects/', existing_video_index=None): Initialize and load all models - def sc...
Implement the Python class `SubjectVectorizer` described below. Class description: The class for training topic model Method signatures and docstrings: - def __init__(self, folder='./subject_models', cl_folder='../text_cleaner_models_with_subjects/', existing_video_index=None): Initialize and load all models - def sc...
61e6d2e222c4f4407987a88f5b23b80edfd5d4ed
<|skeleton|> class SubjectVectorizer: """The class for training topic model""" def __init__(self, folder='./subject_models', cl_folder='../text_cleaner_models_with_subjects/', existing_video_index=None): """Initialize and load all models""" <|body_0|> def score_video_based_on_topic(self, t...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SubjectVectorizer: """The class for training topic model""" def __init__(self, folder='./subject_models', cl_folder='../text_cleaner_models_with_subjects/', existing_video_index=None): """Initialize and load all models""" self.folder = folder self.dictionary = corpora.Dictionary.l...
the_stack_v2_python_sparse
src/website/learnah/data_manager/VideoVectorizer.py
Zhilin123/YHack_2018_WhyHat
train
0
5dba968a269457eb7dd0457a9c86c419e3247d63
[ "self.opts = opts\nself.svn_repos = self.__gen_svn_repos()\n{'packages': 'svn://svn.archlinux.org/packages', 'community': 'svn://svn.archlinux.org/community'}", "svn_repos = {}\nif self.opts['core_pkg']:\n svn_repos['packages'] = 'svn://svn.archlinux.org/packages'\nif self.opts['community_pkg']:\n svn_repos...
<|body_start_0|> self.opts = opts self.svn_repos = self.__gen_svn_repos() {'packages': 'svn://svn.archlinux.org/packages', 'community': 'svn://svn.archlinux.org/community'} <|end_body_0|> <|body_start_1|> svn_repos = {} if self.opts['core_pkg']: svn_repos['packages']...
Reads SVN repos.
ArchSVN
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ArchSVN: """Reads SVN repos.""" def __init__(self, opts): """Pass the options structure, we want those in here.""" <|body_0|> def __gen_svn_repos(self): """Generate the svn repos""" <|body_1|> def _update_repos(self): """Check the state of th...
stack_v2_sparse_classes_75kplus_train_006361
1,725
no_license
[ { "docstring": "Pass the options structure, we want those in here.", "name": "__init__", "signature": "def __init__(self, opts)" }, { "docstring": "Generate the svn repos", "name": "__gen_svn_repos", "signature": "def __gen_svn_repos(self)" }, { "docstring": "Check the state of t...
3
stack_v2_sparse_classes_30k_train_011797
Implement the Python class `ArchSVN` described below. Class description: Reads SVN repos. Method signatures and docstrings: - def __init__(self, opts): Pass the options structure, we want those in here. - def __gen_svn_repos(self): Generate the svn repos - def _update_repos(self): Check the state of the svn repositor...
Implement the Python class `ArchSVN` described below. Class description: Reads SVN repos. Method signatures and docstrings: - def __init__(self, opts): Pass the options structure, we want those in here. - def __gen_svn_repos(self): Generate the svn repos - def _update_repos(self): Check the state of the svn repositor...
631ebfccb17bcc1fd1509ded910d38de7a434ddf
<|skeleton|> class ArchSVN: """Reads SVN repos.""" def __init__(self, opts): """Pass the options structure, we want those in here.""" <|body_0|> def __gen_svn_repos(self): """Generate the svn repos""" <|body_1|> def _update_repos(self): """Check the state of th...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ArchSVN: """Reads SVN repos.""" def __init__(self, opts): """Pass the options structure, we want those in here.""" self.opts = opts self.svn_repos = self.__gen_svn_repos() {'packages': 'svn://svn.archlinux.org/packages', 'community': 'svn://svn.archlinux.org/community'} ...
the_stack_v2_python_sparse
quarters/quarters/scm.py
ChristianSP/sandbox
train
0
fa7290313a58eae2c6fe61233ab168b1abf1fb46
[ "neg_tau = -1.0 * abs(self.tau_matrix)\nX = {0}\nwhile len(X) != self.n_nodes:\n adj_set = set()\n for x in X:\n for k in range(self.n_nodes):\n if k not in X and k != x:\n adj_set.add((x, k))\n edge = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]\n copula = Biva...
<|body_start_0|> neg_tau = -1.0 * abs(self.tau_matrix) X = {0} while len(X) != self.n_nodes: adj_set = set() for x in X: for k in range(self.n_nodes): if k not in X and k != x: adj_set.add((x, k)) edg...
RegularTree class.
RegularTree
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegularTree: """RegularTree class.""" def _build_first_tree(self): """Build the first tree with n-1 variable.""" <|body_0|> def _build_kth_tree(self): """Build tree for level k.""" <|body_1|> <|end_skeleton|> <|body_start_0|> neg_tau = -1.0 * ab...
stack_v2_sparse_classes_75kplus_train_006362
22,020
permissive
[ { "docstring": "Build the first tree with n-1 variable.", "name": "_build_first_tree", "signature": "def _build_first_tree(self)" }, { "docstring": "Build tree for level k.", "name": "_build_kth_tree", "signature": "def _build_kth_tree(self)" } ]
2
null
Implement the Python class `RegularTree` described below. Class description: RegularTree class. Method signatures and docstrings: - def _build_first_tree(self): Build the first tree with n-1 variable. - def _build_kth_tree(self): Build tree for level k.
Implement the Python class `RegularTree` described below. Class description: RegularTree class. Method signatures and docstrings: - def _build_first_tree(self): Build the first tree with n-1 variable. - def _build_kth_tree(self): Build tree for level k. <|skeleton|> class RegularTree: """RegularTree class.""" ...
4de54e946ecb1e2bf831874e6a00a7d04d302804
<|skeleton|> class RegularTree: """RegularTree class.""" def _build_first_tree(self): """Build the first tree with n-1 variable.""" <|body_0|> def _build_kth_tree(self): """Build tree for level k.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegularTree: """RegularTree class.""" def _build_first_tree(self): """Build the first tree with n-1 variable.""" neg_tau = -1.0 * abs(self.tau_matrix) X = {0} while len(X) != self.n_nodes: adj_set = set() for x in X: for k in range(s...
the_stack_v2_python_sparse
copulas/multivariate/tree.py
pvk-developer/Copulas
train
0
3e10bac4df4189ea854ea704ddd9191799710f1c
[ "self.filepath = bpy.path.ensure_ext(self.filepath, self.filename_ext)\nprint(self.filepath)\nexported = self.main(context)\nif exported:\n print('Finished export')\nreturn {'FINISHED'}", "wm = context.window_manager\nif True:\n wm.fileselect_add(self)\n return {'RUNNING_MODAL'}\nelif True:\n wm.invok...
<|body_start_0|> self.filepath = bpy.path.ensure_ext(self.filepath, self.filename_ext) print(self.filepath) exported = self.main(context) if exported: print('Finished export') return {'FINISHED'} <|end_body_0|> <|body_start_1|> wm = context.window_manager ...
SimpleExport
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleExport: def execute(self, context): """blender callback hook""" <|body_0|> def invoke(self, context, event): """blender add-on callback hook This logic might look weird, but according to limited research it might be vital for the IO functions of an add-on - wm....
stack_v2_sparse_classes_75kplus_train_006363
4,229
no_license
[ { "docstring": "blender callback hook", "name": "execute", "signature": "def execute(self, context)" }, { "docstring": "blender add-on callback hook This logic might look weird, but according to limited research it might be vital for the IO functions of an add-on - wm.fileselect_add(self) Probab...
3
null
Implement the Python class `SimpleExport` described below. Class description: Implement the SimpleExport class. Method signatures and docstrings: - def execute(self, context): blender callback hook - def invoke(self, context, event): blender add-on callback hook This logic might look weird, but according to limited r...
Implement the Python class `SimpleExport` described below. Class description: Implement the SimpleExport class. Method signatures and docstrings: - def execute(self, context): blender callback hook - def invoke(self, context, event): blender add-on callback hook This logic might look weird, but according to limited r...
7b796d30dfd22b7706a93e4419ed913d18d29a44
<|skeleton|> class SimpleExport: def execute(self, context): """blender callback hook""" <|body_0|> def invoke(self, context, event): """blender add-on callback hook This logic might look weird, but according to limited research it might be vital for the IO functions of an add-on - wm....
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SimpleExport: def execute(self, context): """blender callback hook""" self.filepath = bpy.path.ensure_ext(self.filepath, self.filename_ext) print(self.filepath) exported = self.main(context) if exported: print('Finished export') return {'FINISHED'} ...
the_stack_v2_python_sparse
All_In_One/addons/io_export_simple_export.py
2434325680/Learnbgame
train
0
ef47079f0d3fb71453f277831396e9718a4489d4
[ "self.sample_size = sample_size\nself.sampler = UnigramSampler(corpus, power, sample_size)\nself.loss_layers = [SigmoidWithLoss() for _ in range(sample_size + 1)]\nself.embed_dot_layers = [EmbeddingDot(W) for _ in range(sample_size + 1)]\nself.params, self.grads = ([], [])\nfor layer in self.embed_dot_layers:\n ...
<|body_start_0|> self.sample_size = sample_size self.sampler = UnigramSampler(corpus, power, sample_size) self.loss_layers = [SigmoidWithLoss() for _ in range(sample_size + 1)] self.embed_dot_layers = [EmbeddingDot(W) for _ in range(sample_size + 1)] self.params, self.grads = ([]...
NegativeSamplingLoss
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NegativeSamplingLoss: def __init__(self, W, corpus, power=0.75, sample_size=5): """1. W : 출력층의 가중치(W_out) 2. corpus : 단어 ID의 리스트 3. power : 부정 단어 추출에서 확률 분포에 제곱할 값 (낮은 확률의 단어를 구제하는 변수) 4. sample_size : 부정 샘플링할 단어 수(긍정 + 부정 단어만큼 layer 생성) 5. sampler : UnigramSampler 클래스를 담은 변수 6. loss_lay...
stack_v2_sparse_classes_75kplus_train_006364
6,878
no_license
[ { "docstring": "1. W : 출력층의 가중치(W_out) 2. corpus : 단어 ID의 리스트 3. power : 부정 단어 추출에서 확률 분포에 제곱할 값 (낮은 확률의 단어를 구제하는 변수) 4. sample_size : 부정 샘플링할 단어 수(긍정 + 부정 단어만큼 layer 생성) 5. sampler : UnigramSampler 클래스를 담은 변수 6. loss_layers : SigmoidWithLoss 클래스를 sample_size + 1 만큼 담은 리스트 변수 7. embed_dot_layers : EmbeddingDot ...
3
stack_v2_sparse_classes_30k_train_041073
Implement the Python class `NegativeSamplingLoss` described below. Class description: Implement the NegativeSamplingLoss class. Method signatures and docstrings: - def __init__(self, W, corpus, power=0.75, sample_size=5): 1. W : 출력층의 가중치(W_out) 2. corpus : 단어 ID의 리스트 3. power : 부정 단어 추출에서 확률 분포에 제곱할 값 (낮은 확률의 단어를 구제하...
Implement the Python class `NegativeSamplingLoss` described below. Class description: Implement the NegativeSamplingLoss class. Method signatures and docstrings: - def __init__(self, W, corpus, power=0.75, sample_size=5): 1. W : 출력층의 가중치(W_out) 2. corpus : 단어 ID의 리스트 3. power : 부정 단어 추출에서 확률 분포에 제곱할 값 (낮은 확률의 단어를 구제하...
a7a8d590fa13f53348f83f8c808538affbc7b3e8
<|skeleton|> class NegativeSamplingLoss: def __init__(self, W, corpus, power=0.75, sample_size=5): """1. W : 출력층의 가중치(W_out) 2. corpus : 단어 ID의 리스트 3. power : 부정 단어 추출에서 확률 분포에 제곱할 값 (낮은 확률의 단어를 구제하는 변수) 4. sample_size : 부정 샘플링할 단어 수(긍정 + 부정 단어만큼 layer 생성) 5. sampler : UnigramSampler 클래스를 담은 변수 6. loss_lay...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NegativeSamplingLoss: def __init__(self, W, corpus, power=0.75, sample_size=5): """1. W : 출력층의 가중치(W_out) 2. corpus : 단어 ID의 리스트 3. power : 부정 단어 추출에서 확률 분포에 제곱할 값 (낮은 확률의 단어를 구제하는 변수) 4. sample_size : 부정 샘플링할 단어 수(긍정 + 부정 단어만큼 layer 생성) 5. sampler : UnigramSampler 클래스를 담은 변수 6. loss_layers : SigmoidW...
the_stack_v2_python_sparse
practice/deep-learning-from-scratch-2/common/negative_sampling_layer.py
heaven324/Deeplearning
train
1
78e3b8669c3d1d90a704fb1da0deeacee79bdf0e
[ "super(WeightedMinkowski, self).__init__(**kwargs)\nif rho_initializer is None:\n rho_initializer = tf.random_uniform_initializer(1.01, 3.0)\nself.rho_initializer = tf.keras.initializers.get(rho_initializer)\nself.rho = self.add_weight(shape=[], initializer=self.rho_initializer, trainable=self.trainable, name='r...
<|body_start_0|> super(WeightedMinkowski, self).__init__(**kwargs) if rho_initializer is None: rho_initializer = tf.random_uniform_initializer(1.01, 3.0) self.rho_initializer = tf.keras.initializers.get(rho_initializer) self.rho = self.add_weight(shape=[], initializer=self.rh...
Weighted Minkowski distance.
WeightedMinkowski
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeightedMinkowski: """Weighted Minkowski distance.""" def __init__(self, rho_initializer=None, **kwargs): """Initialize. Arguments: rho_initializer (optional): Initializer for rho.""" <|body_0|> def call(self, inputs): """Call. Arguments: inputs: z_0: A tf.Tensor...
stack_v2_sparse_classes_75kplus_train_006365
3,152
permissive
[ { "docstring": "Initialize. Arguments: rho_initializer (optional): Initializer for rho.", "name": "__init__", "signature": "def __init__(self, rho_initializer=None, **kwargs)" }, { "docstring": "Call. Arguments: inputs: z_0: A tf.Tensor denoting a set of vectors. shape = (batch_size, [n, m, ...]...
3
stack_v2_sparse_classes_30k_train_054012
Implement the Python class `WeightedMinkowski` described below. Class description: Weighted Minkowski distance. Method signatures and docstrings: - def __init__(self, rho_initializer=None, **kwargs): Initialize. Arguments: rho_initializer (optional): Initializer for rho. - def call(self, inputs): Call. Arguments: inp...
Implement the Python class `WeightedMinkowski` described below. Class description: Weighted Minkowski distance. Method signatures and docstrings: - def __init__(self, rho_initializer=None, **kwargs): Initialize. Arguments: rho_initializer (optional): Initializer for rho. - def call(self, inputs): Call. Arguments: inp...
4f05348cf43d2d53ff9cc6dee633de385df883e3
<|skeleton|> class WeightedMinkowski: """Weighted Minkowski distance.""" def __init__(self, rho_initializer=None, **kwargs): """Initialize. Arguments: rho_initializer (optional): Initializer for rho.""" <|body_0|> def call(self, inputs): """Call. Arguments: inputs: z_0: A tf.Tensor...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WeightedMinkowski: """Weighted Minkowski distance.""" def __init__(self, rho_initializer=None, **kwargs): """Initialize. Arguments: rho_initializer (optional): Initializer for rho.""" super(WeightedMinkowski, self).__init__(**kwargs) if rho_initializer is None: rho_ini...
the_stack_v2_python_sparse
psiz/keras/layers/distances/minkowski.py
asuiconlab/psiz
train
0
c273307560cddad80cd6009b73e0e2ac49685e4d
[ "super().__init__()\nself.dropout_rate = dropout_rate\nout_features = out_features or in_features\nhidden_features = hidden_features or in_features\nself.fc1 = Linear(in_features, hidden_features, bias=bias_on)\nself.act = act_layer()\nself.fc2 = Linear(hidden_features, out_features, bias=bias_on)\nif self.dropout_...
<|body_start_0|> super().__init__() self.dropout_rate = dropout_rate out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = Linear(in_features, hidden_features, bias=bias_on) self.act = act_layer() self.fc2 = Linear(...
A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropout (p=dropout_rate)
Mlp
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Mlp: """A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropou...
stack_v2_sparse_classes_75kplus_train_006366
28,184
permissive
[ { "docstring": "Args: in_features (int): Input feature dimension. hidden_features (Optional[int]): Hidden feature dimension. By default, hidden feature is set to input feature dimension. out_features (Optional[int]): Output feature dimension. By default, output features dimension is set to input feature dimensi...
2
stack_v2_sparse_classes_30k_train_010129
Implement the Python class `Mlp` described below. Class description: A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (...
Implement the Python class `Mlp` described below. Class description: A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (...
c60dc19788217556ba12ea378c02b9fd0aea9ffe
<|skeleton|> class Mlp: """A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropou...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Mlp: """A MLP block that contains two linear layers with a normalization layer. The MLP block is used in a transformer model after the attention block. :: Linear (in_features, hidden_features) ↓ Normalization (act_layer) ↓ Dropout (p=dropout_rate) ↓ Linear (hidden_features, out_features) ↓ Dropout (p=dropout_...
the_stack_v2_python_sparse
python/aitemplate/frontend/nn/multiscale_attention.py
facebookincubator/AITemplate
train
4,065
f831e670e8c2ad31e567c1a4bbf72f754e00a301
[ "super(Similarity, self).__init__()\nself.input_dim = input_dim\nself.hidden_dim = hidden_dim\nself.num_classes = num_classes\nself.h_s_1 = nn.Linear(self.input_dim, self.hidden_dim)\nself.h_s_2 = nn.Linear(self.input_dim, self.hidden_dim)\nself.h_p = nn.Linear(self.hidden_dim, self.num_classes)", "h_mul = torch....
<|body_start_0|> super(Similarity, self).__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.num_classes = num_classes self.h_s_1 = nn.Linear(self.input_dim, self.hidden_dim) self.h_s_2 = nn.Linear(self.input_dim, self.hidden_dim) self.h_p = nn...
Similarity Model
Similarity
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Similarity: """Similarity Model""" def __init__(self, input_dim, hidden_dim, num_classes): """:param input_dim: input dimension :param hidden_dim: hidden dimension :param num_classes: the number of class""" <|body_0|> def forward(self, l_h, r_h): """forward funct...
stack_v2_sparse_classes_75kplus_train_006367
1,161
no_license
[ { "docstring": ":param input_dim: input dimension :param hidden_dim: hidden dimension :param num_classes: the number of class", "name": "__init__", "signature": "def __init__(self, input_dim, hidden_dim, num_classes)" }, { "docstring": "forward function of the model :param l_h: the representatio...
2
stack_v2_sparse_classes_30k_train_037256
Implement the Python class `Similarity` described below. Class description: Similarity Model Method signatures and docstrings: - def __init__(self, input_dim, hidden_dim, num_classes): :param input_dim: input dimension :param hidden_dim: hidden dimension :param num_classes: the number of class - def forward(self, l_h...
Implement the Python class `Similarity` described below. Class description: Similarity Model Method signatures and docstrings: - def __init__(self, input_dim, hidden_dim, num_classes): :param input_dim: input dimension :param hidden_dim: hidden dimension :param num_classes: the number of class - def forward(self, l_h...
21adc6150148dc63684a1f8a387a19b7e9131f26
<|skeleton|> class Similarity: """Similarity Model""" def __init__(self, input_dim, hidden_dim, num_classes): """:param input_dim: input dimension :param hidden_dim: hidden dimension :param num_classes: the number of class""" <|body_0|> def forward(self, l_h, r_h): """forward funct...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Similarity: """Similarity Model""" def __init__(self, input_dim, hidden_dim, num_classes): """:param input_dim: input dimension :param hidden_dim: hidden dimension :param num_classes: the number of class""" super(Similarity, self).__init__() self.input_dim = input_dim self...
the_stack_v2_python_sparse
modules/Similarity.py
yin-hong/treelstm-pytorch
train
1
0974239e6d6361063e1eab70da650ce93b4e09e2
[ "self.persons = persons\nself.times = times\nself.cache = {}", "if t in self.cache:\n return self.cache[t]\ncounter = collections.Counter()\ntickets = []\nfor i, tm in enumerate(self.times):\n if t < tm:\n break\n tickets.append(self.persons[i])\ncounter.update(tickets)\ncandidates = set()\nfor i ...
<|body_start_0|> self.persons = persons self.times = times self.cache = {} <|end_body_0|> <|body_start_1|> if t in self.cache: return self.cache[t] counter = collections.Counter() tickets = [] for i, tm in enumerate(self.times): if t < tm:...
TopVotedCandidate
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TopVotedCandidate: def __init__(self, persons, times): """:type persons: List[int] :type times: List[int]""" <|body_0|> def q(self, t): """:type t: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.persons = persons self.t...
stack_v2_sparse_classes_75kplus_train_006368
1,505
no_license
[ { "docstring": ":type persons: List[int] :type times: List[int]", "name": "__init__", "signature": "def __init__(self, persons, times)" }, { "docstring": ":type t: int :rtype: int", "name": "q", "signature": "def q(self, t)" } ]
2
stack_v2_sparse_classes_30k_train_015666
Implement the Python class `TopVotedCandidate` described below. Class description: Implement the TopVotedCandidate class. Method signatures and docstrings: - def __init__(self, persons, times): :type persons: List[int] :type times: List[int] - def q(self, t): :type t: int :rtype: int
Implement the Python class `TopVotedCandidate` described below. Class description: Implement the TopVotedCandidate class. Method signatures and docstrings: - def __init__(self, persons, times): :type persons: List[int] :type times: List[int] - def q(self, t): :type t: int :rtype: int <|skeleton|> class TopVotedCandi...
d2cbd0aabff2f0b617d34a59b62771f6764adf95
<|skeleton|> class TopVotedCandidate: def __init__(self, persons, times): """:type persons: List[int] :type times: List[int]""" <|body_0|> def q(self, t): """:type t: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TopVotedCandidate: def __init__(self, persons, times): """:type persons: List[int] :type times: List[int]""" self.persons = persons self.times = times self.cache = {} def q(self, t): """:type t: int :rtype: int""" if t in self.cache: return self...
the_stack_v2_python_sparse
911.在线选举.py
ChenghaoZHU/LeetCode
train
0
8021d4df1b0bb7265d69d20dfda5c0d3e39f3cff
[ "try:\n with open(path, modifier):\n return True\nexcept IOError:\n return False", "try:\n value = int(value)\n if value < 0:\n raise argparse.ArgumentTypeError(\"Prefix quantity isn't represented by positive number\")\nexcept ValueError:\n raise\nreturn value", "parsed = value.spli...
<|body_start_0|> try: with open(path, modifier): return True except IOError: return False <|end_body_0|> <|body_start_1|> try: value = int(value) if value < 0: raise argparse.ArgumentTypeError("Prefix quantity isn't...
InputArgumentsValidator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InputArgumentsValidator: def validate_file(path, modifier) -> bool: """Check if file exists and it is readable (for input file) and writable (for output) :param path: path to the dataset or prefix set file :param modifier: additional flag which used for check if file is readable or writa...
stack_v2_sparse_classes_75kplus_train_006369
4,344
no_license
[ { "docstring": "Check if file exists and it is readable (for input file) and writable (for output) :param path: path to the dataset or prefix set file :param modifier: additional flag which used for check if file is readable or writable :return: true in case that file could be used (according to modifier). Fals...
6
stack_v2_sparse_classes_30k_train_051055
Implement the Python class `InputArgumentsValidator` described below. Class description: Implement the InputArgumentsValidator class. Method signatures and docstrings: - def validate_file(path, modifier) -> bool: Check if file exists and it is readable (for input file) and writable (for output) :param path: path to t...
Implement the Python class `InputArgumentsValidator` described below. Class description: Implement the InputArgumentsValidator class. Method signatures and docstrings: - def validate_file(path, modifier) -> bool: Check if file exists and it is readable (for input file) and writable (for output) :param path: path to t...
2318e02ddab6ae70f438e5d6e63405d5d97e6b1c
<|skeleton|> class InputArgumentsValidator: def validate_file(path, modifier) -> bool: """Check if file exists and it is readable (for input file) and writable (for output) :param path: path to the dataset or prefix set file :param modifier: additional flag which used for check if file is readable or writa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class InputArgumentsValidator: def validate_file(path, modifier) -> bool: """Check if file exists and it is readable (for input file) and writable (for output) :param path: path to the dataset or prefix set file :param modifier: additional flag which used for check if file is readable or writable :return: t...
the_stack_v2_python_sparse
Common/Validator/Validator.py
OriginalUtkin/IPv6-prefix-generator
train
1
b3216b2e8501a0d64451f80d8715c76a6de275f1
[ "t_data = np.copy(_t_data.astype(np.float))\nt_data = (_t_outLimits[1] - _t_outLimits[0]) * (t_data - t_data.min()) / (t_data.max() - t_data.min()) + _t_outLimits[0]\nreturn t_data", "t_data = np.copy(_t_data.astype(np.float))\nt_hist = np.histogram(t_data, QARK_HISTOGRAM_BINS)\nt_histCumul = np.cumsum(1.0 * t_hi...
<|body_start_0|> t_data = np.copy(_t_data.astype(np.float)) t_data = (_t_outLimits[1] - _t_outLimits[0]) * (t_data - t_data.min()) / (t_data.max() - t_data.min()) + _t_outLimits[0] return t_data <|end_body_0|> <|body_start_1|> t_data = np.copy(_t_data.astype(np.float)) t_hist = ...
QArkHistogramEqualization
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QArkHistogramEqualization: def equalize_LINEAR(cls, _t_data, _t_outLimits): """Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}""" <|b...
stack_v2_sparse_classes_75kplus_train_006370
3,223
permissive
[ { "docstring": "Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}", "name": "equalize_LINEAR", "signature": "def equalize_LINEAR(cls, _t_data, _t_outLimits)" ...
3
stack_v2_sparse_classes_30k_train_017105
Implement the Python class `QArkHistogramEqualization` described below. Class description: Implement the QArkHistogramEqualization class. Method signatures and docstrings: - def equalize_LINEAR(cls, _t_data, _t_outLimits): Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : ...
Implement the Python class `QArkHistogramEqualization` described below. Class description: Implement the QArkHistogramEqualization class. Method signatures and docstrings: - def equalize_LINEAR(cls, _t_data, _t_outLimits): Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : ...
46e03095028d2a2f153959d910ceab06a633223d
<|skeleton|> class QArkHistogramEqualization: def equalize_LINEAR(cls, _t_data, _t_outLimits): """Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}""" <|b...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class QArkHistogramEqualization: def equalize_LINEAR(cls, _t_data, _t_outLimits): """Egalisation lineaire de la matrice en entree @param _t_data : donnee en entree @type _t_data : L{np.nparray} @param _t_outLimits : (min, max) @type _t_outLimits : C{tuple} @rtype : L{np.nparray}""" t_data = np.copy(...
the_stack_v2_python_sparse
src/pyQArk/Image/QArkHistogramEqualization.py
arnaudkelbert/pyQArk
train
1
5c3940226ddcd00390d2a886d80e6c2a945af85e
[ "if len(prices) == 0:\n return 0\nleft = 0\nright = 1\nres = 0\nwhile right < len(prices):\n if prices[left] > prices[right]:\n left = right\n else:\n res += prices[right] - prices[left]\n left += 1\n right += 1\nreturn res", "result = 0\nfor i in range(1, len(prices)):\n if pr...
<|body_start_0|> if len(prices) == 0: return 0 left = 0 right = 1 res = 0 while right < len(prices): if prices[left] > prices[right]: left = right else: res += prices[right] - prices[left] left +=...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """我的解法""" <|body_0|> def maxProfit2(self, prices: List[int]) -> int: """官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。""" <|body_1|> <|end_skeleton|> <|body_start_0|> if len(prices) == 0: ...
stack_v2_sparse_classes_75kplus_train_006371
2,357
no_license
[ { "docstring": "我的解法", "name": "maxProfit", "signature": "def maxProfit(self, prices: List[int]) -> int" }, { "docstring": "官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。", "name": "maxProfit2", "signature": "def maxProfit2(self, prices: List[int]) -> int" } ]
2
stack_v2_sparse_classes_30k_train_045244
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 我的解法 - def maxProfit2(self, prices: List[int]) -> int: 官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxProfit(self, prices: List[int]) -> int: 我的解法 - def maxProfit2(self, prices: List[int]) -> int: 官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。 <|skeleton|> class Solution: ...
6932d69353b94ec824dd0ddc86a92453f6673232
<|skeleton|> class Solution: def maxProfit(self, prices: List[int]) -> int: """我的解法""" <|body_0|> def maxProfit2(self, prices: List[int]) -> int: """官方解法 时间复杂度:O(n),遍历一次。 空间复杂度:O(1),需要常量的空间。""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxProfit(self, prices: List[int]) -> int: """我的解法""" if len(prices) == 0: return 0 left = 0 right = 1 res = 0 while right < len(prices): if prices[left] > prices[right]: left = right else: ...
the_stack_v2_python_sparse
0112_best-time-to-buy-and-sell-stock-ii.py
Nigirimeshi/leetcode
train
0
86ecab3aa46cfdb295e821ffec6152cc97045635
[ "infra_map = self.get_infra_map()\nopenshift_provider_uuids, infra_provider_uuids = self.get_openshift_and_infra_providers_lists(infra_map)\nif self._provider.type == Provider.PROVIDER_OCP and self._provider_uuid not in openshift_provider_uuids:\n infra_map = self._generate_ocp_infra_map_from_sql(start_date, end...
<|body_start_0|> infra_map = self.get_infra_map() openshift_provider_uuids, infra_provider_uuids = self.get_openshift_and_infra_providers_lists(infra_map) if self._provider.type == Provider.PROVIDER_OCP and self._provider_uuid not in openshift_provider_uuids: infra_map = self._genera...
Class to update OCP report summary data.
OCPCloudReportSummaryUpdater
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class OCPCloudReportSummaryUpdater: """Class to update OCP report summary data.""" def update_summary_tables(self, start_date, end_date): """Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns ...
stack_v2_sparse_classes_75kplus_train_006372
6,579
permissive
[ { "docstring": "Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns None", "name": "update_summary_tables", "signature": "def update_summary_tables(self, start_date, end_date)" }, { "docstring": "Upd...
3
stack_v2_sparse_classes_30k_train_041811
Implement the Python class `OCPCloudReportSummaryUpdater` described below. Class description: Class to update OCP report summary data. Method signatures and docstrings: - def update_summary_tables(self, start_date, end_date): Populate the summary tables for reporting. Args: start_date (str) The date to start populati...
Implement the Python class `OCPCloudReportSummaryUpdater` described below. Class description: Class to update OCP report summary data. Method signatures and docstrings: - def update_summary_tables(self, start_date, end_date): Populate the summary tables for reporting. Args: start_date (str) The date to start populati...
2979f03fbdd1c20c3abc365a963a1282b426f321
<|skeleton|> class OCPCloudReportSummaryUpdater: """Class to update OCP report summary data.""" def update_summary_tables(self, start_date, end_date): """Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class OCPCloudReportSummaryUpdater: """Class to update OCP report summary data.""" def update_summary_tables(self, start_date, end_date): """Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns None""" ...
the_stack_v2_python_sparse
koku/masu/processor/ocp/ocp_cloud_summary_updater.py
luisfdez/koku
train
0
56f68d4b60daefe00071e36a054e869d34127be4
[ "self.encode = encode\nself.decode = decode\nsuper(SerialisedCache, self).__init__(proxied)", "value = super(SerialisedCache, self).get(key)\nif self.decode:\n value = self.decode(value)\nreturn value", "if self.encode:\n value = self.encode(value)\nsuper(SerialisedCache, self).set(key, value)" ]
<|body_start_0|> self.encode = encode self.decode = decode super(SerialisedCache, self).__init__(proxied) <|end_body_0|> <|body_start_1|> value = super(SerialisedCache, self).get(key) if self.decode: value = self.decode(value) return value <|end_body_1|> <|b...
Proxied cache that stores values as serialised data.
SerialisedCache
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SerialisedCache: """Proxied cache that stores values as serialised data.""" def __init__(self, proxied, encode=None, decode=None): """Initialise cache with *encode* and *decode* callables. *proxied* is the underlying cache to use for storage.""" <|body_0|> def get(self, ...
stack_v2_sparse_classes_75kplus_train_006373
15,766
permissive
[ { "docstring": "Initialise cache with *encode* and *decode* callables. *proxied* is the underlying cache to use for storage.", "name": "__init__", "signature": "def __init__(self, proxied, encode=None, decode=None)" }, { "docstring": "Return value for *key*. Raise :exc:`KeyError` if *key* not fo...
3
null
Implement the Python class `SerialisedCache` described below. Class description: Proxied cache that stores values as serialised data. Method signatures and docstrings: - def __init__(self, proxied, encode=None, decode=None): Initialise cache with *encode* and *decode* callables. *proxied* is the underlying cache to u...
Implement the Python class `SerialisedCache` described below. Class description: Proxied cache that stores values as serialised data. Method signatures and docstrings: - def __init__(self, proxied, encode=None, decode=None): Initialise cache with *encode* and *decode* callables. *proxied* is the underlying cache to u...
bcbc9b51dcfaaca86907e89b9ca3c977ae41cee2
<|skeleton|> class SerialisedCache: """Proxied cache that stores values as serialised data.""" def __init__(self, proxied, encode=None, decode=None): """Initialise cache with *encode* and *decode* callables. *proxied* is the underlying cache to use for storage.""" <|body_0|> def get(self, ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class SerialisedCache: """Proxied cache that stores values as serialised data.""" def __init__(self, proxied, encode=None, decode=None): """Initialise cache with *encode* and *decode* callables. *proxied* is the underlying cache to use for storage.""" self.encode = encode self.decode = ...
the_stack_v2_python_sparse
vendor/python/ftrack-python-api/ftrack_api/cache.py
jrsndl/pype-setup
train
1
8a0d86098cca012864736627984cfba1abac7e84
[ "elements = Scatter.getDataSetElements(self, dataset, setting)\nline = self.getDataLine(dataset, setting)\nif line:\n elements.insert(0, self.getDataLine(dataset, setting))\nreturn elements", "id = setting['line']['id']\nclasses = setting['line']['class']\nvertices = []\nfor value in dataset['value']:\n x =...
<|body_start_0|> elements = Scatter.getDataSetElements(self, dataset, setting) line = self.getDataLine(dataset, setting) if line: elements.insert(0, self.getDataLine(dataset, setting)) return elements <|end_body_0|> <|body_start_1|> id = setting['line']['id'] ...
Adds a line connecting the data points of a scatter plot in order.
Line
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Line: """Adds a line connecting the data points of a scatter plot in order.""" def getDataSetElements(self, dataset, setting): """Adds a data line to the dataset. The line is made the first element so the data points are rendered in front.""" <|body_0|> def getDataLine(s...
stack_v2_sparse_classes_75kplus_train_006374
1,143
permissive
[ { "docstring": "Adds a data line to the dataset. The line is made the first element so the data points are rendered in front.", "name": "getDataSetElements", "signature": "def getDataSetElements(self, dataset, setting)" }, { "docstring": "Returns a path element connecting the data points. @param...
2
stack_v2_sparse_classes_30k_train_044012
Implement the Python class `Line` described below. Class description: Adds a line connecting the data points of a scatter plot in order. Method signatures and docstrings: - def getDataSetElements(self, dataset, setting): Adds a data line to the dataset. The line is made the first element so the data points are render...
Implement the Python class `Line` described below. Class description: Adds a line connecting the data points of a scatter plot in order. Method signatures and docstrings: - def getDataSetElements(self, dataset, setting): Adds a data line to the dataset. The line is made the first element so the data points are render...
ff440f55f38d64658fcad3c60ded5236b1c0a401
<|skeleton|> class Line: """Adds a line connecting the data points of a scatter plot in order.""" def getDataSetElements(self, dataset, setting): """Adds a data line to the dataset. The line is made the first element so the data points are rendered in front.""" <|body_0|> def getDataLine(s...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Line: """Adds a line connecting the data points of a scatter plot in order.""" def getDataSetElements(self, dataset, setting): """Adds a data line to the dataset. The line is made the first element so the data points are rendered in front.""" elements = Scatter.getDataSetElements(self, da...
the_stack_v2_python_sparse
lib/generators/Line.py
agold/svgchart
train
1
405ad2ee763b4f710830ff930b1e41ee29db7df7
[ "if request.META.has_key('HTTP_USER_AGENT'):\n for user_agent_regex in settings.DISALLOWED_USER_AGENTS:\n if user_agent_regex.search(request.META['HTTP_USER_AGENT']):\n return httpwrappers.HttpResponseForbidden('<h1>Forbidden</h1>')\nold_url = [request.META['HTTP_HOST'], request.path]\nnew_url ...
<|body_start_0|> if request.META.has_key('HTTP_USER_AGENT'): for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): return httpwrappers.HttpResponseForbidden('<h1>Forbidden</h1>') old_url = [re...
"Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - ETags: If the USE_ETAGS setting is set, ETags w...
CommonMiddleware
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CommonMiddleware: """"Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - ETa...
stack_v2_sparse_classes_75kplus_train_006375
3,684
permissive
[ { "docstring": "Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW", "name": "process_request", "signature": "def process_request(self, request)" }, { "docstring": "Check for a flat page (for 404s) and calculate the Etag, if needed.", "na...
2
stack_v2_sparse_classes_30k_train_026656
Implement the Python class `CommonMiddleware` described below. Class description: "Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes...
Implement the Python class `CommonMiddleware` described below. Class description: "Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes...
9e1917c6c645b4ce0efe115b0da76027d4bc634c
<|skeleton|> class CommonMiddleware: """"Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - ETa...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CommonMiddleware: """"Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - ETags: If the US...
the_stack_v2_python_sparse
Django-0.90/django/middleware/common.py
tungvx/deploy
train
1
d349de07b292bdeab635290cd1dfcd044933b896
[ "res = 0\nfor i in range(len(nums)):\n res = max(res, nums[i] + self.rob(nums[i + 2:]))\nreturn res", "if not nums:\n return 0\np_0 = nums[0]\nif len(nums) == 1:\n return p_0\np_1 = max(p_0, nums[1])\nfor i in range(2, len(nums)):\n p_2 = max(p_1, p_0 + nums[i])\n p_0 = p_1\n p_1 = p_2\nreturn p...
<|body_start_0|> res = 0 for i in range(len(nums)): res = max(res, nums[i] + self.rob(nums[i + 2:])) return res <|end_body_0|> <|body_start_1|> if not nums: return 0 p_0 = nums[0] if len(nums) == 1: return p_0 p_1 = max(p_0, nu...
Solution
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def rob(self, nums): """Brute Force (Time Limit Exceeded)""" <|body_0|> def rob2(self, nums): """DP""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = 0 for i in range(len(nums)): res = max(res, nums[i] + self.rob(nu...
stack_v2_sparse_classes_75kplus_train_006376
1,489
permissive
[ { "docstring": "Brute Force (Time Limit Exceeded)", "name": "rob", "signature": "def rob(self, nums)" }, { "docstring": "DP", "name": "rob2", "signature": "def rob2(self, nums)" } ]
2
stack_v2_sparse_classes_30k_train_013387
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): Brute Force (Time Limit Exceeded) - def rob2(self, nums): DP
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def rob(self, nums): Brute Force (Time Limit Exceeded) - def rob2(self, nums): DP <|skeleton|> class Solution: def rob(self, nums): """Brute Force (Time Limit Excee...
49a0b03c55d8a702785888d473ef96539265ce9c
<|skeleton|> class Solution: def rob(self, nums): """Brute Force (Time Limit Exceeded)""" <|body_0|> def rob2(self, nums): """DP""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def rob(self, nums): """Brute Force (Time Limit Exceeded)""" res = 0 for i in range(len(nums)): res = max(res, nums[i] + self.rob(nums[i + 2:])) return res def rob2(self, nums): """DP""" if not nums: return 0 p_0 = ...
the_stack_v2_python_sparse
leetcode/0198_house_robber.py
chaosWsF/Python-Practice
train
1
d1ee6e1dc29e52977f03a981cd7248e84fe1b775
[ "self.host = host\nself.user = user\nself.pwd = pwd\nself.kwargs = kwargs", "msg = MIMEMultipart('alternative')\nmsg['From'] = self.user\nmsg['Subject'] = self.kwargs['title']\nmsg['To'] = ','.join(self.kwargs['users'])\nmsg.attach(MIMEText(content, 'html', 'utf-8'))\nif 'file_path' in self.kwargs:\n print(sel...
<|body_start_0|> self.host = host self.user = user self.pwd = pwd self.kwargs = kwargs <|end_body_0|> <|body_start_1|> msg = MIMEMultipart('alternative') msg['From'] = self.user msg['Subject'] = self.kwargs['title'] msg['To'] = ','.join(self.kwargs['users...
emailSend
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class emailSend: def __init__(self, host=main_host, user=main_user, pwd=main_pwd, **kwargs): """发送邮件 :param host: 发送邮件服务器host :param user: 发送人 :param pwd: 发送人密码 :param kwargs: users, 接收邮件人, list; title, 邮件标题, str; file_path, 发送邮件的文件路径(包含文件名)""" <|body_0|> def sender(self, content=...
stack_v2_sparse_classes_75kplus_train_006377
2,032
no_license
[ { "docstring": "发送邮件 :param host: 发送邮件服务器host :param user: 发送人 :param pwd: 发送人密码 :param kwargs: users, 接收邮件人, list; title, 邮件标题, str; file_path, 发送邮件的文件路径(包含文件名)", "name": "__init__", "signature": "def __init__(self, host=main_host, user=main_user, pwd=main_pwd, **kwargs)" }, { "docstring": "发送邮...
2
stack_v2_sparse_classes_30k_train_004935
Implement the Python class `emailSend` described below. Class description: Implement the emailSend class. Method signatures and docstrings: - def __init__(self, host=main_host, user=main_user, pwd=main_pwd, **kwargs): 发送邮件 :param host: 发送邮件服务器host :param user: 发送人 :param pwd: 发送人密码 :param kwargs: users, 接收邮件人, list; ...
Implement the Python class `emailSend` described below. Class description: Implement the emailSend class. Method signatures and docstrings: - def __init__(self, host=main_host, user=main_user, pwd=main_pwd, **kwargs): 发送邮件 :param host: 发送邮件服务器host :param user: 发送人 :param pwd: 发送人密码 :param kwargs: users, 接收邮件人, list; ...
483f414741f08ece9ece0880728107309a1fd220
<|skeleton|> class emailSend: def __init__(self, host=main_host, user=main_user, pwd=main_pwd, **kwargs): """发送邮件 :param host: 发送邮件服务器host :param user: 发送人 :param pwd: 发送人密码 :param kwargs: users, 接收邮件人, list; title, 邮件标题, str; file_path, 发送邮件的文件路径(包含文件名)""" <|body_0|> def sender(self, content=...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class emailSend: def __init__(self, host=main_host, user=main_user, pwd=main_pwd, **kwargs): """发送邮件 :param host: 发送邮件服务器host :param user: 发送人 :param pwd: 发送人密码 :param kwargs: users, 接收邮件人, list; title, 邮件标题, str; file_path, 发送邮件的文件路径(包含文件名)""" self.host = host self.user = user self....
the_stack_v2_python_sparse
src/email_base.py
longjymaker1/jolly_email
train
0
40dcd294ac1b15c7f4536a6571b5b8b17ea96b58
[ "super(AttentiveRNN, self).__init__()\nself.rnn = RNN(input_size, hidden_size, batch_first=batch_first, layers=layers, merge_bi=merge_bi, bidirectional=bidirectional, dropout=dropout, rnn_type=rnn_type, packed_sequence=packed_sequence, max_length=max_length)\nself.out_size = hidden_size if not (bidirectional and me...
<|body_start_0|> super(AttentiveRNN, self).__init__() self.rnn = RNN(input_size, hidden_size, batch_first=batch_first, layers=layers, merge_bi=merge_bi, bidirectional=bidirectional, dropout=dropout, rnn_type=rnn_type, packed_sequence=packed_sequence, max_length=max_length) self.out_size = hidden...
AttentiveRNN
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AttentiveRNN: def __init__(self, input_size: int, hidden_size: int=256, batch_first: bool=True, layers: int=1, bidirectional: bool=False, merge_bi: str='cat', dropout: float=0.1, rnn_type: str='lstm', packed_sequence: bool=True, attention: bool=False, max_length: int=-1, num_heads: int=1, nystro...
stack_v2_sparse_classes_75kplus_train_006378
17,025
permissive
[ { "docstring": "RNN with embedding layer and optional attention mechanism Single-headed scaled dot-product attention is used as an attention mechanism Args: input_size (int): Input features dimension hidden_size (int): Hidden features batch_first (bool): Use batch first representation type. Defaults to True. la...
2
stack_v2_sparse_classes_30k_train_031607
Implement the Python class `AttentiveRNN` described below. Class description: Implement the AttentiveRNN class. Method signatures and docstrings: - def __init__(self, input_size: int, hidden_size: int=256, batch_first: bool=True, layers: int=1, bidirectional: bool=False, merge_bi: str='cat', dropout: float=0.1, rnn_t...
Implement the Python class `AttentiveRNN` described below. Class description: Implement the AttentiveRNN class. Method signatures and docstrings: - def __init__(self, input_size: int, hidden_size: int=256, batch_first: bool=True, layers: int=1, bidirectional: bool=False, merge_bi: str='cat', dropout: float=0.1, rnn_t...
e4987310ed277abdec19462bdd749e2e7a000bec
<|skeleton|> class AttentiveRNN: def __init__(self, input_size: int, hidden_size: int=256, batch_first: bool=True, layers: int=1, bidirectional: bool=False, merge_bi: str='cat', dropout: float=0.1, rnn_type: str='lstm', packed_sequence: bool=True, attention: bool=False, max_length: int=-1, num_heads: int=1, nystro...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AttentiveRNN: def __init__(self, input_size: int, hidden_size: int=256, batch_first: bool=True, layers: int=1, bidirectional: bool=False, merge_bi: str='cat', dropout: float=0.1, rnn_type: str='lstm', packed_sequence: bool=True, attention: bool=False, max_length: int=-1, num_heads: int=1, nystrom: bool=True, ...
the_stack_v2_python_sparse
slp/modules/rnn.py
georgepar/slp
train
26
037d5658e5e85f09b18e9b0cab84902de5aed6fe
[ "super().__init__()\nself.average_by_layers = average_by_layers\nself.average_by_discriminators = average_by_discriminators\nself.include_final_outputs = include_final_outputs", "feat_match_loss = 0.0\nfor i, (feats_hat_, feats_) in enumerate(zip(feats_hat, feats)):\n feat_match_loss_ = 0.0\n if not self.in...
<|body_start_0|> super().__init__() self.average_by_layers = average_by_layers self.average_by_discriminators = average_by_discriminators self.include_final_outputs = include_final_outputs <|end_body_0|> <|body_start_1|> feat_match_loss = 0.0 for i, (feats_hat_, feats_) ...
Feature matching loss module.
FeatureMatchLoss
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FeatureMatchLoss: """Feature matching loss module.""" def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): """Initialize FeatureMatchLoss module.""" <|body_0|> def forward(self, feats_hat, feats): """Calcualate ...
stack_v2_sparse_classes_75kplus_train_006379
46,210
permissive
[ { "docstring": "Initialize FeatureMatchLoss module.", "name": "__init__", "signature": "def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False)" }, { "docstring": "Calcualate feature matching loss. Args: feats_hat(list): List of list of discriminat...
2
stack_v2_sparse_classes_30k_train_052074
Implement the Python class `FeatureMatchLoss` described below. Class description: Feature matching loss module. Method signatures and docstrings: - def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): Initialize FeatureMatchLoss module. - def forward(self, feats_hat...
Implement the Python class `FeatureMatchLoss` described below. Class description: Feature matching loss module. Method signatures and docstrings: - def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): Initialize FeatureMatchLoss module. - def forward(self, feats_hat...
17854a04d43c231eff66bfed9d6aa55e94a29e79
<|skeleton|> class FeatureMatchLoss: """Feature matching loss module.""" def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): """Initialize FeatureMatchLoss module.""" <|body_0|> def forward(self, feats_hat, feats): """Calcualate ...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class FeatureMatchLoss: """Feature matching loss module.""" def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): """Initialize FeatureMatchLoss module.""" super().__init__() self.average_by_layers = average_by_layers self.avera...
the_stack_v2_python_sparse
paddlespeech/t2s/modules/losses.py
anniyanvr/DeepSpeech-1
train
0
56621d2397133d0c61339b2cc97f8600f34803fa
[ "if not remote_user:\n return\nusername = self.clean_username(remote_user)\nif not username:\n return\nreturn super(EmailHeaderBackend, self).authenticate(request, remote_user)", "validator = EmailValidator()\ntry:\n validator(username)\nexcept ValidationError:\n log.debug('Invalid email address: %r',...
<|body_start_0|> if not remote_user: return username = self.clean_username(remote_user) if not username: return return super(EmailHeaderBackend, self).authenticate(request, remote_user) <|end_body_0|> <|body_start_1|> validator = EmailValidator() ...
Custom backend that validates username is an email.
EmailHeaderBackend
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class EmailHeaderBackend: """Custom backend that validates username is an email.""" def authenticate(self, request, remote_user): """Override default to return None if username is invalid.""" <|body_0|> def clean_username(self, username): """Makes sure that the usernam...
stack_v2_sparse_classes_75kplus_train_006380
2,816
permissive
[ { "docstring": "Override default to return None if username is invalid.", "name": "authenticate", "signature": "def authenticate(self, request, remote_user)" }, { "docstring": "Makes sure that the username is a valid email address.", "name": "clean_username", "signature": "def clean_user...
3
stack_v2_sparse_classes_30k_train_002274
Implement the Python class `EmailHeaderBackend` described below. Class description: Custom backend that validates username is an email. Method signatures and docstrings: - def authenticate(self, request, remote_user): Override default to return None if username is invalid. - def clean_username(self, username): Makes ...
Implement the Python class `EmailHeaderBackend` described below. Class description: Custom backend that validates username is an email. Method signatures and docstrings: - def authenticate(self, request, remote_user): Override default to return None if username is invalid. - def clean_username(self, username): Makes ...
941b11f84f5c0d210f638654a6ed34a5610af22a
<|skeleton|> class EmailHeaderBackend: """Custom backend that validates username is an email.""" def authenticate(self, request, remote_user): """Override default to return None if username is invalid.""" <|body_0|> def clean_username(self, username): """Makes sure that the usernam...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class EmailHeaderBackend: """Custom backend that validates username is an email.""" def authenticate(self, request, remote_user): """Override default to return None if username is invalid.""" if not remote_user: return username = self.clean_username(remote_user) if n...
the_stack_v2_python_sparse
nsot/middleware/auth.py
dropbox/nsot
train
414
7bd3067a99964878918d4302e738b48b829d8fc1
[ "result = self._get_html(page_name)\nif result['success']:\n result['content'] = self._tidy_html(result['content'])\nreturn result", "error_message = ''\nurl = 'https://en.wikipedia.org/wiki/%s' % page_name\ntry:\n response = requests.get(url, params={'action': 'render'}, timeout=5)\nexcept requests.excepti...
<|body_start_0|> result = self._get_html(page_name) if result['success']: result['content'] = self._tidy_html(result['content']) return result <|end_body_0|> <|body_start_1|> error_message = '' url = 'https://en.wikipedia.org/wiki/%s' % page_name try: ...
WikipediaFetcher
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WikipediaFetcher: def fetch(self, page_name): """Passed a Wikipedia page's URL fragment, like 'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's main contents, tidy the HTML, strip out any elements we don't want and return the final HTML string. Returns a dict with two el...
stack_v2_sparse_classes_75kplus_train_006381
7,254
no_license
[ { "docstring": "Passed a Wikipedia page's URL fragment, like 'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's main contents, tidy the HTML, strip out any elements we don't want and return the final HTML string. Returns a dict with two elements: 'success' is either True or, if we couldn't fetch...
5
stack_v2_sparse_classes_30k_train_041068
Implement the Python class `WikipediaFetcher` described below. Class description: Implement the WikipediaFetcher class. Method signatures and docstrings: - def fetch(self, page_name): Passed a Wikipedia page's URL fragment, like 'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's main contents, tidy th...
Implement the Python class `WikipediaFetcher` described below. Class description: Implement the WikipediaFetcher class. Method signatures and docstrings: - def fetch(self, page_name): Passed a Wikipedia page's URL fragment, like 'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's main contents, tidy th...
c6d99f39046eb5309f3292bfb4edb8b008f37aeb
<|skeleton|> class WikipediaFetcher: def fetch(self, page_name): """Passed a Wikipedia page's URL fragment, like 'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's main contents, tidy the HTML, strip out any elements we don't want and return the final HTML string. Returns a dict with two el...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class WikipediaFetcher: def fetch(self, page_name): """Passed a Wikipedia page's URL fragment, like 'Edward_Montagu,_1st_Earl_of_Sandwich', this will fetch the page's main contents, tidy the HTML, strip out any elements we don't want and return the final HTML string. Returns a dict with two elements: 'succe...
the_stack_v2_python_sparse
pepysdiary/encyclopedia/wikipedia_fetcher.py
philgyford/pepysdiary
train
16
c7287698bfff051eecbd308713ca20cfa9f5244e
[ "out = self.nanoutput()\nt2p = run.trace2p()\ntrs = t2p.trace('deconvolved')\nif run.run_type != 'training':\n c2p = run.classify2p()\n mask = t2p.inactivity()\nelse:\n c2p = self.training_classifier(run)\n mask = t2p.trialmask(padpre=0.1, padpost=0.5)\n mask = np.bitwise_or(mask, t2p.inactivity(nost...
<|body_start_0|> out = self.nanoutput() t2p = run.trace2p() trs = t2p.trace('deconvolved') if run.run_type != 'training': c2p = run.classify2p() mask = t2p.inactivity() else: c2p = self.training_classifier(run) mask = t2p.trialmask(...
Repevent
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Repevent: def run(self, run): """Run all analyses and returns results in a dictionary. Parameters ---------- run : Run object Returns ------- dict All of the output values""" <|body_0|> def training_classifier(self, run): """Get a training classifier instance Paramet...
stack_v2_sparse_classes_75kplus_train_006382
1,958
no_license
[ { "docstring": "Run all analyses and returns results in a dictionary. Parameters ---------- run : Run object Returns ------- dict All of the output values", "name": "run", "signature": "def run(self, run)" }, { "docstring": "Get a training classifier instance Parameters ---------- run : Run obje...
2
null
Implement the Python class `Repevent` described below. Class description: Implement the Repevent class. Method signatures and docstrings: - def run(self, run): Run all analyses and returns results in a dictionary. Parameters ---------- run : Run object Returns ------- dict All of the output values - def training_clas...
Implement the Python class `Repevent` described below. Class description: Implement the Repevent class. Method signatures and docstrings: - def run(self, run): Run all analyses and returns results in a dictionary. Parameters ---------- run : Run object Returns ------- dict All of the output values - def training_clas...
c4e9699fb78db7bd7cc14bc1bd6bd7d2b4e3a16b
<|skeleton|> class Repevent: def run(self, run): """Run all analyses and returns results in a dictionary. Parameters ---------- run : Run object Returns ------- dict All of the output values""" <|body_0|> def training_classifier(self, run): """Get a training classifier instance Paramet...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Repevent: def run(self, run): """Run all analyses and returns results in a dictionary. Parameters ---------- run : Run object Returns ------- dict All of the output values""" out = self.nanoutput() t2p = run.trace2p() trs = t2p.trace('deconvolved') if run.run_type != 't...
the_stack_v2_python_sparse
pool/analyses/repevent.py
jzaremba/pool
train
0
08a90f1d222f0711ecc99595b784caedb29ebac3
[ "if not builder:\n raise ValueError('Builder is not specified')\nself.__builder = builder", "if not record:\n raise ValueError('Record is not specified')\nif not zoneOsh:\n raise ValueError('Zone OSH is not specified')\nosh = self.__builder.buildRecord(record)\nosh.setContainer(zoneOsh)\nreturn osh", "...
<|body_start_0|> if not builder: raise ValueError('Builder is not specified') self.__builder = builder <|end_body_0|> <|body_start_1|> if not record: raise ValueError('Record is not specified') if not zoneOsh: raise ValueError('Zone OSH is not specifi...
ResourceRecordReporter
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ResourceRecordReporter: def __init__(self, builder): """@types: ResourceRecordBuilder @raise ValueError: Builder is not specified""" <|body_0|> def reportRecord(self, record, zoneOsh): """@types: ResourceRecord, ObjectStateHolder -> ObjectStateHolder @raise ValueErro...
stack_v2_sparse_classes_75kplus_train_006383
9,890
no_license
[ { "docstring": "@types: ResourceRecordBuilder @raise ValueError: Builder is not specified", "name": "__init__", "signature": "def __init__(self, builder)" }, { "docstring": "@types: ResourceRecord, ObjectStateHolder -> ObjectStateHolder @raise ValueError: Record is not specified @raise ValueErro...
4
null
Implement the Python class `ResourceRecordReporter` described below. Class description: Implement the ResourceRecordReporter class. Method signatures and docstrings: - def __init__(self, builder): @types: ResourceRecordBuilder @raise ValueError: Builder is not specified - def reportRecord(self, record, zoneOsh): @typ...
Implement the Python class `ResourceRecordReporter` described below. Class description: Implement the ResourceRecordReporter class. Method signatures and docstrings: - def __init__(self, builder): @types: ResourceRecordBuilder @raise ValueError: Builder is not specified - def reportRecord(self, record, zoneOsh): @typ...
c431e809e8d0f82e1bca7e3429dd0245560b5680
<|skeleton|> class ResourceRecordReporter: def __init__(self, builder): """@types: ResourceRecordBuilder @raise ValueError: Builder is not specified""" <|body_0|> def reportRecord(self, record, zoneOsh): """@types: ResourceRecord, ObjectStateHolder -> ObjectStateHolder @raise ValueErro...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class ResourceRecordReporter: def __init__(self, builder): """@types: ResourceRecordBuilder @raise ValueError: Builder is not specified""" if not builder: raise ValueError('Builder is not specified') self.__builder = builder def reportRecord(self, record, zoneOsh): "...
the_stack_v2_python_sparse
reference/ucmdb/discovery/dns.py
madmonkyang/cda-record
train
0
acc3fcd62529ca3842662dff2470d6c9279652c2
[ "res = []\ntmp = []\ndic = {}\nfor word in strs:\n for i in range(len(word)):\n if word[i] in dic:\n dic[word[i]] += 1\n else:\n dic[word[i]] = 1\n if dic in tmp:\n index = tmp.index(dic)\n res[index].append(word)\n else:\n t = dic.copy()\n tm...
<|body_start_0|> res = [] tmp = [] dic = {} for word in strs: for i in range(len(word)): if word[i] in dic: dic[word[i]] += 1 else: dic[word[i]] = 1 if dic in tmp: index = tmp....
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def groupAnagrams(self, strs): """:type strs: List[str] :rtype: List[List[str]]""" <|body_0|> def groupAnagrams0(self, strs): """:type strs: List[str] :rtype: List[List[str]]""" <|body_1|> <|end_skeleton|> <|body_start_0|> res = [] ...
stack_v2_sparse_classes_75kplus_train_006384
1,180
no_license
[ { "docstring": ":type strs: List[str] :rtype: List[List[str]]", "name": "groupAnagrams", "signature": "def groupAnagrams(self, strs)" }, { "docstring": ":type strs: List[str] :rtype: List[List[str]]", "name": "groupAnagrams0", "signature": "def groupAnagrams0(self, strs)" } ]
2
stack_v2_sparse_classes_30k_train_047961
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]] - def groupAnagrams0(self, strs): :type strs: List[str] :rtype: List[List[str]]
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]] - def groupAnagrams0(self, strs): :type strs: List[str] :rtype: List[List[str]] <|skeleton|> class S...
9e49b2c6003b957276737005d4aaac276b44d251
<|skeleton|> class Solution: def groupAnagrams(self, strs): """:type strs: List[str] :rtype: List[List[str]]""" <|body_0|> def groupAnagrams0(self, strs): """:type strs: List[str] :rtype: List[List[str]]""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def groupAnagrams(self, strs): """:type strs: List[str] :rtype: List[List[str]]""" res = [] tmp = [] dic = {} for word in strs: for i in range(len(word)): if word[i] in dic: dic[word[i]] += 1 else...
the_stack_v2_python_sparse
PythonCode/src/0049_Group_Anagrams.py
oneyuan/CodeforFun
train
0
7e3184d936729c96321cefcaafc285ea29012f2c
[ "self.std = std\nself.mean = mean\nself.lower_bound = None\nself.upper_bound = None", "if self.lower_bound is None and self.upper_bound is None:\n return np.random.normal(loc=self.mean, scale=self.std)\nelse:\n raise NotImplemented('Boundaries for normal distribution not implemented yet!')" ]
<|body_start_0|> self.std = std self.mean = mean self.lower_bound = None self.upper_bound = None <|end_body_0|> <|body_start_1|> if self.lower_bound is None and self.upper_bound is None: return np.random.normal(loc=self.mean, scale=self.std) else: ...
RandomGeneratorNormal
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RandomGeneratorNormal: def __init__(self, std, mean, lower_bound=None, upper_bound=None): """Constructor: Args: std: standard deviation of the normal distribution mean: mean of the normal distribution lower_bound, upper_bound: if the generated value lies outside the boundaries, a new val...
stack_v2_sparse_classes_75kplus_train_006385
1,851
no_license
[ { "docstring": "Constructor: Args: std: standard deviation of the normal distribution mean: mean of the normal distribution lower_bound, upper_bound: if the generated value lies outside the boundaries, a new value is drawn till it suffices the boundary requirement", "name": "__init__", "signature": "def...
2
stack_v2_sparse_classes_30k_train_035723
Implement the Python class `RandomGeneratorNormal` described below. Class description: Implement the RandomGeneratorNormal class. Method signatures and docstrings: - def __init__(self, std, mean, lower_bound=None, upper_bound=None): Constructor: Args: std: standard deviation of the normal distribution mean: mean of t...
Implement the Python class `RandomGeneratorNormal` described below. Class description: Implement the RandomGeneratorNormal class. Method signatures and docstrings: - def __init__(self, std, mean, lower_bound=None, upper_bound=None): Constructor: Args: std: standard deviation of the normal distribution mean: mean of t...
0d3b03d32e4f478caf8b5834116dba60518e55ee
<|skeleton|> class RandomGeneratorNormal: def __init__(self, std, mean, lower_bound=None, upper_bound=None): """Constructor: Args: std: standard deviation of the normal distribution mean: mean of the normal distribution lower_bound, upper_bound: if the generated value lies outside the boundaries, a new val...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RandomGeneratorNormal: def __init__(self, std, mean, lower_bound=None, upper_bound=None): """Constructor: Args: std: standard deviation of the normal distribution mean: mean of the normal distribution lower_bound, upper_bound: if the generated value lies outside the boundaries, a new value is drawn ti...
the_stack_v2_python_sparse
src/core/simulation/random_generator.py
LuK2019/ICNN_BA
train
1
0cf55d839fdc00177395aa24ece36a78426c8a0e
[ "files = validated_data.pop('files', [])\ninstance = self.Meta.model.objects.create(**validated_data)\nfor file in files:\n File.objects.create(file=S3Object.objects.get(pk=file['id']), room=instance)\nreturn instance", "files = validated_data.pop('files', [])\nfor file in files:\n try:\n file = File...
<|body_start_0|> files = validated_data.pop('files', []) instance = self.Meta.model.objects.create(**validated_data) for file in files: File.objects.create(file=S3Object.objects.get(pk=file['id']), room=instance) return instance <|end_body_0|> <|body_start_1|> files ...
RoomSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RoomSerializer: def create(self, validated_data): """Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room""" <|body_0|> def update(self, instance, validated_data): """Implementi...
stack_v2_sparse_classes_75kplus_train_006386
16,085
no_license
[ { "docstring": "Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Implementing the update method We extract the file...
3
stack_v2_sparse_classes_30k_train_004407
Implement the Python class `RoomSerializer` described below. Class description: Implement the RoomSerializer class. Method signatures and docstrings: - def create(self, validated_data): Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files wit...
Implement the Python class `RoomSerializer` described below. Class description: Implement the RoomSerializer class. Method signatures and docstrings: - def create(self, validated_data): Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files wit...
bef520659a7316c861933f9609b6b9ca7d9f47ac
<|skeleton|> class RoomSerializer: def create(self, validated_data): """Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room""" <|body_0|> def update(self, instance, validated_data): """Implementi...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RoomSerializer: def create(self, validated_data): """Implementing the create method We extract the files attribute from validated_data. Added added files to list of associated files with the room""" files = validated_data.pop('files', []) instance = self.Meta.model.objects.create(**val...
the_stack_v2_python_sparse
projects/serializers.py
charliephairoj/backend
train
0
899813d6c430bada0e3e38b84264c07ff6d6cb91
[ "super(LAMBOptimizer_v2, self).__init__(False, name)\nself.learning_rate = learning_rate\nself.weight_decay_rate = weight_decay_rate\nself.beta_1 = beta_1\nself.beta_2 = beta_2\nself.epsilon = epsilon\nself.exclude_from_weight_decay = exclude_from_weight_decay\nself.include_in_weight_decay = include_in_weight_decay...
<|body_start_0|> super(LAMBOptimizer_v2, self).__init__(False, name) self.learning_rate = learning_rate self.weight_decay_rate = weight_decay_rate self.beta_1 = beta_1 self.beta_2 = beta_2 self.epsilon = epsilon self.exclude_from_weight_decay = exclude_from_weight...
LAMB (Layer-wise Adaptive Moments optimizer for Batch training).
LAMBOptimizer_v2
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LAMBOptimizer_v2: """LAMB (Layer-wise Adaptive Moments optimizer for Batch training).""" def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_fro...
stack_v2_sparse_classes_75kplus_train_006387
25,398
permissive
[ { "docstring": "Constructs a LAMBOptimizer.", "name": "__init__", "signature": "def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adaptation=No...
5
stack_v2_sparse_classes_30k_test_003017
Implement the Python class `LAMBOptimizer_v2` described below. Class description: LAMB (Layer-wise Adaptive Moments optimizer for Batch training). Method signatures and docstrings: - def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, inclu...
Implement the Python class `LAMBOptimizer_v2` described below. Class description: LAMB (Layer-wise Adaptive Moments optimizer for Batch training). Method signatures and docstrings: - def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, inclu...
480c909e0835a455606e829310ff949c9dd23549
<|skeleton|> class LAMBOptimizer_v2: """LAMB (Layer-wise Adaptive Moments optimizer for Batch training).""" def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_fro...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class LAMBOptimizer_v2: """LAMB (Layer-wise Adaptive Moments optimizer for Batch training).""" def __init__(self, learning_rate, weight_decay_rate=0.0, beta_1=0.9, beta_2=0.999, epsilon=1e-06, exclude_from_weight_decay=None, include_in_weight_decay=['r_s_bias', 'r_r_bias', 'r_w_bias'], exclude_from_layer_adapt...
the_stack_v2_python_sparse
t2t_bert/optimizer/optimizer_utils.py
yyht/BERT
train
37
1f577996c98d6982d49db5e0f9d1622f8a0aac7e
[ "res = 0\na = 0\nfor i in range(32):\n if sum([n >> i & 1 for n in nums]) % 3:\n if i == 31:\n a -= 1 << i\n else:\n a |= 1 << i\nreturn a", "from collections import Counter\nnums_set = Counter(nums)\nfor k, v in nums_set.items():\n if v == 1:\n return k", "from ...
<|body_start_0|> res = 0 a = 0 for i in range(32): if sum([n >> i & 1 for n in nums]) % 3: if i == 31: a -= 1 << i else: a |= 1 << i return a <|end_body_0|> <|body_start_1|> from collections impo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def singleNumber(self, nums) -> int: """位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)""" <|body_0|> def singleNumber_sliding_window(self, nums) -> int: """滑动窗口,当窗口内只含出现一次时右移,否则左移 时间O(n) 空间O(1),存储左右指针""" <|body_...
stack_v2_sparse_classes_75kplus_train_006388
2,225
no_license
[ { "docstring": "位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)", "name": "singleNumber", "signature": "def singleNumber(self, nums) -> int" }, { "docstring": "滑动窗口,当窗口内只含出现一次时右移,否则左移 时间O(n) 空间O(1),存储左右指针", "name": "singleNumber_sliding_window", "sign...
3
stack_v2_sparse_classes_30k_train_023167
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums) -> int: 位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2) - def singleNumber_sliding_window(self, nums) -> int: 滑动...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def singleNumber(self, nums) -> int: 位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2) - def singleNumber_sliding_window(self, nums) -> int: 滑动...
c9eed637887753eb28d78cf252ea3763231e23a2
<|skeleton|> class Solution: def singleNumber(self, nums) -> int: """位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)""" <|body_0|> def singleNumber_sliding_window(self, nums) -> int: """滑动窗口,当窗口内只含出现一次时右移,否则左移 时间O(n) 空间O(1),存储左右指针""" <|body_...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def singleNumber(self, nums) -> int: """位运算,32位的二进制数字,每个位上面总和求余3,最后的结果就是只出现一次的数字 时间O(n) 空间O(1) int('0b'+''.join(a[::-1]), 2)""" res = 0 a = 0 for i in range(32): if sum([n >> i & 1 for n in nums]) % 3: if i == 31: a -= 1...
the_stack_v2_python_sparse
CODE/剑指 Offer II 004. 只出现一次的数字 .py
moshlwx/leetcode
train
5
e61060fa036ff8467775e49941a3e65d714e8539
[ "super(NeuralNetworkTestCase, self).__init__(*args, **kwargs)\nself.cnns = generate_cnn_architectures()\nself.mlps_reg = generate_mlp_architectures('reg')\nself.mlps_class = generate_mlp_architectures('class')", "for idx, nn in enumerate(nns):\n self.report('%s-%d:: #layers=%d, #edges=%d.' % (nn.nn_class, idx,...
<|body_start_0|> super(NeuralNetworkTestCase, self).__init__(*args, **kwargs) self.cnns = generate_cnn_architectures() self.mlps_reg = generate_mlp_architectures('reg') self.mlps_class = generate_mlp_architectures('class') <|end_body_0|> <|body_start_1|> for idx, nn in enumerate...
Unit tests for the NeuralNetwork test class.
NeuralNetworkTestCase
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class NeuralNetworkTestCase: """Unit tests for the NeuralNetwork test class.""" def __init__(self, *args, **kwargs): """Constructor.""" <|body_0|> def _print_path_lengths(self, nns, fwd_or_bkwd, path_length_types): """Prints the path length types.""" <|body_1|>...
stack_v2_sparse_classes_75kplus_train_006389
6,351
permissive
[ { "docstring": "Constructor.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Prints the path length types.", "name": "_print_path_lengths", "signature": "def _print_path_lengths(self, nns, fwd_or_bkwd, path_length_types)" }, { "docstrin...
5
null
Implement the Python class `NeuralNetworkTestCase` described below. Class description: Unit tests for the NeuralNetwork test class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Constructor. - def _print_path_lengths(self, nns, fwd_or_bkwd, path_length_types): Prints the path length types. ...
Implement the Python class `NeuralNetworkTestCase` described below. Class description: Unit tests for the NeuralNetwork test class. Method signatures and docstrings: - def __init__(self, *args, **kwargs): Constructor. - def _print_path_lengths(self, nns, fwd_or_bkwd, path_length_types): Prints the path length types. ...
3eef7d30bcc2e56f2221a624bd8ec7f933f81e40
<|skeleton|> class NeuralNetworkTestCase: """Unit tests for the NeuralNetwork test class.""" def __init__(self, *args, **kwargs): """Constructor.""" <|body_0|> def _print_path_lengths(self, nns, fwd_or_bkwd, path_length_types): """Prints the path length types.""" <|body_1|>...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class NeuralNetworkTestCase: """Unit tests for the NeuralNetwork test class.""" def __init__(self, *args, **kwargs): """Constructor.""" super(NeuralNetworkTestCase, self).__init__(*args, **kwargs) self.cnns = generate_cnn_architectures() self.mlps_reg = generate_mlp_architecture...
the_stack_v2_python_sparse
dragonfly/nn/unittest_neural_network.py
dragonfly/dragonfly
train
868
e3cdd6449c6652fe070a5e258973c4cf68ef85e5
[ "testcases: List[TestCase] = TestCase.query.all()\nres = [{'id': testcase.id, 'name': testcase.name, 'description': testcase.description, 'steps': json.loads(testcase.steps)} for testcase in testcases]\nreturn {'body': res}", "testcase = TestCase(name=request.json.get('name'), description=request.json.get('descri...
<|body_start_0|> testcases: List[TestCase] = TestCase.query.all() res = [{'id': testcase.id, 'name': testcase.name, 'description': testcase.description, 'steps': json.loads(testcase.steps)} for testcase in testcases] return {'body': res} <|end_body_0|> <|body_start_1|> testcase = TestCa...
TestCaseService
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestCaseService: def get(self): """测试用例的浏览获取 /testcase.json /testcase.json?id=1""" <|body_0|> def post(self): """上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}""" <|body_1|> <|end_skeleton|> <|body_start_0|> testcases: L...
stack_v2_sparse_classes_75kplus_train_006390
4,613
no_license
[ { "docstring": "测试用例的浏览获取 /testcase.json /testcase.json?id=1", "name": "get", "signature": "def get(self)" }, { "docstring": "上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}", "name": "post", "signature": "def post(self)" } ]
2
stack_v2_sparse_classes_30k_train_042347
Implement the Python class `TestCaseService` described below. Class description: Implement the TestCaseService class. Method signatures and docstrings: - def get(self): 测试用例的浏览获取 /testcase.json /testcase.json?id=1 - def post(self): 上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}
Implement the Python class `TestCaseService` described below. Class description: Implement the TestCaseService class. Method signatures and docstrings: - def get(self): 测试用例的浏览获取 /testcase.json /testcase.json?id=1 - def post(self): 上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []} <|skeleto...
bd8bce8160c458bf49970dbf94dadb3c822fdd53
<|skeleton|> class TestCaseService: def get(self): """测试用例的浏览获取 /testcase.json /testcase.json?id=1""" <|body_0|> def post(self): """上传用例, 更新用例 /testcase.json {'name': 'xx', 'description': 'xxx', 'steps': []}""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class TestCaseService: def get(self): """测试用例的浏览获取 /testcase.json /testcase.json?id=1""" testcases: List[TestCase] = TestCase.query.all() res = [{'id': testcase.id, 'name': testcase.name, 'description': testcase.description, 'steps': json.loads(testcase.steps)} for testcase in testcases] ...
the_stack_v2_python_sparse
platform/src/backend.py
baihongliang/HogwartsLG4
train
0
99c426825645e581d9cb83d07fadccc5bdf954a8
[ "self.tracker_store = tracker_store\nif strategy not in MarkerTrackerLoader._STRATEGY_MAP:\n raise RasaException(f\"Invalid strategy for loading markers - '{strategy}' was given, options 'all', 'sample_n', or 'first_n' exist.\")\nself.strategy = MarkerTrackerLoader._STRATEGY_MAP[strategy]\nif str...
<|body_start_0|> self.tracker_store = tracker_store if strategy not in MarkerTrackerLoader._STRATEGY_MAP: raise RasaException(f"Invalid strategy for loading markers - '{strategy}' was given, options 'all', 'sample_n', or 'first_n' exist.") self.strategy = MarkerTracke...
Represents a wrapper over a `TrackerStore` with a configurable access pattern.
MarkerTrackerLoader
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MarkerTrackerLoader: """Represents a wrapper over a `TrackerStore` with a configurable access pattern.""" def __init__(self, tracker_store: TrackerStore, strategy: str, count: int=None, seed: Any=None) -> None: """Creates a MarkerTrackerLoader. Args: tracker_store: The underlying tra...
stack_v2_sparse_classes_75kplus_train_006391
3,658
permissive
[ { "docstring": "Creates a MarkerTrackerLoader. Args: tracker_store: The underlying tracker store to access. strategy: The strategy to use for selecting trackers, can be 'all', 'sample_n', or 'first_n'. count: Number of trackers to return, can only be None if strategy is 'all'. seed: Optional seed to set up rand...
2
stack_v2_sparse_classes_30k_train_029774
Implement the Python class `MarkerTrackerLoader` described below. Class description: Represents a wrapper over a `TrackerStore` with a configurable access pattern. Method signatures and docstrings: - def __init__(self, tracker_store: TrackerStore, strategy: str, count: int=None, seed: Any=None) -> None: Creates a Mar...
Implement the Python class `MarkerTrackerLoader` described below. Class description: Represents a wrapper over a `TrackerStore` with a configurable access pattern. Method signatures and docstrings: - def __init__(self, tracker_store: TrackerStore, strategy: str, count: int=None, seed: Any=None) -> None: Creates a Mar...
50857610bdf0c26dc61f3203a6cbb4bcf193768c
<|skeleton|> class MarkerTrackerLoader: """Represents a wrapper over a `TrackerStore` with a configurable access pattern.""" def __init__(self, tracker_store: TrackerStore, strategy: str, count: int=None, seed: Any=None) -> None: """Creates a MarkerTrackerLoader. Args: tracker_store: The underlying tra...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MarkerTrackerLoader: """Represents a wrapper over a `TrackerStore` with a configurable access pattern.""" def __init__(self, tracker_store: TrackerStore, strategy: str, count: int=None, seed: Any=None) -> None: """Creates a MarkerTrackerLoader. Args: tracker_store: The underlying tracker store to...
the_stack_v2_python_sparse
rasa/core/evaluation/marker_tracker_loader.py
RasaHQ/rasa
train
13,167
97c8f9bf93a7fb14a83ce34d692cfce38d97cca4
[ "self.media_markers = media_markers\nself.caption_marker = caption_marker\nself.captions = {}", "for pair1, pair2 in _bigrams(entry):\n marker1, content1 = pair1\n marker2, content2 = pair2\n if marker1 in self.media_markers and marker2 == self.caption_marker:\n for file_id in re.split('\\\\s*;\\\...
<|body_start_0|> self.media_markers = media_markers self.caption_marker = caption_marker self.captions = {} <|end_body_0|> <|body_start_1|> for pair1, pair2 in _bigrams(entry): marker1, content1 = pair1 marker2, content2 = pair2 if marker1 in self.med...
Visitor, which links captions to media files. It looks for SFM markers containing file names and checks if the adjacent marker contains a caption.
CaptionFinder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CaptionFinder: """Visitor, which links captions to media files. It looks for SFM markers containing file names and checks if the adjacent marker contains a caption.""" def __init__(self, media_markers, caption_marker): """Create a caption finder. :args media_markers: markers, which c...
stack_v2_sparse_classes_75kplus_train_006392
44,273
permissive
[ { "docstring": "Create a caption finder. :args media_markers: markers, which contain media file names. :args caption_marker: marker, which contains the caption.", "name": "__init__", "signature": "def __init__(self, media_markers, caption_marker)" }, { "docstring": "Extract captions for media fi...
2
stack_v2_sparse_classes_30k_train_012456
Implement the Python class `CaptionFinder` described below. Class description: Visitor, which links captions to media files. It looks for SFM markers containing file names and checks if the adjacent marker contains a caption. Method signatures and docstrings: - def __init__(self, media_markers, caption_marker): Creat...
Implement the Python class `CaptionFinder` described below. Class description: Visitor, which links captions to media files. It looks for SFM markers containing file names and checks if the adjacent marker contains a caption. Method signatures and docstrings: - def __init__(self, media_markers, caption_marker): Creat...
9fcb35608ab7ce0df3f02a88aba893ce3920e48a
<|skeleton|> class CaptionFinder: """Visitor, which links captions to media files. It looks for SFM markers containing file names and checks if the adjacent marker contains a caption.""" def __init__(self, media_markers, caption_marker): """Create a caption finder. :args media_markers: markers, which c...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class CaptionFinder: """Visitor, which links captions to media files. It looks for SFM markers containing file names and checks if the adjacent marker contains a caption.""" def __init__(self, media_markers, caption_marker): """Create a caption finder. :args media_markers: markers, which contain media ...
the_stack_v2_python_sparse
src/pydictionaria/sfm2cldf.py
dictionaria/pydictionaria
train
1
ea214665bbfa3a89fd1e851fc3802d4bdecabf03
[ "vz_id = Register.objects.filter(access_token=validated_data.get('access_token')).values('vz_id')[0]\nticket_id = str(random.randint(100000, 999999))\nuser_details = Register.objects.filter(vz_id=vz_id).values('firstname', 'lastname', 'email', 'phone')\nreturn Create_ticket.objects.create(access_token=validated_dat...
<|body_start_0|> vz_id = Register.objects.filter(access_token=validated_data.get('access_token')).values('vz_id')[0] ticket_id = str(random.randint(100000, 999999)) user_details = Register.objects.filter(vz_id=vz_id).values('firstname', 'lastname', 'email', 'phone') return Create_ticket....
Create_ticketSerializer
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Create_ticketSerializer: def create(self, validated_data): """Create and return a new `Snippet` instance, given the validated data.""" <|body_0|> def update(self, instance, validated_data): """Update and return an existing `Snippet` instance, given the validated data...
stack_v2_sparse_classes_75kplus_train_006393
2,718
no_license
[ { "docstring": "Create and return a new `Snippet` instance, given the validated data.", "name": "create", "signature": "def create(self, validated_data)" }, { "docstring": "Update and return an existing `Snippet` instance, given the validated data.", "name": "update", "signature": "def u...
2
null
Implement the Python class `Create_ticketSerializer` described below. Class description: Implement the Create_ticketSerializer class. Method signatures and docstrings: - def create(self, validated_data): Create and return a new `Snippet` instance, given the validated data. - def update(self, instance, validated_data)...
Implement the Python class `Create_ticketSerializer` described below. Class description: Implement the Create_ticketSerializer class. Method signatures and docstrings: - def create(self, validated_data): Create and return a new `Snippet` instance, given the validated data. - def update(self, instance, validated_data)...
ed0185f36e274d46f978a8f670a4189571280e8b
<|skeleton|> class Create_ticketSerializer: def create(self, validated_data): """Create and return a new `Snippet` instance, given the validated data.""" <|body_0|> def update(self, instance, validated_data): """Update and return an existing `Snippet` instance, given the validated data...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Create_ticketSerializer: def create(self, validated_data): """Create and return a new `Snippet` instance, given the validated data.""" vz_id = Register.objects.filter(access_token=validated_data.get('access_token')).values('vz_id')[0] ticket_id = str(random.randint(100000, 999999)) ...
the_stack_v2_python_sparse
create_ticket/serializers.py
poojapauskar/vzcards-api
train
0
55eea3aaf121ea18496291a3d3b6eb817090e4d7
[ "self.A = linear_system.A\nself.subB = linear_system.subB\nself.Q = linear_system.q_system\nself.R = linear_system.r_system\nself.success_rates = success_rates\nself.adaptive = adaptive\ninput_matrix_list = []\nfor b, p in zip(self.subB, self.success_rates):\n input_matrix_list.append(b * p)\ninput_matrix = bloc...
<|body_start_0|> self.A = linear_system.A self.subB = linear_system.subB self.Q = linear_system.q_system self.R = linear_system.r_system self.success_rates = success_rates self.adaptive = adaptive input_matrix_list = [] for b, p in zip(self.subB, self.succ...
AdaptiveLinearController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class AdaptiveLinearController: def __init__(self, linear_system, success_rates, adaptive): """This is a class for an adaptive linear quadratic controller, with independent success rates for each actuator dynamic. Parameters ---------- linear_system: class Associated linear system according to...
stack_v2_sparse_classes_75kplus_train_006394
9,949
permissive
[ { "docstring": "This is a class for an adaptive linear quadratic controller, with independent success rates for each actuator dynamic. Parameters ---------- linear_system: class Associated linear system according to the class LinearSystem. success_rates: iterable float Specified success rates for each controlle...
3
stack_v2_sparse_classes_30k_train_008573
Implement the Python class `AdaptiveLinearController` described below. Class description: Implement the AdaptiveLinearController class. Method signatures and docstrings: - def __init__(self, linear_system, success_rates, adaptive): This is a class for an adaptive linear quadratic controller, with independent success ...
Implement the Python class `AdaptiveLinearController` described below. Class description: Implement the AdaptiveLinearController class. Method signatures and docstrings: - def __init__(self, linear_system, success_rates, adaptive): This is a class for an adaptive linear quadratic controller, with independent success ...
2a82b374a778bbee57b0e5f5abd82b05f1430de2
<|skeleton|> class AdaptiveLinearController: def __init__(self, linear_system, success_rates, adaptive): """This is a class for an adaptive linear quadratic controller, with independent success rates for each actuator dynamic. Parameters ---------- linear_system: class Associated linear system according to...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class AdaptiveLinearController: def __init__(self, linear_system, success_rates, adaptive): """This is a class for an adaptive linear quadratic controller, with independent success rates for each actuator dynamic. Parameters ---------- linear_system: class Associated linear system according to the class Lin...
the_stack_v2_python_sparse
pb_cown/system_env/system_models.py
aredder/Control-over-Wireless-Networks
train
0
56b8e0ab214fcf659ace619310e571064096ec9e
[ "n = len(a)\ntotalSum = sum(a)\nif k >= n:\n return totalSum\nwindowSize = n - k\nr, windowSum = (n - k - 1, 0)\nfor i in range(0, r + 1):\n windowSum += a[i]\nres = totalSum - windowSum\nfor l in range(1, n):\n windowSum -= a[l - 1]\n r += 1\n if r == n:\n break\n windowSum += a[r]\n re...
<|body_start_0|> n = len(a) totalSum = sum(a) if k >= n: return totalSum windowSize = n - k r, windowSum = (n - k - 1, 0) for i in range(0, r + 1): windowSum += a[i] res = totalSum - windowSum for l in range(1, n): windo...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def maxScore(self, a: List[int], k: int) -> int: """total sum = a[0] + a[1] + ... + a[n - 1] if k >= n: return total sum else: leftSum = a[0] + a[1] + ... + a[i - 1] rightSum = a[j + 1] + a[j + 2] + ... + a[n - 1] where a[i], a[i + 1], ..., a[j] is the card we cannot take and d...
stack_v2_sparse_classes_75kplus_train_006395
3,034
no_license
[ { "docstring": "total sum = a[0] + a[1] + ... + a[n - 1] if k >= n: return total sum else: leftSum = a[0] + a[1] + ... + a[i - 1] rightSum = a[j + 1] + a[j + 2] + ... + a[n - 1] where a[i], a[i + 1], ..., a[j] is the card we cannot take and dis = (j - i + 1) = n - k res = max(total sum - (leftSum + rightSum)) =...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxScore(self, a: List[int], k: int) -> int: total sum = a[0] + a[1] + ... + a[n - 1] if k >= n: return total sum else: leftSum = a[0] + a[1] + ... + a[i - 1] rightSum = a[j ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def maxScore(self, a: List[int], k: int) -> int: total sum = a[0] + a[1] + ... + a[n - 1] if k >= n: return total sum else: leftSum = a[0] + a[1] + ... + a[i - 1] rightSum = a[j ...
31f7f730227a0e10951e7468bad1b995cf2eafcb
<|skeleton|> class Solution: def maxScore(self, a: List[int], k: int) -> int: """total sum = a[0] + a[1] + ... + a[n - 1] if k >= n: return total sum else: leftSum = a[0] + a[1] + ... + a[i - 1] rightSum = a[j + 1] + a[j + 2] + ... + a[n - 1] where a[i], a[i + 1], ..., a[j] is the card we cannot take and d...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class Solution: def maxScore(self, a: List[int], k: int) -> int: """total sum = a[0] + a[1] + ... + a[n - 1] if k >= n: return total sum else: leftSum = a[0] + a[1] + ... + a[i - 1] rightSum = a[j + 1] + a[j + 2] + ... + a[n - 1] where a[i], a[i + 1], ..., a[j] is the card we cannot take and dis = (j - i + ...
the_stack_v2_python_sparse
from Stephen/google list/1423. Maximum Points You Can Obtain from Cards(once TLE).py
kanglicheng/CodeBreakersCode
train
0
1584e4b608a56cdf5878586b4b876b72c42d2fba
[ "key = self._chooseName('', reg)\nself[key] = reg\nreturn key", "if not name:\n name = reg.__class__.__name__\ni = 1\nchosenName = name\nwhile chosenName in self:\n i += 1\n chosenName = name + str(i)\nreturn chosenName" ]
<|body_start_0|> key = self._chooseName('', reg) self[key] = reg return key <|end_body_0|> <|body_start_1|> if not name: name = reg.__class__.__name__ i = 1 chosenName = name while chosenName in self: i += 1 chosenName = name +...
Registration manager Manages registrations within a package.
RegistrationManager
[ "ZPL-2.1", "Python-2.0", "ICU", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "ZPL-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RegistrationManager: """Registration manager Manages registrations within a package.""" def addRegistration(self, reg): """See IWriteContainer""" <|body_0|> def _chooseName(self, name, reg): """Choose a name for the registration.""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_75kplus_train_006396
9,659
permissive
[ { "docstring": "See IWriteContainer", "name": "addRegistration", "signature": "def addRegistration(self, reg)" }, { "docstring": "Choose a name for the registration.", "name": "_chooseName", "signature": "def _chooseName(self, name, reg)" } ]
2
stack_v2_sparse_classes_30k_train_006605
Implement the Python class `RegistrationManager` described below. Class description: Registration manager Manages registrations within a package. Method signatures and docstrings: - def addRegistration(self, reg): See IWriteContainer - def _chooseName(self, name, reg): Choose a name for the registration.
Implement the Python class `RegistrationManager` described below. Class description: Registration manager Manages registrations within a package. Method signatures and docstrings: - def addRegistration(self, reg): See IWriteContainer - def _chooseName(self, name, reg): Choose a name for the registration. <|skeleton|...
4c538584703754c956ca66392fdcecf0a0ca2314
<|skeleton|> class RegistrationManager: """Registration manager Manages registrations within a package.""" def addRegistration(self, reg): """See IWriteContainer""" <|body_0|> def _chooseName(self, name, reg): """Choose a name for the registration.""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class RegistrationManager: """Registration manager Manages registrations within a package.""" def addRegistration(self, reg): """See IWriteContainer""" key = self._chooseName('', reg) self[key] = reg return key def _chooseName(self, name, reg): """Choose a name for ...
the_stack_v2_python_sparse
CMS/Zope-3.2.1/Dependencies/zope.app-Zope-3.2.1/zope.app/component/registration.py
germanfriday/code-examples-sandbox
train
0
194eab8f4d0e39ebf8f755c2e3183c68e41c6d45
[ "key_list = list()\nfor _ in range(3):\n keypair = self.create_keypair()\n keypair.pop('private_key')\n keypair.pop('user_id')\n key_list.append(keypair)\nfetched_list = self.keypairs_client.list_keypairs()['keypairs']\nnew_list = list()\nfor keypair in fetched_list:\n new_list.append(keypair['keypai...
<|body_start_0|> key_list = list() for _ in range(3): keypair = self.create_keypair() keypair.pop('private_key') keypair.pop('user_id') key_list.append(keypair) fetched_list = self.keypairs_client.list_keypairs()['keypairs'] new_list = list...
Test keypairs API with compute microversion less than 2.2
KeyPairsV2TestJSON
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KeyPairsV2TestJSON: """Test keypairs API with compute microversion less than 2.2""" def test_keypairs_create_list_delete(self): """Test create/list/delete keypairs Keypairs created should be available in the response list""" <|body_0|> def test_keypair_create_delete(self...
stack_v2_sparse_classes_75kplus_train_006397
4,286
permissive
[ { "docstring": "Test create/list/delete keypairs Keypairs created should be available in the response list", "name": "test_keypairs_create_list_delete", "signature": "def test_keypairs_create_list_delete(self)" }, { "docstring": "Test create/delete keypair", "name": "test_keypair_create_dele...
4
stack_v2_sparse_classes_30k_train_023609
Implement the Python class `KeyPairsV2TestJSON` described below. Class description: Test keypairs API with compute microversion less than 2.2 Method signatures and docstrings: - def test_keypairs_create_list_delete(self): Test create/list/delete keypairs Keypairs created should be available in the response list - def...
Implement the Python class `KeyPairsV2TestJSON` described below. Class description: Test keypairs API with compute microversion less than 2.2 Method signatures and docstrings: - def test_keypairs_create_list_delete(self): Test create/list/delete keypairs Keypairs created should be available in the response list - def...
3932a799e620a20d7abf7b89e21b520683a1809b
<|skeleton|> class KeyPairsV2TestJSON: """Test keypairs API with compute microversion less than 2.2""" def test_keypairs_create_list_delete(self): """Test create/list/delete keypairs Keypairs created should be available in the response list""" <|body_0|> def test_keypair_create_delete(self...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class KeyPairsV2TestJSON: """Test keypairs API with compute microversion less than 2.2""" def test_keypairs_create_list_delete(self): """Test create/list/delete keypairs Keypairs created should be available in the response list""" key_list = list() for _ in range(3): keypair...
the_stack_v2_python_sparse
tempest/api/compute/keypairs/test_keypairs.py
openstack/tempest
train
270
477a0c6f480895d2ba1428305ab944968e0ea14d
[ "self.__bit = BIT(n)\nself.__lookup = {i: i + 1 for i in range(n)}\nself.__curr = n", "pos = self.__bit.binary_lift(k)\nval = self.__lookup.pop(pos)\nself.__bit.add(pos, -1)\nself.__bit.add(self.__curr, 1)\nself.__lookup[self.__curr] = val\nself.__curr += 1\nreturn val" ]
<|body_start_0|> self.__bit = BIT(n) self.__lookup = {i: i + 1 for i in range(n)} self.__curr = n <|end_body_0|> <|body_start_1|> pos = self.__bit.binary_lift(k) val = self.__lookup.pop(pos) self.__bit.add(pos, -1) self.__bit.add(self.__curr, 1) self.__lo...
MRUQueue2
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MRUQueue2: def __init__(self, n): """:type n: int""" <|body_0|> def fetch(self, k): """:type k: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.__bit = BIT(n) self.__lookup = {i: i + 1 for i in range(n)} self.__c...
stack_v2_sparse_classes_75kplus_train_006398
5,194
no_license
[ { "docstring": ":type n: int", "name": "__init__", "signature": "def __init__(self, n)" }, { "docstring": ":type k: int :rtype: int", "name": "fetch", "signature": "def fetch(self, k)" } ]
2
null
Implement the Python class `MRUQueue2` described below. Class description: Implement the MRUQueue2 class. Method signatures and docstrings: - def __init__(self, n): :type n: int - def fetch(self, k): :type k: int :rtype: int
Implement the Python class `MRUQueue2` described below. Class description: Implement the MRUQueue2 class. Method signatures and docstrings: - def __init__(self, n): :type n: int - def fetch(self, k): :type k: int :rtype: int <|skeleton|> class MRUQueue2: def __init__(self, n): """:type n: int""" ...
810575368ecffa97677bdb51744d1f716140bbb1
<|skeleton|> class MRUQueue2: def __init__(self, n): """:type n: int""" <|body_0|> def fetch(self, k): """:type k: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class MRUQueue2: def __init__(self, n): """:type n: int""" self.__bit = BIT(n) self.__lookup = {i: i + 1 for i in range(n)} self.__curr = n def fetch(self, k): """:type k: int :rtype: int""" pos = self.__bit.binary_lift(k) val = self.__lookup.pop(pos) ...
the_stack_v2_python_sparse
D/DesignMostRecentlyUsedQueue.py
bssrdf/pyleet
train
2
7c1f032ccb30f943e5d04d80e7adbd5448b38a3c
[ "queryset = NewUser.objects.all().filter(is_veterinary=True)\nserializer = VeterinaryUserSerializer(queryset, many=True)\nreturn Response(serializer.data)", "queryset = NewUser.objects.all().filter(is_veterinary=True)\nuser = get_object_or_404(queryset, pk=pk)\nserializer = VeterinaryUserSerializer(user)\nreturn ...
<|body_start_0|> queryset = NewUser.objects.all().filter(is_veterinary=True) serializer = VeterinaryUserSerializer(queryset, many=True) return Response(serializer.data) <|end_body_0|> <|body_start_1|> queryset = NewUser.objects.all().filter(is_veterinary=True) user = get_object_...
View que retorna informações de usuários veterináriso
VeterinaryUserView
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class VeterinaryUserView: """View que retorna informações de usuários veterináriso""" def list(self, request): """Retorna a lista de usuários veterinários""" <|body_0|> def retrieve(self, request, pk=None): """Retorna um usuário veterinário específico""" <|body...
stack_v2_sparse_classes_75kplus_train_006399
4,671
no_license
[ { "docstring": "Retorna a lista de usuários veterinários", "name": "list", "signature": "def list(self, request)" }, { "docstring": "Retorna um usuário veterinário específico", "name": "retrieve", "signature": "def retrieve(self, request, pk=None)" }, { "docstring": "Cria um usuá...
3
null
Implement the Python class `VeterinaryUserView` described below. Class description: View que retorna informações de usuários veterináriso Method signatures and docstrings: - def list(self, request): Retorna a lista de usuários veterinários - def retrieve(self, request, pk=None): Retorna um usuário veterinário específ...
Implement the Python class `VeterinaryUserView` described below. Class description: View que retorna informações de usuários veterináriso Method signatures and docstrings: - def list(self, request): Retorna a lista de usuários veterinários - def retrieve(self, request, pk=None): Retorna um usuário veterinário específ...
4ee69ab46a33c326bf41fca5b9fe0d6746ce683d
<|skeleton|> class VeterinaryUserView: """View que retorna informações de usuários veterináriso""" def list(self, request): """Retorna a lista de usuários veterinários""" <|body_0|> def retrieve(self, request, pk=None): """Retorna um usuário veterinário específico""" <|body...
stack_v2_sparse_classes_75kplus
data/stack_v2_sparse_classes_30k
75,829
class VeterinaryUserView: """View que retorna informações de usuários veterináriso""" def list(self, request): """Retorna a lista de usuários veterinários""" queryset = NewUser.objects.all().filter(is_veterinary=True) serializer = VeterinaryUserSerializer(queryset, many=True) re...
the_stack_v2_python_sparse
manage_users/views.py
gomeslucasm/Backend_canil
train
1