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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d184f43ace6aed4cafc1c44e3e9997b24506c9d6 | [
"if not nums:\n return None\nmaxnum = nums[0]\ndp = [0] * len(nums)\ndp[0] = nums[0]\nfor i in range(1, len(nums)):\n dp[i] = nums[i] + dp[i - 1] if dp[i - 1] > 0 else nums[i]\n maxnum = max(dp[i], maxnum)\nreturn maxnum",
"if not nums:\n return None\nmaxnum = nums[0]\nmaxendwithi = nums[0]\nfor i in ... | <|body_start_0|>
if not nums:
return None
maxnum = nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = nums[i] + dp[i - 1] if dp[i - 1] > 0 else nums[i]
maxnum = max(dp[i], maxnum)
return maxnum
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070200 | 1,035 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],",
"name": "maxSubArray2",
"signature": "def maxSubArray2(self, nums... | 2 | stack_v2_sparse_classes_30k_train_042904 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4], | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int [-2,1,-3,4,-1,2,1,-5,4],"""
if not nums:
return None
maxnum = nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = nums[i] + dp[i - ... | the_stack_v2_python_sparse | src/maxSubArray.py | jsdiuf/leetcode | train | 1 | |
b23a4f10e6832228d0190d82263907644be4854b | [
"self.q = q\nself.eps = epsilon\nself.eps_iter = step_size\nself.nb_iter = num_iter\nself.num_classes = num_classes\nlogging.info('L1 CONFIG CREATION: %s', self.__dict__)",
"y_onehot = tf.reshape(tf.one_hot(y, self.num_classes), [-1, self.num_classes])\nadv_x = x\nif random_start:\n perturb = utils_tf.random_l... | <|body_start_0|>
self.q = q
self.eps = epsilon
self.eps_iter = step_size
self.nb_iter = num_iter
self.num_classes = num_classes
logging.info('L1 CONFIG CREATION: %s', self.__dict__)
<|end_body_0|>
<|body_start_1|>
y_onehot = tf.reshape(tf.one_hot(y, self.num_clas... | A wrapper for the SparseL1Attack from Cleverhans. | SparseL1Attack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseL1Attack:
"""A wrapper for the SparseL1Attack from Cleverhans."""
def __init__(self, num_iter, epsilon, step_size, q, num_classes):
"""Constructs an Attack object wrapping the SparseL1Attack from Cleverhans. Args: num_iter: Number of iterations to run the attack. epsilon: The e... | stack_v2_sparse_classes_75kplus_train_070201 | 9,538 | permissive | [
{
"docstring": "Constructs an Attack object wrapping the SparseL1Attack from Cleverhans. Args: num_iter: Number of iterations to run the attack. epsilon: The epsilon ball to clip to. step_size: The step size for the attack. q: Sparsity of the gradient update step in percent. Gradient values larger than this per... | 2 | stack_v2_sparse_classes_30k_train_040679 | Implement the Python class `SparseL1Attack` described below.
Class description:
A wrapper for the SparseL1Attack from Cleverhans.
Method signatures and docstrings:
- def __init__(self, num_iter, epsilon, step_size, q, num_classes): Constructs an Attack object wrapping the SparseL1Attack from Cleverhans. Args: num_ite... | Implement the Python class `SparseL1Attack` described below.
Class description:
A wrapper for the SparseL1Attack from Cleverhans.
Method signatures and docstrings:
- def __init__(self, num_iter, epsilon, step_size, q, num_classes): Constructs an Attack object wrapping the SparseL1Attack from Cleverhans. Args: num_ite... | aaa9d3e4733f3b551823b86f67cf8a572acfeb7d | <|skeleton|>
class SparseL1Attack:
"""A wrapper for the SparseL1Attack from Cleverhans."""
def __init__(self, num_iter, epsilon, step_size, q, num_classes):
"""Constructs an Attack object wrapping the SparseL1Attack from Cleverhans. Args: num_iter: Number of iterations to run the attack. epsilon: The e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparseL1Attack:
"""A wrapper for the SparseL1Attack from Cleverhans."""
def __init__(self, num_iter, epsilon, step_size, q, num_classes):
"""Constructs an Attack object wrapping the SparseL1Attack from Cleverhans. Args: num_iter: Number of iterations to run the attack. epsilon: The epsilon ball t... | the_stack_v2_python_sparse | research/multi_representation_adversary/multi_representation_adversary/attacks.py | jango-blockchained/neural-structured-learning | train | 0 |
1fa931797f1feb2ffd1470afa62aeaff5aa9f853 | [
"if not request.user.has_perm('Groups.group_user_in_group'):\n return HttpResponseForbidden()\ngroup = group_backend.get(service=request.user, name=name)\nuser = user_backend.get(username=subname)\nif group_backend.is_member(group=group, user=user):\n return HttpResponseNoContent()\nelse:\n raise UserNotFo... | <|body_start_0|>
if not request.user.has_perm('Groups.group_user_in_group'):
return HttpResponseForbidden()
group = group_backend.get(service=request.user, name=name)
user = user_backend.get(username=subname)
if group_backend.is_member(group=group, user=user):
ret... | Handle requests to ``/groups/<group>/users/<user>/``. | GroupUserHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupUserHandler:
"""Handle requests to ``/groups/<group>/users/<user>/``."""
def get(self, request, largs, name, subname):
"""Verify that a user is in a group."""
<|body_0|>
def delete(self, request, largs, name, subname):
"""Remove a user from a group."""
... | stack_v2_sparse_classes_75kplus_train_070202 | 9,051 | no_license | [
{
"docstring": "Verify that a user is in a group.",
"name": "get",
"signature": "def get(self, request, largs, name, subname)"
},
{
"docstring": "Remove a user from a group.",
"name": "delete",
"signature": "def delete(self, request, largs, name, subname)"
}
] | 2 | null | Implement the Python class `GroupUserHandler` described below.
Class description:
Handle requests to ``/groups/<group>/users/<user>/``.
Method signatures and docstrings:
- def get(self, request, largs, name, subname): Verify that a user is in a group.
- def delete(self, request, largs, name, subname): Remove a user f... | Implement the Python class `GroupUserHandler` described below.
Class description:
Handle requests to ``/groups/<group>/users/<user>/``.
Method signatures and docstrings:
- def get(self, request, largs, name, subname): Verify that a user is in a group.
- def delete(self, request, largs, name, subname): Remove a user f... | 60769f6b4965836b2220878cfa2e1bc403d8f8a3 | <|skeleton|>
class GroupUserHandler:
"""Handle requests to ``/groups/<group>/users/<user>/``."""
def get(self, request, largs, name, subname):
"""Verify that a user is in a group."""
<|body_0|>
def delete(self, request, largs, name, subname):
"""Remove a user from a group."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupUserHandler:
"""Handle requests to ``/groups/<group>/users/<user>/``."""
def get(self, request, largs, name, subname):
"""Verify that a user is in a group."""
if not request.user.has_perm('Groups.group_user_in_group'):
return HttpResponseForbidden()
group = group_... | the_stack_v2_python_sparse | env/lib/python3.6/site-packages/RestAuth/Groups/views.py | sachinlokesh05/login-registration-forgotpassword-and-resetpassword-using-django-rest-framework- | train | 3 |
97b804d172bd91582e35b5d6897bbe44f6130447 | [
"self.request = request\nself.template = template\nself.tpl_vars = tpl_vars\nself.ajax_request = ajax_request\nself.user = user\nself.admin_view = admin_view\nself.public_view = request.user.is_anonymous()\nself.brand = self.user and self.user.brand",
"if self.user:\n self.tpl_vars['page_user_prof'] = self.use... | <|body_start_0|>
self.request = request
self.template = template
self.tpl_vars = tpl_vars
self.ajax_request = ajax_request
self.user = user
self.admin_view = admin_view
self.public_view = request.user.is_anonymous()
self.brand = self.user and self.user.bra... | The base class for all other widgets. This class exposes a method :meth:`debra.widgets.Widget.render` for rendering of itself. | Widget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Widget:
"""The base class for all other widgets. This class exposes a method :meth:`debra.widgets.Widget.render` for rendering of itself."""
def __init__(self, request, template, tpl_vars={}, ajax_request=False, user=None, admin_view=False):
""":param request: an ``HttpRequest`` inst... | stack_v2_sparse_classes_75kplus_train_070203 | 25,658 | no_license | [
{
"docstring": ":param request: an ``HttpRequest`` instance :param template: the path to the template file for this **Widget**. :param tpl_vars: a ``dict`` of variables to render the ``template`` with :param ajax_request: is this **Widget** being rendered in an ajax request or should we render it to a string to... | 2 | null | Implement the Python class `Widget` described below.
Class description:
The base class for all other widgets. This class exposes a method :meth:`debra.widgets.Widget.render` for rendering of itself.
Method signatures and docstrings:
- def __init__(self, request, template, tpl_vars={}, ajax_request=False, user=None, a... | Implement the Python class `Widget` described below.
Class description:
The base class for all other widgets. This class exposes a method :meth:`debra.widgets.Widget.render` for rendering of itself.
Method signatures and docstrings:
- def __init__(self, request, template, tpl_vars={}, ajax_request=False, user=None, a... | 2f15c4ddd8bbb112c407d222ae48746b626c674f | <|skeleton|>
class Widget:
"""The base class for all other widgets. This class exposes a method :meth:`debra.widgets.Widget.render` for rendering of itself."""
def __init__(self, request, template, tpl_vars={}, ajax_request=False, user=None, admin_view=False):
""":param request: an ``HttpRequest`` inst... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Widget:
"""The base class for all other widgets. This class exposes a method :meth:`debra.widgets.Widget.render` for rendering of itself."""
def __init__(self, request, template, tpl_vars={}, ajax_request=False, user=None, admin_view=False):
""":param request: an ``HttpRequest`` instance :param t... | the_stack_v2_python_sparse | Projects/miami_metro/debra/widgets.py | TopWebGhost/Angular-Influencer | train | 1 |
8575e306afee80a72b3b276a6f971bbdcb27d071 | [
"self.rawdata = {}\nf = open(filename, 'r')\nheader = f.readline().strip().split(',')\nfor line in f:\n items = line.strip().split(',')\n date = re.match('(\\\\d\\\\d\\\\d\\\\d)(\\\\d\\\\d)(\\\\d\\\\d)', items[header.index('DATE')])\n year = int(date.group(1))\n month = int(date.group(2))\n day = int... | <|body_start_0|>
self.rawdata = {}
f = open(filename, 'r')
header = f.readline().strip().split(',')
for line in f:
items = line.strip().split(',')
date = re.match('(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)', items[header.index('DATE')])
year = int(date.group(1))
... | The collection of temperature records loaded from given csv file | Climate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Climate:
"""The collection of temperature records loaded from given csv file"""
def __init__(self, filename):
"""Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)"""
... | stack_v2_sparse_classes_75kplus_train_070204 | 19,842 | permissive | [
{
"docstring": "Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Get the daily temperatures for t... | 3 | stack_v2_sparse_classes_30k_train_044579 | Implement the Python class `Climate` described below.
Class description:
The collection of temperature records loaded from given csv file
Method signatures and docstrings:
- def __init__(self, filename): Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by file... | Implement the Python class `Climate` described below.
Class description:
The collection of temperature records loaded from given csv file
Method signatures and docstrings:
- def __init__(self, filename): Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by file... | 19295613460265cf01561d6229bea290c59a5247 | <|skeleton|>
class Climate:
"""The collection of temperature records loaded from given csv file"""
def __init__(self, filename):
"""Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Climate:
"""The collection of temperature records loaded from given csv file"""
def __init__(self, filename):
"""Initialize a Climate instance, which stores the temperature records loaded from a given csv file specified by filename. Args: filename: name of the csv file (str)"""
self.rawda... | the_stack_v2_python_sparse | 6.0002/problem_sets/ps5/ps5.py | Haplo-Dragon/MIT | train | 0 |
08cfb894160af5e8947367b6a643fef33adb84f6 | [
"self.nodes = []\nself.node_domains = {}\nself.unary_constraints = {}\nself.binary_constraints = {}",
"if node not in self.nodes:\n self.nodes.append(node)\n self.node_domains[node] = domain",
"if node not in self.nodes:\n raise ValueError(node, 'was not added.')\nnode_domain = self.node_domains[node]\... | <|body_start_0|>
self.nodes = []
self.node_domains = {}
self.unary_constraints = {}
self.binary_constraints = {}
<|end_body_0|>
<|body_start_1|>
if node not in self.nodes:
self.nodes.append(node)
self.node_domains[node] = domain
<|end_body_1|>
<|body_sta... | CSP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSP:
def __init__(self):
"""Constraint Satisfaction Problem class. Attributes: nodes {list} -- A list of nodes (course, professor). node_domains {dict} -- Maps each node to its domain (rooms, hours). unary_constraints {dict} -- Maps each node to its unary constraints binary_constraints {... | stack_v2_sparse_classes_75kplus_train_070205 | 8,989 | no_license | [
{
"docstring": "Constraint Satisfaction Problem class. Attributes: nodes {list} -- A list of nodes (course, professor). node_domains {dict} -- Maps each node to its domain (rooms, hours). unary_constraints {dict} -- Maps each node to its unary constraints binary_constraints {dict} -- Maps each node to its binar... | 5 | null | Implement the Python class `CSP` described below.
Class description:
Implement the CSP class.
Method signatures and docstrings:
- def __init__(self): Constraint Satisfaction Problem class. Attributes: nodes {list} -- A list of nodes (course, professor). node_domains {dict} -- Maps each node to its domain (rooms, hour... | Implement the Python class `CSP` described below.
Class description:
Implement the CSP class.
Method signatures and docstrings:
- def __init__(self): Constraint Satisfaction Problem class. Attributes: nodes {list} -- A list of nodes (course, professor). node_domains {dict} -- Maps each node to its domain (rooms, hour... | 7b8f81aa91b2123c5509bcf2a5f00a0bb7e84d55 | <|skeleton|>
class CSP:
def __init__(self):
"""Constraint Satisfaction Problem class. Attributes: nodes {list} -- A list of nodes (course, professor). node_domains {dict} -- Maps each node to its domain (rooms, hours). unary_constraints {dict} -- Maps each node to its unary constraints binary_constraints {... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSP:
def __init__(self):
"""Constraint Satisfaction Problem class. Attributes: nodes {list} -- A list of nodes (course, professor). node_domains {dict} -- Maps each node to its domain (rooms, hours). unary_constraints {dict} -- Maps each node to its unary constraints binary_constraints {dict} -- Maps ... | the_stack_v2_python_sparse | scheduler/cspsolver.py | gcallah/Scheduler | train | 5 | |
4ff22b7683aa12ee3d4804c1f46a46681ba4304d | [
"if minfo is None:\n minfo = {}\nsuper(QuorumBallotMessage, self).__init__(minfo)\nself.IsSystemMessage = False\nself.IsForward = True\nself.IsReliable = True\nself.Ballot = minfo.get('Ballot', 0)\nself.BlockNumber = minfo.get('BlockNumber', 0)\nself.TransactionIDs = []\nif 'TransactionIDs' in minfo:\n for tx... | <|body_start_0|>
if minfo is None:
minfo = {}
super(QuorumBallotMessage, self).__init__(minfo)
self.IsSystemMessage = False
self.IsForward = True
self.IsReliable = True
self.Ballot = minfo.get('Ballot', 0)
self.BlockNumber = minfo.get('BlockNumber', 0)... | Quorum ballot message represent the message format for exchanging quorum ballots. Attributes: QuorumBallotMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not this message is forwarded. IsReliable (bool): Whet... | QuorumBallotMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuorumBallotMessage:
"""Quorum ballot message represent the message format for exchanging quorum ballots. Attributes: QuorumBallotMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not thi... | stack_v2_sparse_classes_75kplus_train_070206 | 8,559 | permissive | [
{
"docstring": "Constructor for QuorumBallotMessage. Args: minfo (dict): A dict containing initial values for the new QuorumBallotMessages.",
"name": "__init__",
"signature": "def __init__(self, minfo=None)"
},
{
"docstring": "Returns a dict containing information about the quorum ballot message... | 2 | stack_v2_sparse_classes_30k_train_020195 | Implement the Python class `QuorumBallotMessage` described below.
Class description:
Quorum ballot message represent the message format for exchanging quorum ballots. Attributes: QuorumBallotMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system messag... | Implement the Python class `QuorumBallotMessage` described below.
Class description:
Quorum ballot message represent the message format for exchanging quorum ballots. Attributes: QuorumBallotMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system messag... | e3eb79f32c97a25993c87eda7f77a02fd2086c7c | <|skeleton|>
class QuorumBallotMessage:
"""Quorum ballot message represent the message format for exchanging quorum ballots. Attributes: QuorumBallotMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not thi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuorumBallotMessage:
"""Quorum ballot message represent the message format for exchanging quorum ballots. Attributes: QuorumBallotMessage.MessageType (str): The class name of the message. IsSystemMessage (bool): Whether or not this message is a system message. IsForward (bool): Whether or not this message is ... | the_stack_v2_python_sparse | validator/sawtooth_validator/consensus/quorum/messages/quorum_ballot.py | jrineck/sawtooth-core | train | 0 |
96505689d222f9165b2760b3634d952cd552a759 | [
"kwargs = {'mode': mode}\ncommand = 'netsh {interface} show networks {kwargs}'.format(interface=interface, kwargs=' '.join(['{key}={val}'.format(key=key, val=val) for key, val in kwargs.items()]))\ncmd_resp = utils.cmd_exec_subprocess(command)\ncmd_resp = '\\n'.join(cmd_resp.splitlines()[3:]).strip()\nsoup = CmdSou... | <|body_start_0|>
kwargs = {'mode': mode}
command = 'netsh {interface} show networks {kwargs}'.format(interface=interface, kwargs=' '.join(['{key}={val}'.format(key=key, val=val) for key, val in kwargs.items()]))
cmd_resp = utils.cmd_exec_subprocess(command)
cmd_resp = '\n'.join(cmd_resp.... | Class to interface with the cmd command 'netsh' Very limited support | Netsh | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Netsh:
"""Class to interface with the cmd command 'netsh' Very limited support"""
def get_networks(interface='wlan', mode='bssid'):
"""Returns a dictionay of data extacted from ... the command 'netsh {interface} show networks mode={mode}' Tailored for when 'mode' == 'bssid'"""
... | stack_v2_sparse_classes_75kplus_train_070207 | 2,827 | no_license | [
{
"docstring": "Returns a dictionay of data extacted from ... the command 'netsh {interface} show networks mode={mode}' Tailored for when 'mode' == 'bssid'",
"name": "get_networks",
"signature": "def get_networks(interface='wlan', mode='bssid')"
},
{
"docstring": "Returns a dictionay of data ext... | 2 | null | Implement the Python class `Netsh` described below.
Class description:
Class to interface with the cmd command 'netsh' Very limited support
Method signatures and docstrings:
- def get_networks(interface='wlan', mode='bssid'): Returns a dictionay of data extacted from ... the command 'netsh {interface} show networks m... | Implement the Python class `Netsh` described below.
Class description:
Class to interface with the cmd command 'netsh' Very limited support
Method signatures and docstrings:
- def get_networks(interface='wlan', mode='bssid'): Returns a dictionay of data extacted from ... the command 'netsh {interface} show networks m... | 7d370342f34e26e6e66718ae397eb1d81253cd8a | <|skeleton|>
class Netsh:
"""Class to interface with the cmd command 'netsh' Very limited support"""
def get_networks(interface='wlan', mode='bssid'):
"""Returns a dictionay of data extacted from ... the command 'netsh {interface} show networks mode={mode}' Tailored for when 'mode' == 'bssid'"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Netsh:
"""Class to interface with the cmd command 'netsh' Very limited support"""
def get_networks(interface='wlan', mode='bssid'):
"""Returns a dictionay of data extacted from ... the command 'netsh {interface} show networks mode={mode}' Tailored for when 'mode' == 'bssid'"""
kwargs = {'... | the_stack_v2_python_sparse | yatwin/onekeywifi/network/netsh/Netsh.py | andre95d/python-yatwin | train | 0 |
a9c5d4fcb9b28e3b9843002f48c2a648782f674a | [
"res = 0\nif not grid:\n return res\nwidth, length = (len(grid), len(grid[0]))\n\ndef dfs(i: int, j: int) -> None:\n grid[i][j] = '0'\n for x, y in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:\n if 0 <= x < width and 0 <= y < length and (grid[x][y] == '1'):\n dfs(x, y)\nfor i in rang... | <|body_start_0|>
res = 0
if not grid:
return res
width, length = (len(grid), len(grid[0]))
def dfs(i: int, j: int) -> None:
grid[i][j] = '0'
for x, y in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
if 0 <= x < width and 0 <= y < l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""dfs"""
<|body_0|>
def numIslands1(self, grid: List[List[str]]) -> int:
"""bfs"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
if not grid:
return res
... | stack_v2_sparse_classes_75kplus_train_070208 | 4,072 | no_license | [
{
"docstring": "dfs",
"name": "numIslands",
"signature": "def numIslands(self, grid: List[List[str]]) -> int"
},
{
"docstring": "bfs",
"name": "numIslands1",
"signature": "def numIslands1(self, grid: List[List[str]]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid: List[List[str]]) -> int: dfs
- def numIslands1(self, grid: List[List[str]]) -> int: bfs | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid: List[List[str]]) -> int: dfs
- def numIslands1(self, grid: List[List[str]]) -> int: bfs
<|skeleton|>
class Solution:
def numIslands(self, grid: L... | e2fecd266bfced6208694b19a2d81182b13dacd6 | <|skeleton|>
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""dfs"""
<|body_0|>
def numIslands1(self, grid: List[List[str]]) -> int:
"""bfs"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""dfs"""
res = 0
if not grid:
return res
width, length = (len(grid), len(grid[0]))
def dfs(i: int, j: int) -> None:
grid[i][j] = '0'
for x, y in [(i - 1, j), (i + 1, j), ... | the_stack_v2_python_sparse | numIslands.py | HuipengXu/leetcode | train | 0 | |
89f507bc0e205ae3fc33ab4b8d80c3be9424c360 | [
"super(MidasNet_StackedHourGlass, self).__init__()\nuse_pretrained = False if path else True\nself.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)\nself.scratch.refinenet4 = ProgressiveUpsample(features, features // 2, 32)\nself.scratch.refinenet3 = ProgressiveUpsample(features + featur... | <|body_start_0|>
super(MidasNet_StackedHourGlass, self).__init__()
use_pretrained = False if path else True
self.pretrained, self.scratch = _make_encoder(backbone, features, use_pretrained)
self.scratch.refinenet4 = ProgressiveUpsample(features, features // 2, 32)
self.scratch.re... | Network for monocular depth estimation. | MidasNet_StackedHourGlass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MidasNet_StackedHourGlass:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defa... | stack_v2_sparse_classes_75kplus_train_070209 | 13,019 | permissive | [
{
"docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50",
"name": "__init__",
"signature": "def __init__(self, path=None, features=... | 2 | stack_v2_sparse_classes_30k_train_003268 | Implement the Python class `MidasNet_StackedHourGlass` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to... | Implement the Python class `MidasNet_StackedHourGlass` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True): Init. Args: path (str, optional): Path to saved model. Defaults to... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class MidasNet_StackedHourGlass:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MidasNet_StackedHourGlass:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256, backbone='resnet50', non_negative=True):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. ... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/midas_net.py | kcyu2014/nas-landmarkreg | train | 10 |
4d019a29e51e495b47122cfa229f8aad67779262 | [
"results = []\nfragments = Fragment.objects.filter(language__iso=self.kwargs['language']).filter(document__corpus__in=get_available_corpora(self.request.user))\nfor fragment in fragments:\n if Annotation.objects.filter(alignment__original_fragment=fragment, is_no_target=False).exists():\n results.append(f... | <|body_start_0|>
results = []
fragments = Fragment.objects.filter(language__iso=self.kwargs['language']).filter(document__corpus__in=get_available_corpora(self.request.user))
for fragment in fragments:
if Annotation.objects.filter(alignment__original_fragment=fragment, is_no_target=F... | TODO: consider refactoring, too many queries. | FragmentList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FragmentList:
"""TODO: consider refactoring, too many queries."""
def get_queryset(self):
"""Retrieves all Fragments for the given language that have an Annotation that contains a target expression. :return: A list of Fragments."""
<|body_0|>
def get_context_data(self, *... | stack_v2_sparse_classes_75kplus_train_070210 | 26,956 | permissive | [
{
"docstring": "Retrieves all Fragments for the given language that have an Annotation that contains a target expression. :return: A list of Fragments.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Sets the current language and other_languages on the context.... | 2 | null | Implement the Python class `FragmentList` described below.
Class description:
TODO: consider refactoring, too many queries.
Method signatures and docstrings:
- def get_queryset(self): Retrieves all Fragments for the given language that have an Annotation that contains a target expression. :return: A list of Fragments... | Implement the Python class `FragmentList` described below.
Class description:
TODO: consider refactoring, too many queries.
Method signatures and docstrings:
- def get_queryset(self): Retrieves all Fragments for the given language that have an Annotation that contains a target expression. :return: A list of Fragments... | 7a6e98f2023f763cba5742be097b8cb34ee7007c | <|skeleton|>
class FragmentList:
"""TODO: consider refactoring, too many queries."""
def get_queryset(self):
"""Retrieves all Fragments for the given language that have an Annotation that contains a target expression. :return: A list of Fragments."""
<|body_0|>
def get_context_data(self, *... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FragmentList:
"""TODO: consider refactoring, too many queries."""
def get_queryset(self):
"""Retrieves all Fragments for the given language that have an Annotation that contains a target expression. :return: A list of Fragments."""
results = []
fragments = Fragment.objects.filter(... | the_stack_v2_python_sparse | annotations/views.py | UUDigitalHumanitieslab/timealign | train | 9 |
8dda35a770f3899f757c187ab6befdb854a8e844 | [
"trees = cfn.search_deep_keys(ref_function)\ntrees = filter(lambda x: x[0] == 'Resources', trees)\ntrees = filter(lambda x: x[1] == resource, trees)\nreturn trees",
"matches = []\ntrees = self.get_resource_references(cfn, 'Ref', resource)\nfor tree in trees:\n if tree[-1] == key:\n message = 'Obsolete D... | <|body_start_0|>
trees = cfn.search_deep_keys(ref_function)
trees = filter(lambda x: x[0] == 'Resources', trees)
trees = filter(lambda x: x[1] == resource, trees)
return trees
<|end_body_0|>
<|body_start_1|>
matches = []
trees = self.get_resource_references(cfn, 'Ref', r... | Check unneeded DepensOn Resource Configuration | DependsOnObsolete | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependsOnObsolete:
"""Check unneeded DepensOn Resource Configuration"""
def get_resource_references(self, cfn, ref_function, resource):
"""Get tree of all resource references of a resource"""
<|body_0|>
def check_depends_on(self, cfn, resource, key, path):
"""Che... | stack_v2_sparse_classes_75kplus_train_070211 | 3,864 | permissive | [
{
"docstring": "Get tree of all resource references of a resource",
"name": "get_resource_references",
"signature": "def get_resource_references(self, cfn, ref_function, resource)"
},
{
"docstring": "Check if the DependsOn is already specified",
"name": "check_depends_on",
"signature": "... | 3 | stack_v2_sparse_classes_30k_test_000360 | Implement the Python class `DependsOnObsolete` described below.
Class description:
Check unneeded DepensOn Resource Configuration
Method signatures and docstrings:
- def get_resource_references(self, cfn, ref_function, resource): Get tree of all resource references of a resource
- def check_depends_on(self, cfn, reso... | Implement the Python class `DependsOnObsolete` described below.
Class description:
Check unneeded DepensOn Resource Configuration
Method signatures and docstrings:
- def get_resource_references(self, cfn, ref_function, resource): Get tree of all resource references of a resource
- def check_depends_on(self, cfn, reso... | 3f5324cfd000e14d9324a242bb7fad528b22a7df | <|skeleton|>
class DependsOnObsolete:
"""Check unneeded DepensOn Resource Configuration"""
def get_resource_references(self, cfn, ref_function, resource):
"""Get tree of all resource references of a resource"""
<|body_0|>
def check_depends_on(self, cfn, resource, key, path):
"""Che... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DependsOnObsolete:
"""Check unneeded DepensOn Resource Configuration"""
def get_resource_references(self, cfn, ref_function, resource):
"""Get tree of all resource references of a resource"""
trees = cfn.search_deep_keys(ref_function)
trees = filter(lambda x: x[0] == 'Resources', ... | the_stack_v2_python_sparse | src/cfnlint/rules/resources/DependsOnObsolete.py | jlongtine/cfn-python-lint | train | 1 |
aef3ce0856e8442108b8d4cc179f2a544944efff | [
"Frame.__init__(self, master)\nself.pack()\nself.label = Label(self, text='Enter your guess:')\nself.label.grid(row=0, column=0)\nself.guess = Entry(self, width=14)\nself.guess.grid(row=1, column=0)\nself.answer = randrange(0, 10)\nself.button = Button(self, text='Enter', command=self.compute_guess)\nself.button.gr... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.label = Label(self, text='Enter your guess:')
self.label.grid(row=0, column=0)
self.guess = Entry(self, width=14)
self.guess.grid(row=1, column=0)
self.answer = randrange(0, 10)
self.button = B... | 1-10 endless guessing game | GameRefresh | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameRefresh:
"""1-10 endless guessing game"""
def __init__(self, master=None):
"""Constructor"""
<|body_0|>
def compute_guess(self):
"""Display guess"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Frame.__init__(self, master)
self.pack(... | stack_v2_sparse_classes_75kplus_train_070212 | 46,883 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Display guess",
"name": "compute_guess",
"signature": "def compute_guess(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012137 | Implement the Python class `GameRefresh` described below.
Class description:
1-10 endless guessing game
Method signatures and docstrings:
- def __init__(self, master=None): Constructor
- def compute_guess(self): Display guess | Implement the Python class `GameRefresh` described below.
Class description:
1-10 endless guessing game
Method signatures and docstrings:
- def __init__(self, master=None): Constructor
- def compute_guess(self): Display guess
<|skeleton|>
class GameRefresh:
"""1-10 endless guessing game"""
def __init__(self... | 15a8d4aebc53ccd02f2c7ba36ae8d2abae7eb4c8 | <|skeleton|>
class GameRefresh:
"""1-10 endless guessing game"""
def __init__(self, master=None):
"""Constructor"""
<|body_0|>
def compute_guess(self):
"""Display guess"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GameRefresh:
"""1-10 endless guessing game"""
def __init__(self, master=None):
"""Constructor"""
Frame.__init__(self, master)
self.pack()
self.label = Label(self, text='Enter your guess:')
self.label.grid(row=0, column=0)
self.guess = Entry(self, width=14)
... | the_stack_v2_python_sparse | ch09/Perkovic_Ch_09.2.py | testowy4u/L_Python_Perkovic_Introduction-to-Computing-Using-Python_Edition-1 | train | 0 |
f27fa8f844fd374a175fd9a1c73a102e9552a32a | [
"self.clusters_count = count\nself._leaders = [i for i in range(count)]\nself._ranks = [0] * count",
"ot = self.find(x)\nto = self.find(y)\nif ot == to:\n return\nself.clusters_count -= 1\nrank_ot = self._ranks[ot]\nrank_to = self._ranks[to]\nif rank_ot == rank_to:\n self._leaders[ot] = to\n self._ranks[... | <|body_start_0|>
self.clusters_count = count
self._leaders = [i for i in range(count)]
self._ranks = [0] * count
<|end_body_0|>
<|body_start_1|>
ot = self.find(x)
to = self.find(y)
if ot == to:
return
self.clusters_count -= 1
rank_ot = self._r... | UnionFind | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnionFind:
def __init__(self, count):
"""Constructor of the union find structure"""
<|body_0|>
def union(self, x, y):
"""Put x and y into one cluster"""
<|body_1|>
def find(self, i):
"""Find cluster for i"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_070213 | 1,847 | no_license | [
{
"docstring": "Constructor of the union find structure",
"name": "__init__",
"signature": "def __init__(self, count)"
},
{
"docstring": "Put x and y into one cluster",
"name": "union",
"signature": "def union(self, x, y)"
},
{
"docstring": "Find cluster for i",
"name": "find... | 3 | stack_v2_sparse_classes_30k_train_026489 | Implement the Python class `UnionFind` described below.
Class description:
Implement the UnionFind class.
Method signatures and docstrings:
- def __init__(self, count): Constructor of the union find structure
- def union(self, x, y): Put x and y into one cluster
- def find(self, i): Find cluster for i | Implement the Python class `UnionFind` described below.
Class description:
Implement the UnionFind class.
Method signatures and docstrings:
- def __init__(self, count): Constructor of the union find structure
- def union(self, x, y): Put x and y into one cluster
- def find(self, i): Find cluster for i
<|skeleton|>
c... | 8eac3ac57066d3e91f4621abf88264c48ba0f691 | <|skeleton|>
class UnionFind:
def __init__(self, count):
"""Constructor of the union find structure"""
<|body_0|>
def union(self, x, y):
"""Put x and y into one cluster"""
<|body_1|>
def find(self, i):
"""Find cluster for i"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnionFind:
def __init__(self, count):
"""Constructor of the union find structure"""
self.clusters_count = count
self._leaders = [i for i in range(count)]
self._ranks = [0] * count
def union(self, x, y):
"""Put x and y into one cluster"""
ot = self.find(x)
... | the_stack_v2_python_sparse | Pythoning/computer_science/datatypes/union_find.py | omikad/omikad-stuff | train | 0 | |
cdadc407975e560b75267cc2610ff964e7b79cc9 | [
"self.stop_word_remove_list = stop_word_remove_list\nself.to_lowercase = to_lowercase\nself.remove_newlines = remove_newlines\nself.remove_html_tags = remove_html_tags\nself.remove_accented_chars = remove_accented_chars\nself.expand_contractions = expand_contractions\nself.remove_special_chars = remove_special_char... | <|body_start_0|>
self.stop_word_remove_list = stop_word_remove_list
self.to_lowercase = to_lowercase
self.remove_newlines = remove_newlines
self.remove_html_tags = remove_html_tags
self.remove_accented_chars = remove_accented_chars
self.expand_contractions = expand_contra... | AmazonTextNormalizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmazonTextNormalizer:
def __init__(self, stop_word_remove_list=STOP_WORDS_TO_REMOVE, to_lowercase=True, remove_newlines=True, remove_html_tags=True, remove_accented_chars=True, expand_contractions=True, remove_special_chars=True, stem_text=False, lemmatize_text=False, remove_alphanumeric_words=T... | stack_v2_sparse_classes_75kplus_train_070214 | 5,137 | no_license | [
{
"docstring": ":param text_columns: list of columns to process. required :param columns_to_drop: list of columns to drop. optional :param stop_word_remove_list: list of stopwords to remove :param to_lowercase: :param remove_newlines: :param remove_html_tags: :param remove_accented_chars: :param expand_contract... | 2 | stack_v2_sparse_classes_30k_train_004901 | Implement the Python class `AmazonTextNormalizer` described below.
Class description:
Implement the AmazonTextNormalizer class.
Method signatures and docstrings:
- def __init__(self, stop_word_remove_list=STOP_WORDS_TO_REMOVE, to_lowercase=True, remove_newlines=True, remove_html_tags=True, remove_accented_chars=True,... | Implement the Python class `AmazonTextNormalizer` described below.
Class description:
Implement the AmazonTextNormalizer class.
Method signatures and docstrings:
- def __init__(self, stop_word_remove_list=STOP_WORDS_TO_REMOVE, to_lowercase=True, remove_newlines=True, remove_html_tags=True, remove_accented_chars=True,... | 7a0f1b5a6db36b02814206a98aae6c4bd615e02c | <|skeleton|>
class AmazonTextNormalizer:
def __init__(self, stop_word_remove_list=STOP_WORDS_TO_REMOVE, to_lowercase=True, remove_newlines=True, remove_html_tags=True, remove_accented_chars=True, expand_contractions=True, remove_special_chars=True, stem_text=False, lemmatize_text=False, remove_alphanumeric_words=T... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AmazonTextNormalizer:
def __init__(self, stop_word_remove_list=STOP_WORDS_TO_REMOVE, to_lowercase=True, remove_newlines=True, remove_html_tags=True, remove_accented_chars=True, expand_contractions=True, remove_special_chars=True, stem_text=False, lemmatize_text=False, remove_alphanumeric_words=True, remove_st... | the_stack_v2_python_sparse | util/amazon_util.py | sv650s/amazon-review-classification | train | 0 | |
3e79601fb9582a89895752f4851208bac731fa8c | [
"self.text = ''\nself.keywords = None\nself.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters)\nself.sentences = None\nself.words_no_filter = None\nself.words_no_stop_words = None\nself.words_all_filters = None",
"self.text = text\nself.word_index = {}\... | <|body_start_0|>
self.text = ''
self.keywords = None
self.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters)
self.sentences = None
self.words_no_filter = None
self.words_no_stop_words = None
self.words_a... | TextRank4Keyword | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextRank4Keyword:
def __init__(self, allow_speech_tags, delimiters, stop_words_file=None):
"""Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words... | stack_v2_sparse_classes_75kplus_train_070215 | 20,624 | no_license | [
{
"docstring": "Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words_no_stop_words -- 去掉words_no_filter中的停止词而得到的两级列表。 self.words_all_filters -- 保留words_no_stop_words中指定词性... | 4 | stack_v2_sparse_classes_30k_train_049049 | Implement the Python class `TextRank4Keyword` described below.
Class description:
Implement the TextRank4Keyword class.
Method signatures and docstrings:
- def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters... | Implement the Python class `TextRank4Keyword` described below.
Class description:
Implement the TextRank4Keyword class.
Method signatures and docstrings:
- def __init__(self, allow_speech_tags, delimiters, stop_words_file=None): Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters... | ca2cf55b4dbae09a3c85689c8dae104908060c86 | <|skeleton|>
class TextRank4Keyword:
def __init__(self, allow_speech_tags, delimiters, stop_words_file=None):
"""Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextRank4Keyword:
def __init__(self, allow_speech_tags, delimiters, stop_words_file=None):
"""Keyword arguments: stop_words_file -- str,指定停止词文件路径(一行一个停止词),若为其他类型,则使用默认停止词文件 delimiters -- 默认值是`?!;?!。;… `,用来将文本拆分为句子。 Object Var: self.words_no_filter -- 对sentences中每个句子分词而得到的两级列表。 self.words_no_stop_words... | the_stack_v2_python_sparse | owner/吴伟/keyword_extraction.py | dxcv/GsEnv | train | 0 | |
0ab0b0c37a84d9b350b48acb1b70954d5714ac12 | [
"for idx in POSSIBLE_INDEXES:\n try:\n soup = BeautifulSoup(open(os.path.join(self.docpath, idx)), 'lxml')\n break\n except IOError:\n pass\nelse:\n raise IOError(errno.ENOENT, 'Essential index file not found.')\nfor t in _parse_soup(soup):\n yield t",
"link = soup.find('a', {'cla... | <|body_start_0|>
for idx in POSSIBLE_INDEXES:
try:
soup = BeautifulSoup(open(os.path.join(self.docpath, idx)), 'lxml')
break
except IOError:
pass
else:
raise IOError(errno.ENOENT, 'Essential index file not found.')
... | Parser for Sphinx-based documenation: Python, Django, Pyramid... | SphinxParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphinxParser:
"""Parser for Sphinx-based documenation: Python, Django, Pyramid..."""
def parse(self):
"""Parse sphinx docs at *path*. yield tuples of symbol name, type and path"""
<|body_0|>
def find_and_patch_entry(self, soup, entry):
"""Modify soup so dash can ... | stack_v2_sparse_classes_75kplus_train_070216 | 35,122 | no_license | [
{
"docstring": "Parse sphinx docs at *path*. yield tuples of symbol name, type and path",
"name": "parse",
"signature": "def parse(self)"
},
{
"docstring": "Modify soup so dash can generate TOCs on the fly.",
"name": "find_and_patch_entry",
"signature": "def find_and_patch_entry(self, so... | 2 | stack_v2_sparse_classes_30k_train_014710 | Implement the Python class `SphinxParser` described below.
Class description:
Parser for Sphinx-based documenation: Python, Django, Pyramid...
Method signatures and docstrings:
- def parse(self): Parse sphinx docs at *path*. yield tuples of symbol name, type and path
- def find_and_patch_entry(self, soup, entry): Mod... | Implement the Python class `SphinxParser` described below.
Class description:
Parser for Sphinx-based documenation: Python, Django, Pyramid...
Method signatures and docstrings:
- def parse(self): Parse sphinx docs at *path*. yield tuples of symbol name, type and path
- def find_and_patch_entry(self, soup, entry): Mod... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class SphinxParser:
"""Parser for Sphinx-based documenation: Python, Django, Pyramid..."""
def parse(self):
"""Parse sphinx docs at *path*. yield tuples of symbol name, type and path"""
<|body_0|>
def find_and_patch_entry(self, soup, entry):
"""Modify soup so dash can ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SphinxParser:
"""Parser for Sphinx-based documenation: Python, Django, Pyramid..."""
def parse(self):
"""Parse sphinx docs at *path*. yield tuples of symbol name, type and path"""
for idx in POSSIBLE_INDEXES:
try:
soup = BeautifulSoup(open(os.path.join(self.doc... | the_stack_v2_python_sparse | repoData/hynek-doc2dash/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
c072ecb3e02b4ecdec11538562e199d8f20a2518 | [
"self._channel_mapping = {}\nself._requests = {}\nself._request_id = 0",
"request_id = msg.protected_payload.channel_request_id\nchannel = self._requests.get(request_id)\nif not channel:\n raise ChannelError('Request Id %d not found. Was the channel request saved?' % request_id)\nif msg.protected_payload.resul... | <|body_start_0|>
self._channel_mapping = {}
self._requests = {}
self._request_id = 0
<|end_body_0|>
<|body_start_1|>
request_id = msg.protected_payload.channel_request_id
channel = self._requests.get(request_id)
if not channel:
raise ChannelError('Request Id ... | ChannelManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChannelManager:
def __init__(self):
"""Keep track of established ServiceChannels"""
<|body_0|>
def handle_channel_start_response(self, msg: XStruct) -> ServiceChannel:
"""Handle message of type `StartChannelResponse` Args: msg: Start Channel Response message Raises: ... | stack_v2_sparse_classes_75kplus_train_070217 | 32,500 | permissive | [
{
"docstring": "Keep track of established ServiceChannels",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handle message of type `StartChannelResponse` Args: msg: Start Channel Response message Raises: :class:`ChannelError`: If channel acquire failed Returns: Acquired ... | 6 | stack_v2_sparse_classes_30k_train_022939 | Implement the Python class `ChannelManager` described below.
Class description:
Implement the ChannelManager class.
Method signatures and docstrings:
- def __init__(self): Keep track of established ServiceChannels
- def handle_channel_start_response(self, msg: XStruct) -> ServiceChannel: Handle message of type `Start... | Implement the Python class `ChannelManager` described below.
Class description:
Implement the ChannelManager class.
Method signatures and docstrings:
- def __init__(self): Keep track of established ServiceChannels
- def handle_channel_start_response(self, msg: XStruct) -> ServiceChannel: Handle message of type `Start... | 96e1e0a45db347f66101c3df5eec3f7cb92d1236 | <|skeleton|>
class ChannelManager:
def __init__(self):
"""Keep track of established ServiceChannels"""
<|body_0|>
def handle_channel_start_response(self, msg: XStruct) -> ServiceChannel:
"""Handle message of type `StartChannelResponse` Args: msg: Start Channel Response message Raises: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChannelManager:
def __init__(self):
"""Keep track of established ServiceChannels"""
self._channel_mapping = {}
self._requests = {}
self._request_id = 0
def handle_channel_start_response(self, msg: XStruct) -> ServiceChannel:
"""Handle message of type `StartChannelR... | the_stack_v2_python_sparse | xbox/sg/protocol.py | OpenXbox/xbox-smartglass-core-python | train | 74 | |
7079cf98171ef4f835dbdde7340b8c3a3cb552c5 | [
"self.img_filename = img_filename\nself.pcd_filename = pcd_filename\nself.img = np.asarray(Image.open(img_filename))\nself.cloud = pcd_reader.read_pcd(pcd_filename)",
"clicker = ck.Clicker()\nclicker.clicker(img_filename)\nself.img_clicks = np.array(clicker.coords, dtype=np.float).T\nreturn self.img_clicks",
"d... | <|body_start_0|>
self.img_filename = img_filename
self.pcd_filename = pcd_filename
self.img = np.asarray(Image.open(img_filename))
self.cloud = pcd_reader.read_pcd(pcd_filename)
<|end_body_0|>
<|body_start_1|>
clicker = ck.Clicker()
clicker.clicker(img_filename)
... | Calib2d3d - Class to calibrate image to 3D data. | Calib2d3d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Calib2d3d:
"""Calib2d3d - Class to calibrate image to 3D data."""
def __init__(self, img_filename, pcd_filename):
"""Initialization. Usage: Calib2d3d( image_filename, pcd_filename )"""
<|body_0|>
def getClicks2D(self):
"""Display image and get click positions. Us... | stack_v2_sparse_classes_75kplus_train_070218 | 4,460 | no_license | [
{
"docstring": "Initialization. Usage: Calib2d3d( image_filename, pcd_filename )",
"name": "__init__",
"signature": "def __init__(self, img_filename, pcd_filename)"
},
{
"docstring": "Display image and get click positions. Usage: pts2D = getClicks2D() Input: -NONE- Output: pts2D - 2d points (x,y... | 4 | stack_v2_sparse_classes_30k_train_039625 | Implement the Python class `Calib2d3d` described below.
Class description:
Calib2d3d - Class to calibrate image to 3D data.
Method signatures and docstrings:
- def __init__(self, img_filename, pcd_filename): Initialization. Usage: Calib2d3d( image_filename, pcd_filename )
- def getClicks2D(self): Display image and ge... | Implement the Python class `Calib2d3d` described below.
Class description:
Calib2d3d - Class to calibrate image to 3D data.
Method signatures and docstrings:
- def __init__(self, img_filename, pcd_filename): Initialization. Usage: Calib2d3d( image_filename, pcd_filename )
- def getClicks2D(self): Display image and ge... | a9d9dc5f4132ccfe1713e84dcbfba992b68b782b | <|skeleton|>
class Calib2d3d:
"""Calib2d3d - Class to calibrate image to 3D data."""
def __init__(self, img_filename, pcd_filename):
"""Initialization. Usage: Calib2d3d( image_filename, pcd_filename )"""
<|body_0|>
def getClicks2D(self):
"""Display image and get click positions. Us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Calib2d3d:
"""Calib2d3d - Class to calibrate image to 3D data."""
def __init__(self, img_filename, pcd_filename):
"""Initialization. Usage: Calib2d3d( image_filename, pcd_filename )"""
self.img_filename = img_filename
self.pcd_filename = pcd_filename
self.img = np.asarray(... | the_stack_v2_python_sparse | Modeling_with_python/utils/camera_3d_calib.py | DavidB-CMU/moped | train | 2 |
beb8235c64dca058fec439588077b62aed96fbd0 | [
"levels = []\nif not root:\n return levels\n\ndef helper(node, level):\n if len(levels) == level:\n levels.append([])\n levels[level].append(node.val)\n if node.left:\n helper(node.left, level + 1)\n if node.right:\n helper(node.right, level + 1)\nhelper(root, 0)\nreturn levels",... | <|body_start_0|>
levels = []
if not root:
return levels
def helper(node, level):
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
if node.left:
helper(node.left, level + 1)
if no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder(self, root: TreeNode):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder_bianli(self, root: TreeNode):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070219 | 1,813 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder",
"signature": "def levelOrder(self, root: TreeNode)"
},
{
"docstring": ":type root: TreeNode :rtype: List[List[int]]",
"name": "levelOrder_bianli",
"signature": "def levelOrder_bianli(self, root: TreeNode... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root: TreeNode): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder_bianli(self, root: TreeNode): :type root: TreeNode :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder(self, root: TreeNode): :type root: TreeNode :rtype: List[List[int]]
- def levelOrder_bianli(self, root: TreeNode): :type root: TreeNode :rtype: List[List[int]]
<|... | 3f3aa0cc869d7edf349691ecf1e057fd4aad2ab1 | <|skeleton|>
class Solution:
def levelOrder(self, root: TreeNode):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def levelOrder_bianli(self, root: TreeNode):
""":type root: TreeNode :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrder(self, root: TreeNode):
""":type root: TreeNode :rtype: List[List[int]]"""
levels = []
if not root:
return levels
def helper(node, level):
if len(levels) == level:
levels.append([])
levels[level].appen... | the_stack_v2_python_sparse | LeetCode_Python/LeetCode102.py | GDUT-Rp/LeetCode | train | 2 | |
7512b2720125566d1d3c723337955530995e2ba1 | [
"with Database() as db:\n if id_risk_level is None and is_active is None:\n data = db.query(Table).all()\n elif id_risk_level is None:\n data = db.query(Table).filter(Table.is_active == is_active).all()\n else:\n data = db.query(Table).get(id_risk_level)\nreturn {'data': data}",
"if ... | <|body_start_0|>
with Database() as db:
if id_risk_level is None and is_active is None:
data = db.query(Table).all()
elif id_risk_level is None:
data = db.query(Table).filter(Table.is_active == is_active).all()
else:
data = db.q... | RiskLevel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskLevel:
def get(self, id_risk_level=None, is_active=None):
"""Return all information for risk level :param id_risk_level: UUID :param is_active: BOOLEAN"""
<|body_0|>
def create(self, body):
"""Create a new risk level :param body: { name: JSON, sequence: INTEGER, ... | stack_v2_sparse_classes_75kplus_train_070220 | 2,806 | no_license | [
{
"docstring": "Return all information for risk level :param id_risk_level: UUID :param is_active: BOOLEAN",
"name": "get",
"signature": "def get(self, id_risk_level=None, is_active=None)"
},
{
"docstring": "Create a new risk level :param body: { name: JSON, sequence: INTEGER, code: INTEGER, col... | 4 | stack_v2_sparse_classes_30k_train_028329 | Implement the Python class `RiskLevel` described below.
Class description:
Implement the RiskLevel class.
Method signatures and docstrings:
- def get(self, id_risk_level=None, is_active=None): Return all information for risk level :param id_risk_level: UUID :param is_active: BOOLEAN
- def create(self, body): Create a... | Implement the Python class `RiskLevel` described below.
Class description:
Implement the RiskLevel class.
Method signatures and docstrings:
- def get(self, id_risk_level=None, is_active=None): Return all information for risk level :param id_risk_level: UUID :param is_active: BOOLEAN
- def create(self, body): Create a... | 43bd57c466a5cd3b133ddc437cb4a6b9f007d267 | <|skeleton|>
class RiskLevel:
def get(self, id_risk_level=None, is_active=None):
"""Return all information for risk level :param id_risk_level: UUID :param is_active: BOOLEAN"""
<|body_0|>
def create(self, body):
"""Create a new risk level :param body: { name: JSON, sequence: INTEGER, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RiskLevel:
def get(self, id_risk_level=None, is_active=None):
"""Return all information for risk level :param id_risk_level: UUID :param is_active: BOOLEAN"""
with Database() as db:
if id_risk_level is None and is_active is None:
data = db.query(Table).all()
... | the_stack_v2_python_sparse | resturls/risklevel.py | CAUCA-9-1-1/survip-api | train | 1 | |
f32b567fbb5784421eae8e19fe51d260b3c9010f | [
"self.capacity = capacity\nself.key_node = {}\nself.count_node = {}\nself.minV = None",
"if not key in self.key_node:\n return -1\nnode = self.key_node[key]\ndel self.count_node[node.count][key]\nif not self.count_node[node.count]:\n del self.count_node[node.count]\nnode.count += 1\nif not node.count in sel... | <|body_start_0|>
self.capacity = capacity
self.key_node = {}
self.count_node = {}
self.minV = None
<|end_body_0|>
<|body_start_1|>
if not key in self.key_node:
return -1
node = self.key_node[key]
del self.count_node[node.count][key]
if not sel... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_070221 | 2,045 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_039666 | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 08b3d9cab3c1806c37d36587372b1e8fb1683f64 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.key_node = {}
self.count_node = {}
self.minV = None
def get(self, key):
""":type key: int :rtype: int"""
if not key in self.key_node:
return ... | the_stack_v2_python_sparse | history/460.py | HonniLin/leetcode | train | 0 | |
260f9a96117b66eb93e91d32de4938de4cdfa909 | [
"if head == None:\n return head\nif head.next == None:\n return head\nrhead = ListNode(head.val)\nrhead.next = None\nwhile head.next != None:\n r2head = ListNode(head.next.val)\n r2head.next = rhead\n rhead = r2head\n head = head.next\nreturn rhead",
"rhead = Solution.reverseList(self, head)\nwh... | <|body_start_0|>
if head == None:
return head
if head.next == None:
return head
rhead = ListNode(head.val)
rhead.next = None
while head.next != None:
r2head = ListNode(head.next.val)
r2head.next = rhead
rhead = r2head
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if head == None:
return head... | stack_v2_sparse_classes_75kplus_train_070222 | 1,226 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001426 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def isPalindrome(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def revers... | 14176f1752e2bb94dec51bd90dfd412896ed84de | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
if head == None:
return head
if head.next == None:
return head
rhead = ListNode(head.val)
rhead.next = None
while head.next != None:
r2head = L... | the_stack_v2_python_sparse | solutions/234-palindrome-linked-list/palindrome-linked-list.py | fagan2888/leetcode-6 | train | 0 | |
dafb0811b993fd6d1bdcd69430fb64bf6045dafb | [
"if not hasattr(self, 'output_view'):\n self.output_view = self.view.window().get_output_panel(panel_name)\nreturn self.output_view",
"output_view = self._get_output_view(panel_name)\noutput_view.run_command('append', {'characters': text + end, 'scroll_to_end': True})\nself.view.window().run_command('show_pane... | <|body_start_0|>
if not hasattr(self, 'output_view'):
self.output_view = self.view.window().get_output_panel(panel_name)
return self.output_view
<|end_body_0|>
<|body_start_1|>
output_view = self._get_output_view(panel_name)
output_view.run_command('append', {'characters': t... | Provides methods for working with output panels. | OutputPanelMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputPanelMixin:
"""Provides methods for working with output panels."""
def _get_output_view(self, panel_name):
"""Returns the output panel specified by panel_name. The method also creates the output panel if it doesn't exist. Arguments: panel_name -- the name of the output panel"""... | stack_v2_sparse_classes_75kplus_train_070223 | 1,525 | permissive | [
{
"docstring": "Returns the output panel specified by panel_name. The method also creates the output panel if it doesn't exist. Arguments: panel_name -- the name of the output panel",
"name": "_get_output_view",
"signature": "def _get_output_view(self, panel_name)"
},
{
"docstring": "Appends a l... | 3 | stack_v2_sparse_classes_30k_train_048704 | Implement the Python class `OutputPanelMixin` described below.
Class description:
Provides methods for working with output panels.
Method signatures and docstrings:
- def _get_output_view(self, panel_name): Returns the output panel specified by panel_name. The method also creates the output panel if it doesn't exist.... | Implement the Python class `OutputPanelMixin` described below.
Class description:
Provides methods for working with output panels.
Method signatures and docstrings:
- def _get_output_view(self, panel_name): Returns the output panel specified by panel_name. The method also creates the output panel if it doesn't exist.... | d81eae2742629a717686ddeab6e9f2acfecb8025 | <|skeleton|>
class OutputPanelMixin:
"""Provides methods for working with output panels."""
def _get_output_view(self, panel_name):
"""Returns the output panel specified by panel_name. The method also creates the output panel if it doesn't exist. Arguments: panel_name -- the name of the output panel"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OutputPanelMixin:
"""Provides methods for working with output panels."""
def _get_output_view(self, panel_name):
"""Returns the output panel specified by panel_name. The method also creates the output panel if it doesn't exist. Arguments: panel_name -- the name of the output panel"""
if n... | the_stack_v2_python_sparse | behave_toolkit/mixins/output_panel.py | mixxorz/BehaveToolkit | train | 6 |
3e81808da865c4ead6268a04e2a5426d50e1682b | [
"current = l\nres = []\nwhile current:\n res.append(current.val)\n current = current.next\nreturn res",
"if not (l1 and l2):\n return l1 or l2\nres = str(int(''.join([str(i) for i in self.linklist2list(l1)])) + int(''.join([str(i) for i in self.linklist2list(l2)])))\nhead = ListNode(0)\ncur = head\nfor i... | <|body_start_0|>
current = l
res = []
while current:
res.append(current.val)
current = current.next
return res
<|end_body_0|>
<|body_start_1|>
if not (l1 and l2):
return l1 or l2
res = str(int(''.join([str(i) for i in self.linklist2lis... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def linklist2list(self, l):
""":type l: ListNode :rtype: list"""
<|body_0|>
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
current = l
res ... | stack_v2_sparse_classes_75kplus_train_070224 | 958 | no_license | [
{
"docstring": ":type l: ListNode :rtype: list",
"name": "linklist2list",
"signature": "def linklist2list(self, l)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1, l2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_031148 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def linklist2list(self, l): :type l: ListNode :rtype: list
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def linklist2list(self, l): :type l: ListNode :rtype: list
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>
class Solution:... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def linklist2list(self, l):
""":type l: ListNode :rtype: list"""
<|body_0|>
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def linklist2list(self, l):
""":type l: ListNode :rtype: list"""
current = l
res = []
while current:
res.append(current.val)
current = current.next
return res
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2:... | the_stack_v2_python_sparse | leetcode/addTwoNumbers-445.py | pittcat/Algorithm_Practice | train | 0 | |
68095f19ed68159a5bdc0e8b825e5ca4507e8605 | [
"for key, value in params.items():\n if '#' in params[key]:\n params[key] = params[key].replace(delimiter, ' ')\nreturn params",
"if key in params:\n return params[key]\nelse:\n return 'None'"
] | <|body_start_0|>
for key, value in params.items():
if '#' in params[key]:
params[key] = params[key].replace(delimiter, ' ')
return params
<|end_body_0|>
<|body_start_1|>
if key in params:
return params[key]
else:
return 'None'
<|end_bo... | CommonUtils class is used to do some common functions | CommonUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonUtils:
"""CommonUtils class is used to do some common functions"""
def replace_delimiter(self, params, delimiter):
"""takes params as dict and one delimiter,replaces delimeter with space and return the dict"""
<|body_0|>
def get_value_if_present_in_dict(self, param... | stack_v2_sparse_classes_75kplus_train_070225 | 1,219 | no_license | [
{
"docstring": "takes params as dict and one delimiter,replaces delimeter with space and return the dict",
"name": "replace_delimiter",
"signature": "def replace_delimiter(self, params, delimiter)"
},
{
"docstring": "searches key in dict if present return the values else None as string",
"na... | 2 | null | Implement the Python class `CommonUtils` described below.
Class description:
CommonUtils class is used to do some common functions
Method signatures and docstrings:
- def replace_delimiter(self, params, delimiter): takes params as dict and one delimiter,replaces delimeter with space and return the dict
- def get_valu... | Implement the Python class `CommonUtils` described below.
Class description:
CommonUtils class is used to do some common functions
Method signatures and docstrings:
- def replace_delimiter(self, params, delimiter): takes params as dict and one delimiter,replaces delimeter with space and return the dict
- def get_valu... | 708550f6742ff91f956b7a700fa20e91ea757f4e | <|skeleton|>
class CommonUtils:
"""CommonUtils class is used to do some common functions"""
def replace_delimiter(self, params, delimiter):
"""takes params as dict and one delimiter,replaces delimeter with space and return the dict"""
<|body_0|>
def get_value_if_present_in_dict(self, param... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommonUtils:
"""CommonUtils class is used to do some common functions"""
def replace_delimiter(self, params, delimiter):
"""takes params as dict and one delimiter,replaces delimeter with space and return the dict"""
for key, value in params.items():
if '#' in params[key]:
... | the_stack_v2_python_sparse | Framework/utils/commonUtils.py | Narasimha-MIVC/MIVC-Automation | train | 1 |
cb3c659d628ce19299a30bf96fa5288c23c34547 | [
"if len(self.size) != len(self.grain_size):\n raise RuntimeError('Dimensions of size and grain_size are not equal.')\nX = np.random.random((self.n_samples,) + self.size)\n_gaussian_size = np.around(self.grain_size).astype(int)\ngaussian = fourier_gaussian(np.ones(_gaussian_size), np.ones(len(self.size)))\nfilter... | <|body_start_0|>
if len(self.size) != len(self.grain_size):
raise RuntimeError('Dimensions of size and grain_size are not equal.')
X = np.random.random((self.n_samples,) + self.size)
_gaussian_size = np.around(self.grain_size).astype(int)
gaussian = fourier_gaussian(np.ones(_... | Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator = MicrostructureGenerator(n_samples, size, ... n_p... | MicrostructureGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MicrostructureGenerator:
"""Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator... | stack_v2_sparse_classes_75kplus_train_070226 | 3,149 | permissive | [
{
"docstring": "Generates a microstructure of dimensions of self.size and grains with dimensions self.grain_size. Returns: periodic microstructure",
"name": "generate",
"signature": "def generate(self)"
},
{
"docstring": "Takes in blurred array and assigns phase values. Args: X_blur: random fiel... | 2 | stack_v2_sparse_classes_30k_train_011376 | Implement the Python class `MicrostructureGenerator` described below.
Class description:
Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases... | Implement the Python class `MicrostructureGenerator` described below.
Class description:
Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases... | 9b582ddd5e120ea50d9023301577797ae5c434c3 | <|skeleton|>
class MicrostructureGenerator:
"""Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MicrostructureGenerator:
"""Generates n_samples number of a periodic random microstructures with domain size equal to size and with n_phases number of phases. The optional grain_size argument controls the size and shape of the grains. >>> n_samples, n_phases = 1, 2 >>> size = (4, 4) >>> generator = Microstruc... | the_stack_v2_python_sparse | pymks/datasets/microstructure_generator.py | materialsinnovation/pymks | train | 118 |
7c083965d9c593cc5611e07778410c8f0e3bf067 | [
"super().__init__(listRef.localControlRef)\nif not isinstance(nodes, list):\n nodes = [nodes]\nfor node in nodes:\n self.dataList.append((node, node.formatRef.name, node.data.copy()))\nlistRef.addUndoObj(self, notRedo)",
"if redoRef != None:\n TypeUndo(redoRef, [data[0] for data in self.dataList], False)... | <|body_start_0|>
super().__init__(listRef.localControlRef)
if not isinstance(nodes, list):
nodes = [nodes]
for node in nodes:
self.dataList.append((node, node.formatRef.name, node.data.copy()))
listRef.addUndoObj(self, notRedo)
<|end_body_0|>
<|body_start_1|>
... | Info for undo/redo of tree node type name changes. Also saves node data to cover blank node title replacement and initial data settings. | TypeUndo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeUndo:
"""Info for undo/redo of tree node type name changes. Also saves node data to cover blank node title replacement and initial data settings."""
def __init__(self, listRef, nodes, notRedo=True):
"""Create the data undo class and add it to the undoStore. Arguments: listRef -- ... | stack_v2_sparse_classes_75kplus_train_070227 | 17,816 | no_license | [
{
"docstring": "Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the undo/redo list this gets added to nodes -- a node or a list of nodes to back up notRedo -- if True, add clones and clear redo list (after changes)",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_train_054246 | Implement the Python class `TypeUndo` described below.
Class description:
Info for undo/redo of tree node type name changes. Also saves node data to cover blank node title replacement and initial data settings.
Method signatures and docstrings:
- def __init__(self, listRef, nodes, notRedo=True): Create the data undo ... | Implement the Python class `TypeUndo` described below.
Class description:
Info for undo/redo of tree node type name changes. Also saves node data to cover blank node title replacement and initial data settings.
Method signatures and docstrings:
- def __init__(self, listRef, nodes, notRedo=True): Create the data undo ... | c9429496e8ed15116746a23f3a90f262cf54f755 | <|skeleton|>
class TypeUndo:
"""Info for undo/redo of tree node type name changes. Also saves node data to cover blank node title replacement and initial data settings."""
def __init__(self, listRef, nodes, notRedo=True):
"""Create the data undo class and add it to the undoStore. Arguments: listRef -- ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TypeUndo:
"""Info for undo/redo of tree node type name changes. Also saves node data to cover blank node title replacement and initial data settings."""
def __init__(self, listRef, nodes, notRedo=True):
"""Create the data undo class and add it to the undoStore. Arguments: listRef -- a ref to the ... | the_stack_v2_python_sparse | source/undo.py | doug-101/TreeLine | train | 121 |
94736cac4d6c768c63c9559b9aa8c9750fc4b0a6 | [
"this_verbose_string, this_abbrev_string = model_interpretation.model_component_to_string(component_type_string=model_interpretation.CLASS_COMPONENT_TYPE_STRING, target_class=TARGET_CLASS, layer_name=LAYER_NAME, neuron_indices=NEURON_INDICES, channel_index=CHANNEL_INDEX)\nself.assertTrue(this_verbose_string == CLAS... | <|body_start_0|>
this_verbose_string, this_abbrev_string = model_interpretation.model_component_to_string(component_type_string=model_interpretation.CLASS_COMPONENT_TYPE_STRING, target_class=TARGET_CLASS, layer_name=LAYER_NAME, neuron_indices=NEURON_INDICES, channel_index=CHANNEL_INDEX)
self.assertTrue(... | Each method is a unit test for model_interpretation.py. | ModelInterpretationTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelInterpretationTests:
"""Each method is a unit test for model_interpretation.py."""
def test_model_component_to_string_class(self):
"""Ensures correct output from model_component_to_string. In this case, the component is an output class."""
<|body_0|>
def test_model_... | stack_v2_sparse_classes_75kplus_train_070228 | 2,860 | permissive | [
{
"docstring": "Ensures correct output from model_component_to_string. In this case, the component is an output class.",
"name": "test_model_component_to_string_class",
"signature": "def test_model_component_to_string_class(self)"
},
{
"docstring": "Ensures correct output from model_component_to... | 3 | stack_v2_sparse_classes_30k_train_035585 | Implement the Python class `ModelInterpretationTests` described below.
Class description:
Each method is a unit test for model_interpretation.py.
Method signatures and docstrings:
- def test_model_component_to_string_class(self): Ensures correct output from model_component_to_string. In this case, the component is an... | Implement the Python class `ModelInterpretationTests` described below.
Class description:
Each method is a unit test for model_interpretation.py.
Method signatures and docstrings:
- def test_model_component_to_string_class(self): Ensures correct output from model_component_to_string. In this case, the component is an... | 1835a71ababb7ad7e47bfa19e62948d466559d56 | <|skeleton|>
class ModelInterpretationTests:
"""Each method is a unit test for model_interpretation.py."""
def test_model_component_to_string_class(self):
"""Ensures correct output from model_component_to_string. In this case, the component is an output class."""
<|body_0|>
def test_model_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelInterpretationTests:
"""Each method is a unit test for model_interpretation.py."""
def test_model_component_to_string_class(self):
"""Ensures correct output from model_component_to_string. In this case, the component is an output class."""
this_verbose_string, this_abbrev_string = mo... | the_stack_v2_python_sparse | gewittergefahr/deep_learning/model_interpretation_test.py | thunderhoser/GewitterGefahr | train | 29 |
a5bec19a18ad7ebeda6e191272e9ba4e471ce6d9 | [
"if not root:\n return ''\nres = []\nq = collections.deque([root])\nwhile q:\n node = q.popleft()\n if node:\n res.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\n else:\n res.append(str(-1))\nreturn ','.join(res)",
"if not data:\n return None\ndata_q... | <|body_start_0|>
if not root:
return ''
res = []
q = collections.deque([root])
while q:
node = q.popleft()
if node:
res.append(str(node.val))
q.append(node.left)
q.append(node.right)
else:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070229 | 1,442 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: Optional[TreeNode]) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> Optional[TreeNode... | 2 | stack_v2_sparse_classes_30k_train_004145 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree.
<... | c7a42753b2b16c7b9c66b8d7c2e67b683a15e27d | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
res = []
q = collections.deque([root])
while q:
node = q.popleft()
if node:
res.append(str(no... | the_stack_v2_python_sparse | medium/449.py | brandoneng000/LeetCode | train | 0 | |
82157eed34835feedd5e9923b7153c728b7de506 | [
"FirstYearMedSchool.__init__(self)\nself.attribs_et_valeurs = attribs_et_valeurs\ndel self.attribs_et_valeurs['age']\ndel self.attribs_et_valeurs['sex']\nself.titre = 'médecin diplomé'",
"traitement = '1'\nif k not in range(1, len(self.attribs_et_valeurs) + 1):\n raise ValueError('Le nombre de symptômes n est ... | <|body_start_0|>
FirstYearMedSchool.__init__(self)
self.attribs_et_valeurs = attribs_et_valeurs
del self.attribs_et_valeurs['age']
del self.attribs_et_valeurs['sex']
self.titre = 'médecin diplomé'
<|end_body_0|>
<|body_start_1|>
traitement = '1'
if k not in range... | Docteur | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Docteur:
def __init__(self, attribs_et_valeurs):
""":param regles: Générateur de règles contenant les règles générées par l'arbre :param attribs_et_valeurs:liste des attributs et des valeurs possibles"""
<|body_0|>
def traitement(self, patient, k):
"""Prescrit un tra... | stack_v2_sparse_classes_75kplus_train_070230 | 5,378 | no_license | [
{
"docstring": ":param regles: Générateur de règles contenant les règles générées par l'arbre :param attribs_et_valeurs:liste des attributs et des valeurs possibles",
"name": "__init__",
"signature": "def __init__(self, attribs_et_valeurs)"
},
{
"docstring": "Prescrit un traitement à un patient.... | 5 | null | Implement the Python class `Docteur` described below.
Class description:
Implement the Docteur class.
Method signatures and docstrings:
- def __init__(self, attribs_et_valeurs): :param regles: Générateur de règles contenant les règles générées par l'arbre :param attribs_et_valeurs:liste des attributs et des valeurs p... | Implement the Python class `Docteur` described below.
Class description:
Implement the Docteur class.
Method signatures and docstrings:
- def __init__(self, attribs_et_valeurs): :param regles: Générateur de règles contenant les règles générées par l'arbre :param attribs_et_valeurs:liste des attributs et des valeurs p... | 20f4bdaf73b7aa59b39a94dc586ccc25392204d6 | <|skeleton|>
class Docteur:
def __init__(self, attribs_et_valeurs):
""":param regles: Générateur de règles contenant les règles générées par l'arbre :param attribs_et_valeurs:liste des attributs et des valeurs possibles"""
<|body_0|>
def traitement(self, patient, k):
"""Prescrit un tra... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Docteur:
def __init__(self, attribs_et_valeurs):
""":param regles: Générateur de règles contenant les règles générées par l'arbre :param attribs_et_valeurs:liste des attributs et des valeurs possibles"""
FirstYearMedSchool.__init__(self)
self.attribs_et_valeurs = attribs_et_valeurs
... | the_stack_v2_python_sparse | moteur_diagnostic/docteur.py | RenardDesNeiges/CS-330_Project_2020 | train | 0 | |
adf72916a0f8dd10be0381de0aeb7948abcaf351 | [
"super(CustomUpdater, self).__init__(iterator, optimizer)\nself.model = model\nself.grad_clip = grad_clip\nself.device = device\nself.clip_grad_norm = torch.nn.utils.clip_grad_norm_\nself.accum_grad = accum_grad\nself.forward_count = 0",
"train_iter = self.get_iterator('main')\noptimizer = self.get_optimizer('mai... | <|body_start_0|>
super(CustomUpdater, self).__init__(iterator, optimizer)
self.model = model
self.grad_clip = grad_clip
self.device = device
self.clip_grad_norm = torch.nn.utils.clip_grad_norm_
self.accum_grad = accum_grad
self.forward_count = 0
<|end_body_0|>
<|... | Custom updater. | CustomUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUpdater:
"""Custom updater."""
def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1):
"""Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset... | stack_v2_sparse_classes_75kplus_train_070231 | 26,532 | permissive | [
{
"docstring": "Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset.Iterator): Iterator for training. optimizer (torch.optim.Optimizer) : Pytorch optimizer instance. device (torch.device): The device ... | 3 | stack_v2_sparse_classes_30k_train_040407 | Implement the Python class `CustomUpdater` described below.
Class description:
Custom updater.
Method signatures and docstrings:
- def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1): Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip... | Implement the Python class `CustomUpdater` described below.
Class description:
Custom updater.
Method signatures and docstrings:
- def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1): Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class CustomUpdater:
"""Custom updater."""
def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1):
"""Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomUpdater:
"""Custom updater."""
def __init__(self, model, grad_clip, iterator, optimizer, device, accum_grad=1):
"""Initilize module. Args: model (torch.nn.Module) model: Pytorch model instance. grad_clip (float) grad_clip : The gradient clipping value. iterator (chainer.dataset.Iterator): I... | the_stack_v2_python_sparse | espnet/tts/pytorch_backend/tts.py | espnet/espnet | train | 7,242 |
85f0336c7172858a0663ef959058988dd8cd52dd | [
"n = len(nums)\nfor i in range(n - 1):\n if nums[i + 1] - nums[i] - 1 >= k:\n return nums[i] + k\n else:\n k -= nums[i + 1] - nums[i] - 1\nreturn nums[-1] + k",
"set1 = set(nums)\nset2 = set(list(range(nums[0], nums[-1] + k + 1)))\nset3 = set2 - set1\nl = sorted(list(set3))\nreturn l[k - 1]"
] | <|body_start_0|>
n = len(nums)
for i in range(n - 1):
if nums[i + 1] - nums[i] - 1 >= k:
return nums[i] + k
else:
k -= nums[i + 1] - nums[i] - 1
return nums[-1] + k
<|end_body_0|>
<|body_start_1|>
set1 = set(nums)
set2 = se... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingElement(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def missingElement2(self, nums, k):
"""超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,9900210] 10 :type nums: List[int] :type k: int :rtype: int"""... | stack_v2_sparse_classes_75kplus_train_070232 | 1,502 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "missingElement",
"signature": "def missingElement(self, nums, k)"
},
{
"docstring": "超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,9900210] 10 :type nums: List[int] :type k: int :rtype: int",
"name": "missi... | 2 | stack_v2_sparse_classes_30k_train_015315 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingElement(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def missingElement2(self, nums, k): 超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingElement(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def missingElement2(self, nums, k): 超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def missingElement(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def missingElement2(self, nums, k):
"""超时 [247645,695157,1735965,4220736,4322043,9465544,9543270,9900210] 10 :type nums: List[int] :type k: int :rtype: int"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def missingElement(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
n = len(nums)
for i in range(n - 1):
if nums[i + 1] - nums[i] - 1 >= k:
return nums[i] + k
else:
k -= nums[i + 1] - nums[i] - 1
... | the_stack_v2_python_sparse | contest/全国高校春季编程大赛/决赛/1. 有序数组中的缺失元素.py | lovehhf/LeetCode | train | 0 | |
20340e5e2658cc6874fba5f9e428a8cd9ac197e6 | [
"engagement_details = WorkflowCollectionEngagementDetail.objects.filter(workflow_collection_engagement=id, workflow_collection_engagement__user=request.user)\nserializer = WorkflowCollectionEngagementDetailSerializer(engagement_details, context={'request': request}, many=True)\nreturn Response(data=serializer.data)... | <|body_start_0|>
engagement_details = WorkflowCollectionEngagementDetail.objects.filter(workflow_collection_engagement=id, workflow_collection_engagement__user=request.user)
serializer = WorkflowCollectionEngagementDetailSerializer(engagement_details, context={'request': request}, many=True)
ret... | **Supported HTTP Methods** * Get: Retrieve summary representations of all WorkflowCollectionEngagementDetails for a given WorkflowEngagement belonging to the requesting user. * Post: Create a new WorkflowCollectionEngagementDetail resource for a given WorkflowEngagement on behalf of the requesting user. | WorkflowCollectionEngagementDetailsView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowCollectionEngagementDetailsView:
"""**Supported HTTP Methods** * Get: Retrieve summary representations of all WorkflowCollectionEngagementDetails for a given WorkflowEngagement belonging to the requesting user. * Post: Create a new WorkflowCollectionEngagementDetail resource for a given W... | stack_v2_sparse_classes_75kplus_train_070233 | 15,762 | permissive | [
{
"docstring": "Retrieve WorkflowCollectionEngagementDetail representations associated with a given WorkflowEngagement for current user. Path Parameters: id (str): The UUID of the WorkflowEngagement to retrieve details on. Returns: A HTTP response containing a list-like JSON representation of the subscription w... | 2 | stack_v2_sparse_classes_30k_train_024560 | Implement the Python class `WorkflowCollectionEngagementDetailsView` described below.
Class description:
**Supported HTTP Methods** * Get: Retrieve summary representations of all WorkflowCollectionEngagementDetails for a given WorkflowEngagement belonging to the requesting user. * Post: Create a new WorkflowCollection... | Implement the Python class `WorkflowCollectionEngagementDetailsView` described below.
Class description:
**Supported HTTP Methods** * Get: Retrieve summary representations of all WorkflowCollectionEngagementDetails for a given WorkflowEngagement belonging to the requesting user. * Post: Create a new WorkflowCollection... | dc0e8807263266713d3d7fa46e240e8d72db28d1 | <|skeleton|>
class WorkflowCollectionEngagementDetailsView:
"""**Supported HTTP Methods** * Get: Retrieve summary representations of all WorkflowCollectionEngagementDetails for a given WorkflowEngagement belonging to the requesting user. * Post: Create a new WorkflowCollectionEngagementDetail resource for a given W... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowCollectionEngagementDetailsView:
"""**Supported HTTP Methods** * Get: Retrieve summary representations of all WorkflowCollectionEngagementDetails for a given WorkflowEngagement belonging to the requesting user. * Post: Create a new WorkflowCollectionEngagementDetail resource for a given WorkflowEngage... | the_stack_v2_python_sparse | django_workflow_system/api/views/user/workflows/engagement_detail.py | kwang1971/django-workflow-system | train | 0 |
017e44a15e91b41a507242976abb31e014c20d4c | [
"LS.LinearSpectrum.__init__(self, verbose=verbose, **kwargs)\nif self.verbose > 1:\n print('NistTools.nist.__init__()')\nif verbose > 2:\n print('kwargs:')\n for k, v in kwargs.items():\n print(' {:} : {:}'.format(k, v))\nself.path = kwargs.get('path', None)\nself.filename = kwargs.get('filename', ... | <|body_start_0|>
LS.LinearSpectrum.__init__(self, verbose=verbose, **kwargs)
if self.verbose > 1:
print('NistTools.nist.__init__()')
if verbose > 2:
print('kwargs:')
for k, v in kwargs.items():
print(' {:} : {:}'.format(k, v))
self.pat... | Attributes ---------- Notes ----- - 2019-03-03/RB: started class | nist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class nist:
"""Attributes ---------- Notes ----- - 2019-03-03/RB: started class"""
def __init__(self, verbose=0, **kwargs):
"""Arguments --------- path : Path Path to the file filename : Path Filename Notes ----- - 2019-03-03/RB: started function"""
<|body_0|>
def import_data(... | stack_v2_sparse_classes_75kplus_train_070234 | 4,267 | no_license | [
{
"docstring": "Arguments --------- path : Path Path to the file filename : Path Filename Notes ----- - 2019-03-03/RB: started function",
"name": "__init__",
"signature": "def __init__(self, verbose=0, **kwargs)"
},
{
"docstring": "Import the data. self.path and self.filename should have been se... | 3 | stack_v2_sparse_classes_30k_train_051061 | Implement the Python class `nist` described below.
Class description:
Attributes ---------- Notes ----- - 2019-03-03/RB: started class
Method signatures and docstrings:
- def __init__(self, verbose=0, **kwargs): Arguments --------- path : Path Path to the file filename : Path Filename Notes ----- - 2019-03-03/RB: sta... | Implement the Python class `nist` described below.
Class description:
Attributes ---------- Notes ----- - 2019-03-03/RB: started class
Method signatures and docstrings:
- def __init__(self, verbose=0, **kwargs): Arguments --------- path : Path Path to the file filename : Path Filename Notes ----- - 2019-03-03/RB: sta... | 9a6ed081f6a94a554a15d50bdae766cc8a4aec07 | <|skeleton|>
class nist:
"""Attributes ---------- Notes ----- - 2019-03-03/RB: started class"""
def __init__(self, verbose=0, **kwargs):
"""Arguments --------- path : Path Path to the file filename : Path Filename Notes ----- - 2019-03-03/RB: started function"""
<|body_0|>
def import_data(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class nist:
"""Attributes ---------- Notes ----- - 2019-03-03/RB: started class"""
def __init__(self, verbose=0, **kwargs):
"""Arguments --------- path : Path Path to the file filename : Path Filename Notes ----- - 2019-03-03/RB: started function"""
LS.LinearSpectrum.__init__(self, verbose=verb... | the_stack_v2_python_sparse | nist.py | robbertbloem/SpectraTools | train | 0 |
64442154adfcbd553fd688ac048bc6595cd7042e | [
"self.name = name\nself.courses = {'courses': courses}\nself.students = {'students': []}\nself.teachers = {'teachers': []}\nself.begin_date = datetime.datetime.now()\nself.status = 0",
"print(' 班级信息 '.center(50, '-'))\nprint('class name: ')\nprint('\\x1b[34;1m{}\\x1b[0m'.format(self.name))\nprint('teachers: ')\nf... | <|body_start_0|>
self.name = name
self.courses = {'courses': courses}
self.students = {'students': []}
self.teachers = {'teachers': []}
self.begin_date = datetime.datetime.now()
self.status = 0
<|end_body_0|>
<|body_start_1|>
print(' 班级信息 '.center(50, '-'))
... | 班级类 | Grade | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grade:
"""班级类"""
def __init__(self, name, courses):
"""定义班级属性 :param name: 班级名称,字符属性 :param courses: 学习课程名称,字典类型 :param students: 学员,字典类型 :param teachers: 讲师,字典类型 :param begin_date: 开课时间,默认为班级创建时间 :param status: 是否已开课,默认开课后不允许添加新成员 0 为开课, 1 为已开课"""
<|body_0|>
def show_in... | stack_v2_sparse_classes_75kplus_train_070235 | 1,393 | no_license | [
{
"docstring": "定义班级属性 :param name: 班级名称,字符属性 :param courses: 学习课程名称,字典类型 :param students: 学员,字典类型 :param teachers: 讲师,字典类型 :param begin_date: 开课时间,默认为班级创建时间 :param status: 是否已开课,默认开课后不允许添加新成员 0 为开课, 1 为已开课",
"name": "__init__",
"signature": "def __init__(self, name, courses)"
},
{
"docstring": ... | 2 | stack_v2_sparse_classes_30k_train_021753 | Implement the Python class `Grade` described below.
Class description:
班级类
Method signatures and docstrings:
- def __init__(self, name, courses): 定义班级属性 :param name: 班级名称,字符属性 :param courses: 学习课程名称,字典类型 :param students: 学员,字典类型 :param teachers: 讲师,字典类型 :param begin_date: 开课时间,默认为班级创建时间 :param status: 是否已开课,默认开课后不允许添... | Implement the Python class `Grade` described below.
Class description:
班级类
Method signatures and docstrings:
- def __init__(self, name, courses): 定义班级属性 :param name: 班级名称,字符属性 :param courses: 学习课程名称,字典类型 :param students: 学员,字典类型 :param teachers: 讲师,字典类型 :param begin_date: 开课时间,默认为班级创建时间 :param status: 是否已开课,默认开课后不允许添... | 8e304b8ee0680555f328270845ba9a4b5c25f393 | <|skeleton|>
class Grade:
"""班级类"""
def __init__(self, name, courses):
"""定义班级属性 :param name: 班级名称,字符属性 :param courses: 学习课程名称,字典类型 :param students: 学员,字典类型 :param teachers: 讲师,字典类型 :param begin_date: 开课时间,默认为班级创建时间 :param status: 是否已开课,默认开课后不允许添加新成员 0 为开课, 1 为已开课"""
<|body_0|>
def show_in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grade:
"""班级类"""
def __init__(self, name, courses):
"""定义班级属性 :param name: 班级名称,字符属性 :param courses: 学习课程名称,字典类型 :param students: 学员,字典类型 :param teachers: 讲师,字典类型 :param begin_date: 开课时间,默认为班级创建时间 :param status: 是否已开课,默认开课后不允许添加新成员 0 为开课, 1 为已开课"""
self.name = name
self.courses = ... | the_stack_v2_python_sparse | Course_selection_system/course_selection_system/lib/grade.py | sdxy0506/pystudy | train | 0 |
3656641b2029ebf0abfcc07bd24468b297a97533 | [
"CoreBlock.__init__(self, Block.types.DIRECTORY, file_context)\nfor attr in ['target', 'source']:\n self.path_attrs.add(attr)\nfor attr in ['target']:\n self.min_attrs.add(attr)\nself.primary_attr = 'target'",
"act = create.DirCreateAction(dirname, self.file_context)\nif 'mode' in self:\n act = ActionLis... | <|body_start_0|>
CoreBlock.__init__(self, Block.types.DIRECTORY, file_context)
for attr in ['target', 'source']:
self.path_attrs.add(attr)
for attr in ['target']:
self.min_attrs.add(attr)
self.primary_attr = 'target'
<|end_body_0|>
<|body_start_1|>
act = ... | A directory block describes an action performed on a directory. This includes creation, deletion, and copying from source. | DirBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirBlock:
"""A directory block describes an action performed on a directory. This includes creation, deletion, and copying from source."""
def __init__(self, file_context):
"""Directory Block constructor. Args: @file_context The FileContext for this block."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_070236 | 6,593 | permissive | [
{
"docstring": "Directory Block constructor. Args: @file_context The FileContext for this block.",
"name": "__init__",
"signature": "def __init__(self, file_context)"
},
{
"docstring": "Creates a shell action to create the specified directory with the block's mode if set. Useful throughout dir a... | 5 | null | Implement the Python class `DirBlock` described below.
Class description:
A directory block describes an action performed on a directory. This includes creation, deletion, and copying from source.
Method signatures and docstrings:
- def __init__(self, file_context): Directory Block constructor. Args: @file_context Th... | Implement the Python class `DirBlock` described below.
Class description:
A directory block describes an action performed on a directory. This includes creation, deletion, and copying from source.
Method signatures and docstrings:
- def __init__(self, file_context): Directory Block constructor. Args: @file_context Th... | 5711b5c71e39b958bc8185c6b893358de7598ae2 | <|skeleton|>
class DirBlock:
"""A directory block describes an action performed on a directory. This includes creation, deletion, and copying from source."""
def __init__(self, file_context):
"""Directory Block constructor. Args: @file_context The FileContext for this block."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirBlock:
"""A directory block describes an action performed on a directory. This includes creation, deletion, and copying from source."""
def __init__(self, file_context):
"""Directory Block constructor. Args: @file_context The FileContext for this block."""
CoreBlock.__init__(self, Bloc... | the_stack_v2_python_sparse | salve/block/directory.py | sirosen/SALVE | train | 0 |
07aaab1862077c0edbec886152b7e1f3cb76dc8c | [
"air = InsufficientOutsideAir()\nif isinstance(air, InsufficientOutsideAir):\n assert True\nelse:\n assert False",
"air = InsufficientOutsideAir()\ndata_window = td(minutes=1)\nresults = []\nair.set_class_values('test', results, data_window, 1, 10.0)\nassert air.data_window == td(minutes=1)\nassert air.no_r... | <|body_start_0|>
air = InsufficientOutsideAir()
if isinstance(air, InsufficientOutsideAir):
assert True
else:
assert False
<|end_body_0|>
<|body_start_1|>
air = InsufficientOutsideAir()
data_window = td(minutes=1)
results = []
air.set_clas... | Contains all the tests for Insufficient Outside Air Diagnostic | TestDiagnosticsInsufficientOutsideAir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDiagnosticsInsufficientOutsideAir:
"""Contains all the tests for Insufficient Outside Air Diagnostic"""
def test_insufficient_outside_air_creation(self):
"""test the creation of excess_outside_air diagnostic class"""
<|body_0|>
def test_insufficient_ouside_air_set_va... | stack_v2_sparse_classes_75kplus_train_070237 | 42,174 | permissive | [
{
"docstring": "test the creation of excess_outside_air diagnostic class",
"name": "test_insufficient_outside_air_creation",
"signature": "def test_insufficient_outside_air_creation(self)"
},
{
"docstring": "test the Insufficient_outside_air set values method",
"name": "test_insufficient_ous... | 6 | stack_v2_sparse_classes_30k_train_049183 | Implement the Python class `TestDiagnosticsInsufficientOutsideAir` described below.
Class description:
Contains all the tests for Insufficient Outside Air Diagnostic
Method signatures and docstrings:
- def test_insufficient_outside_air_creation(self): test the creation of excess_outside_air diagnostic class
- def tes... | Implement the Python class `TestDiagnosticsInsufficientOutsideAir` described below.
Class description:
Contains all the tests for Insufficient Outside Air Diagnostic
Method signatures and docstrings:
- def test_insufficient_outside_air_creation(self): test the creation of excess_outside_air diagnostic class
- def tes... | 24d50729aef8d91036cc13b0f5c03be76f3237ed | <|skeleton|>
class TestDiagnosticsInsufficientOutsideAir:
"""Contains all the tests for Insufficient Outside Air Diagnostic"""
def test_insufficient_outside_air_creation(self):
"""test the creation of excess_outside_air diagnostic class"""
<|body_0|>
def test_insufficient_ouside_air_set_va... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDiagnosticsInsufficientOutsideAir:
"""Contains all the tests for Insufficient Outside Air Diagnostic"""
def test_insufficient_outside_air_creation(self):
"""test the creation of excess_outside_air diagnostic class"""
air = InsufficientOutsideAir()
if isinstance(air, Insufficie... | the_stack_v2_python_sparse | EnergyEfficiency/EconomizerRCxAgent/economizer/test.py | shwethanidd/volttron-pnnl-applications-2 | train | 0 |
f081faa062dde9bd33d6f2b360a71e713dc07952 | [
"user = kwargs.get('__user', None)\nresponse = None\ntry:\n page = int(req.GET.get('page', '1'))\n if page < 1:\n raise ValueError()\n all_pages = Paginator(get_application_model().objects.filter(Q(user=user) | Q(user=None)).order_by('id'), 25)\n curr_page = all_pages.page(page)\n response = R... | <|body_start_0|>
user = kwargs.get('__user', None)
response = None
try:
page = int(req.GET.get('page', '1'))
if page < 1:
raise ValueError()
all_pages = Paginator(get_application_model().objects.filter(Q(user=user) | Q(user=None)).order_by('id'... | ApplicationListHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationListHandler:
def get(self, req, **kwargs):
"""@api {get} /oauth/applications/ Get OAuth app list @apiName GetOAuthAppList @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} [page] Specifies the page number (starting from 1, per page 25 elements) @api... | stack_v2_sparse_classes_75kplus_train_070238 | 42,340 | no_license | [
{
"docstring": "@api {get} /oauth/applications/ Get OAuth app list @apiName GetOAuthAppList @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} [page] Specifies the page number (starting from 1, per page 25 elements) @apiSuccess {Object} payload Response object @apiSuccess {Number} pay... | 2 | stack_v2_sparse_classes_30k_train_044453 | Implement the Python class `ApplicationListHandler` described below.
Class description:
Implement the ApplicationListHandler class.
Method signatures and docstrings:
- def get(self, req, **kwargs): @api {get} /oauth/applications/ Get OAuth app list @apiName GetOAuthAppList @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPe... | Implement the Python class `ApplicationListHandler` described below.
Class description:
Implement the ApplicationListHandler class.
Method signatures and docstrings:
- def get(self, req, **kwargs): @api {get} /oauth/applications/ Get OAuth app list @apiName GetOAuthAppList @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPe... | 251c7dd0d8ae4756a684ec90c38392866b67d0bb | <|skeleton|>
class ApplicationListHandler:
def get(self, req, **kwargs):
"""@api {get} /oauth/applications/ Get OAuth app list @apiName GetOAuthAppList @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} [page] Specifies the page number (starting from 1, per page 25 elements) @api... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApplicationListHandler:
def get(self, req, **kwargs):
"""@api {get} /oauth/applications/ Get OAuth app list @apiName GetOAuthAppList @apiGroup OAuthMgmt @apiVersion 0.1.0 @apiPermission admin @apiParam {Number} [page] Specifies the page number (starting from 1, per page 25 elements) @apiSuccess {Objec... | the_stack_v2_python_sparse | backend/user_model/views.py | zx1239856/Cloud-Scheduler-OJ | train | 0 | |
ad172e5a3e540aefdba0482081d3aa7db0343e33 | [
"capa = crear_capa()\nself.assertEqual(capa.metadatos is not None, True)\nself.assertEqual(capa.mapserverlayer is not None, True)",
"c = Client()\nresponse = c.get(reverse('layers:detalle_capa_por_id', args=(1,)))\nself.assertEqual(response.status_code, 404)\ncapa = crear_capa(nombre='prueba333')\nresponse = c.ge... | <|body_start_0|>
capa = crear_capa()
self.assertEqual(capa.metadatos is not None, True)
self.assertEqual(capa.mapserverlayer is not None, True)
<|end_body_0|>
<|body_start_1|>
c = Client()
response = c.get(reverse('layers:detalle_capa_por_id', args=(1,)))
self.assertEqua... | CapaMethodTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CapaMethodTests:
def test_crear_capa_crea_dependencias_1a1(self):
"""Toda Capa debe tener un Metadatos y un MapServerLayer"""
<|body_0|>
def test_detalle_capa_por_id(self):
"""Detalle Capa por id"""
<|body_1|>
def test_ultimas(self):
"""Test de u... | stack_v2_sparse_classes_75kplus_train_070239 | 2,901 | permissive | [
{
"docstring": "Toda Capa debe tener un Metadatos y un MapServerLayer",
"name": "test_crear_capa_crea_dependencias_1a1",
"signature": "def test_crear_capa_crea_dependencias_1a1(self)"
},
{
"docstring": "Detalle Capa por id",
"name": "test_detalle_capa_por_id",
"signature": "def test_deta... | 4 | stack_v2_sparse_classes_30k_train_004085 | Implement the Python class `CapaMethodTests` described below.
Class description:
Implement the CapaMethodTests class.
Method signatures and docstrings:
- def test_crear_capa_crea_dependencias_1a1(self): Toda Capa debe tener un Metadatos y un MapServerLayer
- def test_detalle_capa_por_id(self): Detalle Capa por id
- d... | Implement the Python class `CapaMethodTests` described below.
Class description:
Implement the CapaMethodTests class.
Method signatures and docstrings:
- def test_crear_capa_crea_dependencias_1a1(self): Toda Capa debe tener un Metadatos y un MapServerLayer
- def test_detalle_capa_por_id(self): Detalle Capa por id
- d... | e0f345ec137fe31f51ebf28b77e38fb8037fb978 | <|skeleton|>
class CapaMethodTests:
def test_crear_capa_crea_dependencias_1a1(self):
"""Toda Capa debe tener un Metadatos y un MapServerLayer"""
<|body_0|>
def test_detalle_capa_por_id(self):
"""Detalle Capa por id"""
<|body_1|>
def test_ultimas(self):
"""Test de u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CapaMethodTests:
def test_crear_capa_crea_dependencias_1a1(self):
"""Toda Capa debe tener un Metadatos y un MapServerLayer"""
capa = crear_capa()
self.assertEqual(capa.metadatos is not None, True)
self.assertEqual(capa.mapserverlayer is not None, True)
def test_detalle_cap... | the_stack_v2_python_sparse | layers/tests.py | pcecconi/mapground | train | 0 | |
1d577e94c374924f73b8c291c197408ac148301b | [
"self.logger = logging.getLogger(name)\nhandler = logging.FileHandler(filename=file_path)\nself.logger.setLevel(logging.INFO)\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(message)s')\nhandler.setFormatter(formatter)\nself.logger.addHandler(handler)",
"if with_time:\n date_str = datetime.da... | <|body_start_0|>
self.logger = logging.getLogger(name)
handler = logging.FileHandler(filename=file_path)
self.logger.setLevel(logging.INFO)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(message)s')
handler.setFormatter(formatter)
self.logger.addH... | Logger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Logger:
def __init__(self, file_path, name='logger'):
"""Initialize the log class :param file_path: Log file path"""
<|body_0|>
def out_print(self, line, with_time=False):
"""Print output to file :param with_time: Whether to print the date :param line: Input text lin... | stack_v2_sparse_classes_75kplus_train_070240 | 1,020 | no_license | [
{
"docstring": "Initialize the log class :param file_path: Log file path",
"name": "__init__",
"signature": "def __init__(self, file_path, name='logger')"
},
{
"docstring": "Print output to file :param with_time: Whether to print the date :param line: Input text line :return: None",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_036760 | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self, file_path, name='logger'): Initialize the log class :param file_path: Log file path
- def out_print(self, line, with_time=False): Print output to file :param with_... | Implement the Python class `Logger` described below.
Class description:
Implement the Logger class.
Method signatures and docstrings:
- def __init__(self, file_path, name='logger'): Initialize the log class :param file_path: Log file path
- def out_print(self, line, with_time=False): Print output to file :param with_... | 1e2ee783a0ddbb460e2b77d480c4cfe680e7cef5 | <|skeleton|>
class Logger:
def __init__(self, file_path, name='logger'):
"""Initialize the log class :param file_path: Log file path"""
<|body_0|>
def out_print(self, line, with_time=False):
"""Print output to file :param with_time: Whether to print the date :param line: Input text lin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Logger:
def __init__(self, file_path, name='logger'):
"""Initialize the log class :param file_path: Log file path"""
self.logger = logging.getLogger(name)
handler = logging.FileHandler(filename=file_path)
self.logger.setLevel(logging.INFO)
handler.setLevel(logging.INFO)... | the_stack_v2_python_sparse | utils/common.py | Tanny16/hierarchy-classification | train | 0 | |
8228042941c2133364bfd382005fd6823d56ca4d | [
"flash_sale_ids = []\ndetail_id2promotion = {}\nfor promotion in promotions:\n flash_sale_ids.append(promotion.context['detail_id'])\n detail_id2promotion[promotion.context['detail_id']] = promotion\nflash_sale_models = promotion_models.FlashSale.select().dj_where(id__in=flash_sale_ids)\nfor model in flash_sa... | <|body_start_0|>
flash_sale_ids = []
detail_id2promotion = {}
for promotion in promotions:
flash_sale_ids.append(promotion.context['detail_id'])
detail_id2promotion[promotion.context['detail_id']] = promotion
flash_sale_models = promotion_models.FlashSale.select()... | 对促销集合批量填充详情服务 | FillPromotionDetailService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillPromotionDetailService:
"""对促销集合批量填充详情服务"""
def __fill_flash_sale_details(self, promotions):
"""填充限时抢购的详细信息"""
<|body_0|>
def __fill_integral_sale_rule_details(self, promotions):
"""填充与积分应用相关的`积分应用规则`"""
<|body_1|>
def __fill_premium_sale_details... | stack_v2_sparse_classes_75kplus_train_070241 | 6,129 | no_license | [
{
"docstring": "填充限时抢购的详细信息",
"name": "__fill_flash_sale_details",
"signature": "def __fill_flash_sale_details(self, promotions)"
},
{
"docstring": "填充与积分应用相关的`积分应用规则`",
"name": "__fill_integral_sale_rule_details",
"signature": "def __fill_integral_sale_rule_details(self, promotions)"
... | 6 | stack_v2_sparse_classes_30k_train_019569 | Implement the Python class `FillPromotionDetailService` described below.
Class description:
对促销集合批量填充详情服务
Method signatures and docstrings:
- def __fill_flash_sale_details(self, promotions): 填充限时抢购的详细信息
- def __fill_integral_sale_rule_details(self, promotions): 填充与积分应用相关的`积分应用规则`
- def __fill_premium_sale_details(sel... | Implement the Python class `FillPromotionDetailService` described below.
Class description:
对促销集合批量填充详情服务
Method signatures and docstrings:
- def __fill_flash_sale_details(self, promotions): 填充限时抢购的详细信息
- def __fill_integral_sale_rule_details(self, promotions): 填充与积分应用相关的`积分应用规则`
- def __fill_premium_sale_details(sel... | 39860a451678ab50ad93ce8ebe2ef8490af65d62 | <|skeleton|>
class FillPromotionDetailService:
"""对促销集合批量填充详情服务"""
def __fill_flash_sale_details(self, promotions):
"""填充限时抢购的详细信息"""
<|body_0|>
def __fill_integral_sale_rule_details(self, promotions):
"""填充与积分应用相关的`积分应用规则`"""
<|body_1|>
def __fill_premium_sale_details... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FillPromotionDetailService:
"""对促销集合批量填充详情服务"""
def __fill_flash_sale_details(self, promotions):
"""填充限时抢购的详细信息"""
flash_sale_ids = []
detail_id2promotion = {}
for promotion in promotions:
flash_sale_ids.append(promotion.context['detail_id'])
detail... | the_stack_v2_python_sparse | business/mall/promotion/fill_promotion_detail_service.py | chengdg/gaia | train | 0 |
6281cbd186b452b80e592ebff488b3bb0195415e | [
"from hw6 import flights\nif flights.numVertices == 0:\n raise unittest.SkipTest('Not attempted yet')",
"from hw6 import flights\nif flights.numVertices == 0:\n raise unittest.SkipTest('Not attempted yet')\nself.assertEqual(47, flights.getVertex('SFO').getDistance())",
"from hw6 import flights\nif flights... | <|body_start_0|>
from hw6 import flights
if flights.numVertices == 0:
raise unittest.SkipTest('Not attempted yet')
<|end_body_0|>
<|body_start_1|>
from hw6 import flights
if flights.numVertices == 0:
raise unittest.SkipTest('Not attempted yet')
self.asser... | TestProblem5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProblem5:
def test_API(self):
"""P5: Sanity Test: Has flights graph been defined?"""
<|body_0|>
def test_flightToSFO(self):
"""P5: Is the flight to San Francisco calculated correctly?"""
<|body_1|>
def test_flightToLAX(self):
"""P5: Is the fl... | stack_v2_sparse_classes_75kplus_train_070242 | 11,669 | no_license | [
{
"docstring": "P5: Sanity Test: Has flights graph been defined?",
"name": "test_API",
"signature": "def test_API(self)"
},
{
"docstring": "P5: Is the flight to San Francisco calculated correctly?",
"name": "test_flightToSFO",
"signature": "def test_flightToSFO(self)"
},
{
"docst... | 5 | stack_v2_sparse_classes_30k_train_008678 | Implement the Python class `TestProblem5` described below.
Class description:
Implement the TestProblem5 class.
Method signatures and docstrings:
- def test_API(self): P5: Sanity Test: Has flights graph been defined?
- def test_flightToSFO(self): P5: Is the flight to San Francisco calculated correctly?
- def test_fli... | Implement the Python class `TestProblem5` described below.
Class description:
Implement the TestProblem5 class.
Method signatures and docstrings:
- def test_API(self): P5: Sanity Test: Has flights graph been defined?
- def test_flightToSFO(self): P5: Is the flight to San Francisco calculated correctly?
- def test_fli... | d4f32507a5f581ad8ee0ce84e6cd92daac0941d7 | <|skeleton|>
class TestProblem5:
def test_API(self):
"""P5: Sanity Test: Has flights graph been defined?"""
<|body_0|>
def test_flightToSFO(self):
"""P5: Is the flight to San Francisco calculated correctly?"""
<|body_1|>
def test_flightToLAX(self):
"""P5: Is the fl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProblem5:
def test_API(self):
"""P5: Sanity Test: Has flights graph been defined?"""
from hw6 import flights
if flights.numVertices == 0:
raise unittest.SkipTest('Not attempted yet')
def test_flightToSFO(self):
"""P5: Is the flight to San Francisco calculat... | the_stack_v2_python_sparse | Homework6/hw6_test.py | pillowfication/ECS-32B | train | 1 | |
f3e1c325abdc4091947b5d1b8d87c9af0878e13d | [
"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... | A set of methods for managing Key resources. | KeyServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyServiceServicer:
"""A set of methods for managing Key resources."""
def Get(self, request, context):
"""Returns the specified Key resource. To get the list of available Key resources, make a [List] request."""
<|body_0|>
def List(self, request, context):
"""Re... | stack_v2_sparse_classes_75kplus_train_070243 | 4,489 | permissive | [
{
"docstring": "Returns the specified Key resource. To get the list of available Key resources, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of Key resources for the specified service account.",
"name": "List",
... | 4 | null | Implement the Python class `KeyServiceServicer` described below.
Class description:
A set of methods for managing Key resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Key resource. To get the list of available Key resources, make a [List] request.
- def List(self, ... | Implement the Python class `KeyServiceServicer` described below.
Class description:
A set of methods for managing Key resources.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified Key resource. To get the list of available Key resources, make a [List] request.
- def List(self, ... | 980e2c5d848eadb42799132b35a9f58ab7b27157 | <|skeleton|>
class KeyServiceServicer:
"""A set of methods for managing Key resources."""
def Get(self, request, context):
"""Returns the specified Key resource. To get the list of available Key resources, make a [List] request."""
<|body_0|>
def List(self, request, context):
"""Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyServiceServicer:
"""A set of methods for managing Key resources."""
def Get(self, request, context):
"""Returns the specified Key resource. To get the list of available Key resources, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details(... | the_stack_v2_python_sparse | yandex/cloud/iam/v1/key_service_pb2_grpc.py | IIKovalenko/python-sdk | train | 1 |
d6780c86c579863d31ca82f7752780366f4af574 | [
"params = params or {}\nif db is None:\n logger.warning('Be careful, you are instanciating a matching without db')\nself.db = db\nself.fingerprinting = fingerprinting",
"current_segment_indexes = np.arange(int(t1 * self.fingerprinting.sr / 50), int(np.ceil(t2 * self.fingerprinting.sr / 50)))\ntracks_scored_uns... | <|body_start_0|>
params = params or {}
if db is None:
logger.warning('Be careful, you are instanciating a matching without db')
self.db = db
self.fingerprinting = fingerprinting
<|end_body_0|>
<|body_start_1|>
current_segment_indexes = np.arange(int(t1 * self.fingerp... | Simplest matching: check if two fingerprints are strictly equal. You have access to self.db, a database instance, and self.fingerprinting | SampleMatching | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleMatching:
"""Simplest matching: check if two fingerprints are strictly equal. You have access to self.db, a database instance, and self.fingerprinting"""
def __init__(self, db, params=None, fingerprinting=None):
"""Initializes the Fingerprinting class. Args: db: an instance of ... | stack_v2_sparse_classes_75kplus_train_070244 | 6,595 | no_license | [
{
"docstring": "Initializes the Fingerprinting class. Args: db: an instance of a child of DbApi params: a dictionary of parameters. Corresponds to params['fingerprint'] fingerprinting: an instance of a child of Fingerprinting.",
"name": "__init__",
"signature": "def __init__(self, db, params=None, finge... | 2 | stack_v2_sparse_classes_30k_train_043479 | Implement the Python class `SampleMatching` described below.
Class description:
Simplest matching: check if two fingerprints are strictly equal. You have access to self.db, a database instance, and self.fingerprinting
Method signatures and docstrings:
- def __init__(self, db, params=None, fingerprinting=None): Initia... | Implement the Python class `SampleMatching` described below.
Class description:
Simplest matching: check if two fingerprints are strictly equal. You have access to self.db, a database instance, and self.fingerprinting
Method signatures and docstrings:
- def __init__(self, db, params=None, fingerprinting=None): Initia... | bb874d019f70f671637b1269ad5c0681fb97715a | <|skeleton|>
class SampleMatching:
"""Simplest matching: check if two fingerprints are strictly equal. You have access to self.db, a database instance, and self.fingerprinting"""
def __init__(self, db, params=None, fingerprinting=None):
"""Initializes the Fingerprinting class. Args: db: an instance of ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SampleMatching:
"""Simplest matching: check if two fingerprints are strictly equal. You have access to self.db, a database instance, and self.fingerprinting"""
def __init__(self, db, params=None, fingerprinting=None):
"""Initializes the Fingerprinting class. Args: db: an instance of a child of Db... | the_stack_v2_python_sparse | traxit_manage/sample_algorithm.py | Trax-air/traxit-manage | train | 0 |
8db85045ef59d09ad6a8ce9c4dbb4bc3f4eaa9c4 | [
"print('Testing homepage route')\nhomepage_url = reverse('home')\nr = self.client.get(homepage_url)\nself.assertEqual(r.status_code, HTTPStatus.OK)\nprint('Finished')",
"print('Testing homepage route post not allowed')\nhomepage_url = reverse('home')\nr = self.client.post(homepage_url)\nself.assertEqual(r.status_... | <|body_start_0|>
print('Testing homepage route')
homepage_url = reverse('home')
r = self.client.get(homepage_url)
self.assertEqual(r.status_code, HTTPStatus.OK)
print('Finished')
<|end_body_0|>
<|body_start_1|>
print('Testing homepage route post not allowed')
hom... | Tests for homepage app and robots txt | TestHomePage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHomePage:
"""Tests for homepage app and robots txt"""
def test_homepage_route_get(self):
"""Tests that we get a 200 response on homepage"""
<|body_0|>
def test_homepage_route_post_not_allowed(self):
"""Tests that post method is denied"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_070245 | 1,670 | permissive | [
{
"docstring": "Tests that we get a 200 response on homepage",
"name": "test_homepage_route_get",
"signature": "def test_homepage_route_get(self)"
},
{
"docstring": "Tests that post method is denied",
"name": "test_homepage_route_post_not_allowed",
"signature": "def test_homepage_route_p... | 4 | stack_v2_sparse_classes_30k_train_027297 | Implement the Python class `TestHomePage` described below.
Class description:
Tests for homepage app and robots txt
Method signatures and docstrings:
- def test_homepage_route_get(self): Tests that we get a 200 response on homepage
- def test_homepage_route_post_not_allowed(self): Tests that post method is denied
- d... | Implement the Python class `TestHomePage` described below.
Class description:
Tests for homepage app and robots txt
Method signatures and docstrings:
- def test_homepage_route_get(self): Tests that we get a 200 response on homepage
- def test_homepage_route_post_not_allowed(self): Tests that post method is denied
- d... | 12df4fedfe3f39c03a898a229a96c431627d19bd | <|skeleton|>
class TestHomePage:
"""Tests for homepage app and robots txt"""
def test_homepage_route_get(self):
"""Tests that we get a 200 response on homepage"""
<|body_0|>
def test_homepage_route_post_not_allowed(self):
"""Tests that post method is denied"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestHomePage:
"""Tests for homepage app and robots txt"""
def test_homepage_route_get(self):
"""Tests that we get a 200 response on homepage"""
print('Testing homepage route')
homepage_url = reverse('home')
r = self.client.get(homepage_url)
self.assertEqual(r.statu... | the_stack_v2_python_sparse | my_homepage/homepage/tests.py | beasyx0/my_homepage | train | 0 |
ec7965fea21fc755fd953f35384ff724aac0210a | [
"print('Initializing, may take several minutes...')\nstart_time = time.time()\ntry:\n nltk.data.find('tokenizers/punkt.zip')\nexcept LookupError:\n nltk.download('punkt')\ntry:\n nltk.data.find('corpora/stopwords.zip')\nexcept LookupError:\n nltk.download('stopwords')\nself.pattern = '((http|ftp|https):... | <|body_start_0|>
print('Initializing, may take several minutes...')
start_time = time.time()
try:
nltk.data.find('tokenizers/punkt.zip')
except LookupError:
nltk.download('punkt')
try:
nltk.data.find('corpora/stopwords.zip')
except Look... | Methods about text embedding, initializing this class is expensive | TextEmbedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextEmbedding:
"""Methods about text embedding, initializing this class is expensive"""
def __init__(self, model_path):
"""doing Initialization work :param model_path: the path to the google pre-trained language model"""
<|body_0|>
def _vectors_mean(word_vectors):
... | stack_v2_sparse_classes_75kplus_train_070246 | 4,229 | no_license | [
{
"docstring": "doing Initialization work :param model_path: the path to the google pre-trained language model",
"name": "__init__",
"signature": "def __init__(self, model_path)"
},
{
"docstring": "get the mean of a bunch of vectors :param word_vectors: a bag / list of vectors :return:",
"na... | 6 | null | Implement the Python class `TextEmbedding` described below.
Class description:
Methods about text embedding, initializing this class is expensive
Method signatures and docstrings:
- def __init__(self, model_path): doing Initialization work :param model_path: the path to the google pre-trained language model
- def _ve... | Implement the Python class `TextEmbedding` described below.
Class description:
Methods about text embedding, initializing this class is expensive
Method signatures and docstrings:
- def __init__(self, model_path): doing Initialization work :param model_path: the path to the google pre-trained language model
- def _ve... | cd4e9bdca99696da669d46e9dcfe5487a15fcea0 | <|skeleton|>
class TextEmbedding:
"""Methods about text embedding, initializing this class is expensive"""
def __init__(self, model_path):
"""doing Initialization work :param model_path: the path to the google pre-trained language model"""
<|body_0|>
def _vectors_mean(word_vectors):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextEmbedding:
"""Methods about text embedding, initializing this class is expensive"""
def __init__(self, model_path):
"""doing Initialization work :param model_path: the path to the google pre-trained language model"""
print('Initializing, may take several minutes...')
start_tim... | the_stack_v2_python_sparse | src/data_methods/embedding_methods.py | lgh0504/event-driven-research | train | 0 |
dfe91c59d774f4d7d93386b091ea20b446abf875 | [
"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... | InterfaceTagConfigServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterfaceTagConfigServiceServicer:
def GetOne(self, request, context):
"""GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified)."""
<|body_0|>
def GetAll(self, request, context):
... | stack_v2_sparse_classes_75kplus_train_070247 | 30,872 | permissive | [
{
"docstring": "GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified).",
"name": "GetOne",
"signature": "def GetOne(self, request, context)"
},
{
"docstring": "GetAll returns all entities for this model... | 5 | null | Implement the Python class `InterfaceTagConfigServiceServicer` described below.
Class description:
Implement the InterfaceTagConfigServiceServicer class.
Method signatures and docstrings:
- def GetOne(self, request, context): GetOne returns a unary model as specified by the key in the request. The key must be provide... | Implement the Python class `InterfaceTagConfigServiceServicer` described below.
Class description:
Implement the InterfaceTagConfigServiceServicer class.
Method signatures and docstrings:
- def GetOne(self, request, context): GetOne returns a unary model as specified by the key in the request. The key must be provide... | d93b5f66a00b1e3710257d607d62f9d43736304e | <|skeleton|>
class InterfaceTagConfigServiceServicer:
def GetOne(self, request, context):
"""GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified)."""
<|body_0|>
def GetAll(self, request, context):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InterfaceTagConfigServiceServicer:
def GetOne(self, request, context):
"""GetOne returns a unary model as specified by the key in the request. The key must be provided and all fields populated (unless otherwise specified)."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_... | the_stack_v2_python_sparse | CVP_API/Snapshot_Utils/getSnapshots_Resource_API/cloudvision-python/arista/tag/v1/services/gen_pb2_grpc.py | Hugh-Adams/Example_Scripts | train | 4 | |
688e2ba457752838ee6cf63dea15d2040ba6ea1b | [
"super(RandomMazeWalk, self).__init__(speed, maze_layer=maze_layer)\nself._prevent_backtracking = prevent_backtracking\nself._allow_wall_backtracking = allow_wall_backtracking\nself._only_turn_at_wall = only_turn_at_wall",
"if not self._prevent_backtracking:\n return\naxis = np.argmax(np.abs(velocity))\ndirect... | <|body_start_0|>
super(RandomMazeWalk, self).__init__(speed, maze_layer=maze_layer)
self._prevent_backtracking = prevent_backtracking
self._allow_wall_backtracking = allow_wall_backtracking
self._only_turn_at_wall = only_turn_at_wall
<|end_body_0|>
<|body_start_1|>
if not self._... | Random maze walk. | RandomMazeWalk | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomMazeWalk:
"""Random maze walk."""
def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False):
"""Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turn... | stack_v2_sparse_classes_75kplus_train_070248 | 9,606 | permissive | [
{
"docstring": "Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turns at corners and intersections. Args: speed: Float. Speed for the sprite to move at. maze_layer: String. Layer in the environment state containing the maze sprites. prevent_backtracking... | 3 | stack_v2_sparse_classes_30k_train_041353 | Implement the Python class `RandomMazeWalk` described below.
Class description:
Random maze walk.
Method signatures and docstrings:
- def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False): Constructor. Applying this physics to sprites makes th... | Implement the Python class `RandomMazeWalk` described below.
Class description:
Random maze walk.
Method signatures and docstrings:
- def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False): Constructor. Applying this physics to sprites makes th... | 3e89e46a5918d59475851f9d4f1558956c110d38 | <|skeleton|>
class RandomMazeWalk:
"""Random maze walk."""
def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False):
"""Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomMazeWalk:
"""Random maze walk."""
def __init__(self, speed, maze_layer='walls', prevent_backtracking=True, allow_wall_backtracking=False, only_turn_at_wall=False):
"""Constructor. Applying this physics to sprites makes them walk with constant speed in a maze, taking random turns at corners ... | the_stack_v2_python_sparse | moog/physics/maze_walk.py | hokysung/moog.github.io | train | 0 |
cd95b4c58a1b1fc2528d4abf62d4c312692c8b3e | [
"super(RQExperimentJob, self)._unpickle_data()\nself._submitted_func_name = self._func_name\nmodule_path, func_name = self._func_name.split('|')\nmodule_dir = os.path.dirname(module_path)\nsys.path.insert(0, module_dir)\nself._module_dir = module_dir\nself._func_name = f'{os.path.basename(module_path)}.{func_name}'... | <|body_start_0|>
super(RQExperimentJob, self)._unpickle_data()
self._submitted_func_name = self._func_name
module_path, func_name = self._func_name.split('|')
module_dir = os.path.dirname(module_path)
sys.path.insert(0, module_dir)
self._module_dir = module_dir
se... | "RQ Job Subclass with hacks for dynamic module injection | RQExperimentJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RQExperimentJob:
""""RQ Job Subclass with hacks for dynamic module injection"""
def _unpickle_data(self):
"""Override that parses our "fully qualified" function name, adding the functions module to sys.path. :return:"""
<|body_0|>
def perform(self):
"""Override t... | stack_v2_sparse_classes_75kplus_train_070249 | 15,104 | permissive | [
{
"docstring": "Override that parses our \"fully qualified\" function name, adding the functions module to sys.path. :return:",
"name": "_unpickle_data",
"signature": "def _unpickle_data(self)"
},
{
"docstring": "Override that cleans up sys.path and unloads our runtime-imported module after runn... | 2 | stack_v2_sparse_classes_30k_train_039235 | Implement the Python class `RQExperimentJob` described below.
Class description:
"RQ Job Subclass with hacks for dynamic module injection
Method signatures and docstrings:
- def _unpickle_data(self): Override that parses our "fully qualified" function name, adding the functions module to sys.path. :return:
- def perf... | Implement the Python class `RQExperimentJob` described below.
Class description:
"RQ Job Subclass with hacks for dynamic module injection
Method signatures and docstrings:
- def _unpickle_data(self): Override that parses our "fully qualified" function name, adding the functions module to sys.path. :return:
- def perf... | 7a7ab1a6835fd63b9153463dd08bb53630f15c62 | <|skeleton|>
class RQExperimentJob:
""""RQ Job Subclass with hacks for dynamic module injection"""
def _unpickle_data(self):
"""Override that parses our "fully qualified" function name, adding the functions module to sys.path. :return:"""
<|body_0|>
def perform(self):
"""Override t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RQExperimentJob:
""""RQ Job Subclass with hacks for dynamic module injection"""
def _unpickle_data(self):
"""Override that parses our "fully qualified" function name, adding the functions module to sys.path. :return:"""
super(RQExperimentJob, self)._unpickle_data()
self._submitted... | the_stack_v2_python_sparse | pyromancy/experiment.py | braingineer/pyromancy | train | 0 |
18dae89bfd4d11f7a99f2b065a9a8c6d2064bf58 | [
"documents = self.context.documents\nif not self.request.params.get('all', ''):\n documents_top = dict([(document.id, document) for document in documents]).values()\n documents = sorted(documents_top, key=lambda i: i['dateModified'])\nreturn {'data': [document.serialize('view') for document in documents]}",
... | <|body_start_0|>
documents = self.context.documents
if not self.request.params.get('all', ''):
documents_top = dict([(document.id, document) for document in documents]).values()
documents = sorted(documents_top, key=lambda i: i['dateModified'])
return {'data': [document.s... | MonitoringsDocumentBaseResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MonitoringsDocumentBaseResource:
def collection_get(self):
"""Monitoring Documents List"""
<|body_0|>
def collection_post(self):
"""Monitoring Document Upload"""
<|body_1|>
def get(self):
"""Monitoring Document Read"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus_train_070250 | 12,390 | permissive | [
{
"docstring": "Monitoring Documents List",
"name": "collection_get",
"signature": "def collection_get(self)"
},
{
"docstring": "Monitoring Document Upload",
"name": "collection_post",
"signature": "def collection_post(self)"
},
{
"docstring": "Monitoring Document Read",
"nam... | 5 | null | Implement the Python class `MonitoringsDocumentBaseResource` described below.
Class description:
Implement the MonitoringsDocumentBaseResource class.
Method signatures and docstrings:
- def collection_get(self): Monitoring Documents List
- def collection_post(self): Monitoring Document Upload
- def get(self): Monitor... | Implement the Python class `MonitoringsDocumentBaseResource` described below.
Class description:
Implement the MonitoringsDocumentBaseResource class.
Method signatures and docstrings:
- def collection_get(self): Monitoring Documents List
- def collection_post(self): Monitoring Document Upload
- def get(self): Monitor... | 3180cad76e89d68918f29d696a07b7ba2b5ff02e | <|skeleton|>
class MonitoringsDocumentBaseResource:
def collection_get(self):
"""Monitoring Documents List"""
<|body_0|>
def collection_post(self):
"""Monitoring Document Upload"""
<|body_1|>
def get(self):
"""Monitoring Document Read"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MonitoringsDocumentBaseResource:
def collection_get(self):
"""Monitoring Documents List"""
documents = self.context.documents
if not self.request.params.get('all', ''):
documents_top = dict([(document.id, document) for document in documents]).values()
documents ... | the_stack_v2_python_sparse | openprocurement/audit/monitoring/views/document.py | ProzorroUKR/openprocurement.audit.api | train | 1 | |
d1aa093a67e2ac2c0e4322fb53ccedab63b6af3e | [
"export_path = model_config['model_path']\npredict_tensor_name = 'prediction:0'\ninput_tensor_name = 'image:0'\nself._lbl_encoding = model_config['lbl_encoding']\nwith tf.Graph().as_default() as graph:\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1)\n sess = tf.Session(config=tf.ConfigProto... | <|body_start_0|>
export_path = model_config['model_path']
predict_tensor_name = 'prediction:0'
input_tensor_name = 'image:0'
self._lbl_encoding = model_config['lbl_encoding']
with tf.Graph().as_default() as graph:
gpu_options = tf.GPUOptions(per_process_gpu_memory_fra... | InceptionGenderAnalyzer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InceptionGenderAnalyzer:
def __init__(self, model_config):
"""Initialize inception v3 model for gender analysis on face :param model_config: model_config (dict) - 'model_path' is the path to the trained model 'lbl_encoding' is the encoding of the labels in the trained model."""
<... | stack_v2_sparse_classes_75kplus_train_070251 | 2,095 | no_license | [
{
"docstring": "Initialize inception v3 model for gender analysis on face :param model_config: model_config (dict) - 'model_path' is the path to the trained model 'lbl_encoding' is the encoding of the labels in the trained model.",
"name": "__init__",
"signature": "def __init__(self, model_config)"
},... | 2 | stack_v2_sparse_classes_30k_train_007342 | Implement the Python class `InceptionGenderAnalyzer` described below.
Class description:
Implement the InceptionGenderAnalyzer class.
Method signatures and docstrings:
- def __init__(self, model_config): Initialize inception v3 model for gender analysis on face :param model_config: model_config (dict) - 'model_path' ... | Implement the Python class `InceptionGenderAnalyzer` described below.
Class description:
Implement the InceptionGenderAnalyzer class.
Method signatures and docstrings:
- def __init__(self, model_config): Initialize inception v3 model for gender analysis on face :param model_config: model_config (dict) - 'model_path' ... | 68d7256e98b4fdd01822e618511e9c730729423f | <|skeleton|>
class InceptionGenderAnalyzer:
def __init__(self, model_config):
"""Initialize inception v3 model for gender analysis on face :param model_config: model_config (dict) - 'model_path' is the path to the trained model 'lbl_encoding' is the encoding of the labels in the trained model."""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InceptionGenderAnalyzer:
def __init__(self, model_config):
"""Initialize inception v3 model for gender analysis on face :param model_config: model_config (dict) - 'model_path' is the path to the trained model 'lbl_encoding' is the encoding of the labels in the trained model."""
export_path = m... | the_stack_v2_python_sparse | face_analyzers/inception_gender_analyzer.py | qidiso/human-ai | train | 0 | |
83b5b4b788414ad955dc0084c7766a3876a9abd7 | [
"self.target_concentration = torch.tensor(target_concentration, dtype=torch.float32)\nself.concentration = concentration\nself.reverse = reverse\nself.alpha_fix = alpha_fix",
"alphas = torch.exp(logits)\nif self.alpha_fix:\n alphas = alphas + 1\ntarget_alphas = torch.ones_like(alphas) * self.concentration\nif ... | <|body_start_0|>
self.target_concentration = torch.tensor(target_concentration, dtype=torch.float32)
self.concentration = concentration
self.reverse = reverse
self.alpha_fix = alpha_fix
<|end_body_0|>
<|body_start_1|>
alphas = torch.exp(logits)
if self.alpha_fix:
... | Can be applied to any model which returns logits | DirichletKLLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirichletKLLoss:
"""Can be applied to any model which returns logits"""
def __init__(self, target_concentration=1000.0, concentration=1.0, reverse=True, alpha_fix=False):
""":param target_concentration: The concentration parameter for the target class (if provided) :param concentrati... | stack_v2_sparse_classes_75kplus_train_070252 | 8,832 | no_license | [
{
"docstring": ":param target_concentration: The concentration parameter for the target class (if provided) :param concentration: The 'base' concentration parameters for non-target classes. :param alpha_fix: If set to true make the minimum output alpha for the dirichlet 1 fixing the issue of degenerate paramete... | 2 | stack_v2_sparse_classes_30k_train_054257 | Implement the Python class `DirichletKLLoss` described below.
Class description:
Can be applied to any model which returns logits
Method signatures and docstrings:
- def __init__(self, target_concentration=1000.0, concentration=1.0, reverse=True, alpha_fix=False): :param target_concentration: The concentration parame... | Implement the Python class `DirichletKLLoss` described below.
Class description:
Can be applied to any model which returns logits
Method signatures and docstrings:
- def __init__(self, target_concentration=1000.0, concentration=1.0, reverse=True, alpha_fix=False): :param target_concentration: The concentration parame... | c73e0f4a469375c052cc2ca9f311f3612b158ea1 | <|skeleton|>
class DirichletKLLoss:
"""Can be applied to any model which returns logits"""
def __init__(self, target_concentration=1000.0, concentration=1.0, reverse=True, alpha_fix=False):
""":param target_concentration: The concentration parameter for the target class (if provided) :param concentrati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DirichletKLLoss:
"""Can be applied to any model which returns logits"""
def __init__(self, target_concentration=1000.0, concentration=1.0, reverse=True, alpha_fix=False):
""":param target_concentration: The concentration parameter for the target class (if provided) :param concentration: The 'base... | the_stack_v2_python_sparse | uncertainty_est/models/priornet/dpn_losses.py | pkulwj1994/MA-EBM | train | 0 |
68dbfc9f49e27b954c4bbc4a9feb6ea5f0eda031 | [
"outputFile = open('ClientOutput.txt', 'a+')\noutputFile.write(clientOutput + '\\n')\noutputFile.close()",
"jobBackup = open('JobBackup.txt', 'w+')\nfor Jobs in jobList:\n jobBackup.write(Jobs.FullJob + '\\n')\njobBackup.close()"
] | <|body_start_0|>
outputFile = open('ClientOutput.txt', 'a+')
outputFile.write(clientOutput + '\n')
outputFile.close()
<|end_body_0|>
<|body_start_1|>
jobBackup = open('JobBackup.txt', 'w+')
for Jobs in jobList:
jobBackup.write(Jobs.FullJob + '\n')
jobBackup.c... | FileRecord | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileRecord:
def recordOutput(self, clientOutput):
"""Input: clientOutput (String) Description: This function checks for 'ClientOutput.txt', if not found it will create this file and append the given input to this file. After all is done, the stream to the file is closed ensuring the file... | stack_v2_sparse_classes_75kplus_train_070253 | 1,097 | no_license | [
{
"docstring": "Input: clientOutput (String) Description: This function checks for 'ClientOutput.txt', if not found it will create this file and append the given input to this file. After all is done, the stream to the file is closed ensuring the file gets saved",
"name": "recordOutput",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_test_002810 | Implement the Python class `FileRecord` described below.
Class description:
Implement the FileRecord class.
Method signatures and docstrings:
- def recordOutput(self, clientOutput): Input: clientOutput (String) Description: This function checks for 'ClientOutput.txt', if not found it will create this file and append ... | Implement the Python class `FileRecord` described below.
Class description:
Implement the FileRecord class.
Method signatures and docstrings:
- def recordOutput(self, clientOutput): Input: clientOutput (String) Description: This function checks for 'ClientOutput.txt', if not found it will create this file and append ... | 59f91c1b0282148f971d3371eed770dc6e50751f | <|skeleton|>
class FileRecord:
def recordOutput(self, clientOutput):
"""Input: clientOutput (String) Description: This function checks for 'ClientOutput.txt', if not found it will create this file and append the given input to this file. After all is done, the stream to the file is closed ensuring the file... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileRecord:
def recordOutput(self, clientOutput):
"""Input: clientOutput (String) Description: This function checks for 'ClientOutput.txt', if not found it will create this file and append the given input to this file. After all is done, the stream to the file is closed ensuring the file gets saved"""... | the_stack_v2_python_sparse | Final Project/FileRecord.py | sell50/Network-Project | train | 2 | |
4304c33b5feefd51c3e986003be3c0b792bb9542 | [
"loop = asyncio.get_running_loop()\nnats = FakeNatsHandler('cubesat_1', '4222', loop=loop, user='a', password='b')\nawait nats.connect()\nshared_storage = {'log_path': './'}\nawait logging_service.create_log_file(nats, shared_storage, None)\nfile_made = False\nfor i in os.listdir():\n if f'log-{datetime.utcnow()... | <|body_start_0|>
loop = asyncio.get_running_loop()
nats = FakeNatsHandler('cubesat_1', '4222', loop=loop, user='a', password='b')
await nats.connect()
shared_storage = {'log_path': './'}
await logging_service.create_log_file(nats, shared_storage, None)
file_made = False
... | Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
async def test_create_log_file(self):
"""Testing the creation of the log files"""
<|body_0|>
async def test_print_log(self):
"""Testing printing the log info"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
loop = asyncio.get_running_loop()
... | stack_v2_sparse_classes_75kplus_train_070254 | 2,565 | permissive | [
{
"docstring": "Testing the creation of the log files",
"name": "test_create_log_file",
"signature": "async def test_create_log_file(self)"
},
{
"docstring": "Testing printing the log info",
"name": "test_print_log",
"signature": "async def test_print_log(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_043923 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- async def test_create_log_file(self): Testing the creation of the log files
- async def test_print_log(self): Testing printing the log info | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- async def test_create_log_file(self): Testing the creation of the log files
- async def test_print_log(self): Testing printing the log info
<|skeleton|>
class Test:
async def test_... | e64372cc4cf71d9db7fe2395ba60d93722fccff6 | <|skeleton|>
class Test:
async def test_create_log_file(self):
"""Testing the creation of the log files"""
<|body_0|>
async def test_print_log(self):
"""Testing printing the log info"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test:
async def test_create_log_file(self):
"""Testing the creation of the log files"""
loop = asyncio.get_running_loop()
nats = FakeNatsHandler('cubesat_1', '4222', loop=loop, user='a', password='b')
await nats.connect()
shared_storage = {'log_path': './'}
awai... | the_stack_v2_python_sparse | simulation/logging/test_logging_service.py | sallyom/spacetech-kubesat | train | 0 | |
dbab789fc33857ddedd2e36d0a8dd5819c5fca63 | [
"newsnr = get_newsnr(trigs)\nrchisq = trigs['chisq'] / (2.0 * trigs['chisq_dof'] - 2.0)\nnewsnr[numpy.logical_and(newsnr < 10, rchisq > 2)] = -1\nreturn newsnr",
"cstat = (s0 ** 2.0 + s1 ** 2.0) ** 0.5\ncstat[s0 == -1] = 0\ncstat[s1 == -1] = 0\nreturn cstat"
] | <|body_start_0|>
newsnr = get_newsnr(trigs)
rchisq = trigs['chisq'] / (2.0 * trigs['chisq_dof'] - 2.0)
newsnr[numpy.logical_and(newsnr < 10, rchisq > 2)] = -1
return newsnr
<|end_body_0|>
<|body_start_1|>
cstat = (s0 ** 2.0 + s1 ** 2.0) ** 0.5
cstat[s0 == -1] = 0
... | Same as the NewSNR statistic, but demonstrates a cut of the triggers | NewSNRCutStatistic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewSNRCutStatistic:
"""Same as the NewSNR statistic, but demonstrates a cut of the triggers"""
def single(self, trigs):
"""Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays Dictionary of the single detector trigger information. 'chisq_dof', ... | stack_v2_sparse_classes_75kplus_train_070255 | 16,891 | no_license | [
{
"docstring": "Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays Dictionary of the single detector trigger information. 'chisq_dof', 'snr', and 'chisq' are required keys Returns ------- newsnr: numpy.ndarray Array of single detector values",
"name": "single",
... | 2 | stack_v2_sparse_classes_30k_test_002568 | Implement the Python class `NewSNRCutStatistic` described below.
Class description:
Same as the NewSNR statistic, but demonstrates a cut of the triggers
Method signatures and docstrings:
- def single(self, trigs): Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays Dictionary ... | Implement the Python class `NewSNRCutStatistic` described below.
Class description:
Same as the NewSNR statistic, but demonstrates a cut of the triggers
Method signatures and docstrings:
- def single(self, trigs): Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays Dictionary ... | 063d587d476f56d81a89aed774eff6d97b1c1c9b | <|skeleton|>
class NewSNRCutStatistic:
"""Same as the NewSNR statistic, but demonstrates a cut of the triggers"""
def single(self, trigs):
"""Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays Dictionary of the single detector trigger information. 'chisq_dof', ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewSNRCutStatistic:
"""Same as the NewSNR statistic, but demonstrates a cut of the triggers"""
def single(self, trigs):
"""Calculate the single detector statistic. Parameters ---------- trigs: dict of numpy.ndarrays Dictionary of the single detector trigger information. 'chisq_dof', 'snr', and 'c... | the_stack_v2_python_sparse | pycbc/events/stat.py | bhooshan-gadre/my_pycbc_old | train | 0 |
2f2766f79772f7c59e88e87ab3761ec59c16e924 | [
"self.qpah = float(self.parameters['qpah'])\nself.umin = float(self.parameters['umin'])\nself.alpha = float(self.parameters['alpha'])\nself.gamma = float(self.parameters['gamma'])\nself.umax = 10000000.0\nwith Database() as database:\n self.model_minmin = database.get_dl2014(self.qpah, self.umin, self.umin, 1.0)... | <|body_start_0|>
self.qpah = float(self.parameters['qpah'])
self.umin = float(self.parameters['umin'])
self.alpha = float(self.parameters['alpha'])
self.gamma = float(self.parameters['gamma'])
self.umax = 10000000.0
with Database() as database:
self.model_minm... | Updated Draine and Li (2007) templates IR re-emission module Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises the updated Draine and Li (2007) model corresponding to a given set of parameters to this amount of energy and add it to the SED. Information a... | DL2014 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DL2014:
"""Updated Draine and Li (2007) templates IR re-emission module Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises the updated Draine and Li (2007) model corresponding to a given set of parameters to this amount of energy an... | stack_v2_sparse_classes_75kplus_train_070256 | 5,476 | no_license | [
{
"docstring": "Get the model out of the database",
"name": "_init_code",
"signature": "def _init_code(self)"
},
{
"docstring": "Add the IR re-emission contributions Parameters ---------- sed: pcigale.sed.SED object parameters: dictionary containing the parameters",
"name": "process",
"s... | 2 | stack_v2_sparse_classes_30k_train_020366 | Implement the Python class `DL2014` described below.
Class description:
Updated Draine and Li (2007) templates IR re-emission module Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises the updated Draine and Li (2007) model corresponding to a given set of... | Implement the Python class `DL2014` described below.
Class description:
Updated Draine and Li (2007) templates IR re-emission module Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises the updated Draine and Li (2007) model corresponding to a given set of... | 9ef9b99425537350b8706fddfe90ed47301107a5 | <|skeleton|>
class DL2014:
"""Updated Draine and Li (2007) templates IR re-emission module Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises the updated Draine and Li (2007) model corresponding to a given set of parameters to this amount of energy an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DL2014:
"""Updated Draine and Li (2007) templates IR re-emission module Given an amount of attenuation (e.g. resulting from the action of a dust attenuation module) this module normalises the updated Draine and Li (2007) model corresponding to a given set of parameters to this amount of energy and add it to t... | the_stack_v2_python_sparse | pcigale/sed_modules/dl2014.py | JohannesBuchner/cigale | train | 5 |
9cd1c904a3956b6f4671274dec7d571092c71405 | [
"if not os.path.exists(database_filename):\n creation_query = '\\n create table all_email(id text, body text);\\n create unique index all_email_id on all_email(id);\\n create table sent_email(id text, body text);\\n create unique index sent_email_id on sent_email(id);\... | <|body_start_0|>
if not os.path.exists(database_filename):
creation_query = '\n create table all_email(id text, body text);\n create unique index all_email_id on all_email(id);\n create table sent_email(id text, body text);\n create unique index sent_email... | Store email in raw RFC822 format with identifiers. | EmailDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailDatabase:
"""Store email in raw RFC822 format with identifiers."""
def __init__(self, database_filename, email_source):
"""Parameters ---------- database_filename A string, where to store the file on disk. The folder must exist. email_source A subclass of MailSource with an all(... | stack_v2_sparse_classes_75kplus_train_070257 | 5,065 | no_license | [
{
"docstring": "Parameters ---------- database_filename A string, where to store the file on disk. The folder must exist. email_source A subclass of MailSource with an all() and sent() method.",
"name": "__init__",
"signature": "def __init__(self, database_filename, email_source)"
},
{
"docstrin... | 2 | null | Implement the Python class `EmailDatabase` described below.
Class description:
Store email in raw RFC822 format with identifiers.
Method signatures and docstrings:
- def __init__(self, database_filename, email_source): Parameters ---------- database_filename A string, where to store the file on disk. The folder must ... | Implement the Python class `EmailDatabase` described below.
Class description:
Store email in raw RFC822 format with identifiers.
Method signatures and docstrings:
- def __init__(self, database_filename, email_source): Parameters ---------- database_filename A string, where to store the file on disk. The folder must ... | 6ada50adf63078ba28464c59808234bca3fcc9b7 | <|skeleton|>
class EmailDatabase:
"""Store email in raw RFC822 format with identifiers."""
def __init__(self, database_filename, email_source):
"""Parameters ---------- database_filename A string, where to store the file on disk. The folder must exist. email_source A subclass of MailSource with an all(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailDatabase:
"""Store email in raw RFC822 format with identifiers."""
def __init__(self, database_filename, email_source):
"""Parameters ---------- database_filename A string, where to store the file on disk. The folder must exist. email_source A subclass of MailSource with an all() and sent() ... | the_stack_v2_python_sparse | _7_Keras/KerasText/Section 1/maildatabase.py | cyrsis/TensorflowPY36CPU | train | 5 |
5af95d1137bb56dfcaf453b522fd96f89d2df22c | [
"self.old_nums = list(nums)\nself.nums = list(nums)\nfor i in range(1, len(self.nums)):\n self.nums[i] += self.nums[i - 1]",
"self.old_nums[i] = val\nfor i in range(i, len(self.old_nums)):\n self.nums[i] = self.nums[i - 1] + self.old_nums[i]",
"if not i:\n return self.nums[j]\nelse:\n return self.nu... | <|body_start_0|>
self.old_nums = list(nums)
self.nums = list(nums)
for i in range(1, len(self.nums)):
self.nums[i] += self.nums[i - 1]
<|end_body_0|>
<|body_start_1|>
self.old_nums[i] = val
for i in range(i, len(self.old_nums)):
self.nums[i] = self.nums[i... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_75kplus_train_070258 | 1,052 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: int",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "sum o... | 3 | stack_v2_sparse_classes_30k_train_017793 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: int
- def sumRange(self, i, j... | 09355094c85496cc42f8cb3241da43e0ece1e45a | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: int"""
<|body_1|>
def sumRange(self, i, j):
"""sum of elements nums[i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
self.old_nums = list(nums)
self.nums = list(nums)
for i in range(1, len(self.nums)):
self.nums[i] += self.nums[i - 1]
def update(self, i, val):
""":type... | the_stack_v2_python_sparse | Rakesh/General Interview Questions/Range Sum Query - Mutable_python_tricks.py | rakeshsukla53/interview-preparation | train | 9 | |
7decb386e6ddbcaedc6f551ac24bedaae4b081f3 | [
"self._reactor = reactor\nself._wiring = wiring\nself._settings = settings\nself._inputs = []",
"_log.info('starting')\nfor input_item in self._settings['inputs']:\n input_type = input_item.pop('type', None)\n enabled = input_item.pop('enabled', False)\n if not enabled:\n continue\n try:\n ... | <|body_start_0|>
self._reactor = reactor
self._wiring = wiring
self._settings = settings
self._inputs = []
<|end_body_0|>
<|body_start_1|>
_log.info('starting')
for input_item in self._settings['inputs']:
input_type = input_item.pop('type', None)
... | Initializes inputs and mediates their feeds to a player manager. | InputManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputManager:
"""Initializes inputs and mediates their feeds to a player manager."""
def __init__(self, reactor, wiring, settings):
"""Initializes the instance: - `reactor` is the Twisted reactor. - `wiring` usable by inputs to fire/handle event-like calls. - `settings` is a dict con... | stack_v2_sparse_classes_75kplus_train_070259 | 3,119 | no_license | [
{
"docstring": "Initializes the instance: - `reactor` is the Twisted reactor. - `wiring` usable by inputs to fire/handle event-like calls. - `settings` is a dict containing the 'inputs' key.",
"name": "__init__",
"signature": "def __init__(self, reactor, wiring, settings)"
},
{
"docstring": "Ins... | 3 | stack_v2_sparse_classes_30k_train_004660 | Implement the Python class `InputManager` described below.
Class description:
Initializes inputs and mediates their feeds to a player manager.
Method signatures and docstrings:
- def __init__(self, reactor, wiring, settings): Initializes the instance: - `reactor` is the Twisted reactor. - `wiring` usable by inputs to... | Implement the Python class `InputManager` described below.
Class description:
Initializes inputs and mediates their feeds to a player manager.
Method signatures and docstrings:
- def __init__(self, reactor, wiring, settings): Initializes the instance: - `reactor` is the Twisted reactor. - `wiring` usable by inputs to... | 9ac3d76e9488ef5f789c34979cb3b20feae96476 | <|skeleton|>
class InputManager:
"""Initializes inputs and mediates their feeds to a player manager."""
def __init__(self, reactor, wiring, settings):
"""Initializes the instance: - `reactor` is the Twisted reactor. - `wiring` usable by inputs to fire/handle event-like calls. - `settings` is a dict con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InputManager:
"""Initializes inputs and mediates their feeds to a player manager."""
def __init__(self, reactor, wiring, settings):
"""Initializes the instance: - `reactor` is the Twisted reactor. - `wiring` usable by inputs to fire/handle event-like calls. - `settings` is a dict containing the '... | the_stack_v2_python_sparse | inputs/input_manager.py | tmontes/pyCandle2017 | train | 1 |
2aba06aaca767d5a057b4de667de37da423feeba | [
"if len(self) == 0:\n return []\nselect = ','.join(['\"account_move_line\".' + k + ((self.env.context.get('cash_basis') and k in ['balance', 'credit', 'debit']) and '_cash_basis' or '') for k in field_names])\ntables, where_clause, where_params = self._query_get()\nif (self.env.context.get('sum_if_pos') or self.... | <|body_start_0|>
if len(self) == 0:
return []
select = ','.join(['"account_move_line".' + k + ((self.env.context.get('cash_basis') and k in ['balance', 'credit', 'debit']) and '_cash_basis' or '') for k in field_names])
tables, where_clause, where_params = self._query_get()
i... | AccountMoveLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountMoveLine:
def _compute_fields(self, field_names, group_by=None):
"""Computes the required fields with the options given in the context using _query_get() @param field_names: a list of the fields to compute @returns : a dictionnary that has for each aml in the domain a dictionnary ... | stack_v2_sparse_classes_75kplus_train_070260 | 4,201 | no_license | [
{
"docstring": "Computes the required fields with the options given in the context using _query_get() @param field_names: a list of the fields to compute @returns : a dictionnary that has for each aml in the domain a dictionnary of the values of the fields",
"name": "_compute_fields",
"signature": "def ... | 3 | null | Implement the Python class `AccountMoveLine` described below.
Class description:
Implement the AccountMoveLine class.
Method signatures and docstrings:
- def _compute_fields(self, field_names, group_by=None): Computes the required fields with the options given in the context using _query_get() @param field_names: a l... | Implement the Python class `AccountMoveLine` described below.
Class description:
Implement the AccountMoveLine class.
Method signatures and docstrings:
- def _compute_fields(self, field_names, group_by=None): Computes the required fields with the options given in the context using _query_get() @param field_names: a l... | 6682e60630064641474ddb2d8cbc520e30f64832 | <|skeleton|>
class AccountMoveLine:
def _compute_fields(self, field_names, group_by=None):
"""Computes the required fields with the options given in the context using _query_get() @param field_names: a list of the fields to compute @returns : a dictionnary that has for each aml in the domain a dictionnary ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountMoveLine:
def _compute_fields(self, field_names, group_by=None):
"""Computes the required fields with the options given in the context using _query_get() @param field_names: a list of the fields to compute @returns : a dictionnary that has for each aml in the domain a dictionnary of the values ... | the_stack_v2_python_sparse | poi_account_reports/models/account_move_line.py | blue-connect/illuminati | train | 0 | |
51d4695ffe6cdff7e5b75b5035794f8056b63e6e | [
"self.d = {}\nself.nums = nums\nself.S = S\nreturn self.dfs(0, 0)",
"if i < len(self.nums) and (cur, i) not in self.d:\n self.d[cur, i] = self.dfs(cur + self.nums[i], i + 1) + self.dfs(cur - self.nums[i], i + 1)\nreturn self.d.get((cur, i), int(cur == self.S))"
] | <|body_start_0|>
self.d = {}
self.nums = nums
self.S = S
return self.dfs(0, 0)
<|end_body_0|>
<|body_start_1|>
if i < len(self.nums) and (cur, i) not in self.d:
self.d[cur, i] = self.dfs(cur + self.nums[i], i + 1) + self.dfs(cur - self.nums[i], i + 1)
return ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums, S):
"""递归 Args: nums: list[int] S: int Return: int"""
<|body_0|>
def dfs(self, cur, i):
"""Args: cur: int i: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = {}
self.nums = nums
... | stack_v2_sparse_classes_75kplus_train_070261 | 1,593 | no_license | [
{
"docstring": "递归 Args: nums: list[int] S: int Return: int",
"name": "findTargetSumWays",
"signature": "def findTargetSumWays(self, nums, S)"
},
{
"docstring": "Args: cur: int i: int",
"name": "dfs",
"signature": "def dfs(self, cur, i)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums, S): 递归 Args: nums: list[int] S: int Return: int
- def dfs(self, cur, i): Args: cur: int i: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTargetSumWays(self, nums, S): 递归 Args: nums: list[int] S: int Return: int
- def dfs(self, cur, i): Args: cur: int i: int
<|skeleton|>
class Solution:
def findTarget... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def findTargetSumWays(self, nums, S):
"""递归 Args: nums: list[int] S: int Return: int"""
<|body_0|>
def dfs(self, cur, i):
"""Args: cur: int i: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTargetSumWays(self, nums, S):
"""递归 Args: nums: list[int] S: int Return: int"""
self.d = {}
self.nums = nums
self.S = S
return self.dfs(0, 0)
def dfs(self, cur, i):
"""Args: cur: int i: int"""
if i < len(self.nums) and (cur, i) not... | the_stack_v2_python_sparse | code/494. 目标和.py | AiZhanghan/Leetcode | train | 0 | |
3d74d886c6068490f5546e225ae337483874ee6f | [
"super(CircularParallelCoattention, self).__init__()\nwith self.init_scope():\n self.j_layer = GraphLinear(hidden_dim, out_dim)\nself.hidden_dim = hidden_dim\nself.out_dim = out_dim\nself.head = out_dim\nself.activation = activation\nself.weight_tying = weight_tying",
"atoms_1 = self.j_layer(atoms_1)\nattn_1 =... | <|body_start_0|>
super(CircularParallelCoattention, self).__init__()
with self.init_scope():
self.j_layer = GraphLinear(hidden_dim, out_dim)
self.hidden_dim = hidden_dim
self.out_dim = out_dim
self.head = out_dim
self.activation = activation
self.weigh... | CircularParallelCoattention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CircularParallelCoattention:
def __init__(self, hidden_dim, out_dim, activation=functions.tanh, weight_tying=True):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation"""
<|body_0|>
def __call__(self, atoms_1, g_1, ato... | stack_v2_sparse_classes_75kplus_train_070262 | 7,885 | permissive | [
{
"docstring": ":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation",
"name": "__init__",
"signature": "def __init__(self, hidden_dim, out_dim, activation=functions.tanh, weight_tying=True)"
},
{
"docstring": ":param atoms_1: atomic represent... | 4 | stack_v2_sparse_classes_30k_train_044294 | Implement the Python class `CircularParallelCoattention` described below.
Class description:
Implement the CircularParallelCoattention class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, activation=functions.tanh, weight_tying=True): :param hidden_dim: dimension of atom representation :... | Implement the Python class `CircularParallelCoattention` described below.
Class description:
Implement the CircularParallelCoattention class.
Method signatures and docstrings:
- def __init__(self, hidden_dim, out_dim, activation=functions.tanh, weight_tying=True): :param hidden_dim: dimension of atom representation :... | 21b64a3c8cc9bc33718ae09c65aa917e575132eb | <|skeleton|>
class CircularParallelCoattention:
def __init__(self, hidden_dim, out_dim, activation=functions.tanh, weight_tying=True):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation"""
<|body_0|>
def __call__(self, atoms_1, g_1, ato... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CircularParallelCoattention:
def __init__(self, hidden_dim, out_dim, activation=functions.tanh, weight_tying=True):
""":param hidden_dim: dimension of atom representation :param out_dim: dimension of molecular representation"""
super(CircularParallelCoattention, self).__init__()
with s... | the_stack_v2_python_sparse | models/coattention/parallel_coattention.py | Minys233/GCN-BMP | train | 1 | |
f6eca4cdbd386e5b01ddd36578069acc14a38847 | [
"self.ntot = 0\nself.hospitals = []\nself.hospitals_map = {}\nself.read_gis_data(fname)\nself.read_gis_types(fmap)",
"with open(fname, 'r') as fin:\n next(fin)\n ID = 0\n for line in fin:\n temp = {}\n line = line.strip().split()\n if line[0] is not 'H':\n continue\n ... | <|body_start_0|>
self.ntot = 0
self.hospitals = []
self.hospitals_map = {}
self.read_gis_data(fname)
self.read_gis_types(fmap)
<|end_body_0|>
<|body_start_1|>
with open(fname, 'r') as fin:
next(fin)
ID = 0
for line in fin:
... | Class for generation of hospitals | Hospitals | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hospitals:
"""Class for generation of hospitals"""
def __init__(self, fname, fmap):
"""Generate individual hospitals from input data"""
<|body_0|>
def read_gis_data(self, fname):
"""Read and store hospital data"""
<|body_1|>
def read_gis_types(self, ... | stack_v2_sparse_classes_75kplus_train_070263 | 8,758 | permissive | [
{
"docstring": "Generate individual hospitals from input data",
"name": "__init__",
"signature": "def __init__(self, fname, fmap)"
},
{
"docstring": "Read and store hospital data",
"name": "read_gis_data",
"signature": "def read_gis_data(self, fname)"
},
{
"docstring": "Loads a m... | 4 | stack_v2_sparse_classes_30k_train_043321 | Implement the Python class `Hospitals` described below.
Class description:
Class for generation of hospitals
Method signatures and docstrings:
- def __init__(self, fname, fmap): Generate individual hospitals from input data
- def read_gis_data(self, fname): Read and store hospital data
- def read_gis_types(self, fnam... | Implement the Python class `Hospitals` described below.
Class description:
Class for generation of hospitals
Method signatures and docstrings:
- def __init__(self, fname, fmap): Generate individual hospitals from input data
- def read_gis_data(self, fname): Read and store hospital data
- def read_gis_types(self, fnam... | 87d4fe9dcec4aa0c8dec41547e7589952c371b1f | <|skeleton|>
class Hospitals:
"""Class for generation of hospitals"""
def __init__(self, fname, fmap):
"""Generate individual hospitals from input data"""
<|body_0|>
def read_gis_data(self, fname):
"""Read and store hospital data"""
<|body_1|>
def read_gis_types(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hospitals:
"""Class for generation of hospitals"""
def __init__(self, fname, fmap):
"""Generate individual hospitals from input data"""
self.ntot = 0
self.hospitals = []
self.hospitals_map = {}
self.read_gis_data(fname)
self.read_gis_types(fmap)
def re... | the_stack_v2_python_sparse | src/abm_public.py | atruszkowska/NR-ABM-population | train | 1 |
3ca01405c6950e8b925b5540a0e23562c367a41f | [
"for config_class, getter_class in ProcessFactory.config_getter_map.items():\n if isinstance(config, config_class):\n return getter_class(config)\nraise ValueError('create_getter must pass one of the instance of [RAPIConfig, RCSVConfig, RESConfig, RJsonConfig, RXLSXConfig, RAPIBulkConfig, RRedisConfig, RM... | <|body_start_0|>
for config_class, getter_class in ProcessFactory.config_getter_map.items():
if isinstance(config, config_class):
return getter_class(config)
raise ValueError('create_getter must pass one of the instance of [RAPIConfig, RCSVConfig, RESConfig, RJsonConfig, RXLS... | ProcessFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessFactory:
def create_getter(config):
"""create a getter based on config :return: getter"""
<|body_0|>
def create_writer(config, **kwargs):
"""create a writer based on config :return: a writer"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for... | stack_v2_sparse_classes_75kplus_train_070264 | 2,981 | permissive | [
{
"docstring": "create a getter based on config :return: getter",
"name": "create_getter",
"signature": "def create_getter(config)"
},
{
"docstring": "create a writer based on config :return: a writer",
"name": "create_writer",
"signature": "def create_writer(config, **kwargs)"
}
] | 2 | null | Implement the Python class `ProcessFactory` described below.
Class description:
Implement the ProcessFactory class.
Method signatures and docstrings:
- def create_getter(config): create a getter based on config :return: getter
- def create_writer(config, **kwargs): create a writer based on config :return: a writer | Implement the Python class `ProcessFactory` described below.
Class description:
Implement the ProcessFactory class.
Method signatures and docstrings:
- def create_getter(config): create a getter based on config :return: getter
- def create_writer(config, **kwargs): create a writer based on config :return: a writer
<... | d5c7349fa8b838d44807ba21098b9723a2e098d9 | <|skeleton|>
class ProcessFactory:
def create_getter(config):
"""create a getter based on config :return: getter"""
<|body_0|>
def create_writer(config, **kwargs):
"""create a writer based on config :return: a writer"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcessFactory:
def create_getter(config):
"""create a getter based on config :return: getter"""
for config_class, getter_class in ProcessFactory.config_getter_map.items():
if isinstance(config, config_class):
return getter_class(config)
raise ValueError('cr... | the_stack_v2_python_sparse | idataapi_transform/DataProcess/ProcessFactory.py | zpoint/idataapi-transform | train | 49 | |
14c670249fcfe0073d2b3d8e4ede77fca6ad09b3 | [
"super().__init__()\nself.feature_extractor = backbone\nself.detection = detection\nself.auxiliary = auxiliary",
"x = self.feature_extractor(x)\naux_out = []\nif self.auxiliary:\n x, scene, depth, normals = self.auxiliary(x)\n aux_out.extend([scene, depth, normals])\nlocs, confs = self.detection(x)\nreturn ... | <|body_start_0|>
super().__init__()
self.feature_extractor = backbone
self.detection = detection
self.auxiliary = auxiliary
<|end_body_0|>
<|body_start_1|>
x = self.feature_extractor(x)
aux_out = []
if self.auxiliary:
x, scene, depth, normals = self.a... | Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector | Network | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
"""Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector"""
def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Opt... | stack_v2_sparse_classes_75kplus_train_070265 | 3,381 | permissive | [
{
"docstring": "Args: backbone: backbone used to obtain the base feature map detection: detection layer of Network auxiliary: auxiliary block used for MTL",
"name": "__init__",
"signature": "def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Optional[torch.nn.Module]=No... | 2 | stack_v2_sparse_classes_30k_train_023020 | Implement the Python class `Network` described below.
Class description:
Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector
Method signatures and docstrings:
- def __init__(self, b... | Implement the Python class `Network` described below.
Class description:
Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector
Method signatures and docstrings:
- def __init__(self, b... | 6f4c86d3fec7fe3b0ce65d2687d144e9698e964f | <|skeleton|>
class Network:
"""Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector"""
def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Opt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Network:
"""Network class which combines the backbone, the auxiliary tasks (optional), and the detection block Can be used to implement the ROCK network architecture or a baseline Single Shot Detector"""
def __init__(self, backbone: torch.nn.Module, detection: torch.nn.Module, auxiliary: Optional[torch.n... | the_stack_v2_python_sparse | rock/model/network.py | Shweta200126/rock-pytorch | train | 0 |
88b2439cbb6400403b7c3a34451b6355e3358996 | [
"try:\n version = get_openflow_header(this_packet, 0)\n if version['version'] == 1:\n self.ofp = unpack10(this_packet)\n elif version['version'] == 4:\n self.ofp = unpack13(this_packet)\n else:\n self.ofp = 0\nexcept:\n self.ofp = 0",
"if not libs.core.filters.filter_msg(self):... | <|body_start_0|>
try:
version = get_openflow_header(this_packet, 0)
if version['version'] == 1:
self.ofp = unpack10(this_packet)
elif version['version'] == 4:
self.ofp = unpack13(this_packet)
else:
self.ofp = 0
... | Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary. | OFMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OFMessage:
"""Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary."""
def __init__(self, this_packet):
"""Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format"""
... | stack_v2_sparse_classes_75kplus_train_070266 | 2,331 | permissive | [
{
"docstring": "Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format",
"name": "__init__",
"signature": "def __init__(self, this_packet)"
},
{
"docstring": "Generic printing function Args: pkt: Packet class",
"name": "print_packet",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_003816 | Implement the Python class `OFMessage` described below.
Class description:
Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary.
Method signatures and docstrings:
- def __init__(self, this_packet): Instantiate OFMessage class Args: self: thi... | Implement the Python class `OFMessage` described below.
Class description:
Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary.
Method signatures and docstrings:
- def __init__(self, this_packet): Instantiate OFMessage class Args: self: thi... | 4b79b6c9ebb8f237ed189c38eefc9e98226606f6 | <|skeleton|>
class OFMessage:
"""Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary."""
def __init__(self, this_packet):
"""Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OFMessage:
"""Used to process all data regarding this OpenFlow message. With the python-openflow (pyof) lib, only one variable became necessary."""
def __init__(self, this_packet):
"""Instantiate OFMessage class Args: self: this class this_packet: OpenFlow msg in binary format"""
try:
... | the_stack_v2_python_sparse | libs/gen/ofmessage.py | amlight/ofp_sniffer | train | 16 |
7be1dc53f6967bb42f0f02b32b513538a773bb8a | [
"hash, lookup = (hashlib.sha1(), set())\nfor keygroup in (self.data, self.structure, (self.origin,)):\n for key in keygroup:\n if key not in lookup:\n lookup.add(key)\n hash.update(key)\nreturn hash.hexdigest()",
"id = hashlib.sha1('::'.join(map(str, (self.origin, self.options.desc... | <|body_start_0|>
hash, lookup = (hashlib.sha1(), set())
for keygroup in (self.data, self.structure, (self.origin,)):
for key in keygroup:
if key not in lookup:
lookup.add(key)
hash.update(key)
return hash.hexdigest()
<|end_body_... | Model representing a single instance of a structure representing ``Nodes``, interlinked by ``Edges``. Can optionally contain references to full data for those objects. | Graph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph:
"""Model representing a single instance of a structure representing ``Nodes``, interlinked by ``Edges``. Can optionally contain references to full data for those objects."""
def hash(self):
"""Generate a content-based unique hash of this Graph. Includes both structural and dat... | stack_v2_sparse_classes_75kplus_train_070267 | 3,009 | no_license | [
{
"docstring": "Generate a content-based unique hash of this Graph. Includes both structural and data keys.",
"name": "hash",
"signature": "def hash(self)"
},
{
"docstring": "Generate a string fingerprint for this Graph from the input parameters: ``origin``, ``depth`` and ``limit``. Optionally m... | 2 | stack_v2_sparse_classes_30k_train_051910 | Implement the Python class `Graph` described below.
Class description:
Model representing a single instance of a structure representing ``Nodes``, interlinked by ``Edges``. Can optionally contain references to full data for those objects.
Method signatures and docstrings:
- def hash(self): Generate a content-based un... | Implement the Python class `Graph` described below.
Class description:
Model representing a single instance of a structure representing ``Nodes``, interlinked by ``Edges``. Can optionally contain references to full data for those objects.
Method signatures and docstrings:
- def hash(self): Generate a content-based un... | 4c83d1bfc146f48ac2d1d6b240624a7ece57911e | <|skeleton|>
class Graph:
"""Model representing a single instance of a structure representing ``Nodes``, interlinked by ``Edges``. Can optionally contain references to full data for those objects."""
def hash(self):
"""Generate a content-based unique hash of this Graph. Includes both structural and dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Graph:
"""Model representing a single instance of a structure representing ``Nodes``, interlinked by ``Edges``. Can optionally contain references to full data for those objects."""
def hash(self):
"""Generate a content-based unique hash of this Graph. Includes both structural and data keys."""
... | the_stack_v2_python_sparse | fatcatmap/models/graph.py | sgammon/fatcatmap | train | 0 |
f327e118e8db6182e98c756fafb4a993d8e93560 | [
"super().__init__(base_lr=base_lr)\nself.gamma = gamma\nself.step_size = step_size",
"if isinstance(self.step_size, (tuple, list)):\n exponent = jn.sum(jn.greater_equal(step, jn.array(self.step_size)))\nelse:\n exponent = step // self.step_size\nreturn self.gamma ** exponent"
] | <|body_start_0|>
super().__init__(base_lr=base_lr)
self.gamma = gamma
self.step_size = step_size
<|end_body_0|>
<|body_start_1|>
if isinstance(self.step_size, (tuple, list)):
exponent = jn.sum(jn.greater_equal(step, jn.array(self.step_size)))
else:
expone... | StepDecay | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepDecay:
def __init__(self, step_size: Union[float, List, Tuple], base_lr: float=1.0, gamma: float=0.1):
"""Constructs an instance for step decay learning rate scheduler. Args: step_size: number of train steps to reduce learning rate. base_lr: base learning rate. gamma: learning rate d... | stack_v2_sparse_classes_75kplus_train_070268 | 3,624 | permissive | [
{
"docstring": "Constructs an instance for step decay learning rate scheduler. Args: step_size: number of train steps to reduce learning rate. base_lr: base learning rate. gamma: learning rate decay rate.",
"name": "__init__",
"signature": "def __init__(self, step_size: Union[float, List, Tuple], base_l... | 2 | null | Implement the Python class `StepDecay` described below.
Class description:
Implement the StepDecay class.
Method signatures and docstrings:
- def __init__(self, step_size: Union[float, List, Tuple], base_lr: float=1.0, gamma: float=0.1): Constructs an instance for step decay learning rate scheduler. Args: step_size: ... | Implement the Python class `StepDecay` described below.
Class description:
Implement the StepDecay class.
Method signatures and docstrings:
- def __init__(self, step_size: Union[float, List, Tuple], base_lr: float=1.0, gamma: float=0.1): Constructs an instance for step decay learning rate scheduler. Args: step_size: ... | a2d025d9e1da8660a1883404207c41d4327d8c48 | <|skeleton|>
class StepDecay:
def __init__(self, step_size: Union[float, List, Tuple], base_lr: float=1.0, gamma: float=0.1):
"""Constructs an instance for step decay learning rate scheduler. Args: step_size: number of train steps to reduce learning rate. base_lr: base learning rate. gamma: learning rate d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StepDecay:
def __init__(self, step_size: Union[float, List, Tuple], base_lr: float=1.0, gamma: float=0.1):
"""Constructs an instance for step decay learning rate scheduler. Args: step_size: number of train steps to reduce learning rate. base_lr: base learning rate. gamma: learning rate decay rate."""
... | the_stack_v2_python_sparse | objax/optimizer/scheduler.py | google/objax | train | 801 | |
17d34a929989b4b488eba8e8a7f08a996b3ae995 | [
"assert training_percent + validation_percent <= 1.0, 'Training and validation percentages more than 100 percent'\nself.train_examples = []\nself.validation_examples = []\nself.test_examples = []\nself.training_percent = training_percent\nself.validation_percent = validation_percent",
"placement_rand = random.Ran... | <|body_start_0|>
assert training_percent + validation_percent <= 1.0, 'Training and validation percentages more than 100 percent'
self.train_examples = []
self.validation_examples = []
self.test_examples = []
self.training_percent = training_percent
self.validation_percen... | Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the network while training. They provide an inde... | ExampleManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleManager:
"""Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the ne... | stack_v2_sparse_classes_75kplus_train_070269 | 3,043 | permissive | [
{
"docstring": "Initialize the manager with the training examples. Arguments: o training_percent - The percentage of the training examples that should be used for training the network. o validation_percent - Percent of training examples for validating a network during training. Attributes: o train_examples - A ... | 2 | stack_v2_sparse_classes_30k_train_043684 | Implement the Python class `ExampleManager` described below.
Class description:
Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data --... | Implement the Python class `ExampleManager` described below.
Class description:
Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data --... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class ExampleManager:
"""Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExampleManager:
"""Manage a grouping of Training Examples. This is meant to make it easy to split a bunch of training examples into three types of data: o Training Data -- These are the data used to do the actual training of the network. o Validation Data -- These data are used to validate the network while t... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/NeuralNetwork/Training.py | LyonsLab/coge | train | 41 |
e0b2b668f71bc16c99d17567abc58a2d8f499d43 | [
"fov = parse_value(fov, 'arcmin')\nflux = spec.flux.value / fov / fov\nreturn cls(spec.ebins.value, flux, spec.binscale)",
"t_exp = parse_value(t_exp, 's')\nfov = parse_value(fov, 'arcmin')\nprng = parse_prng(prng)\nrate = fov * fov * self.total_flux.value\nenergy = _generate_energies(self, t_exp, rate, prng, sel... | <|body_start_0|>
fov = parse_value(fov, 'arcmin')
flux = spec.flux.value / fov / fov
return cls(spec.ebins.value, flux, spec.binscale)
<|end_body_0|>
<|body_start_1|>
t_exp = parse_value(t_exp, 's')
fov = parse_value(fov, 'arcmin')
prng = parse_prng(prng)
rate = ... | ConvolvedBackgroundSpectrum | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvolvedBackgroundSpectrum:
def from_spectrum(cls, spec, fov):
"""Create a convolved background spectrum from a regular :class:`~soxs.spectra.ConvolvedSpectrum` object and the width of a field of view on a side. Parameters ---------- spec : :class:`~soxs.spectra.ConvolvedSpectrum` The s... | stack_v2_sparse_classes_75kplus_train_070270 | 5,741 | permissive | [
{
"docstring": "Create a convolved background spectrum from a regular :class:`~soxs.spectra.ConvolvedSpectrum` object and the width of a field of view on a side. Parameters ---------- spec : :class:`~soxs.spectra.ConvolvedSpectrum` The spectrum to be used. fov : float, (value, unit) tuple, or :class:`~astropy.u... | 2 | null | Implement the Python class `ConvolvedBackgroundSpectrum` described below.
Class description:
Implement the ConvolvedBackgroundSpectrum class.
Method signatures and docstrings:
- def from_spectrum(cls, spec, fov): Create a convolved background spectrum from a regular :class:`~soxs.spectra.ConvolvedSpectrum` object and... | Implement the Python class `ConvolvedBackgroundSpectrum` described below.
Class description:
Implement the ConvolvedBackgroundSpectrum class.
Method signatures and docstrings:
- def from_spectrum(cls, spec, fov): Create a convolved background spectrum from a regular :class:`~soxs.spectra.ConvolvedSpectrum` object and... | dee1048f2eb8958aa23c16be896c856d987d6245 | <|skeleton|>
class ConvolvedBackgroundSpectrum:
def from_spectrum(cls, spec, fov):
"""Create a convolved background spectrum from a regular :class:`~soxs.spectra.ConvolvedSpectrum` object and the width of a field of view on a side. Parameters ---------- spec : :class:`~soxs.spectra.ConvolvedSpectrum` The s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConvolvedBackgroundSpectrum:
def from_spectrum(cls, spec, fov):
"""Create a convolved background spectrum from a regular :class:`~soxs.spectra.ConvolvedSpectrum` object and the width of a field of view on a side. Parameters ---------- spec : :class:`~soxs.spectra.ConvolvedSpectrum` The spectrum to be ... | the_stack_v2_python_sparse | soxs/background/spectra.py | jzuhone/soxs | train | 8 | |
4f53eebf489d79c775025a3b2a251a5d34039a3a | [
"self.right_answers = set(right_answers)\nself.problem = problem\nself.task = task\nself.kind = kind\nself.choices = ctypes.py_object * len(choices)\nself.choices = self.choices()\nfor i in range(len(choices)):\n self.choices[i] = choices[i]",
"self.task = Receiver.mml2latex(self.task).strip('$')\nfor i in ran... | <|body_start_0|>
self.right_answers = set(right_answers)
self.problem = problem
self.task = task
self.kind = kind
self.choices = ctypes.py_object * len(choices)
self.choices = self.choices()
for i in range(len(choices)):
self.choices[i] = choices[i]
<|... | A class that represents a separate problem. | Problem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Problem:
"""A class that represents a separate problem."""
def __init__(self, problem='', task='', kind='', choices=(), right_answers=()):
"""(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kin... | stack_v2_sparse_classes_75kplus_train_070271 | 9,855 | no_license | [
{
"docstring": "(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kind of the problem :param choices: available choices :param right_answers: right_answers for the problem",
"name": "__init__",
"signature": "def __i... | 3 | stack_v2_sparse_classes_30k_train_000803 | Implement the Python class `Problem` described below.
Class description:
A class that represents a separate problem.
Method signatures and docstrings:
- def __init__(self, problem='', task='', kind='', choices=(), right_answers=()): (Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem ... | Implement the Python class `Problem` described below.
Class description:
A class that represents a separate problem.
Method signatures and docstrings:
- def __init__(self, problem='', task='', kind='', choices=(), right_answers=()): (Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem ... | 43ea67af67bd9ceb9a2dd0ce7cf4ee342c3e13a2 | <|skeleton|>
class Problem:
"""A class that represents a separate problem."""
def __init__(self, problem='', task='', kind='', choices=(), right_answers=()):
"""(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Problem:
"""A class that represents a separate problem."""
def __init__(self, problem='', task='', kind='', choices=(), right_answers=()):
"""(Problem, str, str, str, tuple. tuple) initialization method :param problem: Problem statement :param task: task to be solved :param kind: kind of the prob... | the_stack_v2_python_sparse | flask-app/my_modules/classes.py | Centurion256/ProjectLogos | train | 1 |
61b1f18570c10932fe8e1ac4eb6d502a50801e85 | [
"country = data['country']\nstate_abbrev = data['state_abbrev']\nif state_abbrev:\n if not use_subdivisions(country):\n raise serializers.ValidationError('State/Province should not be set for {} neighborhoods'.format(country))\n if state_abbrev not in [s['code'] for s in subdivisions_for_country(countr... | <|body_start_0|>
country = data['country']
state_abbrev = data['state_abbrev']
if state_abbrev:
if not use_subdivisions(country):
raise serializers.ValidationError('State/Province should not be set for {} neighborhoods'.format(country))
if state_abbrev not... | NeighborhoodSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeighborhoodSerializer:
def validate(self, data):
"""Cross-field validation that state is set or not based on country."""
<|body_0|>
def save(self, *args, **kwargs):
"""Override the model save to convert errors raised there into serializer errors"""
<|body_1|... | stack_v2_sparse_classes_75kplus_train_070272 | 9,283 | permissive | [
{
"docstring": "Cross-field validation that state is set or not based on country.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Override the model save to convert errors raised there into serializer errors",
"name": "save",
"signature": "def save(self, ... | 2 | stack_v2_sparse_classes_30k_train_042457 | Implement the Python class `NeighborhoodSerializer` described below.
Class description:
Implement the NeighborhoodSerializer class.
Method signatures and docstrings:
- def validate(self, data): Cross-field validation that state is set or not based on country.
- def save(self, *args, **kwargs): Override the model save... | Implement the Python class `NeighborhoodSerializer` described below.
Class description:
Implement the NeighborhoodSerializer class.
Method signatures and docstrings:
- def validate(self, data): Cross-field validation that state is set or not based on country.
- def save(self, *args, **kwargs): Override the model save... | 620a5f4dc975891aa3b1266ced3f331fc17de19d | <|skeleton|>
class NeighborhoodSerializer:
def validate(self, data):
"""Cross-field validation that state is set or not based on country."""
<|body_0|>
def save(self, *args, **kwargs):
"""Override the model save to convert errors raised there into serializer errors"""
<|body_1|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeighborhoodSerializer:
def validate(self, data):
"""Cross-field validation that state is set or not based on country."""
country = data['country']
state_abbrev = data['state_abbrev']
if state_abbrev:
if not use_subdivisions(country):
raise serialize... | the_stack_v2_python_sparse | src/django/pfb_analysis/serializers.py | azavea/pfb-network-connectivity | train | 41 | |
5354a230c0a9a07bb3f03bbdf7b1bad5dbeb713e | [
"range_rate = (endvalue - startvalue) / startvalue\nif isannual:\n range_rate = pow(1 + range_rate, 365.25 / valuedates) - 1\nreturn range_rate",
"range_rate = (endvalue - startvalue) / startvalue\nif isannual:\n range_rate = pow(1 + range_rate, 12 / month) - 1\nreturn range_rate",
"range_rate = (endvalue... | <|body_start_0|>
range_rate = (endvalue - startvalue) / startvalue
if isannual:
range_rate = pow(1 + range_rate, 365.25 / valuedates) - 1
return range_rate
<|end_body_0|>
<|body_start_1|>
range_rate = (endvalue - startvalue) / startvalue
if isannual:
rang... | RangeReturnRate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangeReturnRate:
def annual_earnning_dates(startvalue, endvalue, isannual=False, valuedates=365):
"""计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数"""
<|body_0|>
def annual_earnning_month(startvalue, endvalue, isannual=False, month=12):
"""计算区间收益率,需要传传入区间初和末期的净值,valuedate... | stack_v2_sparse_classes_75kplus_train_070273 | 1,689 | no_license | [
{
"docstring": "计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数",
"name": "annual_earnning_dates",
"signature": "def annual_earnning_dates(startvalue, endvalue, isannual=False, valuedates=365)"
},
{
"docstring": "计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数",
"name": "annual_earnning_month",
"sig... | 3 | null | Implement the Python class `RangeReturnRate` described below.
Class description:
Implement the RangeReturnRate class.
Method signatures and docstrings:
- def annual_earnning_dates(startvalue, endvalue, isannual=False, valuedates=365): 计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数
- def annual_earnning_month(startvalue, e... | Implement the Python class `RangeReturnRate` described below.
Class description:
Implement the RangeReturnRate class.
Method signatures and docstrings:
- def annual_earnning_dates(startvalue, endvalue, isannual=False, valuedates=365): 计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数
- def annual_earnning_month(startvalue, e... | eae782a78ffde1276a0812a43d7deefb0bdedeb4 | <|skeleton|>
class RangeReturnRate:
def annual_earnning_dates(startvalue, endvalue, isannual=False, valuedates=365):
"""计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数"""
<|body_0|>
def annual_earnning_month(startvalue, endvalue, isannual=False, month=12):
"""计算区间收益率,需要传传入区间初和末期的净值,valuedate... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RangeReturnRate:
def annual_earnning_dates(startvalue, endvalue, isannual=False, valuedates=365):
"""计算区间收益率,需要传传入区间初和末期的净值,valuedates为净值区间的天数"""
range_rate = (endvalue - startvalue) / startvalue
if isannual:
range_rate = pow(1 + range_rate, 365.25 / valuedates) - 1
... | the_stack_v2_python_sparse | public_method/indicator_calculation_method/range_return_rate.py | liufubin-git/python | train | 0 | |
ed1d9b1dd8f315215d7c33052d54fc721ffe55f9 | [
"super().__init__()\nself.hidden2tag = nn.Linear(hidden_size, len(label))\nself.crf_part = CRF(class_num=len(label), start_tag=label.start_index, end_tag=label.end_index)\nparameter_init.init_linear(self.hidden2tag)",
"emission = self.hidden2tag.forward(lstm_result)\nn, max_sentence_len, _ = emission.shape\nmask ... | <|body_start_0|>
super().__init__()
self.hidden2tag = nn.Linear(hidden_size, len(label))
self.crf_part = CRF(class_num=len(label), start_tag=label.start_index, end_tag=label.end_index)
parameter_init.init_linear(self.hidden2tag)
<|end_body_0|>
<|body_start_1|>
emission = self.hi... | 这部分是负责接受 LSTM 的输出之后,进行求 loss 和 预测;和 softmax.py 里面的 SoftmaxDecoder 同样的作用 | CRFDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRFDecoder:
"""这部分是负责接受 LSTM 的输出之后,进行求 loss 和 预测;和 softmax.py 里面的 SoftmaxDecoder 同样的作用"""
def __init__(self, hidden_size: int, label: Label):
""":param hidden_size: (LSTM) 注意由于是 双向 LSTM,所以要除以 2 :param label: Label object. See label.py for documentation. 全局共享即可 # 论文中: y0 and yn are th... | stack_v2_sparse_classes_75kplus_train_070274 | 30,398 | no_license | [
{
"docstring": ":param hidden_size: (LSTM) 注意由于是 双向 LSTM,所以要除以 2 :param label: Label object. See label.py for documentation. 全局共享即可 # 论文中: y0 and yn are the start and end tags of a sentence, that we add to the set of possible tags. A is therefore a square matrix of size k+2 # 在有效标注之外,我们添加了 START 和 END",
"na... | 4 | stack_v2_sparse_classes_30k_train_039358 | Implement the Python class `CRFDecoder` described below.
Class description:
这部分是负责接受 LSTM 的输出之后,进行求 loss 和 预测;和 softmax.py 里面的 SoftmaxDecoder 同样的作用
Method signatures and docstrings:
- def __init__(self, hidden_size: int, label: Label): :param hidden_size: (LSTM) 注意由于是 双向 LSTM,所以要除以 2 :param label: Label object. See l... | Implement the Python class `CRFDecoder` described below.
Class description:
这部分是负责接受 LSTM 的输出之后,进行求 loss 和 预测;和 softmax.py 里面的 SoftmaxDecoder 同样的作用
Method signatures and docstrings:
- def __init__(self, hidden_size: int, label: Label): :param hidden_size: (LSTM) 注意由于是 双向 LSTM,所以要除以 2 :param label: Label object. See l... | 29dc4aa0ebd3f610135ceb88f62634b4597b564a | <|skeleton|>
class CRFDecoder:
"""这部分是负责接受 LSTM 的输出之后,进行求 loss 和 预测;和 softmax.py 里面的 SoftmaxDecoder 同样的作用"""
def __init__(self, hidden_size: int, label: Label):
""":param hidden_size: (LSTM) 注意由于是 双向 LSTM,所以要除以 2 :param label: Label object. See label.py for documentation. 全局共享即可 # 论文中: y0 and yn are th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CRFDecoder:
"""这部分是负责接受 LSTM 的输出之后,进行求 loss 和 预测;和 softmax.py 里面的 SoftmaxDecoder 同样的作用"""
def __init__(self, hidden_size: int, label: Label):
""":param hidden_size: (LSTM) 注意由于是 双向 LSTM,所以要除以 2 :param label: Label object. See label.py for documentation. 全局共享即可 # 论文中: y0 and yn are the start and e... | the_stack_v2_python_sparse | task04/modules/crf.py | yjqiang/nlp-beginner | train | 2 |
f4889128b9464fb50f0ede0735e8a6124924cd0a | [
"master = Tk()\nmaster.title('CsvViewer')\nmaster.geometry('1000x400')\nself.view = CSVView(master)\nself.logic = CSVLogic()\nself.view.setReadButtonCommand(self.readButtonCommand)\nmaster.mainloop()",
"columns, datas = self.readCsv()\nself.view.setNewColumnAndData(columns, datas)\nself.view.setSaveButtonCommand(... | <|body_start_0|>
master = Tk()
master.title('CsvViewer')
master.geometry('1000x400')
self.view = CSVView(master)
self.logic = CSVLogic()
self.view.setReadButtonCommand(self.readButtonCommand)
master.mainloop()
<|end_body_0|>
<|body_start_1|>
columns, data... | csvViewerのコントローラー | CSVControl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVControl:
"""csvViewerのコントローラー"""
def __init__(self):
"""アプリの立ち上げとイベント登録"""
<|body_0|>
def readButtonCommand(self):
"""csv読み込みボタン用コマンド csvから取得した列名、データをViewに反映する。 csvが変更されるごとにRowDataフレームがリロードされるので、 保存ボタンコマンドも再設定"""
<|body_1|>
def saveButtonCommand(s... | stack_v2_sparse_classes_75kplus_train_070275 | 3,655 | no_license | [
{
"docstring": "アプリの立ち上げとイベント登録",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "csv読み込みボタン用コマンド csvから取得した列名、データをViewに反映する。 csvが変更されるごとにRowDataフレームがリロードされるので、 保存ボタンコマンドも再設定",
"name": "readButtonCommand",
"signature": "def readButtonCommand(self)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_040340 | Implement the Python class `CSVControl` described below.
Class description:
csvViewerのコントローラー
Method signatures and docstrings:
- def __init__(self): アプリの立ち上げとイベント登録
- def readButtonCommand(self): csv読み込みボタン用コマンド csvから取得した列名、データをViewに反映する。 csvが変更されるごとにRowDataフレームがリロードされるので、 保存ボタンコマンドも再設定
- def saveButtonCommand(self)... | Implement the Python class `CSVControl` described below.
Class description:
csvViewerのコントローラー
Method signatures and docstrings:
- def __init__(self): アプリの立ち上げとイベント登録
- def readButtonCommand(self): csv読み込みボタン用コマンド csvから取得した列名、データをViewに反映する。 csvが変更されるごとにRowDataフレームがリロードされるので、 保存ボタンコマンドも再設定
- def saveButtonCommand(self)... | 5c8d345ac83a908e9513ba21fc8164a3575d4ce6 | <|skeleton|>
class CSVControl:
"""csvViewerのコントローラー"""
def __init__(self):
"""アプリの立ち上げとイベント登録"""
<|body_0|>
def readButtonCommand(self):
"""csv読み込みボタン用コマンド csvから取得した列名、データをViewに反映する。 csvが変更されるごとにRowDataフレームがリロードされるので、 保存ボタンコマンドも再設定"""
<|body_1|>
def saveButtonCommand(s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CSVControl:
"""csvViewerのコントローラー"""
def __init__(self):
"""アプリの立ち上げとイベント登録"""
master = Tk()
master.title('CsvViewer')
master.geometry('1000x400')
self.view = CSVView(master)
self.logic = CSVLogic()
self.view.setReadButtonCommand(self.readButtonComma... | the_stack_v2_python_sparse | CsvViewer/csvcontrol.py | SuzuTakahiro/SampleProject | train | 0 |
4bd8031530ef92e6cfb6cad5044d2de77d57b3aa | [
"if isinstance(context, basestring):\n self.response.write(context)\nelse:\n context = json.dumps(context)\n self.response.write(context)\nself.response.headers['Content-Type'] = 'application/json'",
"error_report = {'method': self.request.method, 'url': self.request.path_url, 'query_string': self.reques... | <|body_start_0|>
if isinstance(context, basestring):
self.response.write(context)
else:
context = json.dumps(context)
self.response.write(context)
self.response.headers['Content-Type'] = 'application/json'
<|end_body_0|>
<|body_start_1|>
error_report ... | Simple webapp2 base handler to return JSON data from API endpoints | JsonHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonHandler:
"""Simple webapp2 base handler to return JSON data from API endpoints"""
def render_response(self, context):
"""Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_070276 | 2,742 | no_license | [
{
"docstring": "Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string.",
"name": "render_response",
"signature": "def render_response(self, context)"
},
{
"docstring": "Override handle_exception() to send errors to our sen... | 2 | stack_v2_sparse_classes_30k_train_008891 | Implement the Python class `JsonHandler` described below.
Class description:
Simple webapp2 base handler to return JSON data from API endpoints
Method signatures and docstrings:
- def render_response(self, context): Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response... | Implement the Python class `JsonHandler` described below.
Class description:
Simple webapp2 base handler to return JSON data from API endpoints
Method signatures and docstrings:
- def render_response(self, context): Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response... | 6e2a4854eac540968ebc8f0893834dcd24cef74e | <|skeleton|>
class JsonHandler:
"""Simple webapp2 base handler to return JSON data from API endpoints"""
def render_response(self, context):
"""Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string."""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JsonHandler:
"""Simple webapp2 base handler to return JSON data from API endpoints"""
def render_response(self, context):
"""Accepts a JSON encoded string or object which can be serialised to JSON and outputs it to the response as a JSON encoded string."""
if isinstance(context, basestrin... | the_stack_v2_python_sparse | handlers/api/base.py | paddycarey/taskr | train | 0 |
2ece75dba9e6a5f417bd8dc57be8d9b704c9183f | [
"if 0 == len(strs):\n return ''\nif 1 == len(strs):\n return strs[0]\nstrs.sort(key=lambda t: len(t))\nfirstStr = strs[0]\nsubStrLen = len(firstStr)\nfor idx in range(1, len(strs)):\n subStrLen = self.interSect(firstStr[:subStrLen], strs[idx])\n if subStrLen == 0:\n return ''\nreturn firstStr[:su... | <|body_start_0|>
if 0 == len(strs):
return ''
if 1 == len(strs):
return strs[0]
strs.sort(key=lambda t: len(t))
firstStr = strs[0]
subStrLen = len(firstStr)
for idx in range(1, len(strs)):
subStrLen = self.interSect(firstStr[:subStrLen]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def interSect(self, str1, str2):
"""两个字符串取公共首字符串,str1长度小于str2 :param str1: :param str2: :return: 返回公共首字符串的长度"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_070277 | 1,616 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": "两个字符串取公共首字符串,str1长度小于str2 :param str1: :param str2: :return: 返回公共首字符串的长度",
"name": "interSect",
"signature": "def interSect(self, str1,... | 2 | stack_v2_sparse_classes_30k_train_033347 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def interSect(self, str1, str2): 两个字符串取公共首字符串,str1长度小于str2 :param str1: :param str2: :return: 返回公共首字符串的长度 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def interSect(self, str1, str2): 两个字符串取公共首字符串,str1长度小于str2 :param str1: :param str2: :return: 返回公共首字符串的长度... | f48adb58482be545ae32fdfcda4a28045378d22f | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def interSect(self, str1, str2):
"""两个字符串取公共首字符串,str1长度小于str2 :param str1: :param str2: :return: 返回公共首字符串的长度"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
if 0 == len(strs):
return ''
if 1 == len(strs):
return strs[0]
strs.sort(key=lambda t: len(t))
firstStr = strs[0]
subStrLen = len(firstStr)
for... | the_stack_v2_python_sparse | 0001~0050/0014_最长公共前缀/longestCommonPrefix.py | JordenDan/LeetCodePython | train | 0 | |
dbcf0a5a456bc078fbeb92623b1de0880bc944dc | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn OrgContact()",
"from .directory_object import DirectoryObject\nfrom .on_premises_provisioning_error import OnPremisesProvisioningError\nfrom .phone import Phone\nfrom .physical_office_address import PhysicalOfficeAddress\nfrom .directo... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return OrgContact()
<|end_body_0|>
<|body_start_1|>
from .directory_object import DirectoryObject
from .on_premises_provisioning_error import OnPremisesProvisioningError
from .phone imp... | OrgContact | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrgContact:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OrgContact:
"""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: OrgC... | stack_v2_sparse_classes_75kplus_train_070278 | 9,476 | 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: OrgContact",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pa... | 3 | stack_v2_sparse_classes_30k_train_036913 | Implement the Python class `OrgContact` described below.
Class description:
Implement the OrgContact class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OrgContact: Creates a new instance of the appropriate class based on discriminator value Args: pa... | Implement the Python class `OrgContact` described below.
Class description:
Implement the OrgContact class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OrgContact: Creates a new instance of the appropriate class based on discriminator value Args: pa... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class OrgContact:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OrgContact:
"""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: OrgC... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OrgContact:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> OrgContact:
"""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: OrgContact"""
... | the_stack_v2_python_sparse | msgraph/generated/models/org_contact.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
6f46dd919218e3530aabd7cd8acb586103a3cb4c | [
"self.dataproc = dataproc\nself.execution_config_factory = execution_config_factory_override\nif not self.execution_config_factory:\n self.execution_config_factory = ecf.ExecutionConfigFactory(self.dataproc)\nself.peripherals_config_factory = peripherals_config_factory_override\nif not self.peripherals_config_fa... | <|body_start_0|>
self.dataproc = dataproc
self.execution_config_factory = execution_config_factory_override
if not self.execution_config_factory:
self.execution_config_factory = ecf.ExecutionConfigFactory(self.dataproc)
self.peripherals_config_factory = peripherals_config_fac... | Factory for EnvironmentConfig message. Add arguments related to EnvironmentConfig to argument parser and create EnvironmentConfig message from parsed arguments. | EnvironmentConfigFactory | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentConfigFactory:
"""Factory for EnvironmentConfig message. Add arguments related to EnvironmentConfig to argument parser and create EnvironmentConfig message from parsed arguments."""
def __init__(self, dataproc, execution_config_factory_override=None, peripherals_config_factory_ove... | stack_v2_sparse_classes_75kplus_train_070279 | 3,047 | permissive | [
{
"docstring": "Factory for EnvironmentConfig message. Args: dataproc: A api_lib.dataproc.Dataproc instance. execution_config_factory_override: Override the default ExecutionConfigFactory instance. This is a keyword argument. peripherals_config_factory_override: Override the default PeripheralsConfigFactory ins... | 2 | stack_v2_sparse_classes_30k_train_026370 | Implement the Python class `EnvironmentConfigFactory` described below.
Class description:
Factory for EnvironmentConfig message. Add arguments related to EnvironmentConfig to argument parser and create EnvironmentConfig message from parsed arguments.
Method signatures and docstrings:
- def __init__(self, dataproc, ex... | Implement the Python class `EnvironmentConfigFactory` described below.
Class description:
Factory for EnvironmentConfig message. Add arguments related to EnvironmentConfig to argument parser and create EnvironmentConfig message from parsed arguments.
Method signatures and docstrings:
- def __init__(self, dataproc, ex... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class EnvironmentConfigFactory:
"""Factory for EnvironmentConfig message. Add arguments related to EnvironmentConfig to argument parser and create EnvironmentConfig message from parsed arguments."""
def __init__(self, dataproc, execution_config_factory_override=None, peripherals_config_factory_ove... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnvironmentConfigFactory:
"""Factory for EnvironmentConfig message. Add arguments related to EnvironmentConfig to argument parser and create EnvironmentConfig message from parsed arguments."""
def __init__(self, dataproc, execution_config_factory_override=None, peripherals_config_factory_override=None):
... | the_stack_v2_python_sparse | lib/googlecloudsdk/command_lib/dataproc/shared_messages/environment_config_factory.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
4a31243dac5c9c40a2effd798d49dd7b5cbd2d24 | [
"self._log = session._log.getChild('post_grid.%s' % uri)\nsuper(PostGridOperation, self).__init__(session=session, uri=uri, args=args, **kwargs)\nself._body = hszinc.dump(grid, mode=post_format).encode('utf-8')\nif post_format == hszinc.MODE_ZINC:\n self._content_type = 'text/zinc'\nelse:\n self._content_type... | <|body_start_0|>
self._log = session._log.getChild('post_grid.%s' % uri)
super(PostGridOperation, self).__init__(session=session, uri=uri, args=args, **kwargs)
self._body = hszinc.dump(grid, mode=post_format).encode('utf-8')
if post_format == hszinc.MODE_ZINC:
self._content_t... | A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid. | PostGridOperation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostGridOperation:
"""A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid."""
def __init__(self, session, uri, grid, args=None, post_format=hszinc.MODE_ZINC, **kwargs):
"""Initialise a POST request for the grid with the given grid, URI and a... | stack_v2_sparse_classes_75kplus_train_070280 | 13,981 | permissive | [
{
"docstring": "Initialise a POST request for the grid with the given grid, URI and arguments. :param session: Haystack HTTP session object. :param uri: Possibly partial URI relative to the server base address to perform a query. No arguments shall be given here. :param grid: Grid (or grids) to be posted to the... | 2 | stack_v2_sparse_classes_30k_train_001480 | Implement the Python class `PostGridOperation` described below.
Class description:
A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid.
Method signatures and docstrings:
- def __init__(self, session, uri, grid, args=None, post_format=hszinc.MODE_ZINC, **kwargs): Initialise a... | Implement the Python class `PostGridOperation` described below.
Class description:
A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid.
Method signatures and docstrings:
- def __init__(self, session, uri, grid, args=None, post_format=hszinc.MODE_ZINC, **kwargs): Initialise a... | 03908c9c4c671aefa129662a0a9ed0360af82d69 | <|skeleton|>
class PostGridOperation:
"""A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid."""
def __init__(self, session, uri, grid, args=None, post_format=hszinc.MODE_ZINC, **kwargs):
"""Initialise a POST request for the grid with the given grid, URI and a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostGridOperation:
"""A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid."""
def __init__(self, session, uri, grid, args=None, post_format=hszinc.MODE_ZINC, **kwargs):
"""Initialise a POST request for the grid with the given grid, URI and arguments. :pa... | the_stack_v2_python_sparse | pyhaystack/client/ops/grid.py | itsmeccr/pyhaystack | train | 1 |
ad1efc0d75b04192b19e155989519f551edaaef0 | [
"if verbose:\n print('SQL Database type %s verbose=%s' % (db_dict, verbose))\nsuper(SQLUsersTable, self).__init__(db_dict, dbtype, verbose)\nself.connection = None",
"try:\n if self.verbose:\n print('Database characteristics')\n for key in self.db_dict:\n print('%s: %s' % key, self... | <|body_start_0|>
if verbose:
print('SQL Database type %s verbose=%s' % (db_dict, verbose))
super(SQLUsersTable, self).__init__(db_dict, dbtype, verbose)
self.connection = None
<|end_body_0|>
<|body_start_1|>
try:
if self.verbose:
print('Database ... | " Table representing the Users database table This table supports a single dictionary that contains the data when the table is intialized. It is a generalization for all database accesses. | SQLUsersTable | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLUsersTable:
"""" Table representing the Users database table This table supports a single dictionary that contains the data when the table is intialized. It is a generalization for all database accesses."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
... | stack_v2_sparse_classes_75kplus_train_070281 | 17,893 | permissive | [
{
"docstring": "Pass through to SQL",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Display the db info and Return info on the database used as a dictionary.",
"name": "db_info",
"signature": "def db_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027831 | Implement the Python class `SQLUsersTable` described below.
Class description:
" Table representing the Users database table This table supports a single dictionary that contains the data when the table is intialized. It is a generalization for all database accesses.
Method signatures and docstrings:
- def __init__(s... | Implement the Python class `SQLUsersTable` described below.
Class description:
" Table representing the Users database table This table supports a single dictionary that contains the data when the table is intialized. It is a generalization for all database accesses.
Method signatures and docstrings:
- def __init__(s... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class SQLUsersTable:
"""" Table representing the Users database table This table supports a single dictionary that contains the data when the table is intialized. It is a generalization for all database accesses."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SQLUsersTable:
"""" Table representing the Users database table This table supports a single dictionary that contains the data when the table is intialized. It is a generalization for all database accesses."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
if verb... | the_stack_v2_python_sparse | smipyping/_userstable.py | KSchopmeyer/smipyping | train | 0 |
d48703fbf709e82d393ad81a46d8640eb7508fed | [
"super(StepLR, self).__init__()\nself.step_size = step_size\nself.gamma = gamma",
"lr_each_step = []\ncur_lr = base_lr\nfor i in range(global_step):\n cur_epoch = int(i // (global_step / total_epoch))\n if cur_epoch > 0 and i % cur_epoch == 0:\n cur_lr = base_lr * self.gamma ** (cur_epoch // self.ste... | <|body_start_0|>
super(StepLR, self).__init__()
self.step_size = step_size
self.gamma = gamma
<|end_body_0|>
<|body_start_1|>
lr_each_step = []
cur_lr = base_lr
for i in range(global_step):
cur_epoch = int(i // (global_step / total_epoch))
if cur_... | StepLR learning rate. :param step_size: the epoch interval to decay lr :type step_size: int :param gamma: the decay rate :type gamma: float | StepLR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StepLR:
"""StepLR learning rate. :param step_size: the epoch interval to decay lr :type step_size: int :param gamma: the decay rate :type gamma: float"""
def __init__(self, optimizer=None, step_size=None, gamma=0.1):
"""Initialize."""
<|body_0|>
def __call__(self, base_l... | stack_v2_sparse_classes_75kplus_train_070282 | 5,873 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, optimizer=None, step_size=None, gamma=0.1)"
},
{
"docstring": "Call lr scheduler class.",
"name": "__call__",
"signature": "def __call__(self, base_lr, global_step, total_epoch)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045829 | Implement the Python class `StepLR` described below.
Class description:
StepLR learning rate. :param step_size: the epoch interval to decay lr :type step_size: int :param gamma: the decay rate :type gamma: float
Method signatures and docstrings:
- def __init__(self, optimizer=None, step_size=None, gamma=0.1): Initial... | Implement the Python class `StepLR` described below.
Class description:
StepLR learning rate. :param step_size: the epoch interval to decay lr :type step_size: int :param gamma: the decay rate :type gamma: float
Method signatures and docstrings:
- def __init__(self, optimizer=None, step_size=None, gamma=0.1): Initial... | 52b53582fe7df95d7aacc8425013fd18645d079f | <|skeleton|>
class StepLR:
"""StepLR learning rate. :param step_size: the epoch interval to decay lr :type step_size: int :param gamma: the decay rate :type gamma: float"""
def __init__(self, optimizer=None, step_size=None, gamma=0.1):
"""Initialize."""
<|body_0|>
def __call__(self, base_l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StepLR:
"""StepLR learning rate. :param step_size: the epoch interval to decay lr :type step_size: int :param gamma: the decay rate :type gamma: float"""
def __init__(self, optimizer=None, step_size=None, gamma=0.1):
"""Initialize."""
super(StepLR, self).__init__()
self.step_size ... | the_stack_v2_python_sparse | vega/trainer/modules/lr_schedulers/ms_lr_scheduler.py | yiziqi/vega | train | 0 |
204c87141738c2b97f77bfd3e5e582a4c531cb82 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.is_active = True\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_active = Tr... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.is_active = True
user.save(using=self._db)
return user
<|end_body_0|>
<|body_s... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_75kplus_train_070283 | 37,720 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_043750 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | f803fd6d582f47a6be745a9852793bac8a293da1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | FIRSTCRM/crm/models.py | uge3/FIRSTCRM | train | 0 | |
7e62e6c49f8f2778fee55552069eed9614fe3032 | [
"preorder = []\n\ndef helper(node):\n if node:\n preorder.append(str(node.val))\n helper(node.left)\n helper(node.right)\nhelper(root)\nreturn '|'.join(preorder)",
"if not data:\n return None\npreorder = list(map(int, data.split('|')))\ni = 0\n\ndef helper(lo=float('-inf'), hi=float('in... | <|body_start_0|>
preorder = []
def helper(node):
if node:
preorder.append(str(node.val))
helper(node.left)
helper(node.right)
helper(root)
return '|'.join(preorder)
<|end_body_0|>
<|body_start_1|>
if not data:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
preorder = []
... | stack_v2_sparse_classes_75kplus_train_070284 | 4,762 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_005962 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 59f70dc4466e15df591ba285317e4a1fe808ed60 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
preorder = []
def helper(node):
if node:
preorder.append(str(node.val))
helper(node.left)
helper(node.right)
helper(root)
... | the_stack_v2_python_sparse | leet/amazon/trees_and_graphs/449_serialize_and_deserialize_BST.py | arsamigullin/problem_solving_python | train | 0 | |
9d98bef6556da0c0ef934ad3d7a2cc47a0cbbbf4 | [
"workflow_id = kwargs.get('workflow_id')\nrequest_data = request.GET\nusername = request.META.get('HTTP_USERNAME')\nsearch_value = request_data.get('search_value', '')\nper_page = int(request_data.get('per_page', 10)) if request_data.get('per_page', 10) else 10\npage = int(request_data.get('page', 1)) if request_da... | <|body_start_0|>
workflow_id = kwargs.get('workflow_id')
request_data = request.GET
username = request.META.get('HTTP_USERNAME')
search_value = request_data.get('search_value', '')
per_page = int(request_data.get('per_page', 10)) if request_data.get('per_page', 10) else 10
... | WorkflowStateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowStateView:
def get(self, request, *args, **kwargs):
"""获取工作流拥有的state列表信息 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""新增状态 :param request: :param args: :param kwargs: :return:"""
<|bod... | stack_v2_sparse_classes_75kplus_train_070285 | 48,278 | permissive | [
{
"docstring": "获取工作流拥有的state列表信息 :param request: :param args: :param kwargs: :return:",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "新增状态 :param request: :param args: :param kwargs: :return:",
"name": "post",
"signature": "def post(self, reque... | 2 | null | Implement the Python class `WorkflowStateView` described below.
Class description:
Implement the WorkflowStateView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取工作流拥有的state列表信息 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 新增状态... | Implement the Python class `WorkflowStateView` described below.
Class description:
Implement the WorkflowStateView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): 获取工作流拥有的state列表信息 :param request: :param args: :param kwargs: :return:
- def post(self, request, *args, **kwargs): 新增状态... | b0e236b314286c5f6cc6959622c9c8505e776443 | <|skeleton|>
class WorkflowStateView:
def get(self, request, *args, **kwargs):
"""获取工作流拥有的state列表信息 :param request: :param args: :param kwargs: :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""新增状态 :param request: :param args: :param kwargs: :return:"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WorkflowStateView:
def get(self, request, *args, **kwargs):
"""获取工作流拥有的state列表信息 :param request: :param args: :param kwargs: :return:"""
workflow_id = kwargs.get('workflow_id')
request_data = request.GET
username = request.META.get('HTTP_USERNAME')
search_value = reques... | the_stack_v2_python_sparse | apps/workflow/views.py | blackholll/loonflow | train | 1,864 | |
84d965c6d90bc14d3f9d00b873c3fc09553ba59a | [
"test_2 = [1, 2]\ntable_of_2 = [[1, 2], [2, 4]]\nself.assertEqual(primes.mult_table(test_2), table_of_2)",
"test_4 = [1, 2, 3, 4]\ntable_of_4 = [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]\nself.assertEqual(primes.mult_table(test_4), table_of_4)"
] | <|body_start_0|>
test_2 = [1, 2]
table_of_2 = [[1, 2], [2, 4]]
self.assertEqual(primes.mult_table(test_2), table_of_2)
<|end_body_0|>
<|body_start_1|>
test_4 = [1, 2, 3, 4]
table_of_4 = [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]
self.assertEqual(primes.m... | Test for the mult_table function | TestMultTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestMultTable:
"""Test for the mult_table function"""
def test_mult_table_size_2(self):
"""Test if it makes a matrix of size 2"""
<|body_0|>
def test_mult_table_size_4(self):
"""Test if it makes a matrix of size 4"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_070286 | 4,108 | no_license | [
{
"docstring": "Test if it makes a matrix of size 2",
"name": "test_mult_table_size_2",
"signature": "def test_mult_table_size_2(self)"
},
{
"docstring": "Test if it makes a matrix of size 4",
"name": "test_mult_table_size_4",
"signature": "def test_mult_table_size_4(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054346 | Implement the Python class `TestMultTable` described below.
Class description:
Test for the mult_table function
Method signatures and docstrings:
- def test_mult_table_size_2(self): Test if it makes a matrix of size 2
- def test_mult_table_size_4(self): Test if it makes a matrix of size 4 | Implement the Python class `TestMultTable` described below.
Class description:
Test for the mult_table function
Method signatures and docstrings:
- def test_mult_table_size_2(self): Test if it makes a matrix of size 2
- def test_mult_table_size_4(self): Test if it makes a matrix of size 4
<|skeleton|>
class TestMult... | e2ead4bfa7a089c9439c00479053b10b69b16c99 | <|skeleton|>
class TestMultTable:
"""Test for the mult_table function"""
def test_mult_table_size_2(self):
"""Test if it makes a matrix of size 2"""
<|body_0|>
def test_mult_table_size_4(self):
"""Test if it makes a matrix of size 4"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestMultTable:
"""Test for the mult_table function"""
def test_mult_table_size_2(self):
"""Test if it makes a matrix of size 2"""
test_2 = [1, 2]
table_of_2 = [[1, 2], [2, 4]]
self.assertEqual(primes.mult_table(test_2), table_of_2)
def test_mult_table_size_4(self):
... | the_stack_v2_python_sparse | Primes with Tests/test_primes.py | setc/PythonSnippets | train | 0 |
9a5adfea89cad9d5e7a12b3e94e9cf12f559e555 | [
"site_info: Dict[str, Dict] = {}\nif isinstance(stations, str):\n stations = [s.strip().lower() for s in stations.split(',')]\nelse:\n stations = [s.lower() for s in stations]\nfor sta in stations:\n site_dict = site_info.setdefault(sta, {})\n for module in _MODULES:\n module_name = 'site_coord' ... | <|body_start_0|>
site_info: Dict[str, Dict] = {}
if isinstance(stations, str):
stations = [s.strip().lower() for s in stations.split(',')]
else:
stations = [s.lower() for s in stations]
for sta in stations:
site_dict = site_info.setdefault(sta, {})
... | Main site information class for site information from various sources into unified classes | SiteInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiteInfo:
"""Main site information class for site information from various sources into unified classes"""
def get(cls, source: str, source_data: Any, stations: Union[str, Iterable], date: Union[None, datetime]=None, source_path: Union[None, str]=None) -> Dict:
"""Get site informatio... | stack_v2_sparse_classes_75kplus_train_070287 | 5,047 | permissive | [
{
"docstring": "Get site information dictionary from given source for specified date Args: source: Site information source type: e.g. 'snx' (SINEX file), 'ssc' (SSC file) or other source_data: Source data with site information from specified source type. stations: List of station names. date: Date for getting s... | 2 | stack_v2_sparse_classes_30k_train_027175 | Implement the Python class `SiteInfo` described below.
Class description:
Main site information class for site information from various sources into unified classes
Method signatures and docstrings:
- def get(cls, source: str, source_data: Any, stations: Union[str, Iterable], date: Union[None, datetime]=None, source_... | Implement the Python class `SiteInfo` described below.
Class description:
Main site information class for site information from various sources into unified classes
Method signatures and docstrings:
- def get(cls, source: str, source_data: Any, stations: Union[str, Iterable], date: Union[None, datetime]=None, source_... | 31939afee943273b23fa0a5ef193cfecfa68d6c0 | <|skeleton|>
class SiteInfo:
"""Main site information class for site information from various sources into unified classes"""
def get(cls, source: str, source_data: Any, stations: Union[str, Iterable], date: Union[None, datetime]=None, source_path: Union[None, str]=None) -> Dict:
"""Get site informatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SiteInfo:
"""Main site information class for site information from various sources into unified classes"""
def get(cls, source: str, source_data: Any, stations: Union[str, Iterable], date: Union[None, datetime]=None, source_path: Union[None, str]=None) -> Dict:
"""Get site information dictionary ... | the_stack_v2_python_sparse | midgard/site_info/site_info.py | kartverket/midgard | train | 18 |
87af4553cf0e887a6e303fa9b2ea4846e58575e7 | [
"self.ip = determine_ip()\nargs = self.get_command_line_args()\nself.port = self.determine_port(args)",
"parser = argparse.ArgumentParser(description='Run UX server.')\nparser.add_argument('-p', '--port', type=int, help='port number to listen on')\nreturn vars(parser.parse_args())",
"command_line_port = args.ge... | <|body_start_0|>
self.ip = determine_ip()
args = self.get_command_line_args()
self.port = self.determine_port(args)
<|end_body_0|>
<|body_start_1|>
parser = argparse.ArgumentParser(description='Run UX server.')
parser.add_argument('-p', '--port', type=int, help='port number to l... | Configuration object for UX server. | Configuration | [
"Apache-2.0",
"Intel",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Configuration:
"""Configuration object for UX server."""
def __init__(self) -> None:
"""Set the variables."""
<|body_0|>
def get_command_line_args(self) -> Dict:
"""Return arguments passed in command line."""
<|body_1|>
def determine_port(self, args:... | stack_v2_sparse_classes_75kplus_train_070288 | 2,954 | permissive | [
{
"docstring": "Set the variables.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Return arguments passed in command line.",
"name": "get_command_line_args",
"signature": "def get_command_line_args(self) -> Dict"
},
{
"docstring": "Return port ... | 4 | stack_v2_sparse_classes_30k_train_015456 | Implement the Python class `Configuration` described below.
Class description:
Configuration object for UX server.
Method signatures and docstrings:
- def __init__(self) -> None: Set the variables.
- def get_command_line_args(self) -> Dict: Return arguments passed in command line.
- def determine_port(self, args: Dic... | Implement the Python class `Configuration` described below.
Class description:
Configuration object for UX server.
Method signatures and docstrings:
- def __init__(self) -> None: Set the variables.
- def get_command_line_args(self) -> Dict: Return arguments passed in command line.
- def determine_port(self, args: Dic... | 1c8bc24dc15d2f6aaeb582c49a2908fb183f63b9 | <|skeleton|>
class Configuration:
"""Configuration object for UX server."""
def __init__(self) -> None:
"""Set the variables."""
<|body_0|>
def get_command_line_args(self) -> Dict:
"""Return arguments passed in command line."""
<|body_1|>
def determine_port(self, args:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Configuration:
"""Configuration object for UX server."""
def __init__(self) -> None:
"""Set the variables."""
self.ip = determine_ip()
args = self.get_command_line_args()
self.port = self.determine_port(args)
def get_command_line_args(self) -> Dict:
"""Return ... | the_stack_v2_python_sparse | lpot/ux/web/configuration.py | SnehalA/lpot | train | 0 |
30c09bd08f985020612c22f5f579a838dce305e6 | [
"super().__init__(api, server_unique_id)\nself.entity_description = description\nif description.key == CONF_CURRENT_VALUES:\n self._attr_name = f\"{description.name}_{('' if sid is None else sid)}\"\nself._attr_unique_id = f\"{server_unique_id}/{description.key}_{('' if sid is None else sid)}\"\nif 'cost' in des... | <|body_start_0|>
super().__init__(api, server_unique_id)
self.entity_description = description
if description.key == CONF_CURRENT_VALUES:
self._attr_name = f"{description.name}_{('' if sid is None else sid)}"
self._attr_unique_id = f"{server_unique_id}/{description.key}_{('' ... | Implementation of an Efergy sensor. | EfergySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EfergySensor:
"""Implementation of an Efergy sensor."""
def __init__(self, api: Efergy, description: SensorEntityDescription, server_unique_id: str, period: str | None=None, currency: str | None=None, sid: int | None=None) -> None:
"""Initialize the sensor."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_070289 | 6,200 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, api: Efergy, description: SensorEntityDescription, server_unique_id: str, period: str | None=None, currency: str | None=None, sid: int | None=None) -> None"
},
{
"docstring": "Get the Efergy monitor dat... | 2 | null | Implement the Python class `EfergySensor` described below.
Class description:
Implementation of an Efergy sensor.
Method signatures and docstrings:
- def __init__(self, api: Efergy, description: SensorEntityDescription, server_unique_id: str, period: str | None=None, currency: str | None=None, sid: int | None=None) -... | Implement the Python class `EfergySensor` described below.
Class description:
Implementation of an Efergy sensor.
Method signatures and docstrings:
- def __init__(self, api: Efergy, description: SensorEntityDescription, server_unique_id: str, period: str | None=None, currency: str | None=None, sid: int | None=None) -... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EfergySensor:
"""Implementation of an Efergy sensor."""
def __init__(self, api: Efergy, description: SensorEntityDescription, server_unique_id: str, period: str | None=None, currency: str | None=None, sid: int | None=None) -> None:
"""Initialize the sensor."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EfergySensor:
"""Implementation of an Efergy sensor."""
def __init__(self, api: Efergy, description: SensorEntityDescription, server_unique_id: str, period: str | None=None, currency: str | None=None, sid: int | None=None) -> None:
"""Initialize the sensor."""
super().__init__(api, server... | the_stack_v2_python_sparse | homeassistant/components/efergy/sensor.py | home-assistant/core | train | 35,501 |
68be0addbbfa6028ee5563b40867015e28294bea | [
"if 'page' in self.request.POST:\n try:\n location = 'dashboard'\n kwargs = {'page': int(self.request.POST.get('page'))}\n if 'tag' in self.request.POST:\n kwargs.update({'tag': self.request.POST.get('tag')})\n location += '_tag'\n return redirect(reverse(locatio... | <|body_start_0|>
if 'page' in self.request.POST:
try:
location = 'dashboard'
kwargs = {'page': int(self.request.POST.get('page'))}
if 'tag' in self.request.POST:
kwargs.update({'tag': self.request.POST.get('tag')})
... | This view shows the dashboard of the logged in user. | DashboardView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardView:
"""This view shows the dashboard of the logged in user."""
def post(self, request, *args, **kwargs):
"""Redirect to display a certain page when jumping towards one."""
<|body_0|>
def get_model_queryset(self, list_name, model):
"""Return the five ne... | stack_v2_sparse_classes_75kplus_train_070290 | 25,887 | no_license | [
{
"docstring": "Redirect to display a certain page when jumping towards one.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Return the five newest objects for Accounts and Contacts. Paginate objects for BlogEntry later.",
"name": "get_model_query... | 3 | stack_v2_sparse_classes_30k_train_003143 | Implement the Python class `DashboardView` described below.
Class description:
This view shows the dashboard of the logged in user.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Redirect to display a certain page when jumping towards one.
- def get_model_queryset(self, list_name, model... | Implement the Python class `DashboardView` described below.
Class description:
This view shows the dashboard of the logged in user.
Method signatures and docstrings:
- def post(self, request, *args, **kwargs): Redirect to display a certain page when jumping towards one.
- def get_model_queryset(self, list_name, model... | 0a284e2aae3ca08955215418a76bb70ad9af1f81 | <|skeleton|>
class DashboardView:
"""This view shows the dashboard of the logged in user."""
def post(self, request, *args, **kwargs):
"""Redirect to display a certain page when jumping towards one."""
<|body_0|>
def get_model_queryset(self, list_name, model):
"""Return the five ne... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DashboardView:
"""This view shows the dashboard of the logged in user."""
def post(self, request, *args, **kwargs):
"""Redirect to display a certain page when jumping towards one."""
if 'page' in self.request.POST:
try:
location = 'dashboard'
kw... | the_stack_v2_python_sparse | lily/users/views.py | rmoorman/hellolily | train | 0 |
18d477926e8f35e3a02987c75f165160a062dd7b | [
"RedisObject.__init__(self, id)\nself.fields = fields\nif defaults:\n for key, val in defaults.items():\n self[key] = val",
"if key == 'id':\n return self.id\nif not key in self.fields:\n raise KeyError('{} not found in {}'.format(key, self))\nreturn RedisObject.decode_value(self.fields[key], self... | <|body_start_0|>
RedisObject.__init__(self, id)
self.fields = fields
if defaults:
for key, val in defaults.items():
self[key] = val
<|end_body_0|>
<|body_start_1|>
if key == 'id':
return self.id
if not key in self.fields:
raise... | An equivalent to dict where all keys/values are stored in Redis. | RedisDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisDict:
"""An equivalent to dict where all keys/values are stored in Redis."""
def __init__(self, id=None, fields={}, defaults=None):
"""Create a new RedisObject id: If specified, use this as the redis ID, otherwise generate a random ID. fields: A map of field name to type/constru... | stack_v2_sparse_classes_75kplus_train_070291 | 4,962 | no_license | [
{
"docstring": "Create a new RedisObject id: If specified, use this as the redis ID, otherwise generate a random ID. fields: A map of field name to type/construtor name used to read values from redis. Objects will be written with json.dumps with default = str, so override __str__ for custom objects. This should... | 4 | stack_v2_sparse_classes_30k_train_015493 | Implement the Python class `RedisDict` described below.
Class description:
An equivalent to dict where all keys/values are stored in Redis.
Method signatures and docstrings:
- def __init__(self, id=None, fields={}, defaults=None): Create a new RedisObject id: If specified, use this as the redis ID, otherwise generate... | Implement the Python class `RedisDict` described below.
Class description:
An equivalent to dict where all keys/values are stored in Redis.
Method signatures and docstrings:
- def __init__(self, id=None, fields={}, defaults=None): Create a new RedisObject id: If specified, use this as the redis ID, otherwise generate... | 02f197196c20e9dce7351e6e374567b33d97453f | <|skeleton|>
class RedisDict:
"""An equivalent to dict where all keys/values are stored in Redis."""
def __init__(self, id=None, fields={}, defaults=None):
"""Create a new RedisObject id: If specified, use this as the redis ID, otherwise generate a random ID. fields: A map of field name to type/constru... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RedisDict:
"""An equivalent to dict where all keys/values are stored in Redis."""
def __init__(self, id=None, fields={}, defaults=None):
"""Create a new RedisObject id: If specified, use this as the redis ID, otherwise generate a random ID. fields: A map of field name to type/construtor name used... | the_stack_v2_python_sparse | backend/core/utils.py | clausgf/epaper-server | train | 3 |
c2c14fbf479e1fd26b13d01f6dbcdb700dcadcc1 | [
"self.dataset = dataset\nself.seen_images = seen_images\nself.n = DatasetConfigManager.n(dataset)\nself.outstanding_suggs = []",
"suggs_confidences = [None for i in range(n_suggs)]\nsuggs_conf_colors = [None for i in range(n_suggs)]\nif refresh:\n suggs_images = []\n n_new_rand_exp = n_suggs\nelse:\n sug... | <|body_start_0|>
self.dataset = dataset
self.seen_images = seen_images
self.n = DatasetConfigManager.n(dataset)
self.outstanding_suggs = []
<|end_body_0|>
<|body_start_1|>
suggs_confidences = [None for i in range(n_suggs)]
suggs_conf_colors = [None for i in range(n_suggs... | Randomized explorer covers the exploration side of the exploration-search axis. It utilizes the collection index to find images that are furthest from what was seen by the model previously, such that the user does not linger in any one semantic region of the collection for too long. Keeps state, i.e., will keep returni... | RandomizedExplorer | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedExplorer:
"""Randomized explorer covers the exploration side of the exploration-search axis. It utilizes the collection index to find images that are furthest from what was seen by the model previously, such that the user does not linger in any one semantic region of the collection for ... | stack_v2_sparse_classes_75kplus_train_070292 | 4,564 | permissive | [
{
"docstring": "Constructor. Parameters ---------- dataset : str The name of the dataset. seen_images : aimodel.SeenImages The images seen by the model during the analytic session.",
"name": "__init__",
"signature": "def __init__(self, dataset, seen_images)"
},
{
"docstring": "Suggest random ima... | 2 | stack_v2_sparse_classes_30k_train_000207 | Implement the Python class `RandomizedExplorer` described below.
Class description:
Randomized explorer covers the exploration side of the exploration-search axis. It utilizes the collection index to find images that are furthest from what was seen by the model previously, such that the user does not linger in any one... | Implement the Python class `RandomizedExplorer` described below.
Class description:
Randomized explorer covers the exploration side of the exploration-search axis. It utilizes the collection index to find images that are furthest from what was seen by the model previously, such that the user does not linger in any one... | 606e685aff7097ff0e24272263d0b1fabc79bb1d | <|skeleton|>
class RandomizedExplorer:
"""Randomized explorer covers the exploration side of the exploration-search axis. It utilizes the collection index to find images that are furthest from what was seen by the model previously, such that the user does not linger in any one semantic region of the collection for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RandomizedExplorer:
"""Randomized explorer covers the exploration side of the exploration-search axis. It utilizes the collection index to find images that are furthest from what was seen by the model previously, such that the user does not linger in any one semantic region of the collection for too long. Kee... | the_stack_v2_python_sparse | ii20/aimodel/RandomizedExplorer.py | JanZahalka/ii20 | train | 1 |
79c893f627e0d13b1f25f704bfb18d46ec378a3c | [
"super(ArcBiaffine, self).__init__()\nself.U = nn.Parameter(torch.Tensor(hidden_size, hidden_size), requires_grad=True)\nself.has_bias = bias\nif self.has_bias:\n self.bias = nn.Parameter(torch.Tensor(hidden_size), requires_grad=True)\nelse:\n self.register_parameter('bias', None)\ninitial_parameter(self)",
... | <|body_start_0|>
super(ArcBiaffine, self).__init__()
self.U = nn.Parameter(torch.Tensor(hidden_size, hidden_size), requires_grad=True)
self.has_bias = bias
if self.has_bias:
self.bias = nn.Parameter(torch.Tensor(hidden_size), requires_grad=True)
else:
self... | Biaffine Dependency Parser 的子模块, 用于构建预测边的图 | ArcBiaffine | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArcBiaffine:
"""Biaffine Dependency Parser 的子模块, 用于构建预测边的图"""
def __init__(self, hidden_size, bias=True):
""":param hidden_size: 输入的特征维度 :param bias: 是否使用bias. Default: ``True``"""
<|body_0|>
def forward(self, head, dep):
""":param head: arc-head tensor [batch, l... | stack_v2_sparse_classes_75kplus_train_070293 | 22,013 | permissive | [
{
"docstring": ":param hidden_size: 输入的特征维度 :param bias: 是否使用bias. Default: ``True``",
"name": "__init__",
"signature": "def __init__(self, hidden_size, bias=True)"
},
{
"docstring": ":param head: arc-head tensor [batch, length, hidden] :param dep: arc-dependent tensor [batch, length, hidden] :r... | 2 | stack_v2_sparse_classes_30k_train_025369 | Implement the Python class `ArcBiaffine` described below.
Class description:
Biaffine Dependency Parser 的子模块, 用于构建预测边的图
Method signatures and docstrings:
- def __init__(self, hidden_size, bias=True): :param hidden_size: 输入的特征维度 :param bias: 是否使用bias. Default: ``True``
- def forward(self, head, dep): :param head: arc-... | Implement the Python class `ArcBiaffine` described below.
Class description:
Biaffine Dependency Parser 的子模块, 用于构建预测边的图
Method signatures and docstrings:
- def __init__(self, hidden_size, bias=True): :param hidden_size: 输入的特征维度 :param bias: 是否使用bias. Default: ``True``
- def forward(self, head, dep): :param head: arc-... | dffc7a06cdbff2671a3ca73d2398159d91a4a7db | <|skeleton|>
class ArcBiaffine:
"""Biaffine Dependency Parser 的子模块, 用于构建预测边的图"""
def __init__(self, hidden_size, bias=True):
""":param hidden_size: 输入的特征维度 :param bias: 是否使用bias. Default: ``True``"""
<|body_0|>
def forward(self, head, dep):
""":param head: arc-head tensor [batch, l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArcBiaffine:
"""Biaffine Dependency Parser 的子模块, 用于构建预测边的图"""
def __init__(self, hidden_size, bias=True):
""":param hidden_size: 输入的特征维度 :param bias: 是否使用bias. Default: ``True``"""
super(ArcBiaffine, self).__init__()
self.U = nn.Parameter(torch.Tensor(hidden_size, hidden_size), re... | the_stack_v2_python_sparse | phenobert/utils/fastNLP/models/biaffine_parser.py | TianlabTech/PhenoBERT | train | 2 |
1f6dc68798ea0b388a911f0412c5826afcb6e2bd | [
"language = get_language_from_request(request, check_path=self.is_language_prefix_patterns_used())\nif language not in get_supported_languages():\n language = get_default_language()\ntranslation.activate(language)\nrequest.LANGUAGE_CODE = translation.get_language()",
"language = translation.get_language()\ndef... | <|body_start_0|>
language = get_language_from_request(request, check_path=self.is_language_prefix_patterns_used())
if language not in get_supported_languages():
language = get_default_language()
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()... | This subclasses the original django LocaleMiddleware. It is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course). | TranslationMiddleware | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TranslationMiddleware:
"""This subclasses the original django LocaleMiddleware. It is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if th... | stack_v2_sparse_classes_75kplus_train_070294 | 3,049 | permissive | [
{
"docstring": "Enable the default language if a supported db language can not be resolved.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Override the original method to redirect permanently and facilitate the :func.`translations.urls.translati... | 2 | stack_v2_sparse_classes_30k_train_038074 | Implement the Python class `TranslationMiddleware` described below.
Class description:
This subclasses the original django LocaleMiddleware. It is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated ... | Implement the Python class `TranslationMiddleware` described below.
Class description:
This subclasses the original django LocaleMiddleware. It is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated ... | 974dc167a6b07bb080c4d741ba981518bf1240e5 | <|skeleton|>
class TranslationMiddleware:
"""This subclasses the original django LocaleMiddleware. It is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TranslationMiddleware:
"""This subclasses the original django LocaleMiddleware. It is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is... | the_stack_v2_python_sparse | translations/middleware.py | deep-hack/yawd-translations | train | 1 |
c915c9e18424e0e560deec2401cc3dda57f65b85 | [
"super(TDProxy, self).__init__(mf, proxy, x, mf_constructor, frozen=frozen, **kwargs)\nself.e = {}\nself.xy = {}",
"if k is None:\n k = numpy.arange(len(self._scf.kpts))\nif isinstance(k, int):\n k = [k]\nfor kk in k:\n self.e[kk], self.xy[kk] = self.__kernel__(k=kk)\nreturn (self.e, self.xy)"
] | <|body_start_0|>
super(TDProxy, self).__init__(mf, proxy, x, mf_constructor, frozen=frozen, **kwargs)
self.e = {}
self.xy = {}
<|end_body_0|>
<|body_start_1|>
if k is None:
k = numpy.arange(len(self._scf.kpts))
if isinstance(k, int):
k = [k]
for k... | TDProxy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDProxy:
def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs):
"""Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, on... | stack_v2_sparse_classes_75kplus_train_070295 | 7,401 | permissive | [
{
"docstring": "Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, one of 'hf', 'dft'; x (Iterable): the original k-grid dimensions (numbers of k-points per each ... | 2 | stack_v2_sparse_classes_30k_train_030503 | Implement the Python class `TDProxy` described below.
Class description:
Implement the TDProxy class.
Method signatures and docstrings:
- def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs): Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model... | Implement the Python class `TDProxy` described below.
Class description:
Implement the TDProxy class.
Method signatures and docstrings:
- def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs): Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model... | dd179a802f0a35e72d8522503172f16977c8d974 | <|skeleton|>
class TDProxy:
def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs):
"""Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, on... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TDProxy:
def __init__(self, mf, proxy, x, mf_constructor, frozen=None, **kwargs):
"""Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the base model with a time-reversal invariant k-point grid; proxy: a pyscf proxy with TD response function, one of 'hf', 'df... | the_stack_v2_python_sparse | pyscf/pbc/tdscf/kproxy.py | sunqm/pyscf | train | 80 | |
66c4ccf98064ab0ce30d4bc2dcc48515c1e4d270 | [
"if not root:\n return ''\nstack = [root]\nres = []\nwhile stack:\n node = stack.pop()\n res.append(str(node.val))\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\nreturn ' '.join(res)",
"def insert(root, val):\n if not root:\n return Tr... | <|body_start_0|>
if not root:
return ''
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(str(node.val))
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.le... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_070296 | 1,615 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_023580 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 4509f4b2b83e172e6ccc21ff89fc1204e0c6b3f3 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(str(node.val))
if node.r... | the_stack_v2_python_sparse | Problems/449. Serialize and Deserialize BST.py | aidardarmesh/leetcode | train | 6 | |
bf1399bf356a793ab3f4f860089f60198a828a6a | [
"self.producers = to_eval(columns)\nself.mapping = mapping\nself.default = to_eval(default) if default is not None else None",
"values = evaluate(df=df, producers=self.producers)\nif self.default is not None:\n defaults = evaluate(df=df, producers=self.default)\nelse:\n defaults = values\nif isinstance(defa... | <|body_start_0|>
self.producers = to_eval(columns)
self.mapping = mapping
self.default = to_eval(default) if default is not None else None
<|end_body_0|>
<|body_start_1|>
values = evaluate(df=df, producers=self.producers)
if self.default is not None:
defaults = evalu... | A Lookup table is a mapping function. For a given lookup value the result is the mapped value from a given dictionary if a mapping exists. Otherwise, the returned value is generated from a default value function. If the default value function is not defined then the input value is returned as the result. The aim of hav... | Lookup | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lookup:
"""A Lookup table is a mapping function. For a given lookup value the result is the mapped value from a given dictionary if a mapping exists. Otherwise, the returned value is generated from a default value function. If the default value function is not defined then the input value is retu... | stack_v2_sparse_classes_75kplus_train_070297 | 8,118 | permissive | [
{
"docstring": "Initialize the mapping and the default value function. Parameters ---------- columns: list, tuple, or openclean.function.eval.base.EvalFunction Evaluation function to extract values from data frame rows. This can also be a list or tuple of evaluation functions or a list of column names or index ... | 3 | null | Implement the Python class `Lookup` described below.
Class description:
A Lookup table is a mapping function. For a given lookup value the result is the mapped value from a given dictionary if a mapping exists. Otherwise, the returned value is generated from a default value function. If the default value function is n... | Implement the Python class `Lookup` described below.
Class description:
A Lookup table is a mapping function. For a given lookup value the result is the mapped value from a given dictionary if a mapping exists. Otherwise, the returned value is generated from a default value function. If the default value function is n... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class Lookup:
"""A Lookup table is a mapping function. For a given lookup value the result is the mapped value from a given dictionary if a mapping exists. Otherwise, the returned value is generated from a default value function. If the default value function is not defined then the input value is retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Lookup:
"""A Lookup table is a mapping function. For a given lookup value the result is the mapped value from a given dictionary if a mapping exists. Otherwise, the returned value is generated from a default value function. If the default value function is not defined then the input value is returned as the r... | the_stack_v2_python_sparse | openclean/function/eval/domain.py | Denisfench/openclean-core | train | 0 |
189c92cc154731393ed8d4514167c5344dc782e6 | [
"s = {}\nfor i in range(len(nums)):\n if s.get(nums[i]) == None:\n s[nums[i]] = []\n s[nums[i]].append(i)\nfor key, value in s.items():\n value.sort()\n for i in range(len(value) - 1):\n if value[i + 1] - value[i] <= k:\n return True\nreturn False",
"seen = {}\nfor idx, num in... | <|body_start_0|>
s = {}
for i in range(len(nums)):
if s.get(nums[i]) == None:
s[nums[i]] = []
s[nums[i]].append(i)
for key, value in s.items():
value.sort()
for i in range(len(value) - 1):
if value[i + 1] - value[i] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_070298 | 1,671 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate2",
"signature": "def containsNearbyDuplicate2(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def conta... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rty... | 099bdc80988126b00cc2204e47d8388bdd095dc1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
s = {}
for i in range(len(nums)):
if s.get(nums[i]) == None:
s[nums[i]] = []
s[nums[i]].append(i)
for key, value in s.items():
... | the_stack_v2_python_sparse | 219. Contains Duplicate II.py | liwb27/leetcode | train | 0 | |
1c3f582db2aaeeab66950d998205913d044c9ab6 | [
"super(HelpSchemeHandler, self).__init__(parent)\nself._engine = engine\nself._replies = []",
"if job.requestUrl().scheme() == 'qthelp':\n reply = HelpSchemeReply(job, self._engine)\n reply.closed.connect(self.__replyClosed)\n self._replies.append(reply)\n job.reply(reply.mimeType(), reply)\nelse:\n ... | <|body_start_0|>
super(HelpSchemeHandler, self).__init__(parent)
self._engine = engine
self._replies = []
<|end_body_0|>
<|body_start_1|>
if job.requestUrl().scheme() == 'qthelp':
reply = HelpSchemeReply(job, self._engine)
reply.closed.connect(self.__replyClosed)... | Class implementing a scheme handler for the qthelp: scheme. see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py All credits for this class go to: Detlev Offenbach, the developer of The Eric Python IDE (https://eric-ide.python-projects.org) | HelpSchemeHandler | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpSchemeHandler:
"""Class implementing a scheme handler for the qthelp: scheme. see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py All credits for this class go to: Detlev Offenbach, the developer of The Eric Python IDE (https://eric-ide.python-projects.org)"""
... | stack_v2_sparse_classes_75kplus_train_070299 | 15,332 | permissive | [
{
"docstring": "Constructor :param engine: reference to the help engine :type engine: QHelpEngine :param parent: reference to the parent object :type parent: QObject",
"name": "__init__",
"signature": "def __init__(self, engine, parent=None)"
},
{
"docstring": "Public method handling the URL req... | 3 | null | Implement the Python class `HelpSchemeHandler` described below.
Class description:
Class implementing a scheme handler for the qthelp: scheme. see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py All credits for this class go to: Detlev Offenbach, the developer of The Eric Python IDE (ht... | Implement the Python class `HelpSchemeHandler` described below.
Class description:
Class implementing a scheme handler for the qthelp: scheme. see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py All credits for this class go to: Detlev Offenbach, the developer of The Eric Python IDE (ht... | f6c86cc95218216cbd0f548b508d0c5fde11520e | <|skeleton|>
class HelpSchemeHandler:
"""Class implementing a scheme handler for the qthelp: scheme. see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py All credits for this class go to: Detlev Offenbach, the developer of The Eric Python IDE (https://eric-ide.python-projects.org)"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HelpSchemeHandler:
"""Class implementing a scheme handler for the qthelp: scheme. see: https://fossies.org/linux/eric6/eric/WebBrowser/Network/QtHelpSchemeHandler.py All credits for this class go to: Detlev Offenbach, the developer of The Eric Python IDE (https://eric-ide.python-projects.org)"""
def __in... | the_stack_v2_python_sparse | oPB/gui/helpviewer.py | pandel/opsiPackageBuilder | train | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.