blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b3dde570c48f3fe2347b1d45ad0b8384561bd7e | [
"AxisFormat.__init__(self, 'patches')\nself._axes['energy'] = 0\nself._axes['energyRough'] = 1\nself._axes['amplitude'] = 2\nself._axes['eta'] = 3\nself._axes['phi'] = 4\nself._axes['isMain'] = 5",
"newobj = AxisFormatTriggerPatches()\nnewobj._Copy(self)\nreturn newobj",
"newobj = AxisFormatTriggerPatches()\nne... | <|body_start_0|>
AxisFormat.__init__(self, 'patches')
self._axes['energy'] = 0
self._axes['energyRough'] = 1
self._axes['amplitude'] = 2
self._axes['eta'] = 3
self._axes['phi'] = 4
self._axes['isMain'] = 5
<|end_body_0|>
<|body_start_1|>
newobj = AxisForm... | Axis definition used in the trigger patch THnSparse | AxisFormatTriggerPatches | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisFormatTriggerPatches:
"""Axis definition used in the trigger patch THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __copy__(self):
"""Shallow copy constructor"""
<|body_1|>
def __deepcopy__(self, memo):
"""Deep copy cons... | stack_v2_sparse_classes_36k_train_022000 | 3,251 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Shallow copy constructor",
"name": "__copy__",
"signature": "def __copy__(self)"
},
{
"docstring": "Deep copy constructor",
"name": "__deepcopy__",
"signature": "def __d... | 3 | stack_v2_sparse_classes_30k_train_005655 | Implement the Python class `AxisFormatTriggerPatches` described below.
Class description:
Axis definition used in the trigger patch THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __copy__(self): Shallow copy constructor
- def __deepcopy__(self, memo): Deep copy constructor | Implement the Python class `AxisFormatTriggerPatches` described below.
Class description:
Axis definition used in the trigger patch THnSparse
Method signatures and docstrings:
- def __init__(self): Constructor
- def __copy__(self): Shallow copy constructor
- def __deepcopy__(self, memo): Deep copy constructor
<|skel... | 5df28b2b415e78e81273b0d9bf5c1b99feda3348 | <|skeleton|>
class AxisFormatTriggerPatches:
"""Axis definition used in the trigger patch THnSparse"""
def __init__(self):
"""Constructor"""
<|body_0|>
def __copy__(self):
"""Shallow copy constructor"""
<|body_1|>
def __deepcopy__(self, memo):
"""Deep copy cons... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisFormatTriggerPatches:
"""Axis definition used in the trigger patch THnSparse"""
def __init__(self):
"""Constructor"""
AxisFormat.__init__(self, 'patches')
self._axes['energy'] = 0
self._axes['energyRough'] = 1
self._axes['amplitude'] = 2
self._axes['eta... | the_stack_v2_python_sparse | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/TriggerPatchTHnSparse.py | alisw/AliPhysics | train | 129 |
0c8e418d0dcbcd8a68827bfc0b7ed2dedd385c47 | [
"keys = list(self.keys())\nmatching_keys = [x for x in keys if re.match(x, key)]\nif len(matching_keys) == 0:\n raise KeyError('No matching keys were found!')\nelif len(matching_keys) > 1:\n raise ValueError('Multiple keys match!')\nelse:\n return super(RegexKeyDict, self).__getitem__(matching_keys[0])",
... | <|body_start_0|>
keys = list(self.keys())
matching_keys = [x for x in keys if re.match(x, key)]
if len(matching_keys) == 0:
raise KeyError('No matching keys were found!')
elif len(matching_keys) > 1:
raise ValueError('Multiple keys match!')
else:
... | Dictionary where key matching applies regular expressions in addition to exact matches | RegexKeyDict | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegexKeyDict:
"""Dictionary where key matching applies regular expressions in addition to exact matches"""
def __getitem__(self, key):
"""Lookup key in dictionary by finding exactly one dict key which, by regex, matches the input argument 'key'"""
<|body_0|>
def __contai... | stack_v2_sparse_classes_36k_train_022001 | 43,699 | permissive | [
{
"docstring": "Lookup key in dictionary by finding exactly one dict key which, by regex, matches the input argument 'key'",
"name": "__getitem__",
"signature": "def __getitem__(self, key)"
},
{
"docstring": "Determine if a key is in the dictionary using regular expression matching",
"name":... | 2 | null | Implement the Python class `RegexKeyDict` described below.
Class description:
Dictionary where key matching applies regular expressions in addition to exact matches
Method signatures and docstrings:
- def __getitem__(self, key): Lookup key in dictionary by finding exactly one dict key which, by regex, matches the inp... | Implement the Python class `RegexKeyDict` described below.
Class description:
Dictionary where key matching applies regular expressions in addition to exact matches
Method signatures and docstrings:
- def __getitem__(self, key): Lookup key in dictionary by finding exactly one dict key which, by regex, matches the inp... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class RegexKeyDict:
"""Dictionary where key matching applies regular expressions in addition to exact matches"""
def __getitem__(self, key):
"""Lookup key in dictionary by finding exactly one dict key which, by regex, matches the input argument 'key'"""
<|body_0|>
def __contai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegexKeyDict:
"""Dictionary where key matching applies regular expressions in addition to exact matches"""
def __getitem__(self, key):
"""Lookup key in dictionary by finding exactly one dict key which, by regex, matches the input argument 'key'"""
keys = list(self.keys())
matching... | the_stack_v2_python_sparse | riglib/bmi/clda.py | carmenalab/brain-python-interface | train | 9 |
8bb053396bfc84bed1b2e1f9f358852fc1435138 | [
"super(LabelSmoothingLoss, self).__init__()\nself.confidence = 1.0 - smoothing\nself.smoothing = smoothing\nself.dim = dim",
"with torch.no_grad():\n true_dist = torch.zeros_like(pred)\n true_dist.fill_(self.smoothing / (pred.shape[-1] - 1))\n true_dist.scatter_(1, target.data.unsqueeze(1), self.confiden... | <|body_start_0|>
super(LabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.dim = dim
<|end_body_0|>
<|body_start_1|>
with torch.no_grad():
true_dist = torch.zeros_like(pred)
true_dist.fill_(self.smoothing... | Create a NLL loss but by employing label smoothing. Particularly useful when the data is not 100% reliable, and there is a probability that other labels can actually be the real one. Credits to github users @ https://github.com/pytorch/pytorch/issues/7455 | LabelSmoothingLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelSmoothingLoss:
"""Create a NLL loss but by employing label smoothing. Particularly useful when the data is not 100% reliable, and there is a probability that other labels can actually be the real one. Credits to github users @ https://github.com/pytorch/pytorch/issues/7455"""
def __init... | stack_v2_sparse_classes_36k_train_022002 | 17,400 | permissive | [
{
"docstring": "Create the label smoothing loss :param smoothing: smooting probability (0 for no smoothing, 1 for full smoothing) :param dim: dimension to apply the loss sum",
"name": "__init__",
"signature": "def __init__(self, smoothing=0.0, dim=-1)"
},
{
"docstring": "Compute the forward pass... | 2 | stack_v2_sparse_classes_30k_train_008737 | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Create a NLL loss but by employing label smoothing. Particularly useful when the data is not 100% reliable, and there is a probability that other labels can actually be the real one. Credits to github users @ https://github.com/pytorch... | Implement the Python class `LabelSmoothingLoss` described below.
Class description:
Create a NLL loss but by employing label smoothing. Particularly useful when the data is not 100% reliable, and there is a probability that other labels can actually be the real one. Credits to github users @ https://github.com/pytorch... | 1b9fbe6c89c74dc706fd8d3b11ea08977ba2c1d3 | <|skeleton|>
class LabelSmoothingLoss:
"""Create a NLL loss but by employing label smoothing. Particularly useful when the data is not 100% reliable, and there is a probability that other labels can actually be the real one. Credits to github users @ https://github.com/pytorch/pytorch/issues/7455"""
def __init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelSmoothingLoss:
"""Create a NLL loss but by employing label smoothing. Particularly useful when the data is not 100% reliable, and there is a probability that other labels can actually be the real one. Credits to github users @ https://github.com/pytorch/pytorch/issues/7455"""
def __init__(self, smoo... | the_stack_v2_python_sparse | models/interaction_modules/train_aux.py | pedro-mgb/pedestrian-arc-lstm-smf | train | 4 |
a068fb1ac28fa5b542dd6751bb2ed76448772d36 | [
"try:\n return struct.unpack('!I', value)[0]\nexcept:\n raise excep.UpdateMessageError(sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data=value)",
"try:\n return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) + struct.pack('!B', 4) + struct.pack('!I', value)\nexcept Exception:\n raise excep.Upd... | <|body_start_0|>
try:
return struct.unpack('!I', value)[0]
except:
raise excep.UpdateMessageError(sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data=value)
<|end_body_0|>
<|body_start_1|>
try:
return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) + str... | LOCAL_PREF is a well-known attribute that is a four-octet unsigned integer. A BGP speaker uses it to inform its other internal peers of the advertising speaker's degree of preference for an advertised route. | LocalPreference | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalPreference:
"""LOCAL_PREF is a well-known attribute that is a four-octet unsigned integer. A BGP speaker uses it to inform its other internal peers of the advertising speaker's degree of preference for an advertised route."""
def parse(cls, value):
"""parse bgp local preference ... | stack_v2_sparse_classes_36k_train_022003 | 2,074 | permissive | [
{
"docstring": "parse bgp local preference attribute :param value: raw binary value",
"name": "parse",
"signature": "def parse(cls, value)"
},
{
"docstring": "encode bgp local preference attribute :param value: interger value",
"name": "construct",
"signature": "def construct(cls, value)... | 2 | null | Implement the Python class `LocalPreference` described below.
Class description:
LOCAL_PREF is a well-known attribute that is a four-octet unsigned integer. A BGP speaker uses it to inform its other internal peers of the advertising speaker's degree of preference for an advertised route.
Method signatures and docstri... | Implement the Python class `LocalPreference` described below.
Class description:
LOCAL_PREF is a well-known attribute that is a four-octet unsigned integer. A BGP speaker uses it to inform its other internal peers of the advertising speaker's degree of preference for an advertised route.
Method signatures and docstri... | 24cbb732d4380ab54d000ac08690e521c60d4f2a | <|skeleton|>
class LocalPreference:
"""LOCAL_PREF is a well-known attribute that is a four-octet unsigned integer. A BGP speaker uses it to inform its other internal peers of the advertising speaker's degree of preference for an advertised route."""
def parse(cls, value):
"""parse bgp local preference ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalPreference:
"""LOCAL_PREF is a well-known attribute that is a four-octet unsigned integer. A BGP speaker uses it to inform its other internal peers of the advertising speaker's degree of preference for an advertised route."""
def parse(cls, value):
"""parse bgp local preference attribute :pa... | the_stack_v2_python_sparse | yabgp/message/attribute/localpref.py | smartbgp/yabgp | train | 227 |
9443fc0f611068feb05997e1b0b320dc0460cad0 | [
"self.data = Counter()\nself.time_record = deque()\nself.count = 0",
"self.data[timestamp] += 1\nself.count += 1\nif not self.time_record or timestamp != self.time_record[-1]:\n self.time_record.append(timestamp)",
"while self.time_record and timestamp - 300 >= self.time_record[0]:\n expired = self.time_r... | <|body_start_0|>
self.data = Counter()
self.time_record = deque()
self.count = 0
<|end_body_0|>
<|body_start_1|>
self.data[timestamp] += 1
self.count += 1
if not self.time_record or timestamp != self.time_record[-1]:
self.time_record.append(timestamp)
<|end_b... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k_train_022004 | 1,121 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | null | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 3390a0ca4eceff72c69721bdc425a3099670faff | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.data = Counter()
self.time_record = deque()
self.count = 0
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
... | the_stack_v2_python_sparse | LeetCode/Problems/Python/362. Design Hit Counter.py | yukai-chiu/CodingPractice | train | 0 | |
bb42c359e732f40fd24c107c3da27f0de4e798d2 | [
"if is_horizontal:\n super(Composition2x1, self).__init__(2 * width, height)\nelse:\n super(Composition2x1, self).__init__(width, 2 * height)\nself.single_w = width\nself.single_h = height\nself.is_horizontal = is_horizontal\nself.empty = np.zeros((height, width, 3), dtype=np.uint8)\nself.left = left\nself.ri... | <|body_start_0|>
if is_horizontal:
super(Composition2x1, self).__init__(2 * width, height)
else:
super(Composition2x1, self).__init__(width, 2 * height)
self.single_w = width
self.single_h = height
self.is_horizontal = is_horizontal
self.empty = np... | Display two keras_tf next to each other. | Composition2x1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Composition2x1:
"""Display two keras_tf next to each other."""
def __init__(self, width, height, left, right, is_horizontal: bool=True):
"""Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final composition. ... | stack_v2_sparse_classes_36k_train_022005 | 1,653 | no_license | [
{
"docstring": "Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final composition. :param left: Reference to the function which gets the frame to be displayed on left. :param right: Reference to the function which gets the frame to be ... | 2 | stack_v2_sparse_classes_30k_train_006322 | Implement the Python class `Composition2x1` described below.
Class description:
Display two keras_tf next to each other.
Method signatures and docstrings:
- def __init__(self, width, height, left, right, is_horizontal: bool=True): Initialize the step with all relevant attributes. :param width: Width of the final comp... | Implement the Python class `Composition2x1` described below.
Class description:
Display two keras_tf next to each other.
Method signatures and docstrings:
- def __init__(self, width, height, left, right, is_horizontal: bool=True): Initialize the step with all relevant attributes. :param width: Width of the final comp... | 8316bcc43805ba3cdc196b68b14f921f81610337 | <|skeleton|>
class Composition2x1:
"""Display two keras_tf next to each other."""
def __init__(self, width, height, left, right, is_horizontal: bool=True):
"""Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final composition. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Composition2x1:
"""Display two keras_tf next to each other."""
def __init__(self, width, height, left, right, is_horizontal: bool=True):
"""Initialize the step with all relevant attributes. :param width: Width of the final composition. :param height: Height of the final composition. :param left: ... | the_stack_v2_python_sparse | video/pipeline/compositions/composition_2x1.py | breitmuuufrosch/OpenCvPipeline | train | 0 |
e140c67ad790e06666b6df1d6144c98355d38db4 | [
"ps = []\nfor p in (p1, p2, p3, p4):\n if not p:\n return False\n ps.append(p)\nps.sort()\nl01 = self.get_distance(ps[0], ps[1])\nl02 = self.get_distance(ps[0], ps[2])\nl13 = self.get_distance(ps[1], ps[3])\nl23 = self.get_distance(ps[2], ps[3])\nl03 = self.get_distance(ps[0], ps[3])\nl12 = self.get_di... | <|body_start_0|>
ps = []
for p in (p1, p2, p3, p4):
if not p:
return False
ps.append(p)
ps.sort()
l01 = self.get_distance(ps[0], ps[1])
l02 = self.get_distance(ps[0], ps[2])
l13 = self.get_distance(ps[1], ps[3])
l23 = self.g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validSquare(self, p1, p2, p3, p4):
""":type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool"""
<|body_0|>
def get_distance(self, a, b):
"""find the size of 'ab'"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_022006 | 958 | no_license | [
{
"docstring": ":type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool",
"name": "validSquare",
"signature": "def validSquare(self, p1, p2, p3, p4)"
},
{
"docstring": "find the size of 'ab'",
"name": "get_distance",
"signature": "def get_distance(sel... | 2 | stack_v2_sparse_classes_30k_train_002128 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validSquare(self, p1, p2, p3, p4): :type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool
- def get_distance(self, a, b): find the size ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validSquare(self, p1, p2, p3, p4): :type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool
- def get_distance(self, a, b): find the size ... | 91892fd64281d96b8a9d5c0d57b938c314ae71be | <|skeleton|>
class Solution:
def validSquare(self, p1, p2, p3, p4):
""":type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool"""
<|body_0|>
def get_distance(self, a, b):
"""find the size of 'ab'"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validSquare(self, p1, p2, p3, p4):
""":type p1: List[int] :type p2: List[int] :type p3: List[int] :type p4: List[int] :rtype: bool"""
ps = []
for p in (p1, p2, p3, p4):
if not p:
return False
ps.append(p)
ps.sort()
l... | the_stack_v2_python_sparse | leetcode/593_valid_square.py | jaychsu/algorithm | train | 143 | |
af677be81b754a046c025331bc3aef98d6281b62 | [
"if solution_name == 'src':\n return ''\nelse:\n root_solution_name = 'src/'\n assert solution_name.startswith(root_solution_name)\n return solution_name[len(root_solution_name):]",
"solution_name = solution_name.replace('\\\\', '/')\nrepo_dir = self._calculate_repo_dir(solution_name)\ncwd = self.m.pa... | <|body_start_0|>
if solution_name == 'src':
return ''
else:
root_solution_name = 'src/'
assert solution_name.startswith(root_solution_name)
return solution_name[len(root_solution_name):]
<|end_body_0|>
<|body_start_1|>
solution_name = solution_nam... | FinditApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FinditApi:
def _calculate_repo_dir(self, solution_name):
"""Returns the relative path of the solution checkout to the root one."""
<|body_0|>
def files_changed_by_revision(self, revision, solution_name='src'):
"""Returns the files changed by the given revision. Args:... | stack_v2_sparse_classes_36k_train_022007 | 4,481 | permissive | [
{
"docstring": "Returns the relative path of the solution checkout to the root one.",
"name": "_calculate_repo_dir",
"signature": "def _calculate_repo_dir(self, solution_name)"
},
{
"docstring": "Returns the files changed by the given revision. Args: revision (str): the git hash of a commit. sol... | 4 | null | Implement the Python class `FinditApi` described below.
Class description:
Implement the FinditApi class.
Method signatures and docstrings:
- def _calculate_repo_dir(self, solution_name): Returns the relative path of the solution checkout to the root one.
- def files_changed_by_revision(self, revision, solution_name=... | Implement the Python class `FinditApi` described below.
Class description:
Implement the FinditApi class.
Method signatures and docstrings:
- def _calculate_repo_dir(self, solution_name): Returns the relative path of the solution checkout to the root one.
- def files_changed_by_revision(self, revision, solution_name=... | 4e95fd33456e552bfaf7d94f7d04b19273d1c534 | <|skeleton|>
class FinditApi:
def _calculate_repo_dir(self, solution_name):
"""Returns the relative path of the solution checkout to the root one."""
<|body_0|>
def files_changed_by_revision(self, revision, solution_name='src'):
"""Returns the files changed by the given revision. Args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FinditApi:
def _calculate_repo_dir(self, solution_name):
"""Returns the relative path of the solution checkout to the root one."""
if solution_name == 'src':
return ''
else:
root_solution_name = 'src/'
assert solution_name.startswith(root_solution_na... | the_stack_v2_python_sparse | scripts/slave/recipe_modules/findit/api.py | eunchong/build | train | 0 | |
d2df443634d4e0b201464077c6d46e831889bd5c | [
"graph = defaultdict(list)\nfor k, v in edges:\n graph[k].append(v)\n graph[v].append(k)\nvisited = set()\nres = 0\nfor i in range(n):\n if i in visited:\n continue\n else:\n res += 1\n visited.add(i)\n self.bfs(visited, i, graph)\nreturn res",
"queue = deque([root])\nwhile... | <|body_start_0|>
graph = defaultdict(list)
for k, v in edges:
graph[k].append(v)
graph[v].append(k)
visited = set()
res = 0
for i in range(n):
if i in visited:
continue
else:
res += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
"""用adjacent list来表示图,无向图,所以key是一个节点,value是个list,连接它的所有节点 一共有n个节点,从0开始,如果遇到就放到visited里,表示这一批的所有节点。 下一批(next for loop)再遇到就略过,否则是另一批(another component) 的节点"""
<|body_0|>
def bfs(self, visited, root, gr... | stack_v2_sparse_classes_36k_train_022008 | 1,706 | no_license | [
{
"docstring": "用adjacent list来表示图,无向图,所以key是一个节点,value是个list,连接它的所有节点 一共有n个节点,从0开始,如果遇到就放到visited里,表示这一批的所有节点。 下一批(next for loop)再遇到就略过,否则是另一批(another component) 的节点",
"name": "countComponents",
"signature": "def countComponents(self, n: int, edges: List[List[int]]) -> int"
},
{
"docstring": "纯... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countComponents(self, n: int, edges: List[List[int]]) -> int: 用adjacent list来表示图,无向图,所以key是一个节点,value是个list,连接它的所有节点 一共有n个节点,从0开始,如果遇到就放到visited里,表示这一批的所有节点。 下一批(next for loo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countComponents(self, n: int, edges: List[List[int]]) -> int: 用adjacent list来表示图,无向图,所以key是一个节点,value是个list,连接它的所有节点 一共有n个节点,从0开始,如果遇到就放到visited里,表示这一批的所有节点。 下一批(next for loo... | 034efcefe9940267abcf4c9cab655b2344e3e901 | <|skeleton|>
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
"""用adjacent list来表示图,无向图,所以key是一个节点,value是个list,连接它的所有节点 一共有n个节点,从0开始,如果遇到就放到visited里,表示这一批的所有节点。 下一批(next for loop)再遇到就略过,否则是另一批(another component) 的节点"""
<|body_0|>
def bfs(self, visited, root, gr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
"""用adjacent list来表示图,无向图,所以key是一个节点,value是个list,连接它的所有节点 一共有n个节点,从0开始,如果遇到就放到visited里,表示这一批的所有节点。 下一批(next for loop)再遇到就略过,否则是另一批(another component) 的节点"""
graph = defaultdict(list)
for k, v in edges:
... | the_stack_v2_python_sparse | 323_number_of_connected_components_in_an_undirected_graph.py | HongsenHe/algo2018 | train | 0 | |
af50065004b0f65f1417d3839533b261a29f9b2a | [
"self.queue = []\nself.front = None\nself.rare = None\nself.max_size = 5",
"if self.rare == self.max_size - 1:\n print('Overflow')\nelse:\n self.queue.append(item)\n if self.front == None:\n self.front = 0\n self.rare = 0\n else:\n self.rare += 1",
"if self.front == None:\n p... | <|body_start_0|>
self.queue = []
self.front = None
self.rare = None
self.max_size = 5
<|end_body_0|>
<|body_start_1|>
if self.rare == self.max_size - 1:
print('Overflow')
else:
self.queue.append(item)
if self.front == None:
... | This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position. | Queue | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queue:
"""This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position."""
def __init__(self):
"""Constructor function. Argument: self -- represents the object of the class."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_022009 | 2,051 | no_license | [
{
"docstring": "Constructor function. Argument: self -- represents the object of the class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This function will add the item to the queue. Argument: self -- represents the object of the class. item -- integer value.",
... | 4 | stack_v2_sparse_classes_30k_test_000470 | Implement the Python class `Queue` described below.
Class description:
This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position.
Method signatures and docstrings:
- def __init__(self): Constructor function. Argument: self -- represen... | Implement the Python class `Queue` described below.
Class description:
This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position.
Method signatures and docstrings:
- def __init__(self): Constructor function. Argument: self -- represen... | 6870426104aef417086788221dad29e887ddfe3f | <|skeleton|>
class Queue:
"""This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position."""
def __init__(self):
"""Constructor function. Argument: self -- represents the object of the class."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queue:
"""This class contains functions for queue data structure implementation. Enqueue: To add at rare position. Dequeue: To remove at front position."""
def __init__(self):
"""Constructor function. Argument: self -- represents the object of the class."""
self.queue = []
self.fr... | the_stack_v2_python_sparse | Data Structure/03. Queue/01. Queue Implementation/py_code.py | Slothfulwave612/Coding-Problems | train | 5 |
12d13c4e8ebb52e213bfdf1f2afb672c0966b735 | [
"endpoint = cls.list_api_endpoint\nif user_id:\n endpoint += f'?user_id={user_id}'\nelif created_after:\n endpoint += f'?created_after={created_after.isoformat()}'\nresponse_json = cls.get(endpoint)\nmessages = [Message(**s) for s in response_json['results']]\nreturn messages",
"response_json = cls.get(cls.... | <|body_start_0|>
endpoint = cls.list_api_endpoint
if user_id:
endpoint += f'?user_id={user_id}'
elif created_after:
endpoint += f'?created_after={created_after.isoformat()}'
response_json = cls.get(endpoint)
messages = [Message(**s) for s in response_json[... | Messages | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Messages:
def list(cls, user_id: Optional[str]=None, created_after: Optional[datetime]=None) -> List[Message]:
"""Get messages between you and another user or your messages with all users :param user_id: Another user ID, must be provided if no created_after date is provided :param create... | stack_v2_sparse_classes_36k_train_022010 | 2,139 | permissive | [
{
"docstring": "Get messages between you and another user or your messages with all users :param user_id: Another user ID, must be provided if no created_after date is provided :param created_after: Only fetch messages created after timestamp. Must be provided if no user_id is provided. You can only fetch up to... | 3 | stack_v2_sparse_classes_30k_train_013643 | Implement the Python class `Messages` described below.
Class description:
Implement the Messages class.
Method signatures and docstrings:
- def list(cls, user_id: Optional[str]=None, created_after: Optional[datetime]=None) -> List[Message]: Get messages between you and another user or your messages with all users :pa... | Implement the Python class `Messages` described below.
Class description:
Implement the Messages class.
Method signatures and docstrings:
- def list(cls, user_id: Optional[str]=None, created_after: Optional[datetime]=None) -> List[Message]: Get messages between you and another user or your messages with all users :pa... | 1f540f9bd866d5fd625be4a4d61ad6bce564f1ed | <|skeleton|>
class Messages:
def list(cls, user_id: Optional[str]=None, created_after: Optional[datetime]=None) -> List[Message]:
"""Get messages between you and another user or your messages with all users :param user_id: Another user ID, must be provided if no created_after date is provided :param create... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Messages:
def list(cls, user_id: Optional[str]=None, created_after: Optional[datetime]=None) -> List[Message]:
"""Get messages between you and another user or your messages with all users :param user_id: Another user ID, must be provided if no created_after date is provided :param created_after: Only ... | the_stack_v2_python_sparse | mephisto/abstractions/providers/prolific/api/messages.py | facebookresearch/Mephisto | train | 281 | |
fa230fc91e77b64b1f2ea22ea48a36ccb04405de | [
"self.before = before\nself.after = after\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nbefore = idfy_rest_client.models.dialog_before.DialogBefore.from_dictionary(dictionary.get('before')) if dictionary.get('before') else None\nafter = idfy_rest_client.models.dia... | <|body_start_0|>
self.before = before
self.after = after
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
before = idfy_rest_client.models.dialog_before.DialogBefore.from_dictionary(dictionary.get('... | Implementation of the 'Dialogs' model. TODO: type model description here. Attributes: before (DialogBefore): Will be presented before the document is signed after (Dialog): Will be presented after the document is signed | Dialogs | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialogs:
"""Implementation of the 'Dialogs' model. TODO: type model description here. Attributes: before (DialogBefore): Will be presented before the document is signed after (Dialog): Will be presented after the document is signed"""
def __init__(self, before=None, after=None, additional_pr... | stack_v2_sparse_classes_36k_train_022011 | 2,312 | permissive | [
{
"docstring": "Constructor for the Dialogs class",
"name": "__init__",
"signature": "def __init__(self, before=None, after=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the ob... | 2 | null | Implement the Python class `Dialogs` described below.
Class description:
Implementation of the 'Dialogs' model. TODO: type model description here. Attributes: before (DialogBefore): Will be presented before the document is signed after (Dialog): Will be presented after the document is signed
Method signatures and doc... | Implement the Python class `Dialogs` described below.
Class description:
Implementation of the 'Dialogs' model. TODO: type model description here. Attributes: before (DialogBefore): Will be presented before the document is signed after (Dialog): Will be presented after the document is signed
Method signatures and doc... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class Dialogs:
"""Implementation of the 'Dialogs' model. TODO: type model description here. Attributes: before (DialogBefore): Will be presented before the document is signed after (Dialog): Will be presented after the document is signed"""
def __init__(self, before=None, after=None, additional_pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dialogs:
"""Implementation of the 'Dialogs' model. TODO: type model description here. Attributes: before (DialogBefore): Will be presented before the document is signed after (Dialog): Will be presented after the document is signed"""
def __init__(self, before=None, after=None, additional_properties={}):... | the_stack_v2_python_sparse | idfy_rest_client/models/dialogs.py | dealflowteam/Idfy | train | 0 |
d5d1e963093b4086cf4517ac939fecbd29695909 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('alanbur_aquan_erj826_jcaluag', 'alanbur_aquan_erj826_jcaluag')\ncollection = repo.alanbur_aquan_erj826_jcaluag.SFaccidents\nrepo.dropCollection('alanbur_aquan_erj826_jcaluag.timeAggregateSF')\nrepo.creat... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('alanbur_aquan_erj826_jcaluag', 'alanbur_aquan_erj826_jcaluag')
collection = repo.alanbur_aquan_erj826_jcaluag.SFaccidents
repo.dropCollection('ala... | timeAggregateSF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class timeAggregateSF:
def execute(trial=False):
"""Retrieve crime incident report information from Boston."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this ... | stack_v2_sparse_classes_36k_train_022012 | 3,791 | no_license | [
{
"docstring": "Retrieve crime incident report information from Boston.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing th... | 2 | null | Implement the Python class `timeAggregateSF` described below.
Class description:
Implement the timeAggregateSF class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve crime incident report information from Boston.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Cre... | Implement the Python class `timeAggregateSF` described below.
Class description:
Implement the timeAggregateSF class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve crime incident report information from Boston.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Cre... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class timeAggregateSF:
def execute(trial=False):
"""Retrieve crime incident report information from Boston."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class timeAggregateSF:
def execute(trial=False):
"""Retrieve crime incident report information from Boston."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('alanbur_aquan_erj826_jcaluag', 'alanbur_aquan_erj826_jca... | the_stack_v2_python_sparse | alanbur_aquan_erj826_jcaluag/timeAggregateSF.py | ROODAY/course-2017-fal-proj | train | 3 | |
3be8a9dbffd8a8e26544b2e2b5a879cb69c0c575 | [
"pygame.init()\nself.screen = pygame.display.set_mode((1200, 800))\npygame.display.set_caption('Sideways Hero')\nself.ship = Ship(self)\nself.aliens = pygame.sprite.Group()\nfor alien_num in range(30):\n new_alien = AlienShip(self)\n self.aliens.add(new_alien)",
"while True:\n for event in pygame.event.g... | <|body_start_0|>
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Sideways Hero')
self.ship = Ship(self)
self.aliens = pygame.sprite.Group()
for alien_num in range(30):
new_alien = AlienShip(self)
self.al... | Overall class to manage game assets and behavior. | SidewaysHero | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SidewaysHero:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
<|body_0|>
def run_game(self):
"""Start the main loop for the game."""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_022013 | 1,784 | permissive | [
{
"docstring": "Initialize the game, and create game resources.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Start the main loop for the game.",
"name": "run_game",
"signature": "def run_game(self)"
}
] | 2 | null | Implement the Python class `SidewaysHero` described below.
Class description:
Overall class to manage game assets and behavior.
Method signatures and docstrings:
- def __init__(self): Initialize the game, and create game resources.
- def run_game(self): Start the main loop for the game. | Implement the Python class `SidewaysHero` described below.
Class description:
Overall class to manage game assets and behavior.
Method signatures and docstrings:
- def __init__(self): Initialize the game, and create game resources.
- def run_game(self): Start the main loop for the game.
<|skeleton|>
class SidewaysHe... | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | <|skeleton|>
class SidewaysHero:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
<|body_0|>
def run_game(self):
"""Start the main loop for the game."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SidewaysHero:
"""Overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption('Sideways Hero')
self.ship = ... | the_stack_v2_python_sparse | MY_REPOS/Lambda-Resource-Static-Assets/2-resources/BLOG/Python/python_teaching_fall_2018-master/sideways_hero_nb_example/sh_game.py | bgoonz/UsefulResourceRepo2.0 | train | 10 |
a02aae8b0ad9829c94253ecbd7d633c80ff9b73a | [
"super().__init__(config)\nself.in_proj_weight = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.weight, wav2vec2_layer.attention.k_proj.weight, wav2vec2_layer.attention.v_proj.weight]))\nself.in_proj_bias = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.bias, wav2vec2_layer.attention.k_proj.bias, ... | <|body_start_0|>
super().__init__(config)
self.in_proj_weight = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.weight, wav2vec2_layer.attention.k_proj.weight, wav2vec2_layer.attention.v_proj.weight]))
self.in_proj_bias = nn.Parameter(torch.cat([wav2vec2_layer.attention.q_proj.bias, wav2... | Wav2Vec2EncoderLayerBetterTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wav2Vec2EncoderLayerBetterTransformer:
def __init__(self, wav2vec2_layer, config):
"""A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be ret... | stack_v2_sparse_classes_36k_train_022014 | 43,670 | no_license | [
{
"docstring": "A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be retrieved.",
"name": "__init__",
"signature": "def __init__(self, wav2vec2_layer, config)... | 2 | stack_v2_sparse_classes_30k_train_016919 | Implement the Python class `Wav2Vec2EncoderLayerBetterTransformer` described below.
Class description:
Implement the Wav2Vec2EncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, wav2vec2_layer, config): A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` i... | Implement the Python class `Wav2Vec2EncoderLayerBetterTransformer` described below.
Class description:
Implement the Wav2Vec2EncoderLayerBetterTransformer class.
Method signatures and docstrings:
- def __init__(self, wav2vec2_layer, config): A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` i... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Wav2Vec2EncoderLayerBetterTransformer:
def __init__(self, wav2vec2_layer, config):
"""A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wav2Vec2EncoderLayerBetterTransformer:
def __init__(self, wav2vec2_layer, config):
"""A simple conversion of the Wav2Vec2EncoderLayer to its `BetterTransformer` implementation. Args: wav2vec2_layer (`torch.nn.Module`): The original `Wav2Vec2EncoderLayer` where the weights needs to be retrieved."""
... | the_stack_v2_python_sparse | generated/test_huggingface_optimum.py | jansel/pytorch-jit-paritybench | train | 35 | |
27804157bd4866469b89c0294fee607aa4b4d174 | [
"polygons = [PolyGon(pts=[(50, 40), (152, 34), (103, 90), (40, 60)], cls_idx=1), PolyGon(pts=[(0, 0), (10, 5), (4, 8)], cls_idx=2)]\nfeat = Segmentation()\nencoded, parsed = encode_decode(feat=feat, poly_or_rle=polygons, mask_shape=(200, 200))\nassert encoded.keys() == feat.encoded_features.keys()\nparsed = parsed[... | <|body_start_0|>
polygons = [PolyGon(pts=[(50, 40), (152, 34), (103, 90), (40, 60)], cls_idx=1), PolyGon(pts=[(0, 0), (10, 5), (4, 8)], cls_idx=2)]
feat = Segmentation()
encoded, parsed = encode_decode(feat=feat, poly_or_rle=polygons, mask_shape=(200, 200))
assert encoded.keys() == feat.... | TestSegmentationFeature | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSegmentationFeature:
def test_encode_decode_polygon(self):
"""Test Segmentation feature in polygon format"""
<|body_0|>
def test_encode_decode_rle(self):
"""Test Segmentation feature in run-length-encode format"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_022015 | 8,391 | no_license | [
{
"docstring": "Test Segmentation feature in polygon format",
"name": "test_encode_decode_polygon",
"signature": "def test_encode_decode_polygon(self)"
},
{
"docstring": "Test Segmentation feature in run-length-encode format",
"name": "test_encode_decode_rle",
"signature": "def test_enco... | 2 | stack_v2_sparse_classes_30k_train_012001 | Implement the Python class `TestSegmentationFeature` described below.
Class description:
Implement the TestSegmentationFeature class.
Method signatures and docstrings:
- def test_encode_decode_polygon(self): Test Segmentation feature in polygon format
- def test_encode_decode_rle(self): Test Segmentation feature in r... | Implement the Python class `TestSegmentationFeature` described below.
Class description:
Implement the TestSegmentationFeature class.
Method signatures and docstrings:
- def test_encode_decode_polygon(self): Test Segmentation feature in polygon format
- def test_encode_decode_rle(self): Test Segmentation feature in r... | 5da5317cedd380c244f20a96213e883d6ef29de2 | <|skeleton|>
class TestSegmentationFeature:
def test_encode_decode_polygon(self):
"""Test Segmentation feature in polygon format"""
<|body_0|>
def test_encode_decode_rle(self):
"""Test Segmentation feature in run-length-encode format"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSegmentationFeature:
def test_encode_decode_polygon(self):
"""Test Segmentation feature in polygon format"""
polygons = [PolyGon(pts=[(50, 40), (152, 34), (103, 90), (40, 60)], cls_idx=1), PolyGon(pts=[(0, 0), (10, 5), (4, 8)], cls_idx=2)]
feat = Segmentation()
encoded, par... | the_stack_v2_python_sparse | Database/_unittests/test_features.py | MingRuey/mlbox | train | 2 | |
ad53c62a3323d9cd3652f0f227af78e381fd0e36 | [
"try:\n self.data = open_workbook(file_contents=data_file).sheet_by_index(0)\nexcept XLRDError as e:\n _logger.error(u'Could not read file (SEB Kontohändelser.xlsx)')\n raise ValueError(e)\nif self.data.cell(5, 1).value != 'Saldo' and self.data.cell(5, 4).value != 'Reserverat belopp':\n raise ValueError... | <|body_start_0|>
try:
self.data = open_workbook(file_contents=data_file).sheet_by_index(0)
except XLRDError as e:
_logger.error(u'Could not read file (SEB Kontohändelser.xlsx)')
raise ValueError(e)
if self.data.cell(5, 1).value != 'Saldo' and self.data.cell(5,... | Parser for SEB Kontohändelser import files. | SEBKontohandelserrapport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEBKontohandelserrapport:
"""Parser for SEB Kontohändelser import files."""
def __init__(self, data_file):
"""Check if file can be read"""
<|body_0|>
def parse(self):
"""Parse SEB transaktionsrapport bank statement file contents type 1."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_022016 | 13,458 | no_license | [
{
"docstring": "Check if file can be read",
"name": "__init__",
"signature": "def __init__(self, data_file)"
},
{
"docstring": "Parse SEB transaktionsrapport bank statement file contents type 1.",
"name": "parse",
"signature": "def parse(self)"
}
] | 2 | null | Implement the Python class `SEBKontohandelserrapport` described below.
Class description:
Parser for SEB Kontohändelser import files.
Method signatures and docstrings:
- def __init__(self, data_file): Check if file can be read
- def parse(self): Parse SEB transaktionsrapport bank statement file contents type 1. | Implement the Python class `SEBKontohandelserrapport` described below.
Class description:
Parser for SEB Kontohändelser import files.
Method signatures and docstrings:
- def __init__(self, data_file): Check if file can be read
- def parse(self): Parse SEB transaktionsrapport bank statement file contents type 1.
<|sk... | fa7debb31bca25a2523081efcd720857edb58acd | <|skeleton|>
class SEBKontohandelserrapport:
"""Parser for SEB Kontohändelser import files."""
def __init__(self, data_file):
"""Check if file can be read"""
<|body_0|>
def parse(self):
"""Parse SEB transaktionsrapport bank statement file contents type 1."""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEBKontohandelserrapport:
"""Parser for SEB Kontohändelser import files."""
def __init__(self, data_file):
"""Check if file can be read"""
try:
self.data = open_workbook(file_contents=data_file).sheet_by_index(0)
except XLRDError as e:
_logger.error(u'Could... | the_stack_v2_python_sparse | l10n_se_seb/seb.py | vertelab/odoo-l10n_se | train | 16 |
3973eee0f3d17e2be9ad03b835f0626d8d4260ae | [
"mocked_file_path = util_tmp_json_file()\nmocker.patch.object(demisto, 'getFilePath', return_value=mocked_file_path)\nmocker.patch.object(Client, 'http_request', return_value={'success': True, 'import_session_id': 'test_session_id'})\nresult = import_ioc_with_approval(mock_client(), import_type, 'test_value')\nfile... | <|body_start_0|>
mocked_file_path = util_tmp_json_file()
mocker.patch.object(demisto, 'getFilePath', return_value=mocked_file_path)
mocker.patch.object(Client, 'http_request', return_value={'success': True, 'import_session_id': 'test_session_id'})
result = import_ioc_with_approval(mock_c... | Group the import commands test | TestImportCommands | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestImportCommands:
"""Group the import commands test"""
def test_import_indicator_with_approval__happy_path(self, mocker, import_type):
"""Given: - Indicator to import with approval When: - Call the import with approval command Then: - Validate the request and response are as expect... | stack_v2_sparse_classes_36k_train_022017 | 31,154 | permissive | [
{
"docstring": "Given: - Indicator to import with approval When: - Call the import with approval command Then: - Validate the request and response are as expected",
"name": "test_import_indicator_with_approval__happy_path",
"signature": "def test_import_indicator_with_approval__happy_path(self, mocker, ... | 4 | null | Implement the Python class `TestImportCommands` described below.
Class description:
Group the import commands test
Method signatures and docstrings:
- def test_import_indicator_with_approval__happy_path(self, mocker, import_type): Given: - Indicator to import with approval When: - Call the import with approval comman... | Implement the Python class `TestImportCommands` described below.
Class description:
Group the import commands test
Method signatures and docstrings:
- def test_import_indicator_with_approval__happy_path(self, mocker, import_type): Given: - Indicator to import with approval When: - Call the import with approval comman... | 01b57f8c658c2faed047313d3034e8052ffa83ce | <|skeleton|>
class TestImportCommands:
"""Group the import commands test"""
def test_import_indicator_with_approval__happy_path(self, mocker, import_type):
"""Given: - Indicator to import with approval When: - Call the import with approval command Then: - Validate the request and response are as expect... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestImportCommands:
"""Group the import commands test"""
def test_import_indicator_with_approval__happy_path(self, mocker, import_type):
"""Given: - Indicator to import with approval When: - Call the import with approval command Then: - Validate the request and response are as expected"""
... | the_stack_v2_python_sparse | Packs/Anomali_ThreatStream/Integrations/AnomaliThreatStreamv3/AnomaliThreatStreamv3_test.py | adambaumeister/content | train | 2 |
c56fe45144124dc23e6d6dd262f9747775ff5506 | [
"type_registry = get_registered_types()\nfor t, cls in sorted(type_registry.items(), key=_specificity_sort_key):\n if t != 'any' and cls.validate(instance):\n return t\nraise MetaschemaTypeError(\"Could not encode 'type' property for Python type: %s\" % type(instance))",
"type_cls = get_type_class(prop1... | <|body_start_0|>
type_registry = get_registered_types()
for t, cls in sorted(type_registry.items(), key=_specificity_sort_key):
if t != 'any' and cls.validate(instance):
return t
raise MetaschemaTypeError("Could not encode 'type' property for Python type: %s" % type(i... | Type property with validation of new properties. | TypeMetaschemaProperty | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TypeMetaschemaProperty:
"""Type property with validation of new properties."""
def encode(cls, instance, typedef=None):
"""Method to encode the property given the object. Args: instance (object): Object to get property for. typedef (object, None): Template value in type definition to... | stack_v2_sparse_classes_36k_train_022018 | 3,037 | permissive | [
{
"docstring": "Method to encode the property given the object. Args: instance (object): Object to get property for. typedef (object, None): Template value in type definition to use for initializing encoding some cases. Defaults to None and is ignored. Returns: object: Encoded property for instance.",
"name... | 3 | null | Implement the Python class `TypeMetaschemaProperty` described below.
Class description:
Type property with validation of new properties.
Method signatures and docstrings:
- def encode(cls, instance, typedef=None): Method to encode the property given the object. Args: instance (object): Object to get property for. typ... | Implement the Python class `TypeMetaschemaProperty` described below.
Class description:
Type property with validation of new properties.
Method signatures and docstrings:
- def encode(cls, instance, typedef=None): Method to encode the property given the object. Args: instance (object): Object to get property for. typ... | dcc4d75a4d2c6aaa7e50e75095a16df1df6b2b0a | <|skeleton|>
class TypeMetaschemaProperty:
"""Type property with validation of new properties."""
def encode(cls, instance, typedef=None):
"""Method to encode the property given the object. Args: instance (object): Object to get property for. typedef (object, None): Template value in type definition to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TypeMetaschemaProperty:
"""Type property with validation of new properties."""
def encode(cls, instance, typedef=None):
"""Method to encode the property given the object. Args: instance (object): Object to get property for. typedef (object, None): Template value in type definition to use for init... | the_stack_v2_python_sparse | yggdrasil/metaschema/properties/TypeMetaschemaProperty.py | leighmatth/yggdrasil | train | 0 |
1fd3fb1b1a0e8eb6c2cd1b009babb13474eb33fc | [
"super(TrafficStreamsBaseClass, self).__init__()\nself.n_tunnels = 1024\nself.p2_geneve_start_vni = 1\nself.p1_src_start_ip = u'10.128.1.0'\nself.p1_dst_start_ip = u'10.0.1.0'\nself.p2_outer_src_ip = u'1.1.1.1'\nself.p2_outer_dst_ip = u'1.1.1.2'\nself.p2_inner_src_start_ip = u'10.0.1.0'\nself.p2_inner_dst_start_ip ... | <|body_start_0|>
super(TrafficStreamsBaseClass, self).__init__()
self.n_tunnels = 1024
self.p2_geneve_start_vni = 1
self.p1_src_start_ip = u'10.128.1.0'
self.p1_dst_start_ip = u'10.0.1.0'
self.p2_outer_src_ip = u'1.1.1.1'
self.p2_outer_dst_ip = u'1.1.1.2'
... | Stream profile. | TrafficStreams | [
"GPL-2.0-only",
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficStreams:
"""Stream profile."""
def __init__(self):
"""Initialization and setting of streams' parameters."""
<|body_0|>
def define_packets(self):
"""Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | UDP | :returns: P... | stack_v2_sparse_classes_36k_train_022019 | 7,809 | permissive | [
{
"docstring": "Initialization and setting of streams' parameters.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | UDP | :returns: Packets to be sent from the traffic generator. ... | 2 | null | Implement the Python class `TrafficStreams` described below.
Class description:
Stream profile.
Method signatures and docstrings:
- def __init__(self): Initialization and setting of streams' parameters.
- def define_packets(self): Defines the packets to be sent from the traffic generator. Packet definition: | ETH | I... | Implement the Python class `TrafficStreams` described below.
Class description:
Stream profile.
Method signatures and docstrings:
- def __init__(self): Initialization and setting of streams' parameters.
- def define_packets(self): Defines the packets to be sent from the traffic generator. Packet definition: | ETH | I... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class TrafficStreams:
"""Stream profile."""
def __init__(self):
"""Initialization and setting of streams' parameters."""
<|body_0|>
def define_packets(self):
"""Defines the packets to be sent from the traffic generator. Packet definition: | ETH | IP | UDP | :returns: P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrafficStreams:
"""Stream profile."""
def __init__(self):
"""Initialization and setting of streams' parameters."""
super(TrafficStreamsBaseClass, self).__init__()
self.n_tunnels = 1024
self.p2_geneve_start_vni = 1
self.p1_src_start_ip = u'10.128.1.0'
self.p... | the_stack_v2_python_sparse | GPL/traffic_profiles/trex/trex-stl-2n-ethip4-geneve-1024t.py | FDio/csit | train | 28 |
7971ae69eec593041f3bb59c11e8855bb4f0e8ff | [
"if sampling_strategy == 'easy':\n sampling_fn = sample_easy_alternative\nelif sampling_strategy == 'hard':\n sampling_fn = sample_hard_alternative\nelse:\n raise ValueError('Only easy and hard sampling are currently supported.')\nself.design = PGMDesign(random_state, num_relations, atom_counts, num_rows, ... | <|body_start_0|>
if sampling_strategy == 'easy':
sampling_fn = sample_easy_alternative
elif sampling_strategy == 'hard':
sampling_fn = sample_hard_alternative
else:
raise ValueError('Only easy and hard sampling are currently supported.')
self.design = ... | PGM where ground-truh factors are represented as integer values. | PGM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PGM:
"""PGM where ground-truh factors are represented as integer values."""
def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6):
"""Creates a PGM. Args: random_state: np.random.RandomState used to sample the ... | stack_v2_sparse_classes_36k_train_022020 | 10,947 | permissive | [
{
"docstring": "Creates a PGM. Args: random_state: np.random.RandomState used to sample the PGM. num_relations: Number of relations to enforce for each row in the PGM. atom_counts: List that contains the number of atoms for each of the ground-truth factors. sampling_strategy: Either `easy` or `hard`. For `easy`... | 2 | stack_v2_sparse_classes_30k_train_000546 | Implement the Python class `PGM` described below.
Class description:
PGM where ground-truh factors are represented as integer values.
Method signatures and docstrings:
- def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6): Creates a PGM. Args... | Implement the Python class `PGM` described below.
Class description:
PGM where ground-truh factors are represented as integer values.
Method signatures and docstrings:
- def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6): Creates a PGM. Args... | 73d4b995e88efdd5ffbe98a72e48a620c58f4dc7 | <|skeleton|>
class PGM:
"""PGM where ground-truh factors are represented as integer values."""
def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6):
"""Creates a PGM. Args: random_state: np.random.RandomState used to sample the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PGM:
"""PGM where ground-truh factors are represented as integer values."""
def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6):
"""Creates a PGM. Args: random_state: np.random.RandomState used to sample the PGM. num_rela... | the_stack_v2_python_sparse | disentanglement_lib/evaluation/abstract_reasoning/pgm_utils.py | travers-rhodes/disentanglement_lib | train | 0 |
a706247e5979fa7a63f8e16f7059b995cc979899 | [
"new_head = None\nwhile head:\n curr = ListNode(head.val)\n curr.next, new_head = (new_head, curr)\n head = head.next\nreturn new_head",
"if not head or not head.next:\n return head\nnew = Solution().reverseList2(head.next)\nhead.next.next = head\nhead.next = None\nreturn new"
] | <|body_start_0|>
new_head = None
while head:
curr = ListNode(head.val)
curr.next, new_head = (new_head, curr)
head = head.next
return new_head
<|end_body_0|>
<|body_start_1|>
if not head or not head.next:
return head
new = Solution... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""Iterative solution"""
<|body_0|>
def reverseList2(self, head):
"""Recursive solution"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
new_head = None
while head:
curr = ListNode(head.val)
... | stack_v2_sparse_classes_36k_train_022021 | 613 | no_license | [
{
"docstring": "Iterative solution",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": "Recursive solution",
"name": "reverseList2",
"signature": "def reverseList2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000539 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): Iterative solution
- def reverseList2(self, head): Recursive solution | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): Iterative solution
- def reverseList2(self, head): Recursive solution
<|skeleton|>
class Solution:
def reverseList(self, head):
"""Iter... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def reverseList(self, head):
"""Iterative solution"""
<|body_0|>
def reverseList2(self, head):
"""Recursive solution"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
"""Iterative solution"""
new_head = None
while head:
curr = ListNode(head.val)
curr.next, new_head = (new_head, curr)
head = head.next
return new_head
def reverseList2(self, head):
"""Recurs... | the_stack_v2_python_sparse | Reverse Linked List.py | aulee888/LeetCode | train | 0 | |
f8c91b5b8e69df879d8c9e0c59c56209d3229e2e | [
"self.internalModel = kwargs.pop('internal', None)\nself.weights = kwargs.pop('weights', 1.0)\nself.nMomentConditions = kwargs.pop('nMoM', self.internalModel.nParams)\nkwargs.setdefault('k_moms', self.nMomentConditions)\nkwargs.setdefault('k_params', self.internalModel.nParams)\nsuper(GMMgeneric, self).__init__(*ar... | <|body_start_0|>
self.internalModel = kwargs.pop('internal', None)
self.weights = kwargs.pop('weights', 1.0)
self.nMomentConditions = kwargs.pop('nMoM', self.internalModel.nParams)
kwargs.setdefault('k_moms', self.nMomentConditions)
kwargs.setdefault('k_params', self.internalMode... | ! @brief General method of moments base class | GMMgeneric | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GMMgeneric:
"""! @brief General method of moments base class"""
def __init__(self, *args, **kwargs):
"""! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univar... | stack_v2_sparse_classes_36k_train_022022 | 9,753 | permissive | [
{
"docstring": "! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univariate model - must have a moment() method.",
"name": "__init__",
"signature": "def __init__(self, *args, **kw... | 2 | stack_v2_sparse_classes_30k_train_021466 | Implement the Python class `GMMgeneric` described below.
Class description:
! @brief General method of moments base class
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): ! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (o... | Implement the Python class `GMMgeneric` described below.
Class description:
! @brief General method of moments base class
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): ! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (o... | 7b63c29e2c31d8ff36ac261381e7e95339421d7e | <|skeleton|>
class GMMgeneric:
"""! @brief General method of moments base class"""
def __init__(self, *args, **kwargs):
"""! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GMMgeneric:
"""! @brief General method of moments base class"""
def __init__(self, *args, **kwargs):
"""! @brief General method of moments base class @param endog Response data @param exog Explanatory data @param instruments (optional) defaults to None @param internal internal univariate model - ... | the_stack_v2_python_sparse | starvine/uvar/uvmodels/uv_base.py | NinelK/StarVine | train | 0 |
b90f6d9f169e2cea25aaed3e8a9ebb492b6483bf | [
"agency_id = request.data.get('agency', None)\nfiscal_year = request.data.get('fiscal_year', None)\ntype_param = request.data.get('type', None)\nrequired_params = {'agency': agency_id, 'fiscal_year': fiscal_year, 'type': type_param}\nfor required, param_value in required_params.items():\n if param_value is None:... | <|body_start_0|>
agency_id = request.data.get('agency', None)
fiscal_year = request.data.get('fiscal_year', None)
type_param = request.data.get('type', None)
required_params = {'agency': agency_id, 'fiscal_year': fiscal_year, 'type': type_param}
for required, param_value in requi... | Returns a list of the current versions of generated archive files for a given fiscal year and agency. | ListMonthlyDownloadsViewSet | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListMonthlyDownloadsViewSet:
"""Returns a list of the current versions of generated archive files for a given fiscal year and agency."""
def post(self, request):
"""Return list of downloads that match the requested params"""
<|body_0|>
def create_download_response_obj(se... | stack_v2_sparse_classes_36k_train_022023 | 4,423 | permissive | [
{
"docstring": "Return list of downloads that match the requested params",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "Return a",
"name": "create_download_response_obj",
"signature": "def create_download_response_obj(self, filename, fiscal_year, type_param, ... | 2 | null | Implement the Python class `ListMonthlyDownloadsViewSet` described below.
Class description:
Returns a list of the current versions of generated archive files for a given fiscal year and agency.
Method signatures and docstrings:
- def post(self, request): Return list of downloads that match the requested params
- def... | Implement the Python class `ListMonthlyDownloadsViewSet` described below.
Class description:
Returns a list of the current versions of generated archive files for a given fiscal year and agency.
Method signatures and docstrings:
- def post(self, request): Return list of downloads that match the requested params
- def... | 38f920438697930ae3ac57bbcaae9034877d8fb7 | <|skeleton|>
class ListMonthlyDownloadsViewSet:
"""Returns a list of the current versions of generated archive files for a given fiscal year and agency."""
def post(self, request):
"""Return list of downloads that match the requested params"""
<|body_0|>
def create_download_response_obj(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListMonthlyDownloadsViewSet:
"""Returns a list of the current versions of generated archive files for a given fiscal year and agency."""
def post(self, request):
"""Return list of downloads that match the requested params"""
agency_id = request.data.get('agency', None)
fiscal_year... | the_stack_v2_python_sparse | usaspending_api/download/v2/list_monthly_downloads.py | fedspendingtransparency/usaspending-api | train | 276 |
ad1e238f7cb17e1939d03ddb82ee30a2424d70ea | [
"buffer = self._get_buffer()\nstart = self._buffer_size * (self._seek - 1)\nend = start + len(buffer)\nfuture = self._workers.submit(self._flush_range, buffer=buffer, start=start, end=end)\nself._write_futures.append(future)\nfuture.add_done_callback(partial(self._update_size, end))",
"with self._size_lock:\n ... | <|body_start_0|>
buffer = self._get_buffer()
start = self._buffer_size * (self._seek - 1)
end = start + len(buffer)
future = self._workers.submit(self._flush_range, buffer=buffer, start=start, end=end)
self._write_futures.append(future)
future.add_done_callback(partial(se... | Base class for buffered binary storage object I/O with partial flush support. | ObjectBufferedIORandomWriteBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectBufferedIORandomWriteBase:
"""Base class for buffered binary storage object I/O with partial flush support."""
def _flush(self):
"""Flush the write buffers of the stream if applicable. In "write" mode, send the buffer content to the storage object."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_022024 | 4,812 | permissive | [
{
"docstring": "Flush the write buffers of the stream if applicable. In \"write\" mode, send the buffer content to the storage object.",
"name": "_flush",
"signature": "def _flush(self)"
},
{
"docstring": "Keep track of the file size during writing. If specified size value is greater than the cu... | 3 | stack_v2_sparse_classes_30k_train_009092 | Implement the Python class `ObjectBufferedIORandomWriteBase` described below.
Class description:
Base class for buffered binary storage object I/O with partial flush support.
Method signatures and docstrings:
- def _flush(self): Flush the write buffers of the stream if applicable. In "write" mode, send the buffer con... | Implement the Python class `ObjectBufferedIORandomWriteBase` described below.
Class description:
Base class for buffered binary storage object I/O with partial flush support.
Method signatures and docstrings:
- def _flush(self): Flush the write buffers of the stream if applicable. In "write" mode, send the buffer con... | 5c1334363f4af29bf2f57681e1ae7dc1866af776 | <|skeleton|>
class ObjectBufferedIORandomWriteBase:
"""Base class for buffered binary storage object I/O with partial flush support."""
def _flush(self):
"""Flush the write buffers of the stream if applicable. In "write" mode, send the buffer content to the storage object."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectBufferedIORandomWriteBase:
"""Base class for buffered binary storage object I/O with partial flush support."""
def _flush(self):
"""Flush the write buffers of the stream if applicable. In "write" mode, send the buffer content to the storage object."""
buffer = self._get_buffer()
... | the_stack_v2_python_sparse | airfs/_core/io_random_write.py | JGoutin/airfs | train | 6 |
07c50ab56308c6a681a4d6a999190e9b85907a60 | [
"q = [(-nums[i], i) for i in range(k)]\nheapq.heapify(q)\nret = [-q[0][0]]\nfor i in range(k, len(nums)):\n while q and q[0][1] <= i - k:\n heapq.heappop(q)\n heapq.heappush(q, (-nums[i], i))\n ret.append(-q[0][0])\nreturn ret",
"if k == 1:\n return nums\nif k == len(nums):\n return [max(num... | <|body_start_0|>
q = [(-nums[i], i) for i in range(k)]
heapq.heapify(q)
ret = [-q[0][0]]
for i in range(k, len(nums)):
while q and q[0][1] <= i - k:
heapq.heappop(q)
heapq.heappush(q, (-nums[i], i))
ret.append(-q[0][0])
return r... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSlidingWindow2(self, nums: List[int], k: int) -> List[int]:
"""Use python heapq Runtime: 1976 ms, faster than 43.70% Memory Usage: 39 MB, less than 5.23% 1 <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4 1 <= k <= nums.length :param nums: :param k: :return:"""
<|... | stack_v2_sparse_classes_36k_train_022025 | 2,696 | permissive | [
{
"docstring": "Use python heapq Runtime: 1976 ms, faster than 43.70% Memory Usage: 39 MB, less than 5.23% 1 <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4 1 <= k <= nums.length :param nums: :param k: :return:",
"name": "maxSlidingWindow2",
"signature": "def maxSlidingWindow2(self, nums: List[int], k: ... | 2 | stack_v2_sparse_classes_30k_train_017828 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow2(self, nums: List[int], k: int) -> List[int]: Use python heapq Runtime: 1976 ms, faster than 43.70% Memory Usage: 39 MB, less than 5.23% 1 <= nums.length <= ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSlidingWindow2(self, nums: List[int], k: int) -> List[int]: Use python heapq Runtime: 1976 ms, faster than 43.70% Memory Usage: 39 MB, less than 5.23% 1 <= nums.length <= ... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def maxSlidingWindow2(self, nums: List[int], k: int) -> List[int]:
"""Use python heapq Runtime: 1976 ms, faster than 43.70% Memory Usage: 39 MB, less than 5.23% 1 <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4 1 <= k <= nums.length :param nums: :param k: :return:"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSlidingWindow2(self, nums: List[int], k: int) -> List[int]:
"""Use python heapq Runtime: 1976 ms, faster than 43.70% Memory Usage: 39 MB, less than 5.23% 1 <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4 1 <= k <= nums.length :param nums: :param k: :return:"""
q = [(-nums[i], ... | the_stack_v2_python_sparse | src/todo/239-SlidingWindowMaximum.py | Jiezhi/myleetcode | train | 1 | |
b1f93a688a4117b9dfd1eb0c597408e1baf3eddb | [
"for c in alsaaudio.card_indexes():\n mixers = alsaaudio.mixers(cardindex=c)\n for m in mixers:\n mixer = alsaaudio.Mixer(m, cardindex=c)\n mixer.close()",
"mixers = alsaaudio.mixers()\nmixer = alsaaudio.Mixer(mixers[0])\nfor m, a in MixerMethods:\n f = alsaaudio.Mixer.__dict__[m]\n if a... | <|body_start_0|>
for c in alsaaudio.card_indexes():
mixers = alsaaudio.mixers(cardindex=c)
for m in mixers:
mixer = alsaaudio.Mixer(m, cardindex=c)
mixer.close()
<|end_body_0|>
<|body_start_1|>
mixers = alsaaudio.mixers()
mixer = alsaaudio... | Test Mixer objects | MixerTest | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Python-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixerTest:
"""Test Mixer objects"""
def testMixer(self):
"""Open the default Mixers and the Mixers on every card"""
<|body_0|>
def testMixerAll(self):
"""Run common Mixer methods on an open object"""
<|body_1|>
def testMixerClose(self):
"""Ru... | stack_v2_sparse_classes_36k_train_022026 | 4,117 | permissive | [
{
"docstring": "Open the default Mixers and the Mixers on every card",
"name": "testMixer",
"signature": "def testMixer(self)"
},
{
"docstring": "Run common Mixer methods on an open object",
"name": "testMixerAll",
"signature": "def testMixerAll(self)"
},
{
"docstring": "Run comm... | 3 | stack_v2_sparse_classes_30k_train_003194 | Implement the Python class `MixerTest` described below.
Class description:
Test Mixer objects
Method signatures and docstrings:
- def testMixer(self): Open the default Mixers and the Mixers on every card
- def testMixerAll(self): Run common Mixer methods on an open object
- def testMixerClose(self): Run common Mixer ... | Implement the Python class `MixerTest` described below.
Class description:
Test Mixer objects
Method signatures and docstrings:
- def testMixer(self): Open the default Mixers and the Mixers on every card
- def testMixerAll(self): Run common Mixer methods on an open object
- def testMixerClose(self): Run common Mixer ... | 758859b3142cef61e34c663ae9677b955ea1f225 | <|skeleton|>
class MixerTest:
"""Test Mixer objects"""
def testMixer(self):
"""Open the default Mixers and the Mixers on every card"""
<|body_0|>
def testMixerAll(self):
"""Run common Mixer methods on an open object"""
<|body_1|>
def testMixerClose(self):
"""Ru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixerTest:
"""Test Mixer objects"""
def testMixer(self):
"""Open the default Mixers and the Mixers on every card"""
for c in alsaaudio.card_indexes():
mixers = alsaaudio.mixers(cardindex=c)
for m in mixers:
mixer = alsaaudio.Mixer(m, cardindex=c)
... | the_stack_v2_python_sparse | lesson-2/pyalsaaudio/test.py | alexyvassili/devman-async | train | 0 |
0f93d66446f004f015d81c97464ca5ba1724a921 | [
"for boy in arrB:\n flag = 0\n for cpl in arrCPL:\n if cpl.boy_name == boy:\n print(boy, ' found, is committed with ', cpl.girl_name)\n flag = 1\n break\n if flag == 0:\n print(boy, ' is not commited')",
"arrCPL.sort(key=attrgetter('boy_name'))\nfor boy in a... | <|body_start_0|>
for boy in arrB:
flag = 0
for cpl in arrCPL:
if cpl.boy_name == boy:
print(boy, ' found, is committed with ', cpl.girl_name)
flag = 1
break
if flag == 0:
print(boy, ' ... | Allocator class specifically for question 7, has implementations of array, sorted array(binary, search) and hash table | allocator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class allocator:
"""Allocator class specifically for question 7, has implementations of array, sorted array(binary, search) and hash table"""
def opt1(self, arrB, arrCPL):
"""option 1: used for placing all the data in an array and do a linear search"""
<|body_0|>
def opt2(self... | stack_v2_sparse_classes_36k_train_022027 | 2,163 | no_license | [
{
"docstring": "option 1: used for placing all the data in an array and do a linear search",
"name": "opt1",
"signature": "def opt1(self, arrB, arrCPL)"
},
{
"docstring": "option 2: used for sorting the array first, so that binary search can be applied",
"name": "opt2",
"signature": "def... | 4 | stack_v2_sparse_classes_30k_train_010296 | Implement the Python class `allocator` described below.
Class description:
Allocator class specifically for question 7, has implementations of array, sorted array(binary, search) and hash table
Method signatures and docstrings:
- def opt1(self, arrB, arrCPL): option 1: used for placing all the data in an array and do... | Implement the Python class `allocator` described below.
Class description:
Allocator class specifically for question 7, has implementations of array, sorted array(binary, search) and hash table
Method signatures and docstrings:
- def opt1(self, arrB, arrCPL): option 1: used for placing all the data in an array and do... | c6e96a7ca5251837281d8d2b8c2123c787ad00de | <|skeleton|>
class allocator:
"""Allocator class specifically for question 7, has implementations of array, sorted array(binary, search) and hash table"""
def opt1(self, arrB, arrCPL):
"""option 1: used for placing all the data in an array and do a linear search"""
<|body_0|>
def opt2(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class allocator:
"""Allocator class specifically for question 7, has implementations of array, sorted array(binary, search) and hash table"""
def opt1(self, arrB, arrCPL):
"""option 1: used for placing all the data in an array and do a linear search"""
for boy in arrB:
flag = 0
... | the_stack_v2_python_sparse | part3/question11/typeError/helper/utils.py | PPL-IIITA/ppl-assignment-dewana-dewan | train | 0 |
d0b3d3db9aab6110be1759054cc99c17449711d2 | [
"super(Lidar, self).__init__(carla_actor=carla_actor, parent=parent, node=node, synchronous_mode=synchronous_mode, prefix='lidar/' + carla_actor.attributes.get('role_name'))\nself.lidar_publisher = rospy.Publisher(self.get_topic_prefix() + '/point_cloud', PointCloud2, queue_size=10)\nself.listen()",
"header = sel... | <|body_start_0|>
super(Lidar, self).__init__(carla_actor=carla_actor, parent=parent, node=node, synchronous_mode=synchronous_mode, prefix='lidar/' + carla_actor.attributes.get('role_name'))
self.lidar_publisher = rospy.Publisher(self.get_topic_prefix() + '/point_cloud', PointCloud2, queue_size=10)
... | Actor implementation details for lidars | Lidar | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lidar:
"""Actor implementation details for lidars"""
def __init__(self, carla_actor, parent, node, synchronous_mode):
"""Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param no... | stack_v2_sparse_classes_36k_train_022028 | 5,360 | permissive | [
{
"docstring": "Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param node: node-handle :type node: carla_ros_bridge.CarlaRosBridge",
"name": "__init__",
"signature": "def __init__(self, carla_acto... | 2 | stack_v2_sparse_classes_30k_test_000432 | Implement the Python class `Lidar` described below.
Class description:
Actor implementation details for lidars
Method signatures and docstrings:
- def __init__(self, carla_actor, parent, node, synchronous_mode): Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the paren... | Implement the Python class `Lidar` described below.
Class description:
Actor implementation details for lidars
Method signatures and docstrings:
- def __init__(self, carla_actor, parent, node, synchronous_mode): Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the paren... | 65ba2fdb2ca24907083bc277ec333294ab174fa6 | <|skeleton|>
class Lidar:
"""Actor implementation details for lidars"""
def __init__(self, carla_actor, parent, node, synchronous_mode):
"""Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param no... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lidar:
"""Actor implementation details for lidars"""
def __init__(self, carla_actor, parent, node, synchronous_mode):
"""Constructor :param carla_actor: carla actor object :type carla_actor: carla.Actor :param parent: the parent of this :type parent: carla_ros_bridge.Parent :param node: node-hand... | the_stack_v2_python_sparse | ros/ros-bridge/carla_ros_bridge/src/carla_ros_bridge/lidar.py | Essentia-Laboratory/intelligent-embedded-systems | train | 3 |
a154be506b01e7ea7fe7a495cb11e0b977de070e | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"size_list = list(range(5))\ndirection_list = [-1, 1]\nsize = choice(size_list)\ndirection = choice(direction_list)\nreturn size * direction",
"while len(self.x_values) < self.num_points:\n x_step = self.get_step()\n y_step = self.g... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
size_list = list(range(5))
direction_list = [-1, 1]
size = choice(size_list)
direction = choice(direction_list)
return size * direction
<... | A class to generate random walks. | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
<|body_0|>
def get_step(self):
"""Get a random step's x coord. & y coord."""
<|body_1|>
def fill_walk(self):
"""Ca... | stack_v2_sparse_classes_36k_train_022029 | 1,071 | no_license | [
{
"docstring": "Initialize attributes of a walk.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Get a random step's x coord. & y coord.",
"name": "get_step",
"signature": "def get_step(self)"
},
{
"docstring": "Calculate all the points... | 3 | null | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialize attributes of a walk.
- def get_step(self): Get a random step's x coord. & y coord.
- def fill_walk(self): Calculate all the... | Implement the Python class `RandomWalk` described below.
Class description:
A class to generate random walks.
Method signatures and docstrings:
- def __init__(self, num_points=5000): Initialize attributes of a walk.
- def get_step(self): Get a random step's x coord. & y coord.
- def fill_walk(self): Calculate all the... | 0af7594385dd06e23031b0f7f1d1152c94006c4b | <|skeleton|>
class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
<|body_0|>
def get_step(self):
"""Get a random step's x coord. & y coord."""
<|body_1|>
def fill_walk(self):
"""Ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""A class to generate random walks."""
def __init__(self, num_points=5000):
"""Initialize attributes of a walk."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
"""Get a random step's x coord. & y coord."... | the_stack_v2_python_sparse | ch_15/random_walk.py | enlambdment/my_pcc | train | 0 |
4705cc19aa0177768399ee69eeb1b993e285d1d4 | [
"self.weather_data = weather_data\nself.input_dim = input_dim\nself.output_dim = output_dim if isinstance(output_dim, list) else [output_dim]\nself.window_in_len = window_in_len\nself.window_out_len = window_out_len\nself.total_window_len = window_in_len + window_out_len\nself.batch_size = batch_size\nself.num_iter... | <|body_start_0|>
self.weather_data = weather_data
self.input_dim = input_dim
self.output_dim = output_dim if isinstance(output_dim, list) else [output_dim]
self.window_in_len = window_in_len
self.window_out_len = window_out_len
self.total_window_len = window_in_len + wind... | WeatherDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeatherDataset:
def __init__(self, weather_data, input_dim, output_dim, window_in_len, window_out_len, batch_size, normalizer, shuffle):
""":param input_dim: :param output_dim: :param window_in_len: :param window_out_len: :param batch_size: :param shuffle:"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_022030 | 4,287 | no_license | [
{
"docstring": ":param input_dim: :param output_dim: :param window_in_len: :param window_out_len: :param batch_size: :param shuffle:",
"name": "__init__",
"signature": "def __init__(self, weather_data, input_dim, output_dim, window_in_len, window_out_len, batch_size, normalizer, shuffle)"
},
{
"... | 5 | stack_v2_sparse_classes_30k_train_014528 | Implement the Python class `WeatherDataset` described below.
Class description:
Implement the WeatherDataset class.
Method signatures and docstrings:
- def __init__(self, weather_data, input_dim, output_dim, window_in_len, window_out_len, batch_size, normalizer, shuffle): :param input_dim: :param output_dim: :param w... | Implement the Python class `WeatherDataset` described below.
Class description:
Implement the WeatherDataset class.
Method signatures and docstrings:
- def __init__(self, weather_data, input_dim, output_dim, window_in_len, window_out_len, batch_size, normalizer, shuffle): :param input_dim: :param output_dim: :param w... | 39b14bed1a094e1beefe0aaafd8a08509dbcfc3d | <|skeleton|>
class WeatherDataset:
def __init__(self, weather_data, input_dim, output_dim, window_in_len, window_out_len, batch_size, normalizer, shuffle):
""":param input_dim: :param output_dim: :param window_in_len: :param window_out_len: :param batch_size: :param shuffle:"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeatherDataset:
def __init__(self, weather_data, input_dim, output_dim, window_in_len, window_out_len, batch_size, normalizer, shuffle):
""":param input_dim: :param output_dim: :param window_in_len: :param window_out_len: :param batch_size: :param shuffle:"""
self.weather_data = weather_data
... | the_stack_v2_python_sparse | dataset.py | junjie2008v/ieee_weather | train | 0 | |
10aa548719970275f9511dd2805223f907bc2b7a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn EducationAssignmentSettings()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'submissionAnimationDisabled': lambda n: setattr(self, 'submission_animation_disabled', n.get_bool_val... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return EducationAssignmentSettings()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Callable[[Any], None]] = {'submissionAnimati... | EducationAssignmentSettings | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EducationAssignmentSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentSettings:
"""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 a... | stack_v2_sparse_classes_36k_train_022031 | 2,228 | 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: EducationAssignmentSettings",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | null | Implement the Python class `EducationAssignmentSettings` described below.
Class description:
Implement the EducationAssignmentSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentSettings: Creates a new instance of the appr... | Implement the Python class `EducationAssignmentSettings` described below.
Class description:
Implement the EducationAssignmentSettings class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentSettings: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class EducationAssignmentSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentSettings:
"""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 a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EducationAssignmentSettings:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> EducationAssignmentSettings:
"""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 ... | the_stack_v2_python_sparse | msgraph/generated/models/education_assignment_settings.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
f354f089c45626f12db35e23d12089aa93cc7066 | [
"params = dict(analyzesFaceLandmarks=True, analyzesAge=True, analyzesGender=True, analyzesHeadPose=True)\nresponse = self.client.post('/detections', params=params, json={'url': image_url})\nfaces = response.json()\nif not faces:\n return None\nreturn faces[0]",
"response = self.client.post('/identifications', ... | <|body_start_0|>
params = dict(analyzesFaceLandmarks=True, analyzesAge=True, analyzesGender=True, analyzesHeadPose=True)
response = self.client.post('/detections', params=params, json={'url': image_url})
faces = response.json()
if not faces:
return None
return faces[0... | Faces | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Faces:
def detect(self, image_url):
"""Tries to detect *one* face! :type image_url: unicode :rtype: dict | None"""
<|body_0|>
def identify(self, face_id, person_group_id):
"""Tries to identify the given face in the given person group :type face_id: unicode :type pers... | stack_v2_sparse_classes_36k_train_022032 | 4,283 | no_license | [
{
"docstring": "Tries to detect *one* face! :type image_url: unicode :rtype: dict | None",
"name": "detect",
"signature": "def detect(self, image_url)"
},
{
"docstring": "Tries to identify the given face in the given person group :type face_id: unicode :type person_group_id: unicode :returns (pe... | 2 | stack_v2_sparse_classes_30k_train_003913 | Implement the Python class `Faces` described below.
Class description:
Implement the Faces class.
Method signatures and docstrings:
- def detect(self, image_url): Tries to detect *one* face! :type image_url: unicode :rtype: dict | None
- def identify(self, face_id, person_group_id): Tries to identify the given face i... | Implement the Python class `Faces` described below.
Class description:
Implement the Faces class.
Method signatures and docstrings:
- def detect(self, image_url): Tries to detect *one* face! :type image_url: unicode :rtype: dict | None
- def identify(self, face_id, person_group_id): Tries to identify the given face i... | 0199789b2e2b0a9be8e3b00887e187b2ac97ea47 | <|skeleton|>
class Faces:
def detect(self, image_url):
"""Tries to detect *one* face! :type image_url: unicode :rtype: dict | None"""
<|body_0|>
def identify(self, face_id, person_group_id):
"""Tries to identify the given face in the given person group :type face_id: unicode :type pers... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Faces:
def detect(self, image_url):
"""Tries to detect *one* face! :type image_url: unicode :rtype: dict | None"""
params = dict(analyzesFaceLandmarks=True, analyzesAge=True, analyzesGender=True, analyzesHeadPose=True)
response = self.client.post('/detections', params=params, json={'ur... | the_stack_v2_python_sparse | faces/lib/faces_api/api.py | bartoszhernas/ecommhack.api | train | 0 | |
db6875b864e0568a878dd9595f35d4496c2d41b7 | [
"if add_one == '0':\n if num1 == '1' and num2 == '1':\n return ('1', '0')\n if num1 == '1' and num2 == '0' or (num1 == '0' and num2 == '1'):\n return ('0', '1')\n else:\n return ('0', '0')\nelse:\n if num1 == '1' and num2 == '1':\n return ('1', '1')\n if num1 == '1' and nu... | <|body_start_0|>
if add_one == '0':
if num1 == '1' and num2 == '1':
return ('1', '0')
if num1 == '1' and num2 == '0' or (num1 == '0' and num2 == '1'):
return ('0', '1')
else:
return ('0', '0')
else:
if num1 =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addBit(self, num1, num2, add_one):
""":return: add_one cur_num"""
<|body_0|>
def addBinary(self, a, b):
""":type a: str :type b: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if add_one == '0':
if num1 == ... | stack_v2_sparse_classes_36k_train_022033 | 2,815 | permissive | [
{
"docstring": ":return: add_one cur_num",
"name": "addBit",
"signature": "def addBit(self, num1, num2, add_one)"
},
{
"docstring": ":type a: str :type b: str :rtype: str",
"name": "addBinary",
"signature": "def addBinary(self, a, b)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addBit(self, num1, num2, add_one): :return: add_one cur_num
- def addBinary(self, a, b): :type a: str :type b: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addBit(self, num1, num2, add_one): :return: add_one cur_num
- def addBinary(self, a, b): :type a: str :type b: str :rtype: str
<|skeleton|>
class Solution:
def addBit(s... | 1ed22267156fb968671731c2e983b0e65f670750 | <|skeleton|>
class Solution:
def addBit(self, num1, num2, add_one):
""":return: add_one cur_num"""
<|body_0|>
def addBinary(self, a, b):
""":type a: str :type b: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addBit(self, num1, num2, add_one):
""":return: add_one cur_num"""
if add_one == '0':
if num1 == '1' and num2 == '1':
return ('1', '0')
if num1 == '1' and num2 == '0' or (num1 == '0' and num2 == '1'):
return ('0', '1')
... | the_stack_v2_python_sparse | leetcode/67.py | pingrunhuang/CodeChallenge | train | 0 | |
72f597e9d8eb2d165c1e54bb62b9fd66f6df2e33 | [
"self._target: str | None = None\nself._tts_service: str | None = None\nif (entity_id := config.get(CONF_ENTITY_ID)):\n self._target = entity_id\nelse:\n _, self._tts_service = split_entity_id(config[CONF_TTS_SERVICE])\nself._media_player = config[CONF_MEDIA_PLAYER]\nself._language = config.get(ATTR_LANGUAGE)... | <|body_start_0|>
self._target: str | None = None
self._tts_service: str | None = None
if (entity_id := config.get(CONF_ENTITY_ID)):
self._target = entity_id
else:
_, self._tts_service = split_entity_id(config[CONF_TTS_SERVICE])
self._media_player = config[... | The TTS Notification Service. | TTSNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TTSNotificationService:
"""The TTS Notification Service."""
def __init__(self, config: ConfigType) -> None:
"""Initialize the service."""
<|body_0|>
async def async_send_message(self, message: str='', **kwargs: Any) -> None:
"""Call TTS service to speak the notif... | stack_v2_sparse_classes_36k_train_022034 | 2,890 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, config: ConfigType) -> None"
},
{
"docstring": "Call TTS service to speak the notification.",
"name": "async_send_message",
"signature": "async def async_send_message(self, message: str='', **k... | 2 | null | Implement the Python class `TTSNotificationService` described below.
Class description:
The TTS Notification Service.
Method signatures and docstrings:
- def __init__(self, config: ConfigType) -> None: Initialize the service.
- async def async_send_message(self, message: str='', **kwargs: Any) -> None: Call TTS servi... | Implement the Python class `TTSNotificationService` described below.
Class description:
The TTS Notification Service.
Method signatures and docstrings:
- def __init__(self, config: ConfigType) -> None: Initialize the service.
- async def async_send_message(self, message: str='', **kwargs: Any) -> None: Call TTS servi... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TTSNotificationService:
"""The TTS Notification Service."""
def __init__(self, config: ConfigType) -> None:
"""Initialize the service."""
<|body_0|>
async def async_send_message(self, message: str='', **kwargs: Any) -> None:
"""Call TTS service to speak the notif... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TTSNotificationService:
"""The TTS Notification Service."""
def __init__(self, config: ConfigType) -> None:
"""Initialize the service."""
self._target: str | None = None
self._tts_service: str | None = None
if (entity_id := config.get(CONF_ENTITY_ID)):
self._ta... | the_stack_v2_python_sparse | homeassistant/components/tts/notify.py | home-assistant/core | train | 35,501 |
2a50d35ad5af8f9be6d5438a05bc04fa903d3869 | [
"n, m = (len(s), len(p))\np = sorted(p)\nres = []\nfor i in range(n):\n if s[i] in p:\n if sorted(s[i:i + m]) == p:\n res.append(i)\nreturn res",
"from collections import defaultdict\nneed = defaultdict(int)\nfor i in p:\n need[i] += 1\nwindow = {}\nn, m = (len(s), len(p))\nleft, right = (... | <|body_start_0|>
n, m = (len(s), len(p))
p = sorted(p)
res = []
for i in range(n):
if s[i] in p:
if sorted(s[i:i + m]) == p:
res.append(i)
return res
<|end_body_0|>
<|body_start_1|>
from collections import defaultdict
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAnagrams0(self, s, p):
""":type s: str :type p: str :rtype: List[int] 暴力解法,超时"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int] 滑动窗口"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n, m = (l... | stack_v2_sparse_classes_36k_train_022035 | 1,695 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: List[int] 暴力解法,超时",
"name": "findAnagrams0",
"signature": "def findAnagrams0(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: List[int] 滑动窗口",
"name": "findAnagrams",
"signature": "def findAnagrams(self, s, p)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004313 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams0(self, s, p): :type s: str :type p: str :rtype: List[int] 暴力解法,超时
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] 滑动窗口 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAnagrams0(self, s, p): :type s: str :type p: str :rtype: List[int] 暴力解法,超时
- def findAnagrams(self, s, p): :type s: str :type p: str :rtype: List[int] 滑动窗口
<|skeleton|>
... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def findAnagrams0(self, s, p):
""":type s: str :type p: str :rtype: List[int] 暴力解法,超时"""
<|body_0|>
def findAnagrams(self, s, p):
""":type s: str :type p: str :rtype: List[int] 滑动窗口"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findAnagrams0(self, s, p):
""":type s: str :type p: str :rtype: List[int] 暴力解法,超时"""
n, m = (len(s), len(p))
p = sorted(p)
res = []
for i in range(n):
if s[i] in p:
if sorted(s[i:i + m]) == p:
res.append(i)
... | the_stack_v2_python_sparse | 438.找到字符串中所有字母异位词.py | yangyuxiang1996/leetcode | train | 0 | |
a3ac01b465bcaf541c7789b907369192bae807dd | [
"layout = self.layout\nlayout.operator('object.object_add_write_perm')\nlayout.operator('object.object_rem_write_perm')\nlayout.operator('object.set_owner')",
"wm = context.window_manager\nif wm.cur_verse_user_index >= 0 and len(wm.verse_user) > 0:\n return True\nelse:\n return False"
] | <|body_start_0|>
layout = self.layout
layout.operator('object.object_add_write_perm')
layout.operator('object.object_rem_write_perm')
layout.operator('object.set_owner')
<|end_body_0|>
<|body_start_1|>
wm = context.window_manager
if wm.cur_verse_user_index >= 0 and len(w... | Menu for object list | VerseObjectPermMtMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerseObjectPermMtMenu:
"""Menu for object list"""
def draw(self, context):
"""Draw menu"""
<|body_0|>
def poll(cls, context):
"""This class method is used, when Blender check, if this operator can be executed"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_022036 | 18,592 | no_license | [
{
"docstring": "Draw menu",
"name": "draw",
"signature": "def draw(self, context)"
},
{
"docstring": "This class method is used, when Blender check, if this operator can be executed",
"name": "poll",
"signature": "def poll(cls, context)"
}
] | 2 | null | Implement the Python class `VerseObjectPermMtMenu` described below.
Class description:
Menu for object list
Method signatures and docstrings:
- def draw(self, context): Draw menu
- def poll(cls, context): This class method is used, when Blender check, if this operator can be executed | Implement the Python class `VerseObjectPermMtMenu` described below.
Class description:
Menu for object list
Method signatures and docstrings:
- def draw(self, context): Draw menu
- def poll(cls, context): This class method is used, when Blender check, if this operator can be executed
<|skeleton|>
class VerseObjectPe... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class VerseObjectPermMtMenu:
"""Menu for object list"""
def draw(self, context):
"""Draw menu"""
<|body_0|>
def poll(cls, context):
"""This class method is used, when Blender check, if this operator can be executed"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VerseObjectPermMtMenu:
"""Menu for object list"""
def draw(self, context):
"""Draw menu"""
layout = self.layout
layout.operator('object.object_add_write_perm')
layout.operator('object.object_rem_write_perm')
layout.operator('object.set_owner')
def poll(cls, co... | the_stack_v2_python_sparse | All_In_One/addons/io_verse/ui_object3d.py | 2434325680/Learnbgame | train | 0 |
7e077b5c788159066ee1180af6b8730ce5ef1c2a | [
"self.setUpPyfakefs()\nself.fuzz_target_path = '/example/do_stuff_fuzzer'\ndeployment = _create_deployment()\nself.target = fuzz_target.FuzzTarget(self.fuzz_target_path, 100, deployment.workspace, deployment, deployment.config)\nself.oss_fuzz_build_path = '/oss-fuzz-build'\nself.fs.create_file(self.fuzz_target_path... | <|body_start_0|>
self.setUpPyfakefs()
self.fuzz_target_path = '/example/do_stuff_fuzzer'
deployment = _create_deployment()
self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, 100, deployment.workspace, deployment, deployment.config)
self.oss_fuzz_build_path = '/oss-fuzz-b... | Tests the is_crash_reportable method of FuzzTarget. | IsCrashReportableTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsCrashReportableTest:
"""Tests the is_crash_reportable method of FuzzTarget."""
def setUp(self):
"""Sets up example fuzz target to test is_crash_reportable method."""
<|body_0|>
def test_new_reproducible_crash(self, mock_info, _):
"""Tests that a new reproducibl... | stack_v2_sparse_classes_36k_train_022037 | 12,595 | permissive | [
{
"docstring": "Sets up example fuzz target to test is_crash_reportable method.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Tests that a new reproducible crash returns True.",
"name": "test_new_reproducible_crash",
"signature": "def test_new_reproducible_crash(se... | 4 | null | Implement the Python class `IsCrashReportableTest` described below.
Class description:
Tests the is_crash_reportable method of FuzzTarget.
Method signatures and docstrings:
- def setUp(self): Sets up example fuzz target to test is_crash_reportable method.
- def test_new_reproducible_crash(self, mock_info, _): Tests t... | Implement the Python class `IsCrashReportableTest` described below.
Class description:
Tests the is_crash_reportable method of FuzzTarget.
Method signatures and docstrings:
- def setUp(self): Sets up example fuzz target to test is_crash_reportable method.
- def test_new_reproducible_crash(self, mock_info, _): Tests t... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class IsCrashReportableTest:
"""Tests the is_crash_reportable method of FuzzTarget."""
def setUp(self):
"""Sets up example fuzz target to test is_crash_reportable method."""
<|body_0|>
def test_new_reproducible_crash(self, mock_info, _):
"""Tests that a new reproducibl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsCrashReportableTest:
"""Tests the is_crash_reportable method of FuzzTarget."""
def setUp(self):
"""Sets up example fuzz target to test is_crash_reportable method."""
self.setUpPyfakefs()
self.fuzz_target_path = '/example/do_stuff_fuzzer'
deployment = _create_deployment()... | the_stack_v2_python_sparse | infra/cifuzz/fuzz_target_test.py | google/oss-fuzz | train | 9,438 |
ab95c56856272868e4cceddbd8924279ee888ea4 | [
"self.entry_point = (0, 0)\nself.map_data = []\npass",
"game_folder = path.dirname(__file__)\nself.map_data = []\nwith open(path.join(game_folder, 'map.txt'), 'r') as f:\n for line in f:\n self.map_data.append(line)",
"for row, tiles in enumerate(self.map_data):\n for col, tiles in enumerate(tiles)... | <|body_start_0|>
self.entry_point = (0, 0)
self.map_data = []
pass
<|end_body_0|>
<|body_start_1|>
game_folder = path.dirname(__file__)
self.map_data = []
with open(path.join(game_folder, 'map.txt'), 'r') as f:
for line in f:
self.map_data.app... | Map | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Map:
def __init__(self):
"""Nothing fancy yet: just the player entry point and an array of text lines that represent the map"""
<|body_0|>
def load_from_file(self, filename):
"""Load a map from a text file"""
<|body_1|>
def create_sprites_from_data(self,... | stack_v2_sparse_classes_36k_train_022038 | 984 | no_license | [
{
"docstring": "Nothing fancy yet: just the player entry point and an array of text lines that represent the map",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Load a map from a text file",
"name": "load_from_file",
"signature": "def load_from_file(self, filen... | 3 | null | Implement the Python class `Map` described below.
Class description:
Implement the Map class.
Method signatures and docstrings:
- def __init__(self): Nothing fancy yet: just the player entry point and an array of text lines that represent the map
- def load_from_file(self, filename): Load a map from a text file
- def... | Implement the Python class `Map` described below.
Class description:
Implement the Map class.
Method signatures and docstrings:
- def __init__(self): Nothing fancy yet: just the player entry point and an array of text lines that represent the map
- def load_from_file(self, filename): Load a map from a text file
- def... | 349367254f85e3e4273cede067ca950913a1332c | <|skeleton|>
class Map:
def __init__(self):
"""Nothing fancy yet: just the player entry point and an array of text lines that represent the map"""
<|body_0|>
def load_from_file(self, filename):
"""Load a map from a text file"""
<|body_1|>
def create_sprites_from_data(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Map:
def __init__(self):
"""Nothing fancy yet: just the player entry point and an array of text lines that represent the map"""
self.entry_point = (0, 0)
self.map_data = []
pass
def load_from_file(self, filename):
"""Load a map from a text file"""
game_fold... | the_stack_v2_python_sparse | 11-videogames/Referencia/02-Mapa desde fichero y con colisiones/map.py | pythoncanarias/eoi | train | 26 | |
a32d00fec978d9851d70d62bba109da632218e8b | [
"super(NODEBlock, self).__init__()\nself.odefunc = odefunc\nself.cost = 0\nself.rtol = tol\nself.atol = tol",
"self.odefunc.nfe = 0\nself.forward_time = torch.tensor([0, time]).float().type_as(x)\nout = odeint(self.odefunc.to(x), x, self.forward_time, rtol=self.rtol, atol=self.atol)\nself.cost = self.odefunc.nfe\... | <|body_start_0|>
super(NODEBlock, self).__init__()
self.odefunc = odefunc
self.cost = 0
self.rtol = tol
self.atol = tol
<|end_body_0|>
<|body_start_1|>
self.odefunc.nfe = 0
self.forward_time = torch.tensor([0, time]).float().type_as(x)
out = odeint(self.o... | Function to solve an IVP defined as dh(x,t)/dt = f(x,t). We use the differentiable ODE Solver by Chen et.al used in their NeuralODE paper. | NODEBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NODEBlock:
"""Function to solve an IVP defined as dh(x,t)/dt = f(x,t). We use the differentiable ODE Solver by Chen et.al used in their NeuralODE paper."""
def __init__(self, odefunc, tol):
"""Initialization. odefunc: The dynamics function to be used for solving IVP tol: tolerance of... | stack_v2_sparse_classes_36k_train_022039 | 17,869 | permissive | [
{
"docstring": "Initialization. odefunc: The dynamics function to be used for solving IVP tol: tolerance of the ODESolver",
"name": "__init__",
"signature": "def __init__(self, odefunc, tol)"
},
{
"docstring": "Solves the ODE in the forward time.",
"name": "forward",
"signature": "def fo... | 3 | stack_v2_sparse_classes_30k_train_000944 | Implement the Python class `NODEBlock` described below.
Class description:
Function to solve an IVP defined as dh(x,t)/dt = f(x,t). We use the differentiable ODE Solver by Chen et.al used in their NeuralODE paper.
Method signatures and docstrings:
- def __init__(self, odefunc, tol): Initialization. odefunc: The dynam... | Implement the Python class `NODEBlock` described below.
Class description:
Function to solve an IVP defined as dh(x,t)/dt = f(x,t). We use the differentiable ODE Solver by Chen et.al used in their NeuralODE paper.
Method signatures and docstrings:
- def __init__(self, odefunc, tol): Initialization. odefunc: The dynam... | 429c3d431b36358e43c61692e0d02df3ea255635 | <|skeleton|>
class NODEBlock:
"""Function to solve an IVP defined as dh(x,t)/dt = f(x,t). We use the differentiable ODE Solver by Chen et.al used in their NeuralODE paper."""
def __init__(self, odefunc, tol):
"""Initialization. odefunc: The dynamics function to be used for solving IVP tol: tolerance of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NODEBlock:
"""Function to solve an IVP defined as dh(x,t)/dt = f(x,t). We use the differentiable ODE Solver by Chen et.al used in their NeuralODE paper."""
def __init__(self, odefunc, tol):
"""Initialization. odefunc: The dynamics function to be used for solving IVP tol: tolerance of the ODESolve... | the_stack_v2_python_sparse | model/meshflow.py | kierannp/3dsnet | train | 0 |
b5fccf2bd2997aa01ff98409b3da657ba559e7da | [
"super().__init__()\nself.heads = heads\nself.mlp_query = nn.ModuleList([nn.Linear(query_dim, att_dim, bias=False) for _ in range(heads)])\nself.mlp_key = nn.ModuleList([nn.Linear(key_dim, att_dim, bias=False) for _ in range(heads)])",
"cs, es = ([], [])\nfor h in range(self.heads):\n q = query.unsqueeze(1)\n ... | <|body_start_0|>
super().__init__()
self.heads = heads
self.mlp_query = nn.ModuleList([nn.Linear(query_dim, att_dim, bias=False) for _ in range(heads)])
self.mlp_key = nn.ModuleList([nn.Linear(key_dim, att_dim, bias=False) for _ in range(heads)])
<|end_body_0|>
<|body_start_1|>
... | MultiHeadDotAttn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadDotAttn:
def __init__(self, query_dim, key_dim, att_dim, heads):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, key_len=None, scaling=1.0):
""":para... | stack_v2_sparse_classes_36k_train_022040 | 10,910 | no_license | [
{
"docstring": "basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim",
"name": "__init__",
"signature": "def __init__(self, query_dim, key_dim, att_dim, heads)"
},
{
"docstring": ":param query: previous hidden state of the decoder, in shape (batch... | 2 | stack_v2_sparse_classes_30k_train_012108 | Implement the Python class `MultiHeadDotAttn` described below.
Class description:
Implement the MultiHeadDotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim, heads): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- de... | Implement the Python class `MultiHeadDotAttn` described below.
Class description:
Implement the MultiHeadDotAttn class.
Method signatures and docstrings:
- def __init__(self, query_dim, key_dim, att_dim, heads): basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim
- de... | d354b06afbd8ae8172314af524f4f6cdeded363c | <|skeleton|>
class MultiHeadDotAttn:
def __init__(self, query_dim, key_dim, att_dim, heads):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
<|body_0|>
def forward(self, query, keys, value, key_len=None, scaling=1.0):
""":para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadDotAttn:
def __init__(self, query_dim, key_dim, att_dim, heads):
"""basic setting: query_dim is decoder hidden dim key_dim is encoder output dim att_dim is projected dim"""
super().__init__()
self.heads = heads
self.mlp_query = nn.ModuleList([nn.Linear(query_dim, att_d... | the_stack_v2_python_sparse | style_word_alignment/self-attn-mask/model.py | ihungalexhsu/Text-style-tranfer | train | 1 | |
2f0cfa672d6a1069d0647c0dd3593ccaa8527330 | [
"self.InitAttr(node, bool, IES_IMPORT_PRINT_TO_CONSOLE)\nnode[IES_IMPORT_PRINT_TO_CONSOLE] = True\nreturn True",
"if 'txt' in name[-3:]:\n if bytes(probe[0:17]).decode().upper() == 'IES Meta Exporter'.upper():\n return True\nreturn False",
"dialogAllowed = bool(filterflags & c4d.SCENEFILTER_DIALOGSALL... | <|body_start_0|>
self.InitAttr(node, bool, IES_IMPORT_PRINT_TO_CONSOLE)
node[IES_IMPORT_PRINT_TO_CONSOLE] = True
return True
<|end_body_0|>
<|body_start_1|>
if 'txt' in name[-3:]:
if bytes(probe[0:17]).decode().upper() == 'IES Meta Exporter'.upper():
return T... | IESMeta Loader | IESMetaLoader | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IESMetaLoader:
"""IESMeta Loader"""
def Init(self, node):
"""Called when a new instance of this object is created. In this context, this allow to define the option by default for the SceneLoaderPlugin that will be displayed to the user. Returns: bool: False if there was an error, oth... | stack_v2_sparse_classes_36k_train_022041 | 7,074 | permissive | [
{
"docstring": "Called when a new instance of this object is created. In this context, this allow to define the option by default for the SceneLoaderPlugin that will be displayed to the user. Returns: bool: False if there was an error, otherwise True.",
"name": "Init",
"signature": "def Init(self, node)... | 3 | stack_v2_sparse_classes_30k_train_001251 | Implement the Python class `IESMetaLoader` described below.
Class description:
IESMeta Loader
Method signatures and docstrings:
- def Init(self, node): Called when a new instance of this object is created. In this context, this allow to define the option by default for the SceneLoaderPlugin that will be displayed to ... | Implement the Python class `IESMetaLoader` described below.
Class description:
IESMeta Loader
Method signatures and docstrings:
- def Init(self, node): Called when a new instance of this object is created. In this context, this allow to define the option by default for the SceneLoaderPlugin that will be displayed to ... | b1ea3fce533df34094bc3d0bd6460dfb84306e53 | <|skeleton|>
class IESMetaLoader:
"""IESMeta Loader"""
def Init(self, node):
"""Called when a new instance of this object is created. In this context, this allow to define the option by default for the SceneLoaderPlugin that will be displayed to the user. Returns: bool: False if there was an error, oth... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IESMetaLoader:
"""IESMeta Loader"""
def Init(self, node):
"""Called when a new instance of this object is created. In this context, this allow to define the option by default for the SceneLoaderPlugin that will be displayed to the user. Returns: bool: False if there was an error, otherwise True."... | the_stack_v2_python_sparse | plugins/py-ies_meta_r12/py-ies-meta_loader.pyp | PluginCafe/cinema4d_py_sdk_extended | train | 112 |
7f6d58ff48c538625a7d231546ee9cf2af57325b | [
"customer = self.context.get('customer')\nif customer:\n return customer\nelse:\n request = self.context.get('request')\n if request and hasattr(request, 'META'):\n _, json_rh_auth = extract_header(request, RH_IDENTITY_HEADER)\n if json_rh_auth and 'identity' in json_rh_auth and ('org_id' in ... | <|body_start_0|>
customer = self.context.get('customer')
if customer:
return customer
else:
request = self.context.get('request')
if request and hasattr(request, 'META'):
_, json_rh_auth = extract_header(request, RH_IDENTITY_HEADER)
... | Serializer for the User model. | UserSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserSerializer:
"""Serializer for the User model."""
def get_customer_from_context(self):
"""Get customer from context."""
<|body_0|>
def create(self, validated_data):
"""Create a user from validated data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_022042 | 4,185 | permissive | [
{
"docstring": "Get customer from context.",
"name": "get_customer_from_context",
"signature": "def get_customer_from_context(self)"
},
{
"docstring": "Create a user from validated data.",
"name": "create",
"signature": "def create(self, validated_data)"
}
] | 2 | null | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for the User model.
Method signatures and docstrings:
- def get_customer_from_context(self): Get customer from context.
- def create(self, validated_data): Create a user from validated data. | Implement the Python class `UserSerializer` described below.
Class description:
Serializer for the User model.
Method signatures and docstrings:
- def get_customer_from_context(self): Get customer from context.
- def create(self, validated_data): Create a user from validated data.
<|skeleton|>
class UserSerializer:
... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class UserSerializer:
"""Serializer for the User model."""
def get_customer_from_context(self):
"""Get customer from context."""
<|body_0|>
def create(self, validated_data):
"""Create a user from validated data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserSerializer:
"""Serializer for the User model."""
def get_customer_from_context(self):
"""Get customer from context."""
customer = self.context.get('customer')
if customer:
return customer
else:
request = self.context.get('request')
i... | the_stack_v2_python_sparse | koku/api/iam/serializers.py | project-koku/koku | train | 225 |
75677fc5081ef046c2e2caa3183d7de2623760fc | [
"super(QuotasClient, self).__init__(serialize_format, deserialize_format)\nself.auth_token = auth_token\nself.default_headers['X-Auth-Token'] = auth_token\nct = ''.join(['application/', self.serialize_format])\naccept = ''.join(['application/', self.deserialize_format])\nself.default_headers['Content-Type'] = ct\ns... | <|body_start_0|>
super(QuotasClient, self).__init__(serialize_format, deserialize_format)
self.auth_token = auth_token
self.default_headers['X-Auth-Token'] = auth_token
ct = ''.join(['application/', self.serialize_format])
accept = ''.join(['application/', self.deserialize_format... | QuotasClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuotasClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for seri... | stack_v2_sparse_classes_36k_train_022043 | 4,506 | permissive | [
{
"docstring": "@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for serializing requests @type serialize_format: String @param deserialize_format: Format for de-serializing responses... | 5 | null | Implement the Python class `QuotasClient` described below.
Class description:
Implement the QuotasClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @param url: Base URL for the compute service @type url: String @param auth_token: Aut... | Implement the Python class `QuotasClient` described below.
Class description:
Implement the QuotasClient class.
Method signatures and docstrings:
- def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None): @param url: Base URL for the compute service @type url: String @param auth_token: Aut... | 7d49cf6bfd7e1a6e5b739e7de52f2e18e5ccf924 | <|skeleton|>
class QuotasClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for seri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuotasClient:
def __init__(self, url, auth_token, serialize_format=None, deserialize_format=None):
"""@param url: Base URL for the compute service @type url: String @param auth_token: Auth token to be used for all requests @type auth_token: String @param serialize_format: Format for serializing reques... | the_stack_v2_python_sparse | cloudcafe/compute/quotas_api/client.py | kurhula/cloudcafe | train | 0 | |
b518c5937cf6496b2ca763deba391e0bee4b56e3 | [
"stack = []\nqueue = []\nwhile head:\n stack.append(head.val)\n queue.insert(0, head.val)\n head = head.next\nreturn stack == queue",
"stack = []\nworker = head\nrunner = head\nwhile runner is not None and runner.next is not None:\n stack.append(worker.val)\n worker = worker.next\n runner = runn... | <|body_start_0|>
stack = []
queue = []
while head:
stack.append(head.val)
queue.insert(0, head.val)
head = head.next
return stack == queue
<|end_body_0|>
<|body_start_1|>
stack = []
worker = head
runner = head
while run... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def isPalindrome1(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack = []
queue = []
whil... | stack_v2_sparse_classes_36k_train_022044 | 1,518 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "isPalindrome1",
"signature": "def isPalindrome1(self, head)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, head): :type head: ListNode :rtype: bool
- def isPalindrome1(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 isPalindrome(self, head): :type head: ListNode :rtype: bool
- def isPalindrome1(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def isPalind... | f27169285db00d3751c3035f2f4dabad6135c8cc | <|skeleton|>
class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def isPalindrome1(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, head):
""":type head: ListNode :rtype: bool"""
stack = []
queue = []
while head:
stack.append(head.val)
queue.insert(0, head.val)
head = head.next
return stack == queue
def isPalindrome1(self, hea... | the_stack_v2_python_sparse | leet_code/easy/234_palindrome-linked-list.py | baofree/solve-problems-every-day | train | 0 | |
60edad5ad0fe9cfb584bf7f4c1d33446714fd404 | [
"res = []\nqueue = deque([root])\nwhile queue:\n node = queue.popleft()\n if node:\n children = node.children\n res.append(node.val)\n res.append(len(children))\n for child in children:\n queue.append(child)\nreturn res",
"if not data:\n root = None\nelse:\n data... | <|body_start_0|>
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
children = node.children
res.append(node.val)
res.append(len(children))
for child in children:
... | CodecBFS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodecBFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_022045 | 2,626 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 2 | null | Implement the Python class `CodecBFS` described below.
Class description:
Implement the CodecBFS class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | Implement the Python class `CodecBFS` described below.
Class description:
Implement the CodecBFS class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | c937fe19be665ba7ac345e1729ff531f370f30e8 | <|skeleton|>
class CodecBFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CodecBFS:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
children = node.children
res.append(nod... | the_stack_v2_python_sparse | facebook/onsite/serializeAndDeserializeNTree.py | nguyenngochuy91/companyQuestions | train | 1 | |
d2939370be65fa29ddc154ae5dcd55a4cbb80cf9 | [
"seen = set()\nwhile head:\n if head in seen:\n return head\n else:\n seen.add(head)\n head = head.next\nreturn None",
"slow = fast = head\nhas_cycle = False\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n has_cycle = True\n ... | <|body_start_0|>
seen = set()
while head:
if head in seen:
return head
else:
seen.add(head)
head = head.next
return None
<|end_body_0|>
<|body_start_1|>
slow = fast = head
has_cycle = False
while fast an... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode 56ms, beats: 99%"""
<|body_0|>
def detectCycle1(self, head):
""":type head: ListNode :rtype: ListNode 84ms, beats: 11.77%"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_022046 | 1,074 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode 56ms, beats: 99%",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode 84ms, beats: 11.77%",
"name": "detectCycle1",
"signature": "def detectCycle1(self, head)"
... | 2 | stack_v2_sparse_classes_30k_train_005694 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode 56ms, beats: 99%
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode 84ms, beats: 11.77% | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode 56ms, beats: 99%
- def detectCycle1(self, head): :type head: ListNode :rtype: ListNode 84ms, beats: 11.77%
<|s... | 624975f767f6efa1d7361cc077eaebc344d57210 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode 56ms, beats: 99%"""
<|body_0|>
def detectCycle1(self, head):
""":type head: ListNode :rtype: ListNode 84ms, beats: 11.77%"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode 56ms, beats: 99%"""
seen = set()
while head:
if head in seen:
return head
else:
seen.add(head)
head = head.next
return None
d... | the_stack_v2_python_sparse | 142. 环形链表 II.py | dx19910707/LeetCode | train | 0 | |
cf7c76489b810eb91ee462f77a8585bfcb0a20c5 | [
"super(CNNText, self).__init__()\nself.embed = embedding.Embedding(embed)\nself.conv_pool = encoder.ConvMaxpool(in_channels=self.embed.embedding_dim, out_channels=kernel_nums, kernel_sizes=kernel_sizes)\nself.dropout = nn.Dropout(dropout)\nself.fc = nn.Linear(sum(kernel_nums), num_classes)",
"x = self.embed(words... | <|body_start_0|>
super(CNNText, self).__init__()
self.embed = embedding.Embedding(embed)
self.conv_pool = encoder.ConvMaxpool(in_channels=self.embed.embedding_dim, out_channels=kernel_nums, kernel_sizes=kernel_sizes)
self.dropout = nn.Dropout(dropout)
self.fc = nn.Linear(sum(kern... | 使用CNN进行文本分类的模型 'Yoon Kim. 2014. Convolution Neural Networks for Sentence Classification.' | CNNText | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNNText:
"""使用CNN进行文本分类的模型 'Yoon Kim. 2014. Convolution Neural Networks for Sentence Classification.'"""
def __init__(self, embed, num_classes, kernel_nums=(30, 40, 50), kernel_sizes=(1, 3, 5), dropout=0.5):
""":param tuple(int,int),torch.FloatTensor,nn.Embedding,numpy.ndarray embed:... | stack_v2_sparse_classes_36k_train_022047 | 2,670 | permissive | [
{
"docstring": ":param tuple(int,int),torch.FloatTensor,nn.Embedding,numpy.ndarray embed: Embedding的大小(传入tuple(int, int), 第一个int为vocab_zie, 第二个int为embed_dim); 如果为Tensor, Embedding, ndarray等则直接使用该值初始化Embedding :param int num_classes: 一共有多少类 :param int,tuple(int) out_channels: 输出channel的数量。如果为list,则需要与kernel_size... | 3 | stack_v2_sparse_classes_30k_train_016066 | Implement the Python class `CNNText` described below.
Class description:
使用CNN进行文本分类的模型 'Yoon Kim. 2014. Convolution Neural Networks for Sentence Classification.'
Method signatures and docstrings:
- def __init__(self, embed, num_classes, kernel_nums=(30, 40, 50), kernel_sizes=(1, 3, 5), dropout=0.5): :param tuple(int... | Implement the Python class `CNNText` described below.
Class description:
使用CNN进行文本分类的模型 'Yoon Kim. 2014. Convolution Neural Networks for Sentence Classification.'
Method signatures and docstrings:
- def __init__(self, embed, num_classes, kernel_nums=(30, 40, 50), kernel_sizes=(1, 3, 5), dropout=0.5): :param tuple(int... | dffc7a06cdbff2671a3ca73d2398159d91a4a7db | <|skeleton|>
class CNNText:
"""使用CNN进行文本分类的模型 'Yoon Kim. 2014. Convolution Neural Networks for Sentence Classification.'"""
def __init__(self, embed, num_classes, kernel_nums=(30, 40, 50), kernel_sizes=(1, 3, 5), dropout=0.5):
""":param tuple(int,int),torch.FloatTensor,nn.Embedding,numpy.ndarray embed:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNNText:
"""使用CNN进行文本分类的模型 'Yoon Kim. 2014. Convolution Neural Networks for Sentence Classification.'"""
def __init__(self, embed, num_classes, kernel_nums=(30, 40, 50), kernel_sizes=(1, 3, 5), dropout=0.5):
""":param tuple(int,int),torch.FloatTensor,nn.Embedding,numpy.ndarray embed: Embedding的大小... | the_stack_v2_python_sparse | phenobert/utils/fastNLP/models/cnn_text_classification.py | TianlabTech/PhenoBERT | train | 2 |
d8341dda6d0e67210c875019a32db939cd571a6c | [
"main_layer_int_index = getattr(self, 'main_layer', None) or 0\nif index is not None:\n valid_ind = isinstance(index, int) and 0 <= index < len(self)\n valid_label = index in [el.label for el in self]\n if not any([valid_ind, valid_label]):\n raise TypeError('Please supply a suitable index or label ... | <|body_start_0|>
main_layer_int_index = getattr(self, 'main_layer', None) or 0
if index is not None:
valid_ind = isinstance(index, int) and 0 <= index < len(self)
valid_label = index in [el.label for el in self]
if not any([valid_ind, valid_label]):
ra... | CompositeOverlay provides a common baseclass for Overlay classes. | CompositeOverlay | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompositeOverlay:
"""CompositeOverlay provides a common baseclass for Overlay classes."""
def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, index=None, show_legend=False, **kwargs):
"""Computes and adjoins histogram along specified dimension(s). Defaults to fir... | stack_v2_sparse_classes_36k_train_022048 | 12,548 | permissive | [
{
"docstring": "Computes and adjoins histogram along specified dimension(s). Defaults to first value dimension if present otherwise falls back to first key dimension. Args: dimension: Dimension(s) to compute histogram on, Falls back the plot dimensions by default. num_bins (int, optional): Number of bins bin_ra... | 2 | stack_v2_sparse_classes_30k_train_014892 | Implement the Python class `CompositeOverlay` described below.
Class description:
CompositeOverlay provides a common baseclass for Overlay classes.
Method signatures and docstrings:
- def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, index=None, show_legend=False, **kwargs): Computes and adjoin... | Implement the Python class `CompositeOverlay` described below.
Class description:
CompositeOverlay provides a common baseclass for Overlay classes.
Method signatures and docstrings:
- def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, index=None, show_legend=False, **kwargs): Computes and adjoin... | e3dee5443dad84b507734c0a3d2bba8ec44f5653 | <|skeleton|>
class CompositeOverlay:
"""CompositeOverlay provides a common baseclass for Overlay classes."""
def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, index=None, show_legend=False, **kwargs):
"""Computes and adjoins histogram along specified dimension(s). Defaults to fir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CompositeOverlay:
"""CompositeOverlay provides a common baseclass for Overlay classes."""
def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, index=None, show_legend=False, **kwargs):
"""Computes and adjoins histogram along specified dimension(s). Defaults to first value dime... | the_stack_v2_python_sparse | holoviews/core/overlay.py | holoviz/holoviews | train | 1,223 |
350be941f0720ac139c61e422e69aafca0aee117 | [
"self.__subscriptions = []\nself.__publisher = None\nself.drop_policy = 'ignore'",
"try:\n if isinstance(subscription, Subscription):\n sub = Subscribe(subscription, self.__pool, self.myAddress)\n self.send(self.__pool, sub)\nexcept Exception:\n handle_actor_system_fail()",
"try:\n if isi... | <|body_start_0|>
self.__subscriptions = []
self.__publisher = None
self.drop_policy = 'ignore'
<|end_body_0|>
<|body_start_1|>
try:
if isinstance(subscription, Subscription):
sub = Subscribe(subscription, self.__pool, self.myAddress)
self.send... | Publisher. Publishes messages to subscribers. | Publisher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Publisher:
"""Publisher. Publishes messages to subscribers."""
def __init__(self):
"""Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub"""
<|body_0|>
def subscribe(self, subscription):
"""Subscribe a subscripti... | stack_v2_sparse_classes_36k_train_022049 | 3,196 | permissive | [
{
"docstring": "Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Subscribe a subscription actor :param subscription: The subscription to use :type subscription: Subscr... | 6 | stack_v2_sparse_classes_30k_train_020717 | Implement the Python class `Publisher` described below.
Class description:
Publisher. Publishes messages to subscribers.
Method signatures and docstrings:
- def __init__(self): Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub
- def subscribe(self, subscription): S... | Implement the Python class `Publisher` described below.
Class description:
Publisher. Publishes messages to subscribers.
Method signatures and docstrings:
- def __init__(self): Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub
- def subscribe(self, subscription): S... | db93ea9acf58b0da12bcc78ab267e83f3c3c473b | <|skeleton|>
class Publisher:
"""Publisher. Publishes messages to subscribers."""
def __init__(self):
"""Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub"""
<|body_0|>
def subscribe(self, subscription):
"""Subscribe a subscripti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Publisher:
"""Publisher. Publishes messages to subscribers."""
def __init__(self):
"""Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub"""
self.__subscriptions = []
self.__publisher = None
self.drop_policy = 'ignore'
... | the_stack_v2_python_sparse | reactive/streams/base_objects/publisher.py | xyicheng/ReactiveThespian | train | 0 |
bde9ad1cbaa666ffde8bdf117ff2394e36d265e4 | [
"notes = get_list_or_404(Note, notebook__id=notebook_id)\nserializer = Notes(notes, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"notebook = get_object_or_404(Notebook, id=notebook_id)\nserializer = Notes(data=request.data)\nif serializer.is_valid():\n serializer.save(notebook=note... | <|body_start_0|>
notes = get_list_or_404(Note, notebook__id=notebook_id)
serializer = Notes(notes, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
notebook = get_object_or_404(Notebook, id=notebook_id)
serializer = Notes(dat... | NoteList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteList:
def get(self, request, notebook_id):
"""Retrieves all notes from a particular notebook. --- request_serializer: notes.apps.writer.resources.Notes responseMessages: - code: 200 message: Retrieval succeeded. - code: 404 message: Notebook empty or non-existent."""
<|body_0... | stack_v2_sparse_classes_36k_train_022050 | 6,451 | permissive | [
{
"docstring": "Retrieves all notes from a particular notebook. --- request_serializer: notes.apps.writer.resources.Notes responseMessages: - code: 200 message: Retrieval succeeded. - code: 404 message: Notebook empty or non-existent.",
"name": "get",
"signature": "def get(self, request, notebook_id)"
... | 2 | stack_v2_sparse_classes_30k_train_019908 | Implement the Python class `NoteList` described below.
Class description:
Implement the NoteList class.
Method signatures and docstrings:
- def get(self, request, notebook_id): Retrieves all notes from a particular notebook. --- request_serializer: notes.apps.writer.resources.Notes responseMessages: - code: 200 messa... | Implement the Python class `NoteList` described below.
Class description:
Implement the NoteList class.
Method signatures and docstrings:
- def get(self, request, notebook_id): Retrieves all notes from a particular notebook. --- request_serializer: notes.apps.writer.resources.Notes responseMessages: - code: 200 messa... | 310cd45f5d1fad25034a274bc497504259c69907 | <|skeleton|>
class NoteList:
def get(self, request, notebook_id):
"""Retrieves all notes from a particular notebook. --- request_serializer: notes.apps.writer.resources.Notes responseMessages: - code: 200 message: Retrieval succeeded. - code: 404 message: Notebook empty or non-existent."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoteList:
def get(self, request, notebook_id):
"""Retrieves all notes from a particular notebook. --- request_serializer: notes.apps.writer.resources.Notes responseMessages: - code: 200 message: Retrieval succeeded. - code: 404 message: Notebook empty or non-existent."""
notes = get_list_or_40... | the_stack_v2_python_sparse | notes/apps/writer/api.py | NTsystems/NoTes-API | train | 0 | |
35e3491b7b9e7e1b4d1326acad20c191b1a7680b | [
"with self.OutputCapturer() as output:\n cros_payload.DisplayValue('key', 'value')\nstdout = output.GetStdout()\nself.assertEquals(stdout, 'key: value\\n')",
"payload_cmd = cros_payload.PayloadCommand(FakeOption(action='show'))\nself.PatchObject(update_payload, 'Payload', return_value=FakeP... | <|body_start_0|>
with self.OutputCapturer() as output:
cros_payload.DisplayValue('key', 'value')
stdout = output.GetStdout()
self.assertEquals(stdout, 'key: value\n')
<|end_body_0|>
<|body_start_1|>
payload_cmd = cros_payload.PayloadCommand(FakeOption(act... | Test class for our PayloadCommand class. | PayloadCommandTest | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayloadCommandTest:
"""Test class for our PayloadCommand class."""
def testDisplayValue(self):
"""Verify that DisplayValue prints what we expect."""
<|body_0|>
def testRun(self):
"""Verify that Run parses and displays the payload like we expect."""
<|body... | stack_v2_sparse_classes_36k_train_022051 | 5,580 | permissive | [
{
"docstring": "Verify that DisplayValue prints what we expect.",
"name": "testDisplayValue",
"signature": "def testDisplayValue(self)"
},
{
"docstring": "Verify that Run parses and displays the payload like we expect.",
"name": "testRun",
"signature": "def testRun(self)"
},
{
"d... | 4 | null | Implement the Python class `PayloadCommandTest` described below.
Class description:
Test class for our PayloadCommand class.
Method signatures and docstrings:
- def testDisplayValue(self): Verify that DisplayValue prints what we expect.
- def testRun(self): Verify that Run parses and displays the payload like we expe... | Implement the Python class `PayloadCommandTest` described below.
Class description:
Test class for our PayloadCommand class.
Method signatures and docstrings:
- def testDisplayValue(self): Verify that DisplayValue prints what we expect.
- def testRun(self): Verify that Run parses and displays the payload like we expe... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class PayloadCommandTest:
"""Test class for our PayloadCommand class."""
def testDisplayValue(self):
"""Verify that DisplayValue prints what we expect."""
<|body_0|>
def testRun(self):
"""Verify that Run parses and displays the payload like we expect."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PayloadCommandTest:
"""Test class for our PayloadCommand class."""
def testDisplayValue(self):
"""Verify that DisplayValue prints what we expect."""
with self.OutputCapturer() as output:
cros_payload.DisplayValue('key', 'value')
stdout = output.GetStdout()
self... | the_stack_v2_python_sparse | third_party/chromite/cli/cros/cros_payload_unittest.py | zenoalbisser/chromium | train | 0 |
5cdce8d3b987cd4adfd5cd2f3a2ad6c73b80dfa6 | [
"super().__init__(*args, **kwargs)\ngroup_choices = Group.objects.all().values_list('pk', 'name').order_by('name')\nselected_group_ids = []\nif 'instance' in kwargs:\n preset = kwargs['instance']\n selected_group_ids = [group.pk for group in preset.groups_with_permission(Permission.VIEW)]\nself.fields['groups... | <|body_start_0|>
super().__init__(*args, **kwargs)
group_choices = Group.objects.all().values_list('pk', 'name').order_by('name')
selected_group_ids = []
if 'instance' in kwargs:
preset = kwargs['instance']
selected_group_ids = [group.pk for group in preset.groups... | Form for AnnotationPreset admin page. | AnnotationPresetForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnnotationPresetForm:
"""Form for AnnotationPreset admin page."""
def __init__(self, *args, **kwargs):
"""Set the groups choices and initial value."""
<|body_0|>
def save(self, commit):
"""Save changes made to the preset."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_022052 | 2,462 | permissive | [
{
"docstring": "Set the groups choices and initial value.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Save changes made to the preset.",
"name": "save",
"signature": "def save(self, commit)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000997 | Implement the Python class `AnnotationPresetForm` described below.
Class description:
Form for AnnotationPreset admin page.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set the groups choices and initial value.
- def save(self, commit): Save changes made to the preset. | Implement the Python class `AnnotationPresetForm` described below.
Class description:
Form for AnnotationPreset admin page.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Set the groups choices and initial value.
- def save(self, commit): Save changes made to the preset.
<|skeleton|>
class ... | 25c0c45235ef37beb45c1af4c917fbbae6282016 | <|skeleton|>
class AnnotationPresetForm:
"""Form for AnnotationPreset admin page."""
def __init__(self, *args, **kwargs):
"""Set the groups choices and initial value."""
<|body_0|>
def save(self, commit):
"""Save changes made to the preset."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnnotationPresetForm:
"""Form for AnnotationPreset admin page."""
def __init__(self, *args, **kwargs):
"""Set the groups choices and initial value."""
super().__init__(*args, **kwargs)
group_choices = Group.objects.all().values_list('pk', 'name').order_by('name')
selected_... | the_stack_v2_python_sparse | resolwe/flow/admin.py | genialis/resolwe | train | 35 |
38cfe0f5bda3e41a51628ae02c58ccc004238a8e | [
"self.capacity = capacity\nself.deque = deque()\nself.cache = {}",
"ans = -1\nif key in self.cache:\n ans = self.cache[key]\n self.deque.remove(key)\n self.deque.appendleft(key)\nreturn ans",
"if key not in self.cache:\n self.deque.appendleft(key)\nelse:\n self.deque.remove(key)\n self.deque.a... | <|body_start_0|>
self.capacity = capacity
self.deque = deque()
self.cache = {}
<|end_body_0|>
<|body_start_1|>
ans = -1
if key in self.cache:
ans = self.cache[key]
self.deque.remove(key)
self.deque.appendleft(key)
return ans
<|end_body... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
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: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_022053 | 22,676 | 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: None",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache 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: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache 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: None
<|sk... | dbe8eb449e5b112a71bc1cd4eabfd138304de4a3 | <|skeleton|>
class LRUCache:
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: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.deque = deque()
self.cache = {}
def get(self, key):
""":type key: int :rtype: int"""
ans = -1
if key in self.cache:
ans = self.cache[key]
... | the_stack_v2_python_sparse | leetcode/leetcode_special.py | Rivarrl/leetcode_python | train | 3 | |
64ea80f07182ca50204cb0a1521e9379d18bdb09 | [
"super(SchedulingOptions, self).__init__()\nself.nodes = None\nself.ppn = None\nself.mail = None\nself.full_node = None\nself.walltime = None\nself.local_jobscript_path = None",
"options = cls()\nif 'nodes' in dictionary:\n options.nodes = dictionary['nodes']\nif 'ppn' in dictionary:\n options.ppn = diction... | <|body_start_0|>
super(SchedulingOptions, self).__init__()
self.nodes = None
self.ppn = None
self.mail = None
self.full_node = None
self.walltime = None
self.local_jobscript_path = None
<|end_body_0|>
<|body_start_1|>
options = cls()
if 'nodes' in... | This function ... | SchedulingOptions | [
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulingOptions:
"""This function ..."""
def __init__(self):
"""The constructor ..."""
<|body_0|>
def from_dict(cls, dictionary):
"""This function ... :param dictionary: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Scheduling... | stack_v2_sparse_classes_36k_train_022054 | 7,769 | permissive | [
{
"docstring": "The constructor ...",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "This function ... :param dictionary: :return:",
"name": "from_dict",
"signature": "def from_dict(cls, dictionary)"
}
] | 2 | null | Implement the Python class `SchedulingOptions` described below.
Class description:
This function ...
Method signatures and docstrings:
- def __init__(self): The constructor ...
- def from_dict(cls, dictionary): This function ... :param dictionary: :return: | Implement the Python class `SchedulingOptions` described below.
Class description:
This function ...
Method signatures and docstrings:
- def __init__(self): The constructor ...
- def from_dict(cls, dictionary): This function ... :param dictionary: :return:
<|skeleton|>
class SchedulingOptions:
"""This function .... | 62b2339beb2eb956565e1605d44d92f934361ad7 | <|skeleton|>
class SchedulingOptions:
"""This function ..."""
def __init__(self):
"""The constructor ..."""
<|body_0|>
def from_dict(cls, dictionary):
"""This function ... :param dictionary: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchedulingOptions:
"""This function ..."""
def __init__(self):
"""The constructor ..."""
super(SchedulingOptions, self).__init__()
self.nodes = None
self.ppn = None
self.mail = None
self.full_node = None
self.walltime = None
self.local_jobsc... | the_stack_v2_python_sparse | CAAPR/CAAPR_AstroMagic/PTS/pts/core/launch/options.py | Stargrazer82301/CAAPR | train | 8 |
a200e69d40d66041531d50468554229dea2a34c3 | [
"super().__init__()\nself.listening_socket = listening_socket\nself.on_recv_callback = on_recv_callback\nself.should_stop = threading.Event()",
"while not self.should_stop.is_set():\n try:\n conn, address = self.listening_socket.accept()\n data = conn.recv(len('hello'))\n self.on_recv_call... | <|body_start_0|>
super().__init__()
self.listening_socket = listening_socket
self.on_recv_callback = on_recv_callback
self.should_stop = threading.Event()
<|end_body_0|>
<|body_start_1|>
while not self.should_stop.is_set():
try:
conn, address = self.l... | A thread used by the music server to accept clients asynchronously. | RecvClientsThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecvClientsThread:
"""A thread used by the music server to accept clients asynchronously."""
def __init__(self, listening_socket, on_recv_callback):
"""Initialize the receive thread, with the given socket and the goven callback function. The callback will be triggered for every clien... | stack_v2_sparse_classes_36k_train_022055 | 8,439 | no_license | [
{
"docstring": "Initialize the receive thread, with the given socket and the goven callback function. The callback will be triggered for every clients that established a new connection with the server. :param listening_socket: The socket to accept clients to. Must be bound and in listening mode. :param on_recv_... | 2 | stack_v2_sparse_classes_30k_train_020488 | Implement the Python class `RecvClientsThread` described below.
Class description:
A thread used by the music server to accept clients asynchronously.
Method signatures and docstrings:
- def __init__(self, listening_socket, on_recv_callback): Initialize the receive thread, with the given socket and the goven callback... | Implement the Python class `RecvClientsThread` described below.
Class description:
A thread used by the music server to accept clients asynchronously.
Method signatures and docstrings:
- def __init__(self, listening_socket, on_recv_callback): Initialize the receive thread, with the given socket and the goven callback... | 80527cb1fdcab50ea733105831566e017d88c825 | <|skeleton|>
class RecvClientsThread:
"""A thread used by the music server to accept clients asynchronously."""
def __init__(self, listening_socket, on_recv_callback):
"""Initialize the receive thread, with the given socket and the goven callback function. The callback will be triggered for every clien... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecvClientsThread:
"""A thread used by the music server to accept clients asynchronously."""
def __init__(self, listening_socket, on_recv_callback):
"""Initialize the receive thread, with the given socket and the goven callback function. The callback will be triggered for every clients that estab... | the_stack_v2_python_sparse | syncalong/syncalong/server/music_server.py | shirasael/20588 | train | 1 |
88abadaa99576e4fab999f949233a0d725b85dcf | [
"try:\n desc = '{:.1f} %'.format(self.ct_success / self.count * 100)\nexcept ZeroDivisionError:\n desc = '-'\nreturn desc",
"if self.ct_success == 0:\n return 0\nreturn round(self.ms_success / self.ct_success)"
] | <|body_start_0|>
try:
desc = '{:.1f} %'.format(self.ct_success / self.count * 100)
except ZeroDivisionError:
desc = '-'
return desc
<|end_body_0|>
<|body_start_1|>
if self.ct_success == 0:
return 0
return round(self.ms_success / self.ct_succes... | 第三方请求统计 | CountThirdApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountThirdApi:
"""第三方请求统计"""
def rate(self):
"""成功比例"""
<|body_0|>
def ms_avg(self):
"""成功平均响应时间(ms)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
desc = '{:.1f} %'.format(self.ct_success / self.count * 100)
except Zer... | stack_v2_sparse_classes_36k_train_022056 | 2,642 | no_license | [
{
"docstring": "成功比例",
"name": "rate",
"signature": "def rate(self)"
},
{
"docstring": "成功平均响应时间(ms)",
"name": "ms_avg",
"signature": "def ms_avg(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008984 | Implement the Python class `CountThirdApi` described below.
Class description:
第三方请求统计
Method signatures and docstrings:
- def rate(self): 成功比例
- def ms_avg(self): 成功平均响应时间(ms) | Implement the Python class `CountThirdApi` described below.
Class description:
第三方请求统计
Method signatures and docstrings:
- def rate(self): 成功比例
- def ms_avg(self): 成功平均响应时间(ms)
<|skeleton|>
class CountThirdApi:
"""第三方请求统计"""
def rate(self):
"""成功比例"""
<|body_0|>
def ms_avg(self):
... | b7ed6588e13d2916a4162d56509d2794742a1eb1 | <|skeleton|>
class CountThirdApi:
"""第三方请求统计"""
def rate(self):
"""成功比例"""
<|body_0|>
def ms_avg(self):
"""成功平均响应时间(ms)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountThirdApi:
"""第三方请求统计"""
def rate(self):
"""成功比例"""
try:
desc = '{:.1f} %'.format(self.ct_success / self.count * 100)
except ZeroDivisionError:
desc = '-'
return desc
def ms_avg(self):
"""成功平均响应时间(ms)"""
if self.ct_success =... | the_stack_v2_python_sparse | server/applibs/monitor/models/count_third.py | fanshuai/kubrick | train | 0 |
5d8715dd02feff4e13919858051abeb5b6828011 | [
"self.min = np.array([-2.903534, -2.903534])\nself.value = -39.16599 * 2.0\nself.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])\nself.n = 2\nself.smooth = True\nself.info = [True, True, True]\nself.latex_name = 'Styblinski-Tang Function'\nself.latex_type = 'Other'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = \\\\fra... | <|body_start_0|>
self.min = np.array([-2.903534, -2.903534])
self.value = -39.16599 * 2.0
self.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])
self.n = 2
self.smooth = True
self.info = [True, True, True]
self.latex_name = 'Styblinski-Tang Function'
self.late... | Styblinski-Tang Function. | StyblinskiTang | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyblinskiTang:
"""Styblinski-Tang Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
""... | stack_v2_sparse_classes_36k_train_022057 | 1,639 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
},
{
"docstring": "Grad function.",
"name": "grad",
"signature": "def grad(self, x)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_008291 | Implement the Python class `StyblinskiTang` described below.
Class description:
Styblinski-Tang Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function. | Implement the Python class `StyblinskiTang` described below.
Class description:
Styblinski-Tang Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function.
<|skeleton|>
class StyblinskiTang:... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class StyblinskiTang:
"""Styblinski-Tang Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StyblinskiTang:
"""Styblinski-Tang Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([-2.903534, -2.903534])
self.value = -39.16599 * 2.0
self.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])
self.n = 2
self.smooth = True
self.inf... | the_stack_v2_python_sparse | ctf/functions2d/styblinski_tang.py | cntaylor/ctf | train | 1 |
1f9db630d99dc883d96748263909c293af90eb94 | [
"self.num_feat_per_dim = num_feat_per_dim\nself.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))\nself.freq = to.randn(num_feat_per_dim, inp_dim)\nif not isinstance(bandwidth, to.Tensor):\n bandwidth = to.from_numpy(np.asanyarray(bandwidth))\nself.freq *= to.sqrt(to.tensor(2.0) / to.atleast_2d(bandwidth))\nsel... | <|body_start_0|>
self.num_feat_per_dim = num_feat_per_dim
self.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))
self.freq = to.randn(num_feat_per_dim, inp_dim)
if not isinstance(bandwidth, to.Tensor):
bandwidth = to.from_numpy(np.asanyarray(bandwidth))
self.freq *= ... | Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007 | RFFeat | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RFFeat:
"""Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor], use_cuda: bool=False):
"""Gaussian ... | stack_v2_sparse_classes_36k_train_022058 | 19,215 | permissive | [
{
"docstring": "Gaussian kernel: $k(x,y) = \\\\exp(-\\\\sigma**2 / (2*d) * ||x-y||^2)$ Sample from $\\\\mathcal{N}(0,1)$ and scale the result by $\\\\sigma / \\\\sqrt{2*d}$ :param inp_dim: flat dimension of the inputs i.e. the observations, called $d$ in [1] :param num_feat_per_dim: number of random Fourier fea... | 2 | null | Implement the Python class `RFFeat` described below.
Class description:
Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
Method signatures and docstrings:
- def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float,... | Implement the Python class `RFFeat` described below.
Class description:
Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
Method signatures and docstrings:
- def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float,... | d7e9cd191ccb318d5f1e580babc2fc38b5b3675a | <|skeleton|>
class RFFeat:
"""Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor], use_cuda: bool=False):
"""Gaussian ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RFFeat:
"""Random Fourier (RF) features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor], use_cuda: bool=False):
"""Gaussian kernel: $k(x,... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/features.py | 1abner1/SimuRLacra | train | 0 |
b341a80d0b98d20bd612ab580d168513811c5f8f | [
"vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU'))\nslice_vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU')[2:4])\nself.assertEqual(vowels[2:4], slice_vowels, 'Wrong slicing in CustomOrderedDict')\nself.assertEqual(vowels[2:-1], slice_vowels, 'Wrong slicing in CustomOrderedDict')\nself.assertEqual(vowe... | <|body_start_0|>
vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU'))
slice_vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU')[2:4])
self.assertEqual(vowels[2:4], slice_vowels, 'Wrong slicing in CustomOrderedDict')
self.assertEqual(vowels[2:-1], slice_vowels, 'Wrong slicing in C... | Test exercise mod 06 CustomOrderedDict | TestCustomOrderedDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCustomOrderedDict:
"""Test exercise mod 06 CustomOrderedDict"""
def test_slicing(self):
"""Check __getitem__ customization (slicing) of CustomOrderedDict"""
<|body_0|>
def test_addition(self):
"""Check __add__ customization of CustomOrderedDict It returns a n... | stack_v2_sparse_classes_36k_train_022059 | 8,327 | no_license | [
{
"docstring": "Check __getitem__ customization (slicing) of CustomOrderedDict",
"name": "test_slicing",
"signature": "def test_slicing(self)"
},
{
"docstring": "Check __add__ customization of CustomOrderedDict It returns a new CustomOrderedDict with content of the first CustomOrderedDict update... | 3 | stack_v2_sparse_classes_30k_test_001137 | Implement the Python class `TestCustomOrderedDict` described below.
Class description:
Test exercise mod 06 CustomOrderedDict
Method signatures and docstrings:
- def test_slicing(self): Check __getitem__ customization (slicing) of CustomOrderedDict
- def test_addition(self): Check __add__ customization of CustomOrder... | Implement the Python class `TestCustomOrderedDict` described below.
Class description:
Test exercise mod 06 CustomOrderedDict
Method signatures and docstrings:
- def test_slicing(self): Check __getitem__ customization (slicing) of CustomOrderedDict
- def test_addition(self): Check __add__ customization of CustomOrder... | 8f082201e24f0f2b991d9388500fdbf95d6f073d | <|skeleton|>
class TestCustomOrderedDict:
"""Test exercise mod 06 CustomOrderedDict"""
def test_slicing(self):
"""Check __getitem__ customization (slicing) of CustomOrderedDict"""
<|body_0|>
def test_addition(self):
"""Check __add__ customization of CustomOrderedDict It returns a n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCustomOrderedDict:
"""Test exercise mod 06 CustomOrderedDict"""
def test_slicing(self):
"""Check __getitem__ customization (slicing) of CustomOrderedDict"""
vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU'))
slice_vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU')[2... | the_stack_v2_python_sparse | intermediate/exercises/mod_04_data_model/tests_mod_04.py | garciacastano09/pycourse | train | 0 |
de3d13b1d01fab85d2e0be18404e8e36437659a0 | [
"if cumulRet == ():\n self.x = returnSeries\nelif cumulRet[0] == 'cumulRet':\n self.x = self.ConvertReturnSeries(returnSeries)\nelse:\n raise 'Incorrect Input'\nself.dataFreq = dataFreq\nself.sharpeRatio = self.CalcSharpe()",
"self.scaling = self.DetermineScaling(self.dataFreq)\nself.avg = np.nanmean(sel... | <|body_start_0|>
if cumulRet == ():
self.x = returnSeries
elif cumulRet[0] == 'cumulRet':
self.x = self.ConvertReturnSeries(returnSeries)
else:
raise 'Incorrect Input'
self.dataFreq = dataFreq
self.sharpeRatio = self.CalcSharpe()
<|end_body_0|>... | SharpeRatio | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharpeRatio:
def __init__(self, returnSeries, dataFreq, *cumulRet):
"""Constructor"""
<|body_0|>
def CalcSharpe(self):
"""Calc Sharpe Ratio"""
<|body_1|>
def DetermineScaling(dataFreq):
"""Determine Conversion Scaling for different data frequency... | stack_v2_sparse_classes_36k_train_022060 | 1,838 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, returnSeries, dataFreq, *cumulRet)"
},
{
"docstring": "Calc Sharpe Ratio",
"name": "CalcSharpe",
"signature": "def CalcSharpe(self)"
},
{
"docstring": "Determine Conversion Scaling for different da... | 4 | stack_v2_sparse_classes_30k_train_015687 | Implement the Python class `SharpeRatio` described below.
Class description:
Implement the SharpeRatio class.
Method signatures and docstrings:
- def __init__(self, returnSeries, dataFreq, *cumulRet): Constructor
- def CalcSharpe(self): Calc Sharpe Ratio
- def DetermineScaling(dataFreq): Determine Conversion Scaling ... | Implement the Python class `SharpeRatio` described below.
Class description:
Implement the SharpeRatio class.
Method signatures and docstrings:
- def __init__(self, returnSeries, dataFreq, *cumulRet): Constructor
- def CalcSharpe(self): Calc Sharpe Ratio
- def DetermineScaling(dataFreq): Determine Conversion Scaling ... | 641545ff06776fe18062962a09ed3f71aca6fe6c | <|skeleton|>
class SharpeRatio:
def __init__(self, returnSeries, dataFreq, *cumulRet):
"""Constructor"""
<|body_0|>
def CalcSharpe(self):
"""Calc Sharpe Ratio"""
<|body_1|>
def DetermineScaling(dataFreq):
"""Determine Conversion Scaling for different data frequency... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SharpeRatio:
def __init__(self, returnSeries, dataFreq, *cumulRet):
"""Constructor"""
if cumulRet == ():
self.x = returnSeries
elif cumulRet[0] == 'cumulRet':
self.x = self.ConvertReturnSeries(returnSeries)
else:
raise 'Incorrect Input'
... | the_stack_v2_python_sparse | SharpeRatio.py | LuoyingLi2991/Technical-Tools | train | 0 | |
e13bfc1c137095254875eca07bd60e7d926f4ea0 | [
"account = self.model(email=self.normalize_email(email), first_name=kwargs.get('first_name', None), last_name=kwargs.get('last_name', None))\naccount.set_password(password)\naccount.save()\nreturn account",
"account = self.create_user(email, password, **kwargs)\naccount.is_admin = True\naccount.save()\nreturn acc... | <|body_start_0|>
account = self.model(email=self.normalize_email(email), first_name=kwargs.get('first_name', None), last_name=kwargs.get('last_name', None))
account.set_password(password)
account.save()
return account
<|end_body_0|>
<|body_start_1|>
account = self.create_user(em... | Contains functionality to operate with User registration | AccountManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountManager:
"""Contains functionality to operate with User registration"""
def create_user(self, email: str, password: str=None, **kwargs):
"""Create User model :param email: User's email :param password: User's password :param kwargs: Kwargs, sent from views :return: User object... | stack_v2_sparse_classes_36k_train_022061 | 2,989 | no_license | [
{
"docstring": "Create User model :param email: User's email :param password: User's password :param kwargs: Kwargs, sent from views :return: User object",
"name": "create_user",
"signature": "def create_user(self, email: str, password: str=None, **kwargs)"
},
{
"docstring": "Create user with ad... | 2 | stack_v2_sparse_classes_30k_train_021026 | Implement the Python class `AccountManager` described below.
Class description:
Contains functionality to operate with User registration
Method signatures and docstrings:
- def create_user(self, email: str, password: str=None, **kwargs): Create User model :param email: User's email :param password: User's password :p... | Implement the Python class `AccountManager` described below.
Class description:
Contains functionality to operate with User registration
Method signatures and docstrings:
- def create_user(self, email: str, password: str=None, **kwargs): Create User model :param email: User's email :param password: User's password :p... | dc07feb22d2ad7357dfef27f8940c8f94db3dc3b | <|skeleton|>
class AccountManager:
"""Contains functionality to operate with User registration"""
def create_user(self, email: str, password: str=None, **kwargs):
"""Create User model :param email: User's email :param password: User's password :param kwargs: Kwargs, sent from views :return: User object... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountManager:
"""Contains functionality to operate with User registration"""
def create_user(self, email: str, password: str=None, **kwargs):
"""Create User model :param email: User's email :param password: User's password :param kwargs: Kwargs, sent from views :return: User object"""
a... | the_stack_v2_python_sparse | messageExchangeACS/authentication/models.py | yuriiZherebukh/MessageExchangeACS | train | 1 |
a25e0473d5c2ce4cab4ac293800d96d1d4fbf45f | [
"QUiLoader.__init__(self, baseinstance)\nself.baseinstance = baseinstance\nself.customWidgets = customWidgets",
"if parent is None and self.baseinstance:\n return self.baseinstance\nelse:\n if class_name in self.availableWidgets():\n widget = QUiLoader.createWidget(self, class_name, parent, name)\n ... | <|body_start_0|>
QUiLoader.__init__(self, baseinstance)
self.baseinstance = baseinstance
self.customWidgets = customWidgets
<|end_body_0|>
<|body_start_1|>
if parent is None and self.baseinstance:
return self.baseinstance
else:
if class_name in self.avail... | Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a allinone instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-level class. This mimics the behaviou... | EzQtUILoader | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EzQtUILoader:
"""Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a allinone instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the t... | stack_v2_sparse_classes_36k_train_022062 | 7,358 | permissive | [
{
"docstring": "Create a loader for the given ``baseinstance``. The user interface is created in ``baseinstance``, which must be an instance of the top-level class in the user interface to load, or a subclass thereof. ``customWidgets`` is a dictionary mapping from class name to class object for widgets that you... | 2 | null | Implement the Python class `EzQtUILoader` described below.
Class description:
Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a allinone instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user int... | Implement the Python class `EzQtUILoader` described below.
Class description:
Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a allinone instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user int... | d0c1c5237523751248fb78973428f42c150cb1dc | <|skeleton|>
class EzQtUILoader:
"""Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a allinone instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EzQtUILoader:
"""Subclass :class:`~PySide.QtUiTools.QUiLoader` to create the user interface in a allinone instance. Unlike :class:`~PySide.QtUiTools.QUiLoader` itself this class does not create a new instance of the top-level widget, but creates the user interface in an existing instance of the top-level clas... | the_stack_v2_python_sparse | mylib/ext/pyside2/ui_loader.py | mo-han/mo-han-toolbox | train | 27 |
c12e21e4857541b39113fe70d8605e3fe6c26398 | [
"try:\n self.ssm = ssm()\nexcept:\n self.ssm = ssm",
"n_pos_vel_states = int(self.ssm.n_states) - 1\nif len(target_pos) < n_pos_vel_states:\n target_vel = np.zeros_like(target_pos)\n offset_val = 1\n target_state = np.hstack([target_pos, target_vel, 1]).reshape(-1, 1)\nelse:\n target_state = np.... | <|body_start_0|>
try:
self.ssm = ssm()
except:
self.ssm = ssm
<|end_body_0|>
<|body_start_1|>
n_pos_vel_states = int(self.ssm.n_states) - 1
if len(target_pos) < n_pos_vel_states:
target_vel = np.zeros_like(target_pos)
offset_val = 1
... | Assumes that the target state of the BMI is to move to the task-specified position with zero velocity | ZeroVelocityGoal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZeroVelocityGoal:
"""Assumes that the target state of the BMI is to move to the task-specified position with zero velocity"""
def __init__(self, ssm=None):
"""Constructor for ZeroVelocityGoal Parameters ---------- ssm : state_space_models.StateSpace instance The state-space model of ... | stack_v2_sparse_classes_36k_train_022063 | 13,329 | permissive | [
{
"docstring": "Constructor for ZeroVelocityGoal Parameters ---------- ssm : state_space_models.StateSpace instance The state-space model of the Decoder that is being assisted/adapted. Not needed for this particular method Returns ------- ZeroVelocityGoal instance",
"name": "__init__",
"signature": "def... | 2 | null | Implement the Python class `ZeroVelocityGoal` described below.
Class description:
Assumes that the target state of the BMI is to move to the task-specified position with zero velocity
Method signatures and docstrings:
- def __init__(self, ssm=None): Constructor for ZeroVelocityGoal Parameters ---------- ssm : state_s... | Implement the Python class `ZeroVelocityGoal` described below.
Class description:
Assumes that the target state of the BMI is to move to the task-specified position with zero velocity
Method signatures and docstrings:
- def __init__(self, ssm=None): Constructor for ZeroVelocityGoal Parameters ---------- ssm : state_s... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class ZeroVelocityGoal:
"""Assumes that the target state of the BMI is to move to the task-specified position with zero velocity"""
def __init__(self, ssm=None):
"""Constructor for ZeroVelocityGoal Parameters ---------- ssm : state_space_models.StateSpace instance The state-space model of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZeroVelocityGoal:
"""Assumes that the target state of the BMI is to move to the task-specified position with zero velocity"""
def __init__(self, ssm=None):
"""Constructor for ZeroVelocityGoal Parameters ---------- ssm : state_space_models.StateSpace instance The state-space model of the Decoder t... | the_stack_v2_python_sparse | riglib/bmi/goal_calculators.py | carmenalab/brain-python-interface | train | 9 |
b75326256032b4b60727982a67443210bbecb2a7 | [
"from apysc.file import file_util\nfile_path: str = _get_indent_num_file_path()\ncurrent_indent_num: int = get_current_indent_num()\ncurrent_indent_num += 1\nfile_util.save_plain_txt(txt=str(current_indent_num), file_path=file_path)",
"from apysc.file import file_util\nfile_path: str = _get_indent_num_file_path()... | <|body_start_0|>
from apysc.file import file_util
file_path: str = _get_indent_num_file_path()
current_indent_num: int = get_current_indent_num()
current_indent_num += 1
file_util.save_plain_txt(txt=str(current_indent_num), file_path=file_path)
<|end_body_0|>
<|body_start_1|>
... | Class implementation for increment and decrement indentation number. Basically use this class at with statement. | Indent | [
"MIT",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Indent:
"""Class implementation for increment and decrement indentation number. Basically use this class at with statement."""
def __enter__(self) -> None:
"""Method to be used by with statement. This method will increment indentation number."""
<|body_0|>
def __exit__(s... | stack_v2_sparse_classes_36k_train_022064 | 3,231 | permissive | [
{
"docstring": "Method to be used by with statement. This method will increment indentation number.",
"name": "__enter__",
"signature": "def __enter__(self) -> None"
},
{
"docstring": "Method to be used by with statement. This method will decrement indentation number. Parameters ---------- *args... | 2 | null | Implement the Python class `Indent` described below.
Class description:
Class implementation for increment and decrement indentation number. Basically use this class at with statement.
Method signatures and docstrings:
- def __enter__(self) -> None: Method to be used by with statement. This method will increment inde... | Implement the Python class `Indent` described below.
Class description:
Class implementation for increment and decrement indentation number. Basically use this class at with statement.
Method signatures and docstrings:
- def __enter__(self) -> None: Method to be used by with statement. This method will increment inde... | 5c6a4674e2e9684cb2cb1325dc9b070879d4d355 | <|skeleton|>
class Indent:
"""Class implementation for increment and decrement indentation number. Basically use this class at with statement."""
def __enter__(self) -> None:
"""Method to be used by with statement. This method will increment indentation number."""
<|body_0|>
def __exit__(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Indent:
"""Class implementation for increment and decrement indentation number. Basically use this class at with statement."""
def __enter__(self) -> None:
"""Method to be used by with statement. This method will increment indentation number."""
from apysc.file import file_util
fi... | the_stack_v2_python_sparse | apysc/expression/indent_num.py | TrendingTechnology/apysc | train | 0 |
e531b15b2e4a6704abdfabcc64c44b104ec86230 | [
"super().__init__(model, gpu_str)\nself.temperature = temperature\nself.build()",
"self.audio_ph = self.graph.get_tensor_by_name('inputs:0')\nself.logits = self.graph.get_tensor_by_name('model/logits/logits-matmul/add:0')\nwith self.graph.as_default():\n self.soft_label = tf.nn.softmax(self.logits / self.tempe... | <|body_start_0|>
super().__init__(model, gpu_str)
self.temperature = temperature
self.build()
<|end_body_0|>
<|body_start_1|>
self.audio_ph = self.graph.get_tensor_by_name('inputs:0')
self.logits = self.graph.get_tensor_by_name('model/logits/logits-matmul/add:0')
with se... | class of Teacher | Teacher | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Teacher:
"""class of Teacher"""
def __init__(self, model, gpu_str=None, temperature=1.0):
"""model: saved model dir, ckpt dir or frozen_graph_pb path gpu_str: list of gpu devices. e.g. '' for cpu, '0,1' for gpu 0,1"""
<|body_0|>
def build(self):
"""build"""
... | stack_v2_sparse_classes_36k_train_022065 | 1,866 | permissive | [
{
"docstring": "model: saved model dir, ckpt dir or frozen_graph_pb path gpu_str: list of gpu devices. e.g. '' for cpu, '0,1' for gpu 0,1",
"name": "__init__",
"signature": "def __init__(self, model, gpu_str=None, temperature=1.0)"
},
{
"docstring": "build",
"name": "build",
"signature":... | 3 | null | Implement the Python class `Teacher` described below.
Class description:
class of Teacher
Method signatures and docstrings:
- def __init__(self, model, gpu_str=None, temperature=1.0): model: saved model dir, ckpt dir or frozen_graph_pb path gpu_str: list of gpu devices. e.g. '' for cpu, '0,1' for gpu 0,1
- def build(... | Implement the Python class `Teacher` described below.
Class description:
class of Teacher
Method signatures and docstrings:
- def __init__(self, model, gpu_str=None, temperature=1.0): model: saved model dir, ckpt dir or frozen_graph_pb path gpu_str: list of gpu devices. e.g. '' for cpu, '0,1' for gpu 0,1
- def build(... | 7eb4e3be578a680737616efff6858d280595ff48 | <|skeleton|>
class Teacher:
"""class of Teacher"""
def __init__(self, model, gpu_str=None, temperature=1.0):
"""model: saved model dir, ckpt dir or frozen_graph_pb path gpu_str: list of gpu devices. e.g. '' for cpu, '0,1' for gpu 0,1"""
<|body_0|>
def build(self):
"""build"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Teacher:
"""class of Teacher"""
def __init__(self, model, gpu_str=None, temperature=1.0):
"""model: saved model dir, ckpt dir or frozen_graph_pb path gpu_str: list of gpu devices. e.g. '' for cpu, '0,1' for gpu 0,1"""
super().__init__(model, gpu_str)
self.temperature = temperature... | the_stack_v2_python_sparse | delta/serving/knowledge_distilling.py | luffywalf/delta | train | 1 |
19d8356a3b0e4138ec6e25fc9eb1fe6d066c26be | [
"try:\n if not self.args or not self.args.isdigit():\n raise FashionError('Requires an ID #.')\n elif not self.switches:\n self.display_item_snapshots()\n elif 'delete' in self.switches:\n self.reverse_snapshot(self.args)\n else:\n raise FashionError('Invalid Switch')\nexcept... | <|body_start_0|>
try:
if not self.args or not self.args.isdigit():
raise FashionError('Requires an ID #.')
elif not self.switches:
self.display_item_snapshots()
elif 'delete' in self.switches:
self.reverse_snapshot(self.args)
... | Admin commands for modeling. Usage: @admin_fashion <item ID#> @admin_fashion/delete <snapshot ID#> Shows the #IDs of model snapshot that was generated whenever the item was modeled. /Delete will remove all status awarded, refund AP, and delete the snapshot, effectively reversing the model command. | CmdAdminFashion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CmdAdminFashion:
"""Admin commands for modeling. Usage: @admin_fashion <item ID#> @admin_fashion/delete <snapshot ID#> Shows the #IDs of model snapshot that was generated whenever the item was modeled. /Delete will remove all status awarded, refund AP, and delete the snapshot, effectively reversi... | stack_v2_sparse_classes_36k_train_022066 | 15,821 | permissive | [
{
"docstring": "Execute command",
"name": "func",
"signature": "def func(self)"
},
{
"docstring": "displays snapshots",
"name": "display_item_snapshots",
"signature": "def display_item_snapshots(self)"
},
{
"docstring": "reverses snapshots",
"name": "reverse_snapshot",
"s... | 3 | null | Implement the Python class `CmdAdminFashion` described below.
Class description:
Admin commands for modeling. Usage: @admin_fashion <item ID#> @admin_fashion/delete <snapshot ID#> Shows the #IDs of model snapshot that was generated whenever the item was modeled. /Delete will remove all status awarded, refund AP, and d... | Implement the Python class `CmdAdminFashion` described below.
Class description:
Admin commands for modeling. Usage: @admin_fashion <item ID#> @admin_fashion/delete <snapshot ID#> Shows the #IDs of model snapshot that was generated whenever the item was modeled. /Delete will remove all status awarded, refund AP, and d... | 363a1f14fd1a640580a4bf4486a1afe776757557 | <|skeleton|>
class CmdAdminFashion:
"""Admin commands for modeling. Usage: @admin_fashion <item ID#> @admin_fashion/delete <snapshot ID#> Shows the #IDs of model snapshot that was generated whenever the item was modeled. /Delete will remove all status awarded, refund AP, and delete the snapshot, effectively reversi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CmdAdminFashion:
"""Admin commands for modeling. Usage: @admin_fashion <item ID#> @admin_fashion/delete <snapshot ID#> Shows the #IDs of model snapshot that was generated whenever the item was modeled. /Delete will remove all status awarded, refund AP, and delete the snapshot, effectively reversing the model ... | the_stack_v2_python_sparse | world/fashion/fashion_commands.py | Arx-Game/arxcode | train | 52 |
f61ba8625335365b5fbaf0c6702c1422b5feba56 | [
"result = g.db.query(MatchQueuePlayer, CorePlayer).filter(MatchQueuePlayer.player_id == player_id, CorePlayer.player_id == player_id).order_by(-MatchQueuePlayer.id).first()\nif not result:\n abort(http_client.NOT_FOUND, message='Player is not in the match queue')\nserver = None\nmy_matchqueueplayer, my_player = ... | <|body_start_0|>
result = g.db.query(MatchQueuePlayer, CorePlayer).filter(MatchQueuePlayer.player_id == player_id, CorePlayer.player_id == player_id).order_by(-MatchQueuePlayer.id).first()
if not result:
abort(http_client.NOT_FOUND, message='Player is not in the match queue')
server ... | MatchQueueEntryAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchQueueEntryAPI:
def get(self, player_id):
"""Find a player in the queue by ID"""
<|body_0|>
def delete(self, player_id):
"""Remove a player from the queue"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = g.db.query(MatchQueuePlayer, Core... | stack_v2_sparse_classes_36k_train_022067 | 10,007 | permissive | [
{
"docstring": "Find a player in the queue by ID",
"name": "get",
"signature": "def get(self, player_id)"
},
{
"docstring": "Remove a player from the queue",
"name": "delete",
"signature": "def delete(self, player_id)"
}
] | 2 | null | Implement the Python class `MatchQueueEntryAPI` described below.
Class description:
Implement the MatchQueueEntryAPI class.
Method signatures and docstrings:
- def get(self, player_id): Find a player in the queue by ID
- def delete(self, player_id): Remove a player from the queue | Implement the Python class `MatchQueueEntryAPI` described below.
Class description:
Implement the MatchQueueEntryAPI class.
Method signatures and docstrings:
- def get(self, player_id): Find a player in the queue by ID
- def delete(self, player_id): Remove a player from the queue
<|skeleton|>
class MatchQueueEntryAP... | 9825cb22b26b577b715f2ce95453363bf90ecc7e | <|skeleton|>
class MatchQueueEntryAPI:
def get(self, player_id):
"""Find a player in the queue by ID"""
<|body_0|>
def delete(self, player_id):
"""Remove a player from the queue"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatchQueueEntryAPI:
def get(self, player_id):
"""Find a player in the queue by ID"""
result = g.db.query(MatchQueuePlayer, CorePlayer).filter(MatchQueuePlayer.player_id == player_id, CorePlayer.player_id == player_id).order_by(-MatchQueuePlayer.id).first()
if not result:
ab... | the_stack_v2_python_sparse | driftbase/api/matchqueue.py | dgnorth/drift-base | train | 1 | |
0d2282d6b33e0530956ea70d8cb1b40432097de1 | [
"if cdp_type == 'any':\n return 'typing.Any'\nreturn cls[cdp_type].value",
"if cdp_type == 'any':\n return val\ncons = cls[cdp_type].value\nreturn f'{cons}({val})'"
] | <|body_start_0|>
if cdp_type == 'any':
return 'typing.Any'
return cls[cdp_type].value
<|end_body_0|>
<|body_start_1|>
if cdp_type == 'any':
return val
cons = cls[cdp_type].value
return f'{cons}({val})'
<|end_body_1|>
| All of the CDP types that map directly to a Python type. | CdpPrimitiveType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CdpPrimitiveType:
"""All of the CDP types that map directly to a Python type."""
def get_annotation(cls, cdp_type):
"""Return a type annotation for the CDP type."""
<|body_0|>
def get_constructor(cls, cdp_type, val):
"""Return the code to construct a value for a ... | stack_v2_sparse_classes_36k_train_022068 | 35,246 | permissive | [
{
"docstring": "Return a type annotation for the CDP type.",
"name": "get_annotation",
"signature": "def get_annotation(cls, cdp_type)"
},
{
"docstring": "Return the code to construct a value for a given CDP type.",
"name": "get_constructor",
"signature": "def get_constructor(cls, cdp_ty... | 2 | null | Implement the Python class `CdpPrimitiveType` described below.
Class description:
All of the CDP types that map directly to a Python type.
Method signatures and docstrings:
- def get_annotation(cls, cdp_type): Return a type annotation for the CDP type.
- def get_constructor(cls, cdp_type, val): Return the code to con... | Implement the Python class `CdpPrimitiveType` described below.
Class description:
All of the CDP types that map directly to a Python type.
Method signatures and docstrings:
- def get_annotation(cls, cdp_type): Return a type annotation for the CDP type.
- def get_constructor(cls, cdp_type, val): Return the code to con... | cc41a883b5138962c6b4408a0fdf4e932bd08071 | <|skeleton|>
class CdpPrimitiveType:
"""All of the CDP types that map directly to a Python type."""
def get_annotation(cls, cdp_type):
"""Return a type annotation for the CDP type."""
<|body_0|>
def get_constructor(cls, cdp_type, val):
"""Return the code to construct a value for a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CdpPrimitiveType:
"""All of the CDP types that map directly to a Python type."""
def get_annotation(cls, cdp_type):
"""Return a type annotation for the CDP type."""
if cdp_type == 'any':
return 'typing.Any'
return cls[cdp_type].value
def get_constructor(cls, cdp_t... | the_stack_v2_python_sparse | py/generate.py | SeleniumHQ/selenium | train | 30,383 |
a9346eff10494f6854fde106d25349d301c2daa6 | [
"self.val = None\nself.kids = dict()\nself.isWord = False",
"current_node = self\nfor idx, letter in enumerate(word):\n if letter not in current_node.kids:\n current_node.kids[letter] = Trie()\n current_node.kids[letter].val = letter\n current_node = current_node.kids[letter]\n if idx == le... | <|body_start_0|>
self.val = None
self.kids = dict()
self.isWord = False
<|end_body_0|>
<|body_start_1|>
current_node = self
for idx, letter in enumerate(word):
if letter not in current_node.kids:
current_node.kids[letter] = Trie()
curr... | Trie | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: void"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.val = None
self.kids =... | stack_v2_sparse_classes_36k_train_022069 | 2,425 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a word into the trie. :type word: str :rtype: void",
"name": "insert",
"signature": "def insert(self, word)"
}
] | 2 | null | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: void | Implement the Python class `Trie` described below.
Class description:
Implement the Trie class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, word): Inserts a word into the trie. :type word: str :rtype: void
<|skeleton|>
class Trie:
def __init__(... | f462b66ae849f4332a4b150f206dd49c7519e83b | <|skeleton|>
class Trie:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: void"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trie:
def __init__(self):
"""Initialize your data structure here."""
self.val = None
self.kids = dict()
self.isWord = False
def insert(self, word):
"""Inserts a word into the trie. :type word: str :rtype: void"""
current_node = self
for idx, letter ... | the_stack_v2_python_sparse | LeetCode/DataStructure/trie/max_xor_two_nums.py | hooyao/Coding-Py3 | train | 0 | |
9514aac7959d4683866f58f39e280b93e6a5eba7 | [
"m = len(dungeon)\nif m <= 0:\n return 1\nn = len(dungeon[0])\ndp = [[0] * n for _ in range(m)]\ndp[-1][-1] = -min(0, dungeon[-1][-1]) + 1\nfor i in range(m - 2, -1, -1):\n dp[i][-1] = max(dp[i + 1][-1] - dungeon[i][-1], 1)\nfor j in range(n - 2, -1, -1):\n dp[-1][j] = max(dp[-1][j + 1] - dungeon[-1][j], 1... | <|body_start_0|>
m = len(dungeon)
if m <= 0:
return 1
n = len(dungeon[0])
dp = [[0] * n for _ in range(m)]
dp[-1][-1] = -min(0, dungeon[-1][-1]) + 1
for i in range(m - 2, -1, -1):
dp[i][-1] = max(dp[i + 1][-1] - dungeon[i][-1], 1)
for j in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int 55ms"""
<|body_0|>
def calculateMinimumHP1(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
def calculateMinimumHP_1(self, dungeon):... | stack_v2_sparse_classes_36k_train_022070 | 3,275 | no_license | [
{
"docstring": ":type dungeon: List[List[int]] :rtype: int 55ms",
"name": "calculateMinimumHP",
"signature": "def calculateMinimumHP(self, dungeon)"
},
{
"docstring": ":type dungeon: List[List[int]] :rtype: int",
"name": "calculateMinimumHP1",
"signature": "def calculateMinimumHP1(self, ... | 3 | stack_v2_sparse_classes_30k_test_001011 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int 55ms
- def calculateMinimumHP1(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int 55ms
- def calculateMinimumHP1(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int 55ms"""
<|body_0|>
def calculateMinimumHP1(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
def calculateMinimumHP_1(self, dungeon):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int 55ms"""
m = len(dungeon)
if m <= 0:
return 1
n = len(dungeon[0])
dp = [[0] * n for _ in range(m)]
dp[-1][-1] = -min(0, dungeon[-1][-1]) + 1
for i i... | the_stack_v2_python_sparse | DungeonGame_HARD_174.py | 953250587/leetcode-python | train | 2 | |
025a94e3cccb0000d1612108a9f87dc72c8517dc | [
"self.bytes_transferred = bytes_transferred\nself.end_time_usecs = end_time_usecs\nself.failure_entities = failure_entities\nself.job_id = job_id\nself.job_run_id = job_run_id\nself.job_type = job_type\nself.sla_violated = sla_violated\nself.start_time_usecs = start_time_usecs\nself.status = status\nself.success_en... | <|body_start_0|>
self.bytes_transferred = bytes_transferred
self.end_time_usecs = end_time_usecs
self.failure_entities = failure_entities
self.job_id = job_id
self.job_run_id = job_run_id
self.job_type = job_type
self.sla_violated = sla_violated
self.start... | Implementation of the 'GetJobRunInfoResult' model. TODO: type description here. Attributes: bytes_transferred (long|int): Specifies bytes transferred in the run. end_time_usecs (long|int): Specifies the end time of the run. failure_entities (long|int): Specifies the number of failed objects in the run. job_id (string):... | GetJobRunInfoResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetJobRunInfoResult:
"""Implementation of the 'GetJobRunInfoResult' model. TODO: type description here. Attributes: bytes_transferred (long|int): Specifies bytes transferred in the run. end_time_usecs (long|int): Specifies the end time of the run. failure_entities (long|int): Specifies the number... | stack_v2_sparse_classes_36k_train_022071 | 4,093 | permissive | [
{
"docstring": "Constructor for the GetJobRunInfoResult class",
"name": "__init__",
"signature": "def __init__(self, bytes_transferred=None, end_time_usecs=None, failure_entities=None, job_id=None, job_run_id=None, job_type=None, sla_violated=None, start_time_usecs=None, status=None, success_entities=No... | 2 | null | Implement the Python class `GetJobRunInfoResult` described below.
Class description:
Implementation of the 'GetJobRunInfoResult' model. TODO: type description here. Attributes: bytes_transferred (long|int): Specifies bytes transferred in the run. end_time_usecs (long|int): Specifies the end time of the run. failure_en... | Implement the Python class `GetJobRunInfoResult` described below.
Class description:
Implementation of the 'GetJobRunInfoResult' model. TODO: type description here. Attributes: bytes_transferred (long|int): Specifies bytes transferred in the run. end_time_usecs (long|int): Specifies the end time of the run. failure_en... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GetJobRunInfoResult:
"""Implementation of the 'GetJobRunInfoResult' model. TODO: type description here. Attributes: bytes_transferred (long|int): Specifies bytes transferred in the run. end_time_usecs (long|int): Specifies the end time of the run. failure_entities (long|int): Specifies the number... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetJobRunInfoResult:
"""Implementation of the 'GetJobRunInfoResult' model. TODO: type description here. Attributes: bytes_transferred (long|int): Specifies bytes transferred in the run. end_time_usecs (long|int): Specifies the end time of the run. failure_entities (long|int): Specifies the number of failed ob... | the_stack_v2_python_sparse | cohesity_management_sdk/models/get_job_run_info_result.py | cohesity/management-sdk-python | train | 24 |
8c3db58622323f7f9e2bf14b6ec68c65495b0bfe | [
"attribute = getattr(self, attribute_name)\nif isinstance(attribute, Tensor):\n return attribute\nraise ValueError(f\"Attribute with name '{attribute_name}' is not a torch Tensor\")",
"persistent_buffers = {k: v for k, v in self._buffers.items() if k not in self._non_persistent_buffers_set}\nlocal_buffers = {k... | <|body_start_0|>
attribute = getattr(self, attribute_name)
if isinstance(attribute, Tensor):
return attribute
raise ValueError(f"Attribute with name '{attribute_name}' is not a torch Tensor")
<|end_body_0|>
<|body_start_1|>
persistent_buffers = {k: v for k, v in self._buffer... | Torch module that allows loading variables from the state dict even in the case of shape mismatch. | DynamicBufferModule | [
"CC-BY-SA-4.0",
"CC-BY-SA-3.0",
"CC-BY-NC-SA-4.0",
"Python-2.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicBufferModule:
"""Torch module that allows loading variables from the state dict even in the case of shape mismatch."""
def get_tensor_attribute(self, attribute_name: str) -> Tensor:
"""Get attribute of the tensor given the name. Args: attribute_name (str): Name of the tensor R... | stack_v2_sparse_classes_36k_train_022072 | 1,878 | permissive | [
{
"docstring": "Get attribute of the tensor given the name. Args: attribute_name (str): Name of the tensor Raises: ValueError: `attribute_name` is not a torch Tensor Returns: Tensor: Tensor attribute",
"name": "get_tensor_attribute",
"signature": "def get_tensor_attribute(self, attribute_name: str) -> T... | 2 | null | Implement the Python class `DynamicBufferModule` described below.
Class description:
Torch module that allows loading variables from the state dict even in the case of shape mismatch.
Method signatures and docstrings:
- def get_tensor_attribute(self, attribute_name: str) -> Tensor: Get attribute of the tensor given t... | Implement the Python class `DynamicBufferModule` described below.
Class description:
Torch module that allows loading variables from the state dict even in the case of shape mismatch.
Method signatures and docstrings:
- def get_tensor_attribute(self, attribute_name: str) -> Tensor: Get attribute of the tensor given t... | 4abfa93dcfcb98771bc768b334c929ff9a02ce8b | <|skeleton|>
class DynamicBufferModule:
"""Torch module that allows loading variables from the state dict even in the case of shape mismatch."""
def get_tensor_attribute(self, attribute_name: str) -> Tensor:
"""Get attribute of the tensor given the name. Args: attribute_name (str): Name of the tensor R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicBufferModule:
"""Torch module that allows loading variables from the state dict even in the case of shape mismatch."""
def get_tensor_attribute(self, attribute_name: str) -> Tensor:
"""Get attribute of the tensor given the name. Args: attribute_name (str): Name of the tensor Raises: ValueE... | the_stack_v2_python_sparse | src/anomalib/models/components/base/dynamic_module.py | openvinotoolkit/anomalib | train | 2,325 |
dca66028761eec4de6d599546012c12f5b8d5a6f | [
"dp = [0] * (amount + 1)\ndp[0] = 1\nfor i in coins:\n for j in range(1, amount + 1):\n if j >= i:\n dp[j] = dp[j] + dp[j - i]\nreturn dp[-1]",
"n = len(coins)\ndp = [[0] * (amount + 1) for _ in range(n + 1)]\nfor k in range(n + 1):\n dp[k][0] = 1\nfor i in range(1, n + 1):\n for j in r... | <|body_start_0|>
dp = [0] * (amount + 1)
dp[0] = 1
for i in coins:
for j in range(1, amount + 1):
if j >= i:
dp[j] = dp[j] + dp[j - i]
return dp[-1]
<|end_body_0|>
<|body_start_1|>
n = len(coins)
dp = [[0] * (amount + 1) fo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_022073 | 973 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
<|s... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
dp = [0] * (amount + 1)
dp[0] = 1
for i in coins:
for j in range(1, amount + 1):
if j >= i:
dp[j] = dp[j] + dp[j - i]
re... | the_stack_v2_python_sparse | 0518_Coin_Change_2.py | bingli8802/leetcode | train | 0 | |
e3facf73ef700212c7a918a2681e121286eb835b | [
"tmp = [Node(i, strs[i]) for i in range(len(strs))]\ntmp.sort()\nresult = dict()\nfor p in tmp:\n if p.string not in result:\n result[p.string] = [strs[p.id]]\n else:\n result[p.string].append(strs[p.id])\nreturn list(result.values())",
"d = dict()\nfor w in strs:\n word = getCountsStr(w)\n... | <|body_start_0|>
tmp = [Node(i, strs[i]) for i in range(len(strs))]
tmp.sort()
result = dict()
for p in tmp:
if p.string not in result:
result[p.string] = [strs[p.id]]
else:
result[p.string].append(strs[p.id])
return list(re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams2(self, strs):
"""计数法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tmp = [Node(i, strs[i]) for i in range(len(strs))]
... | stack_v2_sparse_classes_36k_train_022074 | 1,758 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": "计数法",
"name": "groupAnagrams2",
"signature": "def groupAnagrams2(self, strs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019208 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams2(self, strs): 计数法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams2(self, strs): 计数法
<|skeleton|>
class Solution:
def groupAnagrams(self, strs... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams2(self, strs):
"""计数法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
tmp = [Node(i, strs[i]) for i in range(len(strs))]
tmp.sort()
result = dict()
for p in tmp:
if p.string not in result:
result[p.string] = [strs[p.id]... | the_stack_v2_python_sparse | Tencent/midum/字母异位词分组.py | 2226171237/Algorithmpractice | train | 0 | |
8f540844ba35df23b5dd0188d3d9d7fd9f0228b4 | [
"self.ha = abstract.sdk.libs.abstracted_libs.ha.HA(device=uut)\nfor fabric in self.mapping.keys:\n for key, value in fabric.items():\n if fabricRole and fabricRole not in key:\n continue\n try:\n self.ha.reloadFabric(timeout=self.timeout, steps=steps, fabric=value)\n ex... | <|body_start_0|>
self.ha = abstract.sdk.libs.abstracted_libs.ha.HA(device=uut)
for fabric in self.mapping.keys:
for key, value in fabric.items():
if fabricRole and fabricRole not in key:
continue
try:
self.ha.reloadFabri... | Trigger class for Reload LCs action | TriggerReloadFabric | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerReloadFabric:
"""Trigger class for Reload LCs action"""
def reload(self, uut, abstract, steps, fabricRole=None):
"""Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: ... | stack_v2_sparse_classes_36k_train_022075 | 20,969 | permissive | [
{
"docstring": "Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: pyATS Results",
"name": "reload",
"signature": "def reload(self, uut, abstract, steps, fabricRole=None)"
},
{
... | 2 | null | Implement the Python class `TriggerReloadFabric` described below.
Class description:
Trigger class for Reload LCs action
Method signatures and docstrings:
- def reload(self, uut, abstract, steps, fabricRole=None): Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract... | Implement the Python class `TriggerReloadFabric` described below.
Class description:
Trigger class for Reload LCs action
Method signatures and docstrings:
- def reload(self, uut, abstract, steps, fabricRole=None): Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerReloadFabric:
"""Trigger class for Reload LCs action"""
def reload(self, uut, abstract, steps, fabricRole=None):
"""Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerReloadFabric:
"""Trigger class for Reload LCs action"""
def reload(self, uut, abstract, steps, fabricRole=None):
"""Reload LC and reconnect to device if needed Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object Returns: None Raises: ... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/ha/ha.py | CiscoTestAutomation/genielibs | train | 109 |
db413d85e0393261233990afc452a6cb1e4feda7 | [
"color = choice(['blue', 'green', 'red', 'brown'])\nSphere.__init__(self, x, y, 10, vx, vy, color)\nself.live = LIFETIME * FPS\nself.g = G",
"Sphere.move(self)\nSphere.check_walls(self)\nself.vy += self.g / FPS\nself.live -= 1\nif self.live <= 0:\n self.delete()",
"if (self.x - obj.x) ** 2 + (self.y - obj.y)... | <|body_start_0|>
color = choice(['blue', 'green', 'red', 'brown'])
Sphere.__init__(self, x, y, 10, vx, vy, color)
self.live = LIFETIME * FPS
self.g = G
<|end_body_0|>
<|body_start_1|>
Sphere.move(self)
Sphere.check_walls(self)
self.vy += self.g / FPS
self... | Ball | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ball:
def __init__(self, x=40, y=450, vx=10, vy=10):
"""Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали"""
<|body_0|>
def move(self):
"""Переместить мяч по прошествии единицы времени. Метод описывает... | stack_v2_sparse_classes_36k_train_022076 | 7,340 | no_license | [
{
"docstring": "Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали",
"name": "__init__",
"signature": "def __init__(self, x=40, y=450, vx=10, vy=10)"
},
{
"docstring": "Переместить мяч по прошествии единицы времени. Метод описывает... | 3 | stack_v2_sparse_classes_30k_train_006386 | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, x=40, y=450, vx=10, vy=10): Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали
- def move(self): Перем... | Implement the Python class `Ball` described below.
Class description:
Implement the Ball class.
Method signatures and docstrings:
- def __init__(self, x=40, y=450, vx=10, vy=10): Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали
- def move(self): Перем... | 470f865f4351c0d9379339e38b232de88d2d0edb | <|skeleton|>
class Ball:
def __init__(self, x=40, y=450, vx=10, vy=10):
"""Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали"""
<|body_0|>
def move(self):
"""Переместить мяч по прошествии единицы времени. Метод описывает... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ball:
def __init__(self, x=40, y=450, vx=10, vy=10):
"""Конструктор класса ball Args: x - начальное положение мяча по горизонтали y - начальное положение мяча по вертикали"""
color = choice(['blue', 'green', 'red', 'brown'])
Sphere.__init__(self, x, y, 10, vx, vy, color)
self.l... | the_stack_v2_python_sparse | lab-271020/Lab-8.py | BelkovV/Re-0 | train | 0 | |
efae1a9e376c3011676daf83a65c3c31f155c398 | [
"d = odict()\nfor name, field in self.items():\n d[name] = field._dump()\nreturn d",
"d = odict()\nfor name, field in self.items():\n if field.may_store_entities:\n d[name] = field._entities_in_value()\nreturn d",
"for name, field in other.iteritems():\n if name in self:\n f = self[name]\... | <|body_start_0|>
d = odict()
for name, field in self.items():
d[name] = field._dump()
return d
<|end_body_0|>
<|body_start_1|>
d = odict()
for name, field in self.items():
if field.may_store_entities:
d[name] = field._entities_in_value()
... | Field Mapping based on Ordered Dictionary. | FieldMap | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FieldMap:
"""Field Mapping based on Ordered Dictionary."""
def dump_map(self):
"""Return a dictionary of field_name:dumped_value pairs."""
<|body_0|>
def related_entity_map(self):
"""Return a dictionary of field_name:related_entity_set pairs."""
<|body_1|... | stack_v2_sparse_classes_36k_train_022077 | 7,952 | permissive | [
{
"docstring": "Return a dictionary of field_name:dumped_value pairs.",
"name": "dump_map",
"signature": "def dump_map(self)"
},
{
"docstring": "Return a dictionary of field_name:related_entity_set pairs.",
"name": "related_entity_map",
"signature": "def related_entity_map(self)"
},
... | 4 | null | Implement the Python class `FieldMap` described below.
Class description:
Field Mapping based on Ordered Dictionary.
Method signatures and docstrings:
- def dump_map(self): Return a dictionary of field_name:dumped_value pairs.
- def related_entity_map(self): Return a dictionary of field_name:related_entity_set pairs.... | Implement the Python class `FieldMap` described below.
Class description:
Field Mapping based on Ordered Dictionary.
Method signatures and docstrings:
- def dump_map(self): Return a dictionary of field_name:dumped_value pairs.
- def related_entity_map(self): Return a dictionary of field_name:related_entity_set pairs.... | d57a41f8b7b514ed48dc0164dcd3412a89e9873b | <|skeleton|>
class FieldMap:
"""Field Mapping based on Ordered Dictionary."""
def dump_map(self):
"""Return a dictionary of field_name:dumped_value pairs."""
<|body_0|>
def related_entity_map(self):
"""Return a dictionary of field_name:related_entity_set pairs."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FieldMap:
"""Field Mapping based on Ordered Dictionary."""
def dump_map(self):
"""Return a dictionary of field_name:dumped_value pairs."""
d = odict()
for name, field in self.items():
d[name] = field._dump()
return d
def related_entity_map(self):
"... | the_stack_v2_python_sparse | schevo/fieldspec.py | Schevo/schevo | train | 2 |
3187aef767c9dfa142e47fa30ead8c1f440daaa7 | [
"self.head = head\nself.tail = tail\nassert self.head is not None\nassert isinstance(self.head, BackboneHead), f'argument head must be an instance of BackboneHead not {type(head)}'\nassert self.tail is None or isinstance(self.tail, BackboneHead), f'supplied value for argument tail must be an instance of Backbone, n... | <|body_start_0|>
self.head = head
self.tail = tail
assert self.head is not None
assert isinstance(self.head, BackboneHead), f'argument head must be an instance of BackboneHead not {type(head)}'
assert self.tail is None or isinstance(self.tail, BackboneHead), f'supplied value for ... | Backbone | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Backbone:
def __init__(self, head: BackboneHead=None, tail: BackboneTail=None):
"""Initializes the backbone which consists of two parts; a head and a tail. The head helps with feature extraction from images while the tail is used on selected rois (regions of interest). The output from th... | stack_v2_sparse_classes_36k_train_022078 | 5,806 | permissive | [
{
"docstring": "Initializes the backbone which consists of two parts; a head and a tail. The head helps with feature extraction from images while the tail is used on selected rois (regions of interest). The output from the tail is what is fed to the detector network for object class prediction and bounding box ... | 3 | stack_v2_sparse_classes_30k_train_011828 | Implement the Python class `Backbone` described below.
Class description:
Implement the Backbone class.
Method signatures and docstrings:
- def __init__(self, head: BackboneHead=None, tail: BackboneTail=None): Initializes the backbone which consists of two parts; a head and a tail. The head helps with feature extract... | Implement the Python class `Backbone` described below.
Class description:
Implement the Backbone class.
Method signatures and docstrings:
- def __init__(self, head: BackboneHead=None, tail: BackboneTail=None): Initializes the backbone which consists of two parts; a head and a tail. The head helps with feature extract... | 307e2e873b261b962e1fdaeaa6ed68e439e114ba | <|skeleton|>
class Backbone:
def __init__(self, head: BackboneHead=None, tail: BackboneTail=None):
"""Initializes the backbone which consists of two parts; a head and a tail. The head helps with feature extraction from images while the tail is used on selected rois (regions of interest). The output from th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Backbone:
def __init__(self, head: BackboneHead=None, tail: BackboneTail=None):
"""Initializes the backbone which consists of two parts; a head and a tail. The head helps with feature extraction from images while the tail is used on selected rois (regions of interest). The output from the tail is what... | the_stack_v2_python_sparse | faster_rcnn/backbone/backbone.py | tejuafonja/faster_rcnn | train | 1 | |
77df3be38b1b6bb912ee41f213d8bb20cd34867a | [
"self._config = ConfigParser.ConfigParser()\nself.logger = SEKLogger(__name__, 'INFO')\nself.fileUtil = SEKFileUtil()\nself.insertTables = ('MeterData', 'RegisterData', 'RegisterRead', 'Tier', 'Register', 'IntervalReadData', 'Interval', 'Reading', 'EventData', 'Event')\nconfigFilePath = '~/.msg-data-operations.cfg'... | <|body_start_0|>
self._config = ConfigParser.ConfigParser()
self.logger = SEKLogger(__name__, 'INFO')
self.fileUtil = SEKFileUtil()
self.insertTables = ('MeterData', 'RegisterData', 'RegisterRead', 'Tier', 'Register', 'IntervalReadData', 'Interval', 'Reading', 'EventData', 'Event')
... | Supports system-specific configuration for MECO data processing. The site-level configuration file is located in ~/.meco-data-operations.cfg. Usage: configer = MSGConfiger() | MSGConfiger | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSGConfiger:
"""Supports system-specific configuration for MECO data processing. The site-level configuration file is located in ~/.meco-data-operations.cfg. Usage: configer = MSGConfiger()"""
def __init__(self):
"""Constructor."""
<|body_0|>
def configOptionValue(self, ... | stack_v2_sparse_classes_36k_train_022079 | 2,758 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get a configuration value from the local configuration file. :param section: String of section in config file. :param option: String of option in config file. :returns: The value contained in ... | 2 | null | Implement the Python class `MSGConfiger` described below.
Class description:
Supports system-specific configuration for MECO data processing. The site-level configuration file is located in ~/.meco-data-operations.cfg. Usage: configer = MSGConfiger()
Method signatures and docstrings:
- def __init__(self): Constructor... | Implement the Python class `MSGConfiger` described below.
Class description:
Supports system-specific configuration for MECO data processing. The site-level configuration file is located in ~/.meco-data-operations.cfg. Usage: configer = MSGConfiger()
Method signatures and docstrings:
- def __init__(self): Constructor... | 28539f6cf07cf2cdf9d8913cdb3c1c1d53ee90c2 | <|skeleton|>
class MSGConfiger:
"""Supports system-specific configuration for MECO data processing. The site-level configuration file is located in ~/.meco-data-operations.cfg. Usage: configer = MSGConfiger()"""
def __init__(self):
"""Constructor."""
<|body_0|>
def configOptionValue(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MSGConfiger:
"""Supports system-specific configuration for MECO data processing. The site-level configuration file is located in ~/.meco-data-operations.cfg. Usage: configer = MSGConfiger()"""
def __init__(self):
"""Constructor."""
self._config = ConfigParser.ConfigParser()
self.l... | the_stack_v2_python_sparse | src/msg_configer.py | yuanzy97/Maui-Smart-Grid | train | 0 |
288ecdd0d3af210827c7b5bce80eff00076614f9 | [
"self.bname = bname\nself.bdata = dict()\nparent_folder = pathlib.Path(__file__).parent.absolute()\nbench_filename = '{b}.json'.format(b=bname)\nbench_path = parent_folder.joinpath('..', '..', 'bench_info', bench_filename)\ntry:\n with open(bench_path) as json_file:\n self.info = json.load(json_file)['ben... | <|body_start_0|>
self.bname = bname
self.bdata = dict()
parent_folder = pathlib.Path(__file__).parent.absolute()
bench_filename = '{b}.json'.format(b=bname)
bench_path = parent_folder.joinpath('..', '..', 'bench_info', bench_filename)
try:
with open(bench_path... | A class for reading and benchmark information and initializing bechmark data. | Benchmark | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Benchmark:
"""A class for reading and benchmark information and initializing bechmark data."""
def __init__(self, bname: str):
"""Reads benchmark information. :param bname: The benchmark name."""
<|body_0|>
def get_data(self, preset: str='L') -> Dict[str, Any]:
"... | stack_v2_sparse_classes_36k_train_022080 | 2,800 | permissive | [
{
"docstring": "Reads benchmark information. :param bname: The benchmark name.",
"name": "__init__",
"signature": "def __init__(self, bname: str)"
},
{
"docstring": "Initializes the benchmark data. :param preset: The data-size preset (S, M, L, paper).",
"name": "get_data",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_006417 | Implement the Python class `Benchmark` described below.
Class description:
A class for reading and benchmark information and initializing bechmark data.
Method signatures and docstrings:
- def __init__(self, bname: str): Reads benchmark information. :param bname: The benchmark name.
- def get_data(self, preset: str='... | Implement the Python class `Benchmark` described below.
Class description:
A class for reading and benchmark information and initializing bechmark data.
Method signatures and docstrings:
- def __init__(self, bname: str): Reads benchmark information. :param bname: The benchmark name.
- def get_data(self, preset: str='... | f2f545afe3603d5c8f1771f26d660f25ce4a3cda | <|skeleton|>
class Benchmark:
"""A class for reading and benchmark information and initializing bechmark data."""
def __init__(self, bname: str):
"""Reads benchmark information. :param bname: The benchmark name."""
<|body_0|>
def get_data(self, preset: str='L') -> Dict[str, Any]:
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Benchmark:
"""A class for reading and benchmark information and initializing bechmark data."""
def __init__(self, bname: str):
"""Reads benchmark information. :param bname: The benchmark name."""
self.bname = bname
self.bdata = dict()
parent_folder = pathlib.Path(__file__)... | the_stack_v2_python_sparse | npbench/infrastructure/benchmark.py | learning-chip/npbench | train | 0 |
9b3e4fb6f9b6641c115f1d04f49acd7cc338edb0 | [
"ret = []\n\ndef doSerialize(root):\n if root == None:\n ret.append('None')\n return\n ret.append(str(root.val))\n ret.append(str(len(root.children) if root.children else 0))\n for i in range(len(root.children)):\n doSerialize(root.children[i])\ndoSerialize(root)\nprint(','.join(ret... | <|body_start_0|>
ret = []
def doSerialize(root):
if root == None:
ret.append('None')
return
ret.append(str(root.val))
ret.append(str(len(root.children) if root.children else 0))
for i in range(len(root.children)):
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_022081 | 1,444 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_000349 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | fe30d8ca54309caff975684648495ea953022048 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
ret = []
def doSerialize(root):
if root == None:
ret.append('None')
return
ret.append(str(root.val))
... | the_stack_v2_python_sparse | algorithm/leetCode/0428_serialize_and_deserialize_N-ary_Tree.py | dictator-x/practise_as | train | 0 | |
b710f752e0d22d401031f38017faf2efc7a0b0d9 | [
"self.port_id = port_id\nself.sys_descr = sys_descr\nself.sys_name = sys_name",
"if dictionary is None:\n return None\nport_id = dictionary.get('portId')\nsys_descr = dictionary.get('sysDescr')\nsys_name = dictionary.get('sysName')\nreturn cls(port_id, sys_descr, sys_name)"
] | <|body_start_0|>
self.port_id = port_id
self.sys_descr = sys_descr
self.sys_name = sys_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
port_id = dictionary.get('portId')
sys_descr = dictionary.get('sysDescr')
sys_name = diction... | Implementation of the 'UplinkSwitchInfo' model. TODO: type description here. Attributes: port_id (string): Port ID. sys_descr (string): System description. sys_name (string): System name. | UplinkSwitchInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UplinkSwitchInfo:
"""Implementation of the 'UplinkSwitchInfo' model. TODO: type description here. Attributes: port_id (string): Port ID. sys_descr (string): System description. sys_name (string): System name."""
def __init__(self, port_id=None, sys_descr=None, sys_name=None):
"""Cons... | stack_v2_sparse_classes_36k_train_022082 | 1,688 | permissive | [
{
"docstring": "Constructor for the UplinkSwitchInfo class",
"name": "__init__",
"signature": "def __init__(self, port_id=None, sys_descr=None, sys_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the... | 2 | null | Implement the Python class `UplinkSwitchInfo` described below.
Class description:
Implementation of the 'UplinkSwitchInfo' model. TODO: type description here. Attributes: port_id (string): Port ID. sys_descr (string): System description. sys_name (string): System name.
Method signatures and docstrings:
- def __init__... | Implement the Python class `UplinkSwitchInfo` described below.
Class description:
Implementation of the 'UplinkSwitchInfo' model. TODO: type description here. Attributes: port_id (string): Port ID. sys_descr (string): System description. sys_name (string): System name.
Method signatures and docstrings:
- def __init__... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class UplinkSwitchInfo:
"""Implementation of the 'UplinkSwitchInfo' model. TODO: type description here. Attributes: port_id (string): Port ID. sys_descr (string): System description. sys_name (string): System name."""
def __init__(self, port_id=None, sys_descr=None, sys_name=None):
"""Cons... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UplinkSwitchInfo:
"""Implementation of the 'UplinkSwitchInfo' model. TODO: type description here. Attributes: port_id (string): Port ID. sys_descr (string): System description. sys_name (string): System name."""
def __init__(self, port_id=None, sys_descr=None, sys_name=None):
"""Constructor for t... | the_stack_v2_python_sparse | cohesity_management_sdk/models/uplink_switch_info.py | cohesity/management-sdk-python | train | 24 |
d8a076d4e0560430b9a01557d4fac40c676b4bcf | [
"super().__init__(pool, delegate, probability)\nassert max_constant_length > 0, 'Length limit for constant pool elements must be positive.'\nself._max_constant_length = max_constant_length",
"value = unwrap(value)\nif type(value) in typing.get_args(ConstantTypes):\n if isinstance(value, str | bytes) and len(va... | <|body_start_0|>
super().__init__(pool, delegate, probability)
assert max_constant_length > 0, 'Length limit for constant pool elements must be positive.'
self._max_constant_length = max_constant_length
<|end_body_0|>
<|body_start_1|>
value = unwrap(value)
if type(value) in typi... | Provide values collected during runtime. | DynamicConstantProvider | [
"CC-BY-4.0",
"LGPL-2.1-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DynamicConstantProvider:
"""Provide values collected during runtime."""
def __init__(self, pool: ConstantPool, delegate: ConstantProvider, probability: float, max_constant_length: int):
"""Create a new dynamic constant provider. Args: pool: The pool of constants to use delegate: The ... | stack_v2_sparse_classes_36k_train_022083 | 11,084 | permissive | [
{
"docstring": "Create a new dynamic constant provider. Args: pool: The pool of constants to use delegate: The delegate to forward the query probability: The probability to use a value from this provider, if there is one. max_constant_length: The maximum length of strings to store.",
"name": "__init__",
... | 3 | null | Implement the Python class `DynamicConstantProvider` described below.
Class description:
Provide values collected during runtime.
Method signatures and docstrings:
- def __init__(self, pool: ConstantPool, delegate: ConstantProvider, probability: float, max_constant_length: int): Create a new dynamic constant provider... | Implement the Python class `DynamicConstantProvider` described below.
Class description:
Provide values collected during runtime.
Method signatures and docstrings:
- def __init__(self, pool: ConstantPool, delegate: ConstantProvider, probability: float, max_constant_length: int): Create a new dynamic constant provider... | cc083252c7054824bfaf200533a8b7ad45f7c4fb | <|skeleton|>
class DynamicConstantProvider:
"""Provide values collected during runtime."""
def __init__(self, pool: ConstantPool, delegate: ConstantProvider, probability: float, max_constant_length: int):
"""Create a new dynamic constant provider. Args: pool: The pool of constants to use delegate: The ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DynamicConstantProvider:
"""Provide values collected during runtime."""
def __init__(self, pool: ConstantPool, delegate: ConstantProvider, probability: float, max_constant_length: int):
"""Create a new dynamic constant provider. Args: pool: The pool of constants to use delegate: The delegate to f... | the_stack_v2_python_sparse | src/pynguin/analyses/constants.py | se2p/pynguin | train | 1,223 |
2408c8e28b4bb315cac68c09a501602e50981abc | [
"if not nums:\n return 1\ni = 0\nwhile i < len(nums):\n if nums[i] <= 0 or nums[i] > len(nums) or nums[nums[i] - 1] == nums[i]:\n i += 1\n else:\n nums[nums[i] - 1], nums[i] = (nums[i], nums[nums[i] - 1])\nfor i in range(len(nums)):\n if nums[i] != i + 1:\n return i + 1\nreturn nums... | <|body_start_0|>
if not nums:
return 1
i = 0
while i < len(nums):
if nums[i] <= 0 or nums[i] > len(nums) or nums[nums[i] - 1] == nums[i]:
i += 1
else:
nums[nums[i] - 1], nums[i] = (nums[i], nums[nums[i] - 1])
for i in ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive_failed(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
... | stack_v2_sparse_classes_36k_train_022084 | 2,233 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive",
"signature": "def firstMissingPositive(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "firstMissingPositive_failed",
"signature": "def firstMissingPositive_failed(self, nums)"... | 2 | stack_v2_sparse_classes_30k_train_012532 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive_failed(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def firstMissingPositive(self, nums): :type nums: List[int] :rtype: int
- def firstMissingPositive_failed(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solut... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def firstMissingPositive_failed(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def firstMissingPositive(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 1
i = 0
while i < len(nums):
if nums[i] <= 0 or nums[i] > len(nums) or nums[nums[i] - 1] == nums[i]:
i += 1
else:
... | the_stack_v2_python_sparse | src/lt_41.py | oxhead/CodingYourWay | train | 0 | |
9e4ea0daac7623150e7b70e46bc9dbe79e34d562 | [
"if verbose is False:\n log.setLevel(logging.ERROR)\nelif verbose is True:\n log.setLevel(logging.INFO)\nif debug is True:\n log.setLevel(logging.DEBUG)\nreturn",
"A = 1.0\nB = x0\nC = fwhm / (2 * np.sqrt(2 * np.log(2)))\ny = A * np.exp(-(x - B) ** 2 / (2 * C ** 2))\nreturn y",
"data = np.zeros(size)\n... | <|body_start_0|>
if verbose is False:
log.setLevel(logging.ERROR)
elif verbose is True:
log.setLevel(logging.INFO)
if debug is True:
log.setLevel(logging.DEBUG)
return
<|end_body_0|>
<|body_start_1|>
A = 1.0
B = x0
C = fwhm / (... | Main | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Main:
def __init__(self, verbose=False, debug=False):
"""Main class constructor. @param verbose: Set verbose level on. @param debug: Set debug level on. This overwrites verbose parameter. @return None"""
<|body_0|>
def gaussian(self, x, x0, fwhm):
"""@param x: 1D arr... | stack_v2_sparse_classes_36k_train_022085 | 9,096 | no_license | [
{
"docstring": "Main class constructor. @param verbose: Set verbose level on. @param debug: Set debug level on. This overwrites verbose parameter. @return None",
"name": "__init__",
"signature": "def __init__(self, verbose=False, debug=False)"
},
{
"docstring": "@param x: 1D array containing X v... | 4 | null | Implement the Python class `Main` described below.
Class description:
Implement the Main class.
Method signatures and docstrings:
- def __init__(self, verbose=False, debug=False): Main class constructor. @param verbose: Set verbose level on. @param debug: Set debug level on. This overwrites verbose parameter. @return... | Implement the Python class `Main` described below.
Class description:
Implement the Main class.
Method signatures and docstrings:
- def __init__(self, verbose=False, debug=False): Main class constructor. @param verbose: Set verbose level on. @param debug: Set debug level on. This overwrites verbose parameter. @return... | 04615a318600def7d5f48d04849250bde07c8292 | <|skeleton|>
class Main:
def __init__(self, verbose=False, debug=False):
"""Main class constructor. @param verbose: Set verbose level on. @param debug: Set debug level on. This overwrites verbose parameter. @return None"""
<|body_0|>
def gaussian(self, x, x0, fwhm):
"""@param x: 1D arr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Main:
def __init__(self, verbose=False, debug=False):
"""Main class constructor. @param verbose: Set verbose level on. @param debug: Set debug level on. This overwrites verbose parameter. @return None"""
if verbose is False:
log.setLevel(logging.ERROR)
elif verbose is True:... | the_stack_v2_python_sparse | dev/arials_oned.py | b1quint/btfi | train | 2 | |
0dad0d06e44faa9c3f3f97a73c541c7669eee9f1 | [
"merchObj = Merchant.objects.get(merchant=request.user.id)\nsubObj = SubAdmin.objects.filter(merchant=merchObj.merchantId)\nprint(subObj)\nserializer = SubAdminSerializer(subObj, many=True)\nprint(serializer.data)\nreturn Response(serializer.data)",
"obj2 = Merchant.objects.get(merchant=request.user.id)\nrequest.... | <|body_start_0|>
merchObj = Merchant.objects.get(merchant=request.user.id)
subObj = SubAdmin.objects.filter(merchant=merchObj.merchantId)
print(subObj)
serializer = SubAdminSerializer(subObj, many=True)
print(serializer.data)
return Response(serializer.data)
<|end_body_0|... | A class based view for creating and fetching student records | SubAdminRecordView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubAdminRecordView:
"""A class based view for creating and fetching student records"""
def get(self, request, format=None):
"""Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records"""
<|body_0|>
d... | stack_v2_sparse_classes_36k_train_022086 | 2,583 | no_license | [
{
"docstring": "Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Create a student record :param format: Format of the student rec... | 2 | stack_v2_sparse_classes_30k_train_018343 | Implement the Python class `SubAdminRecordView` described below.
Class description:
A class based view for creating and fetching student records
Method signatures and docstrings:
- def get(self, request, format=None): Get all the student records :param format: Format of the student records to return to :return: Retur... | Implement the Python class `SubAdminRecordView` described below.
Class description:
A class based view for creating and fetching student records
Method signatures and docstrings:
- def get(self, request, format=None): Get all the student records :param format: Format of the student records to return to :return: Retur... | 88e4e994a029527d9e6b9431155a81cd5774b63c | <|skeleton|>
class SubAdminRecordView:
"""A class based view for creating and fetching student records"""
def get(self, request, format=None):
"""Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records"""
<|body_0|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubAdminRecordView:
"""A class based view for creating and fetching student records"""
def get(self, request, format=None):
"""Get all the student records :param format: Format of the student records to return to :return: Returns a list of student records"""
merchObj = Merchant.objects.ge... | the_stack_v2_python_sparse | myuser/views/subadminView.py | anku580/Upfront---Backend | train | 0 |
983c79f1d8e645ce3e9c205ccef45fdd7d09fc6c | [
"assert features.is_contiguous()\nassert idx.is_contiguous()\nassert weight.is_contiguous()\nm, c = features.size()\nn = idx.size(0)\nctx.three_interpolate_for_backward = (idx, weight, m)\noutput = torch.cuda.FloatTensor(n, c)\nsparse_interpolate_ext.three_interpolate_wrapper(c, m, n, features, idx, weight, output)... | <|body_start_0|>
assert features.is_contiguous()
assert idx.is_contiguous()
assert weight.is_contiguous()
m, c = features.size()
n = idx.size(0)
ctx.three_interpolate_for_backward = (idx, weight, m)
output = torch.cuda.FloatTensor(n, c)
sparse_interpolate_... | SparseThreeInterpolate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseThreeInterpolate:
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three neare... | stack_v2_sparse_classes_36k_train_022087 | 3,814 | permissive | [
{
"docstring": "Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three nearest neighbors of the target features in features :param weight: (n, 3) weights :return: output: (N, C) tensor of the interpolated featu... | 2 | stack_v2_sparse_classes_30k_train_020217 | Implement the Python class `SparseThreeInterpolate` described below.
Class description:
Implement the SparseThreeInterpolate class.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: Performs weight linear interpolation on 3 features ... | Implement the Python class `SparseThreeInterpolate` described below.
Class description:
Implement the SparseThreeInterpolate class.
Method signatures and docstrings:
- def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: Performs weight linear interpolation on 3 features ... | 9987806185a4e1619bc15ceecb8a1755e764ff68 | <|skeleton|>
class SparseThreeInterpolate:
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three neare... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SparseThreeInterpolate:
def forward(ctx, features: torch.Tensor, idx: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
"""Performs weight linear interpolation on 3 features :param ctx: :param features: (M, C) Features descriptors to be interpolated from :param idx: (n, 3) three nearest neighbors o... | the_stack_v2_python_sparse | gorilla3d/ops/sparse_interpolate/sparse_interpolate.py | SijanNeupane49/gorilla-3d | train | 0 | |
150889e01da1f226bdc2e47e8d0f9ffe126531c4 | [
"rule = getConstant('registration__orgRule')\nannotations = {'nullParam': Case(default_value=None, output_field=IntegerField()), 'paramOne': Case(default_value=None, output_field=IntegerField()), 'paramTwo': Case(default_value=None, output_field=IntegerField())}\nif rule == 'SessionFirst':\n annotations.update({... | <|body_start_0|>
rule = getConstant('registration__orgRule')
annotations = {'nullParam': Case(default_value=None, output_field=IntegerField()), 'paramOne': Case(default_value=None, output_field=IntegerField()), 'paramTwo': Case(default_value=None, output_field=IntegerField())}
if rule == 'Sessio... | Various registration pages require that Event querysets be ordered based on the value of the constant registration__orgRule (e.g. by session, by month, the combination of the two, or by weekday). Rather than placing this ordering logic in Python, this mixin produces a SQL compliant order parameter that can be added as ... | EventOrderMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventOrderMixin:
"""Various registration pages require that Event querysets be ordered based on the value of the constant registration__orgRule (e.g. by session, by month, the combination of the two, or by weekday). Rather than placing this ordering logic in Python, this mixin produces a SQL comp... | stack_v2_sparse_classes_36k_train_022088 | 30,664 | permissive | [
{
"docstring": "This method gets the annotations for the queryset. Unlike get_ordering() below, it passes the actual Case() and F() objects that will be evaluated with the queryset, returned in a dictionary that is compatible with get_ordering().",
"name": "get_annotations",
"signature": "def get_annota... | 2 | null | Implement the Python class `EventOrderMixin` described below.
Class description:
Various registration pages require that Event querysets be ordered based on the value of the constant registration__orgRule (e.g. by session, by month, the combination of the two, or by weekday). Rather than placing this ordering logic in... | Implement the Python class `EventOrderMixin` described below.
Class description:
Various registration pages require that Event querysets be ordered based on the value of the constant registration__orgRule (e.g. by session, by month, the combination of the two, or by weekday). Rather than placing this ordering logic in... | 19db3e83e76ea2002ee841989410d12d1e601023 | <|skeleton|>
class EventOrderMixin:
"""Various registration pages require that Event querysets be ordered based on the value of the constant registration__orgRule (e.g. by session, by month, the combination of the two, or by weekday). Rather than placing this ordering logic in Python, this mixin produces a SQL comp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventOrderMixin:
"""Various registration pages require that Event querysets be ordered based on the value of the constant registration__orgRule (e.g. by session, by month, the combination of the two, or by weekday). Rather than placing this ordering logic in Python, this mixin produces a SQL compliant order p... | the_stack_v2_python_sparse | danceschool/core/mixins.py | django-danceschool/django-danceschool | train | 40 |
db41f2ab000ef8f7ae894177d86b1b2776ac003f | [
"logger.info('loading corpus from %s' % fname)\nself.fname = fname\nself.length = None\nself.labels = labels\nhead = ''.join(itertools.islice(utils.smart_open(self.fname), 5))\nself.headers = csv.Sniffer().has_header(head)\nself.dialect = csv.Sniffer().sniff(head)\nlogger.info('sniffed CSV delimiter=%r, headers=%s'... | <|body_start_0|>
logger.info('loading corpus from %s' % fname)
self.fname = fname
self.length = None
self.labels = labels
head = ''.join(itertools.islice(utils.smart_open(self.fname), 5))
self.headers = csv.Sniffer().has_header(head)
self.dialect = csv.Sniffer().s... | Corpus in CSV format. The CSV delimiter, headers etc. are guessed automatically based on the file content. All row values are expected to be ints/floats. | CsvCorpus | [
"Python-2.0",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsvCorpus:
"""Corpus in CSV format. The CSV delimiter, headers etc. are guessed automatically based on the file content. All row values are expected to be ints/floats."""
def __init__(self, fname, labels):
"""Initialize the corpus from a file. `labels` = are class labels present in t... | stack_v2_sparse_classes_36k_train_022089 | 1,880 | permissive | [
{
"docstring": "Initialize the corpus from a file. `labels` = are class labels present in the input file? => skip the first column",
"name": "__init__",
"signature": "def __init__(self, fname, labels)"
},
{
"docstring": "Iterate over the corpus, returning one sparse vector at a time.",
"name... | 2 | null | Implement the Python class `CsvCorpus` described below.
Class description:
Corpus in CSV format. The CSV delimiter, headers etc. are guessed automatically based on the file content. All row values are expected to be ints/floats.
Method signatures and docstrings:
- def __init__(self, fname, labels): Initialize the cor... | Implement the Python class `CsvCorpus` described below.
Class description:
Corpus in CSV format. The CSV delimiter, headers etc. are guessed automatically based on the file content. All row values are expected to be ints/floats.
Method signatures and docstrings:
- def __init__(self, fname, labels): Initialize the cor... | 2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6 | <|skeleton|>
class CsvCorpus:
"""Corpus in CSV format. The CSV delimiter, headers etc. are guessed automatically based on the file content. All row values are expected to be ints/floats."""
def __init__(self, fname, labels):
"""Initialize the corpus from a file. `labels` = are class labels present in t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CsvCorpus:
"""Corpus in CSV format. The CSV delimiter, headers etc. are guessed automatically based on the file content. All row values are expected to be ints/floats."""
def __init__(self, fname, labels):
"""Initialize the corpus from a file. `labels` = are class labels present in the input file... | the_stack_v2_python_sparse | lib/python2.7/site-packages/gensim/corpora/csvcorpus.py | wangyum/Anaconda | train | 11 |
c37384686c09dad2774111f86c0a0e3987808f7e | [
"self.archive = []\nself.fileNameInput = preferences.Filename().getFromFilename(interpret.getTranslatorFileTypeTuples(), 'Open File to be Carved', '')\nself.archive.append(self.fileNameInput)\nself.extraDecimalPlaces = preferences.IntPreference().getFromValue('Extra Decimal Places (integer):', 1)\nself.archive.appe... | <|body_start_0|>
self.archive = []
self.fileNameInput = preferences.Filename().getFromFilename(interpret.getTranslatorFileTypeTuples(), 'Open File to be Carved', '')
self.archive.append(self.fileNameInput)
self.extraDecimalPlaces = preferences.IntPreference().getFromValue('Extra Decimal ... | A class to handle the carve preferences. | CarvePreferences | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CarvePreferences:
"""A class to handle the carve preferences."""
def __init__(self):
"""Set the default preferences, execute title & preferences fileName."""
<|body_0|>
def execute(self):
"""Carve button has been clicked."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_022090 | 11,480 | no_license | [
{
"docstring": "Set the default preferences, execute title & preferences fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Carve button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011337 | Implement the Python class `CarvePreferences` described below.
Class description:
A class to handle the carve preferences.
Method signatures and docstrings:
- def __init__(self): Set the default preferences, execute title & preferences fileName.
- def execute(self): Carve button has been clicked. | Implement the Python class `CarvePreferences` described below.
Class description:
A class to handle the carve preferences.
Method signatures and docstrings:
- def __init__(self): Set the default preferences, execute title & preferences fileName.
- def execute(self): Carve button has been clicked.
<|skeleton|>
class ... | 9e24dabbca21e67fecda1ed55a5af45dce41bfe2 | <|skeleton|>
class CarvePreferences:
"""A class to handle the carve preferences."""
def __init__(self):
"""Set the default preferences, execute title & preferences fileName."""
<|body_0|>
def execute(self):
"""Carve button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CarvePreferences:
"""A class to handle the carve preferences."""
def __init__(self):
"""Set the default preferences, execute title & preferences fileName."""
self.archive = []
self.fileNameInput = preferences.Filename().getFromFilename(interpret.getTranslatorFileTypeTuples(), 'Ope... | the_stack_v2_python_sparse | reprap_python_beanshell/skeinforge_tools/craft_plugins/carve.py | TeamTeamUSA/SkeinFox | train | 0 |
21ddfdcfb94a0599b37ae7657c849eaf3da1b4ec | [
"if 'definition_id' not in data:\n return super().validate(data)\ntry:\n data['definition'] = fhir_api.retrieve('StructureDefinition', data['definition_id'], settings.FHIR_API_AUTH_TOKEN)\nexcept Exception as e:\n raise serializers.ValidationError({'definition': [str(e)]}, code=status.HTTP_500_INTERNAL_SER... | <|body_start_0|>
if 'definition_id' not in data:
return super().validate(data)
try:
data['definition'] = fhir_api.retrieve('StructureDefinition', data['definition_id'], settings.FHIR_API_AUTH_TOKEN)
except Exception as e:
raise serializers.ValidationError({'de... | ResourceSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceSerializer:
def validate(self, data):
"""called on resource creation. We fetch the StructureDefinition from fhir-api before validating and saving the resource to the database. Args: data ([dict]): the resource instance Raises: serializers.ValidationError: if the StructureDeifniti... | stack_v2_sparse_classes_36k_train_022091 | 5,457 | permissive | [
{
"docstring": "called on resource creation. We fetch the StructureDefinition from fhir-api before validating and saving the resource to the database. Args: data ([dict]): the resource instance Raises: serializers.ValidationError: if the StructureDeifnition cannot be fetched Returns: [dict]: the instance",
... | 2 | null | Implement the Python class `ResourceSerializer` described below.
Class description:
Implement the ResourceSerializer class.
Method signatures and docstrings:
- def validate(self, data): called on resource creation. We fetch the StructureDefinition from fhir-api before validating and saving the resource to the databas... | Implement the Python class `ResourceSerializer` described below.
Class description:
Implement the ResourceSerializer class.
Method signatures and docstrings:
- def validate(self, data): called on resource creation. We fetch the StructureDefinition from fhir-api before validating and saving the resource to the databas... | 63c798deaec82ba9f3eccb64be465b6ed535b5dc | <|skeleton|>
class ResourceSerializer:
def validate(self, data):
"""called on resource creation. We fetch the StructureDefinition from fhir-api before validating and saving the resource to the database. Args: data ([dict]): the resource instance Raises: serializers.ValidationError: if the StructureDeifniti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceSerializer:
def validate(self, data):
"""called on resource creation. We fetch the StructureDefinition from fhir-api before validating and saving the resource to the database. Args: data ([dict]): the resource instance Raises: serializers.ValidationError: if the StructureDeifnition cannot be f... | the_stack_v2_python_sparse | django/pyrog/api/serializers/basic.py | arkhn/fhir-river | train | 45 | |
b604b1cbf53f80f94673790a58cd756eb702dd1b | [
"if kwargs is not None:\n for key, value in kwargs.items():\n if key == 'optimizer':\n value = optimizer_dict[value]\n if key == 'rnn':\n value = rnn_dict[value]\n setattr(self, key, value)\ndata_dir = project_dir.joinpath('datasets')\nself.dataset_dir = data_dir.joinpa... | <|body_start_0|>
if kwargs is not None:
for key, value in kwargs.items():
if key == 'optimizer':
value = optimizer_dict[value]
if key == 'rnn':
value = rnn_dict[value]
setattr(self, key, value)
data_dir =... | Config | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def __init__(self, **kwargs):
"""Configuration Class: set kwargs as class attributes with setattr"""
<|body_0|>
def __str__(self):
"""Pretty-print configurations in alphabetical order"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if kwargs... | stack_v2_sparse_classes_36k_train_022092 | 4,649 | permissive | [
{
"docstring": "Configuration Class: set kwargs as class attributes with setattr",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Pretty-print configurations in alphabetical order",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015272 | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Configuration Class: set kwargs as class attributes with setattr
- def __str__(self): Pretty-print configurations in alphabetical order | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Configuration Class: set kwargs as class attributes with setattr
- def __str__(self): Pretty-print configurations in alphabetical order
<|skeleton|>
cl... | 72c2e71f0a5068733762078dfbb5f1405ea0be00 | <|skeleton|>
class Config:
def __init__(self, **kwargs):
"""Configuration Class: set kwargs as class attributes with setattr"""
<|body_0|>
def __str__(self):
"""Pretty-print configurations in alphabetical order"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
def __init__(self, **kwargs):
"""Configuration Class: set kwargs as class attributes with setattr"""
if kwargs is not None:
for key, value in kwargs.items():
if key == 'optimizer':
value = optimizer_dict[value]
if key == '... | the_stack_v2_python_sparse | SSREM/configs.py | OpenXAIProject/Neural-Conversation-Models-Response-Evaluation | train | 11 | |
0171558f2dae06aca502e6b126119a6dc2e3c5e5 | [
"form_data = {'username': 'test@example.com', 'first_name': 'Test', 'last_name': 'Person', 'password1': 'test1234', 'password2': 'test1234'}\nform = RegistrationForm(data=form_data)\nself.assertTrue(form.is_valid())",
"form_data = {'username': '', 'first_name': '', 'last_name': '', 'password1': 'pw', 'password2':... | <|body_start_0|>
form_data = {'username': 'test@example.com', 'first_name': 'Test', 'last_name': 'Person', 'password1': 'test1234', 'password2': 'test1234'}
form = RegistrationForm(data=form_data)
self.assertTrue(form.is_valid())
<|end_body_0|>
<|body_start_1|>
form_data = {'username': ... | RegistrationTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationTests:
def test_registration_form_valid(self):
"""Valid user should be successfully created after entering all required fields."""
<|body_0|>
def test_registration_form_invalid(self):
"""Invalid user should not be created after entering the required field... | stack_v2_sparse_classes_36k_train_022093 | 5,020 | no_license | [
{
"docstring": "Valid user should be successfully created after entering all required fields.",
"name": "test_registration_form_valid",
"signature": "def test_registration_form_valid(self)"
},
{
"docstring": "Invalid user should not be created after entering the required fields.",
"name": "t... | 6 | stack_v2_sparse_classes_30k_train_011982 | Implement the Python class `RegistrationTests` described below.
Class description:
Implement the RegistrationTests class.
Method signatures and docstrings:
- def test_registration_form_valid(self): Valid user should be successfully created after entering all required fields.
- def test_registration_form_invalid(self)... | Implement the Python class `RegistrationTests` described below.
Class description:
Implement the RegistrationTests class.
Method signatures and docstrings:
- def test_registration_form_valid(self): Valid user should be successfully created after entering all required fields.
- def test_registration_form_invalid(self)... | ab1537f7e6fde1ac0f92226ebd755800e0992c12 | <|skeleton|>
class RegistrationTests:
def test_registration_form_valid(self):
"""Valid user should be successfully created after entering all required fields."""
<|body_0|>
def test_registration_form_invalid(self):
"""Invalid user should not be created after entering the required field... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationTests:
def test_registration_form_valid(self):
"""Valid user should be successfully created after entering all required fields."""
form_data = {'username': 'test@example.com', 'first_name': 'Test', 'last_name': 'Person', 'password1': 'test1234', 'password2': 'test1234'}
for... | the_stack_v2_python_sparse | accounts/tests.py | haldunanil-portfolio/cashonly | train | 1 | |
2e6a0a6d539a49274d88beacdbd7705fe8aea582 | [
"if self.resource.palette.color and len(self.resource.palette.color) > 1:\n return True\nif self.resource.palette.color_temperature and len(self.resource.palette.color_temperature) > 1:\n return True\nreturn False",
"transition = normalize_hue_transition(kwargs.get(ATTR_TRANSITION))\ndynamic = kwargs.get(AT... | <|body_start_0|>
if self.resource.palette.color and len(self.resource.palette.color) > 1:
return True
if self.resource.palette.color_temperature and len(self.resource.palette.color_temperature) > 1:
return True
return False
<|end_body_0|>
<|body_start_1|>
transit... | Representation of a Scene entity from Hue Scenes. | HueSceneEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HueSceneEntity:
"""Representation of a Scene entity from Hue Scenes."""
def is_dynamic(self) -> bool:
"""Return if this scene has a dynamic color palette."""
<|body_0|>
async def async_activate(self, **kwargs: Any) -> None:
"""Activate Hue scene."""
<|bod... | stack_v2_sparse_classes_36k_train_022094 | 8,830 | permissive | [
{
"docstring": "Return if this scene has a dynamic color palette.",
"name": "is_dynamic",
"signature": "def is_dynamic(self) -> bool"
},
{
"docstring": "Activate Hue scene.",
"name": "async_activate",
"signature": "async def async_activate(self, **kwargs: Any) -> None"
},
{
"docs... | 3 | null | Implement the Python class `HueSceneEntity` described below.
Class description:
Representation of a Scene entity from Hue Scenes.
Method signatures and docstrings:
- def is_dynamic(self) -> bool: Return if this scene has a dynamic color palette.
- async def async_activate(self, **kwargs: Any) -> None: Activate Hue sc... | Implement the Python class `HueSceneEntity` described below.
Class description:
Representation of a Scene entity from Hue Scenes.
Method signatures and docstrings:
- def is_dynamic(self) -> bool: Return if this scene has a dynamic color palette.
- async def async_activate(self, **kwargs: Any) -> None: Activate Hue sc... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class HueSceneEntity:
"""Representation of a Scene entity from Hue Scenes."""
def is_dynamic(self) -> bool:
"""Return if this scene has a dynamic color palette."""
<|body_0|>
async def async_activate(self, **kwargs: Any) -> None:
"""Activate Hue scene."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HueSceneEntity:
"""Representation of a Scene entity from Hue Scenes."""
def is_dynamic(self) -> bool:
"""Return if this scene has a dynamic color palette."""
if self.resource.palette.color and len(self.resource.palette.color) > 1:
return True
if self.resource.palette.c... | the_stack_v2_python_sparse | homeassistant/components/hue/scene.py | home-assistant/core | train | 35,501 |
40e292ea1a269fbf4b9bc44f4b502d7b7761b5d5 | [
"self.nodes, node = ([], head)\nwhile node:\n self.nodes.append(node)\n node = node.next",
"if 0 < len(self.nodes):\n return random.choice(self.nodes).val\nreturn float('inf')"
] | <|body_start_0|>
self.nodes, node = ([], head)
while node:
self.nodes.append(node)
node = node.next
<|end_body_0|>
<|body_start_1|>
if 0 < len(self.nodes):
return random.choice(self.nodes).val
return float('inf')
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_022095 | 935 | no_license | [
{
"docstring": "@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.",
"name": "__init__",
"signature": "def __init__(self, head: ListNode)"
},
{
"docstring": "Returns a random node's value.",
"name": "getRandom",
"signatu... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, head: ListNode): @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
- def getRandom(self) -... | 5376dd48b1cefb4faba9d2ef6a8a497b6b1d6c67 | <|skeleton|>
class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
<|body_0|>
def getRandom(self) -> int:
"""Returns a random node's value."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, head: ListNode):
"""@param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node."""
self.nodes, node = ([], head)
while node:
self.nodes.append(node)
node = node.next
def... | the_stack_v2_python_sparse | python/problem-linked-list/linked_list_random_node.py | hyunjun/practice | train | 3 | |
386a2076b7d1cb6836f7296bc03bf2fe9c9b8032 | [
"user_id = current_token['sub']\nwith flask.current_app.db.session as session:\n user = session.query(User).filter_by(id=user_id).first()\nresult = flask.current_app.storage_manager.list_keypairs(provider, user)\nkeys = {'access_keys': [{'access_key': item['access_key']} for item in result]}\nresult = keys\nretu... | <|body_start_0|>
user_id = current_token['sub']
with flask.current_app.db.session as session:
user = session.query(User).filter_by(id=user_id).first()
result = flask.current_app.storage_manager.list_keypairs(provider, user)
keys = {'access_keys': [{'access_key': item['access_... | For ``/credentials/<provider>`` endpoint. | OtherCredentialsList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OtherCredentialsList:
"""For ``/credentials/<provider>`` endpoint."""
def get(self, provider):
"""List access keys for user **Example:** .. code-block:: http POST /credentials/apis/ HTTP/1.1 Content-Type: application/json Accept: application/json .. code-block:: JavaScript { "access_... | stack_v2_sparse_classes_36k_train_022096 | 3,009 | permissive | [
{
"docstring": "List access keys for user **Example:** .. code-block:: http POST /credentials/apis/ HTTP/1.1 Content-Type: application/json Accept: application/json .. code-block:: JavaScript { \"access_keys\": [ { \"access_key\": \"8DGW9LyC0D4nByoWo6pp\", } ] }",
"name": "get",
"signature": "def get(se... | 2 | null | Implement the Python class `OtherCredentialsList` described below.
Class description:
For ``/credentials/<provider>`` endpoint.
Method signatures and docstrings:
- def get(self, provider): List access keys for user **Example:** .. code-block:: http POST /credentials/apis/ HTTP/1.1 Content-Type: application/json Accep... | Implement the Python class `OtherCredentialsList` described below.
Class description:
For ``/credentials/<provider>`` endpoint.
Method signatures and docstrings:
- def get(self, provider): List access keys for user **Example:** .. code-block:: http POST /credentials/apis/ HTTP/1.1 Content-Type: application/json Accep... | ea885f0e882d8e6bb5db7670c4025bb8e282cdfc | <|skeleton|>
class OtherCredentialsList:
"""For ``/credentials/<provider>`` endpoint."""
def get(self, provider):
"""List access keys for user **Example:** .. code-block:: http POST /credentials/apis/ HTTP/1.1 Content-Type: application/json Accept: application/json .. code-block:: JavaScript { "access_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OtherCredentialsList:
"""For ``/credentials/<provider>`` endpoint."""
def get(self, provider):
"""List access keys for user **Example:** .. code-block:: http POST /credentials/apis/ HTTP/1.1 Content-Type: application/json Accept: application/json .. code-block:: JavaScript { "access_keys": [ { "a... | the_stack_v2_python_sparse | fence/blueprints/storage_creds/other.py | uc-cdis/fence | train | 42 |
9007d7bb2d213ebcca64a38448d8c789a906bd3c | [
"self.positions = positions\nself.position_vals = []\nself.num_trials = num_trials\ntry:\n self.num_trials = int(num_trials)\nexcept:\n raise TypeError\nelse:\n if self.num_trials <= 0:\n raise ValueError\n for i in self.positions:\n self.position_vals.append(int(i) / 1000)",
"num_shares... | <|body_start_0|>
self.positions = positions
self.position_vals = []
self.num_trials = num_trials
try:
self.num_trials = int(num_trials)
except:
raise TypeError
else:
if self.num_trials <= 0:
raise ValueError
... | this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user | Investment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Investment:
"""this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user"""
def __init__(self, positions, num_trials):
"""Initializes the position list and number of simulations"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_022097 | 1,888 | no_license | [
{
"docstring": "Initializes the position list and number of simulations",
"name": "__init__",
"signature": "def __init__(self, positions, num_trials)"
},
{
"docstring": "generates the outcome of betting a total of $1000, given a position value ie. if the position value is 1, it generates the out... | 3 | stack_v2_sparse_classes_30k_train_021367 | Implement the Python class `Investment` described below.
Class description:
this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user
Method signatures and docstrings:
- def __init__(self, positions, num_trials): Initializes the posi... | Implement the Python class `Investment` described below.
Class description:
this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user
Method signatures and docstrings:
- def __init__(self, positions, num_trials): Initializes the posi... | 068db95cef0c693ad833fcfe968aa0b5db2162cd | <|skeleton|>
class Investment:
"""this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user"""
def __init__(self, positions, num_trials):
"""Initializes the position list and number of simulations"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Investment:
"""this class includes the functions and initialization method for the list of positions and number of simulations that will be input by the user"""
def __init__(self, positions, num_trials):
"""Initializes the position list and number of simulations"""
self.positions = positi... | the_stack_v2_python_sparse | neb330/Investment.py | whirlkick/assignment8 | train | 0 |
de9e106ce3605acdd4425ee99b856a83374db9f4 | [
"queryset = super(CategoryAdmin, self).get_queryset(request)\nif request.user.is_superuser:\n return queryset\nreturn queryset.filter(author_id=request.user.id)",
"if not obj.author:\n obj.author = request.user\nobj.save()"
] | <|body_start_0|>
queryset = super(CategoryAdmin, self).get_queryset(request)
if request.user.is_superuser:
return queryset
return queryset.filter(author_id=request.user.id)
<|end_body_0|>
<|body_start_1|>
if not obj.author:
obj.author = request.user
obj.s... | CategoryAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryAdmin:
def get_queryset(self, request):
"""Show only categories created by user"""
<|body_0|>
def save_model(self, request, obj, form, change):
"""Save the user that create the category as author"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_022098 | 4,618 | no_license | [
{
"docstring": "Show only categories created by user",
"name": "get_queryset",
"signature": "def get_queryset(self, request)"
},
{
"docstring": "Save the user that create the category as author",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
}
] | 2 | null | Implement the Python class `CategoryAdmin` described below.
Class description:
Implement the CategoryAdmin class.
Method signatures and docstrings:
- def get_queryset(self, request): Show only categories created by user
- def save_model(self, request, obj, form, change): Save the user that create the category as auth... | Implement the Python class `CategoryAdmin` described below.
Class description:
Implement the CategoryAdmin class.
Method signatures and docstrings:
- def get_queryset(self, request): Show only categories created by user
- def save_model(self, request, obj, form, change): Save the user that create the category as auth... | 3df3984339780f0974aa3da34f955486dd785c88 | <|skeleton|>
class CategoryAdmin:
def get_queryset(self, request):
"""Show only categories created by user"""
<|body_0|>
def save_model(self, request, obj, form, change):
"""Save the user that create the category as author"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryAdmin:
def get_queryset(self, request):
"""Show only categories created by user"""
queryset = super(CategoryAdmin, self).get_queryset(request)
if request.user.is_superuser:
return queryset
return queryset.filter(author_id=request.user.id)
def save_model... | the_stack_v2_python_sparse | healthylife/shop/admin.py | AlbertoSanmartinMartinez/HealthyLife | train | 0 | |
e125e655a8febcb816ca069eaaa3bbd2076ae4e7 | [
"super(TCNLayer, self).__init__()\nself.norm_1 = GroupNormWrapper(generated, E_1, E_2, 8, H, eps=1e-08)\nself.prelu_1 = nn.PReLU()\nself.conv1d = Conv1dWrapper(generated, E_1, E_2, B, H, 1, bias=False)\nself.norm_2 = GroupNormWrapper(generated, E_1, E_2, 8, H, eps=1e-08)\nself.prelu_2 = nn.PReLU()\nself.dconv1d = C... | <|body_start_0|>
super(TCNLayer, self).__init__()
self.norm_1 = GroupNormWrapper(generated, E_1, E_2, 8, H, eps=1e-08)
self.prelu_1 = nn.PReLU()
self.conv1d = Conv1dWrapper(generated, E_1, E_2, B, H, 1, bias=False)
self.norm_2 = GroupNormWrapper(generated, E_1, E_2, 8, H, eps=1e-... | One layer of the dilated temporal convolution with bottleneck | TCNLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCNLayer:
"""One layer of the dilated temporal convolution with bottleneck"""
def __init__(self, generated, E_1, E_2, B, H, Sc, kernel, residual_bias, padding, dilation=1):
"""Arguments: generated {bool} -- True if you want to use the generated weights E_1 {int} -- Dimension of the i... | stack_v2_sparse_classes_36k_train_022099 | 37,269 | no_license | [
{
"docstring": "Arguments: generated {bool} -- True if you want to use the generated weights E_1 {int} -- Dimension of the instrument embedding E_2 {int} -- Dimension of the instrument embedding bottleneck B {int} -- Dimension of the bottleneck convolution H {int} -- Hidden dimension Sc {int} -- Skip-connection... | 2 | stack_v2_sparse_classes_30k_train_018281 | Implement the Python class `TCNLayer` described below.
Class description:
One layer of the dilated temporal convolution with bottleneck
Method signatures and docstrings:
- def __init__(self, generated, E_1, E_2, B, H, Sc, kernel, residual_bias, padding, dilation=1): Arguments: generated {bool} -- True if you want to ... | Implement the Python class `TCNLayer` described below.
Class description:
One layer of the dilated temporal convolution with bottleneck
Method signatures and docstrings:
- def __init__(self, generated, E_1, E_2, B, H, Sc, kernel, residual_bias, padding, dilation=1): Arguments: generated {bool} -- True if you want to ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TCNLayer:
"""One layer of the dilated temporal convolution with bottleneck"""
def __init__(self, generated, E_1, E_2, B, H, Sc, kernel, residual_bias, padding, dilation=1):
"""Arguments: generated {bool} -- True if you want to use the generated weights E_1 {int} -- Dimension of the i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TCNLayer:
"""One layer of the dilated temporal convolution with bottleneck"""
def __init__(self, generated, E_1, E_2, B, H, Sc, kernel, residual_bias, padding, dilation=1):
"""Arguments: generated {bool} -- True if you want to use the generated weights E_1 {int} -- Dimension of the instrument emb... | the_stack_v2_python_sparse | generated/test_pfnet_research_meta_tasnet.py | jansel/pytorch-jit-paritybench | train | 35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.