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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45a06bc7c418d3e49a03b2dff15a33cb2e25bc66 | [
"def dfs(node, vals):\n if not node:\n return\n vals.append(str(node.val))\n for child in node.children:\n dfs(child, vals)\n vals.append('#')\nvals = []\ndfs(root, vals)\nreturn ' '.join(vals)",
"def isplit(source, sep):\n sepsize = len(sep)\n start = 0\n while True:\n i... | <|body_start_0|>
def dfs(node, vals):
if not node:
return
vals.append(str(node.val))
for child in node.children:
dfs(child, vals)
vals.append('#')
vals = []
dfs(root, vals)
return ' '.join(vals)
<|end_body_0|... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
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_0|... | stack_v2_sparse_classes_36k_train_030700 | 1,514 | permissive | [
{
"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 `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class Codec:
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 Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
def dfs(node, vals):
if not node:
return
vals.append(str(node.val))
for child in node.children:
dfs(child, vals)
... | the_stack_v2_python_sparse | Python/serialize-and-deserialize-n-ary-tree.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
13bf17edb20b60bef2ca1380fc1df989cf64456c | [
"self.url = url\nself.auth_token = auth_token\nself.xapi_version = xapi_version",
"headers = {'Authorization': self.auth_token, 'Content-Type': 'application/json', 'X-Experience-API-Version': self.xapi_version}\nresponse = requests.post(self.url, json=xapi_statement.get_statement(), headers=headers, timeout=setti... | <|body_start_0|>
self.url = url
self.auth_token = auth_token
self.xapi_version = xapi_version
<|end_body_0|>
<|body_start_1|>
headers = {'Authorization': self.auth_token, 'Content-Type': 'application/json', 'X-Experience-API-Version': self.xapi_version}
response = requests.post(... | The XAPI object compute statements and send them to a LRS. | XAPI | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XAPI:
"""The XAPI object compute statements and send them to a LRS."""
def __init__(self, url, auth_token, xapi_version='1.0.3'):
"""Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on... | stack_v2_sparse_classes_36k_train_030701 | 11,009 | permissive | [
{
"docstring": "Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on the LRS xapi_version: string The xAPI version used.",
"name": "__init__",
"signature": "def __init__(self, url, auth_token, xapi_version... | 2 | stack_v2_sparse_classes_30k_train_015606 | Implement the Python class `XAPI` described below.
Class description:
The XAPI object compute statements and send them to a LRS.
Method signatures and docstrings:
- def __init__(self, url, auth_token, xapi_version='1.0.3'): Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_t... | Implement the Python class `XAPI` described below.
Class description:
The XAPI object compute statements and send them to a LRS.
Method signatures and docstrings:
- def __init__(self, url, auth_token, xapi_version='1.0.3'): Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_t... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class XAPI:
"""The XAPI object compute statements and send them to a LRS."""
def __init__(self, url, auth_token, xapi_version='1.0.3'):
"""Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XAPI:
"""The XAPI object compute statements and send them to a LRS."""
def __init__(self, url, auth_token, xapi_version='1.0.3'):
"""Initialize the XAPI module. Parameters ---------- url: string The LRS endpoint to fetch auth_token: string The basic_auth token used to authenticate on the LRS xapi... | the_stack_v2_python_sparse | src/backend/marsha/core/xapi.py | openfun/marsha | train | 92 |
a52a95a60b0268bf776a580a761a464295e18229 | [
"def dfs(left, right):\n if left > right:\n return [None]\n res = []\n for i in range(left, right + 1):\n leftNode = dfs(left, i - 1)\n rightNode = dfs(i + 1, right)\n for l in leftNode:\n for r in rightNode:\n root = TreeNode(i)\n root.l... | <|body_start_0|>
def dfs(left, right):
if left > right:
return [None]
res = []
for i in range(left, right + 1):
leftNode = dfs(left, i - 1)
rightNode = dfs(i + 1, right)
for l in leftNode:
for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def numTrees(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dfs(left, right):
if left > right:
... | stack_v2_sparse_classes_36k_train_030702 | 1,446 | no_license | [
{
"docstring": ":type n: int :rtype: List[TreeNode]",
"name": "generateTrees",
"signature": "def generateTrees(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numTrees",
"signature": "def numTrees(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009875 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def numTrees(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateTrees(self, n): :type n: int :rtype: List[TreeNode]
- def numTrees(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def generateTrees(self, n):
... | 2418b3eed1ab85cfd9cac039c6cfdc1a349ad345 | <|skeleton|>
class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
<|body_0|>
def numTrees(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateTrees(self, n):
""":type n: int :rtype: List[TreeNode]"""
def dfs(left, right):
if left > right:
return [None]
res = []
for i in range(left, right + 1):
leftNode = dfs(left, i - 1)
rightNo... | the_stack_v2_python_sparse | leetcode-first_time/leetcode95-96(unique binary search tree).py | HopeCheung/leetcode | train | 0 | |
f12830a2f253bf50146c5d6a1aea20775c3058a1 | [
"world = World()\nworld.collaborative = True\nworld.dimension_communication = 10\nworld.agents = [Agent() for i in range(2)]\nfor i, agent in enumerate(world.agents):\n agent.name = 'agent {}'.format(i)\n agent.collide = False\nworld.landmarks = [Landmark() for i in range(3)]\nfor i, landmark in enumerate(wor... | <|body_start_0|>
world = World()
world.collaborative = True
world.dimension_communication = 10
world.agents = [Agent() for i in range(2)]
for i, agent in enumerate(world.agents):
agent.name = 'agent {}'.format(i)
agent.collide = False
world.landmar... | Define the world, reward, and observations for the scenario. | Scenario | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scenario:
"""Define the world, reward, and observations for the scenario."""
def make_world(self, args=None):
"""Construct the world Returns: world (multiagent_particle_env.core.World): World object with agents and landmarks"""
<|body_0|>
def reset_world(self, world):
... | stack_v2_sparse_classes_36k_train_030703 | 5,797 | permissive | [
{
"docstring": "Construct the world Returns: world (multiagent_particle_env.core.World): World object with agents and landmarks",
"name": "make_world",
"signature": "def make_world(self, args=None)"
},
{
"docstring": "Reset the world to the initial conditions. Args: world (multiagent_particle_en... | 4 | stack_v2_sparse_classes_30k_train_015605 | Implement the Python class `Scenario` described below.
Class description:
Define the world, reward, and observations for the scenario.
Method signatures and docstrings:
- def make_world(self, args=None): Construct the world Returns: world (multiagent_particle_env.core.World): World object with agents and landmarks
- ... | Implement the Python class `Scenario` described below.
Class description:
Define the world, reward, and observations for the scenario.
Method signatures and docstrings:
- def make_world(self, args=None): Construct the world Returns: world (multiagent_particle_env.core.World): World object with agents and landmarks
- ... | f2644a9c1c7472d0a0475fd59207d15b84e73862 | <|skeleton|>
class Scenario:
"""Define the world, reward, and observations for the scenario."""
def make_world(self, args=None):
"""Construct the world Returns: world (multiagent_particle_env.core.World): World object with agents and landmarks"""
<|body_0|>
def reset_world(self, world):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Scenario:
"""Define the world, reward, and observations for the scenario."""
def make_world(self, args=None):
"""Construct the world Returns: world (multiagent_particle_env.core.World): World object with agents and landmarks"""
world = World()
world.collaborative = True
wo... | the_stack_v2_python_sparse | Multi_Agent_Particle_Environment/multiagent_particle_env/scenarios/openai/simple_reference.py | guyna25/speakerListnerRLlibEnv | train | 1 |
d5ba63c82e9e5f2b6af8084d93817476934db7e6 | [
"self.obj = None\nself.source_obj = None\nself.description = ''\nself.count = 0\nself.objection = UVMObjection()",
"self.obj = None\nself.source_obj = None\nself.description = ''\nself.count = 0\nself.objection = UVMObjection()"
] | <|body_start_0|>
self.obj = None
self.source_obj = None
self.description = ''
self.count = 0
self.objection = UVMObjection()
<|end_body_0|>
<|body_start_1|>
self.obj = None
self.source_obj = None
self.description = ''
self.count = 0
self.o... | UVMObjectionContextObject | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UVMObjectionContextObject:
def __init__(self):
"""uvm_object obj uvm_object source_obj string description int count uvm_objection objection"""
<|body_0|>
def clear(self):
"""Clears the values stored within the object, preventing memory leaks from reused objects"""
... | stack_v2_sparse_classes_36k_train_030704 | 49,193 | permissive | [
{
"docstring": "uvm_object obj uvm_object source_obj string description int count uvm_objection objection",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Clears the values stored within the object, preventing memory leaks from reused objects",
"name": "clear",
... | 2 | stack_v2_sparse_classes_30k_train_013066 | Implement the Python class `UVMObjectionContextObject` described below.
Class description:
Implement the UVMObjectionContextObject class.
Method signatures and docstrings:
- def __init__(self): uvm_object obj uvm_object source_obj string description int count uvm_objection objection
- def clear(self): Clears the valu... | Implement the Python class `UVMObjectionContextObject` described below.
Class description:
Implement the UVMObjectionContextObject class.
Method signatures and docstrings:
- def __init__(self): uvm_object obj uvm_object source_obj string description int count uvm_objection objection
- def clear(self): Clears the valu... | fc5f955701b2b56c1fddac195c70cb3ebb9139fe | <|skeleton|>
class UVMObjectionContextObject:
def __init__(self):
"""uvm_object obj uvm_object source_obj string description int count uvm_objection objection"""
<|body_0|>
def clear(self):
"""Clears the values stored within the object, preventing memory leaks from reused objects"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UVMObjectionContextObject:
def __init__(self):
"""uvm_object obj uvm_object source_obj string description int count uvm_objection objection"""
self.obj = None
self.source_obj = None
self.description = ''
self.count = 0
self.objection = UVMObjection()
def cl... | the_stack_v2_python_sparse | src/uvm/base/uvm_objection.py | tpoikela/uvm-python | train | 199 | |
ae3c32b93921c5df08d556c4b36f8d4678ca8993 | [
"self.max_num = maxChoosableInteger\nif (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal or desiredTotal < 0:\n return False\nif maxChoosableInteger >= desiredTotal:\n return True\nself.d = dict()\nreturn self.dfs(desiredTotal, 0)",
"if total <= 0:\n return False\nif choose in self.d:\... | <|body_start_0|>
self.max_num = maxChoosableInteger
if (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal or desiredTotal < 0:
return False
if maxChoosableInteger >= desiredTotal:
return True
self.d = dict()
return self.dfs(desiredTotal, 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
<|body_0|>
def dfs(self, total, choose):
"""深度搜索 :type total: int :type choose: int"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_030705 | 4,497 | no_license | [
{
"docstring": ":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool",
"name": "canIWin",
"signature": "def canIWin(self, maxChoosableInteger, desiredTotal)"
},
{
"docstring": "深度搜索 :type total: int :type choose: int",
"name": "dfs",
"signature": "def dfs(self, total, choo... | 2 | stack_v2_sparse_classes_30k_train_015204 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool
- def dfs(self, total, choose): 深度搜索 :type total: int :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canIWin(self, maxChoosableInteger, desiredTotal): :type maxChoosableInteger: int :type desiredTotal: int :rtype: bool
- def dfs(self, total, choose): 深度搜索 :type total: int :t... | f832227c4d0e0b1c0cc326561187004ef24e2a68 | <|skeleton|>
class Solution:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
<|body_0|>
def dfs(self, total, choose):
"""深度搜索 :type total: int :type choose: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canIWin(self, maxChoosableInteger, desiredTotal):
""":type maxChoosableInteger: int :type desiredTotal: int :rtype: bool"""
self.max_num = maxChoosableInteger
if (maxChoosableInteger + 1) * maxChoosableInteger / 2 <= desiredTotal or desiredTotal < 0:
return Fa... | the_stack_v2_python_sparse | 464.py | Gackle/leetcode_practice | train | 0 | |
135ec78fe3799f98774f33ad18c15172e93e9447 | [
"common_flags.consumer_service_flag(suffix='to disable').AddToParser(parser)\nbase.ASYNC_FLAG.AddToParser(parser)\nparser.add_argument('--force', action='store_true', help='If specified, the disable call will proceed even if there are enabled services which depend on the service to be disabled. Forcing the call mea... | <|body_start_0|>
common_flags.consumer_service_flag(suffix='to disable').AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--force', action='store_true', help='If specified, the disable call will proceed even if there are enabled services which depend on the service to... | Disable a service for consumption for a project. This command disables one or more previously-enabled services for consumption. To see a list of the enabled services for a project, run: $ {parent_command} list More information on listing services can be found at: https://cloud.google.com/service-usage/docs/list-service... | Disable | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Disable:
"""Disable a service for consumption for a project. This command disables one or more previously-enabled services for consumption. To see a list of the enabled services for a project, run: $ {parent_command} list More information on listing services can be found at: https://cloud.google.... | stack_v2_sparse_classes_36k_train_030706 | 4,048 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_005491 | Implement the Python class `Disable` described below.
Class description:
Disable a service for consumption for a project. This command disables one or more previously-enabled services for consumption. To see a list of the enabled services for a project, run: $ {parent_command} list More information on listing services... | Implement the Python class `Disable` described below.
Class description:
Disable a service for consumption for a project. This command disables one or more previously-enabled services for consumption. To see a list of the enabled services for a project, run: $ {parent_command} list More information on listing services... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Disable:
"""Disable a service for consumption for a project. This command disables one or more previously-enabled services for consumption. To see a list of the enabled services for a project, run: $ {parent_command} list More information on listing services can be found at: https://cloud.google.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Disable:
"""Disable a service for consumption for a project. This command disables one or more previously-enabled services for consumption. To see a list of the enabled services for a project, run: $ {parent_command} list More information on listing services can be found at: https://cloud.google.com/service-u... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/services/disable.py | bopopescu/socialliteapp | train | 0 |
a6bdb2edf5d71acdc075fb2864fb34afcff7f321 | [
"n = len(w)\nmemo = [[-1 for _ in range(C + 1)] for _ in range(n)]\nreturn self.bestValue(w, v, n - 1, C, memo)",
"if idx < 0 or c < 0:\n return 0\nif memo[idx][c] != -1:\n return memo[idx][c]\nres = self.bestValue(w, v, idx - 1, c, memo)\nif c >= w[idx]:\n res = max(res, v[idx] + self.bestValue(w, v, id... | <|body_start_0|>
n = len(w)
memo = [[-1 for _ in range(C + 1)] for _ in range(n)]
return self.bestValue(w, v, n - 1, C, memo)
<|end_body_0|>
<|body_start_1|>
if idx < 0 or c < 0:
return 0
if memo[idx][c] != -1:
return memo[idx][c]
res = self.bestV... | a top-down solution | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""a top-down solution"""
def knapsack(self, w, v, C):
""":param w: weight of every knapsack :param v: value :param C: capacity :return: best combination value"""
<|body_0|>
def bestValue(self, w, v, idx, c, memo):
"""考虑从[0, idx]的物品中,填充容量为c的背包能获得的最大价值""... | stack_v2_sparse_classes_36k_train_030707 | 3,991 | no_license | [
{
"docstring": ":param w: weight of every knapsack :param v: value :param C: capacity :return: best combination value",
"name": "knapsack",
"signature": "def knapsack(self, w, v, C)"
},
{
"docstring": "考虑从[0, idx]的物品中,填充容量为c的背包能获得的最大价值",
"name": "bestValue",
"signature": "def bestValue(s... | 2 | null | Implement the Python class `Solution` described below.
Class description:
a top-down solution
Method signatures and docstrings:
- def knapsack(self, w, v, C): :param w: weight of every knapsack :param v: value :param C: capacity :return: best combination value
- def bestValue(self, w, v, idx, c, memo): 考虑从[0, idx]的物品... | Implement the Python class `Solution` described below.
Class description:
a top-down solution
Method signatures and docstrings:
- def knapsack(self, w, v, C): :param w: weight of every knapsack :param v: value :param C: capacity :return: best combination value
- def bestValue(self, w, v, idx, c, memo): 考虑从[0, idx]的物品... | b9a2bd8385e44cc79454f9c7f2146370896559ec | <|skeleton|>
class Solution:
"""a top-down solution"""
def knapsack(self, w, v, C):
""":param w: weight of every knapsack :param v: value :param C: capacity :return: best combination value"""
<|body_0|>
def bestValue(self, w, v, idx, c, memo):
"""考虑从[0, idx]的物品中,填充容量为c的背包能获得的最大价值""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""a top-down solution"""
def knapsack(self, w, v, C):
""":param w: weight of every knapsack :param v: value :param C: capacity :return: best combination value"""
n = len(w)
memo = [[-1 for _ in range(C + 1)] for _ in range(n)]
return self.bestValue(w, v, n - 1, ... | the_stack_v2_python_sparse | SU_0-1knapsack.py | haveGrasses/Algorithm | train | 0 |
1b8966dab0538a1e9b8ed464c26ff46fe285eed0 | [
"if not intervals:\n return 0\nintervals.sort()\nroom_num = 1\nrooms = [[] for _ in intervals]\nrooms[0].append(intervals[0])\nfor i in range(1, len(intervals)):\n for j in range(len(rooms)):\n if rooms[j] != []:\n last_int = rooms[j][-1]\n if intervals[i][0] >= last_int[1]:\n ... | <|body_start_0|>
if not intervals:
return 0
intervals.sort()
room_num = 1
rooms = [[] for _ in intervals]
rooms[0].append(intervals[0])
for i in range(1, len(intervals)):
for j in range(len(rooms)):
if rooms[j] != []:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
"""Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created"""
<|body_0|>
def minMeetingRoomsH... | stack_v2_sparse_classes_36k_train_030708 | 2,318 | no_license | [
{
"docstring": "Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created",
"name": "minMeetingRooms",
"signature": "def minMeetingRooms(self, intervals)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_003800 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMeetingRooms(self, intervals): Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current ... | 7eddbc93a237d1d5cabcdc67806b01ff55ea8562 | <|skeleton|>
class Solution:
def minMeetingRooms(self, intervals):
"""Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created"""
<|body_0|>
def minMeetingRoomsH... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minMeetingRooms(self, intervals):
"""Algorithm: go through all the intervals, and see if current interval can be added to a existing room, if not, create a new room for current interval return the final number of rooms created"""
if not intervals:
return 0
int... | the_stack_v2_python_sparse | LeetCode Problems/Array/Meeting Rooms II.py | GZHOUW/Algorithm | train | 0 | |
f2bbf92e75452096ad0cfb72f7046790e340e4d0 | [
"if not nums:\n return [[]]\nres = []\nfor idx, num in enumerate(nums):\n subsets = self.permute(nums[:idx] + nums[idx + 1:])\n res.extend(map(lambda x: [num] + x, subsets))\nreturn res",
"if not nums:\n return [[]]\nres = []\nexplored = set()\nfor idx, num in enumerate(nums):\n if num not in explo... | <|body_start_0|>
if not nums:
return [[]]
res = []
for idx, num in enumerate(nums):
subsets = self.permute(nums[:idx] + nums[idx + 1:])
res.extend(map(lambda x: [num] + x, subsets))
return res
<|end_body_0|>
<|body_start_1|>
if not nums:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def permuteUnique(self, nums):
""":type nums: List[int... | stack_v2_sparse_classes_36k_train_030709 | 2,920 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": ":t... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique(self, nu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def permuteUnique(self, nu... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
def permuteUnique(self, nums):
""":type nums: List[int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
if not nums:
return [[]]
res = []
for idx, num in enumerate(nums):
subsets = self.permute(nums[:idx] + nums[idx + 1:])
res.extend(map(lambda x: [num] + x, ... | the_stack_v2_python_sparse | LeetCodes/Google/permutation.py | chutianwen/LeetCodes | train | 0 | |
719d78b5fc72a0524b9c6c21fc50e2df08176e42 | [
"super().__init__()\nself.init_point = init_point\nself.groups = groups",
"if X.shape[-2] != 1:\n raise NotImplementedError('group-lasso has not been implemented for q>1 yet.')\nregularization_term = group_lasso_regularizer(X=X.squeeze(-2) - self.init_point, groups=self.groups)\nreturn regularization_term"
] | <|body_start_0|>
super().__init__()
self.init_point = init_point
self.groups = groups
<|end_body_0|>
<|body_start_1|>
if X.shape[-2] != 1:
raise NotImplementedError('group-lasso has not been implemented for q>1 yet.')
regularization_term = group_lasso_regularizer(X=X... | Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction. | GroupLassoPenalty | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupLassoPenalty:
"""Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction."""
def __init__(self, init_point: Tensor, groups: List[List[int]]):
"""Initializing Group-Lasso regularization. Args: init_point: The "1 x di... | stack_v2_sparse_classes_36k_train_030710 | 14,396 | permissive | [
{
"docstring": "Initializing Group-Lasso regularization. Args: init_point: The \"1 x dim\" reference point against which we want to regularize. groups: Groups of indices used in group lasso.",
"name": "__init__",
"signature": "def __init__(self, init_point: Tensor, groups: List[List[int]])"
},
{
... | 2 | null | Implement the Python class `GroupLassoPenalty` described below.
Class description:
Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction.
Method signatures and docstrings:
- def __init__(self, init_point: Tensor, groups: List[List[int]]): Initializing ... | Implement the Python class `GroupLassoPenalty` described below.
Class description:
Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction.
Method signatures and docstrings:
- def __init__(self, init_point: Tensor, groups: List[List[int]]): Initializing ... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class GroupLassoPenalty:
"""Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction."""
def __init__(self, init_point: Tensor, groups: List[List[int]]):
"""Initializing Group-Lasso regularization. Args: init_point: The "1 x di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupLassoPenalty:
"""Group lasso penalty class to be added to any arbitrary acquisition function to construct a PenalizedAcquisitionFunction."""
def __init__(self, init_point: Tensor, groups: List[List[int]]):
"""Initializing Group-Lasso regularization. Args: init_point: The "1 x dim" reference ... | the_stack_v2_python_sparse | botorch/acquisition/penalized.py | pytorch/botorch | train | 2,891 |
15327cc9a8d3a4c854cc81639fbc37c06c5733b2 | [
"population_size = size\npopulation = g.Population(size=population_size)\nassert population.population_size == population_size, 'population size was incorrect, should have been {}'.format(population_size)",
"gene_size = size\nindividual = g.Individual(size=gene_size)\nassert len(individual.genes) == gene_size",
... | <|body_start_0|>
population_size = size
population = g.Population(size=population_size)
assert population.population_size == population_size, 'population size was incorrect, should have been {}'.format(population_size)
<|end_body_0|>
<|body_start_1|>
gene_size = size
individual ... | Test object initialization | TestSize | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSize:
"""Test object initialization"""
def test_population_size_init(self, size):
"""Test initialized population size"""
<|body_0|>
def test_individual_genes_len(self, size):
"""Test initialized individual size"""
<|body_1|>
def test_negative_err... | stack_v2_sparse_classes_36k_train_030711 | 1,259 | permissive | [
{
"docstring": "Test initialized population size",
"name": "test_population_size_init",
"signature": "def test_population_size_init(self, size)"
},
{
"docstring": "Test initialized individual size",
"name": "test_individual_genes_len",
"signature": "def test_individual_genes_len(self, si... | 3 | stack_v2_sparse_classes_30k_train_008663 | Implement the Python class `TestSize` described below.
Class description:
Test object initialization
Method signatures and docstrings:
- def test_population_size_init(self, size): Test initialized population size
- def test_individual_genes_len(self, size): Test initialized individual size
- def test_negative_error(s... | Implement the Python class `TestSize` described below.
Class description:
Test object initialization
Method signatures and docstrings:
- def test_population_size_init(self, size): Test initialized population size
- def test_individual_genes_len(self, size): Test initialized individual size
- def test_negative_error(s... | 8dcbf792c7022fa8b6ba98290d50580c61adcd53 | <|skeleton|>
class TestSize:
"""Test object initialization"""
def test_population_size_init(self, size):
"""Test initialized population size"""
<|body_0|>
def test_individual_genes_len(self, size):
"""Test initialized individual size"""
<|body_1|>
def test_negative_err... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSize:
"""Test object initialization"""
def test_population_size_init(self, size):
"""Test initialized population size"""
population_size = size
population = g.Population(size=population_size)
assert population.population_size == population_size, 'population size was in... | the_stack_v2_python_sparse | experiments/ga_demo/test_genetic_demo.py | the3eyes/neat | train | 0 |
2550ecc84e8f4a7a9e0957362ecf2c1dbfcfd59f | [
"if root is None:\n return []\nresult = [root]\nseen = set([root])\nwhile result:\n current = result[-1]\n seen.add(current)\n if current is node:\n break\n elif current.left and current.left not in seen:\n result.append(current.left)\n elif current.right and current.right not in see... | <|body_start_0|>
if root is None:
return []
result = [root]
seen = set([root])
while result:
current = result[-1]
seen.add(current)
if current is node:
break
elif current.left and current.left not in seen:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def ancestors(self, root, node):
""":param root: :param node: :return: >>> s = Solution() >>> root = TreeNode(None).from_string("3,5,1,6,2,0,8,#,#,7,4") >>> node = root.left >>> result = [n.val for n in s.ancestors(root, node)] >>> result [3, 5] >>> node = root.left.right.right... | stack_v2_sparse_classes_36k_train_030712 | 2,210 | no_license | [
{
"docstring": ":param root: :param node: :return: >>> s = Solution() >>> root = TreeNode(None).from_string(\"3,5,1,6,2,0,8,#,#,7,4\") >>> node = root.left >>> result = [n.val for n in s.ancestors(root, node)] >>> result [3, 5] >>> node = root.left.right.right >>> result = [n.val for n in s.ancestors(root, node... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ancestors(self, root, node): :param root: :param node: :return: >>> s = Solution() >>> root = TreeNode(None).from_string("3,5,1,6,2,0,8,#,#,7,4") >>> node = root.left >>> res... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def ancestors(self, root, node): :param root: :param node: :return: >>> s = Solution() >>> root = TreeNode(None).from_string("3,5,1,6,2,0,8,#,#,7,4") >>> node = root.left >>> res... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def ancestors(self, root, node):
""":param root: :param node: :return: >>> s = Solution() >>> root = TreeNode(None).from_string("3,5,1,6,2,0,8,#,#,7,4") >>> node = root.left >>> result = [n.val for n in s.ancestors(root, node)] >>> result [3, 5] >>> node = root.left.right.right... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def ancestors(self, root, node):
""":param root: :param node: :return: >>> s = Solution() >>> root = TreeNode(None).from_string("3,5,1,6,2,0,8,#,#,7,4") >>> node = root.left >>> result = [n.val for n in s.ancestors(root, node)] >>> result [3, 5] >>> node = root.left.right.right >>> result = ... | the_stack_v2_python_sparse | lca_of_bt.py | gsy/leetcode | train | 1 | |
64c205c66879ce9b153b5476d91bacf986692feb | [
"super().__init__()\nself.register_buffer('support', torch.linspace(vmin, vmax, n_atoms))\nself.fc1 = nn.Linear(state_size, 256)\nself.fc2 = nn.Linear(256 + action_size, 256)\nself.fc3 = nn.Linear(256, 128)\nself.fc4 = nn.Linear(128, n_atoms)",
"x = F.leaky_relu(self.fc1(state))\nx = torch.cat([x, action], dim=1)... | <|body_start_0|>
super().__init__()
self.register_buffer('support', torch.linspace(vmin, vmax, n_atoms))
self.fc1 = nn.Linear(state_size, 256)
self.fc2 = nn.Linear(256 + action_size, 256)
self.fc3 = nn.Linear(256, 128)
self.fc4 = nn.Linear(128, n_atoms)
<|end_body_0|>
<|... | Distributional Value Model | Critic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Distributional Value Model"""
def __init__(self, state_size, action_size, vmin, vmax, n_atoms=51):
"""Initialize parameters and build model. Parameters ---------- state_size : int Dimension of each state action_size : int Dimension of each action vmin, vmax : float Upper &... | stack_v2_sparse_classes_36k_train_030713 | 2,383 | no_license | [
{
"docstring": "Initialize parameters and build model. Parameters ---------- state_size : int Dimension of each state action_size : int Dimension of each action vmin, vmax : float Upper & Lower bounds of the support n_atoms : int Number of bins in the support",
"name": "__init__",
"signature": "def __in... | 2 | stack_v2_sparse_classes_30k_train_001780 | Implement the Python class `Critic` described below.
Class description:
Distributional Value Model
Method signatures and docstrings:
- def __init__(self, state_size, action_size, vmin, vmax, n_atoms=51): Initialize parameters and build model. Parameters ---------- state_size : int Dimension of each state action_size ... | Implement the Python class `Critic` described below.
Class description:
Distributional Value Model
Method signatures and docstrings:
- def __init__(self, state_size, action_size, vmin, vmax, n_atoms=51): Initialize parameters and build model. Parameters ---------- state_size : int Dimension of each state action_size ... | f6d450e0c68236bf493689bffef48a0f3723416d | <|skeleton|>
class Critic:
"""Distributional Value Model"""
def __init__(self, state_size, action_size, vmin, vmax, n_atoms=51):
"""Initialize parameters and build model. Parameters ---------- state_size : int Dimension of each state action_size : int Dimension of each action vmin, vmax : float Upper &... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
"""Distributional Value Model"""
def __init__(self, state_size, action_size, vmin, vmax, n_atoms=51):
"""Initialize parameters and build model. Parameters ---------- state_size : int Dimension of each state action_size : int Dimension of each action vmin, vmax : float Upper & Lower bounds... | the_stack_v2_python_sparse | drlnd/p2_continuous-control/control/model.py | jkorge/udacity | train | 0 |
42b1333b62947bdd16eaa95fde881d23d6610d0d | [
"with DBMgr.__instance_lock:\n if DBMgr.__database is None or refresh:\n try:\n db_host = DBMgr.conf['host']\n db_port = DBMgr.conf['port']\n db_username = DBMgr.conf['username']\n db_password = DBMgr.conf['password']\n db_name = DBMgr.conf['database'... | <|body_start_0|>
with DBMgr.__instance_lock:
if DBMgr.__database is None or refresh:
try:
db_host = DBMgr.conf['host']
db_port = DBMgr.conf['port']
db_username = DBMgr.conf['username']
db_password = DBMgr... | DBMgr | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBMgr:
def get_database(cls, refresh=False):
"""单例多线程模式获取db对象 :param refresh: :return:"""
<|body_0|>
def close_database(cls, func):
"""关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager import DBManager @DBManager.close_database def 使用了数据库的方法"""
... | stack_v2_sparse_classes_36k_train_030714 | 3,937 | permissive | [
{
"docstring": "单例多线程模式获取db对象 :param refresh: :return:",
"name": "get_database",
"signature": "def get_database(cls, refresh=False)"
},
{
"docstring": "关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager import DBManager @DBManager.close_database def 使用了数据库的方法",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_011307 | Implement the Python class `DBMgr` described below.
Class description:
Implement the DBMgr class.
Method signatures and docstrings:
- def get_database(cls, refresh=False): 单例多线程模式获取db对象 :param refresh: :return:
- def close_database(cls, func): 关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager imp... | Implement the Python class `DBMgr` described below.
Class description:
Implement the DBMgr class.
Method signatures and docstrings:
- def get_database(cls, refresh=False): 单例多线程模式获取db对象 :param refresh: :return:
- def close_database(cls, func): 关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager imp... | c679b15ca2f920fd4fa6bd3bb7d2a1a0ac297940 | <|skeleton|>
class DBMgr:
def get_database(cls, refresh=False):
"""单例多线程模式获取db对象 :param refresh: :return:"""
<|body_0|>
def close_database(cls, func):
"""关闭连接 :param cls: :param func: :return: from src.pkg.dsQT.db.db_manager import DBManager @DBManager.close_database def 使用了数据库的方法"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBMgr:
def get_database(cls, refresh=False):
"""单例多线程模式获取db对象 :param refresh: :return:"""
with DBMgr.__instance_lock:
if DBMgr.__database is None or refresh:
try:
db_host = DBMgr.conf['host']
db_port = DBMgr.conf['port']
... | the_stack_v2_python_sparse | dsPyLib/peewee/db_mgr.py | dragonsun7/dsPyLib | train | 0 | |
87323e36928740d00431e582c1fecbb6e30d14f9 | [
"nodes = [(root, 0)]\nhigh_level = 0\ndict = {}\nwhile nodes:\n cur, h = nodes.pop(0)\n if h not in dict:\n dict[h] = [cur.val]\n else:\n dict[h].append(cur.val)\n if h > high_level:\n high_level = h\n if cur.left:\n nodes.append((cur.left, h + 1))\n if cur.right:\n ... | <|body_start_0|>
nodes = [(root, 0)]
high_level = 0
dict = {}
while nodes:
cur, h = nodes.pop(0)
if h not in dict:
dict[h] = [cur.val]
else:
dict[h].append(cur.val)
if h > high_level:
high_lev... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findBottomLeftValue2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nodes = [(root, 0)]
hi... | stack_v2_sparse_classes_36k_train_030715 | 1,566 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findBottomLeftValue",
"signature": "def findBottomLeftValue(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "findBottomLeftValue2",
"signature": "def findBottomLeftValue2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int
- def findBottomLeftValue2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int
- def findBottomLeftValue2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def findBottomLeftValue2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findBottomLeftValue(self, root):
""":type root: TreeNode :rtype: int"""
nodes = [(root, 0)]
high_level = 0
dict = {}
while nodes:
cur, h = nodes.pop(0)
if h not in dict:
dict[h] = [cur.val]
else:
... | the_stack_v2_python_sparse | 513. Find Bottom Left Tree Value/bottomLeft.py | Macielyoung/LeetCode | train | 1 | |
a86b5416fcf166871366c31346d65a4b2056433e | [
"super().__init__()\nself.filedir = os.path.join(filedir, 'iou')\nos.makedirs(self.filedir, exist_ok=True)\nself.gen = generator\nself.save = save\nself.num_classes = self.gen.num_classes\nif self.save:\n self.modelpath = os.path.relpath(os.path.join(self.filedir, '..', 'best_iou_model.h5'))\n self.max_miou =... | <|body_start_0|>
super().__init__()
self.filedir = os.path.join(filedir, 'iou')
os.makedirs(self.filedir, exist_ok=True)
self.gen = generator
self.save = save
self.num_classes = self.gen.num_classes
if self.save:
self.modelpath = os.path.relpath(os.pat... | IoUCallback | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IoUCallback:
def __init__(self, filedir, generator, save=True):
"""Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する"""
<|body_0|>
def calc_confusion(self, gt, pred, key):
"""教師ラベルと予測結果を入力とし、各クラスごとに混同行列の... | stack_v2_sparse_classes_36k_train_030716 | 10,174 | no_license | [
{
"docstring": "Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する",
"name": "__init__",
"signature": "def __init__(self, filedir, generator, save=True)"
},
{
"docstring": "教師ラベルと予測結果を入力とし、各クラスごとに混同行列の要素を計算する。 Parameters ---------- g... | 4 | stack_v2_sparse_classes_30k_test_001169 | Implement the Python class `IoUCallback` described below.
Class description:
Implement the IoUCallback class.
Method signatures and docstrings:
- def __init__(self, filedir, generator, save=True): Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する
- def c... | Implement the Python class `IoUCallback` described below.
Class description:
Implement the IoUCallback class.
Method signatures and docstrings:
- def __init__(self, filedir, generator, save=True): Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する
- def c... | aeb163624db5f97ac3353ffd0da87e1ac1e5b0a0 | <|skeleton|>
class IoUCallback:
def __init__(self, filedir, generator, save=True):
"""Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する"""
<|body_0|>
def calc_confusion(self, gt, pred, key):
"""教師ラベルと予測結果を入力とし、各クラスごとに混同行列の... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IoUCallback:
def __init__(self, filedir, generator, save=True):
"""Parameters ---------- filedir : str 保存先ディレクトリ名 generator : generator.Generator ジェネレータ save : bool True時に計算結果を保存する"""
super().__init__()
self.filedir = os.path.join(filedir, 'iou')
os.makedirs(self.filedir, exist... | the_stack_v2_python_sparse | src/utils/tensorflow/tensorflow.py | R1ck29/kaggle-cassava-leaf-disease-classification | train | 0 | |
4cf4eee6ef3bc0ec8202263745620a13f0b25227 | [
"input_len = len(input_ids)\nif not (input_len == len(input_mask) and input_len == len(segment_ids) and (input_len == len(labels_mask)) and (input_len == len(tag_labels)) and (input_len == len(semiotic_labels))):\n raise ValueError('All feature lists should have the same length ({})'.format(input_len))\nself.fea... | <|body_start_0|>
input_len = len(input_ids)
if not (input_len == len(input_mask) and input_len == len(segment_ids) and (input_len == len(labels_mask)) and (input_len == len(tag_labels)) and (input_len == len(semiotic_labels))):
raise ValueError('All feature lists should have the same length ... | Class for training and inference examples for BERT. Attributes: editing_task: The EditingTask from which this example was created. Needed when realizing labels predicted for this example. features: Feature dictionary. | BertExample | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertExample:
"""Class for training and inference examples for BERT. Attributes: editing_task: The EditingTask from which this example was created. Needed when realizing labels predicted for this example. features: Feature dictionary."""
def __init__(self, input_ids: List[int], input_mask: Li... | stack_v2_sparse_classes_36k_train_030717 | 15,095 | permissive | [
{
"docstring": "Inputs to the example wrapper Args: input_ids: indices of tokens which constitute batches of masked text segments input_mask: bool tensor with 0s in place of source tokens to be masked segment_ids: bool tensor with 0's and 1's to denote the text segment type tag_labels: indices of tokens which s... | 3 | stack_v2_sparse_classes_30k_train_018931 | Implement the Python class `BertExample` described below.
Class description:
Class for training and inference examples for BERT. Attributes: editing_task: The EditingTask from which this example was created. Needed when realizing labels predicted for this example. features: Feature dictionary.
Method signatures and d... | Implement the Python class `BertExample` described below.
Class description:
Class for training and inference examples for BERT. Attributes: editing_task: The EditingTask from which this example was created. Needed when realizing labels predicted for this example. features: Feature dictionary.
Method signatures and d... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class BertExample:
"""Class for training and inference examples for BERT. Attributes: editing_task: The EditingTask from which this example was created. Needed when realizing labels predicted for this example. features: Feature dictionary."""
def __init__(self, input_ids: List[int], input_mask: Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertExample:
"""Class for training and inference examples for BERT. Attributes: editing_task: The EditingTask from which this example was created. Needed when realizing labels predicted for this example. features: Feature dictionary."""
def __init__(self, input_ids: List[int], input_mask: List[int], segm... | the_stack_v2_python_sparse | nemo/collections/nlp/data/text_normalization_as_tagging/bert_example.py | NVIDIA/NeMo | train | 7,957 |
b02454931141648339b5569adc78116d08fc068b | [
"peak_idx = self.find_max_idx(height, 0, len(height))\nself.trap_helper(height, 0, peak_idx, peak_idx)\nself.trap_helper(height, peak_idx + 1, len(height), peak_idx)\nans = self.VOLUME\nself.VOLUME = 0\nreturn ans",
"max_so_far = -1\nmax_idx = -1\nfor i in range(start, end):\n if height[i] > max_so_far:\n ... | <|body_start_0|>
peak_idx = self.find_max_idx(height, 0, len(height))
self.trap_helper(height, 0, peak_idx, peak_idx)
self.trap_helper(height, peak_idx + 1, len(height), peak_idx)
ans = self.VOLUME
self.VOLUME = 0
return ans
<|end_body_0|>
<|body_start_1|>
max_so... | Solution_B | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B:
def trap(self, height: List[int]) -> int:
"""This method no longer needs to generate a peak list, but to recursive check in-place First, find the max peak idx Then Sweep from the max peak idx bi-directional to head and to tail Sweep from max peak to head, finding the next hig... | stack_v2_sparse_classes_36k_train_030718 | 5,662 | permissive | [
{
"docstring": "This method no longer needs to generate a peak list, but to recursive check in-place First, find the max peak idx Then Sweep from the max peak idx bi-directional to head and to tail Sweep from max peak to head, finding the next highest peak, and calculate the volume between Sweep from max peak t... | 3 | stack_v2_sparse_classes_30k_train_006909 | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def trap(self, height: List[int]) -> int: This method no longer needs to generate a peak list, but to recursive check in-place First, find the max peak idx Then Sweep from th... | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def trap(self, height: List[int]) -> int: This method no longer needs to generate a peak list, but to recursive check in-place First, find the max peak idx Then Sweep from th... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B:
def trap(self, height: List[int]) -> int:
"""This method no longer needs to generate a peak list, but to recursive check in-place First, find the max peak idx Then Sweep from the max peak idx bi-directional to head and to tail Sweep from max peak to head, finding the next hig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_B:
def trap(self, height: List[int]) -> int:
"""This method no longer needs to generate a peak list, but to recursive check in-place First, find the max peak idx Then Sweep from the max peak idx bi-directional to head and to tail Sweep from max peak to head, finding the next highest peak, and... | the_stack_v2_python_sparse | LeetCode/LC042_trapping_rain_water.py | jxie0755/Learning_Python | train | 0 | |
90eb0741763786791b3bb7a0bda0ba3851097594 | [
"col = self.db.tag_ware\nvals = col.find()\nkey = [item['total'] for item in vals]\nres = {'tag': key}\nlogger.info('获取所有标签')\nreturn BackstageHTTPResponse(message=u'成功获取所有标签', data=res).to_response()",
"collection = self.db.tag_ware\ndata = self.request_data(request)\nname = data['name']\ntag = data['tag']\ntag_... | <|body_start_0|>
col = self.db.tag_ware
vals = col.find()
key = [item['total'] for item in vals]
res = {'tag': key}
logger.info('获取所有标签')
return BackstageHTTPResponse(message=u'成功获取所有标签', data=res).to_response()
<|end_body_0|>
<|body_start_1|>
collection = self.d... | ManualTagView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManualTagView:
def get(self, request):
"""获取所有标签 --- :param request: :return:"""
<|body_0|>
def post(self, request):
"""新增一个标签 --- parameters: - name: name description: 名称 type: string paramType: form required: true - name: tag description: 标签 type: string paramType:... | stack_v2_sparse_classes_36k_train_030719 | 7,342 | no_license | [
{
"docstring": "获取所有标签 --- :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "新增一个标签 --- parameters: - name: name description: 名称 type: string paramType: form required: true - name: tag description: 标签 type: string paramType: form required: true - ... | 4 | stack_v2_sparse_classes_30k_train_005481 | Implement the Python class `ManualTagView` described below.
Class description:
Implement the ManualTagView class.
Method signatures and docstrings:
- def get(self, request): 获取所有标签 --- :param request: :return:
- def post(self, request): 新增一个标签 --- parameters: - name: name description: 名称 type: string paramType: form ... | Implement the Python class `ManualTagView` described below.
Class description:
Implement the ManualTagView class.
Method signatures and docstrings:
- def get(self, request): 获取所有标签 --- :param request: :return:
- def post(self, request): 新增一个标签 --- parameters: - name: name description: 名称 type: string paramType: form ... | c50def8cde58fd4663032b860eb058302cbac6da | <|skeleton|>
class ManualTagView:
def get(self, request):
"""获取所有标签 --- :param request: :return:"""
<|body_0|>
def post(self, request):
"""新增一个标签 --- parameters: - name: name description: 名称 type: string paramType: form required: true - name: tag description: 标签 type: string paramType:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManualTagView:
def get(self, request):
"""获取所有标签 --- :param request: :return:"""
col = self.db.tag_ware
vals = col.find()
key = [item['total'] for item in vals]
res = {'tag': key}
logger.info('获取所有标签')
return BackstageHTTPResponse(message=u'成功获取所有标签', da... | the_stack_v2_python_sparse | src/api/backstage/views/manual_tags.py | fan1018wen/Alpha | train | 0 | |
8dbc80234a765462be4bb6b6b2759f2416839cc8 | [
"count = [0] * 121\nfor age in ages:\n count[age] += 1\nans = 0\nfor ageA, countA in enumerate(count):\n for ageB, countB in enumerate(count):\n if ageA * 0.5 + 7 >= ageB:\n continue\n if ageA < ageB:\n continue\n if ageA < 100 < ageB:\n continue\n ... | <|body_start_0|>
count = [0] * 121
for age in ages:
count[age] += 1
ans = 0
for ageA, countA in enumerate(count):
for ageB, countB in enumerate(count):
if ageA * 0.5 + 7 >= ageB:
continue
if ageA < ageB:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numFriendRequests_1(self, ages):
""":type ages: List[int] :rtype: int"""
<|body_0|>
def numFriendRequests_2(self, ages):
""":type ages: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = [0] * 121
for... | stack_v2_sparse_classes_36k_train_030720 | 1,940 | no_license | [
{
"docstring": ":type ages: List[int] :rtype: int",
"name": "numFriendRequests_1",
"signature": "def numFriendRequests_1(self, ages)"
},
{
"docstring": ":type ages: List[int] :rtype: int",
"name": "numFriendRequests_2",
"signature": "def numFriendRequests_2(self, ages)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020892 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFriendRequests_1(self, ages): :type ages: List[int] :rtype: int
- def numFriendRequests_2(self, ages): :type ages: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFriendRequests_1(self, ages): :type ages: List[int] :rtype: int
- def numFriendRequests_2(self, ages): :type ages: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def numFriendRequests_1(self, ages):
""":type ages: List[int] :rtype: int"""
<|body_0|>
def numFriendRequests_2(self, ages):
""":type ages: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numFriendRequests_1(self, ages):
""":type ages: List[int] :rtype: int"""
count = [0] * 121
for age in ages:
count[age] += 1
ans = 0
for ageA, countA in enumerate(count):
for ageB, countB in enumerate(count):
if ageA ... | the_stack_v2_python_sparse | medium/arrayandstring/test_825_Friends_Of_Appropriate_Ages.py | wuxu1019/leetcode_sophia | train | 1 | |
c142114697bd50ddeb84156daf4eaebbf302c7c9 | [
"self.dunsnr_field = dunsnr_field\nself.orgnr_field = orgnr_field\nself.navn_field = navn_field\nself.adresse_field = adresse_field\nself.postnr_field = postnr_field\nself.poststed_field = poststed_field\nself.status_kode_field = status_kode_field\nself.status_tekst_field = status_tekst_field\nself.selskapsform_fie... | <|body_start_0|>
self.dunsnr_field = dunsnr_field
self.orgnr_field = orgnr_field
self.navn_field = navn_field
self.adresse_field = adresse_field
self.postnr_field = postnr_field
self.poststed_field = poststed_field
self.status_kode_field = status_kode_field
... | Implementation of the 'Person.FullmaktForetak' model. TODO: type model description here. Attributes: dunsnr_field (int): TODO: type description here. orgnr_field (int): TODO: type description here. navn_field (string): TODO: type description here. adresse_field (string): TODO: type description here. postnr_field (int):... | PersonFullmaktForetak | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonFullmaktForetak:
"""Implementation of the 'Person.FullmaktForetak' model. TODO: type model description here. Attributes: dunsnr_field (int): TODO: type description here. orgnr_field (int): TODO: type description here. navn_field (string): TODO: type description here. adresse_field (string):... | stack_v2_sparse_classes_36k_train_030721 | 6,183 | permissive | [
{
"docstring": "Constructor for the PersonFullmaktForetak class",
"name": "__init__",
"signature": "def __init__(self, dunsnr_field=None, orgnr_field=None, navn_field=None, adresse_field=None, postnr_field=None, poststed_field=None, status_kode_field=None, status_tekst_field=None, selskapsform_field=Non... | 2 | stack_v2_sparse_classes_30k_test_000895 | Implement the Python class `PersonFullmaktForetak` described below.
Class description:
Implementation of the 'Person.FullmaktForetak' model. TODO: type model description here. Attributes: dunsnr_field (int): TODO: type description here. orgnr_field (int): TODO: type description here. navn_field (string): TODO: type de... | Implement the Python class `PersonFullmaktForetak` described below.
Class description:
Implementation of the 'Person.FullmaktForetak' model. TODO: type model description here. Attributes: dunsnr_field (int): TODO: type description here. orgnr_field (int): TODO: type description here. navn_field (string): TODO: type de... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class PersonFullmaktForetak:
"""Implementation of the 'Person.FullmaktForetak' model. TODO: type model description here. Attributes: dunsnr_field (int): TODO: type description here. orgnr_field (int): TODO: type description here. navn_field (string): TODO: type description here. adresse_field (string):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonFullmaktForetak:
"""Implementation of the 'Person.FullmaktForetak' model. TODO: type model description here. Attributes: dunsnr_field (int): TODO: type description here. orgnr_field (int): TODO: type description here. navn_field (string): TODO: type description here. adresse_field (string): TODO: type d... | the_stack_v2_python_sparse | idfy_rest_client/models/person_fullmakt_foretak.py | dealflowteam/Idfy | train | 0 |
e15ab2b23261739bca459199750c62911904177f | [
"if user_id:\n cartReturn = CartModel.FindByIdComplete(user_id)\n return cartReturn\nelse:\n cartsReturn = CartModel.FindAllComplete()\n return cartsReturn\nreturn cartReturn",
"data_payload = request.get_json()\ndata_path = request.path\nif data_path.find('coupons') > 0:\n carReturn = CartModel.Up... | <|body_start_0|>
if user_id:
cartReturn = CartModel.FindByIdComplete(user_id)
return cartReturn
else:
cartsReturn = CartModel.FindAllComplete()
return cartsReturn
return cartReturn
<|end_body_0|>
<|body_start_1|>
data_payload = request.get... | Operations related to carts. | Cart | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cart:
"""Operations related to carts."""
def get(self, user_id=None):
"""Returns details of a(all) cart(s)."""
<|body_0|>
def post(self, user_id):
"""Add a new cart to the database."""
<|body_1|>
def put(self, user_id, product_id=None):
"""Up... | stack_v2_sparse_classes_36k_train_030722 | 3,460 | no_license | [
{
"docstring": "Returns details of a(all) cart(s).",
"name": "get",
"signature": "def get(self, user_id=None)"
},
{
"docstring": "Add a new cart to the database.",
"name": "post",
"signature": "def post(self, user_id)"
},
{
"docstring": "Update an existing cart.",
"name": "pu... | 4 | stack_v2_sparse_classes_30k_train_014423 | Implement the Python class `Cart` described below.
Class description:
Operations related to carts.
Method signatures and docstrings:
- def get(self, user_id=None): Returns details of a(all) cart(s).
- def post(self, user_id): Add a new cart to the database.
- def put(self, user_id, product_id=None): Update an existin... | Implement the Python class `Cart` described below.
Class description:
Operations related to carts.
Method signatures and docstrings:
- def get(self, user_id=None): Returns details of a(all) cart(s).
- def post(self, user_id): Add a new cart to the database.
- def put(self, user_id, product_id=None): Update an existin... | f91a51a044dafbc22b619e386e5bbc2242376c25 | <|skeleton|>
class Cart:
"""Operations related to carts."""
def get(self, user_id=None):
"""Returns details of a(all) cart(s)."""
<|body_0|>
def post(self, user_id):
"""Add a new cart to the database."""
<|body_1|>
def put(self, user_id, product_id=None):
"""Up... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cart:
"""Operations related to carts."""
def get(self, user_id=None):
"""Returns details of a(all) cart(s)."""
if user_id:
cartReturn = CartModel.FindByIdComplete(user_id)
return cartReturn
else:
cartsReturn = CartModel.FindAllComplete()
... | the_stack_v2_python_sparse | src/resources/cart.py | Danil0ws/challenge-01 | train | 0 |
b5a7d57ae1406b06aaa2bfdb15b68d974bdd9fc0 | [
"self.p = p\nself.a = a\nself.b = b\nself.g = g\nself.n = n",
"if point is None:\n return True\nx, y = point\nreturn (y * y - x * x * x - self.a * x - self.b) % self.p == 0",
"assert self.is_on_curve(point)\nif point is None:\n return None\nx, y = point\nresult = (x, -y % self.p)\nassert self.is_on_curve(... | <|body_start_0|>
self.p = p
self.a = a
self.b = b
self.g = g
self.n = n
<|end_body_0|>
<|body_start_1|>
if point is None:
return True
x, y = point
return (y * y - x * x * x - self.a * x - self.b) % self.p == 0
<|end_body_1|>
<|body_start_2|>
... | ECDH | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ECDH:
def __init__(self, p=115792089237316195423570985008687907853269984665640564039457584007908834671663, a=0, b=7, g=(55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424), n=115792089237316... | stack_v2_sparse_classes_36k_train_030723 | 3,454 | no_license | [
{
"docstring": "Create curve with p : prime a : a coefficient of EC b : b coefficient of EC g : basepoint n : order for random and generating private key",
"name": "__init__",
"signature": "def __init__(self, p=115792089237316195423570985008687907853269984665640564039457584007908834671663, a=0, b=7, g=(... | 6 | stack_v2_sparse_classes_30k_train_021648 | Implement the Python class `ECDH` described below.
Class description:
Implement the ECDH class.
Method signatures and docstrings:
- def __init__(self, p=115792089237316195423570985008687907853269984665640564039457584007908834671663, a=0, b=7, g=(550662630222773436695787188951685343262506034537775941755001873603891167... | Implement the Python class `ECDH` described below.
Class description:
Implement the ECDH class.
Method signatures and docstrings:
- def __init__(self, p=115792089237316195423570985008687907853269984665640564039457584007908834671663, a=0, b=7, g=(550662630222773436695787188951685343262506034537775941755001873603891167... | c5b17cd5c670fe2bc8903165d49c4d709a09f55c | <|skeleton|>
class ECDH:
def __init__(self, p=115792089237316195423570985008687907853269984665640564039457584007908834671663, a=0, b=7, g=(55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424), n=115792089237316... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ECDH:
def __init__(self, p=115792089237316195423570985008687907853269984665640564039457584007908834671663, a=0, b=7, g=(55066263022277343669578718895168534326250603453777594175500187360389116729240, 32670510020758816978083085130507043184471273380659243275938904335757337482424), n=11579208923731619542357098500... | the_stack_v2_python_sparse | ECDH.py | aliakbr/Tubes-2-Kripto | train | 0 | |
c6290ad3be936fdfe4d4639d6c5cb815eafe4559 | [
"self.CELL_SIZE = 20\nself.CONTROL_FRAME_HEIGHT = 100\nself.SCORE_FRAME_WIDTH = 200\nself.num_rows = num_rows\nself.num_cols = num_cols\nself.window = tk.Tk()\nself.window.title('Snake')\nself.grid_frame = tk.Frame(self.window, height=num_rows * self.CELL_SIZE, width=num_cols * self.CELL_SIZE)\nself.grid_frame.grid... | <|body_start_0|>
self.CELL_SIZE = 20
self.CONTROL_FRAME_HEIGHT = 100
self.SCORE_FRAME_WIDTH = 200
self.num_rows = num_rows
self.num_cols = num_cols
self.window = tk.Tk()
self.window.title('Snake')
self.grid_frame = tk.Frame(self.window, height=num_rows * s... | SnakeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeView:
def __init__(self, num_rows, num_cols):
"""Initialize view of the game"""
<|body_0|>
def add_cells(self):
"""Add cells to the grid frame"""
<|body_1|>
def add_control(self):
"""Create control buttons and slider, and add them to the con... | stack_v2_sparse_classes_36k_train_030724 | 7,107 | no_license | [
{
"docstring": "Initialize view of the game",
"name": "__init__",
"signature": "def __init__(self, num_rows, num_cols)"
},
{
"docstring": "Add cells to the grid frame",
"name": "add_cells",
"signature": "def add_cells(self)"
},
{
"docstring": "Create control buttons and slider, a... | 4 | stack_v2_sparse_classes_30k_train_007797 | Implement the Python class `SnakeView` described below.
Class description:
Implement the SnakeView class.
Method signatures and docstrings:
- def __init__(self, num_rows, num_cols): Initialize view of the game
- def add_cells(self): Add cells to the grid frame
- def add_control(self): Create control buttons and slide... | Implement the Python class `SnakeView` described below.
Class description:
Implement the SnakeView class.
Method signatures and docstrings:
- def __init__(self, num_rows, num_cols): Initialize view of the game
- def add_cells(self): Add cells to the grid frame
- def add_control(self): Create control buttons and slide... | 8b2dd5340a82ef1964fcf07b9638e0c57632536b | <|skeleton|>
class SnakeView:
def __init__(self, num_rows, num_cols):
"""Initialize view of the game"""
<|body_0|>
def add_cells(self):
"""Add cells to the grid frame"""
<|body_1|>
def add_control(self):
"""Create control buttons and slider, and add them to the con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeView:
def __init__(self, num_rows, num_cols):
"""Initialize view of the game"""
self.CELL_SIZE = 20
self.CONTROL_FRAME_HEIGHT = 100
self.SCORE_FRAME_WIDTH = 200
self.num_rows = num_rows
self.num_cols = num_cols
self.window = tk.Tk()
self.win... | the_stack_v2_python_sparse | Simple Snake/snake4.py | ndelafuente/class-projects | train | 0 | |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"items = []\ncount = read_fmt('I', fp)[0]\nfor _ in range(count):\n key = OSType(fp.read(4))\n kls = TYPES.get(key)\n value = kls.read(fp)\n items.append(value)\nreturn cls(items)",
"written = write_fmt(fp, 'I', len(self))\nfor item in self:\n written += write_bytes(fp, item.ostype.value)\n writ... | <|body_start_0|>
items = []
count = read_fmt('I', fp)[0]
for _ in range(count):
key = OSType(fp.read(4))
kls = TYPES.get(key)
value = kls.read(fp)
items.append(value)
return cls(items)
<|end_body_0|>
<|body_start_1|>
written = writ... | List structure. .. py:attribute:: items | List | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""List structure. .. py:attribute:: items"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
<... | stack_v2_sparse_classes_36k_train_030725 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012555 | Implement the Python class `List` described below.
Class description:
List structure. .. py:attribute:: items
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file-lik... | Implement the Python class `List` described below.
Class description:
List structure. .. py:attribute:: items
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file-lik... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class List:
"""List structure. .. py:attribute:: items"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class List:
"""List structure. .. py:attribute:: items"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
items = []
count = read_fmt('I', fp)[0]
for _ in range(count):
key = OSType(fp.read(4))
kls = TYPES.ge... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
98710912dbbcffc4438a07fa8e9d51cd636bc0fc | [
"l = 0\nr = len(nums) - 1\nwhile l < r:\n mid = (l + r) // 2\n if nums[mid] > nums[mid + 1]:\n r = mid\n else:\n l = mid + 1\nreturn l",
"n = len(nums)\nl = 0\nr = n - 1\nwhile l < r:\n mid = (l + r + 1) // 2\n if nums[mid - 1] < nums[mid]:\n l = mid\n else:\n r = mid... | <|body_start_0|>
l = 0
r = len(nums) - 1
while l < r:
mid = (l + r) // 2
if nums[mid] > nums[mid + 1]:
r = mid
else:
l = mid + 1
return l
<|end_body_0|>
<|body_start_1|>
n = len(nums)
l = 0
r = n... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leftEdge(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rightEdge(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = 0
r = len(nums) - 1
while l < ... | stack_v2_sparse_classes_36k_train_030726 | 1,030 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "leftEdge",
"signature": "def leftEdge(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rightEdge",
"signature": "def rightEdge(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leftEdge(self, nums): :type nums: List[int] :rtype: int
- def rightEdge(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 leftEdge(self, nums): :type nums: List[int] :rtype: int
- def rightEdge(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def leftEdge(self, n... | 819fbc523f3b33742333b6b39b72337a24a26f7a | <|skeleton|>
class Solution:
def leftEdge(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rightEdge(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 leftEdge(self, nums):
""":type nums: List[int] :rtype: int"""
l = 0
r = len(nums) - 1
while l < r:
mid = (l + r) // 2
if nums[mid] > nums[mid + 1]:
r = mid
else:
l = mid + 1
return l
... | the_stack_v2_python_sparse | leetcode/BinarySearch/没有明确target,并且取值范围可能改变(特殊)/162. 寻找峰值(二分找peek).py | Andrewlearning/Leetcoding | train | 1 | |
cefbd0464db5762ad670394baf0502c961302603 | [
"self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.first = Category.objects.create(name='first', caffe=self.caf... | <|body_start_0|>
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')
self.first = Category.objects.c... | Category tests. | CategoryModelTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryModelTest:
"""Category tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_category_name(self):
"""Chcek correctness of setting names."""
<|body_1|>
def test_category_caffe(self):
"""Check if caffe is being set prope... | stack_v2_sparse_classes_36k_train_030727 | 14,711 | permissive | [
{
"docstring": "Test data setup.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Chcek correctness of setting names.",
"name": "test_category_name",
"signature": "def test_category_name(self)"
},
{
"docstring": "Check if caffe is being set properly.",
"na... | 3 | stack_v2_sparse_classes_30k_train_013531 | Implement the Python class `CategoryModelTest` described below.
Class description:
Category tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_category_name(self): Chcek correctness of setting names.
- def test_category_caffe(self): Check if caffe is being set properly. | Implement the Python class `CategoryModelTest` described below.
Class description:
Category tests.
Method signatures and docstrings:
- def setUp(self): Test data setup.
- def test_category_name(self): Chcek correctness of setting names.
- def test_category_caffe(self): Check if caffe is being set properly.
<|skeleto... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class CategoryModelTest:
"""Category tests."""
def setUp(self):
"""Test data setup."""
<|body_0|>
def test_category_name(self):
"""Chcek correctness of setting names."""
<|body_1|>
def test_category_caffe(self):
"""Check if caffe is being set prope... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryModelTest:
"""Category tests."""
def setUp(self):
"""Test data setup."""
self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')
self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='F... | the_stack_v2_python_sparse | caffe/reports/test_models.py | VirrageS/io-kawiarnie | train | 3 |
2ed822bf062e673e96c43cb0eacff104b46ce73b | [
"super(STFTLoss, self).__init__()\nself.fft_size = fft_size\nself.shift_size = shift_size\nself.win_length = win_length\nself.window = getattr(torch, window)(win_length)\nself.spectral_convergenge_loss = SpectralConvergengeLoss()\nself.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()",
"x_mag = stft(x, self.fft_s... | <|body_start_0|>
super(STFTLoss, self).__init__()
self.fft_size = fft_size
self.shift_size = shift_size
self.win_length = win_length
self.window = getattr(torch, window)(win_length)
self.spectral_convergenge_loss = SpectralConvergengeLoss()
self.log_stft_magnitude... | STFT loss module. | STFTLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal ... | stack_v2_sparse_classes_36k_train_030728 | 18,988 | no_license | [
{
"docstring": "Initialize STFT loss module.",
"name": "__init__",
"signature": "def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window')"
},
{
"docstring": "Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtruth signal (B... | 2 | null | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tenso... | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tenso... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'):
"""Initialize STFT loss module."""
super(STFTLoss, self).__init__()
self.fft_size = fft_size
self.shift_size = shift_size
self.win_length = wi... | the_stack_v2_python_sparse | generated/test_rishikksh20_hifigan_denoiser.py | jansel/pytorch-jit-paritybench | train | 35 |
a7f9081cadfd275fe09c3aa50d17c0ef600ad04a | [
"self.xref = xref\nself.dim = dim\nif identical_particles is None:\n identical_particles = np.arange(xref.size)\nself.identical_particles = identical_particles\nself.ip_indices = np.concatenate([dim * self.identical_particles + i for i in range(dim)])\nself.ip_indices.sort()",
"X = ensure_traj(X)\nY = X.copy()... | <|body_start_0|>
self.xref = xref
self.dim = dim
if identical_particles is None:
identical_particles = np.arange(xref.size)
self.identical_particles = identical_particles
self.ip_indices = np.concatenate([dim * self.identical_particles + i for i in range(dim)])
... | HungarianMapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HungarianMapper:
def __init__(self, xref, dim=2, identical_particles=None):
"""Permutes identical particles to minimize distance to reference structure. For a given structure or set of structures finds the permutation of identical particles that minimizes the mean square distance to a gi... | stack_v2_sparse_classes_36k_train_030729 | 2,908 | no_license | [
{
"docstring": "Permutes identical particles to minimize distance to reference structure. For a given structure or set of structures finds the permutation of identical particles that minimizes the mean square distance to a given reference structure. The optimization is done by solving the linear sum assignment ... | 3 | stack_v2_sparse_classes_30k_train_016251 | Implement the Python class `HungarianMapper` described below.
Class description:
Implement the HungarianMapper class.
Method signatures and docstrings:
- def __init__(self, xref, dim=2, identical_particles=None): Permutes identical particles to minimize distance to reference structure. For a given structure or set of... | Implement the Python class `HungarianMapper` described below.
Class description:
Implement the HungarianMapper class.
Method signatures and docstrings:
- def __init__(self, xref, dim=2, identical_particles=None): Permutes identical particles to minimize distance to reference structure. For a given structure or set of... | 15835d43a5ec2d29f05d325d65ffd973a6c8a201 | <|skeleton|>
class HungarianMapper:
def __init__(self, xref, dim=2, identical_particles=None):
"""Permutes identical particles to minimize distance to reference structure. For a given structure or set of structures finds the permutation of identical particles that minimizes the mean square distance to a gi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HungarianMapper:
def __init__(self, xref, dim=2, identical_particles=None):
"""Permutes identical particles to minimize distance to reference structure. For a given structure or set of structures finds the permutation of identical particles that minimizes the mean square distance to a given reference ... | the_stack_v2_python_sparse | bgflow/bgflow/distribution/sampling/_mcmc/permutation.py | noegroup/smooth_normalizing_flows | train | 1 | |
6cfee43b0338e9d172c4ca80bc8a6451963240fd | [
"super(DJFFeatureFusionBlock, self).__init__()\nself.resConfUnit1 = ResidualConvUnit(features)\nself.inter = nn.Sequential(nn.ReLU(True), nn.Conv2d(features + 32, features, kernel_size=1))\nself.resConfUnit2 = ResidualConvUnit(features)",
"guidance = xs[0]\noutput = xs[1]\nif len(xs) == 3:\n output += self.res... | <|body_start_0|>
super(DJFFeatureFusionBlock, self).__init__()
self.resConfUnit1 = ResidualConvUnit(features)
self.inter = nn.Sequential(nn.ReLU(True), nn.Conv2d(features + 32, features, kernel_size=1))
self.resConfUnit2 = ResidualConvUnit(features)
<|end_body_0|>
<|body_start_1|>
... | Feature fusion block. | DJFFeatureFusionBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DJFFeatureFusionBlock:
"""Feature fusion block."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, *xs):
"""Forward pass. Returns: tensor: output"""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_030730 | 17,410 | permissive | [
{
"docstring": "Init. Args: features (int): number of features",
"name": "__init__",
"signature": "def __init__(self, features)"
},
{
"docstring": "Forward pass. Returns: tensor: output",
"name": "forward",
"signature": "def forward(self, *xs)"
}
] | 2 | null | Implement the Python class `DJFFeatureFusionBlock` described below.
Class description:
Feature fusion block.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, *xs): Forward pass. Returns: tensor: output | Implement the Python class `DJFFeatureFusionBlock` described below.
Class description:
Feature fusion block.
Method signatures and docstrings:
- def __init__(self, features): Init. Args: features (int): number of features
- def forward(self, *xs): Forward pass. Returns: tensor: output
<|skeleton|>
class DJFFeatureFu... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class DJFFeatureFusionBlock:
"""Feature fusion block."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
<|body_0|>
def forward(self, *xs):
"""Forward pass. Returns: tensor: output"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DJFFeatureFusionBlock:
"""Feature fusion block."""
def __init__(self, features):
"""Init. Args: features (int): number of features"""
super(DJFFeatureFusionBlock, self).__init__()
self.resConfUnit1 = ResidualConvUnit(features)
self.inter = nn.Sequential(nn.ReLU(True), nn.C... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/blocks.py | kcyu2014/nas-landmarkreg | train | 10 |
271f013315013ff33c300a4a717f2f9179f46190 | [
"if not isinstance(scheme, avro.schema.Schema):\n scheme = avro.schema.parse(scheme)\nself.scheme = scheme\nself.datum_writer = avro.io.DatumWriter(writers_schema=self.scheme)\nself.outputClient = outputClient",
"with io.BytesIO() as buff:\n self.encoder = avro.io.BinaryEncoder(buff)\n self.datum_writer.... | <|body_start_0|>
if not isinstance(scheme, avro.schema.Schema):
scheme = avro.schema.parse(scheme)
self.scheme = scheme
self.datum_writer = avro.io.DatumWriter(writers_schema=self.scheme)
self.outputClient = outputClient
<|end_body_0|>
<|body_start_1|>
with io.BytesI... | Collector for map and reduce output values | Collector | [
"BSD-3-Clause",
"Zlib",
"GPL-1.0-or-later",
"FSFAP",
"MIT",
"LicenseRef-scancode-other-permissive",
"zlib-acknowledgement",
"GPL-2.0-only",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Collector:
"""Collector for map and reduce output values"""
def __init__(self, scheme, outputClient):
"""Parameters --------------------------------------------- scheme - The scheme for the datums to output - can be a json string - or an instance of Schema outputClient - The output c... | stack_v2_sparse_classes_36k_train_030731 | 17,442 | permissive | [
{
"docstring": "Parameters --------------------------------------------- scheme - The scheme for the datums to output - can be a json string - or an instance of Schema outputClient - The output client used to send messages to the parent",
"name": "__init__",
"signature": "def __init__(self, scheme, outp... | 2 | stack_v2_sparse_classes_30k_train_005051 | Implement the Python class `Collector` described below.
Class description:
Collector for map and reduce output values
Method signatures and docstrings:
- def __init__(self, scheme, outputClient): Parameters --------------------------------------------- scheme - The scheme for the datums to output - can be a json stri... | Implement the Python class `Collector` described below.
Class description:
Collector for map and reduce output values
Method signatures and docstrings:
- def __init__(self, scheme, outputClient): Parameters --------------------------------------------- scheme - The scheme for the datums to output - can be a json stri... | 7ff2d7a075debbf7e038f0a4f0674cb312d5473a | <|skeleton|>
class Collector:
"""Collector for map and reduce output values"""
def __init__(self, scheme, outputClient):
"""Parameters --------------------------------------------- scheme - The scheme for the datums to output - can be a json string - or an instance of Schema outputClient - The output c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Collector:
"""Collector for map and reduce output values"""
def __init__(self, scheme, outputClient):
"""Parameters --------------------------------------------- scheme - The scheme for the datums to output - can be a json string - or an instance of Schema outputClient - The output client used to... | the_stack_v2_python_sparse | lang/py/avro/tether/tether_task.py | apache/avro | train | 2,523 |
486e310f29216480f63f060de5c48302d593cd54 | [
"config_info = mongo_cli[config_db].find_one({'config_name': settings.CONFIG_NAME})\nconfig_info['_id'] = '%s' % config_info['_id']\nresponse_data = self.wrap_json_response(data=config_info, code=ReturnCode.SUCCESS)\nreturn jsonify(response_data)",
"body_data = json.loads(request.get_data().decode())\nmongo_cli[c... | <|body_start_0|>
config_info = mongo_cli[config_db].find_one({'config_name': settings.CONFIG_NAME})
config_info['_id'] = '%s' % config_info['_id']
response_data = self.wrap_json_response(data=config_info, code=ReturnCode.SUCCESS)
return jsonify(response_data)
<|end_body_0|>
<|body_start... | SysConfig | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SysConfig:
def get(self):
"""系统数据 --- tags: - 系统设置 definitions: - schema: id: dao.system_config_info properties: _id: type: string config_name: type: integer description: 配置名 poc_thread: type: integer description: Poc线程扫描数 port_thread: type: integer description: 端口扫描线程数 auth_tester_threa... | stack_v2_sparse_classes_36k_train_030732 | 5,725 | no_license | [
{
"docstring": "系统数据 --- tags: - 系统设置 definitions: - schema: id: dao.system_config_info properties: _id: type: string config_name: type: integer description: 配置名 poc_thread: type: integer description: Poc线程扫描数 port_thread: type: integer description: 端口扫描线程数 auth_tester_thread: type: integer description: 认证爆破线程数... | 2 | null | Implement the Python class `SysConfig` described below.
Class description:
Implement the SysConfig class.
Method signatures and docstrings:
- def get(self): 系统数据 --- tags: - 系统设置 definitions: - schema: id: dao.system_config_info properties: _id: type: string config_name: type: integer description: 配置名 poc_thread: typ... | Implement the Python class `SysConfig` described below.
Class description:
Implement the SysConfig class.
Method signatures and docstrings:
- def get(self): 系统数据 --- tags: - 系统设置 definitions: - schema: id: dao.system_config_info properties: _id: type: string config_name: type: integer description: 配置名 poc_thread: typ... | aa75f06ad25b1238176165a0dcf4685c59cd8284 | <|skeleton|>
class SysConfig:
def get(self):
"""系统数据 --- tags: - 系统设置 definitions: - schema: id: dao.system_config_info properties: _id: type: string config_name: type: integer description: 配置名 poc_thread: type: integer description: Poc线程扫描数 port_thread: type: integer description: 端口扫描线程数 auth_tester_threa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SysConfig:
def get(self):
"""系统数据 --- tags: - 系统设置 definitions: - schema: id: dao.system_config_info properties: _id: type: string config_name: type: integer description: 配置名 poc_thread: type: integer description: Poc线程扫描数 port_thread: type: integer description: 端口扫描线程数 auth_tester_thread: type: integ... | the_stack_v2_python_sparse | aquaman/views/sys_config.py | jstang9527/aquaman | train | 15 | |
1b3b8aef461926e771e8748320838a3fa9e19765 | [
"class SettingsCls(SettingsMixin, InvenTreePlugin):\n SETTINGS = self.TEST_SETTINGS\nself.mixin = SettingsCls()\n\nclass NoSettingsCls(SettingsMixin, InvenTreePlugin):\n pass\nself.mixin_nothing = NoSettingsCls()\nsuper().setUp()",
"self.assertEqual(self.mixin.settings, self.TEST_SETTINGS)\nself.assertEqual... | <|body_start_0|>
class SettingsCls(SettingsMixin, InvenTreePlugin):
SETTINGS = self.TEST_SETTINGS
self.mixin = SettingsCls()
class NoSettingsCls(SettingsMixin, InvenTreePlugin):
pass
self.mixin_nothing = NoSettingsCls()
super().setUp()
<|end_body_0|>
<|b... | Tests for SettingsMixin. | SettingsMixinTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SettingsMixinTest:
"""Tests for SettingsMixin."""
def setUp(self):
"""Setup for all tests."""
<|body_0|>
def test_function(self):
"""Test that the mixin functions."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
class SettingsCls(SettingsMixin, ... | stack_v2_sparse_classes_36k_train_030733 | 14,946 | permissive | [
{
"docstring": "Setup for all tests.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the mixin functions.",
"name": "test_function",
"signature": "def test_function(self)"
}
] | 2 | null | Implement the Python class `SettingsMixinTest` described below.
Class description:
Tests for SettingsMixin.
Method signatures and docstrings:
- def setUp(self): Setup for all tests.
- def test_function(self): Test that the mixin functions. | Implement the Python class `SettingsMixinTest` described below.
Class description:
Tests for SettingsMixin.
Method signatures and docstrings:
- def setUp(self): Setup for all tests.
- def test_function(self): Test that the mixin functions.
<|skeleton|>
class SettingsMixinTest:
"""Tests for SettingsMixin."""
... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class SettingsMixinTest:
"""Tests for SettingsMixin."""
def setUp(self):
"""Setup for all tests."""
<|body_0|>
def test_function(self):
"""Test that the mixin functions."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SettingsMixinTest:
"""Tests for SettingsMixin."""
def setUp(self):
"""Setup for all tests."""
class SettingsCls(SettingsMixin, InvenTreePlugin):
SETTINGS = self.TEST_SETTINGS
self.mixin = SettingsCls()
class NoSettingsCls(SettingsMixin, InvenTreePlugin):
... | the_stack_v2_python_sparse | InvenTree/plugin/base/integration/test_mixins.py | inventree/InvenTree | train | 3,077 |
948465607d5d900b53e50bf6d6c5af150c9f8456 | [
"super(DiscreteGenerator, self).__init__()\nself.design_shape = design_shape\nself.latent_size = latent_size\nself.embed_0 = tfkl.Dense(hidden)\nself.embed_0.build((None, 1))\nself.dense_0 = tfkl.Dense(hidden)\nself.dense_0.build((None, latent_size + hidden))\nself.ln_0 = tfkl.LayerNormalization()\nself.ln_0.build(... | <|body_start_0|>
super(DiscreteGenerator, self).__init__()
self.design_shape = design_shape
self.latent_size = latent_size
self.embed_0 = tfkl.Dense(hidden)
self.embed_0.build((None, 1))
self.dense_0 = tfkl.Dense(hidden)
self.dense_0.build((None, latent_size + hid... | A Fully Connected Network conditioned on a score | DiscreteGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteGenerator:
"""A Fully Connected Network conditioned on a score"""
def __init__(self, design_shape, latent_size, hidden=50):
"""Create a fully connected architecture using keras that can process several parallel streams of weights and biases Args: design_shape: List[int] a lis... | stack_v2_sparse_classes_36k_train_030734 | 30,757 | permissive | [
{
"docstring": "Create a fully connected architecture using keras that can process several parallel streams of weights and biases Args: design_shape: List[int] a list of tuple of integers that represents the shape of a float design for a particular task latent_size: int the number of hidden units in the latent ... | 2 | stack_v2_sparse_classes_30k_train_019514 | Implement the Python class `DiscreteGenerator` described below.
Class description:
A Fully Connected Network conditioned on a score
Method signatures and docstrings:
- def __init__(self, design_shape, latent_size, hidden=50): Create a fully connected architecture using keras that can process several parallel streams ... | Implement the Python class `DiscreteGenerator` described below.
Class description:
A Fully Connected Network conditioned on a score
Method signatures and docstrings:
- def __init__(self, design_shape, latent_size, hidden=50): Create a fully connected architecture using keras that can process several parallel streams ... | d46ff40d8b665953afb64a3332ddf1953b8a0766 | <|skeleton|>
class DiscreteGenerator:
"""A Fully Connected Network conditioned on a score"""
def __init__(self, design_shape, latent_size, hidden=50):
"""Create a fully connected architecture using keras that can process several parallel streams of weights and biases Args: design_shape: List[int] a lis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteGenerator:
"""A Fully Connected Network conditioned on a score"""
def __init__(self, design_shape, latent_size, hidden=50):
"""Create a fully connected architecture using keras that can process several parallel streams of weights and biases Args: design_shape: List[int] a list of tuple of... | the_stack_v2_python_sparse | design_baselines/mins/nets.py | stjordanis/design-baselines | train | 0 |
dfbee4f073ed401085f877421614535fb0873fb7 | [
"metadata = None\nif os.path.exists(metadata_filepath):\n metadata = Kinetics400Dataset.load_metadata(metadata_filepath, video_dir=video_dir, update_file_path=True)\ndataset = Kinetics(video_dir, frames_per_clip, num_classes='400', step_between_clips=step_between_clips, frame_rate=frame_rate, _precomputed_metada... | <|body_start_0|>
metadata = None
if os.path.exists(metadata_filepath):
metadata = Kinetics400Dataset.load_metadata(metadata_filepath, video_dir=video_dir, update_file_path=True)
dataset = Kinetics(video_dir, frames_per_clip, num_classes='400', step_between_clips=step_between_clips, f... | `Kinetics-400 <https://deepmind.com/research/open-source/ open-source-datasets/kinetics/>`_ is an action recognition video dataset, and it has 400 classes. `Original publication <https://arxiv.org/pdf/1705.06950.pdf>`_ We assume videos are already trimmed to 10-second clip, and are stored in a folder. It is built on to... | Kinetics400Dataset | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kinetics400Dataset:
"""`Kinetics-400 <https://deepmind.com/research/open-source/ open-source-datasets/kinetics/>`_ is an action recognition video dataset, and it has 400 classes. `Original publication <https://arxiv.org/pdf/1705.06950.pdf>`_ We assume videos are already trimmed to 10-second clip,... | stack_v2_sparse_classes_36k_train_030735 | 6,625 | permissive | [
{
"docstring": "The constructor of Kinetics400Dataset. Args: split: dataset split which can be either \"train\" or \"test\" batchsize_per_replica: batch size per model replica shuffle: If true, shuffle the dataset transform: a dict where transforms video and audio data num_samples: if provided, it will subsampl... | 2 | null | Implement the Python class `Kinetics400Dataset` described below.
Class description:
`Kinetics-400 <https://deepmind.com/research/open-source/ open-source-datasets/kinetics/>`_ is an action recognition video dataset, and it has 400 classes. `Original publication <https://arxiv.org/pdf/1705.06950.pdf>`_ We assume videos... | Implement the Python class `Kinetics400Dataset` described below.
Class description:
`Kinetics-400 <https://deepmind.com/research/open-source/ open-source-datasets/kinetics/>`_ is an action recognition video dataset, and it has 400 classes. `Original publication <https://arxiv.org/pdf/1705.06950.pdf>`_ We assume videos... | 08a82e88fcfa143933832994ace2424c03dd43b8 | <|skeleton|>
class Kinetics400Dataset:
"""`Kinetics-400 <https://deepmind.com/research/open-source/ open-source-datasets/kinetics/>`_ is an action recognition video dataset, and it has 400 classes. `Original publication <https://arxiv.org/pdf/1705.06950.pdf>`_ We assume videos are already trimmed to 10-second clip,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kinetics400Dataset:
"""`Kinetics-400 <https://deepmind.com/research/open-source/ open-source-datasets/kinetics/>`_ is an action recognition video dataset, and it has 400 classes. `Original publication <https://arxiv.org/pdf/1705.06950.pdf>`_ We assume videos are already trimmed to 10-second clip, and are stor... | the_stack_v2_python_sparse | classy_vision/dataset/classy_kinetics400.py | facebookresearch/ClassyVision | train | 1,673 |
1dccf0b67990e9391a4ea6813d28c7c13881a034 | [
"self.xi = np.asarray(xi)\nself.T = T\nself.n_waypoints = xi.shape[0]\ntimesteps = np.linspace(0, self.T, self.n_waypoints)\nself.f1 = interp1d(timesteps, self.xi[:, 0], kind='cubic')\nself.f2 = interp1d(timesteps, self.xi[:, 1], kind='cubic')\nself.f3 = interp1d(timesteps, self.xi[:, 2], kind='cubic')\nself.f4 = i... | <|body_start_0|>
self.xi = np.asarray(xi)
self.T = T
self.n_waypoints = xi.shape[0]
timesteps = np.linspace(0, self.T, self.n_waypoints)
self.f1 = interp1d(timesteps, self.xi[:, 0], kind='cubic')
self.f2 = interp1d(timesteps, self.xi[:, 1], kind='cubic')
self.f3 =... | Trajectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
<|body_0|>
def get(self, t):
"""get interpolated position"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.xi = np.asarray(xi)
self.T = T
... | stack_v2_sparse_classes_36k_train_030736 | 6,389 | permissive | [
{
"docstring": "create cublic interpolators between waypoints",
"name": "__init__",
"signature": "def __init__(self, xi, T)"
},
{
"docstring": "get interpolated position",
"name": "get",
"signature": "def get(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002765 | Implement the Python class `Trajectory` described below.
Class description:
Implement the Trajectory class.
Method signatures and docstrings:
- def __init__(self, xi, T): create cublic interpolators between waypoints
- def get(self, t): get interpolated position | Implement the Python class `Trajectory` described below.
Class description:
Implement the Trajectory class.
Method signatures and docstrings:
- def __init__(self, xi, T): create cublic interpolators between waypoints
- def get(self, t): get interpolated position
<|skeleton|>
class Trajectory:
def __init__(self,... | 65695ac0ad4ffc28474f1920c2d2ff484481caf3 | <|skeleton|>
class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
<|body_0|>
def get(self, t):
"""get interpolated position"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
self.xi = np.asarray(xi)
self.T = T
self.n_waypoints = xi.shape[0]
timesteps = np.linspace(0, self.T, self.n_waypoints)
self.f1 = interp1d(timesteps, self.xi[:, 0], kind='... | the_stack_v2_python_sparse | robot-experiment/play_task2.py | VT-Collab/choice-sets | train | 1 | |
370fb5f38c5dc50220443b44b196ced6fa06e4ae | [
"self.apex_domain = ''\nself.ip = ''\nself.count = ''\nself.status = True\nself.url = url\nself.csp_header = ''\nself.sub_domains = set()",
"try:\n async with aiohttp.request('HEAD', url=self.url, headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.32... | <|body_start_0|>
self.apex_domain = ''
self.ip = ''
self.count = ''
self.status = True
self.url = url
self.csp_header = ''
self.sub_domains = set()
<|end_body_0|>
<|body_start_1|>
try:
async with aiohttp.request('HEAD', url=self.url, headers={... | 利用csp头搜集子域名 | CSPInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSPInfo:
"""利用csp头搜集子域名"""
def __init__(self, url):
""":param apex_domain: csp头中对应的顶级域名 :param ip: 域名对应ip地址 :param count: 域名有几个子域名 :param status: 域名是否可访问 :param url: 网址"""
<|body_0|>
async def get_csp_header(self):
"""获取url的csp头"""
<|body_1|>
def get... | stack_v2_sparse_classes_36k_train_030737 | 3,401 | permissive | [
{
"docstring": ":param apex_domain: csp头中对应的顶级域名 :param ip: 域名对应ip地址 :param count: 域名有几个子域名 :param status: 域名是否可访问 :param url: 网址",
"name": "__init__",
"signature": "def __init__(self, url)"
},
{
"docstring": "获取url的csp头",
"name": "get_csp_header",
"signature": "async def get_csp_header(... | 3 | stack_v2_sparse_classes_30k_train_011234 | Implement the Python class `CSPInfo` described below.
Class description:
利用csp头搜集子域名
Method signatures and docstrings:
- def __init__(self, url): :param apex_domain: csp头中对应的顶级域名 :param ip: 域名对应ip地址 :param count: 域名有几个子域名 :param status: 域名是否可访问 :param url: 网址
- async def get_csp_header(self): 获取url的csp头
- def get_sub... | Implement the Python class `CSPInfo` described below.
Class description:
利用csp头搜集子域名
Method signatures and docstrings:
- def __init__(self, url): :param apex_domain: csp头中对应的顶级域名 :param ip: 域名对应ip地址 :param count: 域名有几个子域名 :param status: 域名是否可访问 :param url: 网址
- async def get_csp_header(self): 获取url的csp头
- def get_sub... | 0d1d31c9abf1d3293d113bff46c400b246434807 | <|skeleton|>
class CSPInfo:
"""利用csp头搜集子域名"""
def __init__(self, url):
""":param apex_domain: csp头中对应的顶级域名 :param ip: 域名对应ip地址 :param count: 域名有几个子域名 :param status: 域名是否可访问 :param url: 网址"""
<|body_0|>
async def get_csp_header(self):
"""获取url的csp头"""
<|body_1|>
def get... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSPInfo:
"""利用csp头搜集子域名"""
def __init__(self, url):
""":param apex_domain: csp头中对应的顶级域名 :param ip: 域名对应ip地址 :param count: 域名有几个子域名 :param status: 域名是否可访问 :param url: 网址"""
self.apex_domain = ''
self.ip = ''
self.count = ''
self.status = True
self.url = url
... | the_stack_v2_python_sparse | module/active/csp_info.py | j5s/getdomain | train | 0 |
0a39d7e8fe212f64f06a1c50090714b50567b231 | [
"if not root:\n return\nself.recoverTree(root.left)\nif self.lastVisited > root.val:\n if not self.firstMisplaced:\n self.firstMisplaced = root\n else:\n self.secondMisplaced = root\nself.lastVisited = root.val\nself.recoverTree(root.right)\nif self.firstMisplaced and self.secondMisplaced:\n ... | <|body_start_0|>
if not root:
return
self.recoverTree(root.left)
if self.lastVisited > root.val:
if not self.firstMisplaced:
self.firstMisplaced = root
else:
self.secondMisplaced = root
self.lastVisited = root.val
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k_train_030738 | 2,119 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "recoverTree",
"signature": "def recoverTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "re... | 3 | stack_v2_sparse_classes_30k_train_001084 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def recoverTree(self, root): :type root: TreeNode :rtype: v... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
- def recoverTree(self, root): :type root: TreeNode :rtype: v... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
if not root:
return
self.recoverTree(root.left)
if self.lastVisited > root.val:
if not self.firstMisplaced:
... | the_stack_v2_python_sparse | Python_leetcode/99_recover_binary_search_tree.py | xiangcao/Leetcode | train | 0 | |
8333efe61f8291df6e488ce2d6b2a973e1692b8d | [
"self.Wf = np.random.normal(size=(i + h, h))\nself.Wu = np.random.normal(size=(i + h, h))\nself.Wc = np.random.normal(size=(i + h, h))\nself.Wo = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bf = np.zeros((1, h))\nself.bu = np.zeros((1, h))\nself.bc = np.zeros((1, h))\nself.bo = ... | <|body_start_0|>
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc = np.random.normal(size=(i + h, h))
self.Wo = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bf = np.zeros((1, h))
self... | [summary] | LSTMCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSTMCell:
"""[summary]"""
def __init__(self, i, h, o):
"""[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
"""[summary] Args: h_prev ([type]): [description] c_prev ... | stack_v2_sparse_classes_36k_train_030739 | 1,922 | no_license | [
{
"docstring": "[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "[summary] Args: h_prev ([type]): [description] c_prev ([type]): [description] x_t ([type]): [descripti... | 2 | null | Implement the Python class `LSTMCell` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, i, h, o): [summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]
- def forward(self, h_prev, c_prev, x_t): [summary] Args: h_prev ([type]): ... | Implement the Python class `LSTMCell` described below.
Class description:
[summary]
Method signatures and docstrings:
- def __init__(self, i, h, o): [summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]
- def forward(self, h_prev, c_prev, x_t): [summary] Args: h_prev ([type]): ... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class LSTMCell:
"""[summary]"""
def __init__(self, i, h, o):
"""[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]"""
<|body_0|>
def forward(self, h_prev, c_prev, x_t):
"""[summary] Args: h_prev ([type]): [description] c_prev ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LSTMCell:
"""[summary]"""
def __init__(self, i, h, o):
"""[summary] Args: i ([type]): [description] h ([type]): [description] o ([type]): [description]"""
self.Wf = np.random.normal(size=(i + h, h))
self.Wu = np.random.normal(size=(i + h, h))
self.Wc = np.random.normal(siz... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/3-lstm_cell.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
09de470be2c2634ab66936a3c925e44de07bb43b | [
"if text.startswith('\"'):\n return PVS_dquotedString.decode(text)\nreturn PVS_ptoken.decode(text)",
"m = PVS_ptoken._re.match(value)\nif m is not None and len(value) == m.end():\n return PVS_ptoken.encode(value)\nreturn PVS_dquotedString.encode(value)"
] | <|body_start_0|>
if text.startswith('"'):
return PVS_dquotedString.decode(text)
return PVS_ptoken.decode(text)
<|end_body_0|>
<|body_start_1|>
m = PVS_ptoken._re.match(value)
if m is not None and len(value) == m.end():
return PVS_ptoken.encode(value)
retu... | Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value. | PVS_unknown | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PVS_unknown:
"""Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value."""
def decode(self, text):
"""Override base class to support either dquotedString or ptoken. If the text begins wit... | stack_v2_sparse_classes_36k_train_030740 | 11,879 | permissive | [
{
"docstring": "Override base class to support either dquotedString or ptoken. If the text begins with double-quotes, this processes as :meth:`PVS_dquotedString.decode`. Otherwise, it processes as :meth:`PVS_ptoken.decode`.",
"name": "decode",
"signature": "def decode(self, text)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_017281 | Implement the Python class `PVS_unknown` described below.
Class description:
Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value.
Method signatures and docstrings:
- def decode(self, text): Override base class to suppo... | Implement the Python class `PVS_unknown` described below.
Class description:
Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value.
Method signatures and docstrings:
- def decode(self, text): Override base class to suppo... | f512355c5fde6bf027d23558e256b96e2296e0f2 | <|skeleton|>
class PVS_unknown:
"""Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value."""
def decode(self, text):
"""Override base class to support either dquotedString or ptoken. If the text begins wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PVS_unknown:
"""Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value."""
def decode(self, text):
"""Override base class to support either dquotedString or ptoken. If the text begins with double-quot... | the_stack_v2_python_sparse | eds/openmtc-gevent/common/openmtc/lib/coap/coapy/coapy/link.py | elastest/elastest-device-emulator-service | train | 3 |
3f6c1c26bc9f466ec63f89f0aa202fd250727eab | [
"self.results = self.stan_model.vb(data=self.impl.format_data_to_stan(data), pars=self.impl.get_pars(), output_samples=iterations, seed=seed, algorithm=algorithm)\nparams = VI.pystan_vb_extract(self.results)\nreturn self.impl.extract_data_from_stan(params)",
"param_specs = results['sampler_param_names']\nsamples ... | <|body_start_0|>
self.results = self.stan_model.vb(data=self.impl.format_data_to_stan(data), pars=self.impl.get_pars(), output_samples=iterations, seed=seed, algorithm=algorithm)
params = VI.pystan_vb_extract(self.results)
return self.impl.extract_data_from_stan(params)
<|end_body_0|>
<|body_st... | VI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VI:
def infer(self, data: xr.Dataset, iterations: int, num_warmup: int, seed: int, algorithm: str='meanfield') -> xr.Dataset:
"""See https://pystan.readthedocs.io/en/latest/api.html#pystan.StanModel.vb"""
<|body_0|>
def pystan_vb_extract(results: OrderedDict):
"""Fro... | stack_v2_sparse_classes_36k_train_030741 | 4,459 | permissive | [
{
"docstring": "See https://pystan.readthedocs.io/en/latest/api.html#pystan.StanModel.vb",
"name": "infer",
"signature": "def infer(self, data: xr.Dataset, iterations: int, num_warmup: int, seed: int, algorithm: str='meanfield') -> xr.Dataset"
},
{
"docstring": "From: https://gist.github.com/lwi... | 2 | null | Implement the Python class `VI` described below.
Class description:
Implement the VI class.
Method signatures and docstrings:
- def infer(self, data: xr.Dataset, iterations: int, num_warmup: int, seed: int, algorithm: str='meanfield') -> xr.Dataset: See https://pystan.readthedocs.io/en/latest/api.html#pystan.StanMode... | Implement the Python class `VI` described below.
Class description:
Implement the VI class.
Method signatures and docstrings:
- def infer(self, data: xr.Dataset, iterations: int, num_warmup: int, seed: int, algorithm: str='meanfield') -> xr.Dataset: See https://pystan.readthedocs.io/en/latest/api.html#pystan.StanMode... | d69c652fc882ba50f56eb0cfaa3097d3ede295f9 | <|skeleton|>
class VI:
def infer(self, data: xr.Dataset, iterations: int, num_warmup: int, seed: int, algorithm: str='meanfield') -> xr.Dataset:
"""See https://pystan.readthedocs.io/en/latest/api.html#pystan.StanModel.vb"""
<|body_0|>
def pystan_vb_extract(results: OrderedDict):
"""Fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VI:
def infer(self, data: xr.Dataset, iterations: int, num_warmup: int, seed: int, algorithm: str='meanfield') -> xr.Dataset:
"""See https://pystan.readthedocs.io/en/latest/api.html#pystan.StanModel.vb"""
self.results = self.stan_model.vb(data=self.impl.format_data_to_stan(data), pars=self.imp... | the_stack_v2_python_sparse | pplbench/ppls/stan/inference.py | rambam613/pplbench | train | 0 | |
af4384ecdca8234ab6e9cef7c2858dd382fbf596 | [
"jsonStr = self.to_json()\nretorno = json.loads(jsonStr)\nretorno.pop('_id', '')\nreturn retorno",
"if not document.external_id:\n document.external_id = str(uuid4())\npass"
] | <|body_start_0|>
jsonStr = self.to_json()
retorno = json.loads(jsonStr)
retorno.pop('_id', '')
return retorno
<|end_body_0|>
<|body_start_1|>
if not document.external_id:
document.external_id = str(uuid4())
pass
<|end_body_1|>
| ORM to reference the groups to be assigned to the admins. In system start there are only two basic groups: - GOD: Can do whatever he wants - common: basically can only list who are users and check scsr freely. Future possible groups: - gamemanagers: Can approve suggested games - genremaintainers: Maps or merges genres ... | AdminGroupDB | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminGroupDB:
"""ORM to reference the groups to be assigned to the admins. In system start there are only two basic groups: - GOD: Can do whatever he wants - common: basically can only list who are users and check scsr freely. Future possible groups: - gamemanagers: Can approve suggested games - ... | stack_v2_sparse_classes_36k_train_030742 | 4,587 | permissive | [
{
"docstring": "Returns the Object as a Python Dict object Returns: dict -- the instantiated object",
"name": "to_obj",
"signature": "def to_obj(self)"
},
{
"docstring": "After saving the genre set the external_id Arguments: sender {UserGameGenre} -- The sender of the signal document {UserGameGe... | 2 | stack_v2_sparse_classes_30k_train_005924 | Implement the Python class `AdminGroupDB` described below.
Class description:
ORM to reference the groups to be assigned to the admins. In system start there are only two basic groups: - GOD: Can do whatever he wants - common: basically can only list who are users and check scsr freely. Future possible groups: - gamem... | Implement the Python class `AdminGroupDB` described below.
Class description:
ORM to reference the groups to be assigned to the admins. In system start there are only two basic groups: - GOD: Can do whatever he wants - common: basically can only list who are users and check scsr freely. Future possible groups: - gamem... | d1c40d7b86b94c50c88833149c29f413e6d39843 | <|skeleton|>
class AdminGroupDB:
"""ORM to reference the groups to be assigned to the admins. In system start there are only two basic groups: - GOD: Can do whatever he wants - common: basically can only list who are users and check scsr freely. Future possible groups: - gamemanagers: Can approve suggested games - ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdminGroupDB:
"""ORM to reference the groups to be assigned to the admins. In system start there are only two basic groups: - GOD: Can do whatever he wants - common: basically can only list who are users and check scsr freely. Future possible groups: - gamemanagers: Can approve suggested games - genremaintain... | the_stack_v2_python_sparse | scsr_api/admin/models/admin.py | hiperlogic/scsr-api | train | 1 |
81575e47933ec49b74e31ed21d0550f463809f52 | [
"url = BASE_URL + '/users/profile/update'\npayload = {'token': test_token, 'last_name': test_last_name, 'first_name': test_first_name}\noutput = requests.post(url, json=payload)\nexpected_output = 'User ' + test_last_name + ' ' + test_first_name + ' updated'\nassert output.json()['message'] == expected_output",
"... | <|body_start_0|>
url = BASE_URL + '/users/profile/update'
payload = {'token': test_token, 'last_name': test_last_name, 'first_name': test_first_name}
output = requests.post(url, json=payload)
expected_output = 'User ' + test_last_name + ' ' + test_first_name + ' updated'
assert o... | TestProfileUser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProfileUser:
def test_post_working(self):
"""this test will pass the user/information method"""
<|body_0|>
def test_post_missing_parameters(self):
"""this test will fail because of missing parameters"""
<|body_1|>
def test_post_user_unidentified(self... | stack_v2_sparse_classes_36k_train_030743 | 1,565 | permissive | [
{
"docstring": "this test will pass the user/information method",
"name": "test_post_working",
"signature": "def test_post_working(self)"
},
{
"docstring": "this test will fail because of missing parameters",
"name": "test_post_missing_parameters",
"signature": "def test_post_missing_par... | 3 | null | Implement the Python class `TestProfileUser` described below.
Class description:
Implement the TestProfileUser class.
Method signatures and docstrings:
- def test_post_working(self): this test will pass the user/information method
- def test_post_missing_parameters(self): this test will fail because of missing parame... | Implement the Python class `TestProfileUser` described below.
Class description:
Implement the TestProfileUser class.
Method signatures and docstrings:
- def test_post_working(self): this test will pass the user/information method
- def test_post_missing_parameters(self): this test will fail because of missing parame... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestProfileUser:
def test_post_working(self):
"""this test will pass the user/information method"""
<|body_0|>
def test_post_missing_parameters(self):
"""this test will fail because of missing parameters"""
<|body_1|>
def test_post_user_unidentified(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProfileUser:
def test_post_working(self):
"""this test will pass the user/information method"""
url = BASE_URL + '/users/profile/update'
payload = {'token': test_token, 'last_name': test_last_name, 'first_name': test_first_name}
output = requests.post(url, json=payload)
... | the_stack_v2_python_sparse | pytest_suit/routes/user/test_profileUser.py | HotMaps/Hotmaps-toolbox-service | train | 4 | |
e47ba0fdadd8b11cfc65007d280b00613c93d760 | [
"nums.sort()\nres = []\nif nums[0] != nums[1]:\n res.append(nums[0])\nif nums[-1] != nums[-2]:\n res.append(nums[-1])\nfor i in range(1, len(nums) - 1):\n if nums[i] == nums[i - 1] or nums[i] == nums[i + 1]:\n continue\n else:\n res.append(nums[i])\nreturn res",
"if not nums:\n return... | <|body_start_0|>
nums.sort()
res = []
if nums[0] != nums[1]:
res.append(nums[0])
if nums[-1] != nums[-2]:
res.append(nums[-1])
for i in range(1, len(nums) - 1):
if nums[i] == nums[i - 1] or nums[i] == nums[i + 1]:
continue
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def singleNumbers2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums.sort()
res = []... | stack_v2_sparse_classes_36k_train_030744 | 1,352 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "singleNumbers",
"signature": "def singleNumbers(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[int]",
"name": "singleNumbers2",
"signature": "def singleNumbers2(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def singleNumbers2(self, nums): :type nums: List[int] :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumbers(self, nums): :type nums: List[int] :rtype: List[int]
- def singleNumbers2(self, nums): :type nums: List[int] :rtype: List[int]
<|skeleton|>
class Solution:
... | 690b685048c8e89d26047b6bc48b5f9af7d59cbb | <|skeleton|>
class Solution:
def singleNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_0|>
def singleNumbers2(self, nums):
""":type nums: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumbers(self, nums):
""":type nums: List[int] :rtype: List[int]"""
nums.sort()
res = []
if nums[0] != nums[1]:
res.append(nums[0])
if nums[-1] != nums[-2]:
res.append(nums[-1])
for i in range(1, len(nums) - 1):
... | the_stack_v2_python_sparse | 数组/剑指 Offer 56 - I. 数组中数字出现的次数.py | SimmonsChen/LeetCode | train | 0 | |
a10d3ff2b8e51789c1699c4c44ef0565a43077aa | [
"if not deterministic and self.stochastic_depth:\n shape = (x.shape[0],) + (1,) * (x.ndim - 1)\n return jax.random.bernoulli(self.make_rng('dropout'), self.stochastic_depth, shape)\nelse:\n return 0.0",
"assert inputs.ndim == 3\nx = nn.LayerNorm(dtype=self.dtype)(inputs)\nx = nn.MultiHeadDotProductAttent... | <|body_start_0|>
if not deterministic and self.stochastic_depth:
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
return jax.random.bernoulli(self.make_rng('dropout'), self.stochastic_depth, shape)
else:
return 0.0
<|end_body_0|>
<|body_start_1|>
assert inputs.ndi... | Transformer encoder layer. Attributes: mlp_dim: Dimension of the mlp on top of attention block. num_heads: Number of self-attention heads. dtype: The dtype of the computation (default: float32). dropout_rate: Dropout rate. attention_dropout_rate: Dropout for attention heads. stochastic_depth: probability of dropping a ... | Encoder1DBlock | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder1DBlock:
"""Transformer encoder layer. Attributes: mlp_dim: Dimension of the mlp on top of attention block. num_heads: Number of self-attention heads. dtype: The dtype of the computation (default: float32). dropout_rate: Dropout rate. attention_dropout_rate: Dropout for attention heads. st... | stack_v2_sparse_classes_36k_train_030745 | 14,611 | permissive | [
{
"docstring": "Generate the stochastic depth mask in order to apply layer-drop. Args: x: Input tensor. deterministic: Weather we are in the deterministic mode (e.g inference time) or not. Returns: Stochastic depth mask.",
"name": "get_stochastic_depth_mask",
"signature": "def get_stochastic_depth_mask(... | 2 | stack_v2_sparse_classes_30k_test_000068 | Implement the Python class `Encoder1DBlock` described below.
Class description:
Transformer encoder layer. Attributes: mlp_dim: Dimension of the mlp on top of attention block. num_heads: Number of self-attention heads. dtype: The dtype of the computation (default: float32). dropout_rate: Dropout rate. attention_dropou... | Implement the Python class `Encoder1DBlock` described below.
Class description:
Transformer encoder layer. Attributes: mlp_dim: Dimension of the mlp on top of attention block. num_heads: Number of self-attention heads. dtype: The dtype of the computation (default: float32). dropout_rate: Dropout rate. attention_dropou... | c3ae6d7b5dc829fafe204a92522a5983959561a0 | <|skeleton|>
class Encoder1DBlock:
"""Transformer encoder layer. Attributes: mlp_dim: Dimension of the mlp on top of attention block. num_heads: Number of self-attention heads. dtype: The dtype of the computation (default: float32). dropout_rate: Dropout rate. attention_dropout_rate: Dropout for attention heads. st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder1DBlock:
"""Transformer encoder layer. Attributes: mlp_dim: Dimension of the mlp on top of attention block. num_heads: Number of self-attention heads. dtype: The dtype of the computation (default: float32). dropout_rate: Dropout rate. attention_dropout_rate: Dropout for attention heads. stochastic_dept... | the_stack_v2_python_sparse | scenic/projects/baselines/vit.py | shreyasarora/scenic | train | 0 |
03236625ed7677af3aba2cfb1d60e5fb5b202e3c | [
"if lang in self.EUROPEAN_TYPED_LANGUAGES:\n super(sppasNumEuropeanType, self).__init__(lang, dictionary)\nelse:\n raise sppasValueError(lang, str(sppasNumEuropeanType.EUROPEAN_TYPED_LANGUAGES))\nfor i in sppasNumEuropeanType.NUMBER_LIST:\n if self._lang_dict.is_unk(str(i)) is True:\n raise sppasVal... | <|body_start_0|>
if lang in self.EUROPEAN_TYPED_LANGUAGES:
super(sppasNumEuropeanType, self).__init__(lang, dictionary)
else:
raise sppasValueError(lang, str(sppasNumEuropeanType.EUROPEAN_TYPED_LANGUAGES))
for i in sppasNumEuropeanType.NUMBER_LIST:
if self._la... | :author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi | sppasNumEuropeanType | [
"GFDL-1.1-or-later",
"GPL-3.0-only",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasNumEuropeanType:
""":author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi"""
def __init__(self, lang=None, dictionary=None):
"""Return an ... | stack_v2_sparse_classes_36k_train_030746 | 5,535 | permissive | [
{
"docstring": "Return an instance of sppasNumEuropeanType. :param lang: (str) name of the language",
"name": "__init__",
"signature": "def __init__(self, lang=None, dictionary=None)"
},
{
"docstring": "Return the \"wordified\" version of a million number. Returns the word corresponding to the g... | 3 | null | Implement the Python class `sppasNumEuropeanType` described below.
Class description:
:author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi
Method signatures and docstrings:
- d... | Implement the Python class `sppasNumEuropeanType` described below.
Class description:
:author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi
Method signatures and docstrings:
- d... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasNumEuropeanType:
""":author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi"""
def __init__(self, lang=None, dictionary=None):
"""Return an ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sppasNumEuropeanType:
""":author: Barthélémy Drabczuk :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2019 Brigitte Bigi"""
def __init__(self, lang=None, dictionary=None):
"""Return an instance of s... | the_stack_v2_python_sparse | sppas/sppas/src/annotations/TextNorm/num2text/num_europ_lang.py | mirfan899/MTTS | train | 0 |
6525f29ac4e3b19423711836644310771b71a7dc | [
"j, lhp = (0, [0] * len(t))\nfor i in range(1, len(t)):\n while j > 0 and t[i] != t[j]:\n j = lhp[j - 1]\n if t[i] == t[j]:\n j += 1\n lhp[i] = j\nreturn lhp",
"j = 0\nlhp, res = (self.get_lhp(pat), [])\nfor i in range(len(text)):\n while j > 0 and text[i] != pat[j]:\n j = lhp... | <|body_start_0|>
j, lhp = (0, [0] * len(t))
for i in range(1, len(t)):
while j > 0 and t[i] != t[j]:
j = lhp[j - 1]
if t[i] == t[j]:
j += 1
lhp[i] = j
return lhp
<|end_body_0|>
<|body_start_1|>
j = 0
lhp, re... | KMP | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KMP:
def get_lhp(self, t: str) -> List[int]:
"""Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t"""
<|body_0|>
def pattern... | stack_v2_sparse_classes_36k_train_030747 | 2,412 | no_license | [
{
"docstring": "Compute the length of LHP for each t[:i], i \\\\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t",
"name": "get_lhp",
"signature": "def get_lhp(self, t: str) -> List[int]"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_008560 | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def get_lhp(self, t: str) -> List[int]: Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswit... | Implement the Python class `KMP` described below.
Class description:
Implement the KMP class.
Method signatures and docstrings:
- def get_lhp(self, t: str) -> List[int]: Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswit... | 9e4f6f1a2830bd9aab1bba374c98f0464825d435 | <|skeleton|>
class KMP:
def get_lhp(self, t: str) -> List[int]:
"""Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t"""
<|body_0|>
def pattern... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KMP:
def get_lhp(self, t: str) -> List[int]:
"""Compute the length of LHP for each t[:i], i \\in [1..len(t)], where a prefix-suffix of t is a substring, u, of t s.t., t.startswith(u) and t.endswith(u). And proper means, len(u) < len(t), i.e., u != t"""
j, lhp = (0, [0] * len(t))
for i ... | the_stack_v2_python_sparse | python_solutions/28.implement-strstr.py | h4hany/leetcode | train | 0 | |
19032d33e00413af0650ce1dd18f00764441df01 | [
"self.rx = rx\nself.ry = ry\nself.rz = rz\nself.wn_sigma = np.radians(wn_sigma)\nself.bias = [np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias))]\nself.bias_instability_var = np.radians(bias_instability_var)\nself.bias_instability = [0, 0, 0]\nrotatio... | <|body_start_0|>
self.rx = rx
self.ry = ry
self.rz = rz
self.wn_sigma = np.radians(wn_sigma)
self.bias = [np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias)), np.random.normal(0, np.radians(bias))]
self.bias_instability_var = np.radians(bias_insta... | A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measurement bias_instability : double the ... | Gyroscope | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gyroscope:
"""A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measu... | stack_v2_sparse_classes_36k_train_030748 | 13,401 | no_license | [
{
"docstring": "Parameters ---------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] axis : str axis about which the rotation between the gyroscope RF and the robot RF is given rotation : double rotation between the reference frames about the axis given in \"axis\" [degrees] b... | 2 | stack_v2_sparse_classes_30k_train_005747 | Implement the Python class `Gyroscope` described below.
Class description:
A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of th... | Implement the Python class `Gyroscope` described below.
Class description:
A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of th... | 5789011d0a7617844d7e8e6e3e758c415a945a5e | <|skeleton|>
class Gyroscope:
"""A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gyroscope:
"""A class to simulate a gyroscope ... Attributes ----------- rx, ry, rz : double position of the gyroscope RF with respect to the robot RF [m] bias : double constant bias error of the gyroscope [degrees] wn_sigma : double standard deviation of the white noise error affecting the measurement bias_i... | the_stack_v2_python_sparse | Code/sensormodel.py | astroHaoPeng/thesis | train | 0 |
5e06285119b99b8c8dff2eb80a381f9dbf5ca643 | [
"if not parent:\n raise ValueError('Missing parent value.')\nsuper(LUKSDEPathSpec, self).__init__(parent=parent, **kwargs)\nself.password = password",
"string_parts = []\nif self.password:\n string_parts.append(f'password: {self.password:s}')\nreturn self._GetComparable(sub_comparable_string=', '.join(strin... | <|body_start_0|>
if not parent:
raise ValueError('Missing parent value.')
super(LUKSDEPathSpec, self).__init__(parent=parent, **kwargs)
self.password = password
<|end_body_0|>
<|body_start_1|>
string_parts = []
if self.password:
string_parts.append(f'pass... | LUKSDE path specification. Attributes: password (str): password. | LUKSDEPathSpec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LUKSDEPathSpec:
"""LUKSDE path specification. Attributes: password (str): password."""
def __init__(self, password=None, parent=None, **kwargs):
"""Initializes a path specification. Note that the LUKSDE path specification must have a parent. Args: password (Optional[str]): password. ... | stack_v2_sparse_classes_36k_train_030749 | 1,217 | permissive | [
{
"docstring": "Initializes a path specification. Note that the LUKSDE path specification must have a parent. Args: password (Optional[str]): password. parent (Optional[PathSpec]): parent path specification. Raises: ValueError: when parent is not set.",
"name": "__init__",
"signature": "def __init__(sel... | 2 | null | Implement the Python class `LUKSDEPathSpec` described below.
Class description:
LUKSDE path specification. Attributes: password (str): password.
Method signatures and docstrings:
- def __init__(self, password=None, parent=None, **kwargs): Initializes a path specification. Note that the LUKSDE path specification must ... | Implement the Python class `LUKSDEPathSpec` described below.
Class description:
LUKSDE path specification. Attributes: password (str): password.
Method signatures and docstrings:
- def __init__(self, password=None, parent=None, **kwargs): Initializes a path specification. Note that the LUKSDE path specification must ... | 28756d910e951a22c5f0b2bcf5184f055a19d544 | <|skeleton|>
class LUKSDEPathSpec:
"""LUKSDE path specification. Attributes: password (str): password."""
def __init__(self, password=None, parent=None, **kwargs):
"""Initializes a path specification. Note that the LUKSDE path specification must have a parent. Args: password (Optional[str]): password. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LUKSDEPathSpec:
"""LUKSDE path specification. Attributes: password (str): password."""
def __init__(self, password=None, parent=None, **kwargs):
"""Initializes a path specification. Note that the LUKSDE path specification must have a parent. Args: password (Optional[str]): password. parent (Optio... | the_stack_v2_python_sparse | dfvfs/path/luksde_path_spec.py | log2timeline/dfvfs | train | 197 |
b9265020adbd65a519ef84290e64b703b1b71d13 | [
"if not token:\n raise OAuth2InvalidTokenDescriptorError('token')\nself._validate_encryption_args(token_iv, token_key)\ntry:\n text = json.dumps(token.dictionary)\n cipher = AES.new(token_key, AES.MODE_CFB, token_iv)\n return base64.b64encode(cipher.encrypt(text)).decode()\nexcept Exception as ex:\n ... | <|body_start_0|>
if not token:
raise OAuth2InvalidTokenDescriptorError('token')
self._validate_encryption_args(token_iv, token_key)
try:
text = json.dumps(token.dictionary)
cipher = AES.new(token_key, AES.MODE_CFB, token_iv)
return base64.b64encode... | This class provides a generic AES token encryption provider. It allows developers to specify the number of bits used for AES (128 / 192 / 256 bits). | AesTokenEncryption | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AesTokenEncryption:
"""This class provides a generic AES token encryption provider. It allows developers to specify the number of bits used for AES (128 / 192 / 256 bits)."""
def encrypt_token(self, token, token_iv, token_key):
"""This method uses AES for encrypting the given token. ... | stack_v2_sparse_classes_36k_train_030750 | 8,538 | permissive | [
{
"docstring": "This method uses AES for encrypting the given token. Internally it transform the token into a JSON string and encrypt it using given token_iv and token_key.",
"name": "encrypt_token",
"signature": "def encrypt_token(self, token, token_iv, token_key)"
},
{
"docstring": "This metho... | 2 | null | Implement the Python class `AesTokenEncryption` described below.
Class description:
This class provides a generic AES token encryption provider. It allows developers to specify the number of bits used for AES (128 / 192 / 256 bits).
Method signatures and docstrings:
- def encrypt_token(self, token, token_iv, token_ke... | Implement the Python class `AesTokenEncryption` described below.
Class description:
This class provides a generic AES token encryption provider. It allows developers to specify the number of bits used for AES (128 / 192 / 256 bits).
Method signatures and docstrings:
- def encrypt_token(self, token, token_iv, token_ke... | 81c8590556baa9e1148071b7835d74b1efada561 | <|skeleton|>
class AesTokenEncryption:
"""This class provides a generic AES token encryption provider. It allows developers to specify the number of bits used for AES (128 / 192 / 256 bits)."""
def encrypt_token(self, token, token_iv, token_key):
"""This method uses AES for encrypting the given token. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AesTokenEncryption:
"""This class provides a generic AES token encryption provider. It allows developers to specify the number of bits used for AES (128 / 192 / 256 bits)."""
def encrypt_token(self, token, token_iv, token_key):
"""This method uses AES for encrypting the given token. Internally it... | the_stack_v2_python_sparse | fantastico/oauth2/token_encryption.py | rcosnita/fantastico | train | 3 |
881b49ebba8baffa4a6e668f02f681078e9beb23 | [
"if size <= 0:\n raise ValueError('Expected positive integer, got %d' % size)\nself.size = size\nself.paulis = PauliMatrices(self.size)\nself.num_params = len(self.paulis)\nself.sigmav = -1j / self.get_dim() * self.paulis.get_numpy()",
"self.check_parameters(params)\nH = dot_product(params, self.sigmav)\neiH =... | <|body_start_0|>
if size <= 0:
raise ValueError('Expected positive integer, got %d' % size)
self.size = size
self.paulis = PauliMatrices(self.size)
self.num_params = len(self.paulis)
self.sigmav = -1j / self.get_dim() * self.paulis.get_numpy()
<|end_body_0|>
<|body_s... | A gate representing an arbitrary rotation. | PauliGate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PauliGate:
"""A gate representing an arbitrary rotation."""
def __init__(self, size: int) -> None:
"""Create a PauliGate acting on `size` qubits."""
<|body_0|>
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gat... | stack_v2_sparse_classes_36k_train_030751 | 2,425 | permissive | [
{
"docstring": "Create a PauliGate acting on `size` qubits.",
"name": "__init__",
"signature": "def __init__(self, size: int) -> None"
},
{
"docstring": "Returns the unitary for this gate, see Unitary for more info.",
"name": "get_unitary",
"signature": "def get_unitary(self, params: Seq... | 5 | stack_v2_sparse_classes_30k_train_014635 | Implement the Python class `PauliGate` described below.
Class description:
A gate representing an arbitrary rotation.
Method signatures and docstrings:
- def __init__(self, size: int) -> None: Create a PauliGate acting on `size` qubits.
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the... | Implement the Python class `PauliGate` described below.
Class description:
A gate representing an arbitrary rotation.
Method signatures and docstrings:
- def __init__(self, size: int) -> None: Create a PauliGate acting on `size` qubits.
- def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix: Returns the... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class PauliGate:
"""A gate representing an arbitrary rotation."""
def __init__(self, size: int) -> None:
"""Create a PauliGate acting on `size` qubits."""
<|body_0|>
def get_unitary(self, params: Sequence[float]=[]) -> UnitaryMatrix:
"""Returns the unitary for this gat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PauliGate:
"""A gate representing an arbitrary rotation."""
def __init__(self, size: int) -> None:
"""Create a PauliGate acting on `size` qubits."""
if size <= 0:
raise ValueError('Expected positive integer, got %d' % size)
self.size = size
self.paulis = PauliM... | the_stack_v2_python_sparse | bqskit/ir/gates/parameterized/pauli.py | mtreinish/bqskit | train | 0 |
c9dcaf594759f452499c06ef3cabc2c2e7d25385 | [
"assert order > 0, 'order must be 1 or more.'\nassert smooth > 2, 'term must be 3 or more.'\nself.__smooth = smooth\nself.__order = order\nself.__r = r\nself.__threshold = threshold",
"detector = Prospective(self.__r, self.__order, self.__smooth)\nscores = []\nfor i in X:\n score = detector.update(i)\n scor... | <|body_start_0|>
assert order > 0, 'order must be 1 or more.'
assert smooth > 2, 'term must be 3 or more.'
self.__smooth = smooth
self.__order = order
self.__r = r
self.__threshold = threshold
<|end_body_0|>
<|body_start_1|>
detector = Prospective(self.__r, self.... | ChangeFinder (Retrospective) | Retrospective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retrospective:
"""ChangeFinder (Retrospective)"""
def __init__(self, r=0.5, order=1, smooth=7, threshold=1):
"""Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters t... | stack_v2_sparse_classes_36k_train_030752 | 7,176 | permissive | [
{
"docstring": "Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters threshold: threshold for alarms.",
"name": "__init__",
"signature": "def __init__(self, r=0.5, order=1, smooth=7, thr... | 3 | stack_v2_sparse_classes_30k_train_021599 | Implement the Python class `Retrospective` described below.
Class description:
ChangeFinder (Retrospective)
Method signatures and docstrings:
- def __init__(self, r=0.5, order=1, smooth=7, threshold=1): Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second sta... | Implement the Python class `Retrospective` described below.
Class description:
ChangeFinder (Retrospective)
Method signatures and docstrings:
- def __init__(self, r=0.5, order=1, smooth=7, threshold=1): Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second sta... | 7faf99f36ac012799602f32b359dcda089bcd119 | <|skeleton|>
class Retrospective:
"""ChangeFinder (Retrospective)"""
def __init__(self, r=0.5, order=1, smooth=7, threshold=1):
"""Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Retrospective:
"""ChangeFinder (Retrospective)"""
def __init__(self, r=0.5, order=1, smooth=7, threshold=1):
"""Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters threshold: thr... | the_stack_v2_python_sparse | changefinder/changefinder.py | IbarakikenYukishi/two-stage-MDL | train | 4 |
f1dfc3c6f29b3d806dd264c14baae1ab3432e2e2 | [
"if not nums:\n return 0\ndp = [[0, 1] for _ in range(len(nums))]\ndp[0] = [0, nums[0]]\nfor i in range(1, len(nums)):\n for j in (0, 1):\n can_reserve = dp[i - 1][0] + nums[i] if j == 1 else dp[i - 1][0]\n can_not_reverse = dp[i - 1][1]\n dp[i][j] = max(can_reserve, can_not_reverse)\nret... | <|body_start_0|>
if not nums:
return 0
dp = [[0, 1] for _ in range(len(nums))]
dp[0] = [0, nums[0]]
for i in range(1, len(nums)):
for j in (0, 1):
can_reserve = dp[i - 1][0] + nums[i] if j == 1 else dp[i - 1][0]
can_not_reverse = dp... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def massage1(self, nums) -> int:
"""动态规划"""
<|body_0|>
def massage(self, nums) -> int:
"""动态规划"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
dp = [[0, 1] for _ in range(len(nums))]
dp[0] ... | stack_v2_sparse_classes_36k_train_030753 | 2,053 | no_license | [
{
"docstring": "动态规划",
"name": "massage1",
"signature": "def massage1(self, nums) -> int"
},
{
"docstring": "动态规划",
"name": "massage",
"signature": "def massage(self, nums) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_004952 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def massage1(self, nums) -> int: 动态规划
- def massage(self, nums) -> int: 动态规划 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def massage1(self, nums) -> int: 动态规划
- def massage(self, nums) -> int: 动态规划
<|skeleton|>
class Solution:
def massage1(self, nums) -> int:
"""动态规划"""
<|body... | 2acf8468c2e3454b9685b214e25617c98d55b3bc | <|skeleton|>
class Solution:
def massage1(self, nums) -> int:
"""动态规划"""
<|body_0|>
def massage(self, nums) -> int:
"""动态规划"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def massage1(self, nums) -> int:
"""动态规划"""
if not nums:
return 0
dp = [[0, 1] for _ in range(len(nums))]
dp[0] = [0, nums[0]]
for i in range(1, len(nums)):
for j in (0, 1):
can_reserve = dp[i - 1][0] + nums[i] if j == 1... | the_stack_v2_python_sparse | the-masseuse-lcci.py | linxuedong/leetcode | train | 0 | |
a772a14e0dfcd83529c7982d014e4b7a24d9da17 | [
"try:\n await self._data.controller.machine.update_firmware()\nexcept RequestError as err:\n raise HomeAssistantError(f'Error while updating firmware: {err}') from err\nawait self.coordinator.async_refresh()",
"if (version := self._version_coordinator.data['swVer']):\n self._attr_installed_version = vers... | <|body_start_0|>
try:
await self._data.controller.machine.update_firmware()
except RequestError as err:
raise HomeAssistantError(f'Error while updating firmware: {err}') from err
await self.coordinator.async_refresh()
<|end_body_0|>
<|body_start_1|>
if (version :... | Define a RainMachine update entity. | RainMachineUpdateEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RainMachineUpdateEntity:
"""Define a RainMachine update entity."""
async def async_install(self, version: str | None, backup: bool, **kwargs: Any) -> None:
"""Install an update."""
<|body_0|>
def update_from_latest_data(self) -> None:
"""Update the state."""
... | stack_v2_sparse_classes_36k_train_030754 | 3,415 | permissive | [
{
"docstring": "Install an update.",
"name": "async_install",
"signature": "async def async_install(self, version: str | None, backup: bool, **kwargs: Any) -> None"
},
{
"docstring": "Update the state.",
"name": "update_from_latest_data",
"signature": "def update_from_latest_data(self) -... | 2 | null | Implement the Python class `RainMachineUpdateEntity` described below.
Class description:
Define a RainMachine update entity.
Method signatures and docstrings:
- async def async_install(self, version: str | None, backup: bool, **kwargs: Any) -> None: Install an update.
- def update_from_latest_data(self) -> None: Upda... | Implement the Python class `RainMachineUpdateEntity` described below.
Class description:
Define a RainMachine update entity.
Method signatures and docstrings:
- async def async_install(self, version: str | None, backup: bool, **kwargs: Any) -> None: Install an update.
- def update_from_latest_data(self) -> None: Upda... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RainMachineUpdateEntity:
"""Define a RainMachine update entity."""
async def async_install(self, version: str | None, backup: bool, **kwargs: Any) -> None:
"""Install an update."""
<|body_0|>
def update_from_latest_data(self) -> None:
"""Update the state."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RainMachineUpdateEntity:
"""Define a RainMachine update entity."""
async def async_install(self, version: str | None, backup: bool, **kwargs: Any) -> None:
"""Install an update."""
try:
await self._data.controller.machine.update_firmware()
except RequestError as err:
... | the_stack_v2_python_sparse | homeassistant/components/rainmachine/update.py | home-assistant/core | train | 35,501 |
6fd5f346d0e8c0069b3d5dbb8f1f97a2d3d3be0a | [
"super(RequestData, self).__init__()\nself.program = None\nself.program_timeline = None\nself.org_app = None\nself.profile = None\nself.is_host = False\nself.mentor_for = []\nself.org_admin_for = []\nself.applied_to = []\nself.not_applied_to = []\nself.student_info = None",
"if isinstance(organization, db.Model):... | <|body_start_0|>
super(RequestData, self).__init__()
self.program = None
self.program_timeline = None
self.org_app = None
self.profile = None
self.is_host = False
self.mentor_for = []
self.org_admin_for = []
self.applied_to = []
self.not_ap... | Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_timeline: The GSoCTimeline entity timeli... | RequestData | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestData:
"""Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_t... | stack_v2_sparse_classes_36k_train_030755 | 14,575 | permissive | [
{
"docstring": "Constructs an empty RequestData object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns true iff the user is admin for the specified organization. Organization may either be a key or an organization instance.",
"name": "orgAdminFor",
"si... | 6 | stack_v2_sparse_classes_30k_train_019391 | Implement the Python class `RequestData` described below.
Class description:
Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity th... | Implement the Python class `RequestData` described below.
Class description:
Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity th... | 9bd45c168f8ddb5c0e6c04eacdcaeafd61908be7 | <|skeleton|>
class RequestData:
"""Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestData:
"""Object containing data we query for each request in the GSoC module. The only view that will be exempt is the one that creates the program. Fields: site: The Site entity user: The user entity (if logged in) program: The GSoC program entity that the request is pointing to program_timeline: The ... | the_stack_v2_python_sparse | app/soc/modules/gsoc/views/helper/request_data.py | pombredanne/Melange-1 | train | 0 |
fde2f43111cc6e471931a244a3ba6f4e1447dcdb | [
"op_maker = OpMaker()\nread_op = op_maker.create('general_reader')\ninfer_op = op_maker.create('general_infer')\nresponse_op = op_maker.create('general_response')\nread_op_dict = yaml.safe_load(read_op)\nassert read_op_dict['name'] == 'general_reader_0'\nassert read_op_dict['type'] == 'GeneralReaderOp'\ninfer_op_di... | <|body_start_0|>
op_maker = OpMaker()
read_op = op_maker.create('general_reader')
infer_op = op_maker.create('general_infer')
response_op = op_maker.create('general_response')
read_op_dict = yaml.safe_load(read_op)
assert read_op_dict['name'] == 'general_reader_0'
... | test OpMaker class | TestOpMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestOpMaker:
"""test OpMaker class"""
def test_create_with_existed_node(self):
"""test create normally"""
<|body_0|>
def test_create_with_undefined_node(self):
"""test create with undefined node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
op... | stack_v2_sparse_classes_36k_train_030756 | 3,472 | no_license | [
{
"docstring": "test create normally",
"name": "test_create_with_existed_node",
"signature": "def test_create_with_existed_node(self)"
},
{
"docstring": "test create with undefined node",
"name": "test_create_with_undefined_node",
"signature": "def test_create_with_undefined_node(self)"
... | 2 | null | Implement the Python class `TestOpMaker` described below.
Class description:
test OpMaker class
Method signatures and docstrings:
- def test_create_with_existed_node(self): test create normally
- def test_create_with_undefined_node(self): test create with undefined node | Implement the Python class `TestOpMaker` described below.
Class description:
test OpMaker class
Method signatures and docstrings:
- def test_create_with_existed_node(self): test create normally
- def test_create_with_undefined_node(self): test create with undefined node
<|skeleton|>
class TestOpMaker:
"""test Op... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestOpMaker:
"""test OpMaker class"""
def test_create_with_existed_node(self):
"""test create normally"""
<|body_0|>
def test_create_with_undefined_node(self):
"""test create with undefined node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestOpMaker:
"""test OpMaker class"""
def test_create_with_existed_node(self):
"""test create normally"""
op_maker = OpMaker()
read_op = op_maker.create('general_reader')
infer_op = op_maker.create('general_infer')
response_op = op_maker.create('general_response')
... | the_stack_v2_python_sparse | inference/serving_api_test/paddle_serving_server/test_dag.py | PaddlePaddle/PaddleTest | train | 42 |
c58059f9b80a15a5416b031ad7d14c25490bc644 | [
"self.file = open(motif_file, 'rbU')\nself.header = self.file.readline()\nself.reader = csv.reader(self.file, delimiter=' ')",
"meme_str = 'Meme'\nweeder_str = 'Weeder'\nchipmunk_str = 'ChiPMunk'\nfor j_str in [meme_str, weeder_str, chipmunk_str]:\n if j_str in self.header:\n print('%s is from %s tool.'... | <|body_start_0|>
self.file = open(motif_file, 'rbU')
self.header = self.file.readline()
self.reader = csv.reader(self.file, delimiter=' ')
<|end_body_0|>
<|body_start_1|>
meme_str = 'Meme'
weeder_str = 'Weeder'
chipmunk_str = 'ChiPMunk'
for j_str in [meme_str, we... | Object to play with a motif. Convert to pwm etc. | motif_obj | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class motif_obj:
"""Object to play with a motif. Convert to pwm etc."""
def __init__(self, motif_file):
"""Constructor"""
<|body_0|>
def guess_motif_tool(self):
"""Read the header and guess if motif is made from tools: meme weeder chipmunk Expects header to be a one li... | stack_v2_sparse_classes_36k_train_030757 | 5,806 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, motif_file)"
},
{
"docstring": "Read the header and guess if motif is made from tools: meme weeder chipmunk Expects header to be a one liner, no other columns.",
"name": "guess_motif_tool",
"signature": "d... | 2 | null | Implement the Python class `motif_obj` described below.
Class description:
Object to play with a motif. Convert to pwm etc.
Method signatures and docstrings:
- def __init__(self, motif_file): Constructor
- def guess_motif_tool(self): Read the header and guess if motif is made from tools: meme weeder chipmunk Expects ... | Implement the Python class `motif_obj` described below.
Class description:
Object to play with a motif. Convert to pwm etc.
Method signatures and docstrings:
- def __init__(self, motif_file): Constructor
- def guess_motif_tool(self): Read the header and guess if motif is made from tools: meme weeder chipmunk Expects ... | 8fdfa5d3a7ce9b1f2890f27c4dc16a65f12f1d6f | <|skeleton|>
class motif_obj:
"""Object to play with a motif. Convert to pwm etc."""
def __init__(self, motif_file):
"""Constructor"""
<|body_0|>
def guess_motif_tool(self):
"""Read the header and guess if motif is made from tools: meme weeder chipmunk Expects header to be a one li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class motif_obj:
"""Object to play with a motif. Convert to pwm etc."""
def __init__(self, motif_file):
"""Constructor"""
self.file = open(motif_file, 'rbU')
self.header = self.file.readline()
self.reader = csv.reader(self.file, delimiter=' ')
def guess_motif_tool(self):
... | the_stack_v2_python_sparse | alternative_splicing_scripts/motif_scripts/motif_utils.py | jakeyeung/alternative-splicing | train | 5 |
9c0f12d3830209fcc4478a33de2f2a56ab9cb80b | [
"super(AttnBahd, self).__init__()\nself.h_dim = input_size\nself.s_dim = output_size\nself.a_dim = self.s_dim if attn_dim is None else attn_dim\nself.U = nn.Linear(self.h_dim, self.a_dim)\nself.W = nn.Linear(self.s_dim, self.a_dim)\nself.v = nn.Linear(self.a_dim, 1)\nself.tanh = nn.Tanh()\nself.softmax = nn.LogSoft... | <|body_start_0|>
super(AttnBahd, self).__init__()
self.h_dim = input_size
self.s_dim = output_size
self.a_dim = self.s_dim if attn_dim is None else attn_dim
self.U = nn.Linear(self.h_dim, self.a_dim)
self.W = nn.Linear(self.s_dim, self.a_dim)
self.v = nn.Linear(se... | AttnBahd | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttnBahd:
def __init__(self, input_size: int, output_size: int, attn_dim: int=None):
"""Attention mechanism of Bahdanau et al., 2014 Args: input_size: usually -- dimension of the output of the encoder (h_j) * num_directions of the encoder output_size: usually -- dimension of the hidden s... | stack_v2_sparse_classes_36k_train_030758 | 2,922 | permissive | [
{
"docstring": "Attention mechanism of Bahdanau et al., 2014 Args: input_size: usually -- dimension of the output of the encoder (h_j) * num_directions of the encoder output_size: usually -- dimension of the hidden state of the decoder (s_{i-1}) attn_dim: dimension of the internal state (default: same as decode... | 3 | stack_v2_sparse_classes_30k_train_019786 | Implement the Python class `AttnBahd` described below.
Class description:
Implement the AttnBahd class.
Method signatures and docstrings:
- def __init__(self, input_size: int, output_size: int, attn_dim: int=None): Attention mechanism of Bahdanau et al., 2014 Args: input_size: usually -- dimension of the output of th... | Implement the Python class `AttnBahd` described below.
Class description:
Implement the AttnBahd class.
Method signatures and docstrings:
- def __init__(self, input_size: int, output_size: int, attn_dim: int=None): Attention mechanism of Bahdanau et al., 2014 Args: input_size: usually -- dimension of the output of th... | 250196403ee4050cac78c547add90087ea04243f | <|skeleton|>
class AttnBahd:
def __init__(self, input_size: int, output_size: int, attn_dim: int=None):
"""Attention mechanism of Bahdanau et al., 2014 Args: input_size: usually -- dimension of the output of the encoder (h_j) * num_directions of the encoder output_size: usually -- dimension of the hidden s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttnBahd:
def __init__(self, input_size: int, output_size: int, attn_dim: int=None):
"""Attention mechanism of Bahdanau et al., 2014 Args: input_size: usually -- dimension of the output of the encoder (h_j) * num_directions of the encoder output_size: usually -- dimension of the hidden state of the de... | the_stack_v2_python_sparse | binlin/model/modules/attention.py | UKPLab/inlg2019-revisiting-binlin | train | 1 | |
947bb894473e2eb5b37295415f27abc6f7c81227 | [
"self.parsed_urls = []\nself.parsed_payloads = []\nreturn",
"if self.url_match.match(data):\n self.parsed_urls.append(data)\nif validators.sha256(data):\n self.parsed_payloads.append(data)\nreturn"
] | <|body_start_0|>
self.parsed_urls = []
self.parsed_payloads = []
return
<|end_body_0|>
<|body_start_1|>
if self.url_match.match(data):
self.parsed_urls.append(data)
if validators.sha256(data):
self.parsed_payloads.append(data)
return
<|end_body_1|... | HTML parser class | ParserHTML | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParserHTML:
"""HTML parser class"""
def reload(self):
"""Empty the list of URLs and payloads."""
<|body_0|>
def handle_data(self, data):
"""Feed source code to parser and extract URLs and hashes."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_030759 | 8,066 | permissive | [
{
"docstring": "Empty the list of URLs and payloads.",
"name": "reload",
"signature": "def reload(self)"
},
{
"docstring": "Feed source code to parser and extract URLs and hashes.",
"name": "handle_data",
"signature": "def handle_data(self, data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003655 | Implement the Python class `ParserHTML` described below.
Class description:
HTML parser class
Method signatures and docstrings:
- def reload(self): Empty the list of URLs and payloads.
- def handle_data(self, data): Feed source code to parser and extract URLs and hashes. | Implement the Python class `ParserHTML` described below.
Class description:
HTML parser class
Method signatures and docstrings:
- def reload(self): Empty the list of URLs and payloads.
- def handle_data(self, data): Feed source code to parser and extract URLs and hashes.
<|skeleton|>
class ParserHTML:
"""HTML pa... | 914232c99ca10bf0d42c560860c8c05d24485c75 | <|skeleton|>
class ParserHTML:
"""HTML parser class"""
def reload(self):
"""Empty the list of URLs and payloads."""
<|body_0|>
def handle_data(self, data):
"""Feed source code to parser and extract URLs and hashes."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParserHTML:
"""HTML parser class"""
def reload(self):
"""Empty the list of URLs and payloads."""
self.parsed_urls = []
self.parsed_payloads = []
return
def handle_data(self, data):
"""Feed source code to parser and extract URLs and hashes."""
if self.u... | the_stack_v2_python_sparse | bin/urlhaus_api.py | lin0x/osweep | train | 0 |
cf0c3cc2469e73713689eb926d630c5644478781 | [
"self.positional_encoding = SinePositionalEncoding(**self.positional_encoding)\nself.encoder = DetrTransformerEncoder(**self.encoder)\nself.decoder = ConditionalDetrTransformerDecoder(**self.decoder)\nself.embed_dims = self.encoder.embed_dims\nself.query_embedding = nn.Embedding(self.num_queries, self.embed_dims)\n... | <|body_start_0|>
self.positional_encoding = SinePositionalEncoding(**self.positional_encoding)
self.encoder = DetrTransformerEncoder(**self.encoder)
self.decoder = ConditionalDetrTransformerDecoder(**self.decoder)
self.embed_dims = self.encoder.embed_dims
self.query_embedding = n... | Implementation of `Conditional DETR for Fast Training Convergence. <https://arxiv.org/abs/2108.06152>`_. Code is modified from the `official github repo <https://github.com/Atten4Vis/ConditionalDETR>`_. | ConditionalDETR | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConditionalDETR:
"""Implementation of `Conditional DETR for Fast Training Convergence. <https://arxiv.org/abs/2108.06152>`_. Code is modified from the `official github repo <https://github.com/Atten4Vis/ConditionalDETR>`_."""
def _init_layers(self) -> None:
"""Initialize layers excep... | stack_v2_sparse_classes_36k_train_030760 | 3,029 | permissive | [
{
"docstring": "Initialize layers except for backbone, neck and bbox_head.",
"name": "_init_layers",
"signature": "def _init_layers(self) -> None"
},
{
"docstring": "Forward with Transformer decoder. Args: query (Tensor): The queries of decoder inputs, has shape (bs, num_queries, dim). query_pos... | 2 | null | Implement the Python class `ConditionalDETR` described below.
Class description:
Implementation of `Conditional DETR for Fast Training Convergence. <https://arxiv.org/abs/2108.06152>`_. Code is modified from the `official github repo <https://github.com/Atten4Vis/ConditionalDETR>`_.
Method signatures and docstrings:
... | Implement the Python class `ConditionalDETR` described below.
Class description:
Implementation of `Conditional DETR for Fast Training Convergence. <https://arxiv.org/abs/2108.06152>`_. Code is modified from the `official github repo <https://github.com/Atten4Vis/ConditionalDETR>`_.
Method signatures and docstrings:
... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class ConditionalDETR:
"""Implementation of `Conditional DETR for Fast Training Convergence. <https://arxiv.org/abs/2108.06152>`_. Code is modified from the `official github repo <https://github.com/Atten4Vis/ConditionalDETR>`_."""
def _init_layers(self) -> None:
"""Initialize layers excep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConditionalDETR:
"""Implementation of `Conditional DETR for Fast Training Convergence. <https://arxiv.org/abs/2108.06152>`_. Code is modified from the `official github repo <https://github.com/Atten4Vis/ConditionalDETR>`_."""
def _init_layers(self) -> None:
"""Initialize layers except for backbon... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/detectors/conditional_detr.py | alldatacenter/alldata | train | 774 |
b944d90d4784de8c2f92b8ac1bae26e5718db186 | [
"super(SignalDecoder, self).__init__()\nself.upsampling = kwargs.get('upsampling', False)\nbn = kwargs.get('batch_norm', True)\nif isinstance(signal_dim, int):\n signal_dim = (signal_dim,)\nif not 0 < len(signal_dim) < 3:\n raise AssertionError('signal dimensionality must be to 1D or 2D')\nndim = 2 if len(sig... | <|body_start_0|>
super(SignalDecoder, self).__init__()
self.upsampling = kwargs.get('upsampling', False)
bn = kwargs.get('batch_norm', True)
if isinstance(signal_dim, int):
signal_dim = (signal_dim,)
if not 0 < len(signal_dim) < 3:
raise AssertionError('si... | Decodes a latent vector into 1D/2D signal Args: signal_dim: Size of input signal. For images, it is (height, width). For spectra, it is (length,) z_dim: Number of fully-connected neurons in a "bottleneck layer" (latent dimensions) nb_layers: Number of convolutional layers nb_filters: Number of convolutional filters (ak... | SignalDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalDecoder:
"""Decodes a latent vector into 1D/2D signal Args: signal_dim: Size of input signal. For images, it is (height, width). For spectra, it is (length,) z_dim: Number of fully-connected neurons in a "bottleneck layer" (latent dimensions) nb_layers: Number of convolutional layers nb_fil... | stack_v2_sparse_classes_36k_train_030761 | 28,462 | permissive | [
{
"docstring": "Initializes module parameters",
"name": "__init__",
"signature": "def __init__(self, signal_dim: Tuple[int], z_dim: int, nb_layers: int, nb_filters: int, **kwargs: bool) -> None"
},
{
"docstring": "Generates a signal from embedded features (latent vector)",
"name": "forward",... | 2 | stack_v2_sparse_classes_30k_train_000465 | Implement the Python class `SignalDecoder` described below.
Class description:
Decodes a latent vector into 1D/2D signal Args: signal_dim: Size of input signal. For images, it is (height, width). For spectra, it is (length,) z_dim: Number of fully-connected neurons in a "bottleneck layer" (latent dimensions) nb_layers... | Implement the Python class `SignalDecoder` described below.
Class description:
Decodes a latent vector into 1D/2D signal Args: signal_dim: Size of input signal. For images, it is (height, width). For spectra, it is (length,) z_dim: Number of fully-connected neurons in a "bottleneck layer" (latent dimensions) nb_layers... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class SignalDecoder:
"""Decodes a latent vector into 1D/2D signal Args: signal_dim: Size of input signal. For images, it is (height, width). For spectra, it is (length,) z_dim: Number of fully-connected neurons in a "bottleneck layer" (latent dimensions) nb_layers: Number of convolutional layers nb_fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignalDecoder:
"""Decodes a latent vector into 1D/2D signal Args: signal_dim: Size of input signal. For images, it is (height, width). For spectra, it is (length,) z_dim: Number of fully-connected neurons in a "bottleneck layer" (latent dimensions) nb_layers: Number of convolutional layers nb_filters: Number ... | the_stack_v2_python_sparse | atomai/nets/ed.py | pycroscopy/atomai | train | 157 |
8d60b0ba6e91583703959f1b6cc2c3b2777b6db4 | [
"sc.logger.info('小影圈推荐页面初始状态检查开始')\nfun_name = 'test_planet_notify_ui'\nsc.logger.info('点击小影圈主按钮')\np_btn = 'com.quvideo.xiaoying:id/img_find'\nWebDriverWait(sc.driver, 10, 1).until(lambda el: el.find_element_by_id(p_btn)).click()\nsc.logger.info('开始查找小影圈消息中心图标')\nmessage_btn = 'com.quvideo.xiaoying:id/btn_message'... | <|body_start_0|>
sc.logger.info('小影圈推荐页面初始状态检查开始')
fun_name = 'test_planet_notify_ui'
sc.logger.info('点击小影圈主按钮')
p_btn = 'com.quvideo.xiaoying:id/img_find'
WebDriverWait(sc.driver, 10, 1).until(lambda el: el.find_element_by_id(p_btn)).click()
sc.logger.info('开始查找小影圈消息中心图标... | 小影圈通知页的测试类,分步截图. | TestPlanetNotify | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPlanetNotify:
"""小影圈通知页的测试类,分步截图."""
def test_planet_notify_ui(self):
"""小影圈推荐页面初始状态测试."""
<|body_0|>
def test_notify_info(self):
"""测试消息中心通知页."""
<|body_1|>
def test_notify_message(self):
"""测试消息中心动态."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_030762 | 2,201 | no_license | [
{
"docstring": "小影圈推荐页面初始状态测试.",
"name": "test_planet_notify_ui",
"signature": "def test_planet_notify_ui(self)"
},
{
"docstring": "测试消息中心通知页.",
"name": "test_notify_info",
"signature": "def test_notify_info(self)"
},
{
"docstring": "测试消息中心动态.",
"name": "test_notify_message",... | 3 | stack_v2_sparse_classes_30k_train_008419 | Implement the Python class `TestPlanetNotify` described below.
Class description:
小影圈通知页的测试类,分步截图.
Method signatures and docstrings:
- def test_planet_notify_ui(self): 小影圈推荐页面初始状态测试.
- def test_notify_info(self): 测试消息中心通知页.
- def test_notify_message(self): 测试消息中心动态. | Implement the Python class `TestPlanetNotify` described below.
Class description:
小影圈通知页的测试类,分步截图.
Method signatures and docstrings:
- def test_planet_notify_ui(self): 小影圈推荐页面初始状态测试.
- def test_notify_info(self): 测试消息中心通知页.
- def test_notify_message(self): 测试消息中心动态.
<|skeleton|>
class TestPlanetNotify:
"""小影圈通知页... | 0003b68fc8e26a96ee1661c1eb1f26f96810e909 | <|skeleton|>
class TestPlanetNotify:
"""小影圈通知页的测试类,分步截图."""
def test_planet_notify_ui(self):
"""小影圈推荐页面初始状态测试."""
<|body_0|>
def test_notify_info(self):
"""测试消息中心通知页."""
<|body_1|>
def test_notify_message(self):
"""测试消息中心动态."""
<|body_2|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPlanetNotify:
"""小影圈通知页的测试类,分步截图."""
def test_planet_notify_ui(self):
"""小影圈推荐页面初始状态测试."""
sc.logger.info('小影圈推荐页面初始状态检查开始')
fun_name = 'test_planet_notify_ui'
sc.logger.info('点击小影圈主按钮')
p_btn = 'com.quvideo.xiaoying:id/img_find'
WebDriverWait(sc.driver... | the_stack_v2_python_sparse | iOS/VivaVideo/test_community/test_planet/test_notify.py | Lemonzhulixin/UItest | train | 5 |
be439d3edf3e6188aad544062f1a3afa8156fd6a | [
"self.rule_name = rule_name\nself.rule_index = rule_index\nself.rules = rules",
"for instance_network_interface in instance_network_interface_list:\n network_and_project = re.search('compute/.*/projects/([^/]*).*networks/([^/]*)', instance_network_interface.network)\n project = network_and_project.group(1)\... | <|body_start_0|>
self.rule_name = rule_name
self.rule_index = rule_index
self.rules = rules
<|end_body_0|>
<|body_start_1|>
for instance_network_interface in instance_network_interface_list:
network_and_project = re.search('compute/.*/projects/([^/]*).*networks/([^/]*)', ins... | The rules class for instance_network_interface. | Rule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""The rules class for instance_network_interface."""
def __init__(self, rule_name, rule_index, rules):
"""Initialize. Args: rule_name (str): Name of the loaded rule rule_index (int): The index of the rule from the definitions rules (dict): The resources associated with the rul... | stack_v2_sparse_classes_36k_train_030763 | 9,506 | permissive | [
{
"docstring": "Initialize. Args: rule_name (str): Name of the loaded rule rule_index (int): The index of the rule from the definitions rules (dict): The resources associated with the rules like the whitelist",
"name": "__init__",
"signature": "def __init__(self, rule_name, rule_index, rules)"
},
{
... | 2 | null | Implement the Python class `Rule` described below.
Class description:
The rules class for instance_network_interface.
Method signatures and docstrings:
- def __init__(self, rule_name, rule_index, rules): Initialize. Args: rule_name (str): Name of the loaded rule rule_index (int): The index of the rule from the defini... | Implement the Python class `Rule` described below.
Class description:
The rules class for instance_network_interface.
Method signatures and docstrings:
- def __init__(self, rule_name, rule_index, rules): Initialize. Args: rule_name (str): Name of the loaded rule rule_index (int): The index of the rule from the defini... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Rule:
"""The rules class for instance_network_interface."""
def __init__(self, rule_name, rule_index, rules):
"""Initialize. Args: rule_name (str): Name of the loaded rule rule_index (int): The index of the rule from the definitions rules (dict): The resources associated with the rul... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rule:
"""The rules class for instance_network_interface."""
def __init__(self, rule_name, rule_index, rules):
"""Initialize. Args: rule_name (str): Name of the loaded rule rule_index (int): The index of the rule from the definitions rules (dict): The resources associated with the rules like the w... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/audit/instance_network_interface_rules_engine.py | kevensen/forseti-security | train | 1 |
503c72178d8d2931ae0e3700e7ee3a0b5478a821 | [
"result = {'result': 'NG'}\ndata = request.get_json(force=True)\nif data:\n succsee, message = CtrlQuotations().add_option_by_quotation_id2(quotation_id, data)\n if succsee:\n result = {'result': 'OK', 'content': message}\n else:\n result['error'] = message\nelse:\n result['error'] = '请不要传... | <|body_start_0|>
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().add_option_by_quotation_id2(quotation_id, data)
if succsee:
result = {'result': 'OK', 'content': message}
else:
... | ApiOptionInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiOptionInfo:
def post(self, quotation_id):
"""更新/添加此报价下的Option :return:"""
<|body_0|>
def get(self, quotation_id):
"""获取此报价下的所有Option :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = {'result': 'NG'}
data = request.get_jso... | stack_v2_sparse_classes_36k_train_030764 | 10,406 | no_license | [
{
"docstring": "更新/添加此报价下的Option :return:",
"name": "post",
"signature": "def post(self, quotation_id)"
},
{
"docstring": "获取此报价下的所有Option :return:",
"name": "get",
"signature": "def get(self, quotation_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009018 | Implement the Python class `ApiOptionInfo` described below.
Class description:
Implement the ApiOptionInfo class.
Method signatures and docstrings:
- def post(self, quotation_id): 更新/添加此报价下的Option :return:
- def get(self, quotation_id): 获取此报价下的所有Option :return: | Implement the Python class `ApiOptionInfo` described below.
Class description:
Implement the ApiOptionInfo class.
Method signatures and docstrings:
- def post(self, quotation_id): 更新/添加此报价下的Option :return:
- def get(self, quotation_id): 获取此报价下的所有Option :return:
<|skeleton|>
class ApiOptionInfo:
def post(self, q... | 64b31e7bdfcb8a4c95f0a8a607f0bcff576cec11 | <|skeleton|>
class ApiOptionInfo:
def post(self, quotation_id):
"""更新/添加此报价下的Option :return:"""
<|body_0|>
def get(self, quotation_id):
"""获取此报价下的所有Option :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiOptionInfo:
def post(self, quotation_id):
"""更新/添加此报价下的Option :return:"""
result = {'result': 'NG'}
data = request.get_json(force=True)
if data:
succsee, message = CtrlQuotations().add_option_by_quotation_id2(quotation_id, data)
if succsee:
... | the_stack_v2_python_sparse | koala/koala_server/app/api_1_0/api_quotations.py | lsn1183/web_project | train | 0 | |
8e1e4ebaaffdcc24bcf5eda616ab59b18b1a7d12 | [
"super(MixAuxiliaryLoss, self).__init__()\nself.aux_weight = aux_weight\nloss_base_cp = loss_base.copy()\nloss_base_name = loss_base_cp.pop('type')\nself.loss_fn = ClassFactory.get_cls('trainer.loss', loss_base_name)(**loss_base_cp['params'])",
"if len(outputs) != 2:\n raise Exception('outputs length must be 2... | <|body_start_0|>
super(MixAuxiliaryLoss, self).__init__()
self.aux_weight = aux_weight
loss_base_cp = loss_base.copy()
loss_base_name = loss_base_cp.pop('type')
self.loss_fn = ClassFactory.get_cls('trainer.loss', loss_base_name)(**loss_base_cp['params'])
<|end_body_0|>
<|body_st... | Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str | MixAuxiliaryLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixAuxiliaryLoss:
"""Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str"""
def __init__(self, aux_weight, loss_base):
"""Init MixAuxiliaryLoss."""
<|body_0|>
def forward(self, outpu... | stack_v2_sparse_classes_36k_train_030765 | 1,457 | permissive | [
{
"docstring": "Init MixAuxiliaryLoss.",
"name": "__init__",
"signature": "def __init__(self, aux_weight, loss_base)"
},
{
"docstring": "Loss forward function.",
"name": "forward",
"signature": "def forward(self, outputs, targets)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009206 | Implement the Python class `MixAuxiliaryLoss` described below.
Class description:
Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str
Method signatures and docstrings:
- def __init__(self, aux_weight, loss_base): Init MixAuxiliar... | Implement the Python class `MixAuxiliaryLoss` described below.
Class description:
Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str
Method signatures and docstrings:
- def __init__(self, aux_weight, loss_base): Init MixAuxiliar... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class MixAuxiliaryLoss:
"""Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str"""
def __init__(self, aux_weight, loss_base):
"""Init MixAuxiliaryLoss."""
<|body_0|>
def forward(self, outpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MixAuxiliaryLoss:
"""Class of Mix Auxiliary Loss. :param aux_weight: auxiliary loss weight :type aux_weight: float :loss_base: base loss function :loss_base: str"""
def __init__(self, aux_weight, loss_base):
"""Init MixAuxiliaryLoss."""
super(MixAuxiliaryLoss, self).__init__()
sel... | the_stack_v2_python_sparse | zeus/networks/pytorch/losses/mix_auxiliary_loss.py | huawei-noah/xingtian | train | 308 |
d26aa17184ed3846a2e954bf7ebdb5870aca4019 | [
"os.remove(invoice_file)\nadd_furniture(invoice_file, 'Elisa Miles', 'LR04', 'Leather Sofa', 25)\nadd_furniture(invoice_file, 'Edward Data', 'KT78', 'Kitchen Table', 10)\nadd_furniture(invoice_file, 'Alex Gonzales', 'BR02', 'Queen Mattress', 17)\nexpected = [['Elisa Miles', 'LR04', 'Leather Sofa', '25'], ['Edward D... | <|body_start_0|>
os.remove(invoice_file)
add_furniture(invoice_file, 'Elisa Miles', 'LR04', 'Leather Sofa', 25)
add_furniture(invoice_file, 'Edward Data', 'KT78', 'Kitchen Table', 10)
add_furniture(invoice_file, 'Alex Gonzales', 'BR02', 'Queen Mattress', 17)
expected = [['Elisa M... | This class tests inventory functions | InventoryTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InventoryTests:
"""This class tests inventory functions"""
def test_add_furniture(self, invoice_file='invoice_test.csv'):
"""Test inventory function"""
<|body_0|>
def test_single_customer(self, invoice_file='invoice_test.csv'):
"""This module tests single_custome... | stack_v2_sparse_classes_36k_train_030766 | 1,772 | no_license | [
{
"docstring": "Test inventory function",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self, invoice_file='invoice_test.csv')"
},
{
"docstring": "This module tests single_customer function",
"name": "test_single_customer",
"signature": "def test_single_customer(self... | 2 | stack_v2_sparse_classes_30k_train_020178 | Implement the Python class `InventoryTests` described below.
Class description:
This class tests inventory functions
Method signatures and docstrings:
- def test_add_furniture(self, invoice_file='invoice_test.csv'): Test inventory function
- def test_single_customer(self, invoice_file='invoice_test.csv'): This module... | Implement the Python class `InventoryTests` described below.
Class description:
This class tests inventory functions
Method signatures and docstrings:
- def test_add_furniture(self, invoice_file='invoice_test.csv'): Test inventory function
- def test_single_customer(self, invoice_file='invoice_test.csv'): This module... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class InventoryTests:
"""This class tests inventory functions"""
def test_add_furniture(self, invoice_file='invoice_test.csv'):
"""Test inventory function"""
<|body_0|>
def test_single_customer(self, invoice_file='invoice_test.csv'):
"""This module tests single_custome... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InventoryTests:
"""This class tests inventory functions"""
def test_add_furniture(self, invoice_file='invoice_test.csv'):
"""Test inventory function"""
os.remove(invoice_file)
add_furniture(invoice_file, 'Elisa Miles', 'LR04', 'Leather Sofa', 25)
add_furniture(invoice_file... | the_stack_v2_python_sparse | students/philip_behrend/lesson08/test_inventory.py | JavaRod/SP_Python220B_2019 | train | 1 |
7c0594018cb01fd001d9aa07898cf64629ce10b8 | [
"if not data.get('project_id'):\n data['project_id'] = lambda: uuid.uuid4().hex\nreturn data",
"try:\n git_url = GitURL.parse(data['git_url'])\nexcept UnicodeError as e:\n raise ValidationError('`git_url` contains unsupported characters') from e\nexcept ConfigurationError as e:\n raise ValidationError... | <|body_start_0|>
if not data.get('project_id'):
data['project_id'] = lambda: uuid.uuid4().hex
return data
<|end_body_0|>
<|body_start_1|>
try:
git_url = GitURL.parse(data['git_url'])
except UnicodeError as e:
raise ValidationError('`git_url` contains ... | Context schema for project clone. | ProjectCloneContext | [
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectCloneContext:
"""Context schema for project clone."""
def set_missing_id(self, data, **kwargs):
"""Set project_id when missing."""
<|body_0|>
def set_owner_name(self, data, **kwargs):
"""Set owner and name fields."""
<|body_1|>
def format_url(... | stack_v2_sparse_classes_36k_train_030767 | 7,933 | permissive | [
{
"docstring": "Set project_id when missing.",
"name": "set_missing_id",
"signature": "def set_missing_id(self, data, **kwargs)"
},
{
"docstring": "Set owner and name fields.",
"name": "set_owner_name",
"signature": "def set_owner_name(self, data, **kwargs)"
},
{
"docstring": "Fo... | 4 | stack_v2_sparse_classes_30k_train_004343 | Implement the Python class `ProjectCloneContext` described below.
Class description:
Context schema for project clone.
Method signatures and docstrings:
- def set_missing_id(self, data, **kwargs): Set project_id when missing.
- def set_owner_name(self, data, **kwargs): Set owner and name fields.
- def format_url(self... | Implement the Python class `ProjectCloneContext` described below.
Class description:
Context schema for project clone.
Method signatures and docstrings:
- def set_missing_id(self, data, **kwargs): Set project_id when missing.
- def set_owner_name(self, data, **kwargs): Set owner and name fields.
- def format_url(self... | 449ec7bca1cc435e5a8ceb278e49a422b953bb09 | <|skeleton|>
class ProjectCloneContext:
"""Context schema for project clone."""
def set_missing_id(self, data, **kwargs):
"""Set project_id when missing."""
<|body_0|>
def set_owner_name(self, data, **kwargs):
"""Set owner and name fields."""
<|body_1|>
def format_url(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectCloneContext:
"""Context schema for project clone."""
def set_missing_id(self, data, **kwargs):
"""Set project_id when missing."""
if not data.get('project_id'):
data['project_id'] = lambda: uuid.uuid4().hex
return data
def set_owner_name(self, data, **kwar... | the_stack_v2_python_sparse | renku/service/serializers/cache.py | code-inflation/renku-python | train | 0 |
97fa7117ba6ac2633241f6c3e812691bd96ac0e9 | [
"redirect = redirect_uri if redirect_uri else self._redirect_uri\nif not redirect:\n raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')\nresponse_type = kw.pop('response_type', 'code')\nreturn 'https://api.weibo.com/oauth2/authorize?%s' % _encode_params(client_id=self._client_id, respons... | <|body_start_0|>
redirect = redirect_uri if redirect_uri else self._redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
response_type = kw.pop('response_type', 'code')
return 'https://api.weibo.com/oauth2/authorize?%s' % _... | SinaWeiboMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinaWeiboMixin:
def get_authorize_url(self, redirect_uri, **kw):
"""return the authorization url that the user should be redirected to."""
<|body_0|>
def _prepare_api(self, method, path, access_token, **kw):
"""Get api url."""
<|body_1|>
def request_acce... | stack_v2_sparse_classes_36k_train_030768 | 31,415 | permissive | [
{
"docstring": "return the authorization url that the user should be redirected to.",
"name": "get_authorize_url",
"signature": "def get_authorize_url(self, redirect_uri, **kw)"
},
{
"docstring": "Get api url.",
"name": "_prepare_api",
"signature": "def _prepare_api(self, method, path, a... | 4 | stack_v2_sparse_classes_30k_train_008259 | Implement the Python class `SinaWeiboMixin` described below.
Class description:
Implement the SinaWeiboMixin class.
Method signatures and docstrings:
- def get_authorize_url(self, redirect_uri, **kw): return the authorization url that the user should be redirected to.
- def _prepare_api(self, method, path, access_tok... | Implement the Python class `SinaWeiboMixin` described below.
Class description:
Implement the SinaWeiboMixin class.
Method signatures and docstrings:
- def get_authorize_url(self, redirect_uri, **kw): return the authorization url that the user should be redirected to.
- def _prepare_api(self, method, path, access_tok... | 32414aefca3dece429f3282793c6a73017d9497a | <|skeleton|>
class SinaWeiboMixin:
def get_authorize_url(self, redirect_uri, **kw):
"""return the authorization url that the user should be redirected to."""
<|body_0|>
def _prepare_api(self, method, path, access_token, **kw):
"""Get api url."""
<|body_1|>
def request_acce... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SinaWeiboMixin:
def get_authorize_url(self, redirect_uri, **kw):
"""return the authorization url that the user should be redirected to."""
redirect = redirect_uri if redirect_uri else self._redirect_uri
if not redirect:
raise APIError('21305', 'Parameter absent: redirect_ur... | the_stack_v2_python_sparse | oauth2/snspy.py | water-law/waterlawblog | train | 4 | |
c0a207a496b0aa927b693e60f278d4ceddbf14c3 | [
"self.repeat_time = repeat_time\nself.function = function\nself.include_event = include_event\nself.args = args\nif current_time is None:\n self.prev_time = 0.0\nelse:\n self.prev_time = current_time",
"if timestamp - self.prev_time > self.repeat_time:\n if self.include_event:\n self.function(self... | <|body_start_0|>
self.repeat_time = repeat_time
self.function = function
self.include_event = include_event
self.args = args
if current_time is None:
self.prev_time = 0.0
else:
self.prev_time = current_time
<|end_body_0|>
<|body_start_1|>
... | Object used when linking recurring functions for a serial stream. | RecurringEvent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurringEvent:
"""Object used when linking recurring functions for a serial stream."""
def __init__(self, repeat_time, current_time, function, args, include_event):
""":param repeat_time: How often to call the passed function :param current_time: The start time (in case this is bein... | stack_v2_sparse_classes_36k_train_030769 | 2,511 | no_license | [
{
"docstring": ":param repeat_time: How often to call the passed function :param current_time: The start time (in case this is being used in a simulated environment) :param function: a reference to a function. It doesn't take parameters by default. You can supply parameters with the args parameter :param args: ... | 2 | stack_v2_sparse_classes_30k_train_009104 | Implement the Python class `RecurringEvent` described below.
Class description:
Object used when linking recurring functions for a serial stream.
Method signatures and docstrings:
- def __init__(self, repeat_time, current_time, function, args, include_event): :param repeat_time: How often to call the passed function ... | Implement the Python class `RecurringEvent` described below.
Class description:
Object used when linking recurring functions for a serial stream.
Method signatures and docstrings:
- def __init__(self, repeat_time, current_time, function, args, include_event): :param repeat_time: How often to call the passed function ... | 06abf4f441e22db87c34ff655546a520de696fda | <|skeleton|>
class RecurringEvent:
"""Object used when linking recurring functions for a serial stream."""
def __init__(self, repeat_time, current_time, function, args, include_event):
""":param repeat_time: How often to call the passed function :param current_time: The start time (in case this is bein... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecurringEvent:
"""Object used when linking recurring functions for a serial stream."""
def __init__(self, repeat_time, current_time, function, args, include_event):
""":param repeat_time: How often to call the passed function :param current_time: The start time (in case this is being used in a s... | the_stack_v2_python_sparse | atlasbuggy/serial/events.py | Twizanex/HSA1 | train | 0 |
ea195272b59877c2b0347cdedbb42f77a10574c4 | [
"self.cmd_q = queue.Queue()\nself.data_list = list()\nself.msg_num = 0",
"self.data_list.append(data)\nself.cmd_q.put(self.msg_num, block=block)\nself.msg_num += 1",
"try:\n self.cmd_q.get(block=block)\nexcept queue.Empty:\n data = None\nelse:\n data = self.data_list.pop(0)\nreturn data"
] | <|body_start_0|>
self.cmd_q = queue.Queue()
self.data_list = list()
self.msg_num = 0
<|end_body_0|>
<|body_start_1|>
self.data_list.append(data)
self.cmd_q.put(self.msg_num, block=block)
self.msg_num += 1
<|end_body_1|>
<|body_start_2|>
try:
self.cmd... | Create local message used for communication inner process. | LocalMsg | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalMsg:
"""Create local message used for communication inner process."""
def __init__(self, comm_info):
"""Initialize."""
<|body_0|>
def send(self, data, name=None, block=True):
"""Send data."""
<|body_1|>
def recv(self, name=None, block=True):
... | stack_v2_sparse_classes_36k_train_030770 | 2,003 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, comm_info)"
},
{
"docstring": "Send data.",
"name": "send",
"signature": "def send(self, data, name=None, block=True)"
},
{
"docstring": "Receive data.",
"name": "recv",
"signature": "def r... | 3 | null | Implement the Python class `LocalMsg` described below.
Class description:
Create local message used for communication inner process.
Method signatures and docstrings:
- def __init__(self, comm_info): Initialize.
- def send(self, data, name=None, block=True): Send data.
- def recv(self, name=None, block=True): Receive... | Implement the Python class `LocalMsg` described below.
Class description:
Create local message used for communication inner process.
Method signatures and docstrings:
- def __init__(self, comm_info): Initialize.
- def send(self, data, name=None, block=True): Send data.
- def recv(self, name=None, block=True): Receive... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class LocalMsg:
"""Create local message used for communication inner process."""
def __init__(self, comm_info):
"""Initialize."""
<|body_0|>
def send(self, data, name=None, block=True):
"""Send data."""
<|body_1|>
def recv(self, name=None, block=True):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalMsg:
"""Create local message used for communication inner process."""
def __init__(self, comm_info):
"""Initialize."""
self.cmd_q = queue.Queue()
self.data_list = list()
self.msg_num = 0
def send(self, data, name=None, block=True):
"""Send data."""
... | the_stack_v2_python_sparse | zeus/common/ipc/local_msg.py | huawei-noah/xingtian | train | 308 |
760b63e1240909073159b3ebf99ed17172a39268 | [
"self.periods = periods\nself.num_per = len(periods)\nself.acceleration = convert_accel_units(acceleration, units)\nself.damping = damping\nself.d_t = time_step\nself.velocity, self.displacement = get_velocity_displacement(self.d_t, self.acceleration)\nself.num_steps = len(self.acceleration)\nself.omega = 2.0 * np.... | <|body_start_0|>
self.periods = periods
self.num_per = len(periods)
self.acceleration = convert_accel_units(acceleration, units)
self.damping = damping
self.d_t = time_step
self.velocity, self.displacement = get_velocity_displacement(self.d_t, self.acceleration)
s... | Evaluates the response spectrum using the Newmark-Beta methodology | NewmarkBeta | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewmarkBeta:
"""Evaluates the response spectrum using the Newmark-Beta methodology"""
def __init__(self, acceleration, time_step, periods, damping=0.05, dt_disc=0.002, units='g'):
"""Setup the response spectrum calculator :param numpy.ndarray time_hist: Acceleration time history :par... | stack_v2_sparse_classes_36k_train_030771 | 8,322 | no_license | [
{
"docstring": "Setup the response spectrum calculator :param numpy.ndarray time_hist: Acceleration time history :param numpy.ndarray periods: Spectral periods (s) for calculation :param float damping: Fractional coefficient of damping :param float dt_disc: Sampling rate of the acceleartion :param str units: Un... | 3 | null | Implement the Python class `NewmarkBeta` described below.
Class description:
Evaluates the response spectrum using the Newmark-Beta methodology
Method signatures and docstrings:
- def __init__(self, acceleration, time_step, periods, damping=0.05, dt_disc=0.002, units='g'): Setup the response spectrum calculator :para... | Implement the Python class `NewmarkBeta` described below.
Class description:
Evaluates the response spectrum using the Newmark-Beta methodology
Method signatures and docstrings:
- def __init__(self, acceleration, time_step, periods, damping=0.05, dt_disc=0.002, units='g'): Setup the response spectrum calculator :para... | 9c051b36e3c62b63795ae0ce072f80a02e342c34 | <|skeleton|>
class NewmarkBeta:
"""Evaluates the response spectrum using the Newmark-Beta methodology"""
def __init__(self, acceleration, time_step, periods, damping=0.05, dt_disc=0.002, units='g'):
"""Setup the response spectrum calculator :param numpy.ndarray time_hist: Acceleration time history :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewmarkBeta:
"""Evaluates the response spectrum using the Newmark-Beta methodology"""
def __init__(self, acceleration, time_step, periods, damping=0.05, dt_disc=0.002, units='g'):
"""Setup the response spectrum calculator :param numpy.ndarray time_hist: Acceleration time history :param numpy.ndar... | the_stack_v2_python_sparse | modules/Workflow/computeResponseSpectrum.py | NHERI-SimCenter/SimCenterBackendApplications | train | 5 |
9c241f79983ac279ab284914368fc9ac6c83c872 | [
"super(ObsEnsemble, self).__init__()\nself._Cs = nn.Parameter(torch.randn(num_submodels, obs_dim, latent_dim))\nself._weight_model = weight_model",
"if full_seq:\n return torch.sum(self._Cs[None, None, ...] * alpha[..., None, None], dim=2)\nelse:\n return torch.sum(self._Cs.unsqueeze(0) * alpha[..., None, N... | <|body_start_0|>
super(ObsEnsemble, self).__init__()
self._Cs = nn.Parameter(torch.randn(num_submodels, obs_dim, latent_dim))
self._weight_model = weight_model
<|end_body_0|>
<|body_start_1|>
if full_seq:
return torch.sum(self._Cs[None, None, ...] * alpha[..., None, None], d... | Observation ensemble. | ObsEnsemble | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObsEnsemble:
"""Observation ensemble."""
def __init__(self, num_submodels: int, latent_dim: int, obs_dim: int, weight_model: WeightModel) -> None:
"""Initialize the observation model."""
<|body_0|>
def get_C(self, alpha: torch.Tensor, full_seq: bool=False) -> torch.Tenso... | stack_v2_sparse_classes_36k_train_030772 | 19,607 | permissive | [
{
"docstring": "Initialize the observation model.",
"name": "__init__",
"signature": "def __init__(self, num_submodels: int, latent_dim: int, obs_dim: int, weight_model: WeightModel) -> None"
},
{
"docstring": "Returns C.",
"name": "get_C",
"signature": "def get_C(self, alpha: torch.Tens... | 3 | stack_v2_sparse_classes_30k_train_002518 | Implement the Python class `ObsEnsemble` described below.
Class description:
Observation ensemble.
Method signatures and docstrings:
- def __init__(self, num_submodels: int, latent_dim: int, obs_dim: int, weight_model: WeightModel) -> None: Initialize the observation model.
- def get_C(self, alpha: torch.Tensor, full... | Implement the Python class `ObsEnsemble` described below.
Class description:
Observation ensemble.
Method signatures and docstrings:
- def __init__(self, num_submodels: int, latent_dim: int, obs_dim: int, weight_model: WeightModel) -> None: Initialize the observation model.
- def get_C(self, alpha: torch.Tensor, full... | 184b1537c22ebc2f614677be8fe171de785bda42 | <|skeleton|>
class ObsEnsemble:
"""Observation ensemble."""
def __init__(self, num_submodels: int, latent_dim: int, obs_dim: int, weight_model: WeightModel) -> None:
"""Initialize the observation model."""
<|body_0|>
def get_C(self, alpha: torch.Tensor, full_seq: bool=False) -> torch.Tenso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObsEnsemble:
"""Observation ensemble."""
def __init__(self, num_submodels: int, latent_dim: int, obs_dim: int, weight_model: WeightModel) -> None:
"""Initialize the observation model."""
super(ObsEnsemble, self).__init__()
self._Cs = nn.Parameter(torch.randn(num_submodels, obs_dim... | the_stack_v2_python_sparse | dynamics_learning/networks/kalman/le_ekf.py | cristovaoiglesias/replay-overshooting | train | 0 |
d4e2aa4665885a5ebfcf6e20152a510f8f84aaa5 | [
"dp = [float('inf')] * (n + 1)\ndp[0] = 0\nfor i in range(n + 1):\n j = 1\n while j * j <= i:\n dp[i] = min(dp[i], dp[i - j * j] + 1)\n j += 1\nreturn dp[n]",
"def isPerfectSquare(x: int) -> bool:\n y = int(x ** 0.5)\n return y * y == x\n\ndef check(x: int) -> bool:\n while x % 4 == 0... | <|body_start_0|>
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j * j] + 1)
j += 1
return dp[n]
<|end_body_0|>
<|body_start_1|>
def isPerfectSquare(x: int) -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares_MK1(self, n: int) -> int:
"""Time complexity: O(n√n) Space complexity: O(n)"""
<|body_0|>
def numSquares_MK2(self, n: int) -> int:
"""四平方和定理 Time complexity: O(√n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_030773 | 1,025 | no_license | [
{
"docstring": "Time complexity: O(n√n) Space complexity: O(n)",
"name": "numSquares_MK1",
"signature": "def numSquares_MK1(self, n: int) -> int"
},
{
"docstring": "四平方和定理 Time complexity: O(√n) Space complexity: O(1)",
"name": "numSquares_MK2",
"signature": "def numSquares_MK2(self, n: ... | 2 | stack_v2_sparse_classes_30k_train_016567 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares_MK1(self, n: int) -> int: Time complexity: O(n√n) Space complexity: O(n)
- def numSquares_MK2(self, n: int) -> int: 四平方和定理 Time complexity: O(√n) Space complexity:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares_MK1(self, n: int) -> int: Time complexity: O(n√n) Space complexity: O(n)
- def numSquares_MK2(self, n: int) -> int: 四平方和定理 Time complexity: O(√n) Space complexity:... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def numSquares_MK1(self, n: int) -> int:
"""Time complexity: O(n√n) Space complexity: O(n)"""
<|body_0|>
def numSquares_MK2(self, n: int) -> int:
"""四平方和定理 Time complexity: O(√n) Space complexity: O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares_MK1(self, n: int) -> int:
"""Time complexity: O(n√n) Space complexity: O(n)"""
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j * j] + 1)
... | the_stack_v2_python_sparse | 0279. Perfect Squares/Solution.py | faterazer/LeetCode | train | 4 | |
3a14b1c867f2c14502bad08049a6b49735b4e163 | [
"super(ContainerLossFunction, self).__init__(scope=scope, **kwargs)\nif isinstance(loss_functions_spec, dict):\n weights_ = {}\n self.loss_functions = {}\n for i, (key, loss_fn_spec) in enumerate(loss_functions_spec.items()):\n if weights is None and 'weight' in loss_fn_spec:\n weights_[k... | <|body_start_0|>
super(ContainerLossFunction, self).__init__(scope=scope, **kwargs)
if isinstance(loss_functions_spec, dict):
weights_ = {}
self.loss_functions = {}
for i, (key, loss_fn_spec) in enumerate(loss_functions_spec.items()):
if weights is Non... | A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss. | ContainerLossFunction | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerLossFunction:
"""A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss."""
def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs):
"""Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A spe... | stack_v2_sparse_classes_36k_train_030774 | 5,330 | permissive | [
{
"docstring": "Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A specification dict or tuple with values being the spec dicts for the single loss functions. The `loss` methods expect a dict input or a single tuple input (not as *args) in its first parameter. weights (Optional[List[float]]): If g... | 2 | stack_v2_sparse_classes_30k_train_004155 | Implement the Python class `ContainerLossFunction` described below.
Class description:
A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss.
Method signatures and docstrings:
- def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs): Args: loss_... | Implement the Python class `ContainerLossFunction` described below.
Class description:
A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss.
Method signatures and docstrings:
- def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs): Args: loss_... | a10f382e0681ba1f7aa8e83a8c1483afb8b825c1 | <|skeleton|>
class ContainerLossFunction:
"""A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss."""
def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs):
"""Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainerLossFunction:
"""A loss function consisting of n sub-loss functions whose weighted sum is used as the total loss."""
def __init__(self, loss_functions_spec, weights=None, scope='mixture-loss', **kwargs):
"""Args: loss_functions_spec (Union[Dict[str,dict],Tuple[dict]]): A specification di... | the_stack_v2_python_sparse | rlgraph/components/loss_functions/container_loss_function.py | jon-chuang/rlgraph | train | 0 |
4e4983b22a77a1b1b2e49d0b769a275e4683f201 | [
"if len(lipids) != len(ref_rt) or len(lipids) != len(meas_rt):\n m = 'RTCalibration: __init__: lipids, ref_rt, and meas_rt must all be the same length ({}, {}, {})'\n raise ValueError(m.format(len(lipids), len(ref_rt), len(meas_rt)))\nself.meas_rt, self.ref_rt, self.lipids = (list(t) for t in zip(*sorted(zip(... | <|body_start_0|>
if len(lipids) != len(ref_rt) or len(lipids) != len(meas_rt):
m = 'RTCalibration: __init__: lipids, ref_rt, and meas_rt must all be the same length ({}, {}, {})'
raise ValueError(m.format(len(lipids), len(ref_rt), len(meas_rt)))
self.meas_rt, self.ref_rt, self.li... | RTCalibration description: An object for performing HILIC retention time calibration | RTCalibration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RTCalibration:
"""RTCalibration description: An object for performing HILIC retention time calibration"""
def __init__(self, lipids, meas_rt, ref_rt):
"""RTCalibration.__init__ description: Stores lists of lipid calibrants and their reference/measured retention times, lists are sorte... | stack_v2_sparse_classes_36k_train_030775 | 5,954 | permissive | [
{
"docstring": "RTCalibration.__init__ description: Stores lists of lipid calibrants and their reference/measured retention times, lists are sorted together by measured retention time parameters: lipids (list(str)) -- lipid calibrants meas_rt (list(float)) -- measured retention times ref_rt (list(float)) -- ref... | 4 | stack_v2_sparse_classes_30k_train_002703 | Implement the Python class `RTCalibration` described below.
Class description:
RTCalibration description: An object for performing HILIC retention time calibration
Method signatures and docstrings:
- def __init__(self, lipids, meas_rt, ref_rt): RTCalibration.__init__ description: Stores lists of lipid calibrants and ... | Implement the Python class `RTCalibration` described below.
Class description:
RTCalibration description: An object for performing HILIC retention time calibration
Method signatures and docstrings:
- def __init__(self, lipids, meas_rt, ref_rt): RTCalibration.__init__ description: Stores lists of lipid calibrants and ... | c7c3b72d4549a1a9937f287f3b314eff8e7ed054 | <|skeleton|>
class RTCalibration:
"""RTCalibration description: An object for performing HILIC retention time calibration"""
def __init__(self, lipids, meas_rt, ref_rt):
"""RTCalibration.__init__ description: Stores lists of lipid calibrants and their reference/measured retention times, lists are sorte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RTCalibration:
"""RTCalibration description: An object for performing HILIC retention time calibration"""
def __init__(self, lipids, meas_rt, ref_rt):
"""RTCalibration.__init__ description: Stores lists of lipid calibrants and their reference/measured retention times, lists are sorted together by... | the_stack_v2_python_sparse | lipydomics/identification/rt_calibration.py | kaitlin-rempfert/lipydomics | train | 0 |
1afa1c6a694d315ade76cf6f35a6e7ac68991a10 | [
"for parent_id_option_expression in PARENT_ID_OPTION_EXPRESSIONS:\n if parent_id_option_expression.match(option):\n return True\nreturn False",
"for parent_id_option_expression in PARENT_ID_OPTION_EXPRESSIONS:\n match = parent_id_option_expression.match(option)\n if match is not None:\n ret... | <|body_start_0|>
for parent_id_option_expression in PARENT_ID_OPTION_EXPRESSIONS:
if parent_id_option_expression.match(option):
return True
return False
<|end_body_0|>
<|body_start_1|>
for parent_id_option_expression in PARENT_ID_OPTION_EXPRESSIONS:
match... | OptionHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionHelper:
def is_parent_id_option(option):
"""Checks if the given option name is a reference to a parent entity."""
<|body_0|>
def get_parent_id_type(option):
"""Extracts the name of the type from an option that is a reference to a parent entity. For example, if ... | stack_v2_sparse_classes_36k_train_030776 | 1,932 | permissive | [
{
"docstring": "Checks if the given option name is a reference to a parent entity.",
"name": "is_parent_id_option",
"signature": "def is_parent_id_option(option)"
},
{
"docstring": "Extracts the name of the type from an option that is a reference to a parent entity. For example, if the option is... | 2 | stack_v2_sparse_classes_30k_train_015884 | Implement the Python class `OptionHelper` described below.
Class description:
Implement the OptionHelper class.
Method signatures and docstrings:
- def is_parent_id_option(option): Checks if the given option name is a reference to a parent entity.
- def get_parent_id_type(option): Extracts the name of the type from a... | Implement the Python class `OptionHelper` described below.
Class description:
Implement the OptionHelper class.
Method signatures and docstrings:
- def is_parent_id_option(option): Checks if the given option name is a reference to a parent entity.
- def get_parent_id_type(option): Extracts the name of the type from a... | 422d70e1dc422f0ca248abea47a472e3605caa4b | <|skeleton|>
class OptionHelper:
def is_parent_id_option(option):
"""Checks if the given option name is a reference to a parent entity."""
<|body_0|>
def get_parent_id_type(option):
"""Extracts the name of the type from an option that is a reference to a parent entity. For example, if ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptionHelper:
def is_parent_id_option(option):
"""Checks if the given option name is a reference to a parent entity."""
for parent_id_option_expression in PARENT_ID_OPTION_EXPRESSIONS:
if parent_id_option_expression.match(option):
return True
return False
... | the_stack_v2_python_sparse | src/ovirtcli/utils/optionhelper.py | minqf/ovirt-engine-cli | train | 0 | |
3ed3271ee557eab71bd20744e2844954fe54f01a | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_unique_id = f'{DOMAIN}_{coordinator.data.agreement.agreement_id}_binary_sensor_{description.key}'",
"section = getattr(self.coordinator.data, self.entity_description.section)\nvalue = getattr(section, self.entity_description.measure... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f'{DOMAIN}_{coordinator.data.agreement.agreement_id}_binary_sensor_{description.key}'
<|end_body_0|>
<|body_start_1|>
section = getattr(self.coordinator.data, self.entity_descript... | Defines an Toon binary sensor. | ToonBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ToonBinarySensor:
"""Defines an Toon binary sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None:
"""Initialize the Toon sensor."""
<|body_0|>
def is_on(self) -> bool | None:
"""Return the s... | stack_v2_sparse_classes_36k_train_030777 | 5,719 | permissive | [
{
"docstring": "Initialize the Toon sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None"
},
{
"docstring": "Return the status of the binary sensor.",
"name": "is_on",
"signature": "... | 2 | stack_v2_sparse_classes_30k_train_009398 | Implement the Python class `ToonBinarySensor` described below.
Class description:
Defines an Toon binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None: Initialize the Toon sensor.
- def is_on(self) -> bool... | Implement the Python class `ToonBinarySensor` described below.
Class description:
Defines an Toon binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None: Initialize the Toon sensor.
- def is_on(self) -> bool... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ToonBinarySensor:
"""Defines an Toon binary sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None:
"""Initialize the Toon sensor."""
<|body_0|>
def is_on(self) -> bool | None:
"""Return the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ToonBinarySensor:
"""Defines an Toon binary sensor."""
def __init__(self, coordinator: ToonDataUpdateCoordinator, description: ToonBinarySensorEntityDescription) -> None:
"""Initialize the Toon sensor."""
super().__init__(coordinator)
self.entity_description = description
... | the_stack_v2_python_sparse | homeassistant/components/toon/binary_sensor.py | home-assistant/core | train | 35,501 |
eca57b80ccc11698f5b1d8d335263cb647758501 | [
"form_mock = {'xmlns': 'unknown', 'domain': 'test-domain'}\npayload_generator = FormRepeaterDhis2EventPayloadGenerator(None)\nwith self.assertRaises(IgnoreDocument):\n payload_generator.get_payload(None, form_mock)",
"case_mock = Mock()\ncase_mock.type = CASE_TYPE\ncases_referenced_by_xform.return_value = [cas... | <|body_start_0|>
form_mock = {'xmlns': 'unknown', 'domain': 'test-domain'}
payload_generator = FormRepeaterDhis2EventPayloadGenerator(None)
with self.assertRaises(IgnoreDocument):
payload_generator.get_payload(None, form_mock)
<|end_body_0|>
<|body_start_1|>
case_mock = Mock... | PayloadGeneratorTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayloadGeneratorTest:
def test_get_payload_ignores_unknown_form(self):
"""get_payload should raise IgnoreDocument on unknown form XMLNS"""
<|body_0|>
def test_get_payload_ignores_registration(self, Dhis2SettingsPatch, cases_referenced_by_xform, push_case):
"""get_pay... | stack_v2_sparse_classes_36k_train_030778 | 18,511 | no_license | [
{
"docstring": "get_payload should raise IgnoreDocument on unknown form XMLNS",
"name": "test_get_payload_ignores_unknown_form",
"signature": "def test_get_payload_ignores_unknown_form(self)"
},
{
"docstring": "get_payload should raise IgnoreDocument given a registration form",
"name": "test... | 2 | stack_v2_sparse_classes_30k_train_000894 | Implement the Python class `PayloadGeneratorTest` described below.
Class description:
Implement the PayloadGeneratorTest class.
Method signatures and docstrings:
- def test_get_payload_ignores_unknown_form(self): get_payload should raise IgnoreDocument on unknown form XMLNS
- def test_get_payload_ignores_registration... | Implement the Python class `PayloadGeneratorTest` described below.
Class description:
Implement the PayloadGeneratorTest class.
Method signatures and docstrings:
- def test_get_payload_ignores_unknown_form(self): get_payload should raise IgnoreDocument on unknown form XMLNS
- def test_get_payload_ignores_registration... | 6d3eb1a0e70cc2a59a82ec5bba12170387803150 | <|skeleton|>
class PayloadGeneratorTest:
def test_get_payload_ignores_unknown_form(self):
"""get_payload should raise IgnoreDocument on unknown form XMLNS"""
<|body_0|>
def test_get_payload_ignores_registration(self, Dhis2SettingsPatch, cases_referenced_by_xform, push_case):
"""get_pay... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PayloadGeneratorTest:
def test_get_payload_ignores_unknown_form(self):
"""get_payload should raise IgnoreDocument on unknown form XMLNS"""
form_mock = {'xmlns': 'unknown', 'domain': 'test-domain'}
payload_generator = FormRepeaterDhis2EventPayloadGenerator(None)
with self.assert... | the_stack_v2_python_sparse | custom/dhis2/tests.py | saketkanth/commcare-hq | train | 0 | |
f1d08a616b7c7824a8d1b0cdb5f6513ba8aab957 | [
"queryset = self.queryset\nkeywords = self.request.query_params.get('keywords', None)\nif keywords:\n queryset = queryset.filter(slug__icontains=slugify(keywords))\nreturn queryset",
"name = request.data.get('name', None)\nif name:\n queryset = self.get_queryset()\n tag = queryset.filter(name=name).first... | <|body_start_0|>
queryset = self.queryset
keywords = self.request.query_params.get('keywords', None)
if keywords:
queryset = queryset.filter(slug__icontains=slugify(keywords))
return queryset
<|end_body_0|>
<|body_start_1|>
name = request.data.get('name', None)
... | Tag view set | TagsViewSets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagsViewSets:
"""Tag view set"""
def get_queryset(self):
"""Query set selection"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Overwrite create method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queryset = self.queryset
... | stack_v2_sparse_classes_36k_train_030779 | 4,926 | no_license | [
{
"docstring": "Query set selection",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Overwrite create method",
"name": "create",
"signature": "def create(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020457 | Implement the Python class `TagsViewSets` described below.
Class description:
Tag view set
Method signatures and docstrings:
- def get_queryset(self): Query set selection
- def create(self, request, *args, **kwargs): Overwrite create method | Implement the Python class `TagsViewSets` described below.
Class description:
Tag view set
Method signatures and docstrings:
- def get_queryset(self): Query set selection
- def create(self, request, *args, **kwargs): Overwrite create method
<|skeleton|>
class TagsViewSets:
"""Tag view set"""
def get_queryse... | 85f6836405560deb1415d0fc0dc66b6a1f30ec7a | <|skeleton|>
class TagsViewSets:
"""Tag view set"""
def get_queryset(self):
"""Query set selection"""
<|body_0|>
def create(self, request, *args, **kwargs):
"""Overwrite create method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagsViewSets:
"""Tag view set"""
def get_queryset(self):
"""Query set selection"""
queryset = self.queryset
keywords = self.request.query_params.get('keywords', None)
if keywords:
queryset = queryset.filter(slug__icontains=slugify(keywords))
return quer... | the_stack_v2_python_sparse | cms-api/cms/views.py | duykieu/react-query-trainning-demo | train | 2 |
0193f15208172b756f69b712573ddaac26bfc8eb | [
"self._heater = heater\nself._store = store\nself._attr_unique_id = heater.device_id\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, self.unique_id)}, manufacturer='Ambiclimate', name=heater.name)",
"if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:\n return\nawait self._heater.set_target_te... | <|body_start_0|>
self._heater = heater
self._store = store
self._attr_unique_id = heater.device_id
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, self.unique_id)}, manufacturer='Ambiclimate', name=heater.name)
<|end_body_0|>
<|body_start_1|>
if (temperature := kwargs.... | Representation of a Ambiclimate Thermostat device. | AmbiclimateEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmbiclimateEntity:
"""Representation of a Ambiclimate Thermostat device."""
def __init__(self, heater, store):
"""Initialize the thermostat."""
<|body_0|>
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
<|bo... | stack_v2_sparse_classes_36k_train_030780 | 6,562 | permissive | [
{
"docstring": "Initialize the thermostat.",
"name": "__init__",
"signature": "def __init__(self, heater, store)"
},
{
"docstring": "Set new target temperature.",
"name": "async_set_temperature",
"signature": "async def async_set_temperature(self, **kwargs: Any) -> None"
},
{
"do... | 4 | null | Implement the Python class `AmbiclimateEntity` described below.
Class description:
Representation of a Ambiclimate Thermostat device.
Method signatures and docstrings:
- def __init__(self, heater, store): Initialize the thermostat.
- async def async_set_temperature(self, **kwargs: Any) -> None: Set new target tempera... | Implement the Python class `AmbiclimateEntity` described below.
Class description:
Representation of a Ambiclimate Thermostat device.
Method signatures and docstrings:
- def __init__(self, heater, store): Initialize the thermostat.
- async def async_set_temperature(self, **kwargs: Any) -> None: Set new target tempera... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AmbiclimateEntity:
"""Representation of a Ambiclimate Thermostat device."""
def __init__(self, heater, store):
"""Initialize the thermostat."""
<|body_0|>
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmbiclimateEntity:
"""Representation of a Ambiclimate Thermostat device."""
def __init__(self, heater, store):
"""Initialize the thermostat."""
self._heater = heater
self._store = store
self._attr_unique_id = heater.device_id
self._attr_device_info = DeviceInfo(ide... | the_stack_v2_python_sparse | homeassistant/components/ambiclimate/climate.py | home-assistant/core | train | 35,501 |
b79c00304ac3ff140cd963c481b6756af2da4651 | [
"if not nums:\n return\nself.dp = [None for _ in range(len(nums))]\nself.dp[0] = nums[0]\nfor i in range(1, len(nums)):\n self.dp[i] = nums[i] + self.dp[i - 1]\nreturn",
"if i == 0:\n return self.dp[j]\nreturn self.dp[j] - self.dp[i - 1]"
] | <|body_start_0|>
if not nums:
return
self.dp = [None for _ in range(len(nums))]
self.dp[0] = nums[0]
for i in range(1, len(nums)):
self.dp[i] = nums[i] + self.dp[i - 1]
return
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.dp[j... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return
self.dp = [None for... | stack_v2_sparse_classes_36k_train_030781 | 793 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | f915e7b7665b9efcc7e9d5a63258d9e65d9abfea | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
if not nums:
return
self.dp = [None for _ in range(len(nums))]
self.dp[0] = nums[0]
for i in range(1, len(nums)):
self.dp[i] = nums[i] + self.dp[i - 1]
return
def sumRan... | the_stack_v2_python_sparse | dynamic_programming/303_range_sum_query_immutable.py | jingyiZhang123/leetcode_practice | train | 0 | |
82766567ef50931bca44c5a008007a5838cdb042 | [
"driver = self.driver\ndriver.get(self.base_url)\nhomepage = HomePage(self.driver)\nhomepage.click_oa()\nhomepage.sleep(0.5)\nhomepage.click_itfw()\nhomepage.click_itfwsq()\nhomepage.sleep(0.1)\nhomepage.click_rjdjgl()\nhomepage.switch_frame(driver.find_element_by_xpath(\"//iframe[@src='http://oa2.eascs.com/eaoa/so... | <|body_start_0|>
driver = self.driver
driver.get(self.base_url)
homepage = HomePage(self.driver)
homepage.click_oa()
homepage.sleep(0.5)
homepage.click_itfw()
homepage.click_itfwsq()
homepage.sleep(0.1)
homepage.click_rjdjgl()
homepage.swit... | IT服务申请 | Start | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Start:
"""IT服务申请"""
def test1_rjdjgl(self):
"""软件登记管理"""
<|body_0|>
def test2_xnjsq(self):
"""虚拟机申请"""
<|body_1|>
def test3_xttjsq(self):
"""系统停机申请"""
<|body_2|>
def test4_xttjrz(self):
"""系统停机日志"""
<|body_3|>
<|... | stack_v2_sparse_classes_36k_train_030782 | 3,953 | no_license | [
{
"docstring": "软件登记管理",
"name": "test1_rjdjgl",
"signature": "def test1_rjdjgl(self)"
},
{
"docstring": "虚拟机申请",
"name": "test2_xnjsq",
"signature": "def test2_xnjsq(self)"
},
{
"docstring": "系统停机申请",
"name": "test3_xttjsq",
"signature": "def test3_xttjsq(self)"
},
{... | 4 | stack_v2_sparse_classes_30k_train_009560 | Implement the Python class `Start` described below.
Class description:
IT服务申请
Method signatures and docstrings:
- def test1_rjdjgl(self): 软件登记管理
- def test2_xnjsq(self): 虚拟机申请
- def test3_xttjsq(self): 系统停机申请
- def test4_xttjrz(self): 系统停机日志 | Implement the Python class `Start` described below.
Class description:
IT服务申请
Method signatures and docstrings:
- def test1_rjdjgl(self): 软件登记管理
- def test2_xnjsq(self): 虚拟机申请
- def test3_xttjsq(self): 系统停机申请
- def test4_xttjrz(self): 系统停机日志
<|skeleton|>
class Start:
"""IT服务申请"""
def test1_rjdjgl(self):
... | a90695147681163d45d4951f6a921eda816500bb | <|skeleton|>
class Start:
"""IT服务申请"""
def test1_rjdjgl(self):
"""软件登记管理"""
<|body_0|>
def test2_xnjsq(self):
"""虚拟机申请"""
<|body_1|>
def test3_xttjsq(self):
"""系统停机申请"""
<|body_2|>
def test4_xttjrz(self):
"""系统停机日志"""
<|body_3|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Start:
"""IT服务申请"""
def test1_rjdjgl(self):
"""软件登记管理"""
driver = self.driver
driver.get(self.base_url)
homepage = HomePage(self.driver)
homepage.click_oa()
homepage.sleep(0.5)
homepage.click_itfw()
homepage.click_itfwsq()
homepage.s... | the_stack_v2_python_sparse | oa_test_case/oa_itfwsq.py | shengli520/yyt | train | 0 |
bcdcc17c3993b468bece06eda03b03c8be32c884 | [
"self.shell_name = os.path.basename(shell)\nself.shell_dir = os.path.dirname(shell)\nself.files_to_push = (resources_func or (lambda: []))()\nrel_args = []\nfind_path_re = re.compile('.*(%s/[^\\\\\\'\"]+).*' % re.escape(BASE_DIR))\nfor arg in args or []:\n match = find_path_re.match(arg)\n if match:\n ... | <|body_start_0|>
self.shell_name = os.path.basename(shell)
self.shell_dir = os.path.dirname(shell)
self.files_to_push = (resources_func or (lambda: []))()
rel_args = []
find_path_re = re.compile('.*(%s/[^\\\'"]+).*' % re.escape(BASE_DIR))
for arg in args or []:
... | AndroidCommand | [
"bzip2-1.0.6",
"BSD-3-Clause",
"Apache-2.0",
"SunPro",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidCommand:
def __init__(self, shell, args=None, cmd_prefix=None, timeout=60, env=None, verbose=False, resources_func=None):
"""Initialize the command and all files that need to be pushed to the Android device."""
<|body_0|>
def execute(self, **additional_popen_kwargs):
... | stack_v2_sparse_classes_36k_train_030783 | 9,143 | permissive | [
{
"docstring": "Initialize the command and all files that need to be pushed to the Android device.",
"name": "__init__",
"signature": "def __init__(self, shell, args=None, cmd_prefix=None, timeout=60, env=None, verbose=False, resources_func=None)"
},
{
"docstring": "Execute the command on the de... | 2 | stack_v2_sparse_classes_30k_train_021506 | Implement the Python class `AndroidCommand` described below.
Class description:
Implement the AndroidCommand class.
Method signatures and docstrings:
- def __init__(self, shell, args=None, cmd_prefix=None, timeout=60, env=None, verbose=False, resources_func=None): Initialize the command and all files that need to be ... | Implement the Python class `AndroidCommand` described below.
Class description:
Implement the AndroidCommand class.
Method signatures and docstrings:
- def __init__(self, shell, args=None, cmd_prefix=None, timeout=60, env=None, verbose=False, resources_func=None): Initialize the command and all files that need to be ... | 43c40535cee37fc7349a21793dc33b1833735af5 | <|skeleton|>
class AndroidCommand:
def __init__(self, shell, args=None, cmd_prefix=None, timeout=60, env=None, verbose=False, resources_func=None):
"""Initialize the command and all files that need to be pushed to the Android device."""
<|body_0|>
def execute(self, **additional_popen_kwargs):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AndroidCommand:
def __init__(self, shell, args=None, cmd_prefix=None, timeout=60, env=None, verbose=False, resources_func=None):
"""Initialize the command and all files that need to be pushed to the Android device."""
self.shell_name = os.path.basename(shell)
self.shell_dir = os.path.d... | the_stack_v2_python_sparse | 3rdParty/V8/v7.9.317/tools/testrunner/local/command.py | arangodb/arangodb | train | 13,385 | |
5976a2dd80d24ba694dad84da69c4cae4b9f5dd8 | [
"super(ESPNETMultiHeadedAttention, self).__init__()\nassert n_feat % n_head == 0\nself.d_k = n_feat // n_head\nself.h = n_head\nself.linear_q = nn.Linear(n_feat, n_feat)\nself.linear_k = nn.Linear(n_feat, n_feat)\nself.linear_v = nn.Linear(n_feat, n_feat)\nself.linear_out = nn.Linear(n_feat, n_feat)\nself.attn = No... | <|body_start_0|>
super(ESPNETMultiHeadedAttention, self).__init__()
assert n_feat % n_head == 0
self.d_k = n_feat // n_head
self.h = n_head
self.linear_q = nn.Linear(n_feat, n_feat)
self.linear_k = nn.Linear(n_feat, n_feat)
self.linear_v = nn.Linear(n_feat, n_feat... | Multi-Head Attention layer. Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. | ESPNETMultiHeadedAttention | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ESPNETMultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate."""
def __init__(self, n_feat, n_head, dropout):
"""Construct an MultiHeadedAttention object."""
<|body_0|>
def forward_qkv... | stack_v2_sparse_classes_36k_train_030784 | 9,673 | permissive | [
{
"docstring": "Construct an MultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_feat, n_head, dropout)"
},
{
"docstring": "Transform query, key and value. Args: query: Query tensor B X T1 X C key: Key tensor B X T2 X C value: Value tensor B X T2 X C Returns: to... | 4 | stack_v2_sparse_classes_30k_train_001691 | Implement the Python class `ESPNETMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer. Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate.
Method signatures and docstrings:
- def __init__(self, n_feat, n_head, dropout): Construct an MultiHeadedAtt... | Implement the Python class `ESPNETMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer. Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate.
Method signatures and docstrings:
- def __init__(self, n_feat, n_head, dropout): Construct an MultiHeadedAtt... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class ESPNETMultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate."""
def __init__(self, n_feat, n_head, dropout):
"""Construct an MultiHeadedAttention object."""
<|body_0|>
def forward_qkv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ESPNETMultiHeadedAttention:
"""Multi-Head Attention layer. Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate."""
def __init__(self, n_feat, n_head, dropout):
"""Construct an MultiHeadedAttention object."""
super(ESPNETMultiHeadedAttention, self).__in... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/espnet_multihead_attention.py | microsoft/unilm | train | 15,313 |
ef47079f0d3fb71453f277831396e9718a4489d4 | [
"self.sample_size = sample_size\nself.vocab_size = None\nself.word_p = None\ncounts = collections.Counter()\nfor word_id in corpus:\n counts[word_id] += 1\nvocab_size = len(counts)\nself.vocab_size = vocab_size\nself.word_p = np.zeros(vocab_size)\nfor i in range(vocab_size):\n self.word_p[i] = counts[i]\nself... | <|body_start_0|>
self.sample_size = sample_size
self.vocab_size = None
self.word_p = None
counts = collections.Counter()
for word_id in corpus:
counts[word_id] += 1
vocab_size = len(counts)
self.vocab_size = vocab_size
self.word_p = np.zeros(vo... | nagative sampling을 할 때 확률분포에 따라 샘플링하게 해주는 클래스 | UnigramSampler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnigramSampler:
"""nagative sampling을 할 때 확률분포에 따라 샘플링하게 해주는 클래스"""
def __init__(self, corpus, power, sample_size):
"""1. corpus : 단어 ID목록(단어의 구분은 index로) 2. power : 확률 분포에 제곱할 값(낮은 확률의 단어를 구제하는 변수) 3. sample_size(self) : 샘플링을 수행할 단어수 4. vocab_size : 어휘 수 5. word_p(self) : 어휘별 확률분포(p... | stack_v2_sparse_classes_36k_train_030785 | 6,878 | no_license | [
{
"docstring": "1. corpus : 단어 ID목록(단어의 구분은 index로) 2. power : 확률 분포에 제곱할 값(낮은 확률의 단어를 구제하는 변수) 3. sample_size(self) : 샘플링을 수행할 단어수 4. vocab_size : 어휘 수 5. word_p(self) : 어휘별 확률분포(power적용)",
"name": "__init__",
"signature": "def __init__(self, corpus, power, sample_size)"
},
{
"docstring": "1. t... | 2 | stack_v2_sparse_classes_30k_train_018771 | Implement the Python class `UnigramSampler` described below.
Class description:
nagative sampling을 할 때 확률분포에 따라 샘플링하게 해주는 클래스
Method signatures and docstrings:
- def __init__(self, corpus, power, sample_size): 1. corpus : 단어 ID목록(단어의 구분은 index로) 2. power : 확률 분포에 제곱할 값(낮은 확률의 단어를 구제하는 변수) 3. sample_size(self) : 샘플링을 ... | Implement the Python class `UnigramSampler` described below.
Class description:
nagative sampling을 할 때 확률분포에 따라 샘플링하게 해주는 클래스
Method signatures and docstrings:
- def __init__(self, corpus, power, sample_size): 1. corpus : 단어 ID목록(단어의 구분은 index로) 2. power : 확률 분포에 제곱할 값(낮은 확률의 단어를 구제하는 변수) 3. sample_size(self) : 샘플링을 ... | a7a8d590fa13f53348f83f8c808538affbc7b3e8 | <|skeleton|>
class UnigramSampler:
"""nagative sampling을 할 때 확률분포에 따라 샘플링하게 해주는 클래스"""
def __init__(self, corpus, power, sample_size):
"""1. corpus : 단어 ID목록(단어의 구분은 index로) 2. power : 확률 분포에 제곱할 값(낮은 확률의 단어를 구제하는 변수) 3. sample_size(self) : 샘플링을 수행할 단어수 4. vocab_size : 어휘 수 5. word_p(self) : 어휘별 확률분포(p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnigramSampler:
"""nagative sampling을 할 때 확률분포에 따라 샘플링하게 해주는 클래스"""
def __init__(self, corpus, power, sample_size):
"""1. corpus : 단어 ID목록(단어의 구분은 index로) 2. power : 확률 분포에 제곱할 값(낮은 확률의 단어를 구제하는 변수) 3. sample_size(self) : 샘플링을 수행할 단어수 4. vocab_size : 어휘 수 5. word_p(self) : 어휘별 확률분포(power적용)"""
... | the_stack_v2_python_sparse | practice/deep-learning-from-scratch-2/common/negative_sampling_layer.py | heaven324/Deeplearning | train | 1 |
4218e899c58ff21aefc71adfab6b7216eda90cc8 | [
"self.ID = ID\nself.admin = admin\nself.name = name\nself.cord = (float(X), float(Y))\nself.check = check",
"k = 0.004\np = 0.5\nq = 0.5\nself.mass = 1\nreturn self.mass"
] | <|body_start_0|>
self.ID = ID
self.admin = admin
self.name = name
self.cord = (float(X), float(Y))
self.check = check
<|end_body_0|>
<|body_start_1|>
k = 0.004
p = 0.5
q = 0.5
self.mass = 1
return self.mass
<|end_body_1|>
| This class defines center village which creates center village instance. | Center_Village | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Center_Village:
"""This class defines center village which creates center village instance."""
def __init__(self, ID, admin, name: str, check, X, Y):
"""Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the n... | stack_v2_sparse_classes_36k_train_030786 | 7,338 | permissive | [
{
"docstring": "Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the name of village check -- mark whether a village is hollow or center X & Y -- geographical coordinates represented as a tuple type",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_005540 | Implement the Python class `Center_Village` described below.
Class description:
This class defines center village which creates center village instance.
Method signatures and docstrings:
- def __init__(self, ID, admin, name: str, check, X, Y): Meaning of arguments: ID -- object id admin -- the administrative village ... | Implement the Python class `Center_Village` described below.
Class description:
This class defines center village which creates center village instance.
Method signatures and docstrings:
- def __init__(self, ID, admin, name: str, check, X, Y): Meaning of arguments: ID -- object id admin -- the administrative village ... | 407d61b3583c472707a4e7b077a9a3ab12743996 | <|skeleton|>
class Center_Village:
"""This class defines center village which creates center village instance."""
def __init__(self, ID, admin, name: str, check, X, Y):
"""Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Center_Village:
"""This class defines center village which creates center village instance."""
def __init__(self, ID, admin, name: str, check, X, Y):
"""Meaning of arguments: ID -- object id admin -- the administrative village where this very instance village belongs to name -- the name of villag... | the_stack_v2_python_sparse | VillageMerger/village_new.py | spencerzhang91/coconuts-on-fire | train | 0 |
e315300a30b15850767f98f346ae3062864c903d | [
"from .tier_config_request import TierConfigRequest\nfrom connect.resources.base import ApiClient\nresponse, _ = ApiClient(config, base_path='tier/config-requests').get(params={'status': 'approved', 'configuration.product.id': product_id, 'configuration.account.id': account_id})\nobjects = TierConfigRequest.deseria... | <|body_start_0|>
from .tier_config_request import TierConfigRequest
from connect.resources.base import ApiClient
response, _ = ApiClient(config, base_path='tier/config-requests').get(params={'status': 'approved', 'configuration.product.id': product_id, 'configuration.account.id': account_id})
... | Full representation of Tier object. | TierConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TierConfig:
"""Full representation of Tier object."""
def get(cls, account_id, product_id, config=None):
"""Gets the specified tier config data. For example, to get Tier 1 configuration data for one request we can do: :: TierConfig.get(request.asset.tiers.tier1.id, request.asset.prod... | stack_v2_sparse_classes_36k_train_030787 | 3,868 | permissive | [
{
"docstring": "Gets the specified tier config data. For example, to get Tier 1 configuration data for one request we can do: :: TierConfig.get(request.asset.tiers.tier1.id, request.asset.product.id) :param str account_id: Account Id of the requested Tier Config (id with TA prefix). :param str product_id: Id of... | 2 | stack_v2_sparse_classes_30k_train_018944 | Implement the Python class `TierConfig` described below.
Class description:
Full representation of Tier object.
Method signatures and docstrings:
- def get(cls, account_id, product_id, config=None): Gets the specified tier config data. For example, to get Tier 1 configuration data for one request we can do: :: TierCo... | Implement the Python class `TierConfig` described below.
Class description:
Full representation of Tier object.
Method signatures and docstrings:
- def get(cls, account_id, product_id, config=None): Gets the specified tier config data. For example, to get Tier 1 configuration data for one request we can do: :: TierCo... | 656d653e4065637e2cc5768d7d554de17d0120eb | <|skeleton|>
class TierConfig:
"""Full representation of Tier object."""
def get(cls, account_id, product_id, config=None):
"""Gets the specified tier config data. For example, to get Tier 1 configuration data for one request we can do: :: TierConfig.get(request.asset.tiers.tier1.id, request.asset.prod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TierConfig:
"""Full representation of Tier object."""
def get(cls, account_id, product_id, config=None):
"""Gets the specified tier config data. For example, to get Tier 1 configuration data for one request we can do: :: TierConfig.get(request.asset.tiers.tier1.id, request.asset.product.id) :para... | the_stack_v2_python_sparse | connect/models/tier_config.py | cloudblue/connect-python-sdk | train | 13 |
48505463af0fc4fa9e477daae3a01830a30ac4e2 | [
"super().__init__(path)\nself._req_set = set()\nself._parse()",
"if self._req_set != other._req_set:\n print('GC request lists do not match.')\n return False\nelse:\n return True",
"with open(self._path, 'r') as file:\n try:\n line = file.readline()\n while line:\n if SENDIN... | <|body_start_0|>
super().__init__(path)
self._req_set = set()
self._parse()
<|end_body_0|>
<|body_start_1|>
if self._req_set != other._req_set:
print('GC request lists do not match.')
return False
else:
return True
<|end_body_1|>
<|body_start... | Responsible for parsing garbage collector logs | GarbageCollectorLogParser | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GarbageCollectorLogParser:
"""Responsible for parsing garbage collector logs"""
def __init__(self, path):
"""GarbageCollectorLogParser constructor @param path: The path to the garbage collector log file @type path: Str"""
<|body_0|>
def diff_log(self, other):
"""... | stack_v2_sparse_classes_36k_train_030788 | 9,641 | permissive | [
{
"docstring": "GarbageCollectorLogParser constructor @param path: The path to the garbage collector log file @type path: Str",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Diffs a GarbageCollectorLogParser's req list to this object's req list @param other: The ... | 3 | stack_v2_sparse_classes_30k_train_015504 | Implement the Python class `GarbageCollectorLogParser` described below.
Class description:
Responsible for parsing garbage collector logs
Method signatures and docstrings:
- def __init__(self, path): GarbageCollectorLogParser constructor @param path: The path to the garbage collector log file @type path: Str
- def di... | Implement the Python class `GarbageCollectorLogParser` described below.
Class description:
Responsible for parsing garbage collector logs
Method signatures and docstrings:
- def __init__(self, path): GarbageCollectorLogParser constructor @param path: The path to the garbage collector log file @type path: Str
- def di... | 5a9ba1af74953334fcf54570f1e31e74ea057688 | <|skeleton|>
class GarbageCollectorLogParser:
"""Responsible for parsing garbage collector logs"""
def __init__(self, path):
"""GarbageCollectorLogParser constructor @param path: The path to the garbage collector log file @type path: Str"""
<|body_0|>
def diff_log(self, other):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GarbageCollectorLogParser:
"""Responsible for parsing garbage collector logs"""
def __init__(self, path):
"""GarbageCollectorLogParser constructor @param path: The path to the garbage collector log file @type path: Str"""
super().__init__(path)
self._req_set = set()
self._... | the_stack_v2_python_sparse | restler/test_servers/log_parser.py | wisec/restler-fuzzer | train | 0 |
4cd8b858327553c6f121ce50b44ec1653d08e330 | [
"self.stdout.write('Re-assigining started', ending='\\n')\nif not args:\n raise CommandError('Param not set. <app model [created_perm]>')\nif len(args) < 3:\n raise CommandError('Param not set. <app model [created_perm]>')\napp = args[0]\nmodel = args[1]\nusername = args[2]\nnew_perms = list(args[3:])\nif use... | <|body_start_0|>
self.stdout.write('Re-assigining started', ending='\n')
if not args:
raise CommandError('Param not set. <app model [created_perm]>')
if len(args) < 3:
raise CommandError('Param not set. <app model [created_perm]>')
app = args[0]
model = ar... | Reassign permission to the model when permissions are changed | Command | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Reassign permission to the model when permissions are changed"""
def handle(self, *args, **options):
"""Reassign permission to the model when permissions are changed"""
<|body_0|>
def reassign_perms(self, user, app, model, new_perm):
"""Gets all the p... | stack_v2_sparse_classes_36k_train_030789 | 4,631 | permissive | [
{
"docstring": "Reassign permission to the model when permissions are changed",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Gets all the permissions the user has on objects and assigns the new permission to them :param user: :param app: :param model: :p... | 3 | stack_v2_sparse_classes_30k_train_020620 | Implement the Python class `Command` described below.
Class description:
Reassign permission to the model when permissions are changed
Method signatures and docstrings:
- def handle(self, *args, **options): Reassign permission to the model when permissions are changed
- def reassign_perms(self, user, app, model, new_... | Implement the Python class `Command` described below.
Class description:
Reassign permission to the model when permissions are changed
Method signatures and docstrings:
- def handle(self, *args, **options): Reassign permission to the model when permissions are changed
- def reassign_perms(self, user, app, model, new_... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class Command:
"""Reassign permission to the model when permissions are changed"""
def handle(self, *args, **options):
"""Reassign permission to the model when permissions are changed"""
<|body_0|>
def reassign_perms(self, user, app, model, new_perm):
"""Gets all the p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Reassign permission to the model when permissions are changed"""
def handle(self, *args, **options):
"""Reassign permission to the model when permissions are changed"""
self.stdout.write('Re-assigining started', ending='\n')
if not args:
raise CommandError(... | the_stack_v2_python_sparse | onadata/apps/api/management/commands/reassign_permission.py | onaio/onadata | train | 177 |
219c36926b4e80b33f1da567b30c7c7a912c09e6 | [
"self.data_description = data_description\nself.name = 'image_reshape'\nNI = self.data_description['NI']\nself.M = M\nself.N = N\nself.transf = transforms.Resize((self.M, self.N))",
"N = X.shape[0]\nNC = X.shape[1]\nX_t = np.zeros((N, NC, self.M, self.N))\nfor k in tqdm(range(N)):\n for kc in range(NC):\n ... | <|body_start_0|>
self.data_description = data_description
self.name = 'image_reshape'
NI = self.data_description['NI']
self.M = M
self.N = N
self.transf = transforms.Resize((self.M, self.N))
<|end_body_0|>
<|body_start_1|>
N = X.shape[0]
NC = X.shape[1]
... | This class represents the main object for reshaping images. | image_reshape_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class image_reshape_model:
"""This class represents the main object for reshaping images."""
def __init__(self, data_description, M, N):
"""Create an image_reshape_model instance. Parameters ---------- data_description: dict Description of the input features M: integer Target number of row... | stack_v2_sparse_classes_36k_train_030790 | 1,851 | permissive | [
{
"docstring": "Create an image_reshape_model instance. Parameters ---------- data_description: dict Description of the input features M: integer Target number of rows N: integer Target number of columns",
"name": "__init__",
"signature": "def __init__(self, data_description, M, N)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_002012 | Implement the Python class `image_reshape_model` described below.
Class description:
This class represents the main object for reshaping images.
Method signatures and docstrings:
- def __init__(self, data_description, M, N): Create an image_reshape_model instance. Parameters ---------- data_description: dict Descript... | Implement the Python class `image_reshape_model` described below.
Class description:
This class represents the main object for reshaping images.
Method signatures and docstrings:
- def __init__(self, data_description, M, N): Create an image_reshape_model instance. Parameters ---------- data_description: dict Descript... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class image_reshape_model:
"""This class represents the main object for reshaping images."""
def __init__(self, data_description, M, N):
"""Create an image_reshape_model instance. Parameters ---------- data_description: dict Description of the input features M: integer Target number of row... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class image_reshape_model:
"""This class represents the main object for reshaping images."""
def __init__(self, data_description, M, N):
"""Create an image_reshape_model instance. Parameters ---------- data_description: dict Description of the input features M: integer Target number of rows N: integer ... | the_stack_v2_python_sparse | MMLL/preprocessors/image_reshape.py | Musketeer-H2020/MMLL-Robust | train | 0 |
3342f222fda78504b78785b21f32d93d3a638e25 | [
"super(GuidedBackprop, self).__init__(graph, session, y, x)\ntensorflow = _import_tf()\ntf = tensorflow.compat.v1\nself.x = x\nif not GuidedBackprop.guided_relu_registered:\n\n @tf.RegisterGradient('GuidedRelu')\n def _GuidedReluGrad(op, grad):\n gate_g = tf.cast(grad > 0, 'float32')\n gate_y = ... | <|body_start_0|>
super(GuidedBackprop, self).__init__(graph, session, y, x)
tensorflow = _import_tf()
tf = tensorflow.compat.v1
self.x = x
if not GuidedBackprop.guided_relu_registered:
@tf.RegisterGradient('GuidedRelu')
def _GuidedReluGrad(op, grad):
... | A TF1Saliency class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 Thanks to Chris Olah for generously sharing his implementation of the ReLU backprop. | GuidedBackprop | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuidedBackprop:
"""A TF1Saliency class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 Thanks to Chris Olah for generously sharing his implementatio... | stack_v2_sparse_classes_36k_train_030791 | 3,213 | permissive | [
{
"docstring": "Constructs a GuidedBackprop method using TF1 Saliency.",
"name": "__init__",
"signature": "def __init__(self, graph, session, y, x, tmp_ckpt_path='/tmp/guided_backprop_ckpt')"
},
{
"docstring": "Returns a GuidedBackprop mask. Args: x_value: Input value, not batched. feed_dict: (O... | 2 | stack_v2_sparse_classes_30k_train_008534 | Implement the Python class `GuidedBackprop` described below.
Class description:
A TF1Saliency class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 Thanks to Chris Olah f... | Implement the Python class `GuidedBackprop` described below.
Class description:
A TF1Saliency class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 Thanks to Chris Olah f... | fc90418fadff32285620331e8c385cef852793a5 | <|skeleton|>
class GuidedBackprop:
"""A TF1Saliency class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 Thanks to Chris Olah for generously sharing his implementatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GuidedBackprop:
"""A TF1Saliency class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 Thanks to Chris Olah for generously sharing his implementation of the ReLU... | the_stack_v2_python_sparse | saliency/tf1/guided_backprop.py | Pandinosaurus/saliency | train | 1 |
7fe1fbff1b69d3afa2f8e5aa59c40a4581205ed5 | [
"images, kspaces = from_train_file_to_image_and_kspace(filename)\nimages = images[..., None]\nkspaces = kspaces[..., None]\nreturn (images, kspaces)",
"mask, kspaces = from_test_file_to_mask_and_kspace(filename)\nkspaces = kspaces[..., None]\nreturn (mask, kspaces)"
] | <|body_start_0|>
images, kspaces = from_train_file_to_image_and_kspace(filename)
images = images[..., None]
kspaces = kspaces[..., None]
return (images, kspaces)
<|end_body_0|>
<|body_start_1|>
mask, kspaces = from_test_file_to_mask_and_kspace(filename)
kspaces = kspaces... | Untouched2DSequence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Untouched2DSequence:
def get_item_train(self, filename):
"""Get the images and the kspaces of the volume at filename. Parameters: filename (str): the name of the h5 file containing the images and the kspaces Returns: tuple (ndarray, ndarray): the images and the kspaces corresponding to t... | stack_v2_sparse_classes_36k_train_030792 | 15,972 | permissive | [
{
"docstring": "Get the images and the kspaces of the volume at filename. Parameters: filename (str): the name of the h5 file containing the images and the kspaces Returns: tuple (ndarray, ndarray): the images and the kspaces corresponding to the volume in HWC format (i.e. with an extra dimension).",
"name"... | 2 | stack_v2_sparse_classes_30k_train_018471 | Implement the Python class `Untouched2DSequence` described below.
Class description:
Implement the Untouched2DSequence class.
Method signatures and docstrings:
- def get_item_train(self, filename): Get the images and the kspaces of the volume at filename. Parameters: filename (str): the name of the h5 file containing... | Implement the Python class `Untouched2DSequence` described below.
Class description:
Implement the Untouched2DSequence class.
Method signatures and docstrings:
- def get_item_train(self, filename): Get the images and the kspaces of the volume at filename. Parameters: filename (str): the name of the h5 file containing... | 4a4ec09524437d11153fc5a525621783689bed38 | <|skeleton|>
class Untouched2DSequence:
def get_item_train(self, filename):
"""Get the images and the kspaces of the volume at filename. Parameters: filename (str): the name of the h5 file containing the images and the kspaces Returns: tuple (ndarray, ndarray): the images and the kspaces corresponding to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Untouched2DSequence:
def get_item_train(self, filename):
"""Get the images and the kspaces of the volume at filename. Parameters: filename (str): the name of the h5 file containing the images and the kspaces Returns: tuple (ndarray, ndarray): the images and the kspaces corresponding to the volume in H... | the_stack_v2_python_sparse | fastmri_recon/data/sequences/fastmri_sequences.py | zaccharieramzi/fastmri-reproducible-benchmark | train | 147 | |
934b9e67364ce5164d6b5d4ad2ec60aacba0e50f | [
"position = []\nfor i, a in enumerate(A):\n if a == 1:\n position.append(i)\ntotal = 0\nif S == 0:\n if len(position) == 0:\n return sum([i + 1 for i in range(len(A))])\n for i in range(len(position)):\n between = position[i] - (position[i - 1] + 1 if i > 0 else 0)\n total += su... | <|body_start_0|>
position = []
for i, a in enumerate(A):
if a == 1:
position.append(i)
total = 0
if S == 0:
if len(position) == 0:
return sum([i + 1 for i in range(len(A))])
for i in range(len(position)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarraysWithSum(self, A, S):
""":type A: List[int] :type S: int :rtype: int 48 ms"""
<|body_0|>
def numSubarraysWithSum_1(self, A, S):
""":type A: List[int] :type S: int :rtype: int 44ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_030793 | 2,640 | no_license | [
{
"docstring": ":type A: List[int] :type S: int :rtype: int 48 ms",
"name": "numSubarraysWithSum",
"signature": "def numSubarraysWithSum(self, A, S)"
},
{
"docstring": ":type A: List[int] :type S: int :rtype: int 44ms",
"name": "numSubarraysWithSum_1",
"signature": "def numSubarraysWithS... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarraysWithSum(self, A, S): :type A: List[int] :type S: int :rtype: int 48 ms
- def numSubarraysWithSum_1(self, A, S): :type A: List[int] :type S: int :rtype: int 44ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarraysWithSum(self, A, S): :type A: List[int] :type S: int :rtype: int 48 ms
- def numSubarraysWithSum_1(self, A, S): :type A: List[int] :type S: int :rtype: int 44ms
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numSubarraysWithSum(self, A, S):
""":type A: List[int] :type S: int :rtype: int 48 ms"""
<|body_0|>
def numSubarraysWithSum_1(self, A, S):
""":type A: List[int] :type S: int :rtype: int 44ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarraysWithSum(self, A, S):
""":type A: List[int] :type S: int :rtype: int 48 ms"""
position = []
for i, a in enumerate(A):
if a == 1:
position.append(i)
total = 0
if S == 0:
if len(position) == 0:
... | the_stack_v2_python_sparse | BinarySubarraysWithSum_MID_930.py | 953250587/leetcode-python | train | 2 | |
7e5ebf1deea270e3abfb052d41ccdb09571cdf63 | [
"import paramiko\nprint('ssh_to_host %s@%s' % (username, hostname))\nk = paramiko.RSAKey.from_private_key_file(ssh_key)\nself.ssh_client = paramiko.SSHClient()\nself.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\ncounter = retry\nwhile counter > 0:\n try:\n self.ssh_client.connect(hostn... | <|body_start_0|>
import paramiko
print('ssh_to_host %s@%s' % (username, hostname))
k = paramiko.RSAKey.from_private_key_file(ssh_key)
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
counter = retry
while... | SshClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SshClient:
def __init__(self, hostname, ssh_key=None, username=None, retry=1):
"""Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full... | stack_v2_sparse_classes_36k_train_030794 | 32,544 | no_license | [
{
"docstring": "Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full path to the ssk hey to use to connect. username: username to connect with. returns SSH cl... | 3 | stack_v2_sparse_classes_30k_test_000927 | Implement the Python class `SshClient` described below.
Class description:
Implement the SshClient class.
Method signatures and docstrings:
- def __init__(self, hostname, ssh_key=None, username=None, retry=1): Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: ... | Implement the Python class `SshClient` described below.
Class description:
Implement the SshClient class.
Method signatures and docstrings:
- def __init__(self, hostname, ssh_key=None, username=None, retry=1): Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: ... | 2e316cf1def0b72b47f79a864ed3aa778c297b95 | <|skeleton|>
class SshClient:
def __init__(self, hostname, ssh_key=None, username=None, retry=1):
"""Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SshClient:
def __init__(self, hostname, ssh_key=None, username=None, retry=1):
"""Create ssh connection to host Creates and returns and ssh connection to the host passed in. Args: hostname: host name or ip address of the system to connect to. retry: number of time to retry. ssh_key: full path to the s... | the_stack_v2_python_sparse | util.py | bearpelican/cluster | train | 3 | |
9bfcbd5218623d123f45bd79352697db1d2b2f0f | [
"super().__init__()\nself.attention_layer = MultiHeadedSelfAttention(hidden_size, device, num_heads=num_heads, dropout_value=dropout_value)\nself.norm_layer = nn.LayerNorm(hidden_size)\nself.positionwise_feedforward = PositionwiseFeedforwardLayer(hidden_size, pf_dim, dropout_value)\nself.dropout = nn.Dropout(dropou... | <|body_start_0|>
super().__init__()
self.attention_layer = MultiHeadedSelfAttention(hidden_size, device, num_heads=num_heads, dropout_value=dropout_value)
self.norm_layer = nn.LayerNorm(hidden_size)
self.positionwise_feedforward = PositionwiseFeedforwardLayer(hidden_size, pf_dim, dropout... | EncoderLayer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderLayer:
def __init__(self, hidden_size: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device):
"""Constructs the EncoderLayer Parameters ---------- hidden_size : int The hidden size num_heads : int The number of heads in the self-attention layer pf_dim : int... | stack_v2_sparse_classes_36k_train_030795 | 5,240 | permissive | [
{
"docstring": "Constructs the EncoderLayer Parameters ---------- hidden_size : int The hidden size num_heads : int The number of heads in the self-attention layer pf_dim : int The dimension for the PositionwiseFeedforwardLayer dropout_value : float The dropout value device : torch.device The device to run the ... | 2 | stack_v2_sparse_classes_30k_train_009963 | Implement the Python class `EncoderLayer` described below.
Class description:
Implement the EncoderLayer class.
Method signatures and docstrings:
- def __init__(self, hidden_size: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device): Constructs the EncoderLayer Parameters ---------- hidden_si... | Implement the Python class `EncoderLayer` described below.
Class description:
Implement the EncoderLayer class.
Method signatures and docstrings:
- def __init__(self, hidden_size: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device): Constructs the EncoderLayer Parameters ---------- hidden_si... | da9cecce49498c4f79946a631206985f99daaed3 | <|skeleton|>
class EncoderLayer:
def __init__(self, hidden_size: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device):
"""Constructs the EncoderLayer Parameters ---------- hidden_size : int The hidden size num_heads : int The number of heads in the self-attention layer pf_dim : int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderLayer:
def __init__(self, hidden_size: int, num_heads: int, pf_dim: int, dropout_value: float, device: torch.device):
"""Constructs the EncoderLayer Parameters ---------- hidden_size : int The hidden size num_heads : int The number of heads in the self-attention layer pf_dim : int The dimension... | the_stack_v2_python_sparse | Translator/src/model/encoder.py | add54/Translator | train | 0 | |
b3f885bb006ad2ef704f42a1df903371175c905e | [
"self.email_address = email_address\nself.group = group\nself.mtype = mtype\nself.user_id = user_id",
"if dictionary is None:\n return None\nemail_address = dictionary.get('emailAddress')\ngroup = dictionary.get('group')\nmtype = dictionary.get('type')\nuser_id = dictionary.get('userId')\nreturn cls(email_addr... | <|body_start_0|>
self.email_address = email_address
self.group = group
self.mtype = mtype
self.user_id = user_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
email_address = dictionary.get('emailAddress')
group = dictionary.get('... | Implementation of the 'GranteeProto' model. TODO: type description here. Attributes: email_address (string): If grantee is of type 'kEmailUser', this field will contain the email address of the user. group (int): If grantee is of type 'kGroup', this field will contain the group to which permission is granted. mtype (in... | GranteeProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GranteeProto:
"""Implementation of the 'GranteeProto' model. TODO: type description here. Attributes: email_address (string): If grantee is of type 'kEmailUser', this field will contain the email address of the user. group (int): If grantee is of type 'kGroup', this field will contain the group t... | stack_v2_sparse_classes_36k_train_030796 | 2,150 | permissive | [
{
"docstring": "Constructor for the GranteeProto class",
"name": "__init__",
"signature": "def __init__(self, email_address=None, group=None, mtype=None, user_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representati... | 2 | null | Implement the Python class `GranteeProto` described below.
Class description:
Implementation of the 'GranteeProto' model. TODO: type description here. Attributes: email_address (string): If grantee is of type 'kEmailUser', this field will contain the email address of the user. group (int): If grantee is of type 'kGrou... | Implement the Python class `GranteeProto` described below.
Class description:
Implementation of the 'GranteeProto' model. TODO: type description here. Attributes: email_address (string): If grantee is of type 'kEmailUser', this field will contain the email address of the user. group (int): If grantee is of type 'kGrou... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GranteeProto:
"""Implementation of the 'GranteeProto' model. TODO: type description here. Attributes: email_address (string): If grantee is of type 'kEmailUser', this field will contain the email address of the user. group (int): If grantee is of type 'kGroup', this field will contain the group t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GranteeProto:
"""Implementation of the 'GranteeProto' model. TODO: type description here. Attributes: email_address (string): If grantee is of type 'kEmailUser', this field will contain the email address of the user. group (int): If grantee is of type 'kGroup', this field will contain the group to which permi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/grantee_proto.py | cohesity/management-sdk-python | train | 24 |
1cc5c99926c620117b5ad2a6171dfbec7027136d | [
"super().__init__()\nself._c_prob, self._d_prob = (c_prob, d_prob)\nself._init_c_prob, self._init_d_prob = (c_prob, d_prob)\nself._aspiration_level = abs(max(self.match_attributes['game'].RPST()) / aspiration_level_divider)\nself._stimulus = 0.0\nself._learning_rate = learning_rate",
"game = self.match_attributes... | <|body_start_0|>
super().__init__()
self._c_prob, self._d_prob = (c_prob, d_prob)
self._init_c_prob, self._init_d_prob = (c_prob, d_prob)
self._aspiration_level = abs(max(self.match_attributes['game'].RPST()) / aspiration_level_divider)
self._stimulus = 0.0
self._learning... | A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous play's payoff in the specified probability. ... | BushMosteller | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BushMosteller:
"""A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous pla... | stack_v2_sparse_classes_36k_train_030797 | 4,480 | permissive | [
{
"docstring": "Parameters c_prob: float, 0.5 Probability to play C , is modified during the match d_prob: float, 0.5 Probability to play D , is modified during the match aspiration_level_divider: float, 3.0 Value that regulates the aspiration level, isn't modified during match learning rate [0 , 1] Percentage ... | 3 | stack_v2_sparse_classes_30k_train_019583 | Implement the Python class `BushMosteller` described below.
Class description:
A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a ... | Implement the Python class `BushMosteller` described below.
Class description:
A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a ... | fa748627cd4f0333bb2dbfcb1454372a78a9098a | <|skeleton|>
class BushMosteller:
"""A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous pla... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BushMosteller:
"""A player that is based on Bush Mosteller reinforced learning algorithm, it decides what it will play only depending on its own previous payoffs. The probability of playing C or D will be updated using a stimulus which represents a win or a loss of value based on its previous play's payoff in... | the_stack_v2_python_sparse | axelrod/strategies/bush_mosteller.py | Axelrod-Python/Axelrod | train | 673 |
d34b6a9099a7057be8034369c4a9fbe02f51ad33 | [
"prefix_sum = 0\ncounts = [0] * k\nfor num in nums:\n prefix_sum += num\n counts[prefix_sum % k] += 1\nresult = counts[0]\nfor count in counts:\n result += count * (count - 1) // 2\nreturn result",
"prefix_sum = 0\nresult = 0\nkey_mapper = {0: 1}\nfor num in nums:\n prefix_sum += num\n key = prefix... | <|body_start_0|>
prefix_sum = 0
counts = [0] * k
for num in nums:
prefix_sum += num
counts[prefix_sum % k] += 1
result = counts[0]
for count in counts:
result += count * (count - 1) // 2
return result
<|end_body_0|>
<|body_start_1|>
... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def total_sub_array_sum_div_by_k_(self, nums: List[int], k: int) -> int:
"""Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(N) Formulae: nC2 = n (n - 1) / 2 :param nums: :param k: :return:"""
<|body_0|>
def total_sub_array_sum_div_by_k(self, nums: List[... | stack_v2_sparse_classes_36k_train_030798 | 1,536 | no_license | [
{
"docstring": "Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(N) Formulae: nC2 = n (n - 1) / 2 :param nums: :param k: :return:",
"name": "total_sub_array_sum_div_by_k_",
"signature": "def total_sub_array_sum_div_by_k_(self, nums: List[int], k: int) -> int"
},
{
"docstring": "App... | 2 | null | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def total_sub_array_sum_div_by_k_(self, nums: List[int], k: int) -> int: Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(N) Formulae: nC2 = n (n - 1) / 2 :param nums: :p... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def total_sub_array_sum_div_by_k_(self, nums: List[int], k: int) -> int: Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(N) Formulae: nC2 = n (n - 1) / 2 :param nums: :p... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def total_sub_array_sum_div_by_k_(self, nums: List[int], k: int) -> int:
"""Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(N) Formulae: nC2 = n (n - 1) / 2 :param nums: :param k: :return:"""
<|body_0|>
def total_sub_array_sum_div_by_k(self, nums: List[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Array:
def total_sub_array_sum_div_by_k_(self, nums: List[int], k: int) -> int:
"""Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(N) Formulae: nC2 = n (n - 1) / 2 :param nums: :param k: :return:"""
prefix_sum = 0
counts = [0] * k
for num in nums:
pre... | the_stack_v2_python_sparse | expedia/sub_array_sum_divisible_by_k.py | Shiv2157k/leet_code | train | 1 | |
73074b91866c70a8b72b7013d4d91a6c8b8297f6 | [
"parser.add_argument('appname', help='The sample app name, e.g. \"finance\".')\nparser.add_argument('--duration', default='1h', type=arg_parsers.Duration(), help='Duration of time allowed to run before stopping the workload.')\nparser.add_argument('--port', type=int, help='Port of the running backend service.')\npa... | <|body_start_0|>
parser.add_argument('appname', help='The sample app name, e.g. "finance".')
parser.add_argument('--duration', default='1h', type=arg_parsers.Duration(), help='Duration of time allowed to run before stopping the workload.')
parser.add_argument('--port', type=int, help='Port of th... | Generate gRPC traffic for a given sample app's backend service. Before sending traffic to the backend service, create the database and start the service with: $ {parent_command} init APPNAME --instance-id=INSTANCE_ID $ {parent_command} backend APPNAME --instance-id=INSTANCE_ID To run all three steps together, use: $ {p... | Workload | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workload:
"""Generate gRPC traffic for a given sample app's backend service. Before sending traffic to the backend service, create the database and start the service with: $ {parent_command} init APPNAME --instance-id=INSTANCE_ID $ {parent_command} backend APPNAME --instance-id=INSTANCE_ID To run... | stack_v2_sparse_classes_36k_train_030799 | 4,042 | permissive | [
{
"docstring": "Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_val_001086 | Implement the Python class `Workload` described below.
Class description:
Generate gRPC traffic for a given sample app's backend service. Before sending traffic to the backend service, create the database and start the service with: $ {parent_command} init APPNAME --instance-id=INSTANCE_ID $ {parent_command} backend A... | Implement the Python class `Workload` described below.
Class description:
Generate gRPC traffic for a given sample app's backend service. Before sending traffic to the backend service, create the database and start the service with: $ {parent_command} init APPNAME --instance-id=INSTANCE_ID $ {parent_command} backend A... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Workload:
"""Generate gRPC traffic for a given sample app's backend service. Before sending traffic to the backend service, create the database and start the service with: $ {parent_command} init APPNAME --instance-id=INSTANCE_ID $ {parent_command} backend APPNAME --instance-id=INSTANCE_ID To run... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Workload:
"""Generate gRPC traffic for a given sample app's backend service. Before sending traffic to the backend service, create the database and start the service with: $ {parent_command} init APPNAME --instance-id=INSTANCE_ID $ {parent_command} backend APPNAME --instance-id=INSTANCE_ID To run all three st... | the_stack_v2_python_sparse | lib/surface/spanner/samples/workload.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.