blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
191f5dfda5fea93e317215b3cab2ce5a93ef14d5 | [
"super(AppAllLogsConverter, self).__init__()\nlogger = logging.getLogger('AppAllLogsConverter')\nlogger.setLevel(logging.INFO)\nlogging.basicConfig()\nself.logger = logger\npass",
"self.logger.info('convert starts')\nst = time.time()\nall_usrs_all_in_one_log_path = glob.glob('%s/*/%s/%s' % (AllLogsConverter.json_... | <|body_start_0|>
super(AppAllLogsConverter, self).__init__()
logger = logging.getLogger('AppAllLogsConverter')
logger.setLevel(logging.INFO)
logging.basicConfig()
self.logger = logger
pass
<|end_body_0|>
<|body_start_1|>
self.logger.info('convert starts')
... | Convert all json file for each user to one coordinated file for each user. | AppAllLogsConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppAllLogsConverter:
"""Convert all json file for each user to one coordinated file for each user."""
def __init__(self, json_usrs_log_path=AllLogsConverter.json_usrs_log_path):
"""init - `filename`: filname created unser"""
<|body_0|>
def convert(self):
"""conve... | stack_v2_sparse_classes_75kplus_train_065300 | 3,343 | no_license | [
{
"docstring": "init - `filename`: filname created unser",
"name": "__init__",
"signature": "def __init__(self, json_usrs_log_path=AllLogsConverter.json_usrs_log_path)"
},
{
"docstring": "convert all of all-in-one log for each usrs to app log for each app Arguments:",
"name": "convert",
... | 3 | stack_v2_sparse_classes_30k_test_000389 | Implement the Python class `AppAllLogsConverter` described below.
Class description:
Convert all json file for each user to one coordinated file for each user.
Method signatures and docstrings:
- def __init__(self, json_usrs_log_path=AllLogsConverter.json_usrs_log_path): init - `filename`: filname created unser
- def... | Implement the Python class `AppAllLogsConverter` described below.
Class description:
Convert all json file for each user to one coordinated file for each user.
Method signatures and docstrings:
- def __init__(self, json_usrs_log_path=AllLogsConverter.json_usrs_log_path): init - `filename`: filname created unser
- def... | e3268f0f7ff4f5a4a68931e28c483184bbf8e926 | <|skeleton|>
class AppAllLogsConverter:
"""Convert all json file for each user to one coordinated file for each user."""
def __init__(self, json_usrs_log_path=AllLogsConverter.json_usrs_log_path):
"""init - `filename`: filname created unser"""
<|body_0|>
def convert(self):
"""conve... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppAllLogsConverter:
"""Convert all json file for each user to one coordinated file for each user."""
def __init__(self, json_usrs_log_path=AllLogsConverter.json_usrs_log_path):
"""init - `filename`: filname created unser"""
super(AppAllLogsConverter, self).__init__()
logger = log... | the_stack_v2_python_sparse | external_attachements/src/data_management/converter/app_all_logs_converter.py | khalilhajji/discovering_user_habbits_from_smartphone_logs | train | 0 |
350be941f0720ac139c61e422e69aafca0aee117 | [
"self.__subscriptions = []\nself.__publisher = None\nself.drop_policy = 'ignore'",
"try:\n if isinstance(subscription, Subscription):\n sub = Subscribe(subscription, self.__pool, self.myAddress)\n self.send(self.__pool, sub)\nexcept Exception:\n handle_actor_system_fail()",
"try:\n if isi... | <|body_start_0|>
self.__subscriptions = []
self.__publisher = None
self.drop_policy = 'ignore'
<|end_body_0|>
<|body_start_1|>
try:
if isinstance(subscription, Subscription):
sub = Subscribe(subscription, self.__pool, self.myAddress)
self.send... | Publisher. Publishes messages to subscribers. | Publisher | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Publisher:
"""Publisher. Publishes messages to subscribers."""
def __init__(self):
"""Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub"""
<|body_0|>
def subscribe(self, subscription):
"""Subscribe a subscripti... | stack_v2_sparse_classes_75kplus_train_065301 | 3,196 | permissive | [
{
"docstring": "Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Subscribe a subscription actor :param subscription: The subscription to use :type subscription: Subscr... | 6 | stack_v2_sparse_classes_30k_train_022861 | Implement the Python class `Publisher` described below.
Class description:
Publisher. Publishes messages to subscribers.
Method signatures and docstrings:
- def __init__(self): Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub
- def subscribe(self, subscription): S... | Implement the Python class `Publisher` described below.
Class description:
Publisher. Publishes messages to subscribers.
Method signatures and docstrings:
- def __init__(self): Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub
- def subscribe(self, subscription): S... | db93ea9acf58b0da12bcc78ab267e83f3c3c473b | <|skeleton|>
class Publisher:
"""Publisher. Publishes messages to subscribers."""
def __init__(self):
"""Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub"""
<|body_0|>
def subscribe(self, subscription):
"""Subscribe a subscripti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Publisher:
"""Publisher. Publishes messages to subscribers."""
def __init__(self):
"""Constructor :param router: The router to use. All extend PubSub which is default. :type router: PubSub"""
self.__subscriptions = []
self.__publisher = None
self.drop_policy = 'ignore'
... | the_stack_v2_python_sparse | reactive/streams/base_objects/publisher.py | xyicheng/ReactiveThespian | train | 0 |
9aadd019c468d65ce465426765c9058914338add | [
"super().__init__()\nself.velocity.dx = random.randint(1, 3)\nself.velocity.dy = random.randint(-2, 3)\nself.lives = 3",
"self.radius = 10\narcade.draw_circle_outline(self.center.x, self.center.y, self.radius, TARGET_COLOR)\ntext_x = self.center.x - self.radius / 2\ntext_y = self.center.y - self.radius / 2\narcad... | <|body_start_0|>
super().__init__()
self.velocity.dx = random.randint(1, 3)
self.velocity.dy = random.randint(-2, 3)
self.lives = 3
<|end_body_0|>
<|body_start_1|>
self.radius = 10
arcade.draw_circle_outline(self.center.x, self.center.y, self.radius, TARGET_COLOR)
... | The strong target takes 3 hits to destroy and awards 5 points upon being destroyed. Has a slower velocity than other targets Member Variables: (See Target class), lives(int) Methods: (See Target class), __init__(), draw(), hit() | StrongTarget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrongTarget:
"""The strong target takes 3 hits to destroy and awards 5 points upon being destroyed. Has a slower velocity than other targets Member Variables: (See Target class), lives(int) Methods: (See Target class), __init__(), draw(), hit()"""
def __init__(self):
"""Sets random ... | stack_v2_sparse_classes_75kplus_train_065302 | 15,127 | no_license | [
{
"docstring": "Sets random velocity for dx and dy and sets lives to 3",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Draws an outlines circle with the number of lives inside as text.",
"name": "draw",
"signature": "def draw(self)"
},
{
"docstring": "U... | 3 | stack_v2_sparse_classes_30k_train_044503 | Implement the Python class `StrongTarget` described below.
Class description:
The strong target takes 3 hits to destroy and awards 5 points upon being destroyed. Has a slower velocity than other targets Member Variables: (See Target class), lives(int) Methods: (See Target class), __init__(), draw(), hit()
Method sign... | Implement the Python class `StrongTarget` described below.
Class description:
The strong target takes 3 hits to destroy and awards 5 points upon being destroyed. Has a slower velocity than other targets Member Variables: (See Target class), lives(int) Methods: (See Target class), __init__(), draw(), hit()
Method sign... | c80d8bf80690c8fde5bd9639d072b7bfa1537c6c | <|skeleton|>
class StrongTarget:
"""The strong target takes 3 hits to destroy and awards 5 points upon being destroyed. Has a slower velocity than other targets Member Variables: (See Target class), lives(int) Methods: (See Target class), __init__(), draw(), hit()"""
def __init__(self):
"""Sets random ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StrongTarget:
"""The strong target takes 3 hits to destroy and awards 5 points upon being destroyed. Has a slower velocity than other targets Member Variables: (See Target class), lives(int) Methods: (See Target class), __init__(), draw(), hit()"""
def __init__(self):
"""Sets random velocity for ... | the_stack_v2_python_sparse | skeet/skeet.py | israeljgarcia/OOP-Data-Structures | train | 0 |
ef16fba0f02c4509ebc0d2daf8aa18f1d9a09001 | [
"if 'answers' not in validated_data:\n raise ParseError(detail='The quiz has no answers', code=None)\nanswers = validated_data.pop('answers')\nquiz = QuizQuestion(**validated_data)\nquiz.save()\ntry:\n if len(answers) != 4:\n raise ParseError(detail='Quiz must have 4 answers', code=None)\n for ans i... | <|body_start_0|>
if 'answers' not in validated_data:
raise ParseError(detail='The quiz has no answers', code=None)
answers = validated_data.pop('answers')
quiz = QuizQuestion(**validated_data)
quiz.save()
try:
if len(answers) != 4:
raise Pa... | Quiz Serializer for a single quiz question :author: Leonhard Wiedmann | QuizSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuizSerializer:
"""Quiz Serializer for a single quiz question :author: Leonhard Wiedmann"""
def create(self, validated_data):
"""method creating a Quiz object form a json input :param validated_data: validated json data for the object"""
<|body_0|>
def to_representation(... | stack_v2_sparse_classes_75kplus_train_065303 | 20,775 | no_license | [
{
"docstring": "method creating a Quiz object form a json input :param validated_data: validated json data for the object",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "representation of a Quiz object :author: Claas Voelcker :param obj: the user object to ... | 2 | stack_v2_sparse_classes_30k_test_001853 | Implement the Python class `QuizSerializer` described below.
Class description:
Quiz Serializer for a single quiz question :author: Leonhard Wiedmann
Method signatures and docstrings:
- def create(self, validated_data): method creating a Quiz object form a json input :param validated_data: validated json data for the... | Implement the Python class `QuizSerializer` described below.
Class description:
Quiz Serializer for a single quiz question :author: Leonhard Wiedmann
Method signatures and docstrings:
- def create(self, validated_data): method creating a Quiz object form a json input :param validated_data: validated json data for the... | 6fc102c6841449dd9782183b22340d1f1cb7c5c4 | <|skeleton|>
class QuizSerializer:
"""Quiz Serializer for a single quiz question :author: Leonhard Wiedmann"""
def create(self, validated_data):
"""method creating a Quiz object form a json input :param validated_data: validated json data for the object"""
<|body_0|>
def to_representation(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuizSerializer:
"""Quiz Serializer for a single quiz question :author: Leonhard Wiedmann"""
def create(self, validated_data):
"""method creating a Quiz object form a json input :param validated_data: validated json data for the object"""
if 'answers' not in validated_data:
rai... | the_stack_v2_python_sparse | django/learning_base/serializers.py | cvoelcker/clonecademy | train | 2 |
d027bccc583393b34fe541a3e6c79894ea27757b | [
"state, self.player = env_variables\nnum_rows, num_cols = (len(state[0]), len(state[0][0]))\nself.problem_manager = ConnectingGroupManager(env_variables=env_variables, num_to_connect=num_to_connect)\nself.square_types = self._create_initial_square_types(num_rows=num_rows, num_cols=num_cols)\nfor player in range(len... | <|body_start_0|>
state, self.player = env_variables
num_rows, num_cols = (len(state[0]), len(state[0][0]))
self.problem_manager = ConnectingGroupManager(env_variables=env_variables, num_to_connect=num_to_connect)
self.square_types = self._create_initial_square_types(num_rows=num_rows, nu... | SquareTypeManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SquareTypeManager:
def __init__(self, env_variables: TwoPlayerGameEnvVariables, num_to_connect: int):
"""Initializes the SquareTypeManager with the given env_variables. Args: env_variables (TwoPlayerGameEnvVariables): a TwoPlayerGame's env_variables."""
<|body_0|>
def _creat... | stack_v2_sparse_classes_75kplus_train_065304 | 7,072 | permissive | [
{
"docstring": "Initializes the SquareTypeManager with the given env_variables. Args: env_variables (TwoPlayerGameEnvVariables): a TwoPlayerGame's env_variables.",
"name": "__init__",
"signature": "def __init__(self, env_variables: TwoPlayerGameEnvVariables, num_to_connect: int)"
},
{
"docstring... | 6 | stack_v2_sparse_classes_30k_train_017387 | Implement the Python class `SquareTypeManager` described below.
Class description:
Implement the SquareTypeManager class.
Method signatures and docstrings:
- def __init__(self, env_variables: TwoPlayerGameEnvVariables, num_to_connect: int): Initializes the SquareTypeManager with the given env_variables. Args: env_var... | Implement the Python class `SquareTypeManager` described below.
Class description:
Implement the SquareTypeManager class.
Method signatures and docstrings:
- def __init__(self, env_variables: TwoPlayerGameEnvVariables, num_to_connect: int): Initializes the SquareTypeManager with the given env_variables. Args: env_var... | 6caf6965afaaff6883193ac295c6ac5b1f4e9c4a | <|skeleton|>
class SquareTypeManager:
def __init__(self, env_variables: TwoPlayerGameEnvVariables, num_to_connect: int):
"""Initializes the SquareTypeManager with the given env_variables. Args: env_variables (TwoPlayerGameEnvVariables): a TwoPlayerGame's env_variables."""
<|body_0|>
def _creat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SquareTypeManager:
def __init__(self, env_variables: TwoPlayerGameEnvVariables, num_to_connect: int):
"""Initializes the SquareTypeManager with the given env_variables. Args: env_variables (TwoPlayerGameEnvVariables): a TwoPlayerGame's env_variables."""
state, self.player = env_variables
... | the_stack_v2_python_sparse | connect_four/hashing/square_type_manager.py | rpachauri/connect4 | train | 0 | |
a8a3ac9f37c0e38c8014e2c9316a7b3033b47357 | [
"n, res = (len(nums1), 1)\ndp = [1, 1]\nfor i in range(1, n):\n ndp = [1, 1]\n for pre in range(2):\n preNums = nums1 if pre == 0 else nums2\n for cur in range(2):\n curNums = nums1 if cur == 0 else nums2\n if preNums[i - 1] <= curNums[i]:\n ndp[cur] = max(nd... | <|body_start_0|>
n, res = (len(nums1), 1)
dp = [1, 1]
for i in range(1, n):
ndp = [1, 1]
for pre in range(2):
preNums = nums1 if pre == 0 else nums2
for cur in range(2):
curNums = nums1 if cur == 0 else nums2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子数组`最长."""
<|body_0|>
def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子序列`最长->LIS."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_065305 | 1,361 | no_license | [
{
"docstring": "两个数组选数,使得最长非递减`子数组`最长.",
"name": "maxNonDecreasingLength",
"signature": "def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int"
},
{
"docstring": "两个数组选数,使得最长非递减`子序列`最长->LIS.",
"name": "maxNonDecreasingLength2",
"signature": "def maxNonDecreasingLeng... | 2 | stack_v2_sparse_classes_30k_train_011465 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: 两个数组选数,使得最长非递减`子数组`最长.
- def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: 两个数组选数,使得最长非递减`子数组`最长.
- def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子数组`最长."""
<|body_0|>
def maxNonDecreasingLength2(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子序列`最长->LIS."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int:
"""两个数组选数,使得最长非递减`子数组`最长."""
n, res = (len(nums1), 1)
dp = [1, 1]
for i in range(1, n):
ndp = [1, 1]
for pre in range(2):
preNums = nums1 if pre == 0 e... | the_stack_v2_python_sparse | 11_动态规划/lis最长上升子序列问题/6912. 构造最长非递减子数组.py | 981377660LMT/algorithm-study | train | 225 | |
8b03217edb2d1199fe7d74cc8eb36c3e3cc3166d | [
"K = self.kadane(A)\nCircleLength = 0\nfor i in range(len(A)):\n CircleLength += A[i]\n A[i] = -A[i]\nCircleLength += self.kadane(A)\nif K < CircleLength and CircleLength != 0:\n return CircleLength\nelse:\n return K",
"from sys import maxsize\nmax_ending_here = 0\nmax_so_far = -maxsize\nfor i in A:\n... | <|body_start_0|>
K = self.kadane(A)
CircleLength = 0
for i in range(len(A)):
CircleLength += A[i]
A[i] = -A[i]
CircleLength += self.kadane(A)
if K < CircleLength and CircleLength != 0:
return CircleLength
else:
return K
<|en... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubarraySumCircular(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def kadane(self, A):
"""Using max_ending_here to look for all positive contiguous segments of the array. Using max_so_far to keep track of maximum sum contiguous segment am... | stack_v2_sparse_classes_75kplus_train_065306 | 1,327 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int",
"name": "maxSubarraySumCircular",
"signature": "def maxSubarraySumCircular(self, A)"
},
{
"docstring": "Using max_ending_here to look for all positive contiguous segments of the array. Using max_so_far to keep track of maximum sum contiguous segme... | 2 | stack_v2_sparse_classes_30k_train_034531 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubarraySumCircular(self, A): :type A: List[int] :rtype: int
- def kadane(self, A): Using max_ending_here to look for all positive contiguous segments of the array. Using ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubarraySumCircular(self, A): :type A: List[int] :rtype: int
- def kadane(self, A): Using max_ending_here to look for all positive contiguous segments of the array. Using ... | 5de62902bee08a1b76259839dc797e305d1c3898 | <|skeleton|>
class Solution:
def maxSubarraySumCircular(self, A):
""":type A: List[int] :rtype: int"""
<|body_0|>
def kadane(self, A):
"""Using max_ending_here to look for all positive contiguous segments of the array. Using max_so_far to keep track of maximum sum contiguous segment am... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSubarraySumCircular(self, A):
""":type A: List[int] :rtype: int"""
K = self.kadane(A)
CircleLength = 0
for i in range(len(A)):
CircleLength += A[i]
A[i] = -A[i]
CircleLength += self.kadane(A)
if K < CircleLength and Circl... | the_stack_v2_python_sparse | 20200515_maxSubarraySumCircular.py | hanggun/leetcode | train | 0 | |
7a677b43a8d65181f43e11dfd842e3d33098647d | [
"with self.cached_session() as sess:\n\n @batch_ops.batch_function_v1(1, 10, 100000)\n def computation(in_t):\n return in_t + 1\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n result = computation(inp)\n thread_results = []\n\n def worker():\n thread_results.extend(ses... | <|body_start_0|>
with self.cached_session() as sess:
@batch_ops.batch_function_v1(1, 10, 100000)
def computation(in_t):
return in_t + 1
inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])
result = computation(inp)
thread_results... | Tests for batch_ops.{un,}batch. | BatchOpsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchOpsTest:
"""Tests for batch_ops.{un,}batch."""
def testBasicUnbatchV1Decorated(self):
"""Tests that the batch_function_v1 decorator works."""
<|body_0|>
def testUnbatchGrad(self):
"""Tests that batch and unbatch are differentiable."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus_train_065307 | 3,094 | permissive | [
{
"docstring": "Tests that the batch_function_v1 decorator works.",
"name": "testBasicUnbatchV1Decorated",
"signature": "def testBasicUnbatchV1Decorated(self)"
},
{
"docstring": "Tests that batch and unbatch are differentiable.",
"name": "testUnbatchGrad",
"signature": "def testUnbatchGr... | 2 | stack_v2_sparse_classes_30k_val_002651 | Implement the Python class `BatchOpsTest` described below.
Class description:
Tests for batch_ops.{un,}batch.
Method signatures and docstrings:
- def testBasicUnbatchV1Decorated(self): Tests that the batch_function_v1 decorator works.
- def testUnbatchGrad(self): Tests that batch and unbatch are differentiable. | Implement the Python class `BatchOpsTest` described below.
Class description:
Tests for batch_ops.{un,}batch.
Method signatures and docstrings:
- def testBasicUnbatchV1Decorated(self): Tests that the batch_function_v1 decorator works.
- def testUnbatchGrad(self): Tests that batch and unbatch are differentiable.
<|sk... | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | <|skeleton|>
class BatchOpsTest:
"""Tests for batch_ops.{un,}batch."""
def testBasicUnbatchV1Decorated(self):
"""Tests that the batch_function_v1 decorator works."""
<|body_0|>
def testUnbatchGrad(self):
"""Tests that batch and unbatch are differentiable."""
<|body_1|>
<|e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BatchOpsTest:
"""Tests for batch_ops.{un,}batch."""
def testBasicUnbatchV1Decorated(self):
"""Tests that the batch_function_v1 decorator works."""
with self.cached_session() as sess:
@batch_ops.batch_function_v1(1, 10, 100000)
def computation(in_t):
... | the_stack_v2_python_sparse | tensorflow/contrib/batching/python/ops/batch_ops_test.py | NVIDIA/tensorflow | train | 763 |
c3e988cbbea731cde9312159ed65ece510b11506 | [
"self.res = 0\nself.dfs(matrix, 0, n, 0)\nreturn self.res",
"if index == len(matrix) or rest_n <= 0:\n self.res = max(self.res, path)\n return\nself.dfs(matrix, index + 1, rest_n, path)\nfor j in range(rest_n):\n self.dfs(matrix, index + 1, rest_n - j - 1, path + matrix[index][j])"
] | <|body_start_0|>
self.res = 0
self.dfs(matrix, 0, n, 0)
return self.res
<|end_body_0|>
<|body_start_1|>
if index == len(matrix) or rest_n <= 0:
self.res = max(self.res, path)
return
self.dfs(matrix, index + 1, rest_n, path)
for j in range(rest_n):... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def func(self, matrix, n):
"""Args: matrix: list[list[int]] n: int Return: int"""
<|body_0|>
def dfs(self, matrix, index, rest_n, path):
"""Args: matrix: list[list[int]] index: int rest_n: int path: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_065308 | 938 | no_license | [
{
"docstring": "Args: matrix: list[list[int]] n: int Return: int",
"name": "func",
"signature": "def func(self, matrix, n)"
},
{
"docstring": "Args: matrix: list[list[int]] index: int rest_n: int path: int",
"name": "dfs",
"signature": "def dfs(self, matrix, index, rest_n, path)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, matrix, n): Args: matrix: list[list[int]] n: int Return: int
- def dfs(self, matrix, index, rest_n, path): Args: matrix: list[list[int]] index: int rest_n: int pat... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def func(self, matrix, n): Args: matrix: list[list[int]] n: int Return: int
- def dfs(self, matrix, index, rest_n, path): Args: matrix: list[list[int]] index: int rest_n: int pat... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def func(self, matrix, n):
"""Args: matrix: list[list[int]] n: int Return: int"""
<|body_0|>
def dfs(self, matrix, index, rest_n, path):
"""Args: matrix: list[list[int]] index: int rest_n: int path: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def func(self, matrix, n):
"""Args: matrix: list[list[int]] n: int Return: int"""
self.res = 0
self.dfs(matrix, 0, n, 0)
return self.res
def dfs(self, matrix, index, rest_n, path):
"""Args: matrix: list[list[int]] index: int rest_n: int path: int"""
... | the_stack_v2_python_sparse | 秋招/360/2/3.py | AiZhanghan/Leetcode | train | 0 | |
2904747960a0ee16dbd6271054ddbcfee599a5cd | [
"self.driver = driver\nself.comp_name = comp_name\nself.element = self.get_component()",
"try:\n return self.element.find_element_by_css_selector('table[name=\"' + self.comp_name + '\"] > thead > tr > th:nth-child(1)').text\nexcept Exception as ex:\n print('流程催办历史控件获取控件table head里第一个td的text值异常:%s' % ex)\n ... | <|body_start_0|>
self.driver = driver
self.comp_name = comp_name
self.element = self.get_component()
<|end_body_0|>
<|body_start_1|>
try:
return self.element.find_element_by_css_selector('table[name="' + self.comp_name + '"] > thead > tr > th:nth-child(1)').text
exce... | 流程催办历史控件手机端 | FlowRemindHistoryPhonePage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlowRemindHistoryPhonePage:
"""流程催办历史控件手机端"""
def __init__(self, driver, comp_name):
"""类初始化执行"""
<|body_0|>
def get_table_head_first_td_text(self):
"""获取控件table head里第一个td的text值"""
<|body_1|>
def get_table_tbody_first_td_text(self):
"""获取控件t... | stack_v2_sparse_classes_75kplus_train_065309 | 3,071 | no_license | [
{
"docstring": "类初始化执行",
"name": "__init__",
"signature": "def __init__(self, driver, comp_name)"
},
{
"docstring": "获取控件table head里第一个td的text值",
"name": "get_table_head_first_td_text",
"signature": "def get_table_head_first_td_text(self)"
},
{
"docstring": "获取控件table tbody里第一个td... | 3 | null | Implement the Python class `FlowRemindHistoryPhonePage` described below.
Class description:
流程催办历史控件手机端
Method signatures and docstrings:
- def __init__(self, driver, comp_name): 类初始化执行
- def get_table_head_first_td_text(self): 获取控件table head里第一个td的text值
- def get_table_tbody_first_td_text(self): 获取控件table tbody里第一个t... | Implement the Python class `FlowRemindHistoryPhonePage` described below.
Class description:
流程催办历史控件手机端
Method signatures and docstrings:
- def __init__(self, driver, comp_name): 类初始化执行
- def get_table_head_first_td_text(self): 获取控件table head里第一个td的text值
- def get_table_tbody_first_td_text(self): 获取控件table tbody里第一个t... | 78768989a79a14013b983024cf6e4838d51ed595 | <|skeleton|>
class FlowRemindHistoryPhonePage:
"""流程催办历史控件手机端"""
def __init__(self, driver, comp_name):
"""类初始化执行"""
<|body_0|>
def get_table_head_first_td_text(self):
"""获取控件table head里第一个td的text值"""
<|body_1|>
def get_table_tbody_first_td_text(self):
"""获取控件t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlowRemindHistoryPhonePage:
"""流程催办历史控件手机端"""
def __init__(self, driver, comp_name):
"""类初始化执行"""
self.driver = driver
self.comp_name = comp_name
self.element = self.get_component()
def get_table_head_first_td_text(self):
"""获取控件table head里第一个td的text值"""
... | the_stack_v2_python_sparse | test_case/page_obj/form/flow_remind_history_page.py | pylk/pythonSelenium | train | 0 |
8cf940d6a16f051f4a8695a0f8e7a462ecbf6074 | [
"if lr < 0.0:\n raise ValueError('Invalid Learning Rate')\nif momentum < 0:\n raise ValueError('Invalid momentum value')\nif epoch < 1:\n raise ValueError('Invalid epoch value')\nif cost < 0 or cost > 4:\n raise ValueError('Invalid cost value, it should be between 0 and 4')\nself.activation = activation... | <|body_start_0|>
if lr < 0.0:
raise ValueError('Invalid Learning Rate')
if momentum < 0:
raise ValueError('Invalid momentum value')
if epoch < 1:
raise ValueError('Invalid epoch value')
if cost < 0 or cost > 4:
raise ValueError('Invalid cos... | SGD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SGD:
def __init__(self, params, data, activation=0, lr=0.1, nesterov=False, momentum=0.2, epoch=50, cost=0, huber_point=0.0, quantile=0):
"""The following costs imply the following loss functions: 0 - Mean Squared Error 1 - Mean Absolute Error 2 - Huber Loss 3 - Log Cosh loss function 4 ... | stack_v2_sparse_classes_75kplus_train_065310 | 3,158 | no_license | [
{
"docstring": "The following costs imply the following loss functions: 0 - Mean Squared Error 1 - Mean Absolute Error 2 - Huber Loss 3 - Log Cosh loss function 4 - Quantile Error Ideally the epochs should be contained within a container class. This will make modifications lot easier, but this approach will do ... | 2 | stack_v2_sparse_classes_30k_train_029443 | Implement the Python class `SGD` described below.
Class description:
Implement the SGD class.
Method signatures and docstrings:
- def __init__(self, params, data, activation=0, lr=0.1, nesterov=False, momentum=0.2, epoch=50, cost=0, huber_point=0.0, quantile=0): The following costs imply the following loss functions:... | Implement the Python class `SGD` described below.
Class description:
Implement the SGD class.
Method signatures and docstrings:
- def __init__(self, params, data, activation=0, lr=0.1, nesterov=False, momentum=0.2, epoch=50, cost=0, huber_point=0.0, quantile=0): The following costs imply the following loss functions:... | 2f792760d9a67c76a5387e57aa8c5c7523a39658 | <|skeleton|>
class SGD:
def __init__(self, params, data, activation=0, lr=0.1, nesterov=False, momentum=0.2, epoch=50, cost=0, huber_point=0.0, quantile=0):
"""The following costs imply the following loss functions: 0 - Mean Squared Error 1 - Mean Absolute Error 2 - Huber Loss 3 - Log Cosh loss function 4 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SGD:
def __init__(self, params, data, activation=0, lr=0.1, nesterov=False, momentum=0.2, epoch=50, cost=0, huber_point=0.0, quantile=0):
"""The following costs imply the following loss functions: 0 - Mean Squared Error 1 - Mean Absolute Error 2 - Huber Loss 3 - Log Cosh loss function 4 - Quantile Err... | the_stack_v2_python_sparse | optim/sgd.py | Shivanshu17/ML-From-Scratch | train | 0 | |
d267fbb2880065bf54cb737b7a95791f39abb1ee | [
"self.q = []\nself.q2 = []\nself.tag = 1",
"if self.tag == 1:\n self.q.append(x)\nelse:\n self.q2.append(x)",
"if self.tag == 1:\n while len(self.q) > 1:\n t = self.q.pop(0)\n self.q2.append(t)\n self.tag = 2\n return self.q.pop(0)\nelse:\n while len(self.q2) > 1:\n t = se... | <|body_start_0|>
self.q = []
self.q2 = []
self.tag = 1
<|end_body_0|>
<|body_start_1|>
if self.tag == 1:
self.q.append(x)
else:
self.q2.append(x)
<|end_body_1|>
<|body_start_2|>
if self.tag == 1:
while len(self.q) > 1:
... | MyStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyStack:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def push(self, x):
"""Push element x onto stack. :type x: int :rtype: None"""
<|body_1|>
def pop(self):
"""Removes the element on top of the stack and returns that... | stack_v2_sparse_classes_75kplus_train_065311 | 1,852 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Push element x onto stack. :type x: int :rtype: None",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": "Removes the element on top of... | 5 | stack_v2_sparse_classes_30k_test_001988 | Implement the Python class `MyStack` described below.
Class description:
Implement the MyStack class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def push(self, x): Push element x onto stack. :type x: int :rtype: None
- def pop(self): Removes the element on top of th... | Implement the Python class `MyStack` described below.
Class description:
Implement the MyStack class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def push(self, x): Push element x onto stack. :type x: int :rtype: None
- def pop(self): Removes the element on top of th... | fd6c8082f81bcd9eda084b347c77fd570cfbee4a | <|skeleton|>
class MyStack:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def push(self, x):
"""Push element x onto stack. :type x: int :rtype: None"""
<|body_1|>
def pop(self):
"""Removes the element on top of the stack and returns that... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyStack:
def __init__(self):
"""Initialize your data structure here."""
self.q = []
self.q2 = []
self.tag = 1
def push(self, x):
"""Push element x onto stack. :type x: int :rtype: None"""
if self.tag == 1:
self.q.append(x)
else:
... | the_stack_v2_python_sparse | problems/225/test.py | neuxxm/leetcode | train | 0 | |
9e7d845f1105f7a97f8953a3a5b35c74fcf67d06 | [
"self._expression = expression\n\ndef function_wrapper(q, p):\n \"\"\" helper function for sympy differentiation\"\"\"\n return eval(self._expression)\nq, p = sym.symbols('q p', real=True)\ntry:\n self._derivative_q = str(sym.diff(function_wrapper(q, p), q))\n self._derivative_p = str(sym.diff(function_... | <|body_start_0|>
self._expression = expression
def function_wrapper(q, p):
""" helper function for sympy differentiation"""
return eval(self._expression)
q, p = sym.symbols('q p', real=True)
try:
self._derivative_q = str(sym.diff(function_wrapper(q, p... | Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array | Interaction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interaction:
"""Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array"""
def __init__(self, expression):
"""base interaction clas... | stack_v2_sparse_classes_75kplus_train_065312 | 4,161 | no_license | [
{
"docstring": "base interaction class that will call the expression Parameters ---------- expression : string the expression of the term for variable q and p which represents position and momentum respectively otherwise, eval would return error",
"name": "__init__",
"signature": "def __init__(self, exp... | 4 | stack_v2_sparse_classes_30k_test_001125 | Implement the Python class `Interaction` described below.
Class description:
Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array
Method signatures and docstrings... | Implement the Python class `Interaction` described below.
Class description:
Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array
Method signatures and docstrings... | fe939de84a8d8f3ad74c0f3172214e0304bff05f | <|skeleton|>
class Interaction:
"""Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array"""
def __init__(self, expression):
"""base interaction clas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Interaction:
"""Interaction base class between particles Common Parameters ----------------- q_state : np.array current state of the position of N X DIM array p_state : np.array current state of the momentum of N X DIM array"""
def __init__(self, expression):
"""base interaction class that will c... | the_stack_v2_python_sparse | hamiltonian/Interaction.py | simonjulianl/Langevin_Machine_Learning | train | 4 |
42a0b3a8a3fdf238898e0cd8b958c06e447c72cd | [
"args = parser.parse_args()\ntry:\n db.session.add(UserModel(username=args['username'], password=args['password']))\n db.session.commit()\n response = {'message': 'success'}\nexcept IntegrityError:\n db.session.rollback()\n response = {'message': f\"User {args['username']} already exists in database.... | <|body_start_0|>
args = parser.parse_args()
try:
db.session.add(UserModel(username=args['username'], password=args['password']))
db.session.commit()
response = {'message': 'success'}
except IntegrityError:
db.session.rollback()
response... | Users | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def post(self):
"""Create a user."""
<|body_0|>
def delete(self):
"""Deletes a user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = parser.parse_args()
try:
db.session.add(UserModel(username=args['username'], passw... | stack_v2_sparse_classes_75kplus_train_065313 | 2,132 | permissive | [
{
"docstring": "Create a user.",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Deletes a user.",
"name": "delete",
"signature": "def delete(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_035711 | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def post(self): Create a user.
- def delete(self): Deletes a user. | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def post(self): Create a user.
- def delete(self): Deletes a user.
<|skeleton|>
class Users:
def post(self):
"""Create a user."""
<|body_0|>
def delete(self)... | 4ddf5cd60d5e0e87e7641e97c9fbe78965c4b522 | <|skeleton|>
class Users:
def post(self):
"""Create a user."""
<|body_0|>
def delete(self):
"""Deletes a user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Users:
def post(self):
"""Create a user."""
args = parser.parse_args()
try:
db.session.add(UserModel(username=args['username'], password=args['password']))
db.session.commit()
response = {'message': 'success'}
except IntegrityError:
... | the_stack_v2_python_sparse | api/api/endpoints/user.py | andschneider/soil_sense | train | 0 | |
d4c2d75e0f6562f23c9124b614eba3304dd9977c | [
"if self.data is None:\n return {}\nreturn {'hosp': self.data['hosp'].values}",
"mean_y = self.mean_y(samples, **args)\nif args.get('forecast'):\n first = self.mean_y(samples, forecast=False)[:, -1, None]\nelse:\n first = np.nan\nreturn onp.diff(mean_y, axis=1, prepend=first)",
"dy_mean = self.dy_mean(... | <|body_start_0|>
if self.data is None:
return {}
return {'hosp': self.data['hosp'].values}
<|end_body_0|>
<|body_start_1|>
mean_y = self.mean_y(samples, **args)
if args.get('forecast'):
first = self.mean_y(samples, forecast=False)[:, -1, None]
else:
... | SEIHRBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEIHRBase:
def obs(self):
"""Provide extra arguments for observations Used during inference and forecasting"""
<|body_0|>
def dy_mean(self, samples, **args):
"""Daily confirmed cases mean"""
<|body_1|>
def dy(self, samples, noise_scale=0.4, **args):
... | stack_v2_sparse_classes_75kplus_train_065314 | 5,642 | permissive | [
{
"docstring": "Provide extra arguments for observations Used during inference and forecasting",
"name": "obs",
"signature": "def obs(self)"
},
{
"docstring": "Daily confirmed cases mean",
"name": "dy_mean",
"signature": "def dy_mean(self, samples, **args)"
},
{
"docstring": "Dai... | 3 | stack_v2_sparse_classes_30k_train_044485 | Implement the Python class `SEIHRBase` described below.
Class description:
Implement the SEIHRBase class.
Method signatures and docstrings:
- def obs(self): Provide extra arguments for observations Used during inference and forecasting
- def dy_mean(self, samples, **args): Daily confirmed cases mean
- def dy(self, sa... | Implement the Python class `SEIHRBase` described below.
Class description:
Implement the SEIHRBase class.
Method signatures and docstrings:
- def obs(self): Provide extra arguments for observations Used during inference and forecasting
- def dy_mean(self, samples, **args): Daily confirmed cases mean
- def dy(self, sa... | 1ee264d64ac81cf1f8a2bbcf24832541e1b7574d | <|skeleton|>
class SEIHRBase:
def obs(self):
"""Provide extra arguments for observations Used during inference and forecasting"""
<|body_0|>
def dy_mean(self, samples, **args):
"""Daily confirmed cases mean"""
<|body_1|>
def dy(self, samples, noise_scale=0.4, **args):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SEIHRBase:
def obs(self):
"""Provide extra arguments for observations Used during inference and forecasting"""
if self.data is None:
return {}
return {'hosp': self.data['hosp'].values}
def dy_mean(self, samples, **args):
"""Daily confirmed cases mean"""
... | the_stack_v2_python_sparse | covid/models/SEIHR.py | aleccrowell/covid | train | 0 | |
6b2c4143a80df5931e14f92675e9c4bdb2ab2741 | [
"super(TransformerLayer, self).__init__()\nself.attention = Attention(input_dim, head_dim, output_dim, head_num, dropout)\nself.layernorm1 = build_normalization('LN')(output_dim)\nself.dropout = dropout\nlayers = []\ndims = [output_dim] + [hidden_dim] * (mlp_num - 1) + [output_dim]\nfor i in range(mlp_num):\n la... | <|body_start_0|>
super(TransformerLayer, self).__init__()
self.attention = Attention(input_dim, head_dim, output_dim, head_num, dropout)
self.layernorm1 = build_normalization('LN')(output_dim)
self.dropout = dropout
layers = []
dims = [output_dim] + [hidden_dim] * (mlp_nu... | Overview: In transformer layer, first computes entries's attention and applies a feedforward layer | TransformerLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerLayer:
"""Overview: In transformer layer, first computes entries's attention and applies a feedforward layer"""
def __init__(self, input_dim: int, head_dim: int, hidden_dim: int, output_dim: int, head_num: int, mlp_num: int, dropout: nn.Module, activation: nn.Module) -> None:
... | stack_v2_sparse_classes_75kplus_train_065315 | 8,556 | permissive | [
{
"docstring": "Overview: Init transformer layer Arguments: - input_dim (:obj:`int`): dimension of input - head_dim (:obj:`int`): dimension of each head - hidden_dim (:obj:`int`): dimension of hidden layer in mlp - output_dim (:obj:`int`): dimension of output - head_num (:obj:`int`): number of heads for multihe... | 2 | stack_v2_sparse_classes_30k_train_041083 | Implement the Python class `TransformerLayer` described below.
Class description:
Overview: In transformer layer, first computes entries's attention and applies a feedforward layer
Method signatures and docstrings:
- def __init__(self, input_dim: int, head_dim: int, hidden_dim: int, output_dim: int, head_num: int, ml... | Implement the Python class `TransformerLayer` described below.
Class description:
Overview: In transformer layer, first computes entries's attention and applies a feedforward layer
Method signatures and docstrings:
- def __init__(self, input_dim: int, head_dim: int, hidden_dim: int, output_dim: int, head_num: int, ml... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class TransformerLayer:
"""Overview: In transformer layer, first computes entries's attention and applies a feedforward layer"""
def __init__(self, input_dim: int, head_dim: int, hidden_dim: int, output_dim: int, head_num: int, mlp_num: int, dropout: nn.Module, activation: nn.Module) -> None:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerLayer:
"""Overview: In transformer layer, first computes entries's attention and applies a feedforward layer"""
def __init__(self, input_dim: int, head_dim: int, hidden_dim: int, output_dim: int, head_num: int, mlp_num: int, dropout: nn.Module, activation: nn.Module) -> None:
"""Overvi... | the_stack_v2_python_sparse | ding/torch_utils/network/transformer.py | shengxuesun/DI-engine | train | 1 |
3d750237b6adfef47a16bcf0afec85f0100b1f50 | [
"super().__init__(pe, dbm)\nself.data_exports = []\nfor result in self._pipe_element.result_in:\n for export in result.data_exports:\n self.data_exports.append(export)",
"path_list = []\nfor export in self.data_exports:\n path_list.append(export.file_path)\nreturn path_list",
"d_list = []\nfor expo... | <|body_start_0|>
super().__init__(pe, dbm)
self.data_exports = []
for result in self._pipe_element.result_in:
for export in result.data_exports:
self.data_exports.append(export)
<|end_body_0|>
<|body_start_1|>
path_list = []
for export in self.data_ex... | DataExport | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataExport:
def __init__(self, pe, dbm):
"""Represents a DataExport element. Args: pe (object): :class:`lost.db.model.PipeElement` dbm (object): Database Management object. Note: Please note that a DataExport element can contain multiple exported files."""
<|body_0|>
def fil... | stack_v2_sparse_classes_75kplus_train_065316 | 8,022 | permissive | [
{
"docstring": "Represents a DataExport element. Args: pe (object): :class:`lost.db.model.PipeElement` dbm (object): Database Management object. Note: Please note that a DataExport element can contain multiple exported files.",
"name": "__init__",
"signature": "def __init__(self, pe, dbm)"
},
{
... | 3 | null | Implement the Python class `DataExport` described below.
Class description:
Implement the DataExport class.
Method signatures and docstrings:
- def __init__(self, pe, dbm): Represents a DataExport element. Args: pe (object): :class:`lost.db.model.PipeElement` dbm (object): Database Management object. Note: Please not... | Implement the Python class `DataExport` described below.
Class description:
Implement the DataExport class.
Method signatures and docstrings:
- def __init__(self, pe, dbm): Represents a DataExport element. Args: pe (object): :class:`lost.db.model.PipeElement` dbm (object): Database Management object. Note: Please not... | d4fc117bbe37d0843bf5e0b3675e7be2e96ea9c3 | <|skeleton|>
class DataExport:
def __init__(self, pe, dbm):
"""Represents a DataExport element. Args: pe (object): :class:`lost.db.model.PipeElement` dbm (object): Database Management object. Note: Please note that a DataExport element can contain multiple exported files."""
<|body_0|>
def fil... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataExport:
def __init__(self, pe, dbm):
"""Represents a DataExport element. Args: pe (object): :class:`lost.db.model.PipeElement` dbm (object): Database Management object. Note: Please note that a DataExport element can contain multiple exported files."""
super().__init__(pe, dbm)
sel... | the_stack_v2_python_sparse | backend/lost/pyapi/pipe_elements.py | l3p-cv/lost | train | 556 | |
a3abe0808af1e76c3bb1654e89787d8f9b8da60e | [
"if cache_root is None:\n cache_root = '/tmp/arclus/bert'\nself.precomputed_similarities, self.premise_representations = _load_or_compute_similarities(cache_root=cache_root, model_path=model_path, similarities_dir=similarities_dir, softmax=softmax, product=False, with_states=premise_representation == PremiseRepr... | <|body_start_0|>
if cache_root is None:
cache_root = '/tmp/arclus/bert'
self.precomputed_similarities, self.premise_representations = _load_or_compute_similarities(cache_root=cache_root, model_path=model_path, similarities_dir=similarities_dir, softmax=softmax, product=False, with_states=pre... | Base class for ranking methods based on learned similarity between claims and premises. | LearnedSimilarityBasedMethod | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearnedSimilarityBasedMethod:
"""Base class for ranking methods based on learned similarity between claims and premises."""
def __init__(self, softmax: bool, model_path: str, similarities_dir: str, cache_root: Optional[str]=None, premise_representation: PremiseRepresentationEnum=PremiseRepre... | stack_v2_sparse_classes_75kplus_train_065317 | 29,416 | permissive | [
{
"docstring": "Initialize the method. :param softmax: Whether to apply softmax on the scores for the pairwise similarity model. :param model_path: Directory where the fine-tuned bert similarity model checkpoint is located. :param cache_root: The directory where temporary BERT inference files are stored.",
... | 2 | stack_v2_sparse_classes_30k_train_017951 | Implement the Python class `LearnedSimilarityBasedMethod` described below.
Class description:
Base class for ranking methods based on learned similarity between claims and premises.
Method signatures and docstrings:
- def __init__(self, softmax: bool, model_path: str, similarities_dir: str, cache_root: Optional[str]=... | Implement the Python class `LearnedSimilarityBasedMethod` described below.
Class description:
Base class for ranking methods based on learned similarity between claims and premises.
Method signatures and docstrings:
- def __init__(self, softmax: bool, model_path: str, similarities_dir: str, cache_root: Optional[str]=... | bd810aa89ec55d492a38293f85b5c75d3c4d603b | <|skeleton|>
class LearnedSimilarityBasedMethod:
"""Base class for ranking methods based on learned similarity between claims and premises."""
def __init__(self, softmax: bool, model_path: str, similarities_dir: str, cache_root: Optional[str]=None, premise_representation: PremiseRepresentationEnum=PremiseRepre... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LearnedSimilarityBasedMethod:
"""Base class for ranking methods based on learned similarity between claims and premises."""
def __init__(self, softmax: bool, model_path: str, similarities_dir: str, cache_root: Optional[str]=None, premise_representation: PremiseRepresentationEnum=PremiseRepresentationEnum... | the_stack_v2_python_sparse | src/arclus/models/learned_similarity.py | cthoyt-forks-and-packages/ecir2021-am-search | train | 0 |
4f39b5a617dbc422eb7a36fedf89d9e3ddcd3c2c | [
"super().__init__()\nGatedGraphConv.global_count += 1\nself.name = name if name else 'GatedGraphConv_{}'.format(GatedGraphConv.global_count)\nself.output_channel_size = output_channels\nself.input_channel_size = input_channels\nself.num_nodes = num_nodes\nself.rnn = lbann.modules.ChannelwiseGRU(num_nodes, output_ch... | <|body_start_0|>
super().__init__()
GatedGraphConv.global_count += 1
self.name = name if name else 'GatedGraphConv_{}'.format(GatedGraphConv.global_count)
self.output_channel_size = output_channels
self.input_channel_size = input_channels
self.num_nodes = num_nodes
... | Gated Graph Convolution layer. For kernel details, see: https://arxiv.org/abs/1511.05493 Implementation in the spirit of: https://github.com/rusty1s/pytorch_geometric/blob/ master/torch_geometric/nn/conv/gated_graph_conv.py | GatedGraphConv | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GatedGraphConv:
"""Gated Graph Convolution layer. For kernel details, see: https://arxiv.org/abs/1511.05493 Implementation in the spirit of: https://github.com/rusty1s/pytorch_geometric/blob/ master/torch_geometric/nn/conv/gated_graph_conv.py"""
def __init__(self, input_channels, output_chan... | stack_v2_sparse_classes_75kplus_train_065318 | 3,883 | permissive | [
{
"docstring": "Initialize GatedGraph layer Args: input_channels (int): The size of the input node features output_channels (int): The output size of the node features num_nodes (int): Number of vertices in the graph num_layers (int): Number of passes through the GRU (default: 1) name (str): Name of the layers ... | 2 | null | Implement the Python class `GatedGraphConv` described below.
Class description:
Gated Graph Convolution layer. For kernel details, see: https://arxiv.org/abs/1511.05493 Implementation in the spirit of: https://github.com/rusty1s/pytorch_geometric/blob/ master/torch_geometric/nn/conv/gated_graph_conv.py
Method signatu... | Implement the Python class `GatedGraphConv` described below.
Class description:
Gated Graph Convolution layer. For kernel details, see: https://arxiv.org/abs/1511.05493 Implementation in the spirit of: https://github.com/rusty1s/pytorch_geometric/blob/ master/torch_geometric/nn/conv/gated_graph_conv.py
Method signatu... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class GatedGraphConv:
"""Gated Graph Convolution layer. For kernel details, see: https://arxiv.org/abs/1511.05493 Implementation in the spirit of: https://github.com/rusty1s/pytorch_geometric/blob/ master/torch_geometric/nn/conv/gated_graph_conv.py"""
def __init__(self, input_channels, output_chan... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GatedGraphConv:
"""Gated Graph Convolution layer. For kernel details, see: https://arxiv.org/abs/1511.05493 Implementation in the spirit of: https://github.com/rusty1s/pytorch_geometric/blob/ master/torch_geometric/nn/conv/gated_graph_conv.py"""
def __init__(self, input_channels, output_channels, num_nod... | the_stack_v2_python_sparse | python/lbann/modules/graph/sparse/GatedGraphConv.py | LLNL/lbann | train | 225 |
d32bed55295035141333b179478f099bac7aaefe | [
"Compilation.__init__(self, sandbox)\nsource_file = tempfile.mktemp(suffix='.py', prefix='elif_code_')\nself.exec_file = self.sandbox.mktemp(prefix='exec_', suffix='.pyc')\nwith open(source_file, 'w') as f:\n f.write(code)\ntry:\n py_compile.compile(source_file, self.exec_file, doraise=True)\n self.return_... | <|body_start_0|>
Compilation.__init__(self, sandbox)
source_file = tempfile.mktemp(suffix='.py', prefix='elif_code_')
self.exec_file = self.sandbox.mktemp(prefix='exec_', suffix='.pyc')
with open(source_file, 'w') as f:
f.write(code)
try:
py_compile.compil... | PythonCompilation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PythonCompilation:
def __init__(self, sandbox, code):
"""Compiles the code Parameters: - code must be encoded in UTF8"""
<|body_0|>
def run(self, params=list(), stdin=None):
"""Runs the code in the sandbox and return its process's feedback"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus_train_065319 | 4,057 | no_license | [
{
"docstring": "Compiles the code Parameters: - code must be encoded in UTF8",
"name": "__init__",
"signature": "def __init__(self, sandbox, code)"
},
{
"docstring": "Runs the code in the sandbox and return its process's feedback",
"name": "run",
"signature": "def run(self, params=list()... | 2 | stack_v2_sparse_classes_30k_train_007073 | Implement the Python class `PythonCompilation` described below.
Class description:
Implement the PythonCompilation class.
Method signatures and docstrings:
- def __init__(self, sandbox, code): Compiles the code Parameters: - code must be encoded in UTF8
- def run(self, params=list(), stdin=None): Runs the code in the... | Implement the Python class `PythonCompilation` described below.
Class description:
Implement the PythonCompilation class.
Method signatures and docstrings:
- def __init__(self, sandbox, code): Compiles the code Parameters: - code must be encoded in UTF8
- def run(self, params=list(), stdin=None): Runs the code in the... | d20e5f1ee1a9ac7b4fd50b23c58016af5cd91178 | <|skeleton|>
class PythonCompilation:
def __init__(self, sandbox, code):
"""Compiles the code Parameters: - code must be encoded in UTF8"""
<|body_0|>
def run(self, params=list(), stdin=None):
"""Runs the code in the sandbox and return its process's feedback"""
<|body_1|>
<|en... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PythonCompilation:
def __init__(self, sandbox, code):
"""Compiles the code Parameters: - code must be encoded in UTF8"""
Compilation.__init__(self, sandbox)
source_file = tempfile.mktemp(suffix='.py', prefix='elif_code_')
self.exec_file = self.sandbox.mktemp(prefix='exec_', suf... | the_stack_v2_python_sparse | src/compilation.py | INSA-4IF-SpecIFic/elif | train | 0 | |
e2eaa97178da69bfb79d5d11dbd118223968cc9e | [
"try:\n grant = Grant.objects.get(pk=pk)\n serializer = GrantsSerializer(grant, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"by_wish = self.request.query_params.get('by_wish')\nrelevant_wish = self.request.user.id\nif... | <|body_start_0|>
try:
grant = Grant.objects.get(pk=pk)
serializer = GrantsSerializer(grant, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end_body_0|>
<|body_start_1|>
b... | Grants | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grants:
def retrieve(self, request, pk=None):
"""Handle GET requests for single grants Returns: Response -- JSON serialized grants instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to grants resource Returns: Response -- JSON serialized list of g... | stack_v2_sparse_classes_75kplus_train_065320 | 4,447 | no_license | [
{
"docstring": "Handle GET requests for single grants Returns: Response -- JSON serialized grants instance",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to grants resource Returns: Response -- JSON serialized list of grants",
... | 6 | stack_v2_sparse_classes_30k_train_041860 | Implement the Python class `Grants` described below.
Class description:
Implement the Grants class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single grants Returns: Response -- JSON serialized grants instance
- def list(self, request): Handle GET requests to gra... | Implement the Python class `Grants` described below.
Class description:
Implement the Grants class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single grants Returns: Response -- JSON serialized grants instance
- def list(self, request): Handle GET requests to gra... | 582048dafa7e354fffdc0478ec68088e8bbf42b1 | <|skeleton|>
class Grants:
def retrieve(self, request, pk=None):
"""Handle GET requests for single grants Returns: Response -- JSON serialized grants instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to grants resource Returns: Response -- JSON serialized list of g... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Grants:
def retrieve(self, request, pk=None):
"""Handle GET requests for single grants Returns: Response -- JSON serialized grants instance"""
try:
grant = Grant.objects.get(pk=pk)
serializer = GrantsSerializer(grant, context={'request': request})
return Res... | the_stack_v2_python_sparse | genieioapp/views/grants.py | cherkesky/GenieIO | train | 1 | |
75f986562bc7adb0043500c82eb52498ed6c439a | [
"self.msg_id = error_info['msg_id']\nself.level = error_info['loglevel']\nself.msg = error_info['msg']\nself.suffix = error_info['suffix']",
"msg = self.msg % kwargs\nif storage_id:\n LOG.log(self.level, '%(storage_id)s MSGID%(msg_id)04d-%(msg_suffix)s: %(msg)s', {'storage_id': storage_id[-6:], 'msg_id': self.... | <|body_start_0|>
self.msg_id = error_info['msg_id']
self.level = error_info['loglevel']
self.msg = error_info['msg']
self.suffix = error_info['suffix']
<|end_body_0|>
<|body_start_1|>
msg = self.msg % kwargs
if storage_id:
LOG.log(self.level, '%(storage_id)s ... | messages for Hitachi HBSD Driver. | HBSDMsg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HBSDMsg:
"""messages for Hitachi HBSD Driver."""
def __init__(self, error_info):
"""Initialize Enum attributes."""
<|body_0|>
def output_log(self, storage_id, **kwargs):
"""Output the message to the log file and return the message."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus_train_065321 | 29,040 | permissive | [
{
"docstring": "Initialize Enum attributes.",
"name": "__init__",
"signature": "def __init__(self, error_info)"
},
{
"docstring": "Output the message to the log file and return the message.",
"name": "output_log",
"signature": "def output_log(self, storage_id, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024758 | Implement the Python class `HBSDMsg` described below.
Class description:
messages for Hitachi HBSD Driver.
Method signatures and docstrings:
- def __init__(self, error_info): Initialize Enum attributes.
- def output_log(self, storage_id, **kwargs): Output the message to the log file and return the message. | Implement the Python class `HBSDMsg` described below.
Class description:
messages for Hitachi HBSD Driver.
Method signatures and docstrings:
- def __init__(self, error_info): Initialize Enum attributes.
- def output_log(self, storage_id, **kwargs): Output the message to the log file and return the message.
<|skeleto... | 04a5d6b8c28271f6aefe2bbae6a1e16c1c235835 | <|skeleton|>
class HBSDMsg:
"""messages for Hitachi HBSD Driver."""
def __init__(self, error_info):
"""Initialize Enum attributes."""
<|body_0|>
def output_log(self, storage_id, **kwargs):
"""Output the message to the log file and return the message."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HBSDMsg:
"""messages for Hitachi HBSD Driver."""
def __init__(self, error_info):
"""Initialize Enum attributes."""
self.msg_id = error_info['msg_id']
self.level = error_info['loglevel']
self.msg = error_info['msg']
self.suffix = error_info['suffix']
def output... | the_stack_v2_python_sparse | cinder/volume/drivers/hitachi/hbsd_utils.py | LINBIT/openstack-cinder | train | 9 |
85c92667f174749c2d68e710f2fce59dc1338007 | [
"self.plugin = OpticalFlow()\nrain = np.ones((3, 3))\nself.rain_mask = np.where(rain > 0)",
"greater_than_10_percent_zeroes_array = np.array([[3.0, 5.0, 7.0], [0.0, 2.0, 1.0], [1.0, 1.0, 1.0]])\nwarning_msg = 'cells within the domain have zero advection'\nwith pytest.warns(UserWarning, match=warning_msg):\n se... | <|body_start_0|>
self.plugin = OpticalFlow()
rain = np.ones((3, 3))
self.rain_mask = np.where(rain > 0)
<|end_body_0|>
<|body_start_1|>
greater_than_10_percent_zeroes_array = np.array([[3.0, 5.0, 7.0], [0.0, 2.0, 1.0], [1.0, 1.0, 1.0]])
warning_msg = 'cells within the domain hav... | Test the _zero_advection_velocities_warning. | Test__zero_advection_velocities_warning | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__zero_advection_velocities_warning:
"""Test the _zero_advection_velocities_warning."""
def setUp(self):
"""Set up arrays of advection velocities"""
<|body_0|>
def test_warning_raised(self):
"""Test that a warning is raised if an excess number of zero values ... | stack_v2_sparse_classes_75kplus_train_065322 | 37,677 | permissive | [
{
"docstring": "Set up arrays of advection velocities",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that a warning is raised if an excess number of zero values are present within the input array.",
"name": "test_warning_raised",
"signature": "def test_warning_... | 6 | null | Implement the Python class `Test__zero_advection_velocities_warning` described below.
Class description:
Test the _zero_advection_velocities_warning.
Method signatures and docstrings:
- def setUp(self): Set up arrays of advection velocities
- def test_warning_raised(self): Test that a warning is raised if an excess n... | Implement the Python class `Test__zero_advection_velocities_warning` described below.
Class description:
Test the _zero_advection_velocities_warning.
Method signatures and docstrings:
- def setUp(self): Set up arrays of advection velocities
- def test_warning_raised(self): Test that a warning is raised if an excess n... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__zero_advection_velocities_warning:
"""Test the _zero_advection_velocities_warning."""
def setUp(self):
"""Set up arrays of advection velocities"""
<|body_0|>
def test_warning_raised(self):
"""Test that a warning is raised if an excess number of zero values ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__zero_advection_velocities_warning:
"""Test the _zero_advection_velocities_warning."""
def setUp(self):
"""Set up arrays of advection velocities"""
self.plugin = OpticalFlow()
rain = np.ones((3, 3))
self.rain_mask = np.where(rain > 0)
def test_warning_raised(self... | the_stack_v2_python_sparse | improver_tests/nowcasting/optical_flow/test_OpticalFlow.py | metoppv/improver | train | 101 |
5bb8cdfa78315be53d1982702c1364c72f18cf35 | [
"base.Widget.__init__(self)\nself._spacing = spacing\nself._columns = columns",
"base.Widget.render(self, width)\nx = 0\nfor col_width, col in self._columns:\n self.setxy(0, x)\n if col_width is None:\n col_max_width = width - self.cursor[1]\n col_width = 0\n else:\n col_max_width = ... | <|body_start_0|>
base.Widget.__init__(self)
self._spacing = spacing
self._columns = columns
<|end_body_0|>
<|body_start_1|>
base.Widget.render(self, width)
x = 0
for col_width, col in self._columns:
self.setxy(0, x)
if col_width is None:
... | ColumnWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnWidget:
def __init__(self, columns, spacing=0):
"""Create text columns :param columns: list containing (column width, [list of widgets to put into this column]) :type columns: [(int, [...]), ...] :param spacing: number of spaces to use between columns :type spacing: int"""
... | stack_v2_sparse_classes_75kplus_train_065323 | 7,653 | no_license | [
{
"docstring": "Create text columns :param columns: list containing (column width, [list of widgets to put into this column]) :type columns: [(int, [...]), ...] :param spacing: number of spaces to use between columns :type spacing: int",
"name": "__init__",
"signature": "def __init__(self, columns, spac... | 2 | stack_v2_sparse_classes_30k_test_002529 | Implement the Python class `ColumnWidget` described below.
Class description:
Implement the ColumnWidget class.
Method signatures and docstrings:
- def __init__(self, columns, spacing=0): Create text columns :param columns: list containing (column width, [list of widgets to put into this column]) :type columns: [(int... | Implement the Python class `ColumnWidget` described below.
Class description:
Implement the ColumnWidget class.
Method signatures and docstrings:
- def __init__(self, columns, spacing=0): Create text columns :param columns: list containing (column width, [list of widgets to put into this column]) :type columns: [(int... | 6976d7e1d8af45b1432cbf4f1461076ca04349e0 | <|skeleton|>
class ColumnWidget:
def __init__(self, columns, spacing=0):
"""Create text columns :param columns: list containing (column width, [list of widgets to put into this column]) :type columns: [(int, [...]), ...] :param spacing: number of spaces to use between columns :type spacing: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColumnWidget:
def __init__(self, columns, spacing=0):
"""Create text columns :param columns: list containing (column width, [list of widgets to put into this column]) :type columns: [(int, [...]), ...] :param spacing: number of spaces to use between columns :type spacing: int"""
base.Widget.__... | the_stack_v2_python_sparse | rootfs/usr/lib64/python2.7/site-packages/pyanaconda/ui/tui/simpleline/widgets.py | outstanding-mjy/make_rootfs | train | 0 | |
e63926a3cb50c9549a2ec2f9d11c968a89d51b2f | [
"request = kwargs['request']\npool = request.app.state.writepool\nawait dbfunc(pool, 'create_item', item)\nreturn item",
"request = kwargs['request']\npool = request.app.state.writepool\nawait dbfunc(pool, 'update_item', item)\nreturn item",
"request = kwargs['request']\npool = request.app.state.writepool\nawai... | <|body_start_0|>
request = kwargs['request']
pool = request.app.state.writepool
await dbfunc(pool, 'create_item', item)
return item
<|end_body_0|>
<|body_start_1|>
request = kwargs['request']
pool = request.app.state.writepool
await dbfunc(pool, 'update_item', it... | Transactions extension specific CRUD operations. | TransactionsClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionsClient:
"""Transactions extension specific CRUD operations."""
async def create_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item:
"""Create item."""
<|body_0|>
async def update_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item:
... | stack_v2_sparse_classes_75kplus_train_065324 | 2,167 | permissive | [
{
"docstring": "Create item.",
"name": "create_item",
"signature": "async def create_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item"
},
{
"docstring": "Update item.",
"name": "update_item",
"signature": "async def update_item(self, item: stac_types.Item, **kwargs) -> stac... | 6 | stack_v2_sparse_classes_30k_train_012703 | Implement the Python class `TransactionsClient` described below.
Class description:
Transactions extension specific CRUD operations.
Method signatures and docstrings:
- async def create_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item: Create item.
- async def update_item(self, item: stac_types.Item, **... | Implement the Python class `TransactionsClient` described below.
Class description:
Transactions extension specific CRUD operations.
Method signatures and docstrings:
- async def create_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item: Create item.
- async def update_item(self, item: stac_types.Item, **... | 3219b65a850926b622197ee6a7c3f5fb07c0d5cf | <|skeleton|>
class TransactionsClient:
"""Transactions extension specific CRUD operations."""
async def create_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item:
"""Create item."""
<|body_0|>
async def update_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransactionsClient:
"""Transactions extension specific CRUD operations."""
async def create_item(self, item: stac_types.Item, **kwargs) -> stac_types.Item:
"""Create item."""
request = kwargs['request']
pool = request.app.state.writepool
await dbfunc(pool, 'create_item', i... | the_stack_v2_python_sparse | stac_fastapi/pgstac/stac_fastapi/pgstac/transactions.py | cuulee/stac-fastapi | train | 0 |
c2d4a009b3d1c2f35f4a7ca4178e15a89d0ebb5b | [
"todo = Todo.objects.create(description='be a good man', done=False)\nurl = reverse('todo:index')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\nself.assertContains(response, todo.description)",
"todo = Todo.objects.create(description='be a good son', done=False)\nreverse('todo:don... | <|body_start_0|>
todo = Todo.objects.create(description='be a good man', done=False)
url = reverse('todo:index')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, todo.description)
<|end_body_0|>
<|body_start_1|>
to... | TodoTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TodoTests:
def test_if_todo_in_index(self):
"""test if todo which is created is already in index page."""
<|body_0|>
def test_if_no_todo_in_index(self):
"""test if no todo which already done."""
<|body_1|>
def test_if_redirect_to_index(self):
"""... | stack_v2_sparse_classes_75kplus_train_065325 | 1,601 | no_license | [
{
"docstring": "test if todo which is created is already in index page.",
"name": "test_if_todo_in_index",
"signature": "def test_if_todo_in_index(self)"
},
{
"docstring": "test if no todo which already done.",
"name": "test_if_no_todo_in_index",
"signature": "def test_if_no_todo_in_inde... | 4 | null | Implement the Python class `TodoTests` described below.
Class description:
Implement the TodoTests class.
Method signatures and docstrings:
- def test_if_todo_in_index(self): test if todo which is created is already in index page.
- def test_if_no_todo_in_index(self): test if no todo which already done.
- def test_if... | Implement the Python class `TodoTests` described below.
Class description:
Implement the TodoTests class.
Method signatures and docstrings:
- def test_if_todo_in_index(self): test if todo which is created is already in index page.
- def test_if_no_todo_in_index(self): test if no todo which already done.
- def test_if... | 92f40466c6ffa2b432b672327205d6b87c39591f | <|skeleton|>
class TodoTests:
def test_if_todo_in_index(self):
"""test if todo which is created is already in index page."""
<|body_0|>
def test_if_no_todo_in_index(self):
"""test if no todo which already done."""
<|body_1|>
def test_if_redirect_to_index(self):
"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TodoTests:
def test_if_todo_in_index(self):
"""test if todo which is created is already in index page."""
todo = Todo.objects.create(description='be a good man', done=False)
url = reverse('todo:index')
response = self.client.get(url)
self.assertEqual(response.status_cod... | the_stack_v2_python_sparse | labexam2-Noboomta/todo/tests.py | Noboomta/ISP-SKE-KU-2020 | train | 0 | |
48b4e75b53c36217b319de28103a3ade9799f768 | [
"import os\nfrom MDSplus import Uint32\ndebug = os.getenv('DEBUG_DEVICES')\ntry:\n host = str(self.node.record.data())\nexcept:\n host = 'local'\nif Data.execute('mdsconnect($)', host) == 0:\n raise Exception('Error connecting to host: ' + host)\nboard = int(self.board.record)\nfor i in range(4):\n do_n... | <|body_start_0|>
import os
from MDSplus import Uint32
debug = os.getenv('DEBUG_DEVICES')
try:
host = str(self.node.record.data())
except:
host = 'local'
if Data.execute('mdsconnect($)', host) == 0:
raise Exception('Error connecting to h... | Adlink CP7452 DIO | CP7452 | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CP7452:
"""Adlink CP7452 DIO"""
def init(self):
"""Initialize digital outputs of CP7452 cpci board. Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output."""
<|body_0|>
def store(self):
"""Stores th... | stack_v2_sparse_classes_75kplus_train_065326 | 5,266 | permissive | [
{
"docstring": "Initialize digital outputs of CP7452 cpci board. Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output.",
"name": "init",
"signature": "def init(self)"
},
{
"docstring": "Stores the digital input values into the tre... | 2 | stack_v2_sparse_classes_30k_train_048782 | Implement the Python class `CP7452` described below.
Class description:
Adlink CP7452 DIO
Method signatures and docstrings:
- def init(self): Initialize digital outputs of CP7452 cpci board. Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output.
- def s... | Implement the Python class `CP7452` described below.
Class description:
Adlink CP7452 DIO
Method signatures and docstrings:
- def init(self): Initialize digital outputs of CP7452 cpci board. Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output.
- def s... | 9cb20ed47249576d100a5e395028605a220e6146 | <|skeleton|>
class CP7452:
"""Adlink CP7452 DIO"""
def init(self):
"""Initialize digital outputs of CP7452 cpci board. Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output."""
<|body_0|>
def store(self):
"""Stores th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CP7452:
"""Adlink CP7452 DIO"""
def init(self):
"""Initialize digital outputs of CP7452 cpci board. Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output."""
import os
from MDSplus import Uint32
debug = os.ge... | the_stack_v2_python_sparse | pydevices/MitDevices/cp7452.py | MDSplus/mdsplus | train | 61 |
9c93000f2cf108359a31f1888174a54168173ed5 | [
"super().__init__(start_endpoint, status_endpoint, runtime_endpoint, result_endpoint)\nself.status: AnalyzerRuntimeInfo = AnalyzerRuntimeInfo(progress=0, is_finished=False)\nself.result = None\nself.is_finished = False",
"data = json.dumps({'path': in_file.path})\nresponse_status_code = requests.post(self.start_e... | <|body_start_0|>
super().__init__(start_endpoint, status_endpoint, runtime_endpoint, result_endpoint)
self.status: AnalyzerRuntimeInfo = AnalyzerRuntimeInfo(progress=0, is_finished=False)
self.result = None
self.is_finished = False
<|end_body_0|>
<|body_start_1|>
data = json.dum... | AnalyzerHttpExecutor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyzerHttpExecutor:
def __init__(self, start_endpoint: str, status_endpoint: str, runtime_endpoint: str, result_endpoint: str):
"""Creates http executor for SIMBAD-ANALYZER :param start_endpoint: formatted string representing request endpoint :param status_endpoint: formatted string re... | stack_v2_sparse_classes_75kplus_train_065327 | 3,071 | no_license | [
{
"docstring": "Creates http executor for SIMBAD-ANALYZER :param start_endpoint: formatted string representing request endpoint :param status_endpoint: formatted string representing status endpoint",
"name": "__init__",
"signature": "def __init__(self, start_endpoint: str, status_endpoint: str, runtime_... | 4 | stack_v2_sparse_classes_30k_train_013520 | Implement the Python class `AnalyzerHttpExecutor` described below.
Class description:
Implement the AnalyzerHttpExecutor class.
Method signatures and docstrings:
- def __init__(self, start_endpoint: str, status_endpoint: str, runtime_endpoint: str, result_endpoint: str): Creates http executor for SIMBAD-ANALYZER :par... | Implement the Python class `AnalyzerHttpExecutor` described below.
Class description:
Implement the AnalyzerHttpExecutor class.
Method signatures and docstrings:
- def __init__(self, start_endpoint: str, status_endpoint: str, runtime_endpoint: str, result_endpoint: str): Creates http executor for SIMBAD-ANALYZER :par... | 15e208c99221cc0e1d8482ae549802856f8254a4 | <|skeleton|>
class AnalyzerHttpExecutor:
def __init__(self, start_endpoint: str, status_endpoint: str, runtime_endpoint: str, result_endpoint: str):
"""Creates http executor for SIMBAD-ANALYZER :param start_endpoint: formatted string representing request endpoint :param status_endpoint: formatted string re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AnalyzerHttpExecutor:
def __init__(self, start_endpoint: str, status_endpoint: str, runtime_endpoint: str, result_endpoint: str):
"""Creates http executor for SIMBAD-ANALYZER :param start_endpoint: formatted string representing request endpoint :param status_endpoint: formatted string representing sta... | the_stack_v2_python_sparse | src/server/pipeline/analyzer/analyzer_http_executor.py | biel-wro/simbad-pipeline-server | train | 0 | |
d8af31a9b93ae2105cee8fac2f9837f4640f559c | [
"self.capacity = capacity\nself.stacks = []\nself.q = []",
"while self.q and self.q[0] < len(self.stacks) and (len(self.stacks[self.q[0]]) == self.capacity):\n heapq.heappop(self.q)\nif not self.q:\n heapq.heappush(self.q, len(self.stacks))\nif self.q[0] == len(self.stacks):\n self.stacks.append([])\nsel... | <|body_start_0|>
self.capacity = capacity
self.stacks = []
self.q = []
<|end_body_0|>
<|body_start_1|>
while self.q and self.q[0] < len(self.stacks) and (len(self.stacks[self.q[0]]) == self.capacity):
heapq.heappop(self.q)
if not self.q:
heapq.heappush(se... | DinnerPlates | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def push(self, val):
""":type val: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def popAtStack(self, index):
""":t... | stack_v2_sparse_classes_75kplus_train_065328 | 1,958 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type val: int :rtype: None",
"name": "push",
"signature": "def push(self, val)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def pop(... | 4 | stack_v2_sparse_classes_30k_train_023554 | Implement the Python class `DinnerPlates` described below.
Class description:
Implement the DinnerPlates class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def push(self, val): :type val: int :rtype: None
- def pop(self): :rtype: int
- def popAtStack(self, index): :type ind... | Implement the Python class `DinnerPlates` described below.
Class description:
Implement the DinnerPlates class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def push(self, val): :type val: int :rtype: None
- def pop(self): :rtype: int
- def popAtStack(self, index): :type ind... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def push(self, val):
""":type val: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def popAtStack(self, index):
""":t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DinnerPlates:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.stacks = []
self.q = []
def push(self, val):
""":type val: int :rtype: None"""
while self.q and self.q[0] < len(self.stacks) and (len(self.stacks[self.q[0]])... | the_stack_v2_python_sparse | 字节/餐盘栈.py | 2226171237/Algorithmpractice | train | 0 | |
821ced1924541beac87d68d2066ca75365cf22ed | [
"a1, a2 = ([], [])\nwhile l1:\n a1.append(l1.val)\n l1 = l1.next\nwhile l2:\n a2.append(l2.val)\n l2 = l2.next\ns1 = ''\nfor i in range(len(a1) - 1, -1, -1):\n s1 = s1 + str(a1[i])\ns2 = ''\nfor j in range(len(a2) - 1, -1, -1):\n s2 = s2 + str(a2[j])\nm1, m2 = (int(s1), int(s2))\nm3 = str(m1 + m2)... | <|body_start_0|>
a1, a2 = ([], [])
while l1:
a1.append(l1.val)
l1 = l1.next
while l2:
a2.append(l2.val)
l2 = l2.next
s1 = ''
for i in range(len(a1) - 1, -1, -1):
s1 = s1 + str(a1[i])
s2 = ''
for j in rang... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""正向思维,根据题意直推法,先将两个链表转换成列表形式 为了计算两个链表之和,将列表转成字符串形式,再将字符串转成 int型 此时计算出和,因为最后返回的是链表形式,所以计算出和之后,将和值转为字符串 然后再从后往前遍历字符串,并插入空链表,最后可返回结果链表 地址:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-ji... | stack_v2_sparse_classes_75kplus_train_065329 | 7,511 | no_license | [
{
"docstring": "正向思维,根据题意直推法,先将两个链表转换成列表形式 为了计算两个链表之和,将列表转成字符串形式,再将字符串转成 int型 此时计算出和,因为最后返回的是链表形式,所以计算出和之后,将和值转为字符串 然后再从后往前遍历字符串,并插入空链表,最后可返回结果链表 地址:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-xing-yun-de-bei-ji-lang/ # 注意此思路没问题,结果有问题。。。。 :param l1: :param l2: :return:",
... | 3 | stack_v2_sparse_classes_30k_train_028227 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode: 正向思维,根据题意直推法,先将两个链表转换成列表形式 为了计算两个链表之和,将列表转成字符串形式,再将字符串转成 int型 此时计算出和,因为最后返回的是链表形式,所以计算出和之后,将和值转为字符串 然后再从后往前遍历字符串... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode: 正向思维,根据题意直推法,先将两个链表转换成列表形式 为了计算两个链表之和,将列表转成字符串形式,再将字符串转成 int型 此时计算出和,因为最后返回的是链表形式,所以计算出和之后,将和值转为字符串 然后再从后往前遍历字符串... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""正向思维,根据题意直推法,先将两个链表转换成列表形式 为了计算两个链表之和,将列表转成字符串形式,再将字符串转成 int型 此时计算出和,因为最后返回的是链表形式,所以计算出和之后,将和值转为字符串 然后再从后往前遍历字符串,并插入空链表,最后可返回结果链表 地址:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-ji... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def addTwoNumbers1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""正向思维,根据题意直推法,先将两个链表转换成列表形式 为了计算两个链表之和,将列表转成字符串形式,再将字符串转成 int型 此时计算出和,因为最后返回的是链表形式,所以计算出和之后,将和值转为字符串 然后再从后往前遍历字符串,并插入空链表,最后可返回结果链表 地址:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-by-xing-yun-... | the_stack_v2_python_sparse | LeetCode_practice/LinkedList/0002_AddTwoNumbers.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
5930fd36e7c7047adc771d88c1acf4f90821ef6c | [
"self.dic = collections.defaultdict(set)\nfor s in dictionary:\n val = s\n if len(s) > 2:\n s = s[0] + str(len(s) - 2) + s[-1]\n self.dic[s].add(val)",
"val = word\nif len(word) > 2:\n word = word[0] + str(len(word) - 2) + word[-1]\nreturn len(self.dic[word]) == 0 or (len(self.dic[word]) == 1 a... | <|body_start_0|>
self.dic = collections.defaultdict(set)
for s in dictionary:
val = s
if len(s) > 2:
s = s[0] + str(len(s) - 2) + s[-1]
self.dic[s].add(val)
<|end_body_0|>
<|body_start_1|>
val = word
if len(word) > 2:
word ... | ValidWordAbbr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str] beats 45.93%"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dic = collections.defaultdict(set... | stack_v2_sparse_classes_75kplus_train_065330 | 1,017 | no_license | [
{
"docstring": ":type dictionary: List[str] beats 45.93%",
"name": "__init__",
"signature": "def __init__(self, dictionary)"
},
{
"docstring": ":type word: str :rtype: bool",
"name": "isUnique",
"signature": "def isUnique(self, word)"
}
] | 2 | null | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str] beats 45.93%
- def isUnique(self, word): :type word: str :rtype: bool | Implement the Python class `ValidWordAbbr` described below.
Class description:
Implement the ValidWordAbbr class.
Method signatures and docstrings:
- def __init__(self, dictionary): :type dictionary: List[str] beats 45.93%
- def isUnique(self, word): :type word: str :rtype: bool
<|skeleton|>
class ValidWordAbbr:
... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str] beats 45.93%"""
<|body_0|>
def isUnique(self, word):
""":type word: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValidWordAbbr:
def __init__(self, dictionary):
""":type dictionary: List[str] beats 45.93%"""
self.dic = collections.defaultdict(set)
for s in dictionary:
val = s
if len(s) > 2:
s = s[0] + str(len(s) - 2) + s[-1]
self.dic[s].add(val)
... | the_stack_v2_python_sparse | LeetCode/288_unique_word_abbreviation.py | yao23/Machine_Learning_Playground | train | 12 | |
f560ac4f2fc88f9b0b84e2036443d6b19c5cbbe9 | [
"queryset = queryset or self.get_queryset()\nurl = self.kwargs.get('url')\nfor flatpage in queryset.filter(slug=url.split('/')[-1]):\n if flatpage.get_absolute_url().strip('/') == url:\n obj = flatpage\n break\nelse:\n raise Http404\nreturn obj",
"template_names = []\nif self.object.template_n... | <|body_start_0|>
queryset = queryset or self.get_queryset()
url = self.kwargs.get('url')
for flatpage in queryset.filter(slug=url.split('/')[-1]):
if flatpage.get_absolute_url().strip('/') == url:
obj = flatpage
break
else:
raise Ht... | View for static pages. | FlatPageView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlatPageView:
"""View for static pages."""
def get_object(self, queryset=None):
"""Returns the flatpage instance. Raises Http404 if inexistent."""
<|body_0|>
def get_template_names(self):
"""Returns the template names for the view as list. The name 'flatpage_defa... | stack_v2_sparse_classes_75kplus_train_065331 | 3,724 | permissive | [
{
"docstring": "Returns the flatpage instance. Raises Http404 if inexistent.",
"name": "get_object",
"signature": "def get_object(self, queryset=None)"
},
{
"docstring": "Returns the template names for the view as list. The name 'flatpage_default.html' is always appended.",
"name": "get_temp... | 3 | stack_v2_sparse_classes_30k_train_045600 | Implement the Python class `FlatPageView` described below.
Class description:
View for static pages.
Method signatures and docstrings:
- def get_object(self, queryset=None): Returns the flatpage instance. Raises Http404 if inexistent.
- def get_template_names(self): Returns the template names for the view as list. Th... | Implement the Python class `FlatPageView` described below.
Class description:
View for static pages.
Method signatures and docstrings:
- def get_object(self, queryset=None): Returns the flatpage instance. Raises Http404 if inexistent.
- def get_template_names(self): Returns the template names for the view as list. Th... | 6b77451881031dcb640d2e61ce862617d634f9ac | <|skeleton|>
class FlatPageView:
"""View for static pages."""
def get_object(self, queryset=None):
"""Returns the flatpage instance. Raises Http404 if inexistent."""
<|body_0|>
def get_template_names(self):
"""Returns the template names for the view as list. The name 'flatpage_defa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FlatPageView:
"""View for static pages."""
def get_object(self, queryset=None):
"""Returns the flatpage instance. Raises Http404 if inexistent."""
queryset = queryset or self.get_queryset()
url = self.kwargs.get('url')
for flatpage in queryset.filter(slug=url.split('/')[-1... | the_stack_v2_python_sparse | esg_leipzig_homepage_2015/views.py | ESG-Leipzig/Homepage-2015 | train | 0 |
1456f0a454731e47776e98d47bcd2c7403dbd3a0 | [
"protos = []\nif not isinstance(x, Iterable):\n protos.append(x.proto_with_data)\nelse:\n protos = [r.proto_with_data for r in x]\nreturn jina_pb2.DataRequestListProto(requests=protos).SerializeToString()",
"rlp = jina_pb2.DataRequestListProto()\nrlp.ParseFromString(x)\nreturn [DataRequest.from_proto(reques... | <|body_start_0|>
protos = []
if not isinstance(x, Iterable):
protos.append(x.proto_with_data)
else:
protos = [r.proto_with_data for r in x]
return jina_pb2.DataRequestListProto(requests=protos).SerializeToString()
<|end_body_0|>
<|body_start_1|>
rlp = jin... | This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is hiding MessageListProto from the consumer | DataRequestListProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataRequestListProto:
"""This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is h... | stack_v2_sparse_classes_75kplus_train_065332 | 7,917 | permissive | [
{
"docstring": "# noqa: DAR101 # noqa: DAR102 # noqa: DAR201",
"name": "SerializeToString",
"signature": "def SerializeToString(x: 'Union[List[DataRequest], DataRequest]')"
},
{
"docstring": "# noqa: DAR101 # noqa: DAR102 # noqa: DAR201",
"name": "FromString",
"signature": "def FromStrin... | 2 | stack_v2_sparse_classes_30k_train_048562 | Implement the Python class `DataRequestListProto` described below.
Class description:
This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a ... | Implement the Python class `DataRequestListProto` described below.
Class description:
This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a ... | 23c7b8c78fc4ad67d16d83fc0c9f0eae9e935e71 | <|skeleton|>
class DataRequestListProto:
"""This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is h... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataRequestListProto:
"""This class is a drop-in replacement for gRPC default serializer. It replaces default serializer to make sure the message sending interface is convenient. It can handle sending single messages or a list of messages. It also returns a list of messages. Effectively this is hiding Message... | the_stack_v2_python_sparse | jina/proto/serializer.py | jina-ai/jina | train | 20,687 |
148efd57ea6fada2e1ec016d1823b1bd614d6efe | [
"headers = {'Content-type': 'application/json', 'sense_key': self.sense_key}\nurl = 'api.sen.se'\nres = None\ntry:\n conn = httplib.HTTPConnection(url, timeout=8)\n conn.request('POST', '/events/', json.dumps(self.events), headers)\n response = conn.getresponse()\n res = response.reason\nexcept:\n pa... | <|body_start_0|>
headers = {'Content-type': 'application/json', 'sense_key': self.sense_key}
url = 'api.sen.se'
res = None
try:
conn = httplib.HTTPConnection(url, timeout=8)
conn.request('POST', '/events/', json.dumps(self.events), headers)
response = ... | Generic open.sen.se packet class | OpenSensePacket | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenSensePacket:
"""Generic open.sen.se packet class"""
def push(self):
"""Push values to open.sen.se @return response from open.sen.se"""
<|body_0|>
def __init__(self, sense_key, endpoints):
"""Constructor @param sense_key: open.sen.se authentication key @param ... | stack_v2_sparse_classes_75kplus_train_065333 | 7,332 | no_license | [
{
"docstring": "Push values to open.sen.se @return response from open.sen.se",
"name": "push",
"signature": "def push(self)"
},
{
"docstring": "Constructor @param sense_key: open.sen.se authentication key @param endpoints: list of (feed_ID, value) pairs",
"name": "__init__",
"signature":... | 2 | null | Implement the Python class `OpenSensePacket` described below.
Class description:
Generic open.sen.se packet class
Method signatures and docstrings:
- def push(self): Push values to open.sen.se @return response from open.sen.se
- def __init__(self, sense_key, endpoints): Constructor @param sense_key: open.sen.se authe... | Implement the Python class `OpenSensePacket` described below.
Class description:
Generic open.sen.se packet class
Method signatures and docstrings:
- def push(self): Push values to open.sen.se @return response from open.sen.se
- def __init__(self, sense_key, endpoints): Constructor @param sense_key: open.sen.se authe... | 4c5b4ab455b62a9b1b0a1477121997ca8a495aef | <|skeleton|>
class OpenSensePacket:
"""Generic open.sen.se packet class"""
def push(self):
"""Push values to open.sen.se @return response from open.sen.se"""
<|body_0|>
def __init__(self, sense_key, endpoints):
"""Constructor @param sense_key: open.sen.se authentication key @param ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenSensePacket:
"""Generic open.sen.se packet class"""
def push(self):
"""Push values to open.sen.se @return response from open.sen.se"""
headers = {'Content-type': 'application/json', 'sense_key': self.sense_key}
url = 'api.sen.se'
res = None
try:
con... | the_stack_v2_python_sparse | python/lagarto/lagarto-max/clouding.py | ntruchsess/panstamp | train | 3 |
3e0abac0d9d72f48592728dd3052f3024fb71925 | [
"self.dim = pos_samples.shape[1]\nif self.dim + 1 != pos_samples.shape[0]:\n raise ValueError('Wrong number of samples')\nself.vertices = pos_samples\nself.facets = []\nself.create_facets()",
"for sample_id in range(self.vertices.shape[0]):\n facet_points = np.delete(self.vertices, sample_id, axis=0)\n s... | <|body_start_0|>
self.dim = pos_samples.shape[1]
if self.dim + 1 != pos_samples.shape[0]:
raise ValueError('Wrong number of samples')
self.vertices = pos_samples
self.facets = []
self.create_facets()
<|end_body_0|>
<|body_start_1|>
for sample_id in range(self... | Implement the convex polytope | PosRegion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosRegion:
"""Implement the convex polytope"""
def __init__(self, pos_samples):
"""Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope."""
<|body_0|>
def create_facets(self):
"""Create the facets of the polytope"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_065334 | 4,260 | permissive | [
{
"docstring": "Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope.",
"name": "__init__",
"signature": "def __init__(self, pos_samples)"
},
{
"docstring": "Create the facets of the polytope",
"name": "create_facets",
"signature": "def create_facets(self)"... | 5 | stack_v2_sparse_classes_30k_train_016014 | Implement the Python class `PosRegion` described below.
Class description:
Implement the convex polytope
Method signatures and docstrings:
- def __init__(self, pos_samples): Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope.
- def create_facets(self): Create the facets of the polytop... | Implement the Python class `PosRegion` described below.
Class description:
Implement the convex polytope
Method signatures and docstrings:
- def __init__(self, pos_samples): Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope.
- def create_facets(self): Create the facets of the polytop... | b37b4ba33e035ff2c005e3faa194c25702b7e5f1 | <|skeleton|>
class PosRegion:
"""Implement the convex polytope"""
def __init__(self, pos_samples):
"""Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope."""
<|body_0|>
def create_facets(self):
"""Create the facets of the polytope"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PosRegion:
"""Implement the convex polytope"""
def __init__(self, pos_samples):
"""Params: pos_samples (np.array): dim+1 positive samples to create the (dim)-polytope."""
self.dim = pos_samples.shape[1]
if self.dim + 1 != pos_samples.shape[0]:
raise ValueError('Wrong n... | the_stack_v2_python_sparse | neural_aide/threesetsmetric/posregion.py | AlexandreSev/neural_aide | train | 0 |
6a69df370ec9607afaa3dffb5f765c542dbb4e7a | [
"dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]\nMOD = 10 ** 9 + 7\ndp[0][0] = 1\nfor i in range(n + 1):\n for j in range(i):\n for m in range(k + 1):\n if m - j >= 0 and m - j <= k:\n dp[i][m] = (dp[i][m] + dp[i - 1][m - j]) % MOD\nreturn dp[n][k]",
"\"\"\"\n dp... | <|body_start_0|>
dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]
MOD = 10 ** 9 + 7
dp[0][0] = 1
for i in range(n + 1):
for j in range(i):
for m in range(k + 1):
if m - j >= 0 and m - j <= k:
dp[i][m] = (dp[i][... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kInversePairsTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [[0 for _ in range(k + 1)... | stack_v2_sparse_classes_75kplus_train_065335 | 3,240 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kInversePairsTLE",
"signature": "def kInversePairsTLE(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kInversePairs",
"signature": "def kInversePairs(self, n, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002025 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kInversePairsTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kInversePairsTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kInversePairs(self, n, k): :type n: int :type k: int :rtype: int
<|skeleton|>
class Solution:
... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def kInversePairsTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kInversePairs(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def kInversePairsTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]
MOD = 10 ** 9 + 7
dp[0][0] = 1
for i in range(n + 1):
for j in range(i):
for m in range(k + 1):
... | the_stack_v2_python_sparse | K/KInversePairsArray.py | bssrdf/pyleet | train | 2 | |
1f1fbebc67a57db32ae9d622dd1bf90ad796da30 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_java_time.JavaTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = AndroidTwitterSearchEventData()\nevent_data.creation_time = self._GetDateTimeRowValue(query_hash, row, 'time')\ne... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_java_time.JavaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = AndroidTwitterSearchEventData... | SQLite parser plugin for Twitter on Android database files. | AndroidTwitterPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidTwitterPlugin:
"""SQLite parser plugin for Twitter on Android database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that pro... | stack_v2_sparse_classes_75kplus_train_065336 | 21,169 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.JavaTime: date and time value or None if not available.",
"name"... | 4 | stack_v2_sparse_classes_30k_train_032625 | Implement the Python class `AndroidTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on Android database files.
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash ... | Implement the Python class `AndroidTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on Android database files.
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class AndroidTwitterPlugin:
"""SQLite parser plugin for Twitter on Android database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AndroidTwitterPlugin:
"""SQLite parser plugin for Twitter on Android database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/android_twitter.py | log2timeline/plaso | train | 1,506 |
c166ed5cb0d6684aad646d10d4c9515b788a90a5 | [
"samples = []\nfor line in header.split('\\n'):\n if line.startswith('#CHROM'):\n columns = line.split()\n for col in columns:\n if col not in ['#CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT']:\n samples.append(col)\n break\nreturn samples",
... | <|body_start_0|>
samples = []
for line in header.split('\n'):
if line.startswith('#CHROM'):
columns = line.split()
for col in columns:
if col not in ['#CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT']:
... | This class contains the functionality needed for VCF file's header. | VCFHeaderParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VCFHeaderParser:
"""This class contains the functionality needed for VCF file's header."""
def _extract_sample_list(cls, header):
"""This function extracts the list of samples from the file header and returns it. Params: the header (string) Returns: list of samples identifiers"""
... | stack_v2_sparse_classes_75kplus_train_065337 | 4,596 | no_license | [
{
"docstring": "This function extracts the list of samples from the file header and returns it. Params: the header (string) Returns: list of samples identifiers",
"name": "_extract_sample_list",
"signature": "def _extract_sample_list(cls, header)"
},
{
"docstring": "This function checks if there... | 6 | stack_v2_sparse_classes_30k_train_023409 | Implement the Python class `VCFHeaderParser` described below.
Class description:
This class contains the functionality needed for VCF file's header.
Method signatures and docstrings:
- def _extract_sample_list(cls, header): This function extracts the list of samples from the file header and returns it. Params: the he... | Implement the Python class `VCFHeaderParser` described below.
Class description:
This class contains the functionality needed for VCF file's header.
Method signatures and docstrings:
- def _extract_sample_list(cls, header): This function extracts the list of samples from the file header and returns it. Params: the he... | 8b87a11463ce60757bb371479e654a9fd54a0323 | <|skeleton|>
class VCFHeaderParser:
"""This class contains the functionality needed for VCF file's header."""
def _extract_sample_list(cls, header):
"""This function extracts the list of samples from the file header and returns it. Params: the header (string) Returns: list of samples identifiers"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VCFHeaderParser:
"""This class contains the functionality needed for VCF file's header."""
def _extract_sample_list(cls, header):
"""This function extracts the list of samples from the file header and returns it. Params: the header (string) Returns: list of samples identifiers"""
samples ... | the_stack_v2_python_sparse | serapis/header_parser/vcf_hparser.py | wtsi-hgi/serapis-web | train | 1 |
36d7f35ff2d557ab4a3036d467a7da54ccacc7f1 | [
"x = len(matrix)\ny = 0\nif x != 0:\n y = len(matrix[0])\nfor i in range(x):\n for j in range(y):\n left = 0\n top = 0\n leftTop = 0\n if j - 1 >= 0:\n left = matrix[i][j - 1]\n if i - 1 >= 0:\n top = matrix[i - 1][j]\n if i - 1 >= 0 and j - 1 >=... | <|body_start_0|>
x = len(matrix)
y = 0
if x != 0:
y = len(matrix[0])
for i in range(x):
for j in range(y):
left = 0
top = 0
leftTop = 0
if j - 1 >= 0:
left = matrix[i][j - 1]
... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_065338 | 1,387 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_009282 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | b890a5ea050cfe3886b5275cc26c1593b35b58db | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
x = len(matrix)
y = 0
if x != 0:
y = len(matrix[0])
for i in range(x):
for j in range(y):
left = 0
top = 0
leftTop = 0
... | the_stack_v2_python_sparse | 面试练习/304.py | QkqBeer/PythonSubject | train | 4 | |
2d904da14fc420017fd413bd8263fdc4afd2560b | [
"for row in matrix:\n for col in row:\n if col == target:\n return True\nreturn False",
"if len(matrix) == 0 or len(matrix[0]) == 0:\n return False\nleft, right = (0, len(matrix[0]) - 1)\nfor i in range(len(matrix)):\n while left <= right:\n mid = (left + right + 1) // 2\n ... | <|body_start_0|>
for row in matrix:
for col in row:
if col == target:
return True
return False
<|end_body_0|>
<|body_start_1|>
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
left, right = (0, len(matrix[0]) - 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNumberIn2DArray1(self, matrix: List[List[int]], target: int) -> bool:
"""日常暴力,虽然没用 复杂度分析: 时间复杂度:O(MN) 最好情况O(1) 空间复杂度:O(1)"""
<|body_0|>
def findNumberIn2DArray2(self, matrix: List[List[int]], target: int) -> bool:
"""也可以这样查找,但是针对性不强,因为对于二维矩阵,我们只使用了行... | stack_v2_sparse_classes_75kplus_train_065339 | 3,083 | no_license | [
{
"docstring": "日常暴力,虽然没用 复杂度分析: 时间复杂度:O(MN) 最好情况O(1) 空间复杂度:O(1)",
"name": "findNumberIn2DArray1",
"signature": "def findNumberIn2DArray1(self, matrix: List[List[int]], target: int) -> bool"
},
{
"docstring": "也可以这样查找,但是针对性不强,因为对于二维矩阵,我们只使用了行,或者列 复杂度分析: 时间复杂度:O(nlogn) 空间复杂度:O(1)",
"name": "f... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNumberIn2DArray1(self, matrix: List[List[int]], target: int) -> bool: 日常暴力,虽然没用 复杂度分析: 时间复杂度:O(MN) 最好情况O(1) 空间复杂度:O(1)
- def findNumberIn2DArray2(self, matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNumberIn2DArray1(self, matrix: List[List[int]], target: int) -> bool: 日常暴力,虽然没用 复杂度分析: 时间复杂度:O(MN) 最好情况O(1) 空间复杂度:O(1)
- def findNumberIn2DArray2(self, matrix: List[List[... | 51943e2c2c4ec70c7c1d5b53c9fdf0a719428d7a | <|skeleton|>
class Solution:
def findNumberIn2DArray1(self, matrix: List[List[int]], target: int) -> bool:
"""日常暴力,虽然没用 复杂度分析: 时间复杂度:O(MN) 最好情况O(1) 空间复杂度:O(1)"""
<|body_0|>
def findNumberIn2DArray2(self, matrix: List[List[int]], target: int) -> bool:
"""也可以这样查找,但是针对性不强,因为对于二维矩阵,我们只使用了行... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findNumberIn2DArray1(self, matrix: List[List[int]], target: int) -> bool:
"""日常暴力,虽然没用 复杂度分析: 时间复杂度:O(MN) 最好情况O(1) 空间复杂度:O(1)"""
for row in matrix:
for col in row:
if col == target:
return True
return False
def findNumb... | the_stack_v2_python_sparse | 剑指offer/PythonVersion/04_二维数组中的查找.py | LeBron-Jian/BasicAlgorithmPractice | train | 13 | |
c5b8604ae9055f603494c1f984ff3a943eae1c98 | [
"self._header = ProgressiveHeader(request_event.request.request_id)\nself._api_endpoint = request_event.context.system.api_endpoint + '/v1/directives'\nself._api_access_token = request_event.context.system.api_access_token",
"directive = ProgressiveDirective(speech)\nresponse = ProgressiveResponse(self._header, d... | <|body_start_0|>
self._header = ProgressiveHeader(request_event.request.request_id)
self._api_endpoint = request_event.context.system.api_endpoint + '/v1/directives'
self._api_access_token = request_event.context.system.api_access_token
<|end_body_0|>
<|body_start_1|>
directive = Progre... | This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response. | ProgressiveResponseBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressiveResponseBuilder:
"""This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response."""
def __init__(self, request_event):
"""Create a progressive response builder. You only need to create one of these pe... | stack_v2_sparse_classes_75kplus_train_065340 | 3,057 | permissive | [
{
"docstring": "Create a progressive response builder. You only need to create one of these per each request and simply call the send speech each time you need to send a response. Initialize with the request event object.",
"name": "__init__",
"signature": "def __init__(self, request_event)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_043212 | Implement the Python class `ProgressiveResponseBuilder` described below.
Class description:
This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response.
Method signatures and docstrings:
- def __init__(self, request_event): Create a progressive ... | Implement the Python class `ProgressiveResponseBuilder` described below.
Class description:
This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response.
Method signatures and docstrings:
- def __init__(self, request_event): Create a progressive ... | aac9d8aa4d6d5d2e9dcd079e0ac516b06c8a94ba | <|skeleton|>
class ProgressiveResponseBuilder:
"""This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response."""
def __init__(self, request_event):
"""Create a progressive response builder. You only need to create one of these pe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProgressiveResponseBuilder:
"""This class provides a simple way to create and send a progressive response to Alexa while your skill processes the complete response."""
def __init__(self, request_event):
"""Create a progressive response builder. You only need to create one of these per each reques... | the_stack_v2_python_sparse | askalexa/response/progressive.py | scottenglert/AskAlexa | train | 2 |
4cfcd500e415d9c5ff86b93b9635b32938362e27 | [
"nums = self._convertBST2Array(root)\nlength = len(nums)\nif length < 2:\n return False\ni, j = (0, length - 1)\nwhile i < j:\n sum_value = nums[i] + nums[j]\n if sum_value == k:\n return True\n elif sum_value < k:\n i += 1\n else:\n j -= 1\nreturn False",
"if root is None:\n ... | <|body_start_0|>
nums = self._convertBST2Array(root)
length = len(nums)
if length < 2:
return False
i, j = (0, length - 1)
while i < j:
sum_value = nums[i] + nums[j]
if sum_value == k:
return True
elif sum_value < k:... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findTarget(self, root, k):
""":type root: TreeNode :type k: int :rtype: bool"""
<|body_0|>
def _convertBST2Array(self, root):
""":type root: TreeNode :rtype: list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
nums = self._convertBST2... | stack_v2_sparse_classes_75kplus_train_065341 | 2,419 | permissive | [
{
"docstring": ":type root: TreeNode :type k: int :rtype: bool",
"name": "findTarget",
"signature": "def findTarget(self, root, k)"
},
{
"docstring": ":type root: TreeNode :rtype: list",
"name": "_convertBST2Array",
"signature": "def _convertBST2Array(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014434 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget(self, root, k): :type root: TreeNode :type k: int :rtype: bool
- def _convertBST2Array(self, root): :type root: TreeNode :rtype: list | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findTarget(self, root, k): :type root: TreeNode :type k: int :rtype: bool
- def _convertBST2Array(self, root): :type root: TreeNode :rtype: list
<|skeleton|>
class Solution:... | 05420b73d28220681cd7be8253bebcaa83966954 | <|skeleton|>
class Solution:
def findTarget(self, root, k):
""":type root: TreeNode :type k: int :rtype: bool"""
<|body_0|>
def _convertBST2Array(self, root):
""":type root: TreeNode :rtype: list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findTarget(self, root, k):
""":type root: TreeNode :type k: int :rtype: bool"""
nums = self._convertBST2Array(root)
length = len(nums)
if length < 2:
return False
i, j = (0, length - 1)
while i < j:
sum_value = nums[i] + num... | the_stack_v2_python_sparse | two-sum-iv-input-is-a-bst/test.py | optionalg/challenges-leetcode-interesting | train | 0 | |
b2f68f09cbb764875c83288665625e3c86fd4810 | [
"self._vocab = vocab\nself._padding_index = padding_index\nself._detokenizer = detokenizer\nself._encoder = tfhub.load(use_tfhub_url)",
"original_sentence_strings = attack_setup.tensor_to_strings(original_sentences, self._vocab, self._detokenizer, self._padding_index)\nadversarial_sentence_strings = attack_setup.... | <|body_start_0|>
self._vocab = vocab
self._padding_index = padding_index
self._detokenizer = detokenizer
self._encoder = tfhub.load(use_tfhub_url)
<|end_body_0|>
<|body_start_1|>
original_sentence_strings = attack_setup.tensor_to_strings(original_sentences, self._vocab, self._de... | Wraps the Universal Sentence Encoder and converts tensors to strings. The Universal Sentence Encoder expects python strings as input and includes its own tokenizer. The attack functions on tensors, so we need to convert vocab indices to tokens and then detokenize the text back into strings. Attributes: detokenizer: Det... | UniversalSentenceEncoderDistance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UniversalSentenceEncoderDistance:
"""Wraps the Universal Sentence Encoder and converts tensors to strings. The Universal Sentence Encoder expects python strings as input and includes its own tokenizer. The attack functions on tensors, so we need to convert vocab indices to tokens and then detoken... | stack_v2_sparse_classes_75kplus_train_065342 | 9,072 | permissive | [
{
"docstring": "Initializes the UniversalSentenceEncoderDistance class. Arguments: detokenizer: Detokenizer accepts a list of tokens, joins them by whitespace, and then undoes the regexes used to tokenize text. vocab: A list of tokens in the vocabulary. padding_index: An integer indicating which vocab entry is ... | 2 | stack_v2_sparse_classes_30k_val_001352 | Implement the Python class `UniversalSentenceEncoderDistance` described below.
Class description:
Wraps the Universal Sentence Encoder and converts tensors to strings. The Universal Sentence Encoder expects python strings as input and includes its own tokenizer. The attack functions on tensors, so we need to convert v... | Implement the Python class `UniversalSentenceEncoderDistance` described below.
Class description:
Wraps the Universal Sentence Encoder and converts tensors to strings. The Universal Sentence Encoder expects python strings as input and includes its own tokenizer. The attack functions on tensors, so we need to convert v... | aacdc8c88cc11f57456b989da0832f2e0ad89178 | <|skeleton|>
class UniversalSentenceEncoderDistance:
"""Wraps the Universal Sentence Encoder and converts tensors to strings. The Universal Sentence Encoder expects python strings as input and includes its own tokenizer. The attack functions on tensors, so we need to convert vocab indices to tokens and then detoken... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UniversalSentenceEncoderDistance:
"""Wraps the Universal Sentence Encoder and converts tensors to strings. The Universal Sentence Encoder expects python strings as input and includes its own tokenizer. The attack functions on tensors, so we need to convert vocab indices to tokens and then detokenize the text ... | the_stack_v2_python_sparse | discretezoo/loss/semantic_similarity.py | googleinterns/adversarial-0th-order-optimization | train | 0 |
c730e22aefcebae91711984ff1fdcc6566bbe101 | [
"if not l1:\n return l2\nif not l2:\n return l1\nprehead = ListNode(-1)\nprev = prehead\nwhile l1 and l2:\n if l1.val < l2.val:\n prev.next = l1\n l1 = l1.next\n else:\n prev.next = l2\n l2 = l2.next\n prev = prev.next\nprev.next = l1 if l1 else l2\nreturn prehead.next",
... | <|body_start_0|>
if not l1:
return l2
if not l2:
return l1
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val < l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
""":type l1: ListNode :type l2: ListNode :rtype: ListNode 迭代 时间击败90.85%,内存击败51.97%"""
<|body_0|>
def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
""":type l1: ListNode :type l... | stack_v2_sparse_classes_75kplus_train_065343 | 2,050 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode 迭代 时间击败90.85%,内存击败51.97%",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode 递归 时间击败75.93%,内存击败26... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: :type l1: ListNode :type l2: ListNode :rtype: ListNode 迭代 时间击败90.85%,内存击败51.97%
- def mergeTwoLists1(self, l1: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: :type l1: ListNode :type l2: ListNode :rtype: ListNode 迭代 时间击败90.85%,内存击败51.97%
- def mergeTwoLists1(self, l1: Li... | 2dc982e690b153c33bc7e27a63604f754a0df90c | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
""":type l1: ListNode :type l2: ListNode :rtype: ListNode 迭代 时间击败90.85%,内存击败51.97%"""
<|body_0|>
def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
""":type l1: ListNode :type l... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
""":type l1: ListNode :type l2: ListNode :rtype: ListNode 迭代 时间击败90.85%,内存击败51.97%"""
if not l1:
return l2
if not l2:
return l1
prehead = ListNode(-1)
prev = prehead
... | the_stack_v2_python_sparse | 21_merge-two-sorted-lists.py | 95275059/Algorithm | train | 0 | |
50df8e3400864558bbcc8f40378e8e2b51bab452 | [
"if self._server:\n raise RuntimeError('Already serving')\nserver = DGServer(self._loop)\nloop = self._loop\nif sockets:\n for sock in sockets:\n transport, _ = await loop.create_datagram_endpoint(self.create_protocol, sock=sock)\n server.transports.append(transport)\nelif isinstance(address, tu... | <|body_start_0|>
if self._server:
raise RuntimeError('Already serving')
server = DGServer(self._loop)
loop = self._loop
if sockets:
for sock in sockets:
transport, _ = await loop.create_datagram_endpoint(self.create_protocol, sock=sock)
... | DatagramServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatagramServer:
async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint."""
<|body_0|>
async def close(self):
"""Stop serving the :attr:`.Server.sockets` and close all concurrent connections."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_065344 | 12,244 | no_license | [
{
"docstring": "create the server endpoint.",
"name": "start_serving",
"signature": "async def start_serving(self, address=None, sockets=None, **kw)"
},
{
"docstring": "Stop serving the :attr:`.Server.sockets` and close all concurrent connections.",
"name": "close",
"signature": "async d... | 2 | null | Implement the Python class `DatagramServer` described below.
Class description:
Implement the DatagramServer class.
Method signatures and docstrings:
- async def start_serving(self, address=None, sockets=None, **kw): create the server endpoint.
- async def close(self): Stop serving the :attr:`.Server.sockets` and clo... | Implement the Python class `DatagramServer` described below.
Class description:
Implement the DatagramServer class.
Method signatures and docstrings:
- async def start_serving(self, address=None, sockets=None, **kw): create the server endpoint.
- async def close(self): Stop serving the :attr:`.Server.sockets` and clo... | f37ed822b5863a5a11b09550dd32a73d68e7070b | <|skeleton|>
class DatagramServer:
async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint."""
<|body_0|>
async def close(self):
"""Stop serving the :attr:`.Server.sockets` and close all concurrent connections."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DatagramServer:
async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint."""
if self._server:
raise RuntimeError('Already serving')
server = DGServer(self._loop)
loop = self._loop
if sockets:
for sock in sock... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/pulsar/async/protocols.py | ravisjoshi/python_snippets | train | 1 | |
f4f87afcd2d9a2d79e99e764dec261398a562be5 | [
"GObject.GObject.__init__(self)\nmsg = long_op_status.get_msg()\nself._old_val = -1\nself._lbl = Gtk.Label(label=msg)\nself._lbl.set_use_markup(True)\nself._pbar = Gtk.ProgressBar()\nself._hbox = Gtk.HBox()\nif long_op_status.can_cancel():\n self._cancel = Gtk.Button(stock=Gtk.STOCK_CANCEL)\n self._cancel.con... | <|body_start_0|>
GObject.GObject.__init__(self)
msg = long_op_status.get_msg()
self._old_val = -1
self._lbl = Gtk.Label(label=msg)
self._lbl.set_use_markup(True)
self._pbar = Gtk.ProgressBar()
self._hbox = Gtk.HBox()
if long_op_status.can_cancel():
... | This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar. | _GtkProgressBar | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _GtkProgressBar:
"""This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar."""
def __init__(self, long_op_status):
""":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpSta... | stack_v2_sparse_classes_75kplus_train_065345 | 20,395 | no_license | [
{
"docstring": ":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpStatus`",
"name": "__init__",
"signature": "def __init__(self, long_op_status)"
},
{
"docstring": "Move the progress bar on a step.",
"name": "step",
"signature": "def step(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_009692 | Implement the Python class `_GtkProgressBar` described below.
Class description:
This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar.
Method signatures and docstrings:
- def __init__(self, long_op_status): :param long_op_status: the status o... | Implement the Python class `_GtkProgressBar` described below.
Class description:
This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar.
Method signatures and docstrings:
- def __init__(self, long_op_status): :param long_op_status: the status o... | 0c79561bed7ff42c88714edbc85197fa9235e188 | <|skeleton|>
class _GtkProgressBar:
"""This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar."""
def __init__(self, long_op_status):
""":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpSta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _GtkProgressBar:
"""This widget displays the progress bar and labels for a progress indicator. It provides an interface to updating the progress bar."""
def __init__(self, long_op_status):
""":param long_op_status: the status of the operation. :type long_op_status: :class:`.LongOpStatus`"""
... | the_stack_v2_python_sparse | gui/widgets/progressdialog.py | balrok/gramps_addon | train | 2 |
3464ffddaded89baf7023f78c7b8703b8959e5c2 | [
"if not self.config_file:\n return\ndefault_path = os.path.dirname(self.config_file)\ntry:\n for option in ('ssl_ca', 'ssl_key', 'ssl_cert'):\n value = self.get(section, option)\n if not value:\n self.remove_option(section, option)\n elif not os.path.isabs(value):\n ... | <|body_start_0|>
if not self.config_file:
return
default_path = os.path.dirname(self.config_file)
try:
for option in ('ssl_ca', 'ssl_key', 'ssl_cert'):
value = self.get(section, option)
if not value:
self.remove_option(s... | Fabric configuration file parser and configuration handler. This class manages the configuration of Fabric nodes and clients, including configuration file locations. Sample usage:: from mysql.fabric.options import OptionParser from mysql.fabric.config import Config parser = OptionParser() ... options, args = parser.par... | Config | [
"Apache-2.0",
"LicenseRef-scancode-python-cwi",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft",
"Sleepycat",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
"""Fabric configuration file parser and configuration handler. This class manages the configuration of Fabric nodes and clients, including configuration file locations. Sample usage:: from mysql.fabric.options import OptionParser from mysql.fabric.config import Config parser = OptionParse... | stack_v2_sparse_classes_75kplus_train_065346 | 4,112 | permissive | [
{
"docstring": "Normalizes the SSL option in a section :param section: Section from which we read SSL configuration.",
"name": "normalize_ssl_config",
"signature": "def normalize_ssl_config(self, section)"
},
{
"docstring": "Create the configuration parser, read the configuration files, and set ... | 2 | stack_v2_sparse_classes_30k_train_001358 | Implement the Python class `Config` described below.
Class description:
Fabric configuration file parser and configuration handler. This class manages the configuration of Fabric nodes and clients, including configuration file locations. Sample usage:: from mysql.fabric.options import OptionParser from mysql.fabric.co... | Implement the Python class `Config` described below.
Class description:
Fabric configuration file parser and configuration handler. This class manages the configuration of Fabric nodes and clients, including configuration file locations. Sample usage:: from mysql.fabric.options import OptionParser from mysql.fabric.co... | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | <|skeleton|>
class Config:
"""Fabric configuration file parser and configuration handler. This class manages the configuration of Fabric nodes and clients, including configuration file locations. Sample usage:: from mysql.fabric.options import OptionParser from mysql.fabric.config import Config parser = OptionParse... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Config:
"""Fabric configuration file parser and configuration handler. This class manages the configuration of Fabric nodes and clients, including configuration file locations. Sample usage:: from mysql.fabric.options import OptionParser from mysql.fabric.config import Config parser = OptionParser() ... optio... | the_stack_v2_python_sparse | mysql-utilities-1.6.0/mysql/fabric/config.py | scavarda/mysql-dbcompare | train | 2 |
0ec659472519cd9e32a6f3a56b0d3e6a7980bbc6 | [
"self.config = config_entry\nself._data = dict(config_entry.data)\nself._errors = {}",
"if user_input is not None:\n self._data.update(user_input)\n return self.async_create_entry(title='', data=self._data)\nreturn await self._show_options_form(user_input)",
"self._errors = {}\nif user_input is not None:\... | <|body_start_0|>
self.config = config_entry
self._data = dict(config_entry.data)
self._errors = {}
<|end_body_0|>
<|body_start_1|>
if user_input is not None:
self._data.update(user_input)
return self.async_create_entry(title='', data=self._data)
return aw... | Options flow for NWS Alerts. | NWSAlertsOptionsFlow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NWSAlertsOptionsFlow:
"""Options flow for NWS Alerts."""
def __init__(self, config_entry):
"""Initialize."""
<|body_0|>
async def async_step_init(self, user_input=None):
"""Manage Mail and Packages options."""
<|body_1|>
async def async_step_gps_loc(... | stack_v2_sparse_classes_75kplus_train_065347 | 11,142 | no_license | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, config_entry)"
},
{
"docstring": "Manage Mail and Packages options.",
"name": "async_step_init",
"signature": "async def async_step_init(self, user_input=None)"
},
{
"docstring": "Handle a flow ini... | 6 | stack_v2_sparse_classes_30k_train_041929 | Implement the Python class `NWSAlertsOptionsFlow` described below.
Class description:
Options flow for NWS Alerts.
Method signatures and docstrings:
- def __init__(self, config_entry): Initialize.
- async def async_step_init(self, user_input=None): Manage Mail and Packages options.
- async def async_step_gps_loc(self... | Implement the Python class `NWSAlertsOptionsFlow` described below.
Class description:
Options flow for NWS Alerts.
Method signatures and docstrings:
- def __init__(self, config_entry): Initialize.
- async def async_step_init(self, user_input=None): Manage Mail and Packages options.
- async def async_step_gps_loc(self... | 625290c164c60611f501ee773583c06a85281300 | <|skeleton|>
class NWSAlertsOptionsFlow:
"""Options flow for NWS Alerts."""
def __init__(self, config_entry):
"""Initialize."""
<|body_0|>
async def async_step_init(self, user_input=None):
"""Manage Mail and Packages options."""
<|body_1|>
async def async_step_gps_loc(... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NWSAlertsOptionsFlow:
"""Options flow for NWS Alerts."""
def __init__(self, config_entry):
"""Initialize."""
self.config = config_entry
self._data = dict(config_entry.data)
self._errors = {}
async def async_step_init(self, user_input=None):
"""Manage Mail and ... | the_stack_v2_python_sparse | custom_components/nws_alerts/config_flow.py | ntalekt/homeassistant | train | 213 |
67217bba10145e7e96089f3444cdf7d4ecf1451c | [
"from django.conf.urls import url\n\ndef wrap(view):\n\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view, cacheable=True)(*args, **kwargs)\n return update_wrapper(wrapper, view)\ninfo = self.get_model_info()\nurls = super(HTMLModelReportMixin, self).get_urls()\nreport_url = [url(... | <|body_start_0|>
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view, cacheable=True)(*args, **kwargs)
return update_wrapper(wrapper, view)
info = self.get_model_info()
urls = supe... | HTML Admin Mixin for django admin Generate model object detail in pdf format report with WeasyPrint using html file template | HTMLModelReportMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTMLModelReportMixin:
"""HTML Admin Mixin for django admin Generate model object detail in pdf format report with WeasyPrint using html file template"""
def get_urls(self):
"""Get default django admin urls then add custom url for report link"""
<|body_0|>
def get_context... | stack_v2_sparse_classes_75kplus_train_065348 | 6,508 | no_license | [
{
"docstring": "Get default django admin urls then add custom url for report link",
"name": "get_urls",
"signature": "def get_urls(self)"
},
{
"docstring": "Get the context name to used in template",
"name": "get_context_object_name",
"signature": "def get_context_object_name(self)"
},... | 6 | stack_v2_sparse_classes_30k_train_047724 | Implement the Python class `HTMLModelReportMixin` described below.
Class description:
HTML Admin Mixin for django admin Generate model object detail in pdf format report with WeasyPrint using html file template
Method signatures and docstrings:
- def get_urls(self): Get default django admin urls then add custom url f... | Implement the Python class `HTMLModelReportMixin` described below.
Class description:
HTML Admin Mixin for django admin Generate model object detail in pdf format report with WeasyPrint using html file template
Method signatures and docstrings:
- def get_urls(self): Get default django admin urls then add custom url f... | 0cf8fb1be8ac3c27304807ed7aac7eb0032c2cb6 | <|skeleton|>
class HTMLModelReportMixin:
"""HTML Admin Mixin for django admin Generate model object detail in pdf format report with WeasyPrint using html file template"""
def get_urls(self):
"""Get default django admin urls then add custom url for report link"""
<|body_0|>
def get_context... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HTMLModelReportMixin:
"""HTML Admin Mixin for django admin Generate model object detail in pdf format report with WeasyPrint using html file template"""
def get_urls(self):
"""Get default django admin urls then add custom url for report link"""
from django.conf.urls import url
de... | the_stack_v2_python_sparse | reporting/admin.py | andrewidya/littleerp | train | 1 |
5176b32a3cd5a6a151c5f0076d5d9e4e5946c101 | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = np.mean(data, axis=1).reshape((data.shape[0], 1))\ndata_t = data.T\nmean = np.mean(data_t, axis=0)... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
self.mean = np.mean(data, axis=1).reshape((data.shape[0], 1))
... | class | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
<|body_0|>
def pdf(self, x):
"""method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError(... | stack_v2_sparse_classes_75kplus_train_065349 | 1,296 | no_license | [
{
"docstring": "initializer",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "method",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034033 | Implement the Python class `MultiNormal` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, data): initializer
- def pdf(self, x): method | Implement the Python class `MultiNormal` described below.
Class description:
class
Method signatures and docstrings:
- def __init__(self, data): initializer
- def pdf(self, x): method
<|skeleton|>
class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
<|body_0|>
def ... | b5e8f1253309567ca7be71b9575a150de1be3820 | <|skeleton|>
class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
<|body_0|>
def pdf(self, x):
"""method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""class"""
def __init__(self, data):
"""initializer"""
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data poin... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | jadsm98/holbertonschool-machine_learning | train | 0 |
02ba9822beddc5ff219823c5607d2f42c4b309a3 | [
"wComponent.__init__(self)\nself.element = self.new_tag('w:r')\nself.element.append(self.new_tag('w:rPr'))\nself.bs.append(self.element)",
"if issubclass(component.__class__, wComponent):\n self.element.append(component.__bs__())\nelif issubclass(component.__class__, Tag):\n self.element.append(component)\n... | <|body_start_0|>
wComponent.__init__(self)
self.element = self.new_tag('w:r')
self.element.append(self.new_tag('w:rPr'))
self.bs.append(self.element)
<|end_body_0|>
<|body_start_1|>
if issubclass(component.__class__, wComponent):
self.element.append(component.__bs__(... | wR | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class wR:
def __init__(self):
"""Class Constructor"""
<|body_0|>
def add(self, component):
"""Add a component. component -- wComponent Object"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
wComponent.__init__(self)
self.element = self.new_tag('w:... | stack_v2_sparse_classes_75kplus_train_065350 | 1,790 | permissive | [
{
"docstring": "Class Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add a component. component -- wComponent Object",
"name": "add",
"signature": "def add(self, component)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044943 | Implement the Python class `wR` described below.
Class description:
Implement the wR class.
Method signatures and docstrings:
- def __init__(self): Class Constructor
- def add(self, component): Add a component. component -- wComponent Object | Implement the Python class `wR` described below.
Class description:
Implement the wR class.
Method signatures and docstrings:
- def __init__(self): Class Constructor
- def add(self, component): Add a component. component -- wComponent Object
<|skeleton|>
class wR:
def __init__(self):
"""Class Constructo... | b65882398585973c0efa38b3903f45b6c4d1ca49 | <|skeleton|>
class wR:
def __init__(self):
"""Class Constructor"""
<|body_0|>
def add(self, component):
"""Add a component. component -- wComponent Object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class wR:
def __init__(self):
"""Class Constructor"""
wComponent.__init__(self)
self.element = self.new_tag('w:r')
self.element.append(self.new_tag('w:rPr'))
self.bs.append(self.element)
def add(self, component):
"""Add a component. component -- wComponent Object... | the_stack_v2_python_sparse | genword/lib/r.py | di3g0bs0n/genword | train | 0 | |
13293c47421694a7f4bf05ee9ac8e6031d99a854 | [
"if not self.request.user.has_perm('resources.add_resource'):\n return HttpResponseForbidden()\nreturn super(ResourceCreateView, self).dispatch(*args, **kwargs)",
"form.instance.created_by = self.request.user\nform.instance.content_type = self.request.FILES.items()[0][1].content_type\nreturn super(ResourceCrea... | <|body_start_0|>
if not self.request.user.has_perm('resources.add_resource'):
return HttpResponseForbidden()
return super(ResourceCreateView, self).dispatch(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
form.instance.created_by = self.request.user
form.instance.content_ty... | View for creating a new Resource. | ResourceCreateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceCreateView:
"""View for creating a new Resource."""
def dispatch(self, *args, **kwargs):
"""Limit view to users with access to create a Resource."""
<|body_0|>
def form_valid(self, form):
"""Handle a valid form."""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_75kplus_train_065351 | 5,832 | permissive | [
{
"docstring": "Limit view to users with access to create a Resource.",
"name": "dispatch",
"signature": "def dispatch(self, *args, **kwargs)"
},
{
"docstring": "Handle a valid form.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017690 | Implement the Python class `ResourceCreateView` described below.
Class description:
View for creating a new Resource.
Method signatures and docstrings:
- def dispatch(self, *args, **kwargs): Limit view to users with access to create a Resource.
- def form_valid(self, form): Handle a valid form. | Implement the Python class `ResourceCreateView` described below.
Class description:
View for creating a new Resource.
Method signatures and docstrings:
- def dispatch(self, *args, **kwargs): Limit view to users with access to create a Resource.
- def form_valid(self, form): Handle a valid form.
<|skeleton|>
class Re... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class ResourceCreateView:
"""View for creating a new Resource."""
def dispatch(self, *args, **kwargs):
"""Limit view to users with access to create a Resource."""
<|body_0|>
def form_valid(self, form):
"""Handle a valid form."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceCreateView:
"""View for creating a new Resource."""
def dispatch(self, *args, **kwargs):
"""Limit view to users with access to create a Resource."""
if not self.request.user.has_perm('resources.add_resource'):
return HttpResponseForbidden()
return super(Resourc... | the_stack_v2_python_sparse | open_connect/resources/views.py | ofa/connect | train | 66 |
0760607db001d6263f43dfdb167b2b48d408668a | [
"super(MultiLoss, self).__init__(*losses)\nself.loss_fn = []\nfor loss in losses:\n self.loss_fn.append(loss)",
"outputs = None\nfor model in self.loss_fn:\n if outputs is None:\n outputs = model(output, target)\n else:\n outputs = outputs + model(output, target)\nreturn outputs"
] | <|body_start_0|>
super(MultiLoss, self).__init__(*losses)
self.loss_fn = []
for loss in losses:
self.loss_fn.append(loss)
<|end_body_0|>
<|body_start_1|>
outputs = None
for model in self.loss_fn:
if outputs is None:
outputs = model(output,... | Define Multi loss creator for base. | MultiLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
<|body_0|>
def call(self, output, target):
"""Sum all loss of predict and groundtruth."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_75kplus_train_065352 | 1,238 | permissive | [
{
"docstring": "Initialize loss.",
"name": "__init__",
"signature": "def __init__(self, *losses)"
},
{
"docstring": "Sum all loss of predict and groundtruth.",
"name": "call",
"signature": "def call(self, output, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007389 | Implement the Python class `MultiLoss` described below.
Class description:
Define Multi loss creator for base.
Method signatures and docstrings:
- def __init__(self, *losses): Initialize loss.
- def call(self, output, target): Sum all loss of predict and groundtruth. | Implement the Python class `MultiLoss` described below.
Class description:
Define Multi loss creator for base.
Method signatures and docstrings:
- def __init__(self, *losses): Initialize loss.
- def call(self, output, target): Sum all loss of predict and groundtruth.
<|skeleton|>
class MultiLoss:
"""Define Multi... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
<|body_0|>
def call(self, output, target):
"""Sum all loss of predict and groundtruth."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiLoss:
"""Define Multi loss creator for base."""
def __init__(self, *losses):
"""Initialize loss."""
super(MultiLoss, self).__init__(*losses)
self.loss_fn = []
for loss in losses:
self.loss_fn.append(loss)
def call(self, output, target):
"""Sum... | the_stack_v2_python_sparse | zeus/modules/loss/multiloss.py | huawei-noah/xingtian | train | 308 |
4d4350901835a88354cd08ee2efbb21b59bba11e | [
"layer.Layer.__init__(self, inputs, outputs, alpha)\nself.parameters = dict()\nself.deltaparameters = dict()\nself.parameters['weights'] = numpy.random.normal(0.0, 1.0 / numpy.sqrt(self.inputs), (self.outputs, self.inputs))\nself.function = None\nself.functionderivative = None\nself.weightsderivative = None\nself.c... | <|body_start_0|>
layer.Layer.__init__(self, inputs, outputs, alpha)
self.parameters = dict()
self.deltaparameters = dict()
self.parameters['weights'] = numpy.random.normal(0.0, 1.0 / numpy.sqrt(self.inputs), (self.outputs, self.inputs))
self.function = None
self.functiond... | Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise | SelfOrganising | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfOrganising:
"""Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise"""
def __init__(self, inputs, outputs, alpha=None):
"""Constructor : param inputs : dimension of input feature space : param outputs : dimension of output ... | stack_v2_sparse_classes_75kplus_train_065353 | 5,772 | no_license | [
{
"docstring": "Constructor : param inputs : dimension of input feature space : param outputs : dimension of output feature space : param alpha : learning rate constant hyperparameter",
"name": "__init__",
"signature": "def __init__(self, inputs, outputs, alpha=None)"
},
{
"docstring": "Method t... | 4 | stack_v2_sparse_classes_30k_train_031742 | Implement the Python class `SelfOrganising` described below.
Class description:
Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise
Method signatures and docstrings:
- def __init__(self, inputs, outputs, alpha=None): Constructor : param inputs : dimension of i... | Implement the Python class `SelfOrganising` described below.
Class description:
Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise
Method signatures and docstrings:
- def __init__(self, inputs, outputs, alpha=None): Constructor : param inputs : dimension of i... | 10ee6e2297b7a2e01165ef983ae34097d7178122 | <|skeleton|>
class SelfOrganising:
"""Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise"""
def __init__(self, inputs, outputs, alpha=None):
"""Constructor : param inputs : dimension of input feature space : param outputs : dimension of output ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfOrganising:
"""Base Class for Self Organising Feature Maps Mathematically, f(x)(i) = 1.0 if i = argmin(r(i)) = 0.0 otherwise"""
def __init__(self, inputs, outputs, alpha=None):
"""Constructor : param inputs : dimension of input feature space : param outputs : dimension of output feature space... | the_stack_v2_python_sparse | net/selforganising.py | sunilmallya-work/NET | train | 0 |
36818756dbbc7fba4a01fd6851e0dfc7c8e58103 | [
"try:\n self.music = pyglet.resource.media(file_path)\nexcept pyglet.resource.ResourceNotFoundException:\n self.music = pyglet.media.load(file_path)\nelse:\n self.music = None",
"if self.music:\n self.music.play()\n pyglet.app.run()"
] | <|body_start_0|>
try:
self.music = pyglet.resource.media(file_path)
except pyglet.resource.ResourceNotFoundException:
self.music = pyglet.media.load(file_path)
else:
self.music = None
<|end_body_0|>
<|body_start_1|>
if self.music:
self.mus... | 声音警报. https://github.com/AVbin/AVbin/downloads http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin | WarnMedia | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WarnMedia:
"""声音警报. https://github.com/AVbin/AVbin/downloads http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin"""
def __init__(self, file_path):
"""先尝试相对路径, 再尝试绝对路径载入."""
<|body_0|>
def play(self):
"""如有效可播放."""
<|body_1... | stack_v2_sparse_classes_75kplus_train_065354 | 737 | no_license | [
{
"docstring": "先尝试相对路径, 再尝试绝对路径载入.",
"name": "__init__",
"signature": "def __init__(self, file_path)"
},
{
"docstring": "如有效可播放.",
"name": "play",
"signature": "def play(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_039042 | Implement the Python class `WarnMedia` described below.
Class description:
声音警报. https://github.com/AVbin/AVbin/downloads http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin
Method signatures and docstrings:
- def __init__(self, file_path): 先尝试相对路径, 再尝试绝对路径载入.
- def play(self): 如有效可播放... | Implement the Python class `WarnMedia` described below.
Class description:
声音警报. https://github.com/AVbin/AVbin/downloads http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin
Method signatures and docstrings:
- def __init__(self, file_path): 先尝试相对路径, 再尝试绝对路径载入.
- def play(self): 如有效可播放... | 40faf78b2365137b9da0cc67f511248b390b4c13 | <|skeleton|>
class WarnMedia:
"""声音警报. https://github.com/AVbin/AVbin/downloads http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin"""
def __init__(self, file_path):
"""先尝试相对路径, 再尝试绝对路径载入."""
<|body_0|>
def play(self):
"""如有效可播放."""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WarnMedia:
"""声音警报. https://github.com/AVbin/AVbin/downloads http://stackoverflow.com/questions/10302873/python-pyglet-avbin-how-to-install-avbin"""
def __init__(self, file_path):
"""先尝试相对路径, 再尝试绝对路径载入."""
try:
self.music = pyglet.resource.media(file_path)
except pygle... | the_stack_v2_python_sparse | discuzx_tools/libs/common/warning.py | BabyMelvin/discuzx-tools | train | 0 |
6e795a1fedc2229d4f35b85bab6defca94cecb4b | [
"stub = reco_pb2_grpc.RecoServiceStub(current_app.rpc_reco)\nrequest = reco_pb2.RecoRequest()\nrequest.user_id = str(g.user_id) if g.user_id else 'anomy'\nrequest.channel = channel_id\nrequest.time_stamp = timestamp\nrequest.article_num = article_num\nreturn stub.article_recommend(request)",
"qs_parser = reqparse... | <|body_start_0|>
stub = reco_pb2_grpc.RecoServiceStub(current_app.rpc_reco)
request = reco_pb2.RecoRequest()
request.user_id = str(g.user_id) if g.user_id else 'anomy'
request.channel = channel_id
request.time_stamp = timestamp
request.article_num = article_num
re... | 获取文章列表数据 | ArticleListResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleListResource:
"""获取文章列表数据"""
def __get_article_recommends(self, channel_id, timestamp, article_num):
"""获取推荐的文章的方法 1. 创建rpc连接对象 app.rpc_reco = grpc.insecure_channel('127.0.0.0:8888') 2. 根据rpc连接对象创建rpc解析助手 stub= reco_pb2_grpc.RecoServiceStub(rpc连接对象) 2. 创建rpc请求对象 request = reco... | stack_v2_sparse_classes_75kplus_train_065355 | 4,054 | permissive | [
{
"docstring": "获取推荐的文章的方法 1. 创建rpc连接对象 app.rpc_reco = grpc.insecure_channel('127.0.0.0:8888') 2. 根据rpc连接对象创建rpc解析助手 stub= reco_pb2_grpc.RecoServiceStub(rpc连接对象) 2. 创建rpc请求对象 request = reco_pb2.RecoRequest() 3. 包装rpc请求数据 4. 根据解析助手调用rpc远程服务接口的函数 stub.article_commend(request) :param channel_id: :param timestamp: ... | 2 | stack_v2_sparse_classes_30k_val_000528 | Implement the Python class `ArticleListResource` described below.
Class description:
获取文章列表数据
Method signatures and docstrings:
- def __get_article_recommends(self, channel_id, timestamp, article_num): 获取推荐的文章的方法 1. 创建rpc连接对象 app.rpc_reco = grpc.insecure_channel('127.0.0.0:8888') 2. 根据rpc连接对象创建rpc解析助手 stub= reco_pb2_... | Implement the Python class `ArticleListResource` described below.
Class description:
获取文章列表数据
Method signatures and docstrings:
- def __get_article_recommends(self, channel_id, timestamp, article_num): 获取推荐的文章的方法 1. 创建rpc连接对象 app.rpc_reco = grpc.insecure_channel('127.0.0.0:8888') 2. 根据rpc连接对象创建rpc解析助手 stub= reco_pb2_... | dbdf0f3790d0dc5f233b4c9e7bd69927bbfff28d | <|skeleton|>
class ArticleListResource:
"""获取文章列表数据"""
def __get_article_recommends(self, channel_id, timestamp, article_num):
"""获取推荐的文章的方法 1. 创建rpc连接对象 app.rpc_reco = grpc.insecure_channel('127.0.0.0:8888') 2. 根据rpc连接对象创建rpc解析助手 stub= reco_pb2_grpc.RecoServiceStub(rpc连接对象) 2. 创建rpc请求对象 request = reco... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticleListResource:
"""获取文章列表数据"""
def __get_article_recommends(self, channel_id, timestamp, article_num):
"""获取推荐的文章的方法 1. 创建rpc连接对象 app.rpc_reco = grpc.insecure_channel('127.0.0.0:8888') 2. 根据rpc连接对象创建rpc解析助手 stub= reco_pb2_grpc.RecoServiceStub(rpc连接对象) 2. 创建rpc请求对象 request = reco_pb2.RecoRequ... | the_stack_v2_python_sparse | toutiao/resources/news/article.py | qls7/xinwen | train | 0 |
6a94022974c94a49a9de55c27c5f8ed3408cd44f | [
"candidates.sort()\n\ndef helper(candidates, target, start, arr, curr_sum, result):\n if curr_sum == target:\n result.append(arr[:])\n return\n if curr_sum > target:\n return\n for i in range(start, len(candidates)):\n arr.append(candidates[i])\n curr_sum += candidates[i]... | <|body_start_0|>
candidates.sort()
def helper(candidates, target, start, arr, curr_sum, result):
if curr_sum == target:
result.append(arr[:])
return
if curr_sum > target:
return
for i in range(start, len(candidates)):
... | SolutionLeetCode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolutionLeetCode:
def combinationSum(self, candidates, target):
"""Recursive backtracking algorithm."""
<|body_0|>
def combinationSum(self, candidates, target):
"""Same as above but instead of keeping track of a new variable with current sum, we can just substract cu... | stack_v2_sparse_classes_75kplus_train_065356 | 3,383 | no_license | [
{
"docstring": "Recursive backtracking algorithm.",
"name": "combinationSum",
"signature": "def combinationSum(self, candidates, target)"
},
{
"docstring": "Same as above but instead of keeping track of a new variable with current sum, we can just substract current value from target. If target e... | 2 | stack_v2_sparse_classes_30k_test_001318 | Implement the Python class `SolutionLeetCode` described below.
Class description:
Implement the SolutionLeetCode class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): Recursive backtracking algorithm.
- def combinationSum(self, candidates, target): Same as above but instead of keepi... | Implement the Python class `SolutionLeetCode` described below.
Class description:
Implement the SolutionLeetCode class.
Method signatures and docstrings:
- def combinationSum(self, candidates, target): Recursive backtracking algorithm.
- def combinationSum(self, candidates, target): Same as above but instead of keepi... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class SolutionLeetCode:
def combinationSum(self, candidates, target):
"""Recursive backtracking algorithm."""
<|body_0|>
def combinationSum(self, candidates, target):
"""Same as above but instead of keeping track of a new variable with current sum, we can just substract cu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SolutionLeetCode:
def combinationSum(self, candidates, target):
"""Recursive backtracking algorithm."""
candidates.sort()
def helper(candidates, target, start, arr, curr_sum, result):
if curr_sum == target:
result.append(arr[:])
return
... | the_stack_v2_python_sparse | Backtracking/combination_sum.py | vladn90/Algorithms | train | 0 | |
1a446bd7e2493192b832bcd6e0fb0e3d76b9e624 | [
"super(GRU, self).__init__()\nself.device = device\nself.hidden_dim = hidden_dim\nself.tagset_size = tagset_size\nself.embedding_dim = w2v_weights.shape[1]\nself.w2v_weights = w2v_weights\nself.c2v_weights = c2v_weights\nself.bidirectional = bidirectional\nself.pad_word_length = pad_word_length\nself.bidirectional ... | <|body_start_0|>
super(GRU, self).__init__()
self.device = device
self.hidden_dim = hidden_dim
self.tagset_size = tagset_size
self.embedding_dim = w2v_weights.shape[1]
self.w2v_weights = w2v_weights
self.c2v_weights = c2v_weights
self.bidirectional = bidir... | GRU | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GRU:
def __init__(self, device, w2v_weights, hidden_dim, tagset_size, drop_rate, bidirectional=False, freeze=True, embedding_norm=10.0, c2v_weights=None, pad_word_length=16):
""":param device: Device to which to map tensors (GPU or CPU). :param w2v_weights: Matrix of w2v w2v_weights, ith... | stack_v2_sparse_classes_75kplus_train_065357 | 7,568 | permissive | [
{
"docstring": ":param device: Device to which to map tensors (GPU or CPU). :param w2v_weights: Matrix of w2v w2v_weights, ith row contains the embedding for the word mapped to the ith index, the last row should correspond to the padding token, <padding>. :param hidden_dim Size of the hidden dimension of the re... | 3 | stack_v2_sparse_classes_30k_val_001933 | Implement the Python class `GRU` described below.
Class description:
Implement the GRU class.
Method signatures and docstrings:
- def __init__(self, device, w2v_weights, hidden_dim, tagset_size, drop_rate, bidirectional=False, freeze=True, embedding_norm=10.0, c2v_weights=None, pad_word_length=16): :param device: Dev... | Implement the Python class `GRU` described below.
Class description:
Implement the GRU class.
Method signatures and docstrings:
- def __init__(self, device, w2v_weights, hidden_dim, tagset_size, drop_rate, bidirectional=False, freeze=True, embedding_norm=10.0, c2v_weights=None, pad_word_length=16): :param device: Dev... | 6b2d3360cb21348b83063eac35acb8a2af95ed75 | <|skeleton|>
class GRU:
def __init__(self, device, w2v_weights, hidden_dim, tagset_size, drop_rate, bidirectional=False, freeze=True, embedding_norm=10.0, c2v_weights=None, pad_word_length=16):
""":param device: Device to which to map tensors (GPU or CPU). :param w2v_weights: Matrix of w2v w2v_weights, ith... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GRU:
def __init__(self, device, w2v_weights, hidden_dim, tagset_size, drop_rate, bidirectional=False, freeze=True, embedding_norm=10.0, c2v_weights=None, pad_word_length=16):
""":param device: Device to which to map tensors (GPU or CPU). :param w2v_weights: Matrix of w2v w2v_weights, ith row contains ... | the_stack_v2_python_sparse | src/models/gru.py | geektoni/concept-tagging-with-neural-networks | train | 0 | |
90dd5d969a8567b7e2750ce1d1897e14dcd6ca93 | [
"size = len(nums)\nself.next = [0] * (size + 1)\nself.head = collections.defaultdict(int)\nfor i, n in enumerate(nums):\n self.next[i + 1] = self.head[n]\n self.head[n] = i + 1",
"cnt = 0\nidx = self.head[target]\nwhile idx > 0:\n cnt += 1\n idx = self.next[idx]\nc = int(random.random() * cnt)\nidx = ... | <|body_start_0|>
size = len(nums)
self.next = [0] * (size + 1)
self.head = collections.defaultdict(int)
for i, n in enumerate(nums):
self.next[i + 1] = self.head[n]
self.head[n] = i + 1
<|end_body_0|>
<|body_start_1|>
cnt = 0
idx = self.head[targe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
size = len(nums)
self.next = [0] * (size ... | stack_v2_sparse_classes_75kplus_train_065358 | 4,817 | no_license | [
{
"docstring": ":type nums: List[int] :type numsSize: int",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type target: int :rtype: int",
"name": "pick",
"signature": "def pick(self, target)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001397 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type numsSize: int
- def pick(self, target): :type target: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int] :type numsSize: int
- def pick(self, target): :type target: int :rtype: int
<|skeleton|>
class Solution:
def __init__(self, ... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
<|body_0|>
def pick(self, target):
""":type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, nums):
""":type nums: List[int] :type numsSize: int"""
size = len(nums)
self.next = [0] * (size + 1)
self.head = collections.defaultdict(int)
for i, n in enumerate(nums):
self.next[i + 1] = self.head[n]
self.head[n] =... | the_stack_v2_python_sparse | leetcode_python/Math/random-pick-index.py | yennanliu/CS_basics | train | 64 | |
cb00cb63025a73572505bce255b6a3b6865086ba | [
"super(VectorNetWithPredicting, self).__init__()\nself.device = device\nself.vectorNet = VectorNet(feature_length=feature_length)\nself.timeStamp = timeStampNumber\nself.hidden_size = 64\nself.car_feature = self.vectorNet.pLen\nself.trajDecoder = nn.Sequential(nn.Linear(self.vectorNet.pLen + self.car_feature, self.... | <|body_start_0|>
super(VectorNetWithPredicting, self).__init__()
self.device = device
self.vectorNet = VectorNet(feature_length=feature_length)
self.timeStamp = timeStampNumber
self.hidden_size = 64
self.car_feature = self.vectorNet.pLen
self.trajDecoder = nn.Sequ... | A class for packaging the VectorNet and future trajectory prediction module. The future trajectory prediction module uses MLP without ReLu(because we hope the coordinate of trajectory can be negative). | VectorNetWithPredicting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VectorNetWithPredicting:
"""A class for packaging the VectorNet and future trajectory prediction module. The future trajectory prediction module uses MLP without ReLu(because we hope the coordinate of trajectory can be negative)."""
def __init__(self, feature_length, timeStampNumber, device=... | stack_v2_sparse_classes_75kplus_train_065359 | 9,585 | no_license | [
{
"docstring": "Construct a VectorNet with predicting. :param feature_length: same as VectorNet. :param timeStampNumber: the length of time stamp for predicting the future trajectory.",
"name": "__init__",
"signature": "def __init__(self, feature_length, timeStampNumber, device='cuda:0')"
},
{
"... | 2 | stack_v2_sparse_classes_30k_train_043511 | Implement the Python class `VectorNetWithPredicting` described below.
Class description:
A class for packaging the VectorNet and future trajectory prediction module. The future trajectory prediction module uses MLP without ReLu(because we hope the coordinate of trajectory can be negative).
Method signatures and docst... | Implement the Python class `VectorNetWithPredicting` described below.
Class description:
A class for packaging the VectorNet and future trajectory prediction module. The future trajectory prediction module uses MLP without ReLu(because we hope the coordinate of trajectory can be negative).
Method signatures and docst... | 0a314f7bdfc6db0247c92bc2c5c3806fdd18b885 | <|skeleton|>
class VectorNetWithPredicting:
"""A class for packaging the VectorNet and future trajectory prediction module. The future trajectory prediction module uses MLP without ReLu(because we hope the coordinate of trajectory can be negative)."""
def __init__(self, feature_length, timeStampNumber, device=... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VectorNetWithPredicting:
"""A class for packaging the VectorNet and future trajectory prediction module. The future trajectory prediction module uses MLP without ReLu(because we hope the coordinate of trajectory can be negative)."""
def __init__(self, feature_length, timeStampNumber, device='cuda:0'):
... | the_stack_v2_python_sparse | code/vector_net/vector_net.py | JieFeng-cse/dynamic_driving | train | 1 |
bb187c3336009a125629fb314577f736a3e265d1 | [
"self.neville = User(username='nevooronni')\nself.neville.save()\nself.chelsea = User(username='chelsea')\nself.chelsea.save()\nself.new_profile = Profile(user=self.neville, bio='bla bla blab bla')\nself.follow = Follow(user=self.neville, profile=self.new_profile)\nself.assertTrue(isinstance(self.follow, Follow))",... | <|body_start_0|>
self.neville = User(username='nevooronni')
self.neville.save()
self.chelsea = User(username='chelsea')
self.chelsea.save()
self.new_profile = Profile(user=self.neville, bio='bla bla blab bla')
self.follow = Follow(user=self.neville, profile=self.new_profi... | test the follow class | FollowTestClass | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowTestClass:
"""test the follow class"""
def test_instance(self):
"""tests to see if it was instantiated properly"""
<|body_0|>
def test_retrieve_following(self):
"""test retrieve_following method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_065360 | 4,892 | permissive | [
{
"docstring": "tests to see if it was instantiated properly",
"name": "test_instance",
"signature": "def test_instance(self)"
},
{
"docstring": "test retrieve_following method",
"name": "test_retrieve_following",
"signature": "def test_retrieve_following(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050759 | Implement the Python class `FollowTestClass` described below.
Class description:
test the follow class
Method signatures and docstrings:
- def test_instance(self): tests to see if it was instantiated properly
- def test_retrieve_following(self): test retrieve_following method | Implement the Python class `FollowTestClass` described below.
Class description:
test the follow class
Method signatures and docstrings:
- def test_instance(self): tests to see if it was instantiated properly
- def test_retrieve_following(self): test retrieve_following method
<|skeleton|>
class FollowTestClass:
... | 1640dd4997b94204376fbb25d6987033073b7612 | <|skeleton|>
class FollowTestClass:
"""test the follow class"""
def test_instance(self):
"""tests to see if it was instantiated properly"""
<|body_0|>
def test_retrieve_following(self):
"""test retrieve_following method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FollowTestClass:
"""test the follow class"""
def test_instance(self):
"""tests to see if it was instantiated properly"""
self.neville = User(username='nevooronni')
self.neville.save()
self.chelsea = User(username='chelsea')
self.chelsea.save()
self.new_prof... | the_stack_v2_python_sparse | collabstudio/tests.py | nevooronni/collabstudio | train | 1 |
3214f2afe63d3e9f99ce4956357f2b9d65d1b56d | [
"n_total = len(full_list)\noffset = int(n_total * ratio)\nif n_total == 0 or offset < 1:\n return ([], full_list)\nsublist_1 = full_list[:offset]\nsublist_2 = full_list[offset:]\nreturn (sublist_1, sublist_2)",
"if div_nums == [] or div_nums is None:\n div_nums = [6, 2, 2]\nassert isinstance(src_dataset, Da... | <|body_start_0|>
n_total = len(full_list)
offset = int(n_total * ratio)
if n_total == 0 or offset < 1:
return ([], full_list)
sublist_1 = full_list[:offset]
sublist_2 = full_list[offset:]
return (sublist_1, sublist_2)
<|end_body_0|>
<|body_start_1|>
i... | Spliter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spliter:
def __split(self, full_list, ratio):
"""私有方法,功能是将一个列表按ration切分成两个子列表 :param full_list: :param ratio: :return:"""
<|body_0|>
def split_dataset(self, src_dataset, div_nums=None):
"""将一个dataset对象,按分割比例,拆分为3个dataset对象 :param src_dataset: 待拆分数据集对象 :param div_nums... | stack_v2_sparse_classes_75kplus_train_065361 | 2,083 | permissive | [
{
"docstring": "私有方法,功能是将一个列表按ration切分成两个子列表 :param full_list: :param ratio: :return:",
"name": "__split",
"signature": "def __split(self, full_list, ratio)"
},
{
"docstring": "将一个dataset对象,按分割比例,拆分为3个dataset对象 :param src_dataset: 待拆分数据集对象 :param div_nums: 分割比例数组,数组中有3个数字代表比例 :return: 拆分后的3个data... | 2 | stack_v2_sparse_classes_30k_train_033936 | Implement the Python class `Spliter` described below.
Class description:
Implement the Spliter class.
Method signatures and docstrings:
- def __split(self, full_list, ratio): 私有方法,功能是将一个列表按ration切分成两个子列表 :param full_list: :param ratio: :return:
- def split_dataset(self, src_dataset, div_nums=None): 将一个dataset对象,按分割比例... | Implement the Python class `Spliter` described below.
Class description:
Implement the Spliter class.
Method signatures and docstrings:
- def __split(self, full_list, ratio): 私有方法,功能是将一个列表按ration切分成两个子列表 :param full_list: :param ratio: :return:
- def split_dataset(self, src_dataset, div_nums=None): 将一个dataset对象,按分割比例... | 48b63556b2d12526f82f2b307f15cd4d640a6520 | <|skeleton|>
class Spliter:
def __split(self, full_list, ratio):
"""私有方法,功能是将一个列表按ration切分成两个子列表 :param full_list: :param ratio: :return:"""
<|body_0|>
def split_dataset(self, src_dataset, div_nums=None):
"""将一个dataset对象,按分割比例,拆分为3个dataset对象 :param src_dataset: 待拆分数据集对象 :param div_nums... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Spliter:
def __split(self, full_list, ratio):
"""私有方法,功能是将一个列表按ration切分成两个子列表 :param full_list: :param ratio: :return:"""
n_total = len(full_list)
offset = int(n_total * ratio)
if n_total == 0 or offset < 1:
return ([], full_list)
sublist_1 = full_list[:offs... | the_stack_v2_python_sparse | dataset/spliter.py | mottled233/MRC_FastFrame | train | 3 | |
cbad5f2dcc9b7c4552470abe8d0ea8925579f1eb | [
"if not buf or not skt:\n raise ValueError('<send_bytes> invalid socket descriptor or buf')\nif timeout:\n skt.settimeout(timeout)\nelse:\n skt.settimeout(None)\nlength = len(buf)\nsent_total = 0\nwhile sent_total < length:\n sent = skt.send(buf)\n if not sent:\n raise IOError('<send_bytes> co... | <|body_start_0|>
if not buf or not skt:
raise ValueError('<send_bytes> invalid socket descriptor or buf')
if timeout:
skt.settimeout(timeout)
else:
skt.settimeout(None)
length = len(buf)
sent_total = 0
while sent_total < length:
... | SocketHelper | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SocketHelper:
def send_bytes(skt, buf, timeout=0):
"""Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception"""
<|body_0|>
def recv_bytes(skt, length, timeout=0):
"""Receive bytes from the socket @raise ValueError, IOError, socket.timeout, Exc... | stack_v2_sparse_classes_75kplus_train_065362 | 2,505 | permissive | [
{
"docstring": "Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception",
"name": "send_bytes",
"signature": "def send_bytes(skt, buf, timeout=0)"
},
{
"docstring": "Receive bytes from the socket @raise ValueError, IOError, socket.timeout, Exception",
"name": "recv_byt... | 4 | stack_v2_sparse_classes_30k_test_000610 | Implement the Python class `SocketHelper` described below.
Class description:
Implement the SocketHelper class.
Method signatures and docstrings:
- def send_bytes(skt, buf, timeout=0): Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception
- def recv_bytes(skt, length, timeout=0): Receive byte... | Implement the Python class `SocketHelper` described below.
Class description:
Implement the SocketHelper class.
Method signatures and docstrings:
- def send_bytes(skt, buf, timeout=0): Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception
- def recv_bytes(skt, length, timeout=0): Receive byte... | 9d8220a0925327bddf0e10887e22b57c5d6adb37 | <|skeleton|>
class SocketHelper:
def send_bytes(skt, buf, timeout=0):
"""Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception"""
<|body_0|>
def recv_bytes(skt, length, timeout=0):
"""Receive bytes from the socket @raise ValueError, IOError, socket.timeout, Exc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SocketHelper:
def send_bytes(skt, buf, timeout=0):
"""Send bytes to the socket @raise ValueError, IOError, socket.timeout, Exception"""
if not buf or not skt:
raise ValueError('<send_bytes> invalid socket descriptor or buf')
if timeout:
skt.settimeout(timeout)
... | the_stack_v2_python_sparse | lib/perf_engines/sys_helper.py | couchbase/testrunner | train | 18 | |
93b5d9b23ed103f394252290a070ec27f765d669 | [
"self.log = logging.getLogger('info')\nself.log.addHandler(logging.NullHandler())\nmsg = 'Initializing object with input options: data={data}, timestamp={timestamp}'\nmsg = msg.format(data=data, timestamp=timestamp)\nself.log.debug(msg)\nself.data = data\nif not timestamp:\n timestamp = int(time.time())\n msg... | <|body_start_0|>
self.log = logging.getLogger('info')
self.log.addHandler(logging.NullHandler())
msg = 'Initializing object with input options: data={data}, timestamp={timestamp}'
msg = msg.format(data=data, timestamp=timestamp)
self.log.debug(msg)
self.data = data
... | _Base | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Base:
def __init__(self, data, timestamp=None):
""":param data: the data to be recorded :param timestamp: the time when this object was created"""
<|body_0|>
def get(self, *key_l):
"""returns the data hosted by the Info object in the tree structure pointed by all ke... | stack_v2_sparse_classes_75kplus_train_065363 | 28,092 | permissive | [
{
"docstring": ":param data: the data to be recorded :param timestamp: the time when this object was created",
"name": "__init__",
"signature": "def __init__(self, data, timestamp=None)"
},
{
"docstring": "returns the data hosted by the Info object in the tree structure pointed by all keys The o... | 2 | null | Implement the Python class `_Base` described below.
Class description:
Implement the _Base class.
Method signatures and docstrings:
- def __init__(self, data, timestamp=None): :param data: the data to be recorded :param timestamp: the time when this object was created
- def get(self, *key_l): returns the data hosted ... | Implement the Python class `_Base` described below.
Class description:
Implement the _Base class.
Method signatures and docstrings:
- def __init__(self, data, timestamp=None): :param data: the data to be recorded :param timestamp: the time when this object was created
- def get(self, *key_l): returns the data hosted ... | 9d0d3890b38df2573045111182e45117ed232a46 | <|skeleton|>
class _Base:
def __init__(self, data, timestamp=None):
""":param data: the data to be recorded :param timestamp: the time when this object was created"""
<|body_0|>
def get(self, *key_l):
"""returns the data hosted by the Info object in the tree structure pointed by all ke... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Base:
def __init__(self, data, timestamp=None):
""":param data: the data to be recorded :param timestamp: the time when this object was created"""
self.log = logging.getLogger('info')
self.log.addHandler(logging.NullHandler())
msg = 'Initializing object with input options: dat... | the_stack_v2_python_sparse | attic/info2.py | PanDAWMS/autopyfactory | train | 2 | |
a86ad0c5bd0dc696ac6657777d322a54e00a15fa | [
"if self._facets is Undefined:\n self._facets = self.normalize_facets(self.facets)\nreturn self._facets",
"facets = OrderedDict()\nraw_facets = self.request.GET.get(self.facets_kwarg)\nif raw_facets:\n for raw_facet in raw_facets.split(','):\n facet = raw_facet.split(':', 1)\n if len(facet) ==... | <|body_start_0|>
if self._facets is Undefined:
self._facets = self.normalize_facets(self.facets)
return self._facets
<|end_body_0|>
<|body_start_1|>
facets = OrderedDict()
raw_facets = self.request.GET.get(self.facets_kwarg)
if raw_facets:
for raw_facet i... | FacetedSearchView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FacetedSearchView:
def get_facets(self):
"""Returns a list containing all available facets."""
<|body_0|>
def get_selected_facets(self):
"""Returns a list of facets which the user has selected."""
<|body_1|>
def normalize_facets(self, facets):
""... | stack_v2_sparse_classes_75kplus_train_065364 | 14,538 | permissive | [
{
"docstring": "Returns a list containing all available facets.",
"name": "get_facets",
"signature": "def get_facets(self)"
},
{
"docstring": "Returns a list of facets which the user has selected.",
"name": "get_selected_facets",
"signature": "def get_selected_facets(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_046540 | Implement the Python class `FacetedSearchView` described below.
Class description:
Implement the FacetedSearchView class.
Method signatures and docstrings:
- def get_facets(self): Returns a list containing all available facets.
- def get_selected_facets(self): Returns a list of facets which the user has selected.
- d... | Implement the Python class `FacetedSearchView` described below.
Class description:
Implement the FacetedSearchView class.
Method signatures and docstrings:
- def get_facets(self): Returns a list containing all available facets.
- def get_selected_facets(self): Returns a list of facets which the user has selected.
- d... | 1ef9a42d4eaa70d9b3e6e7fa519396c1e1174fcb | <|skeleton|>
class FacetedSearchView:
def get_facets(self):
"""Returns a list containing all available facets."""
<|body_0|>
def get_selected_facets(self):
"""Returns a list of facets which the user has selected."""
<|body_1|>
def normalize_facets(self, facets):
""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FacetedSearchView:
def get_facets(self):
"""Returns a list containing all available facets."""
if self._facets is Undefined:
self._facets = self.normalize_facets(self.facets)
return self._facets
def get_selected_facets(self):
"""Returns a list of facets which t... | the_stack_v2_python_sparse | yepes/views/search.py | samuelmaudo/yepes | train | 0 | |
e47af7328342db2eb16daff742616551d64b3426 | [
"self.df_aux = df_aux\nself.df_canon = df_canon\nself.aux_suffix = aux_suffix\nself.canon_suffix = canon_suffix\nself.false_overwrite_canon_map = false_overwrite_canon_map\nself.manual_map = manual_map\nself.iso_finder = None\nself.aux_to_canon_map = None",
"if map is None:\n map = dict()\nreturn df.assign(Fig... | <|body_start_0|>
self.df_aux = df_aux
self.df_canon = df_canon
self.aux_suffix = aux_suffix
self.canon_suffix = canon_suffix
self.false_overwrite_canon_map = false_overwrite_canon_map
self.manual_map = manual_map
self.iso_finder = None
self.aux_to_canon_ma... | class for finding the mapping between two sets of IDs in order to join two datasets. Provides a handy wrapper around the IsomorphismFinder class, which is used to find the mapping. Note that MapFinder.aux_to_canon_map maps (FighterID_aux, OpponentID_aux, Date) -> (FighterID_canon, OpponentID_canon, Date) whereas Isomor... | MapFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapFinder:
"""class for finding the mapping between two sets of IDs in order to join two datasets. Provides a handy wrapper around the IsomorphismFinder class, which is used to find the mapping. Note that MapFinder.aux_to_canon_map maps (FighterID_aux, OpponentID_aux, Date) -> (FighterID_canon, O... | stack_v2_sparse_classes_75kplus_train_065365 | 40,328 | no_license | [
{
"docstring": "df_aux: auxiliary dataframe df_canon: canonical dataframe aux_suffix: suffix to add to aux ID columns canon_suffix: suffix to add to canon ID columns false_overwrite_canon_map: overwrite certain IDs in the canonical dataframe manual_map: dict of manual mappings",
"name": "__init__",
"sig... | 3 | null | Implement the Python class `MapFinder` described below.
Class description:
class for finding the mapping between two sets of IDs in order to join two datasets. Provides a handy wrapper around the IsomorphismFinder class, which is used to find the mapping. Note that MapFinder.aux_to_canon_map maps (FighterID_aux, Oppon... | Implement the Python class `MapFinder` described below.
Class description:
class for finding the mapping between two sets of IDs in order to join two datasets. Provides a handy wrapper around the IsomorphismFinder class, which is used to find the mapping. Note that MapFinder.aux_to_canon_map maps (FighterID_aux, Oppon... | a2b51c22914c4ae0d4ee4e8220709da82cc42489 | <|skeleton|>
class MapFinder:
"""class for finding the mapping between two sets of IDs in order to join two datasets. Provides a handy wrapper around the IsomorphismFinder class, which is used to find the mapping. Note that MapFinder.aux_to_canon_map maps (FighterID_aux, OpponentID_aux, Date) -> (FighterID_canon, O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MapFinder:
"""class for finding the mapping between two sets of IDs in order to join two datasets. Provides a handy wrapper around the IsomorphismFinder class, which is used to find the mapping. Note that MapFinder.aux_to_canon_map maps (FighterID_aux, OpponentID_aux, Date) -> (FighterID_canon, OpponentID_can... | the_stack_v2_python_sparse | wrangle/join_datasets.py | John-Curcio/sports | train | 0 |
0e75294380d0bc2bb9663169123bb09648ec7a93 | [
"item = get_object_or_404(Item, pk=kwargs['item_id'])\ncontext = {}\ncontext['form'] = ItemForm(instance=item)\nreturn render(self.request, self.template_name, context)",
"item = get_object_or_404(Item, pk=kwargs['item_id'])\nform = ItemForm(self.request.POST, instance=item)\nif form.is_valid():\n item = form.... | <|body_start_0|>
item = get_object_or_404(Item, pk=kwargs['item_id'])
context = {}
context['form'] = ItemForm(instance=item)
return render(self.request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
item = get_object_or_404(Item, pk=kwargs['item_id'])
form... | Editing invoice | ItemEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItemEditView:
"""Editing invoice"""
def get(self, *args, **kwargs):
"""Display invoice form"""
<|body_0|>
def post(self, *args, **kwargs):
"""Get filled invoice form and create invoice"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
item = get_o... | stack_v2_sparse_classes_75kplus_train_065366 | 4,064 | no_license | [
{
"docstring": "Display invoice form",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Get filled invoice form and create invoice",
"name": "post",
"signature": "def post(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023109 | Implement the Python class `ItemEditView` described below.
Class description:
Editing invoice
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display invoice form
- def post(self, *args, **kwargs): Get filled invoice form and create invoice | Implement the Python class `ItemEditView` described below.
Class description:
Editing invoice
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display invoice form
- def post(self, *args, **kwargs): Get filled invoice form and create invoice
<|skeleton|>
class ItemEditView:
"""Editing invoice"... | 17615ea9bfb1edebe41d60dbf2e977f0018d5339 | <|skeleton|>
class ItemEditView:
"""Editing invoice"""
def get(self, *args, **kwargs):
"""Display invoice form"""
<|body_0|>
def post(self, *args, **kwargs):
"""Get filled invoice form and create invoice"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ItemEditView:
"""Editing invoice"""
def get(self, *args, **kwargs):
"""Display invoice form"""
item = get_object_or_404(Item, pk=kwargs['item_id'])
context = {}
context['form'] = ItemForm(instance=item)
return render(self.request, self.template_name, context)
... | the_stack_v2_python_sparse | items/views.py | Swiftkind/invoice | train | 0 |
08bdd714a00dcdf3a5409aad75e88f5c96977ca6 | [
"Equipment.__init__(self)\npygame.sprite.Sprite.__init__(self)\nself.sprites = {}\nself.channelList = {}\nself.currentVolume = 0",
"self.screen = screen\nself.channelList = {'1': ChannelTV('1'), '2': ChannelTV('2'), '3': ChannelTV('3')}\nself.currentChannelPlay = self.channelList.get('1')\nself.sprites['tv_off'] ... | <|body_start_0|>
Equipment.__init__(self)
pygame.sprite.Sprite.__init__(self)
self.sprites = {}
self.channelList = {}
self.currentVolume = 0
<|end_body_0|>
<|body_start_1|>
self.screen = screen
self.channelList = {'1': ChannelTV('1'), '2': ChannelTV('2'), '3': Ch... | A classe TV é uma classe que vai representar um aparelho de TV do mundo real :version: 224 :author: Felipe Miranda | TV | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TV:
"""A classe TV é uma classe que vai representar um aparelho de TV do mundo real :version: 224 :author: Felipe Miranda"""
def __init__(self):
"""Construtor da classe"""
<|body_0|>
def load(self, screen):
"""Método que faz o carregamento das imagens do aparelho... | stack_v2_sparse_classes_75kplus_train_065367 | 2,814 | permissive | [
{
"docstring": "Construtor da classe",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Método que faz o carregamento das imagens do aparelho TV :Param screen: Tela :Type screen: Screen Pygame",
"name": "load",
"signature": "def load(self, screen)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_054247 | Implement the Python class `TV` described below.
Class description:
A classe TV é uma classe que vai representar um aparelho de TV do mundo real :version: 224 :author: Felipe Miranda
Method signatures and docstrings:
- def __init__(self): Construtor da classe
- def load(self, screen): Método que faz o carregamento da... | Implement the Python class `TV` described below.
Class description:
A classe TV é uma classe que vai representar um aparelho de TV do mundo real :version: 224 :author: Felipe Miranda
Method signatures and docstrings:
- def __init__(self): Construtor da classe
- def load(self, screen): Método que faz o carregamento da... | 491487411bc63db497943fac78b810ac7e37ef44 | <|skeleton|>
class TV:
"""A classe TV é uma classe que vai representar um aparelho de TV do mundo real :version: 224 :author: Felipe Miranda"""
def __init__(self):
"""Construtor da classe"""
<|body_0|>
def load(self, screen):
"""Método que faz o carregamento das imagens do aparelho... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TV:
"""A classe TV é uma classe que vai representar um aparelho de TV do mundo real :version: 224 :author: Felipe Miranda"""
def __init__(self):
"""Construtor da classe"""
Equipment.__init__(self)
pygame.sprite.Sprite.__init__(self)
self.sprites = {}
self.channelLi... | the_stack_v2_python_sparse | Python_Controle_Multimidia_Universal/trunk/Comodo/TV.py | felipelindemberg/ControleMultimidiaUniversal | train | 1 |
f33f27ef0913bd9cccf0bad5f0936e39d5243f70 | [
"input_text = '[[foo]\\n bar] [[baz]]'\noutput = singhtext.text_to_html(input_text)\nassert ('[[' in output) == False, 'Multi-line links fail.'",
"input_text = '\\n$foo\\n== bar ==\\nbaz\\n'\ncorrect_output = '<h2> bar </h2>\\n<p>baz</p>'\nactual_output = singhtext.text_to_html(input_text)\nassert 'bar' in actual... | <|body_start_0|>
input_text = '[[foo]\n bar] [[baz]]'
output = singhtext.text_to_html(input_text)
assert ('[[' in output) == False, 'Multi-line links fail.'
<|end_body_0|>
<|body_start_1|>
input_text = '\n$foo\n== bar ==\nbaz\n'
correct_output = '<h2> bar </h2>\n<p>baz</p>'
... | Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers? | StringMatchingTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringMatchingTests:
"""Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?"""
def testMultilineLinks(self):
"""Test links that span multiple lines, another way."""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_065368 | 3,509 | no_license | [
{
"docstring": "Test links that span multiple lines, another way.",
"name": "testMultilineLinks",
"signature": "def testMultilineLinks(self)"
},
{
"docstring": "Make sure special lines don't interfere with headers.",
"name": "testSpecialLineInterference",
"signature": "def testSpecialLin... | 4 | stack_v2_sparse_classes_30k_train_000888 | Implement the Python class `StringMatchingTests` described below.
Class description:
Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?
Method signatures and docstrings:
- def testMultilineLinks(self): Test links that span ... | Implement the Python class `StringMatchingTests` described below.
Class description:
Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?
Method signatures and docstrings:
- def testMultilineLinks(self): Test links that span ... | da65d948b346d3f455e79168a8753b2b16d8fc5f | <|skeleton|>
class StringMatchingTests:
"""Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?"""
def testMultilineLinks(self):
"""Test links that span multiple lines, another way."""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StringMatchingTests:
"""Test SinghText HTML generation. testMultilineLinks - links that span multiple lines testSpecialLineInterference - $special intefere with headers?"""
def testMultilineLinks(self):
"""Test links that span multiple lines, another way."""
input_text = '[[foo]\n bar] [[... | the_stack_v2_python_sparse | other/singhtext/test.py | BackupTheBerlios/onebigsoup-svn | train | 0 |
7dc23b988c00c3cac5e7830f03507cb4eeab9307 | [
"saliency_task = model_contract_task_mapping(self.dataset_split_name, self.config, ModuleOptions(model_contract_method_name=SupportedMethod.Saliency, pipeline_index=self.mod_options.pipeline_index, indices=indices))\nresult = get_task_result(task_module=saliency_task, result_type=List[SaliencyResponse])\nreturn res... | <|body_start_0|>
saliency_task = model_contract_task_mapping(self.dataset_split_name, self.config, ModuleOptions(model_contract_method_name=SupportedMethod.Saliency, pipeline_index=self.mod_options.pipeline_index, indices=indices))
result = get_task_result(task_module=saliency_task, result_type=List[Sal... | Returns the words in an utterance with their saliency values. | TokensToWordsModule | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokensToWordsModule:
"""Returns the words in an utterance with their saliency values."""
def get_tokens_saliencies(self, indices: List[int]) -> List[SaliencyResponse]:
"""Get saliency values and tokens for the provided indices. Args: indices: Indices in the dataset_split for which to... | stack_v2_sparse_classes_75kplus_train_065369 | 3,378 | permissive | [
{
"docstring": "Get saliency values and tokens for the provided indices. Args: indices: Indices in the dataset_split for which to get saliency values and tokens. Returns: Saliency values for each token. Will be 0 if saliency maps are not available.",
"name": "get_tokens_saliencies",
"signature": "def ge... | 2 | stack_v2_sparse_classes_30k_train_030064 | Implement the Python class `TokensToWordsModule` described below.
Class description:
Returns the words in an utterance with their saliency values.
Method signatures and docstrings:
- def get_tokens_saliencies(self, indices: List[int]) -> List[SaliencyResponse]: Get saliency values and tokens for the provided indices.... | Implement the Python class `TokensToWordsModule` described below.
Class description:
Returns the words in an utterance with their saliency values.
Method signatures and docstrings:
- def get_tokens_saliencies(self, indices: List[int]) -> List[SaliencyResponse]: Get saliency values and tokens for the provided indices.... | 34081048a4de3900ca29ac0d37bce7026113382c | <|skeleton|>
class TokensToWordsModule:
"""Returns the words in an utterance with their saliency values."""
def get_tokens_saliencies(self, indices: List[int]) -> List[SaliencyResponse]:
"""Get saliency values and tokens for the provided indices. Args: indices: Indices in the dataset_split for which to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TokensToWordsModule:
"""Returns the words in an utterance with their saliency values."""
def get_tokens_saliencies(self, indices: List[int]) -> List[SaliencyResponse]:
"""Get saliency values and tokens for the provided indices. Args: indices: Indices in the dataset_split for which to get saliency... | the_stack_v2_python_sparse | azimuth/modules/word_analysis/tokens_to_words.py | ServiceNow/azimuth | train | 172 |
857000e92d7ad62ebd5760e74541e080c926b205 | [
"weightValue = {}\nfor i in range(len(weight)):\n key = weight[i]\n if key not in weightValue.keys():\n weightValue[key] = value[i]\n elif value[i] > weightValue[key]:\n weightValue[key] = value[i]\n else:\n continue\nprint('物品体积价值对应比:', weightValue, list(weightValue.items()))\nweig... | <|body_start_0|>
weightValue = {}
for i in range(len(weight)):
key = weight[i]
if key not in weightValue.keys():
weightValue[key] = value[i]
elif value[i] > weightValue[key]:
weightValue[key] = value[i]
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getdict(self, weight, value):
"""0-1背包转为完全背包问题:有限变无限"""
<|body_0|>
def BagMaxValue(self, num, WeightLimit, weight, value):
"""完全背包问题"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
weightValue = {}
for i in range(len(weight)):
... | stack_v2_sparse_classes_75kplus_train_065370 | 3,707 | no_license | [
{
"docstring": "0-1背包转为完全背包问题:有限变无限",
"name": "getdict",
"signature": "def getdict(self, weight, value)"
},
{
"docstring": "完全背包问题",
"name": "BagMaxValue",
"signature": "def BagMaxValue(self, num, WeightLimit, weight, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_023874 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getdict(self, weight, value): 0-1背包转为完全背包问题:有限变无限
- def BagMaxValue(self, num, WeightLimit, weight, value): 完全背包问题 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getdict(self, weight, value): 0-1背包转为完全背包问题:有限变无限
- def BagMaxValue(self, num, WeightLimit, weight, value): 完全背包问题
<|skeleton|>
class Solution:
def getdict(self, weight... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def getdict(self, weight, value):
"""0-1背包转为完全背包问题:有限变无限"""
<|body_0|>
def BagMaxValue(self, num, WeightLimit, weight, value):
"""完全背包问题"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getdict(self, weight, value):
"""0-1背包转为完全背包问题:有限变无限"""
weightValue = {}
for i in range(len(weight)):
key = weight[i]
if key not in weightValue.keys():
weightValue[key] = value[i]
elif value[i] > weightValue[key]:
... | the_stack_v2_python_sparse | other_code_programe/16.完全背包问题.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
ecf8987c17870b9818691d5a1434b9bb6c143743 | [
"article = Article.objects.filter(pk=article_id, is_deleted=False).first()\nif not article:\n return self.error(errorcode.MSG_NO_DATA, errorcode.NO_DATA)\nif article.status == 'draft':\n me = self.get_user_profile(request)\n if not me:\n return self.error(errorcode.MSG_LOGIN_REQUIRED, errorcode.LOGI... | <|body_start_0|>
article = Article.objects.filter(pk=article_id, is_deleted=False).first()
if not article:
return self.error(errorcode.MSG_NO_DATA, errorcode.NO_DATA)
if article.status == 'draft':
me = self.get_user_profile(request)
if not me:
... | ArticleDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArticleDetailView:
def get(self, request, article_id):
"""查看文章详情,只有作者能查看草稿"""
<|body_0|>
def delete(self, request, article_id):
"""删除文章"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
article = Article.objects.filter(pk=article_id, is_deleted=False)... | stack_v2_sparse_classes_75kplus_train_065371 | 12,861 | no_license | [
{
"docstring": "查看文章详情,只有作者能查看草稿",
"name": "get",
"signature": "def get(self, request, article_id)"
},
{
"docstring": "删除文章",
"name": "delete",
"signature": "def delete(self, request, article_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016615 | Implement the Python class `ArticleDetailView` described below.
Class description:
Implement the ArticleDetailView class.
Method signatures and docstrings:
- def get(self, request, article_id): 查看文章详情,只有作者能查看草稿
- def delete(self, request, article_id): 删除文章 | Implement the Python class `ArticleDetailView` described below.
Class description:
Implement the ArticleDetailView class.
Method signatures and docstrings:
- def get(self, request, article_id): 查看文章详情,只有作者能查看草稿
- def delete(self, request, article_id): 删除文章
<|skeleton|>
class ArticleDetailView:
def get(self, req... | 6a68fb207f43e5ed65299cc08535b35d5e934ead | <|skeleton|>
class ArticleDetailView:
def get(self, request, article_id):
"""查看文章详情,只有作者能查看草稿"""
<|body_0|>
def delete(self, request, article_id):
"""删除文章"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArticleDetailView:
def get(self, request, article_id):
"""查看文章详情,只有作者能查看草稿"""
article = Article.objects.filter(pk=article_id, is_deleted=False).first()
if not article:
return self.error(errorcode.MSG_NO_DATA, errorcode.NO_DATA)
if article.status == 'draft':
... | the_stack_v2_python_sparse | apps/articles/views.py | Slowhalfframe/fanyijiang-API | train | 0 | |
9514aac7959d4683866f58f39e280b93e6a5eba7 | [
"m = len(dungeon)\nif m <= 0:\n return 1\nn = len(dungeon[0])\ndp = [[0] * n for _ in range(m)]\ndp[-1][-1] = -min(0, dungeon[-1][-1]) + 1\nfor i in range(m - 2, -1, -1):\n dp[i][-1] = max(dp[i + 1][-1] - dungeon[i][-1], 1)\nfor j in range(n - 2, -1, -1):\n dp[-1][j] = max(dp[-1][j + 1] - dungeon[-1][j], 1... | <|body_start_0|>
m = len(dungeon)
if m <= 0:
return 1
n = len(dungeon[0])
dp = [[0] * n for _ in range(m)]
dp[-1][-1] = -min(0, dungeon[-1][-1]) + 1
for i in range(m - 2, -1, -1):
dp[i][-1] = max(dp[i + 1][-1] - dungeon[i][-1], 1)
for j in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int 55ms"""
<|body_0|>
def calculateMinimumHP1(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
def calculateMinimumHP_1(self, dungeon):... | stack_v2_sparse_classes_75kplus_train_065372 | 3,275 | no_license | [
{
"docstring": ":type dungeon: List[List[int]] :rtype: int 55ms",
"name": "calculateMinimumHP",
"signature": "def calculateMinimumHP(self, dungeon)"
},
{
"docstring": ":type dungeon: List[List[int]] :rtype: int",
"name": "calculateMinimumHP1",
"signature": "def calculateMinimumHP1(self, ... | 3 | stack_v2_sparse_classes_30k_train_031882 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int 55ms
- def calculateMinimumHP1(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculateMinimumHP(self, dungeon): :type dungeon: List[List[int]] :rtype: int 55ms
- def calculateMinimumHP1(self, dungeon): :type dungeon: List[List[int]] :rtype: int
- def ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int 55ms"""
<|body_0|>
def calculateMinimumHP1(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int"""
<|body_1|>
def calculateMinimumHP_1(self, dungeon):... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def calculateMinimumHP(self, dungeon):
""":type dungeon: List[List[int]] :rtype: int 55ms"""
m = len(dungeon)
if m <= 0:
return 1
n = len(dungeon[0])
dp = [[0] * n for _ in range(m)]
dp[-1][-1] = -min(0, dungeon[-1][-1]) + 1
for i i... | the_stack_v2_python_sparse | DungeonGame_HARD_174.py | 953250587/leetcode-python | train | 2 | |
46a1f00cfe0722687df94410b796348790d10418 | [
"MiWifiEntity.__init__(self, unique_id, description, updater, ENTITY_ID_FORMAT)\nself._attr_available: bool = updater.data.get(ATTR_STATE, False) if description.key != ATTR_STATE else True\nself._attr_is_on = updater.data.get(description.key, False)\nself._change_icon(self._attr_is_on)",
"is_available: bool = sel... | <|body_start_0|>
MiWifiEntity.__init__(self, unique_id, description, updater, ENTITY_ID_FORMAT)
self._attr_available: bool = updater.data.get(ATTR_STATE, False) if description.key != ATTR_STATE else True
self._attr_is_on = updater.data.get(description.key, False)
self._change_icon(self._... | MiWifi binary sensor entry. | MiWifiBinarySensor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MiWifiBinarySensor:
"""MiWifi binary sensor entry."""
def __init__(self, unique_id: str, description: BinarySensorEntityDescription, updater: LuciUpdater) -> None:
"""Initialize sensor. :param unique_id: str: Unique ID :param description: BinarySensorEntityDescription: BinarySensorEn... | stack_v2_sparse_classes_75kplus_train_065373 | 4,815 | no_license | [
{
"docstring": "Initialize sensor. :param unique_id: str: Unique ID :param description: BinarySensorEntityDescription: BinarySensorEntityDescription object :param updater: LuciUpdater: Luci updater object",
"name": "__init__",
"signature": "def __init__(self, unique_id: str, description: BinarySensorEnt... | 3 | stack_v2_sparse_classes_30k_train_043477 | Implement the Python class `MiWifiBinarySensor` described below.
Class description:
MiWifi binary sensor entry.
Method signatures and docstrings:
- def __init__(self, unique_id: str, description: BinarySensorEntityDescription, updater: LuciUpdater) -> None: Initialize sensor. :param unique_id: str: Unique ID :param d... | Implement the Python class `MiWifiBinarySensor` described below.
Class description:
MiWifi binary sensor entry.
Method signatures and docstrings:
- def __init__(self, unique_id: str, description: BinarySensorEntityDescription, updater: LuciUpdater) -> None: Initialize sensor. :param unique_id: str: Unique ID :param d... | feae43a1258e82f55a7e125f5e4b8527074fd745 | <|skeleton|>
class MiWifiBinarySensor:
"""MiWifi binary sensor entry."""
def __init__(self, unique_id: str, description: BinarySensorEntityDescription, updater: LuciUpdater) -> None:
"""Initialize sensor. :param unique_id: str: Unique ID :param description: BinarySensorEntityDescription: BinarySensorEn... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MiWifiBinarySensor:
"""MiWifi binary sensor entry."""
def __init__(self, unique_id: str, description: BinarySensorEntityDescription, updater: LuciUpdater) -> None:
"""Initialize sensor. :param unique_id: str: Unique ID :param description: BinarySensorEntityDescription: BinarySensorEntityDescripti... | the_stack_v2_python_sparse | custom_components/miwifi/binary_sensor.py | gtgt/hass-config | train | 0 |
504d3ecf1a1563c47f214354cece5cbfab259422 | [
"self.distancedb = []\nself.fpfactory = fprintfactory\nself.inputdir = inputdir\nself.metric = metric\nself.dfactory = dfactory\nself.dfactory.create(self.inputdir)\nself.malwarecorpus = self.dfactory.get_corpus()\nself._create_db()",
"for i in range(self.malwarecorpus.get_size()):\n mal1 = self.malwarecorpus.... | <|body_start_0|>
self.distancedb = []
self.fpfactory = fprintfactory
self.inputdir = inputdir
self.metric = metric
self.dfactory = dfactory
self.dfactory.create(self.inputdir)
self.malwarecorpus = self.dfactory.get_corpus()
self._create_db()
<|end_body_0|>... | DisDB will store a list with all the distances of malware | DisDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisDB:
"""DisDB will store a list with all the distances of malware"""
def __init__(self, inputdir, metric, fprintfactory, dfactory):
"""Constructors needs the following: inputdir=directory of malware to read from metric=we need a distance metric to calculate the distances fprintfact... | stack_v2_sparse_classes_75kplus_train_065374 | 2,413 | no_license | [
{
"docstring": "Constructors needs the following: inputdir=directory of malware to read from metric=we need a distance metric to calculate the distances fprintfactory=a fingerprint factory to create fingerprints dfactory=to create a factory to extract malware from",
"name": "__init__",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_016865 | Implement the Python class `DisDB` described below.
Class description:
DisDB will store a list with all the distances of malware
Method signatures and docstrings:
- def __init__(self, inputdir, metric, fprintfactory, dfactory): Constructors needs the following: inputdir=directory of malware to read from metric=we nee... | Implement the Python class `DisDB` described below.
Class description:
DisDB will store a list with all the distances of malware
Method signatures and docstrings:
- def __init__(self, inputdir, metric, fprintfactory, dfactory): Constructors needs the following: inputdir=directory of malware to read from metric=we nee... | 73beebe994a7eb69985d5b56d677796e0c225cd6 | <|skeleton|>
class DisDB:
"""DisDB will store a list with all the distances of malware"""
def __init__(self, inputdir, metric, fprintfactory, dfactory):
"""Constructors needs the following: inputdir=directory of malware to read from metric=we need a distance metric to calculate the distances fprintfact... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisDB:
"""DisDB will store a list with all the distances of malware"""
def __init__(self, inputdir, metric, fprintfactory, dfactory):
"""Constructors needs the following: inputdir=directory of malware to read from metric=we need a distance metric to calculate the distances fprintfactory=a fingerp... | the_stack_v2_python_sparse | core/dmetrics/disdb.py | chesarin/master-thesis | train | 3 |
172bf8e0ff332e0e65e18ecdceff3f7371c44626 | [
"super().__init__(_id, keyword_ref, keyword_string, language, text, timestamp, CrawlTypes.TWITTER.value, score, entities, categories)\nif categories is None:\n categories = []\nif entities is None:\n entities = []\nself.tweet_id = tweet_id\nself.likes = likes\nself.retweets = retweets",
"if not dict_input:\... | <|body_start_0|>
super().__init__(_id, keyword_ref, keyword_string, language, text, timestamp, CrawlTypes.TWITTER.value, score, entities, categories)
if categories is None:
categories = []
if entities is None:
entities = []
self.tweet_id = tweet_id
self.li... | This class serves the purpose of holding Twitter crawl result data | TwitterResult | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterResult:
"""This class serves the purpose of holding Twitter crawl result data"""
def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None, categories=None):
"""Set up all attributes :param ObjectId... | stack_v2_sparse_classes_75kplus_train_065375 | 2,857 | no_license | [
{
"docstring": "Set up all attributes :param ObjectId _id: The Object ID given by mongodb :param long tweet_id: The ID of the tweet given by Twitter :param ObjectId keyword_ref: The ID of the keyword which was used to generate the tweet :param str keyword_string: The target keyword that was used to generate the... | 2 | stack_v2_sparse_classes_30k_train_035763 | Implement the Python class `TwitterResult` described below.
Class description:
This class serves the purpose of holding Twitter crawl result data
Method signatures and docstrings:
- def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None... | Implement the Python class `TwitterResult` described below.
Class description:
This class serves the purpose of holding Twitter crawl result data
Method signatures and docstrings:
- def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None... | 3d775976f2ed26e944083112464aa62c6aea043e | <|skeleton|>
class TwitterResult:
"""This class serves the purpose of holding Twitter crawl result data"""
def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None, categories=None):
"""Set up all attributes :param ObjectId... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterResult:
"""This class serves the purpose of holding Twitter crawl result data"""
def __init__(self, _id, tweet_id, keyword_ref, keyword_string, language, text, timestamp, likes=0, retweets=0, score=None, entities=None, categories=None):
"""Set up all attributes :param ObjectId _id: The Obj... | the_stack_v2_python_sparse | common/mongo/data_types/crawling/crawl_results/twitter_result.py | alex1431999/APOA-Common | train | 0 |
8c672217b17686f525bf1be08c0743391c0c5c2f | [
"self.code = code\nif headers is not None:\n self.headers = headers\nelse:\n self.headers = {}\nif body is None:\n if msg is None:\n msg = 'Internal server error'\n self.body = {'message': msg, 'status': self.code}\nelse:\n self.body = body\nsuper().__init__()",
"resp = jsonify(self.body)\nr... | <|body_start_0|>
self.code = code
if headers is not None:
self.headers = headers
else:
self.headers = {}
if body is None:
if msg is None:
msg = 'Internal server error'
self.body = {'message': msg, 'status': self.code}
... | Base error which provides functionality to return a flask response object | BaseHttpError | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseHttpError:
"""Base error which provides functionality to return a flask response object"""
def __init__(self, code=500, body=None, msg=None, headers=None):
"""Constructor. Args: code (int): http error code body (str): content for response body msg (str): error message error in re... | stack_v2_sparse_classes_75kplus_train_065376 | 16,186 | permissive | [
{
"docstring": "Constructor. Args: code (int): http error code body (str): content for response body msg (str): error message error in response body headers (dict): response headers",
"name": "__init__",
"signature": "def __init__(self, code=500, body=None, msg=None, headers=None)"
},
{
"docstri... | 2 | null | Implement the Python class `BaseHttpError` described below.
Class description:
Base error which provides functionality to return a flask response object
Method signatures and docstrings:
- def __init__(self, code=500, body=None, msg=None, headers=None): Constructor. Args: code (int): http error code body (str): conte... | Implement the Python class `BaseHttpError` described below.
Class description:
Base error which provides functionality to return a flask response object
Method signatures and docstrings:
- def __init__(self, code=500, body=None, msg=None, headers=None): Constructor. Args: code (int): http error code body (str): conte... | 9c9040f6a173af5c495f5447889e9349fa56f234 | <|skeleton|>
class BaseHttpError:
"""Base error which provides functionality to return a flask response object"""
def __init__(self, code=500, body=None, msg=None, headers=None):
"""Constructor. Args: code (int): http error code body (str): content for response body msg (str): error message error in re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseHttpError:
"""Base error which provides functionality to return a flask response object"""
def __init__(self, code=500, body=None, msg=None, headers=None):
"""Constructor. Args: code (int): http error code body (str): content for response body msg (str): error message error in response body h... | the_stack_v2_python_sparse | tessia/server/api/exceptions.py | tessia-project/tessia | train | 10 |
42480c4d93106030127c393894ff33ac1be20346 | [
"super().__init__()\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)\nself.F = tf.keras.layers.Dense(vocab)",
"attention = SelfAttention(s_prev.shape[1])\ncontext, weights = attent... | <|body_start_0|>
super().__init__()
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
self.F = tf.keras.layers.Dense(vocab)
<|end_body_0|>
<|body_start_1|>
... | Decode for machine translation | RNNDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNDecoder:
"""Decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer represent... | stack_v2_sparse_classes_75kplus_train_065377 | 1,824 | no_license | [
{
"docstring": "vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the number of hidden units in the RNN cell batch is an integer representing the batch size",
"name": "__init... | 2 | stack_v2_sparse_classes_30k_train_022988 | Implement the Python class `RNNDecoder` described below.
Class description:
Decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensional... | Implement the Python class `RNNDecoder` described below.
Class description:
Decode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensional... | b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918 | <|skeleton|>
class RNNDecoder:
"""Decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer represent... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNDecoder:
"""Decode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the decode_out vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the numbe... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/2-rnn_decoder.py | Gaspela/holbertonschool-machine_learning | train | 0 |
6bdf2d645cedbc94e6663e4c736aa60bc558bb8c | [
"self.checkpoint_dir = os.getcwd()\nif checkpoint_dir is not None:\n self.checkpoint_dir = checkpoint_dir\nself.name = '{}.pth.tar'\nself.latest = 'last'\nself.best = 'best'\nself.logger = Logger.get()",
"if not os.path.isdir(self.checkpoint_dir):\n msg = 'Checkpoint Directory does not exist! Making directo... | <|body_start_0|>
self.checkpoint_dir = os.getcwd()
if checkpoint_dir is not None:
self.checkpoint_dir = checkpoint_dir
self.name = '{}.pth.tar'
self.latest = 'last'
self.best = 'best'
self.logger = Logger.get()
<|end_body_0|>
<|body_start_1|>
if not o... | Save/load the model and optimizer parameters. | Serialization | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serialization:
"""Save/load the model and optimizer parameters."""
def __init__(self, checkpoint_dir=None):
"""Args: checkpoint_dir (path): the directory of checkpoint files."""
<|body_0|>
def serialize(self, model, epoch, optimizer=None, checkpoint='last', is_best=False... | stack_v2_sparse_classes_75kplus_train_065378 | 16,358 | no_license | [
{
"docstring": "Args: checkpoint_dir (path): the directory of checkpoint files.",
"name": "__init__",
"signature": "def __init__(self, checkpoint_dir=None)"
},
{
"docstring": "Save model, optimizer and other parameters to file. Args: epoch (int): the epoch of training. checkpoint (str): the name... | 3 | stack_v2_sparse_classes_30k_train_048156 | Implement the Python class `Serialization` described below.
Class description:
Save/load the model and optimizer parameters.
Method signatures and docstrings:
- def __init__(self, checkpoint_dir=None): Args: checkpoint_dir (path): the directory of checkpoint files.
- def serialize(self, model, epoch, optimizer=None, ... | Implement the Python class `Serialization` described below.
Class description:
Save/load the model and optimizer parameters.
Method signatures and docstrings:
- def __init__(self, checkpoint_dir=None): Args: checkpoint_dir (path): the directory of checkpoint files.
- def serialize(self, model, epoch, optimizer=None, ... | e953a54cd4599cfbfad11f88de7b354239cb558c | <|skeleton|>
class Serialization:
"""Save/load the model and optimizer parameters."""
def __init__(self, checkpoint_dir=None):
"""Args: checkpoint_dir (path): the directory of checkpoint files."""
<|body_0|>
def serialize(self, model, epoch, optimizer=None, checkpoint='last', is_best=False... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Serialization:
"""Save/load the model and optimizer parameters."""
def __init__(self, checkpoint_dir=None):
"""Args: checkpoint_dir (path): the directory of checkpoint files."""
self.checkpoint_dir = os.getcwd()
if checkpoint_dir is not None:
self.checkpoint_dir = chec... | the_stack_v2_python_sparse | pytorch_startup/utils.py | wikty/MachineLearningExamples | train | 0 |
7f30f759ed3a3e4ee9c5ba7765b4193fef26e47e | [
"check_authorization, response = check_authorization_in_header(request)\nif not check_authorization:\n return response\ndata = json.loads(request.body or '{}')\ncheck_data, response = check_user_data_request(data)\nif not check_data:\n return response\nuser = check_user(request)\nif user is not None:\n ser... | <|body_start_0|>
check_authorization, response = check_authorization_in_header(request)
if not check_authorization:
return response
data = json.loads(request.body or '{}')
check_data, response = check_user_data_request(data)
if not check_data:
return respo... | Users | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def put(self, request):
"""Method updates a user"""
<|body_0|>
def post(self, request):
"""method register a new user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
check_authorization, response = check_authorization_in_header(request)
... | stack_v2_sparse_classes_75kplus_train_065379 | 12,963 | permissive | [
{
"docstring": "Method updates a user",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "method register a new user",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032156 | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def put(self, request): Method updates a user
- def post(self, request): method register a new user | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def put(self, request): Method updates a user
- def post(self, request): method register a new user
<|skeleton|>
class Users:
def put(self, request):
"""Method updates a ... | 8082bb89d00d28ade774a445a1645dc07ac86127 | <|skeleton|>
class Users:
def put(self, request):
"""Method updates a user"""
<|body_0|>
def post(self, request):
"""method register a new user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Users:
def put(self, request):
"""Method updates a user"""
check_authorization, response = check_authorization_in_header(request)
if not check_authorization:
return response
data = json.loads(request.body or '{}')
check_data, response = check_user_data_reque... | the_stack_v2_python_sparse | BettingRestAPI/user/views.py | PatrickKoss/BettingPrediction | train | 0 | |
de89607e5759dae089743bda3645d95adedd563e | [
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.add_dataStage03QuantificationMetid2keggid(data.data)\ndata.clear_data()",
"data = base_importData()\ndata.read_csv(filename)\ndata.format_data()\nself.update_dataStage03QuantificationMetid2keggid(data.data)\ndata.clear_data()"
] | <|body_start_0|>
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage03QuantificationMetid2keggid(data.data)
data.clear_data()
<|end_body_0|>
<|body_start_1|>
data = base_importData()
data.read_csv(filename)
data.format_d... | stage03_quantification_metid2keggid_io | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stage03_quantification_metid2keggid_io:
def import_dataStage03QuantificationMetid2keggid_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage03QuantificationMetid2keggid_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_065380 | 1,006 | permissive | [
{
"docstring": "table adds",
"name": "import_dataStage03QuantificationMetid2keggid_add",
"signature": "def import_dataStage03QuantificationMetid2keggid_add(self, filename)"
},
{
"docstring": "table adds",
"name": "import_dataStage03QuantificationMetid2keggid_update",
"signature": "def im... | 2 | stack_v2_sparse_classes_30k_train_029662 | Implement the Python class `stage03_quantification_metid2keggid_io` described below.
Class description:
Implement the stage03_quantification_metid2keggid_io class.
Method signatures and docstrings:
- def import_dataStage03QuantificationMetid2keggid_add(self, filename): table adds
- def import_dataStage03Quantificatio... | Implement the Python class `stage03_quantification_metid2keggid_io` described below.
Class description:
Implement the stage03_quantification_metid2keggid_io class.
Method signatures and docstrings:
- def import_dataStage03QuantificationMetid2keggid_add(self, filename): table adds
- def import_dataStage03Quantificatio... | 0eeed0191f952ea0226ab8bbc234a30638fb2f9f | <|skeleton|>
class stage03_quantification_metid2keggid_io:
def import_dataStage03QuantificationMetid2keggid_add(self, filename):
"""table adds"""
<|body_0|>
def import_dataStage03QuantificationMetid2keggid_update(self, filename):
"""table adds"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class stage03_quantification_metid2keggid_io:
def import_dataStage03QuantificationMetid2keggid_add(self, filename):
"""table adds"""
data = base_importData()
data.read_csv(filename)
data.format_data()
self.add_dataStage03QuantificationMetid2keggid(data.data)
data.clea... | the_stack_v2_python_sparse | SBaaS_thermodynamics/stage03_quantification_metid2keggid_io.py | dmccloskey/SBaaS_thermodynamics | train | 0 | |
aa01e46aa8c50f4c71d2bfe81d05c96d913ca420 | [
"if type(X_init) is not np.ndarray or len(X_init.shape) != 2:\n raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')\nt, one = X_init.shape\nif one != 1:\n raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')\nif type(Y_init) is not np.ndarray or len(Y_init.shape) != 2:\n raise TypeEr... | <|body_start_0|>
if type(X_init) is not np.ndarray or len(X_init.shape) != 2:
raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')
t, one = X_init.shape
if one != 1:
raise TypeError('X_init must be numpy.ndarray of shape (t, 1)')
if type(Y_init) is not ... | Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of shape (t, 1)]: representing the outputs of t... | GaussianProcess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of s... | stack_v2_sparse_classes_75kplus_train_065381 | 3,918 | no_license | [
{
"docstring": "Class constructor parameters: X_init [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y_init [numpy.ndarry of shape (t, 1)]: representing outputs of the black-box function for each input l [int or float]: length parameter for the k... | 2 | stack_v2_sparse_classes_30k_train_021998 | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t:... | Implement the Python class `GaussianProcess` described below.
Class description:
Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t:... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GaussianProcess:
"""Represents a noiseless 1D Gaussian process class constructor: def __init__(self, X_init, Y_init, l=1, sigma_f=1) public instance attributes: X [numpy.ndarray of shape (t, 1)]: representing the inputs sampled with the black-box function t: number of samples Y [numpy.ndarry of shape (t, 1)]:... | the_stack_v2_python_sparse | unsupervised_learning/0x03-hyperparameter_tuning/0-gp.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
efa153b3551839bb0eb8cb1e2a34f541ca1dcafe | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('francisz_jrashaan', 'francisz_jrashaan')\nrepo.dropPermanent('crimeData')\nrepo.createPermanent('crimeData')\nhomicides = []\nhomicideCount = 0\nfor entry in repo.francisz_jrashaan.crime.find():\n if ... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('francisz_jrashaan', 'francisz_jrashaan')
repo.dropPermanent('crimeData')
repo.createPermanent('crimeData')
homicides = []
homicide... | crimeTransformation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class crimeTransformation:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_75kplus_train_065382 | 4,330 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_048246 | Implement the Python class `crimeTransformation` described below.
Class description:
Implement the crimeTransformation class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | Implement the Python class `crimeTransformation` described below.
Class description:
Implement the crimeTransformation class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), start... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class crimeTransformation:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing ever... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class crimeTransformation:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('francisz_jrashaan', 'francisz_j... | the_stack_v2_python_sparse | francisz_jrashaan/crimeTransformation.py | ROODAY/course-2017-fal-proj | train | 3 | |
6d1fa7f50802de1a432993bcbb5eb82ed8122d4d | [
"self.length = length\nself.partition_number = partition_number\nself.partition_type_uuid = partition_type_uuid\nself.partition_uuid = partition_uuid\nself.start_offset = start_offset",
"if dictionary is None:\n return None\nlength = dictionary.get('length')\npartition_number = dictionary.get('partitionNumber'... | <|body_start_0|>
self.length = length
self.partition_number = partition_number
self.partition_type_uuid = partition_type_uuid
self.partition_uuid = partition_uuid
self.start_offset = start_offset
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return N... | Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in bytes. partition_number (long|int): Partition number. partitio... | VolumeInfo_DiskInfo_PartitionInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in b... | stack_v2_sparse_classes_75kplus_train_065383 | 3,327 | permissive | [
{
"docstring": "Constructor for the VolumeInfo_DiskInfo_PartitionInfo class",
"name": "__init__",
"signature": "def __init__(self, length=None, partition_number=None, partition_type_uuid=None, partition_uuid=None, start_offset=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | stack_v2_sparse_classes_30k_train_052683 | Implement the Python class `VolumeInfo_DiskInfo_PartitionInfo` described below.
Class description:
Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: leng... | Implement the Python class `VolumeInfo_DiskInfo_PartitionInfo` described below.
Class description:
Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: leng... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in bytes. partiti... | the_stack_v2_python_sparse | cohesity_management_sdk/models/volume_info_disk_info_partition_info.py | cohesity/management-sdk-python | train | 24 |
bc2099ae8abf4488dd72fa7b757d9bcb9d25487d | [
"super(NeuralProcess, self).__init__()\nself._num_latents = num_latents\nself._latent_encoder_sizes = latent_encoder_sizes\nself._deterministic_encoder_sizes = deterministic_encoder_sizes\nself._decoder_sizes = decoder_sizes\nself._use_deterministic_path = use_deterministic_path\nself._attention = attention_wrapper... | <|body_start_0|>
super(NeuralProcess, self).__init__()
self._num_latents = num_latents
self._latent_encoder_sizes = latent_encoder_sizes
self._deterministic_encoder_sizes = deterministic_encoder_sizes
self._decoder_sizes = decoder_sizes
self._use_deterministic_path = use_... | Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018). | NeuralProcess | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model... | stack_v2_sparse_classes_75kplus_train_065384 | 14,004 | permissive | [
{
"docstring": "Initializes the Neural Process model. Args: latent_encoder_sizes: (list of ints) Hidden layer sizes for latent encoder. num_latents: (int) Dimensionality of global latent variable. decoder_sizes: (list of ints) Hidden layer sizes for decoder use_deterministic_path: (bool) Uses deterministic enco... | 5 | stack_v2_sparse_classes_30k_train_019962 | Implement the Python class `NeuralProcess` described below.
Class description:
Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018).
Method signatures and docstrings:
- def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, atte... | Implement the Python class `NeuralProcess` described below.
Class description:
Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018).
Method signatures and docstrings:
- def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, atte... | ccdb9bfb11fe713bc449f0e884b405f619f58059 | <|skeleton|>
class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NeuralProcess:
"""Attentive Neural Process (Kim et al., 2019; Garnelo et al., 2018)."""
def __init__(self, latent_encoder_sizes, num_latents, decoder_sizes, use_deterministic_path=True, deterministic_encoder_sizes=None, attention_wrapper=None):
"""Initializes the Neural Process model. Args: laten... | the_stack_v2_python_sparse | edward2/tensorflow/layers/neural_process.py | google/edward2 | train | 710 |
4c9e1f0c609c848d0664973663ff472f13af2aa2 | [
"if max_row == -1:\n max_row = len(self.r)\nclean = True\nlimit = int(ceil((1 + params['c']) * params.block_size))\nfor kappa in range(min_row, max_row - limit):\n assert max_row - kappa >= params.block_size\n clean &= self.svp_reduction(kappa, params.block_size, params, tracer=tracer)\ncost_ceil = log(par... | <|body_start_0|>
if max_row == -1:
max_row = len(self.r)
clean = True
limit = int(ceil((1 + params['c']) * params.block_size))
for kappa in range(min_row, max_row - limit):
assert max_row - kappa >= params.block_size
clean &= self.svp_reduction(kappa, ... | A simulator simulating both quality and time. | ProcrastinatingBKZSimulation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcrastinatingBKZSimulation:
"""A simulator simulating both quality and time."""
def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer):
""":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (e... | stack_v2_sparse_classes_75kplus_train_065385 | 24,318 | no_license | [
{
"docstring": ":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (exclusive) :returns: whether the basis remained untouched or not",
"name": "tour",
"signature": "def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tr... | 2 | stack_v2_sparse_classes_30k_train_006553 | Implement the Python class `ProcrastinatingBKZSimulation` described below.
Class description:
A simulator simulating both quality and time.
Method signatures and docstrings:
- def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer): :param params: BKZ parameters :param min_row: start processing at min_row ... | Implement the Python class `ProcrastinatingBKZSimulation` described below.
Class description:
A simulator simulating both quality and time.
Method signatures and docstrings:
- def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer): :param params: BKZ parameters :param min_row: start processing at min_row ... | d5bfc4e75ebec65d645853041ae548c5bfc066c8 | <|skeleton|>
class ProcrastinatingBKZSimulation:
"""A simulator simulating both quality and time."""
def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer):
""":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (e... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProcrastinatingBKZSimulation:
"""A simulator simulating both quality and time."""
def tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer):
""":param params: BKZ parameters :param min_row: start processing at min_row (inclusive) :param max_row: stop processing at max_row (exclusive) :re... | the_stack_v2_python_sparse | simu.py | fasterBKZ/simulation | train | 0 |
37e9fb2ca4b3a5a904690572b1805351c106bfbc | [
"wx.Panel.__init__(self, parent)\nself.frame = parent\nmain_sizer = wx.BoxSizer(wx.VERTICAL)\ndlg_btn = wx.Button(self, label='Open ColorDialog')\ndlg_btn.Bind(wx.EVT_BUTTON, self.onOpenColorDialog)\nmain_sizer.Add(dlg_btn, 0, wx.ALL | wx.CENTER)\nbusy_btn = wx.Button(self, label='Open BusyInfo')\nbusy_btn.Bind(wx.... | <|body_start_0|>
wx.Panel.__init__(self, parent)
self.frame = parent
main_sizer = wx.BoxSizer(wx.VERTICAL)
dlg_btn = wx.Button(self, label='Open ColorDialog')
dlg_btn.Bind(wx.EVT_BUTTON, self.onOpenColorDialog)
main_sizer.Add(dlg_btn, 0, wx.ALL | wx.CENTER)
busy_b... | MyPanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPanel:
def __init__(self, parent):
"""Constructor"""
<|body_0|>
def onOpenColorDialog(self, event):
"""Creates and opens the wx.ColourDialog"""
<|body_1|>
def onOpenBusyInfo(self, event):
"""Creates and opens an instance of BusyInfo"""
... | stack_v2_sparse_classes_75kplus_train_065386 | 1,587 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Creates and opens the wx.ColourDialog",
"name": "onOpenColorDialog",
"signature": "def onOpenColorDialog(self, event)"
},
{
"docstring": "Creates and opens an instance o... | 3 | stack_v2_sparse_classes_30k_train_006154 | Implement the Python class `MyPanel` described below.
Class description:
Implement the MyPanel class.
Method signatures and docstrings:
- def __init__(self, parent): Constructor
- def onOpenColorDialog(self, event): Creates and opens the wx.ColourDialog
- def onOpenBusyInfo(self, event): Creates and opens an instance... | Implement the Python class `MyPanel` described below.
Class description:
Implement the MyPanel class.
Method signatures and docstrings:
- def __init__(self, parent): Constructor
- def onOpenColorDialog(self, event): Creates and opens the wx.ColourDialog
- def onOpenBusyInfo(self, event): Creates and opens an instance... | ebe43e870b1057c6252671d8739e8ce7bad424fe | <|skeleton|>
class MyPanel:
def __init__(self, parent):
"""Constructor"""
<|body_0|>
def onOpenColorDialog(self, event):
"""Creates and opens the wx.ColourDialog"""
<|body_1|>
def onOpenBusyInfo(self, event):
"""Creates and opens an instance of BusyInfo"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyPanel:
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.frame = parent
main_sizer = wx.BoxSizer(wx.VERTICAL)
dlg_btn = wx.Button(self, label='Open ColorDialog')
dlg_btn.Bind(wx.EVT_BUTTON, self.onOpenColorDialog)
main_... | the_stack_v2_python_sparse | wxPython_recipes_book_code-master/chapter_20_bonus_recipes/recipe_20_2_context_managers/builtin_context.py | canderson71/python | train | 0 | |
8159f1164567379b715edcb6d30520a6feda6ffc | [
"skill = self.get_object()\nSkillIndex.get(id=skill.id).delete()\nskill.delete()\nreturn Response(status=status.HTTP_204_NO_CONTENT)",
"query = request.query_params.get('q')\nsearch = SkillSearch()\nresults = search.find(query)\nreturn Response({'skills': results})"
] | <|body_start_0|>
skill = self.get_object()
SkillIndex.get(id=skill.id).delete()
skill.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
<|end_body_0|>
<|body_start_1|>
query = request.query_params.get('q')
search = SkillSearch()
results = search.find(qu... | ViewSet for skill. | SkillsViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkillsViewSet:
"""ViewSet for skill."""
def destroy(self, request, pk=None):
"""Delete selected skill."""
<|body_0|>
def search(self, request):
"""Search skills."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
skill = self.get_object()
S... | stack_v2_sparse_classes_75kplus_train_065387 | 1,176 | no_license | [
{
"docstring": "Delete selected skill.",
"name": "destroy",
"signature": "def destroy(self, request, pk=None)"
},
{
"docstring": "Search skills.",
"name": "search",
"signature": "def search(self, request)"
}
] | 2 | null | Implement the Python class `SkillsViewSet` described below.
Class description:
ViewSet for skill.
Method signatures and docstrings:
- def destroy(self, request, pk=None): Delete selected skill.
- def search(self, request): Search skills. | Implement the Python class `SkillsViewSet` described below.
Class description:
ViewSet for skill.
Method signatures and docstrings:
- def destroy(self, request, pk=None): Delete selected skill.
- def search(self, request): Search skills.
<|skeleton|>
class SkillsViewSet:
"""ViewSet for skill."""
def destroy... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class SkillsViewSet:
"""ViewSet for skill."""
def destroy(self, request, pk=None):
"""Delete selected skill."""
<|body_0|>
def search(self, request):
"""Search skills."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SkillsViewSet:
"""ViewSet for skill."""
def destroy(self, request, pk=None):
"""Delete selected skill."""
skill = self.get_object()
SkillIndex.get(id=skill.id).delete()
skill.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
def search(self, request)... | the_stack_v2_python_sparse | app/skills/views.py | vsokoltsov/Interview360Server | train | 2 |
3469ad6d577fd5810ed358953e8c30f5d1d71088 | [
"print('Room: at object_receive; has_account:' + str(new_arrival.has_account))\nnew_arrival.msg('Room: at_object_receive')\nsuper(Room, self).at_object_receive(new_arrival, source_location)",
"super(Room, self).at_desc(looker, **kwargs)\nprint('Room at_desc', self, looker, kwargs)\nvisible_things = list(get_visib... | <|body_start_0|>
print('Room: at object_receive; has_account:' + str(new_arrival.has_account))
new_arrival.msg('Room: at_object_receive')
super(Room, self).at_object_receive(new_arrival, source_location)
<|end_body_0|>
<|body_start_1|>
super(Room, self).at_desc(looker, **kwargs)
... | Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all Objects. | Room | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Room:
"""Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all ... | stack_v2_sparse_classes_75kplus_train_065388 | 2,157 | permissive | [
{
"docstring": "this isn't a good place to send the multimedia, because it seems that when a player \"connects\"(logs in), his character is first placed into the world (and this is called) and only then is the player's session assigned to it.",
"name": "at_object_receive",
"signature": "def at_object_re... | 2 | stack_v2_sparse_classes_30k_train_009606 | Implement the Python class `Room` described below.
Class description:
Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of p... | Implement the Python class `Room` described below.
Class description:
Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of p... | 095ad7a2fe583033fb7e2070f3f8920a6e88b323 | <|skeleton|>
class Room:
"""Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Room:
"""Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all Objects."""
... | the_stack_v2_python_sparse | evennia/abbeydale/typeclasses/rooms.py | castlelorestudios/EvenniaPluginSampleProject | train | 3 |
f975f8756ae884510afc0f70ae2d77cdc7d032e9 | [
"result = DanmakuData()\ntitle, duration, target_id = await self.get_video_info(cid)\nif not target_id:\n return result\ncount = duration // 30 + 1\ntasks = [self.get_30s_bullets(cid, target_id, t * 30) for t in range(count)]\nasync for ret in self.as_iter_completed(tasks):\n result.append(ret)\nreturn result... | <|body_start_0|>
result = DanmakuData()
title, duration, target_id = await self.get_video_info(cid)
if not target_id:
return result
count = duration // 30 + 1
tasks = [self.get_30s_bullets(cid, target_id, t * 30) for t in range(count)]
async for ret in self.as... | TencentDanmakuDataParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TencentDanmakuDataParser:
async def parse(self, cid: str) -> DanmakuData:
"""获取视频的全部弹幕"""
<|body_0|>
async def get_30s_bullets(self, video_id: str, target_id: str, start_at: int):
"""获取某个时间点后的 30s 弹幕数据 :params video_id 视频 url 中的id :params target_id 视频的数字id :params st... | stack_v2_sparse_classes_75kplus_train_065389 | 6,185 | permissive | [
{
"docstring": "获取视频的全部弹幕",
"name": "parse",
"signature": "async def parse(self, cid: str) -> DanmakuData"
},
{
"docstring": "获取某个时间点后的 30s 弹幕数据 :params video_id 视频 url 中的id :params target_id 视频的数字id :params start_at 弹幕起始时间点(s)",
"name": "get_30s_bullets",
"signature": "async def get_30s... | 3 | null | Implement the Python class `TencentDanmakuDataParser` described below.
Class description:
Implement the TencentDanmakuDataParser class.
Method signatures and docstrings:
- async def parse(self, cid: str) -> DanmakuData: 获取视频的全部弹幕
- async def get_30s_bullets(self, video_id: str, target_id: str, start_at: int): 获取某个时间点... | Implement the Python class `TencentDanmakuDataParser` described below.
Class description:
Implement the TencentDanmakuDataParser class.
Method signatures and docstrings:
- async def parse(self, cid: str) -> DanmakuData: 获取视频的全部弹幕
- async def get_30s_bullets(self, video_id: str, target_id: str, start_at: int): 获取某个时间点... | 368c5a1835af9b8f77ef6ff4f81cb8f90fa83aa8 | <|skeleton|>
class TencentDanmakuDataParser:
async def parse(self, cid: str) -> DanmakuData:
"""获取视频的全部弹幕"""
<|body_0|>
async def get_30s_bullets(self, video_id: str, target_id: str, start_at: int):
"""获取某个时间点后的 30s 弹幕数据 :params video_id 视频 url 中的id :params target_id 视频的数字id :params st... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TencentDanmakuDataParser:
async def parse(self, cid: str) -> DanmakuData:
"""获取视频的全部弹幕"""
result = DanmakuData()
title, duration, target_id = await self.get_video_info(cid)
if not target_id:
return result
count = duration // 30 + 1
tasks = [self.get_... | the_stack_v2_python_sparse | api/danmaku/tencent.py | juzeon/Anime-API | train | 0 | |
667bd72cb4993f82f60c819b5fb84fe6d7726c59 | [
"if hasattr(self, 'request') and user_id == self.request.session['user_id']:\n username = self.request.session['username']\n token = self.request.session['token']\n user = AuthUser(user_id, username, token)\n return user\nelse:\n return None",
"LOG.debug('Beginning user authentication for user \"%s... | <|body_start_0|>
if hasattr(self, 'request') and user_id == self.request.session['user_id']:
username = self.request.session['username']
token = self.request.session['token']
user = AuthUser(user_id, username, token)
return user
else:
return No... | Django authentication backend class for use with ``django.contrib.auth``. | KeystoneBackend | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeystoneBackend:
"""Django authentication backend class for use with ``django.contrib.auth``."""
def get_user(self, user_id):
"""Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to m... | stack_v2_sparse_classes_75kplus_train_065390 | 2,763 | permissive | [
{
"docstring": "Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to make the ``request`` object available to the auth backend class.",
"name": "get_user",
"signature": "def get_user(self, user_id)"
},... | 4 | stack_v2_sparse_classes_30k_train_010964 | Implement the Python class `KeystoneBackend` described below.
Class description:
Django authentication backend class for use with ``django.contrib.auth``.
Method signatures and docstrings:
- def get_user(self, user_id): Returns the current user (if authenticated) based on the user ID and session data. Note: this requ... | Implement the Python class `KeystoneBackend` described below.
Class description:
Django authentication backend class for use with ``django.contrib.auth``.
Method signatures and docstrings:
- def get_user(self, user_id): Returns the current user (if authenticated) based on the user ID and session data. Note: this requ... | 74140b041ac25ed83898ff3998e8dcbed35572bb | <|skeleton|>
class KeystoneBackend:
"""Django authentication backend class for use with ``django.contrib.auth``."""
def get_user(self, user_id):
"""Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeystoneBackend:
"""Django authentication backend class for use with ``django.contrib.auth``."""
def get_user(self, user_id):
"""Returns the current user (if authenticated) based on the user ID and session data. Note: this required monkey-patching the ``contrib.auth`` middleware to make the ``req... | the_stack_v2_python_sparse | tools/dockerize/webportal/usr/share/openstack-dashboard/openstack_dashboard/backend.py | foruy/openflow-multiopenstack | train | 1 |
0c4e1619a506b5d3e8bbbd5559f45eca6050be26 | [
"title = self.getAttributeNode('title')\nif title is not None:\n return NamedNodeMap({'title': title})\nreturn NamedNodeMap()",
"if name == 'title' and hasattr(self.aq_base, 'title'):\n return self.title\nreturn ''",
"value = self.getAttribute(name)\nif value:\n return Attr(name, value).__of__(self)\nr... | <|body_start_0|>
title = self.getAttributeNode('title')
if title is not None:
return NamedNodeMap({'title': title})
return NamedNodeMap()
<|end_body_0|>
<|body_start_1|>
if name == 'title' and hasattr(self.aq_base, 'title'):
return self.title
return ''
<|... | Elements that allow DOM access to Zope 'title' property. Note: Don't use this sub-class for PropertyManagers | ElementWithTitle | [
"ZPL-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElementWithTitle:
"""Elements that allow DOM access to Zope 'title' property. Note: Don't use this sub-class for PropertyManagers"""
def getAttributes(self):
"""Returns a NamedNodeMap containing the attributes of this node (if it is an element) or None otherwise."""
<|body_0|... | stack_v2_sparse_classes_75kplus_train_065391 | 16,682 | permissive | [
{
"docstring": "Returns a NamedNodeMap containing the attributes of this node (if it is an element) or None otherwise.",
"name": "getAttributes",
"signature": "def getAttributes(self)"
},
{
"docstring": "Retrieves an attribute value by name.",
"name": "getAttribute",
"signature": "def ge... | 3 | stack_v2_sparse_classes_30k_train_032974 | Implement the Python class `ElementWithTitle` described below.
Class description:
Elements that allow DOM access to Zope 'title' property. Note: Don't use this sub-class for PropertyManagers
Method signatures and docstrings:
- def getAttributes(self): Returns a NamedNodeMap containing the attributes of this node (if ... | Implement the Python class `ElementWithTitle` described below.
Class description:
Elements that allow DOM access to Zope 'title' property. Note: Don't use this sub-class for PropertyManagers
Method signatures and docstrings:
- def getAttributes(self): Returns a NamedNodeMap containing the attributes of this node (if ... | dedc799bd7eda913ffc45da43507abe2fa5113be | <|skeleton|>
class ElementWithTitle:
"""Elements that allow DOM access to Zope 'title' property. Note: Don't use this sub-class for PropertyManagers"""
def getAttributes(self):
"""Returns a NamedNodeMap containing the attributes of this node (if it is an element) or None otherwise."""
<|body_0|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ElementWithTitle:
"""Elements that allow DOM access to Zope 'title' property. Note: Don't use this sub-class for PropertyManagers"""
def getAttributes(self):
"""Returns a NamedNodeMap containing the attributes of this node (if it is an element) or None otherwise."""
title = self.getAttrib... | the_stack_v2_python_sparse | lib/python/OFS/ZDOM.py | OS2World/APP-SERVER-Zope | train | 0 |
9ab365c03be6ba926c3dc3eff66ca92c60abe917 | [
"if not root:\n return False\nqueue = collections.deque()\nqueue.append(root)\nwhile queue:\n count = 0\n for i in range(len(queue)):\n root = queue.popleft()\n if root.left and root.right:\n if x in [root.left.val, root.right.val] and y in [root.left.val, root.right.val]:\n ... | <|body_start_0|>
if not root:
return False
queue = collections.deque()
queue.append(root)
while queue:
count = 0
for i in range(len(queue)):
root = queue.popleft()
if root.left and root.right:
if x in... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
"""思路:广度优先搜索(队列) 1. 定义为堂兄弟,如果给定的两个数正好是左右节点,返回FALSE 2. 如果某一层出现了一个,返回FALSE 3. 如果某一层出现了两个,返回TRUE"""
<|body_0|>
def isCousins2(self, root: TreeNode, x: int, y: int) -> bool:
"""仿造官方题解 1、"""
<|... | stack_v2_sparse_classes_75kplus_train_065392 | 3,586 | no_license | [
{
"docstring": "思路:广度优先搜索(队列) 1. 定义为堂兄弟,如果给定的两个数正好是左右节点,返回FALSE 2. 如果某一层出现了一个,返回FALSE 3. 如果某一层出现了两个,返回TRUE",
"name": "isCousins",
"signature": "def isCousins(self, root: TreeNode, x: int, y: int) -> bool"
},
{
"docstring": "仿造官方题解 1、",
"name": "isCousins2",
"signature": "def isCousins2(s... | 3 | stack_v2_sparse_classes_30k_train_034424 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCousins(self, root: TreeNode, x: int, y: int) -> bool: 思路:广度优先搜索(队列) 1. 定义为堂兄弟,如果给定的两个数正好是左右节点,返回FALSE 2. 如果某一层出现了一个,返回FALSE 3. 如果某一层出现了两个,返回TRUE
- def isCousins2(self, roo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCousins(self, root: TreeNode, x: int, y: int) -> bool: 思路:广度优先搜索(队列) 1. 定义为堂兄弟,如果给定的两个数正好是左右节点,返回FALSE 2. 如果某一层出现了一个,返回FALSE 3. 如果某一层出现了两个,返回TRUE
- def isCousins2(self, roo... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
"""思路:广度优先搜索(队列) 1. 定义为堂兄弟,如果给定的两个数正好是左右节点,返回FALSE 2. 如果某一层出现了一个,返回FALSE 3. 如果某一层出现了两个,返回TRUE"""
<|body_0|>
def isCousins2(self, root: TreeNode, x: int, y: int) -> bool:
"""仿造官方题解 1、"""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
"""思路:广度优先搜索(队列) 1. 定义为堂兄弟,如果给定的两个数正好是左右节点,返回FALSE 2. 如果某一层出现了一个,返回FALSE 3. 如果某一层出现了两个,返回TRUE"""
if not root:
return False
queue = collections.deque()
queue.append(root)
while queue:
... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/993. Cousins in Binary Tree.py | yiming1012/MyLeetCode | train | 2 | |
a5a709022df5a8ea83680392dc083b5a52fd10b4 | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_l3_environment_by_search(self.search)\n environments = obj_model['query_set']\n only_main_property = False\nelse:\n return Response(dict(), status=status.HTTP_400_BAD_REQUEST)\nserializer_env = serializers.GrupoL3Serializer(environments, many=True,... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_l3_environment_by_search(self.search)
environments = obj_model['query_set']
only_main_property = False
else:
return Response(dict(), status=status.HTTP_400_BAD_REQUEST)
serialize... | EnvironmentL3DBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentL3DBView:
def get(self, request, *args, **kwargs):
"""Returns a list of environment by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new environment."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not ... | stack_v2_sparse_classes_75kplus_train_065393 | 16,527 | permissive | [
{
"docstring": "Returns a list of environment by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Create new environment.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014961 | Implement the Python class `EnvironmentL3DBView` described below.
Class description:
Implement the EnvironmentL3DBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of environment by ids ou dict.
- def post(self, request, *args, **kwargs): Create new environment. | Implement the Python class `EnvironmentL3DBView` described below.
Class description:
Implement the EnvironmentL3DBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of environment by ids ou dict.
- def post(self, request, *args, **kwargs): Create new environment.
... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class EnvironmentL3DBView:
def get(self, request, *args, **kwargs):
"""Returns a list of environment by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Create new environment."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnvironmentL3DBView:
def get(self, request, *args, **kwargs):
"""Returns a list of environment by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_l3_environment_by_search(self.search)
environments = obj_model['query_set']
only_main_prope... | the_stack_v2_python_sparse | networkapi/api_environment/views.py | globocom/GloboNetworkAPI | train | 86 | |
1e5b21db73c3693e0173834eedb3623fac8a31b2 | [
"if hasattr(tools, 'xcode_cli'):\n return tools.xcode_cli\ncls.ensure_command_line_tools_are_installed(tools=tools)\ncls.confirm_xcode_license_accepted(tools=tools)\ntools.xcode_cli = XcodeCliTools(tools=tools)\nreturn tools.xcode_cli",
"try:\n tools.subprocess.check_output(['xcode-select', '--install'])\n ... | <|body_start_0|>
if hasattr(tools, 'xcode_cli'):
return tools.xcode_cli
cls.ensure_command_line_tools_are_installed(tools=tools)
cls.confirm_xcode_license_accepted(tools=tools)
tools.xcode_cli = XcodeCliTools(tools=tools)
return tools.xcode_cli
<|end_body_0|>
<|body_... | XcodeCliTools | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XcodeCliTools:
def verify_install(cls, tools: ToolCache, **kwargs) -> XcodeCliTools:
"""Verify that command line developer tools are installed and ready for use. A completely clean machine will have neither Xcode *nor* the Command Line Tools. However, it's possible to install Xcode and *... | stack_v2_sparse_classes_75kplus_train_065394 | 19,630 | permissive | [
{
"docstring": "Verify that command line developer tools are installed and ready for use. A completely clean machine will have neither Xcode *nor* the Command Line Tools. However, it's possible to install Xcode and *not* install the command line tools, and vice versa. Lastly, there is a license that needs to be... | 3 | stack_v2_sparse_classes_30k_train_054746 | Implement the Python class `XcodeCliTools` described below.
Class description:
Implement the XcodeCliTools class.
Method signatures and docstrings:
- def verify_install(cls, tools: ToolCache, **kwargs) -> XcodeCliTools: Verify that command line developer tools are installed and ready for use. A completely clean machi... | Implement the Python class `XcodeCliTools` described below.
Class description:
Implement the XcodeCliTools class.
Method signatures and docstrings:
- def verify_install(cls, tools: ToolCache, **kwargs) -> XcodeCliTools: Verify that command line developer tools are installed and ready for use. A completely clean machi... | cc2dae1ffc58f9700d0ca57461cb05909bc01bec | <|skeleton|>
class XcodeCliTools:
def verify_install(cls, tools: ToolCache, **kwargs) -> XcodeCliTools:
"""Verify that command line developer tools are installed and ready for use. A completely clean machine will have neither Xcode *nor* the Command Line Tools. However, it's possible to install Xcode and *... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XcodeCliTools:
def verify_install(cls, tools: ToolCache, **kwargs) -> XcodeCliTools:
"""Verify that command line developer tools are installed and ready for use. A completely clean machine will have neither Xcode *nor* the Command Line Tools. However, it's possible to install Xcode and *not* install t... | the_stack_v2_python_sparse | src/briefcase/integrations/xcode.py | beeware/briefcase | train | 1,609 | |
0662290904cbf50451453e731a0de65b07df7532 | [
"WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located((By.ID, 'username')))\nself.date_driven('../page/data.yml', 'by2', 'value2', 'action2', name)\nself.date_driven('../page/data.yml', 'by3', 'value3', 'action3', account)\nself.date_driven('../page/data.yml', 'by4', 'value4', 'action4', phone_numbe... | <|body_start_0|>
WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located((By.ID, 'username')))
self.date_driven('../page/data.yml', 'by2', 'value2', 'action2', name)
self.date_driven('../page/data.yml', 'by3', 'value3', 'action3', account)
self.date_driven('../page/data.yml'... | Memberinfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Memberinfo:
def member_info(self, name, account, phone_number):
"""被添加成员的信息填写 加入一个显示等待,然分别输入成员的name,account,phone_number,并点击保存 :param name: :param account: :param phone_number: :return:"""
<|body_0|>
def get_member_info(self):
"""成员信息一共有两页 被添加保存的成员的查询 首先查看是否在第一页,不在第一... | stack_v2_sparse_classes_75kplus_train_065395 | 2,157 | no_license | [
{
"docstring": "被添加成员的信息填写 加入一个显示等待,然分别输入成员的name,account,phone_number,并点击保存 :param name: :param account: :param phone_number: :return:",
"name": "member_info",
"signature": "def member_info(self, name, account, phone_number)"
},
{
"docstring": "成员信息一共有两页 被添加保存的成员的查询 首先查看是否在第一页,不在第一页则点击下一页在进行查找 :... | 2 | null | Implement the Python class `Memberinfo` described below.
Class description:
Implement the Memberinfo class.
Method signatures and docstrings:
- def member_info(self, name, account, phone_number): 被添加成员的信息填写 加入一个显示等待,然分别输入成员的name,account,phone_number,并点击保存 :param name: :param account: :param phone_number: :return:
- d... | Implement the Python class `Memberinfo` described below.
Class description:
Implement the Memberinfo class.
Method signatures and docstrings:
- def member_info(self, name, account, phone_number): 被添加成员的信息填写 加入一个显示等待,然分别输入成员的name,account,phone_number,并点击保存 :param name: :param account: :param phone_number: :return:
- d... | 6276e43ef1937c23e310b58058ee737addf2ede5 | <|skeleton|>
class Memberinfo:
def member_info(self, name, account, phone_number):
"""被添加成员的信息填写 加入一个显示等待,然分别输入成员的name,account,phone_number,并点击保存 :param name: :param account: :param phone_number: :return:"""
<|body_0|>
def get_member_info(self):
"""成员信息一共有两页 被添加保存的成员的查询 首先查看是否在第一页,不在第一... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Memberinfo:
def member_info(self, name, account, phone_number):
"""被添加成员的信息填写 加入一个显示等待,然分别输入成员的name,account,phone_number,并点击保存 :param name: :param account: :param phone_number: :return:"""
WebDriverWait(self.driver, 5).until(EC.visibility_of_element_located((By.ID, 'username')))
self.d... | the_stack_v2_python_sparse | web_po_homework/page/member_info.py | Guoxiang1992/Code | train | 0 | |
0d3f1485d18201e8d36eaf8ffab5a8bfe1fe9050 | [
"if synch:\n super(PartyProtocolHandlerRabbitMQ, self).__init__(fl_model, connection, data_handler, local_training_handler, hyperparams, agg_info, synch, is_private, **kwargs)\nelse:\n raise Exception('RabbitMQ connection currently only supports synchronous mode')",
"try:\n response_msg = ResponseMessage... | <|body_start_0|>
if synch:
super(PartyProtocolHandlerRabbitMQ, self).__init__(fl_model, connection, data_handler, local_training_handler, hyperparams, agg_info, synch, is_private, **kwargs)
else:
raise Exception('RabbitMQ connection currently only supports synchronous mode')
<|en... | Extended class for PartyProtocolHandler for using with RabbitMQ connection | PartyProtocolHandlerRabbitMQ | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartyProtocolHandlerRabbitMQ:
"""Extended class for PartyProtocolHandler for using with RabbitMQ connection"""
def __init__(self, fl_model, connection, data_handler, local_training_handler, hyperparams=None, agg_info=None, synch=True, is_private=True, **kwargs):
"""Initiate PartyProt... | stack_v2_sparse_classes_75kplus_train_065396 | 14,141 | permissive | [
{
"docstring": "Initiate PartyProtocolHandlerRabbitMQ with provided fl_model, connection and data_handler and hyperparams :param fl_model: model to be trained :type fl_model: `model.FLModel` :param connection: connection that will be used to send messages :type connection: `Connection` :param data_handler: data... | 2 | null | Implement the Python class `PartyProtocolHandlerRabbitMQ` described below.
Class description:
Extended class for PartyProtocolHandler for using with RabbitMQ connection
Method signatures and docstrings:
- def __init__(self, fl_model, connection, data_handler, local_training_handler, hyperparams=None, agg_info=None, s... | Implement the Python class `PartyProtocolHandlerRabbitMQ` described below.
Class description:
Extended class for PartyProtocolHandler for using with RabbitMQ connection
Method signatures and docstrings:
- def __init__(self, fl_model, connection, data_handler, local_training_handler, hyperparams=None, agg_info=None, s... | 64ffa2ee2e906b1bd6b3dd6aabcf6fc3de862608 | <|skeleton|>
class PartyProtocolHandlerRabbitMQ:
"""Extended class for PartyProtocolHandler for using with RabbitMQ connection"""
def __init__(self, fl_model, connection, data_handler, local_training_handler, hyperparams=None, agg_info=None, synch=True, is_private=True, **kwargs):
"""Initiate PartyProt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PartyProtocolHandlerRabbitMQ:
"""Extended class for PartyProtocolHandler for using with RabbitMQ connection"""
def __init__(self, fl_model, connection, data_handler, local_training_handler, hyperparams=None, agg_info=None, synch=True, is_private=True, **kwargs):
"""Initiate PartyProtocolHandlerRa... | the_stack_v2_python_sparse | debugging-constructs/ibmfl/party/party_protocol_handler.py | SEED-VT/FedDebug | train | 8 |
c72bc7da77279c44bbce212bca987b6e57de76dc | [
"flags.GetRepoArg().AddToParser(parser)\nbase.ASYNC_FLAG.AddToParser(parser)\nparser.add_argument('--source', metavar='SOURCE', required=True, help=' The path of a package to upload.')",
"client = apis.GetClientInstance('artifactregistry', self.api_version)\nmessages = client.MESSAGES_MODULE\nclient.ad... | <|body_start_0|>
flags.GetRepoArg().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--source', metavar='SOURCE', required=True, help=' The path of a package to upload.')
<|end_body_0|>
<|body_start_1|>
client = apis.GetClientInstance('artifactregi... | Upload an RPM package to an artifact repository. | Upload | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Upload:
"""Upload an RPM package to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run package import command."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_065397 | 3,131 | permissive | [
{
"docstring": "Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Run package import command.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044567 | Implement the Python class `Upload` described below.
Class description:
Upload an RPM package to an artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run package import command. | Implement the Python class `Upload` described below.
Class description:
Upload an RPM package to an artifact repository.
Method signatures and docstrings:
- def Args(parser): Set up arguements for this command. Args: parser: An argparse.ArgumentPaser.
- def Run(self, args): Run package import command.
<|skeleton|>
c... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Upload:
"""Upload an RPM package to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
<|body_0|>
def Run(self, args):
"""Run package import command."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Upload:
"""Upload an RPM package to an artifact repository."""
def Args(parser):
"""Set up arguements for this command. Args: parser: An argparse.ArgumentPaser."""
flags.GetRepoArg().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument('--source', me... | the_stack_v2_python_sparse | lib/surface/artifacts/yum/upload.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
cd0bf1c726cb48b9a5f180f46a4b19ffdecd52bc | [
"super(MultiHeadAttention, self).__init__()\nself.dm = dm\nself.h = h\nself.depth = dm // h\nself.Wq = tf.keras.layers.Dense(dm)\nself.Wk = tf.keras.layers.Dense(dm)\nself.Wv = tf.keras.layers.Dense(dm)\nself.linear = tf.keras.layers.Dense(dm)",
"batch_size = tf.shape(Q)[0]\nq = self.Wq(Q)\nk = self.Wk(K)\nv = se... | <|body_start_0|>
super(MultiHeadAttention, self).__init__()
self.dm = dm
self.h = h
self.depth = dm // h
self.Wq = tf.keras.layers.Dense(dm)
self.Wk = tf.keras.layers.Dense(dm)
self.Wv = tf.keras.layers.Dense(dm)
self.linear = tf.keras.layers.Dense(dm)
<|e... | Perform multi head attention | MultiHeadAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Perform multi head attention"""
def __init__(self, dm, h):
"""initialization"""
<|body_0|>
def call(self, Q, K, V, mask):
"""call function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(MultiHeadAttention, self).__i... | stack_v2_sparse_classes_75kplus_train_065398 | 1,358 | no_license | [
{
"docstring": "initialization",
"name": "__init__",
"signature": "def __init__(self, dm, h)"
},
{
"docstring": "call function",
"name": "call",
"signature": "def call(self, Q, K, V, mask)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037176 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Perform multi head attention
Method signatures and docstrings:
- def __init__(self, dm, h): initialization
- def call(self, Q, K, V, mask): call function | Implement the Python class `MultiHeadAttention` described below.
Class description:
Perform multi head attention
Method signatures and docstrings:
- def __init__(self, dm, h): initialization
- def call(self, Q, K, V, mask): call function
<|skeleton|>
class MultiHeadAttention:
"""Perform multi head attention"""
... | 16dc37d1c6dc00a271053b60724c51763914029a | <|skeleton|>
class MultiHeadAttention:
"""Perform multi head attention"""
def __init__(self, dm, h):
"""initialization"""
<|body_0|>
def call(self, Q, K, V, mask):
"""call function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiHeadAttention:
"""Perform multi head attention"""
def __init__(self, dm, h):
"""initialization"""
super(MultiHeadAttention, self).__init__()
self.dm = dm
self.h = h
self.depth = dm // h
self.Wq = tf.keras.layers.Dense(dm)
self.Wk = tf.keras.lay... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/6-multihead_attention.py | jaycer95/holbertonschool-machine_learning | train | 0 |
0a233a99e8228497b896dcee74d297ecb106bcb7 | [
"with file(path, 'r') as stream:\n notaries = self.parse_stream(stream)\nreturn notaries",
"notaries = Notaries()\nwhile True:\n notary = self._parse_notary(stream)\n if notary is None:\n break\n else:\n notaries.append(notary)\nreturn notaries",
"hostname, port, public_key = (None, No... | <|body_start_0|>
with file(path, 'r') as stream:
notaries = self.parse_stream(stream)
return notaries
<|end_body_0|>
<|body_start_1|>
notaries = Notaries()
while True:
notary = self._parse_notary(stream)
if notary is None:
break
... | Parse serialized Notaries and return a Notaries instance | NotaryParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotaryParser:
"""Parse serialized Notaries and return a Notaries instance"""
def parse_file(self, path):
"""Return Notaries described in file. See parse_stream() for expected format"""
<|body_0|>
def parse_stream(self, stream):
"""Return Notaries described in str... | stack_v2_sparse_classes_75kplus_train_065399 | 3,198 | no_license | [
{
"docstring": "Return Notaries described in file. See parse_stream() for expected format",
"name": "parse_file",
"signature": "def parse_file(self, path)"
},
{
"docstring": "Return Notaries described in stream. Expected format for each Notary is: # Lines starting with '#' are comments and ignor... | 4 | stack_v2_sparse_classes_30k_train_001139 | Implement the Python class `NotaryParser` described below.
Class description:
Parse serialized Notaries and return a Notaries instance
Method signatures and docstrings:
- def parse_file(self, path): Return Notaries described in file. See parse_stream() for expected format
- def parse_stream(self, stream): Return Nota... | Implement the Python class `NotaryParser` described below.
Class description:
Parse serialized Notaries and return a Notaries instance
Method signatures and docstrings:
- def parse_file(self, path): Return Notaries described in file. See parse_stream() for expected format
- def parse_stream(self, stream): Return Nota... | 92883090bb3e9f8ccdf3e4a39dce47ba3697ed63 | <|skeleton|>
class NotaryParser:
"""Parse serialized Notaries and return a Notaries instance"""
def parse_file(self, path):
"""Return Notaries described in file. See parse_stream() for expected format"""
<|body_0|>
def parse_stream(self, stream):
"""Return Notaries described in str... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NotaryParser:
"""Parse serialized Notaries and return a Notaries instance"""
def parse_file(self, path):
"""Return Notaries described in file. See parse_stream() for expected format"""
with file(path, 'r') as stream:
notaries = self.parse_stream(stream)
return notaries... | the_stack_v2_python_sparse | Perspectives/NotaryParser.py | von/pyPerspectives | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.